标签:
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 11748 | Accepted: 4018 |
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.
【题意】这个就相当于成语接龙,需满足前一个单词的尾字母与后一个的首字母相同。然后就是问是否 存在欧拉通路。
【分析】用两个数组存每个字母的入度与出度,再用vis[]判断字母是否出现,然后并查集判断是否联通。
#include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> #include <algorithm> #include <climits> #include <cstring> #include <string> #include <set> #include <map> #include <queue> #include <stack> #include <vector> #include <list> #include<functional> #define mod 1000000007 #define inf 0x3f3f3f3f #define pi acos(-1.0) using namespace std; typedef long long ll; const int N=100005; const int M=150005; ll power(ll a,int b,ll c){ll ans=1;while(b){if(b%2==1){ans=(ans*a)%c;b--;}b/=2;a=a*a%c;}return ans;} char str[N]; int n,m; int vis[27],pre[27]; int out[27],in[27]; struct man { int u,v; }edg[N]; void init() { memset(vis,0,sizeof(vis)); memset(out,0,sizeof(out)); memset(in,0,sizeof(in)); for(int i=0;i<26;i++)pre[i]=i; } int Find(int x) { if(pre[x] != x) pre[x] = Find(pre[x]); return pre[x]; } void Union(int x,int y) { x = Find(x); y = Find(y); if(x == y) return; pre[y] = x; } bool beconnect() { for(int i=0;i<n;i++){ int u=edg[i].u,v=edg[i].v; if(u!=v&&Find(u)!=Find(v))Union(u,v); } int f=-1,k; for(k=0;k<26;k++){ if(!vis[k])continue; if(f==-1)f=k; else if(Find(k)!=Find(f))break; } if(k<26)return false; return true; } int main() { int t; scanf("%d",&t); while(t--){ init(); scanf("%d",&n); for(int i=0;i<n;i++){ scanf("%s",str); int u=str[0]-‘a‘,v=str[strlen(str)-1]-‘a‘; edg[i].u=u;edg[i].v=v; vis[u]=vis[v]=1; out[u]++;in[v]++; } bool flag=true; int cnt1=0,cnt2=0; for(int i=0;i<26;i++){ if(!vis[i])continue; if(abs(out[i]-in[i])>1){ flag=false; break; } if(out[i]-in[i]==1){ cnt1++; if(cnt1>1){ flag=false; break; } } if(out[i]-in[i]==-1){ cnt2++; if(cnt2>1){ flag=false; break; } } } if(cnt1!=cnt2)flag=false; if(!beconnect())flag=false; if(flag)puts("Ordering is possible."); else puts("The door cannot be opened."); } return 0; }
标签:
原文地址:http://www.cnblogs.com/jianrenfang/p/5771871.html