b150中等
107 臺中區資訊學科能力競賽(2018)|關鍵字搜尋模擬
對每個文件關鍵字,分別計算它與各查詢字串的最長共同連續子字串長度。二維DP只有字元相同時由左上加1,不同時歸零。
解題思路
對每個文件關鍵字,分別計算它與各查詢字串的最長共同連續子字串長度。二維DP只有字元相同時由左上加1,不同時歸零。
以共同長度除以查詢長度,取各查詢的最大比值作此關鍵字得分,再加總文件所有關鍵字得分。
使用精確有理數,最後才四捨五入為百分位整數;按此整數遞減、文件編號遞增排序,零分文件排除。
時間 O(Σ文件詞w Σ查詢q |w||q|);滾動DP空間 O(max查詢長度),另存查詢、輸出與有理數。
Step-by-step animation
教學小例:最長共同連續子字串與精確總分
步驟 1 / 3
查詢AA與B,文件詞A、B
詞A得max(1/2,0)=1/2
詞A得max(1/2,0)=1/2
- 步驟
- 1
#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
cpp_int gcdBig(cpp_int a, cpp_int b) {
if (a < 0)
a = -a;
if (b < 0)
b = -b;
while (b != 0) {
cpp_int r = a % b;
a = b;
b = r;
}
return a;
}
struct Rat {
cpp_int p, q;
Rat(cpp_int a = 0, cpp_int b = 1) : p(a), q(b) {
if (q < 0)
p = -p, q = -q;
cpp_int g = gcdBig(p, q);
p /= g;
q /= g;
}
};
Rat operator+(Rat a, Rat b) {
return Rat(a.p * b.q + b.p * a.q, a.q * b.q);
}
Rat operator-(Rat a, Rat b) {
return Rat(a.p * b.q - b.p * a.q, a.q * b.q);
}
Rat operator*(Rat a, Rat b) {
return Rat(a.p * b.p, a.q * b.q);
}
Rat operator/(Rat a, Rat b) {
return Rat(a.p * b.q, a.q * b.p);
}
int common(string a, string b) {
vector<int> d(b.size() + 1);
int ans = 0;
for (char x : a) {
for (int j = b.size(); j >= 1; j--) {
d[j] = x == b[j - 1] ? d[j - 1] + 1 : 0;
ans = max(ans, d[j]);
}
}
return ans;
}
int main() {
string line, w;
getline(cin, line);
stringstream ss(line);
vector<string> qs;
while (ss >> w)
qs.push_back(w);
int n;
cin >> n;
getline(cin, line);
vector<pair<cpp_int, cpp_int>> out;
while (n--) {
getline(cin, line);
stringstream st(line);
cpp_int id;
st >> id;
Rat score;
while (st >> w) {
Rat best;
for (auto q : qs) {
Rat v(common(w, q), q.size());
if (v.p * best.q > best.p * v.q)
best = v;
}
score = score + best;
}
cpp_int cents = (200 * score.p + score.q) / (2 * score.q);
if (cents > 0)
out.push_back({-cents, id});
}
sort(out.begin(), out.end());
if (out.empty())
cout << "FALSE";
else
for (int i = 0; i < (int)out.size(); i++) {
if (i)
cout << ' ';
cout << out[i].second;
}
cout << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。