POJ 1386 Play on Words

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值