Time Limit: 5000MS | Memory Limit: 128000K | |
Total Submissions: 37340 | Accepted: 9796 |
Description
You are given a bunch of wooden sticks. Each endpoint of each stick is colored with some color. Is it possible to align the sticks in a straight line such that the colors of the endpoints that touch are of the same color?
Input
Input is a sequence of lines, each line contains two words, separated by spaces, giving the colors of the endpoints of one stick. A word is a sequence of lowercase letters no longer than 10 characters. There is no more than 250000 sticks.
Output
If the sticks can be aligned in the desired way, output a single line saying Possible, otherwise output Impossible.
Sample Input
blue red red violet cyan blue blue magenta magenta cyan
Sample Output
Possible
Hint
Huge input,scanf is recommended.
Source
#include<iostream> #include<cstdio> #include<cmath> #include<cstring> #include<sstream> #include<algorithm> #include<queue> #include<deque> #include<iomanip> #include<vector> #include<cmath> #include<map> #include<stack> #include<set> #include<fstream> #include<memory> #include<list> #include<string> using namespace std; typedef long long LL; typedef unsigned long long ULL; #define MAXN 500008 #define INF 1000000009 #define eps 0.00000001 /* 欧拉路 一笔画问题! Trie树就是一种节省空间的hash 利用并查集判断是否联通 */ char a[15], b[15]; int cnt = 0, index = 1, pre[MAXN], degree[MAXN]; typedef struct node { bool flag; int id; struct node* next[26]; }*Tree; node memory[MAXN]; Tree Newnode() { Tree T = &memory[cnt++]; T->flag = false; T->id = -1; for (int i = 0; i < 26; i++) T->next[i] = NULL; return T; } int Insert(char* s, Tree T) { int p = 0; while (s[p] != '\0') { int k = s[p] - 'a'; if (!T->next[k]) T->next[k] = Newnode(); T = T->next[k]; p++; } if (T->flag) return T->id; else { T->flag = true; T->id = index++; return T->id; } } int find(int x) { if (pre[x] == -1) return x; else return pre[x] = find(pre[x]); } void mix(int a, int b) { int fa = find(a), fb = find(b); if (fa != fb) { pre[fa] = fb; } } int main() { memset(pre, -1, sizeof(pre)); memset(degree, 0, sizeof(degree)); Tree T = Newnode(); while (scanf("%s %s", a, b) != EOF) { //if (a[0] == '#') break; int ia = Insert(a, T), ib = Insert(b, T); //cout << ia << ' ' << ib << endl; degree[ia]++; degree[ib]++; mix(ia, ib); } int s = find(1), tmp = 0; for (int i = 1; i < index; i++) { if (find(i) != s) //存在多个祖先,图为森林,不连通 { printf("Impossible\n"); return 0; } if (degree[i] % 2) tmp++; } if(tmp==0 || tmp==2) printf("Possible\n"); else printf("Impossible\n"); }