POJ 1386 Play on Words

来源:互联网 发布:ummy破解版for mac 编辑:程序博客网 时间:2024/06/16 14:05

Description
Some of the secret doors contain a very interesting word puzzle. The team of archaeologists has to solve it to open that doors. Because there is no other way to open the doors, the puzzle is very important for us.
There is a large number of magnetic plates on every door. Every plate has one word written on it. The plates must be arranged into a sequence in such a way that every word begins with the same letter as the previous word ends. For example, the word “acm” can be followed by the word “motorola”. Your task is to write a computer program that will read the list of words and determine whether it is possible to arrange all of the plates in a sequence (according to the given rule) and consequently to open the door.


【题目分析】
就是利用欧拉路的判定,就是检测一下出度和入度,然后需要注意的是要判连通。


【代码】

#include <cstdio>#include <cstring>#include <cmath>#include <queue>#include <algorithm>using namespace std;char s[1000001];int chu[101],ru[101];int map[101][101];int vis[101];int main(){    int T,n;    scanf("%d",&T);    while (T--)    {          memset(map,0,sizeof 0);memset(vis,0,sizeof vis);          memset(chu,0,sizeof chu);memset(ru,0,sizeof ru);          scanf("%d",&n);int flag1=0,flag2=0,can=0;          for (int i=1;i<=n;++i)          {              scanf("%s",s);              int l=strlen(s)-1;               chu[s[0]-'a']++;              ru[s[l]-'a']++;              map[s[l]-'a'][s[0]-'a']=1;map[s[0]-'a'][s[l]-'a']=1;          }          int cnt=0;          for (int i=0;i<26;++i)              if ((ru[i]!=0||chu[i]!=0)&&!vis[i])              {                  cnt++;                  queue<int>q;                  q.push(i);                  vis[i]=1;                  while (!q.empty())                  {                        int x=q.front();q.pop();                        for (int j=0;j<26;++j)                            if (map[x][j]&&!vis[j]) vis[j]=1,q.push(j);                  }              }          if (cnt>=2) {printf("The door cannot be opened.\n"); continue;}          for (int i=0;i<26;++i)          {              if (ru[i]-chu[i]==1) flag1++;              if (ru[i]-chu[i]==-1) flag2++;              if (abs(ru[i]-chu[i])>=2) can=1;          }          if ((flag1==1&&flag2==1)||(flag1==0&&flag2==0)||cnt<2||can==1) printf("Ordering is possible.\n");          else printf("The door cannot be opened.\n");    }}
0 0