OpenJudge noi 8468单词序列

来源:互联网 发布:mysql 合计行 编辑:程序博客网 时间:2024/05/23 20:00

Description
给出两个单词(开始单词和结束单词)以及一个词典。找出从开始单词转换到结束单词,所需要的最短转换序列。转换的规则如下:

1、每次只能改变一个字母

2、转换过程中出现的单词(除开始单词和结束单词)必须存在于词典中

例如:

开始单词为:hit

结束单词为:cog

词典为:[hot,dot,dog,lot,log,mot]

那么一种可能的最短变换是: hit -> hot -> dot -> dog -> cog,

所以返回的结果是序列的长度5;

注意:

1、如果不能找到这种变换,则输出0;

2、词典中所有单词长度一样;

3、所有的单词都由小写字母构成;

4、开始单词和结束单词可以不在词典中。

Input
共两行,第一行为开始单词和结束单词(两个单词不同),以空格分开。第二行为若干的单词(各不相同),以空格分隔开来,表示词典。单词长度不超过5,单词个数不超过30。
Output
输出转化序列的长度。
Sample Input
hit cog
hot dot dog lot log
Sample Output
5

bfs:
开一个结构体,记录每个单词,单词是否被访问过,和访问到当前单词的步数。把搜索的起点初始化为第一个单词,终点为要得到的单词。搜过的点,vis=1,之后不再搜索。在搜索过程中,我们每次寻找与当前单词只有一个字母不同的单词,然后将这个新的单词扔入队列,直到搜到目标单词。如果搜不到,就输出0.

代码如下:

#include<iostream>#include<cstdio>#include<cstdlib>#include<cstring>#include<queue>using namespace std;const int maxn=35;struct dqs{    string word;    int step;    bool vis;}hh[maxn];queue<dqs>q;string d=hh[0].word;int k=0,len;void bfs(){    dqs begin;    begin.word=hh[0].word;//  cout<<begin.word<<endl;    begin.step=1;    begin.vis=1;    q.push(begin);    while(!q.empty())    {        dqs head=q.front();        q.pop();        for(int i=1;i<=k;i++)        {            int t=0;            for(int j=0;j<len;j++)            {                if(head.word[j]!=hh[i].word[j])                t++;            }            if(t==1&&hh[i].vis==0&&i!=k)            {                hh[i].step=head.step+1;                hh[i].vis=1;                q.push(hh[i]);            }            if(t==1&&hh[i].vis==0&&i==k)            {                printf("%d\n",head.step+1);                return;            }        }                           }    printf("0\n");    return;}int main(){    string a,b,c;    cin>>a>>b;    len=a.length();    while(cin>>c)    {        hh[++k].word=c;         }    hh[0].word=a;    hh[++k].word=b;    bfs();    return 0;}
2 0
原创粉丝点击