有向圖尤拉通路1.1
阿新 • • 發佈:2018-11-07
給定單詞,看是否存在尤拉通路
http://poj.org/problem?id=1386
#include<cstdio> #include<cstring> using namespace std; const int maxn=26+5; int fa[maxn]; int in[maxn],out[maxn]; int m;//單詞數 int findset(int u) { if(fa[u]==-1) return u; return fa[u]=findset(fa[u]); } int main() { int T; scanf("%d",&T); while(T--) { memset(in,0,sizeof(in)); memset(out,0,sizeof(out)); memset(fa,-1,sizeof(fa)); scanf("%d",&m); for(int i=0;i<m;i++) { char str[1200]; scanf("%s",str); int len=strlen(str); int u=str[0]-'a', v=str[len-1]-'a'; in[u]++; out[v]++; u=findset(u), v=findset(v); if(u!=v) fa[u]=v; } int cnt=0; for(int i=0;i<26;i++) if( (in[i]||out[i]) && findset(i)==i ) cnt++; if(cnt>1) { printf("The door cannot be opened.\n"); continue; } int c1=0, c2=0, c3=0;//分別表示入度!=出度時的三種情況 for(int i=0;i<26;i++) { if(in[i]==out[i]) continue; else if(in[i]-out[i]==1) c1++; else if(out[i]-in[i]==1) c2++; else c3++; } if( ( (c1==c2&&c1==1)||(c1==c2&&c1==0) )&&c3==0 ) printf("Ordering is possible.\n"); else printf("The door cannot be opened.\n"); } return 0; }