标签:
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 11312 | Accepted: 3862 |
Description
Input
Output
Sample Input
3 2 acm ibm 3 acm malform mouse 2 ok ok
Sample Output
The door cannot be opened. Ordering is possible. The door cannot be opened.
Source
#include<cstdio> #include<cstring> using namespace std; #define N 27 struct node{ int in,out; }degree[N]; int fa[N],rank[N],mem[N],vis[N],top,t,n; char str[1001]; int find(int x){ return fa[x]==x?x:fa[x]=find(fa[x]); } int main(){ scanf("%d",&t); while(t--){ for(int i=1;i<=26;i++){ fa[i]=i,rank[i]=0; } memset(degree,0,sizeof degree); memset(vis,0,sizeof vis); top=0; scanf("%d",&n); for(int i=1;i<=n;i++){ memset(str,0,sizeof str); scanf("%s",str); int a=str[0]-‘a‘+1,b=str[strlen(str)-1]-‘a‘+1; if(!vis[a]){ vis[a]=1; mem[++top]=a; } if(!vis[b]){ vis[b]=1; mem[++top]=b; } degree[a].out++;degree[b].in++; a=find(a);b=find(b); if(a!=b){ if(rank[a]<rank[b]) fa[a]=b; else{ fa[b]=a; if(rank[a]==rank[b]) rank[a]++; } } } int tmp=find(mem[1]),flag=0; for(int i=2;i<=top;i++){ if(find(mem[i])!=tmp){ flag=1;break; } } if(flag){ printf("The door cannot be opened.\n"); continue; } int sum=0,flag1=0,flag2=0,ok=1; for(int i=1;i<=top&&sum<=2&&ok;i++){ if(degree[mem[i]].in!=degree[mem[i]].out){ sum++; if(degree[mem[i]].in==degree[mem[i]].out+1) flag1++; else if(degree[mem[i]].in==degree[mem[i]].out-1) flag2++; else ok=0; } } if(ok){ if(flag1==1&&flag2==1 || flag1==0&&flag2==0) printf("Ordering is possible.\n"); else printf("The door cannot be opened.\n"); } else printf("The door cannot be opened.\n"); } return 0; }
标签:
原文地址:http://www.cnblogs.com/shenben/p/5564662.html