poj 2513 Colored Sticks

Tire + 并查集 + Eular回路,花了老长时间呢。

 1 #include <stdio.h>
 2 #include <string.h>
 3 const int N = 500050;
 4 int next[5*N][26],d[5*N],cnt=0;
 5 int fa[N],col[N],D[N],color=0;
 6 int inst(char *t)
 7 {
 8     int u = 0,idx;
 9     while(*t)
10     {
11         idx = *t -'a';
12         if(!next[u][idx])
13         {
14             memset(next[cnt++],0,sizeof next[0]);
15             next[u][idx] = cnt;
16         }
17         u = next[u][idx];
18         t++;
19     }
20     if(!d[u])
21         color++,col[u] = color,D[color] = u;
22     d[u]++;
23     return col[u];
24 }
25 int find(int a)
26 {
27     int r=a,b=a,t;
28     while(fa[r] != r) r = fa[r];
29     while(b != r)
30     t = b, b = fa[b], fa[t] = r;
31     return r;
32 }
33 bool divide()
34 {
35     for(int i = 2; i <= color; i++)
36         if(find(i) != fa[1]) return 1;
37     return 0;
38 }
39 bool Eular()
40 {
41     int f=0,i;
42     for(i = 1; i <= color; i++)
43     {
44         if(d[D[i]] & 1) f++;
45         if(f >= 3) return 0;
46     }
47     return 1;
48 }
49 int main()
50 {
51     char t[15],s[15];
52     int x,y;
53     memset(d,0,sizeof(d));
54     for(int i = 0; i < N; i++)
55         fa[i] = i;
56     while(~scanf("%s%s",t,s))
57     {
58         x = find(inst(t));
59         y = find(inst(s));
60         fa[y] = x;
61     }
62     if(divide() || !Eular())
63         printf("Impossible\n");
64     else printf("Possible\n");
65     return 0;
66 }
原文地址:https://www.cnblogs.com/lzxskjo/p/2647826.html