P1032 [NOIP 2002 提高组] 字串变换
题目背景
本题不保证存在靠谱的多项式复杂度的做法。测试数据非常的水,各种做法都可以通过,不代表算法正确。因此本题题目和数据仅供参考。
本题为搜索题,本题不接受 hack 数据。关于此类题目的详细内容
题目描述
已知有两个字串 A,B 及一组字串变换的规则(至多 6 个规则),形如:
- A1→B1。
- A2→B2。
规则的含义为:在 A 中的子串 A1 可以变换为 B1,A2 可以变换为 B2⋯。
例如:A=abcd,B=xyz,
变换规则为:
- abc→xu,ud→y,y→yz。
则此时,A 可以经过一系列的变换变为 B,其变换的过程为:
- abcd→xud→xy→xyz。
共进行了 3 次变换,使得 A 变换为 B。
输入格式
第一行有两个字符串 A,B。
接下来若干行,每行有两个字符串 Ai,Bi,表示一条变换规则。
输出格式
若在 10 步(包含 10 步)以内能将 A 变换为 B,则输出最少的变换步数;否则输出 NO ANSWER!
。
输入输出样例
输入 #1复制
abcd xyz abc xu ud y y yz
输出 #1复制
3
#include<bits/stdc++.h> using namespace std;const int N = 20;int n = 1; struct node {string x;int y; }; map<string,bool> vis; //标记数组string a[N],b[N],s,t;void bfs() {queue<node> q;q.push({s,0});while(!q.empty()) {node tt = q.front();q.pop();if(vis[tt.x]) continue;//这个字符串已经被变过了 防止后续重新变化vis[tt.x] = true;if(tt.x == t) {cout<<tt.y<<endl;return;}if(tt.y > 10) {cout<<"NO ANSWER!"<<endl;return;}for(int i = 1; i <= n; i++) { //遍历数组afor(int j = 0; j < tt.x.size(); j++) {string str = tt.x.substr(j,a[i].size());//遍历当前字符串的长度 找到子串a[i]if(str == a[i]) { // 如果字串和变换的串相同 就可以做变换操作string next = tt.x;//首先记录当前的字符串 next.replace(j,a[i].size(),b[i]);//然后将找到位置替换成b这个串q.push({next,tt.y+1});}}}}cout<<"NO ANSWER!"<<endl; } int main() {cin >> s >> t;while(cin >> a[n] >> b[n]) n++;n--;bfs();return 0; }