P1032 字串变换 - BFS & STL

传送

思路:

STL大法好(然而不能过度依赖STL)。。此题可通过对A串每一位字符,枚举所有变换方案,最终得到答案。然而这样的复杂度是520 ,显然不能接受。

我们可通过multimap存储变换方案,通过find函数寻找当前字串在A串中的位置,通过replace函数进行字串变换,通过map进行字符串判重,然后就可以过了。

AC Code:

#include<cstdio>
#include<algorithm>
#include<map>
#include<queue>
#include<string>
#include<iostream>
#define mp(A,B) make_pair((A),(B))
using namespace std;
multimap<string,string>ch;
map<string,int>vis;
queue<string>q;
int main()
{
    string A,B;
    cin>>A>>B;
    string u,v;
    while(cin>>u>>v)
    {
        ch.insert(mp(u,v));
        //向multimap中插入变换规则 
    }
    vis.insert(mp(A,0));
    //起始串也要判重,i=vis.second代表当前变换次数为i 
    q.push(A);
    while(q.size())
    {
        string now=q.front();q.pop();
        int dep=vis[now];
        if(dep>10)
        //若变换次数超过10还没有达到目标串 就NO ANSWER 
        {
            printf("NO ANSWER!");return 0;
        }
        if(now==B)
        //如果达到了目标串 就输出变换次数 
        {
            printf("%d",dep);return 0;    
        } 
        for(auto i:ch)
        /*auto i:ch 
        auto 是c++ 11 中的特性!!! 所以本机如果不是c++ 11的话会无法编译!!! 
        auto相当于一个自动变量 它会自动判断当前变量的类型
        如现在 auto相当于一个multimap的迭代器
        */ 
        {
            string tmp=now;
            int pos;
            while((pos=tmp.find(i.first,pos))!=string::npos)
            //表示find函数从位置pos起始找到了字串i.first 
            {
                now.replace(pos,i.first.size(),i.second);
                //表示将字符串now中 从pos位置开始到结束总长为i.first的长度的字串 变换为i.second 
                if(!vis.count(now))
                //若不重复 
                {
                    vis[now]=dep+1;
                    q.push(now);
                }
                now=tmp;
                pos++;
            }
        }
    }
    printf("NO ANSWER!");
    //变换次数不超过10次 但还是无法达到目标串 
    return 0;
}

 

posted @ 2018-04-10 23:12  dprswdr  阅读(159)  评论(0)    收藏  举报