这道题意思是:给你一些字符串,看你能不能把他连成一串(连串规则:

一个字符串a【】的首位要是与另一个字符串b【】的末尾相同就能连起来,b后跟着a)

用并查集找出其每个字符出度与入度的个数:

1.当相等时即构成欧拉回路满足条件

2.当只有一个符号的出度多入度一个且一个符号的入度比出度多一个其他符号出度都等于入度是满足条件

(还要判断是否构成回路,当最终点个数>1时不构成回路)

代码:

View Code
 1 #include"iostream"
 2 #include"string"
 3 using namespace std;
 4 char  a[1002];
 5 int f,ff[27],used[27],in[27],out[27];
 6 int find(int x)
 7 {
 8     if(x!=ff[x])
 9         ff[x]=find(ff[x]);
10     return ff[x];
11 }
12 void memg(int x,int y)
13 {
14     x=find(x);
15     y=find(y);
16     if(x!=y)
17         ff[x]=y;
18 }
19 int main()
20 {
21 
22     
23     int n,m;
24     int x,y,i,j;
25     cin>>n;
26     while(n--)
27         {
28             f=0;
29             int s=0,s1=0;
30             memset(in,0,sizeof(in));
31             memset(out,0,sizeof(out));
32             memset(used,0,sizeof(used));//初始化
33             for(i=0;i<26;i++)
34                 ff[i]=i;
35             cin>>m;
36             for(i=0;i<m;i++)
37             {
38                cin>>a;
39                x=a[0]-'a';
40                y=a[strlen(a)-1]-'a';//处理信息
41                in[x]++;//入度个数
42                out[y]++;//出度个数
43                used[x]=1;
44                used[y]=1;
45                memg(x,y);
46             }
47             for(j=0;j<26;j++)
48             {
49                 if(used[j]&&j==ff[j])
50                     f++;
51             }//判断最终点个数
52             if(f>1)
53               
54             {
55                 cout<<"The door cannot be opened."<<endl;
56                 continue;
57             }
58             for(i=0;i<26;i++)
59             {
60                 if(used[i]&&in[i]!=out[i])
61                 {
62                         if(1==in[i]-out[i])
63                             s++;//记录入度大于出度1的个数
64                         else if(1==out[i]-in[i])
65                             s1++;//记录出度大于入度1的个数
66                         else
67                             break;
68                 }            
69             }
70             if(i<26)
71                 cout<<"The door cannot be opened."<<endl;
72             else if(0==(s+s1)||(1==s&&1==s1))//满足条件1,2的
73                 cout<<"Ordering is possible."<<endl;
74             else
75                 cout<<"The door cannot be opened."<<endl;
76         }
77     return 0;
78 }

 

posted on 2012-09-20 20:08  xinmenghuairi  阅读(219)  评论(0编辑  收藏  举报