POJ 2513 (trie)
阿新 • • 發佈:2019-02-10
Colored Sticks
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.
Time Limit: 5000MS | Memory Limit: 128000K |
Total Submissions: 23160 | Accepted: 6107 |
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
Output
If the sticks can be aligned in the desired way, output a single line saying Possible, otherwise output Impossible. 挺綜合的一題,有TRIE,有並查集,還要用歐拉回路的知識#include<stdio.h> #include<string.h> #define maxn 600000 #define kind 26 #define clear(a,b) memset(a,b,sizeof(a)) int fa[maxn],l = 0; int deg[maxn]; struct node{ int num; struct node *next[kind]; node(){ num = 0; clear(next,NULL); } } *root; int build(struct node *T, char s[]) { int i = 0,k; struct node *t = T; while(s[i]) { k = s[i] - 'a'; if (t->next[k] == NULL) t->next[k] = new node(); t = t->next[k]; i++; } t->num = ++l; return l; } int find(struct node *T,char s[]) { int i = 0,k; struct node *t = T; while(s[i]) { k = s[i] - 'a'; if (t->next[k] == NULL) return 0; t = t->next[k]; i++; } return t->num; } int getfa(int t) { while(t != fa[t]) t = fa[t]; return t; } int judge(int a,int b) { return getfa(a) == getfa(b); } void unfa(int a,int b) { fa[b] = getfa(a); } int work() { int i,t1,t2,tmp; char s1[20],s2[20]; root = new node(); clear(deg,0); for(i = 1;i < maxn;i++) fa[i] = i; while (scanf("%s%s",s1,s2) != EOF) { // if (s1[0] == '0') break; if ((t1 = find(root,s1)) == 0) t1 = build(root,s1); if ((t2 = find(root,s2)) == 0) t2 = build(root,s2); if (!judge(t1,t2)) unfa(t1,t2); // printf("%d %d\n",t1,t2); deg[t1]++; deg[t2]++; } if (l == 0) return 1; tmp = getfa(1); t1 = 0; t2 = 0; for(i = 2;i <= l;i++) if (getfa(i) != tmp) return 0; for(i = 1;i <= l;i++) if (deg[i] & 1) t1++; else t2++; if (t1 == 0) return 1; if (t1 == 2) return 1; return 0; } int main() { if (work()) printf("Possible\n"); else printf("Impossible\n"); return 0; }