欧拉路与欧拉回路的判断 poj 1386

来源:互联网 发布:虚拟化桌面软件 编辑:程序博客网 时间:2024/06/05 04:08

点击打开链接


#include <iostream>#include <cstring>#include <string>#define N 100005#define M 26using namespace std;bool a[N];int t,n,in[N],out[N],f[N],r[N];void init(){for(int i=0 ; i<=M ; i++)f[i]=i,r[i]=0;}int find(int k){return f[k]=k!=f[k]?find(f[k]):f[k];}void union_set(int x , int y){int x1=find(x);int y1=find(y);if(x1!=y1){if(r[x1]<r[y1]) f[x1]=y1;else if(r[x1]>r[y1]) f[y1]=x1;else r[y1]++,f[x1]=y1;}}int main (){//freopen("1.txt","r",stdin);string sh;int i,j,k,s,e;for(cin>>t,k=0 ; k<t; k++){init();memset(a , 0 , sizeof(a));memset(in , 0 , sizeof(in));memset(out ,0 ,sizeof(out));for(cin>>n,i=0 ; i<n ; i++){cin>>sh;s=sh[0]-'a';e=sh[sh.size()-1]-'a';a[s]=1 , a[e]=1;in[e]++ , out[s]++;union_set(s,e);}//int nt=find(e),f=0;for(i=0 ; i<=M && f==0 ; i++ )if(a[i] && find(i)!=nt) f=1;int q,p;for(q=p=i=0 ; i<=M && f==0; i++){if(a[i]&&in[i]!=out[i]){if(in[i]-1==out[i]) q++;else if(in[i]==out[i]-1) p++;else break;}}if(i<=M) f=1;if(f!=1 &&((q+p)==0 || (p==1 && q==1)))cout<<"Ordering is possible."<<endl;else cout<<"The door cannot be opened."<<endl;}return 0;}

测试数据

/*

4
2
acm
ibm
3
acm
malform
mouse
2
ok
ok
3
mm
cc

*/

nynn  


此题说白了就是一入门级别的题,只要判断出图是否连通,然后再判断是否有欧拉路 或者 欧拉回路:

无向图: 欧拉路:经过所有的边,且只存在两个奇度顶点;

                 欧拉回路:经过所有的边并且是回路,全是偶度顶点。