解題思路
把兩篇文章轉小寫,取英數單字,分別紀錄每字頻率與第一次出現順序。將兩篇頻率合併成總頻率。
由總頻率高到低逐層挑字。同一層把A、B各自首次順序的字排成兩列,從A開始輪流挑尚未選過的字;某列已無未選字就跳過它。達到N個立即停止,字不足的其餘維度為0。
用挑出的相同字作兩篇向量座標,算dot/√(normA²·normB²)。若其中一篇向量為零,本練習依參考判定輸出0.00;其他時候只在最後保留兩位小數。
W為總詞數、V為相異字數、F為不同總頻率層數。C++ map實作O(W log(V+1)+V log V)時間;Python每頻率層重掃字序,O(W+V log V+VF)時間。O(W+V)主要空間,另加輸入文章字元長度。
Step-by-step animation
示例:A:red red blue,B:red blue blue,取2字。
步驟 1 / 3
示例兩篇
A:red red blue,B:red blue blue,取2字。
A:red2 blue1
B:red1 blue2
- 總頻率
- red3,blue3
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin >> N;
string rest((istreambuf_iterator<char>(cin)), {});
size_t cut = rest.find('*');
string raw[2] = {rest.substr(0, cut), rest.substr(cut + 1)};
raw[1] = raw[1].substr(0, raw[1].find('*'));
map<string, int> cnt[2], total;
vector<string> order[2];
for (int k = 0; k < 2; k++) {
for (char &c : raw[k])
if (isalnum((unsigned char)c))
c = tolower((unsigned char)c);
else
c = ' ';
istringstream in(raw[k]);
string w;
while (in >> w) {
if (!cnt[k].count(w))
order[k].push_back(w);
cnt[k][w]++;
total[w]++;
}
}
map<int, vector<string>, greater<int>> groups[2];
for (int k = 0; k < 2; k++)
for (string w : order[k])
groups[k][total[w]].push_back(w);
set<int, greater<int>> freq;
for (auto [w, f] : total)
freq.insert(f);
set<string> chosen;
vector<string> axes;
for (int f : freq) {
auto &a = groups[0][f], &b = groups[1][f];
size_t pos[2] = {};
int turn = 0;
while (pos[0] < a.size() || pos[1] < b.size()) {
auto &v = turn ? b : a;
while (pos[turn] < v.size() && chosen.count(v[pos[turn]]))
pos[turn]++;
if (pos[turn] < v.size()) {
string w = v[pos[turn]++];
chosen.insert(w);
axes.push_back(w);
if ((int)axes.size() == N)
break;
}
turn ^= 1;
}
if ((int)axes.size() == N)
break;
}
long double dot = 0, A = 0, B = 0;
for (string w : axes) {
long double a = cnt[0][w], b = cnt[1][w];
dot += a * b;
A += a * a;
B += b * b;
}
cout << fixed << setprecision(2) << (A && B ? dot / sqrtl(A * B) : 0) << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。