题解
[NOIP 2002 提高组] 字串变换(疑似错题)
1 条题解
-
0
1. 解题思路
从初始串按正向规则搜索5层,从目标串按反向规则搜索5层,枚举两侧公共字符串的距离和,取不超过10的最小值。
2. 坑点和注意事项
至多6条规则,输入字符串≤20。必须枚举每个匹配位置且允许重叠位置;中间字符串不能无依据截断。题面声明不保证可靠多项式全规模算法,实际状态数可能爆炸,评级待评估。
3. 复杂度
- 时间复杂度:O(S×R×L²),S为两侧生成状态总数。
- 空间复杂度:O(SL)。
/* 思路:从初始串按正向规则搜索5层,从目标串按反向规则搜索5层,枚举两侧公共字符串的距离和,取不超过10的最小值。 关键规则与坑点:至多6条规则,输入字符串≤20。必须枚举每个匹配位置且允许重叠位置;中间字符串不能无依据截断。题面声明不保证可靠多项式全规模算法,实际状态数可能爆炸,评级待评估。 时间复杂度:O(S×R×L²),S为两侧生成状态总数。空间复杂度:O(SL)。 */ #include <bits/stdc++.h> using namespace std; string a[6], b[6]; int n; unordered_map<string, int> build(string start, bool rev) { unordered_map<string, int> d; queue<string> q; d[start] = 0; q.push(start); while (!q.empty()) { string s = q.front(); q.pop(); if (d[s] == 5) continue; for (int i = 0; i < n; i++) { string from = rev ? b[i] : a[i], to = rev ? a[i] : b[i]; for (size_t p = s.find(from); p != string::npos; p = s.find(from, p + 1)) { string t = s.substr(0, p) + to + s.substr(p + from.size()); if (!d.count(t)) { d[t] = d[s] + 1; q.push(t); } } } } return d; } int main() { string s, t; cin >> s >> t; while (n < 6 && cin >> a[n] >> b[n]) n++; unordered_map<string, int> f = build(s, false), g = build(t, true); int ans = 11; for (unordered_map<string, int>::iterator it = f.begin(); it != f.end(); ++it) if (g.count(it->first)) ans = min(ans, it->second + g[it->first]); if (ans <= 10) cout << ans << endl; else cout << "NO ANSWER!" << endl; }
- 1