解題思路
求插入空白後的最高速配指數。
把分數乘10,字母相同得10、不同−5、字母對空白−3,空白對空白可刪除而不影響分數。
dp[i][j]為前i與前j字母的最高分,最後一欄可字母對字母、第一字母對空白、空白對第二字母,取三者最大。
邊界是只有字母對空白,分數−3i或−3j。最佳整數分數v轉為百分比10v/len(第一字),最後精確取兩位並加%。
每組時間 O(L1L2),DP額外空間 O(L2)。Python一次split另保留全部單字,總空間為輸入字元數加 O(L2)。
Step-by-step animation
aaa與aaa完全相同的對齊示例
步驟 1 / 3
步驟 1
示例aaa對aaa,每個相同字母得10縮放分。
分數30
- 步驟
- 1
#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
using ll = long long;
#include <boost/rational.hpp>
using Q = boost::rational<cpp_int>;
Q rat(cpp_int a, cpp_int b) {
if (b < 0) {
a = -a;
b = -b;
}
return Q(a, b);
}
cpp_int abig(cpp_int a) {
return a < 0 ? -a : a;
}
cpp_int ten(int n) {
cpp_int a = 1;
while (n--)
a *= 10;
return a;
}
Q dec(string s) {
auto slash = s.find('/');
if (slash != string::npos)
return Q(cpp_int(s.substr(0, slash)), cpp_int(s.substr(slash + 1)));
bool neg = !s.empty() && s[0] == '-';
if (s[0] == '-' || s[0] == '+')
s.erase(s.begin());
auto p = s.find('.');
int k = p == string::npos ? 0 : s.size() - p - 1;
if (p != string::npos)
s.erase(p, 1);
size_t z = s.find_first_not_of('0');
cpp_int a = z == string::npos ? cpp_int(0) : cpp_int(s.substr(z));
return Q(neg ? -a : a, ten(k));
}
string fixedq(Q q, int digits) {
cpp_int a = q.numerator(), b = q.denominator(), scale = ten(digits);
bool neg = a < 0;
a = abig(a);
cpp_int k = (2 * a * scale + b) / (2 * b);
string s = k.convert_to<string>();
if (digits) {
if (s.size() <= digits)
s = string(digits + 1 - s.size(), '0') + s;
s.insert(s.size() - digits, ".");
}
return (neg && k != 0 ? "-" : "") + s;
}
string finiteq(Q q) {
cpp_int a = q.numerator(), b = q.denominator();
bool neg = a < 0;
a = abig(a);
cpp_int whole = a / b, r = a % b;
string s = whole.convert_to<string>();
if (r != 0) {
s += '.';
while (r != 0) {
r *= 10;
cpp_int z = r / b;
s += char('0' + z.convert_to<int>());
r %= b;
}
}
return (neg ? "-" : "") + s;
}
int main() {
string a, b;
while (cin >> a >> b) {
int n = a.size(), m = b.size();
vector<int> d(m + 1);
for (int j = 0; j <= m; j++)
d[j] = -3 * j;
for (int i = 1; i <= n; i++) {
vector<int> e(m + 1);
e[0] = -3 * i;
for (int j = 1; j <= m; j++)
e[j] = max({d[j - 1] + (a[i - 1] == b[j - 1] ? 10 : -5), d[j] - 3,
e[j - 1] - 3});
d.swap(e);
}
cout << fixedq(Q(10 * d[m], n), 2) << "%\n";
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。