UVA10129 - Play on Words

探讨如何通过排列单词形成序列,使得每个单词的首字母与前一个单词的尾字母相同,问题转化为判断有向图上是否存在欧拉回路。介绍了解决此问题的算法实现,包括节点的进出度检查和连通性验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值