UVA10129 - Play on Words

题目:

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.

题意:给你n个单词,是否可以将所有的单词排成一个序列,使每个单词第一个字母与上一个单词最后一个字母相同,输入中有重复的单词。

把每个单词当作一条边,字母看作点,题目变成判断有向图上是否存在一条欧拉回路。

有向图满足欧拉回路的条件是:除了起点和终点外, 其他点的“进出” 次数应该相等。 换句话说,除了起点和终点外, 其他点的度数应该是偶数。

对于有向图, 则必须其中一个点的出度恰好比入度大1, 另一个的入度比出度大。

欧拉的一些名词意思:1)欧拉路:通过图中所有边的简单路。2)欧拉回路:闭合的欧拉路。3)欧拉图:包含欧拉回路的图。

#include<bits/stdc++.h>
#define ll long long
#define INF 0x3f3f3f3f
#define maxn 110
#define qx std::ios::sync_with_stdio(false)
#define N 2100
using namespace std;
string s;
int vis[200],n,t,in[200],out[200],f[30];
int F(int x) {return f[x]==x? x:f[x]=F(f[x]);}
void Merge(int a,int b) {a=F(a);b=F(b);if(a!=b) f[a]=b;}
int main(){
    cin>>t;
    while(t--){
        memset(in,0,sizeof(in));
        memset(out,0,sizeof(out));
        memset(vis,0,sizeof(vis));
        for(int i=0;i<=26;i++) f[i]=i;
        cin>>n;
        for(int i=0;i<n;i++){
            cin>>s;
            int a=s[0]-'a',b=s[s.length()-1]-'a';
            out[a]++;in[b]++;
            vis[a]=1;vis[b]=1;
            Merge(a,b);
        }
        int cnt=0;
        for(int i=0;i<=26;i++)
            if(vis[i]&&F(i)==i) cnt++;//有几个连通块
        if(cnt>1){//多于一个则不能组成一条
            printf("The door cannot be opened.\n");
            continue;
        }
        cnt=0;
        int t1=-1,t2=-1;
        bool ok=true;
        for(int i=0;i<=26;i++)
            if(vis[i]&&in[i]!=out[i])//入度!=出度
                if(in[i]+1==out[i]&&t1==-1) t1=i;//入度比出度大一
                else if(in[i]==out[i]+1&&t2==-1) t2=i;//出度比入度大一
                else ok=false;
        printf("%s\n",ok ? "Ordering is possible.":"The door cannot be opened.");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Endeavor_G/article/details/84843673
今日推荐