PAT 基於詞頻的檔案相似度 (set) -- 解題報告
阿新 • • 發佈:2019-02-17
解題思路
每個檔案內的單詞存放到單獨的一個 set 中。詢問時直接遍歷其中一個 set(必須是 size 較小的那個,否則會超時在最後一個測試點),用 count() 查詢另一個 set 中存不存在這個單詞即可。做法類似 PAT 上另一道題目「集合相似度」(連示例輸出都幾乎是一樣的)。
參考程式碼
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
#include <string>
using namespace std;
int main(int argc, char const *argv[]) {
int n, m, a, b;
char s[2000], tmp[2000];
set<string> st[101];
scanf("%d%*c", &n);
for(int i=1; i<=n; ++i) {
while(gets(s)) {
if(!strcmp(s, "#")) break;
int last = 0;
for(int j=0; s[j]; ++j) {
if (s[j]>='A' && s[j]<='Z') s[j] += 32;
// 分割單詞,符合要求的存進 set
if(s[j]<'a' || s[j]>'z') {
s[j] = 0;
strcpy(tmp, s+last);
last = j+1;
tmp[10] = 0;
if(strlen(tmp) >= 3 ) st[i].insert(tmp);
}
}
strcpy(tmp, s+last);
tmp[10] = 0;
if(strlen(tmp) >= 3) st[i].insert(tmp);
}
}
scanf("%d", &m);
while(m--) {
scanf("%d %d", &a, &b);
int cnt = 0;
set<string>::iterator it;
// !important: 遍歷 size 較小的 set
if(st[a].size() > st[b].size()) swap(a, b);
for(it=st[a].begin(); it!=st[a].end(); ++it) {
if(st[b].count(*it)) cnt++;
}
printf("%.1f%%\n", 100.0*cnt/(st[a].size()+st[b].size()-cnt));
}
return 0;
}