POJ 2513 Trie
链接:
http://poj.org/problem?id=2513
题意:
就是给你n个木棒,左右两端有颜色,颜色一样的可以连在一起,问你能不能全部连在一起
题解:
其实就是字典树+欧拉通路+并查集
之前写过hdu上一个是字母连接的,好像是暑假集训是写过,这个是字符串,果然map水不过啊。。
那就只好用字典树了,不过小错误不断啊
代码:
31 int par[MAXN]; 32 33 void init(int n) { 34 rep(i, 0, n) par[i] = i; 35 } 36 37 int find(int x) { 38 return par[x] = par[x] == x ? x : find(par[x]); 39 } 40 41 void unite(int x, int y) { 42 int a = find(x), b = find(y); 43 if (a != b) par[a] = b; 44 } 45 46 bool same(int x, int y) { 47 return find(x) == find(y); 48 } 49 50 int pi = 1; 51 52 struct Node { 53 int next[26]; 54 int id; 55 int sum; 56 }tree[MAXN * 10]; 57 58 int Sum = 0; 59 int N = 1; 60 61 int insert(string s) { 62 int index, p, i; 63 for (i = p = 0; s[i]; i++) { 64 index = s[i] - 'a'; 65 if (tree[p].next[index] == 0) 66 tree[p].next[index] = pi++; 67 p = tree[p].next[index]; 68 } 69 tree[p].sum++; 70 if (tree[p].sum % 2) Sum++; 71 else Sum--; 72 if (!tree[p].id) tree[p].id = N++; 73 return tree[p].id; 74 } 75 76 int main() { 77 ios::sync_with_stdio(false), cin.tie(0); 78 init(MAXN); 79 string s; 80 while (getline(cin, s) && s != "") { 81 string a, b; 82 int fg = 1; 83 rep(i, 0, s.length()) { 84 if (s[i] == ' ') { 85 fg = 0; 86 continue; 87 } 88 if (fg) a += s[i]; 89 else b += s[i]; 90 } 91 int x = insert(a); 92 int y = insert(b); 93 unite(x, y); 94 } 95 rep(i, 2, N) if (!same(1, i)) Sum = 1; 96 if (Sum == 0 || Sum == 2) cout << "Possible" << endl; 97 else cout << "Impossible" << endl; 98 return 0; 99 }