POJ 1386 Play on Words G++ 有向图的欧拉路判定 背

本文介绍了一种使用并查集判断连通性的方法,并通过对比出入度来判定有向图中是否存在欧拉路径。该算法适用于竞赛编程及图论问题解决。

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

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string> 
using namespace std;
//英语       看博友分析      抄博友程序        无向图欧拉路判定与有向图欧拉路判定不同       有向图的欧拉路判定     背 
//抄博友分析        用并查集判断连通,然后判断欧拉路径存在。
int out[30];
int in[30];
int fa[30];
int find(int x)
{
	if(fa[x]==-1)
	{
		return x;
	}else
	{
		return fa[x]=find(fa[x]);
	}
}
int main()
{
	int T;
	//cin>>T;
	scanf("%d",&T);
	while(T--)
	{
		int n;
		//cin>>n;
		scanf("%d",&n);
		memset(fa,-1,sizeof(fa));
		memset(out,0,sizeof(out));
		memset(in,0,sizeof(in));
		int s=-1;
		for(int i=0;i<n;i++)
		{
			//string a;
			char a[1008];
			scanf("%s",a);
			//cin>>a;
			int x=a[0]-'a';
			int y=a[strlen(a)-1]-'a';
			out[x]++;
			in[y]++;
			if(find(x)!=find(y))
			{
				fa[find(x)]=find(y);
			}
			if(s==-1)
			{
				s=x;
			}
		}
		int cnt1=0,cnt2=0;
		int flag=true;//抄博友程序
		for(int i=0;i<26;i++)
		{
			if(out[i]-in[i]==1)
			{
				cnt1++;
			}else if(in[i]-out[i]==1)
			{
				cnt2++;
			}else if(in[i]!=out[i])
			{
				flag=false;
			}
			if(out[i]||in[i])
			{
				if(find(i)!=find(s))//连通 
				{
					flag=false;
				}
			}
		}
		if(!((cnt1==1 && cnt2==1)||(cnt1==0 && cnt2==0)))
		{
			flag=false;	
		} 
		if(flag)
		{
			cout<<"Ordering is possible."<<endl;
		}else
		{
			cout<<"The door cannot be opened."<<endl;
		} 
	} 
	return 0;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值