Colored Sticks--POJ 2513

1、解题思路:字典树,并查集,欧拉通路。

2、注意事项:字典树的插入;并查集与DFS的结合;欧拉回路的判断。

3、实现方法:

  
    
1 #include < iostream >
2 #include < map >
3 #include < string >
4 using namespace std;
5
6   // 用邻接表表示连接关系
7 struct Edge
8 {
9 int v;
10 Edge * nxt;
11 };
12 Edge * head[ 1000010 ];
13 Edge Arr[ 1000010 ];
14
15 struct Trie
16 {
17 bool IsStr;
18 int Id;
19 Trie * nxt[ 26 ];
20 };
21 Trie root,temp[ 1000000 ];
22
23 int pos,cnt,num;
24 bool visite[ 500010 ];
25
26 // trie树的插入
27 int Insert( char str[])
28 {
29 int len = strlen(str);
30 Trie * Current =& root;
31 for ( int i = 0 ;i < len;i ++ )
32 {
33 if (Current -> nxt[str[i] - ' a ' ] == NULL)
34 Current -> nxt[str[i] - ' a ' ] =& temp[pos ++ ];
35 Current = Current -> nxt[str[i] - ' a ' ];
36 }
37 if (Current -> IsStr)
38 return Current -> Id;
39 Current -> IsStr = true ;
40 Current -> Id =++ cnt;
41 return Current -> Id;
42 }
43
44 void DFS( int v)
45 {
46 Edge * w = head[v] -> nxt;
47 visite[v] = true ;
48 while (w)
49 {
50 if (visite[w -> v] == false )
51 DFS(w -> v);
52 w = w -> nxt;
53 }
54 }
55
56 bool Judge()
57 {
58 int x = 0 ;
59 for ( int i = 1 ;i <= cnt;i ++ )
60 {
61 if (visite[i] == false )
62 {
63 DFS(i);
64 x ++ ;
65 }
66 if (x > 1 )
67 return false ;
68 }
69 return true ;
70 }
71
72 void Init()
73 {
74 char str1[ 11 ],str2[ 11 ];
75 int A1,A2;
76 while (scanf( " %s %s " ,str1,str2) != EOF)
77 {
78 A1 = Insert(str1);
79 A2 = Insert(str2);
80 if (head[A1] == NULL)
81 head[A1] =& Arr[num ++ ];
82 if (head[A2] == NULL)
83 head[A2] =& Arr[num ++ ];
84 Edge * p = head[A1], * q;
85 while (p)
86 {
87 q = p;p = p -> nxt;
88 }
89 q -> nxt =& Arr[num ++ ];
90 q -> nxt -> v = A2;
91 Edge * r = head[A2], * w;
92 while (r)
93 {
94 w = r;r = r -> nxt;
95 }
96 w -> nxt =& Arr[num ++ ];
97 w -> nxt -> v = A1;
98 }
99 }
100
101 int main()
102 {
103 int i,s,ans = 0 ;
104 Init();
105 if (cnt == 0 )
106 cout << " Possible " << endl;
107 else
108 {
109 if (Judge())
110 {
111 for (i = 1 ;i <= cnt;i ++ )
112 {
113 Edge * p = head[i];
114 s =- 1 ;
115 while (p)
116 {
117 s ++ ; p = p -> nxt;
118 }
119 if (s % 2 == 1 )
120 ans ++ ;
121 }
122 if (ans == 0 || ans == 2 )
123 cout << " Possible " << endl;
124 else
125 cout << " Impossible " << endl;
126 }
127 else
128 cout << " Impossible " << endl;
129 }
130 return 0 ;
131 }

 

 

 

你可能感兴趣的:(color)