标签:
/* *POJ 2513 Colored Sticks *参考: http://poj.org/showmessage?message_id=181500 *Hash + 并查集 + 欧拉通路判定 *把每根棍子看成一条无向边 *Hash函数来自上面的链接,数据弱所以table 1000 就够了 */ #include <cstdio> #include <cstring> const int MAXN = 1000; int parent[MAXN], degree[MAXN]; int hash(char *s) { int key = 1; int len = strlen(s); for (int i = 0; i < len; i++) { key = (key * 29 + s[i] - ‘a‘) % MAXN; } return key; } void init() { for (int i = 0; i < MAXN; i++) { parent[i] = i; degree[i] = 0; } } int find(int x) { return parent[x] == x ? parent[x] : parent[x] = find(parent[x]); } void unin(int u, int v) { parent[find(v)] = find(u); } // int find(int x) // { // int tmp = 0; // int root = x; // while (parent[root] >= 0) { // root = parent[root]; // } // while (x != root) { // tmp = parent[x]; // parent[x] = root; // x = tmp; // } // return root; // } // void unin(int root1, int root2) // { // int sum = parent[root1] + parent[root2]; // if (parent[root1] > parent[root2]) { // parent[root1] = root2; // parent[root2] = sum; // } else { // parent[root2] = root1; // parent[root1] = sum; // } // } int main() { char color1[11], color2[11]; int odd_degree = 0; init(); while (~scanf("%s%s", color1, color2)) { int u = hash(color1); int v = hash(color2); degree[u] ++; degree[v]++; int root1 = find(u); int root2 = find(v); if (root1 != root2) unin(root1, root2); } int root = -1; for (int i = 0; i < MAXN; i++) { if (degree[i] > 0) { if (degree[i] % 2) { odd_degree++; if (odd_degree > 2) { printf("Impossible\n"); return 0; } } if (root == -1) root = find(i); else if (root != find(i)) { printf("Impossible\n"); return 0; } } } printf("Possible\n"); return 0; }
标签:
原文地址:http://www.cnblogs.com/subrshk/p/4267117.html