字串变换

字串变换

来源:
2002年NOIP全国联赛提高组
算法使用:
BFS+STL字符串处理

题目描述:
已知有两个字串 A,B 及一组字串变换的规则(至多6个规则):
A1>B1
A2>B2
规则的含义为:在 A$中的子串 A1B1、A2B2 …。
例如:AabcdB=’xyz’   变换规则为:
‘abc’->‘xu’ ‘ud’->‘y’ ‘y’->‘yz’
则此时,AB,其变换的过程为: ‘abcd’->‘xud’->‘xy’->‘xyz’
共进行了三次变换,使得 AB
输入描述:
输入格式如下:
A B
A2 B2
……
所有字符串长度的上限为 20。
输出描述:
若在 10 步(包含 10步)以内能将 AB ,则输出最少的变换步数;否则输出”NO ANSWER!”
样例输入:
abcd xyz
abc xu
ud y
y yz
样例输出:
3

#include<iostream>
#include<string>
#include<queue>
#include<map>
using namespace std;
struct node
{
    string s;
    int step;
};
map<string,int> visit;
string sa,sb,s1[10001],s2[10001];
queue<node> que;
int n=1;
void init()
{
    cin>>sa>>sb;
    while(cin>>s1[n]>>s2[n]) n++;
    n--;
}
void bfs()
{   
    node e;
    e.step=0;
    e.s=sa;
    que.push(e);
    while(!que.empty())
    {
        node t=que.front();
        que.pop();
        if(t.s==sb&&t.step<11)
        {
            cout<<t.step;
            return;
        }
        if(visit[t.s]==0)
        {
            visit[t.s]=1;
            for(int i=1;i<=n;i++)
            {
                if(t.s.find(s1[i])>=0)
                {
                    for(int j=t.s.find(s1[i]);j>=0&&j<=t.s.size()-s2[i].size();j=t.s.find(s1[i],j+1))
                    {
                        node w=t;
                        w.step++;
                        w.s.replace(j,s1[i].size(),s2[i]);
                        que.push(w);
                    }
                }

            }
        }
    }
    cout<<"NO ANSWER!";
}
int main()
{
    init();
    bfs();
    return 0;
}
posted @ 2016-07-27 16:53  抽空的太阳  阅读(114)  评论(0编辑  收藏  举报