Uva--10129 (欧拉回路,判连通)

2014-07-08 22:08:44

题意&思路:欧拉道路(无环)。思路:用并查集判连通,然后用入出度判断。

 1 #include <cstdio>
 2 #include <vector>
 3 #include <cstring>
 4 #include <iostream>
 5 using namespace std;
 6 
 7 int Case,n,fa[30],inc[100005],outc[100005];
 8 
 9 int Find(int x){
10     if(fa[x] != x) return Find(fa[x]);
11     return fa[x];
12 }
13 
14 void Union(int a,int b){
15     int x = Find(a);
16     int y = Find(b);
17     if(x != y)    fa[y] = x;
18 }
19 
20 int main(){
21     int len;
22     char str[1005];
23     scanf("%d",&Case);
24     while(Case--){
25         scanf("%d",&n);
26         memset(inc,0,sizeof(inc));
27         memset(outc,0,sizeof(outc));
28         for(int i = 0; i < 26; ++i)
29             fa[i] = i;
30 
31         for(int i = 0; i < n; ++i){
32             scanf("%s",str);
33             len = strlen(str);
34             int a = (int)(str[0] - 'a');
35             int b = (int)(str[len - 1] - 'a');
36             if(fa[a] == -1) fa[a] = a;
37             if(fa[b] == -1) fa[b] = b;
38             Union(a,b);
39 
40             outc[a]++;
41             inc[b]++;
42         }
43         int flag = 1,cntmin = 0,cntmax = 0,cnt = 0,setn = 0,ti;
44         for(int i = 0; i < 26; ++i)
45             if((inc[i] + outc[i]) && fa[i] == i) ++setn;
46 
47         if(setn > 1)    printf("The door cannot be opened.\n");
48         else{
49             for(int i = 0; i < 26; ++i){
50                 if(inc[i] != outc[i]){ //白书给出的严格条件
51                     if(outc[i] - inc[i] == 1 && !cntmin)
52                         cntmin = 1;
53                     else if(inc[i] - outc[i] == 1 && !cntmax)
54                         cntmax = 1;
55                     else{
56                         flag = 0;
57                         break;
58                     }
59                 }
60             }
61             if(flag) printf("Ordering is possible.\n");
62             else printf("The door cannot be opened.\n");
63         }
64     }
65     return 0;
66 }

 

posted @ 2014-07-08 22:11  Naturain  阅读(180)  评论(0编辑  收藏  举报