poj 2513 欧拉图/trie
Posted zzq
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj 2513 欧拉图/trie相关的知识,希望对你有一定的参考价值。
http://poj.org/problem?id=2513
Colored Sticks
Time Limit: 5000MS | Memory Limit: 128000K | |
Total Submissions: 37812 | Accepted: 9907 |
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
对每一对颜色进行连接一条无向边然后跑欧拉图验证是否可行,用了Trie来哈希字符串,并查集判断是否是连通图,坑点是有空串,,,所以可能有0个集合,此时输出"Possible";
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 #include<map> 5 using namespace std; 6 int N; 7 struct node 8 { 9 node *next[26]; 10 int v; 11 node(){v=0;memset(next,NULL,sizeof(next));} 12 }*root; 13 int gec(char *s) 14 { 15 int len=strlen(s); 16 node *p=root; 17 for(int i=0;i<len;++i) 18 { 19 if(p->next[s[i]-‘a‘]==NULL) p->next[s[i]-‘a‘]=new node(); 20 p=p->next[s[i]-‘a‘]; 21 } 22 if(p->v==0) p->v=++N; 23 return p->v; 24 } 25 int cnt[500005]; 26 int f[500005]; 27 int getf(int v){return f[v]==v?v:f[v]=getf(f[v]);} 28 int main() 29 { 30 char s1[15],s2[15]; 31 int i; 32 for(i=1;i<=500000;++i)f[i]=i; 33 root=new node(); 34 while(scanf("%s%s",s1,s2)!=EOF){ 35 int u=gec(s1); 36 int v=gec(s2); 37 int fu=getf(u),fv=getf(v); 38 if(fu!=fv) f[fv]=fu; 39 cnt[u]++; 40 cnt[v]++; 41 } 42 int s=0,x=0; 43 for(i=1;i<=N;++i) 44 { 45 if(cnt[i]%2==1) s++; 46 if(i==getf(i))x++; 47 } 48 if(x<=1&&(s==0||s==2)) puts("Possible"); 49 else puts("Impossible"); 50 return 0; 51 }
以上是关于poj 2513 欧拉图/trie的主要内容,如果未能解决你的问题,请参考以下文章
POJ-2513 Colored Sticks 欧拉通路+Trie