P3025 [USACO11OPEN] Forgotten Password S
比较显然的 DP 是很好思考的。
令 表示前 个字符的答案,转移时枚举 ,判断 是否是一个单词,如果是,用 转移。
然而我的实现并不太优美,复杂度甚至已经达到了 。不过其实是跑不满的。因为当 为空时,这个转移是不存在的。
这个复杂度其实并不很优,但是题目数据比较弱,所以就可以过了。不过优化也比较容易思考。发现单词长度不超过 ,所以第二层枚举 只需要 次,就可以达到正确的复杂度了。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <cassert>
using namespace std;
const int N = 1005;
string p[N], s;
string dp[N];
int n, m;
inline string check(string& g)
{
string res = "-1";
for (int i = 1; i <= m; i++)
{
if (p[i].size() != g.size()) continue;
bool f = 1;
for (int j = 0; j < g.size(); j++)
{
if (g[j] != '?' && p[i][j] != g[j])
{
f = 0;
break;
}
}
if (f)
{
if (res == "-1") res = p[i];
else res = min(res, p[i]);
}
}
return res;
}
auto main() -> int
{
ios::sync_with_stdio(0), cin.tie(nullptr), cout.tie(nullptr);
cin >> n >> m >> s;
for (int i = 1; i <= m; i++) cin >> p[i];
for (int i = 0; i < n; i++)
{
for (int j = i; j >= 0; j--)
{
if (j != 0 && dp[j - 1].empty()) continue;
string g = s.substr(j, i - j + 1);
string l = check(g);
if (l != "-1")
{
if (dp[i].empty()) dp[i] = (j == 0 ? "" : dp[j - 1]) + l;
else dp[i] = min(dp[i], (j == 0 ? "" : dp[j - 1]) + l);
}
}
}
cout << dp[n - 1] << "\n";
return 0;
}

浙公网安备 33010602011771号