说下题目大意,给出n根木棍,每根木棍两端都有颜色,颜色为小于10的字符串,问能否将所有的木棍排成一排,使得每两根木棍衔接的地方颜色相同。
这题我一开始暴力做,很随意的就TLE了...看了Discuss发现要用什么"Trie"和"欧拉通路",还要用到前几天学会的并查集...晕死,根本不知道什么是"Trie"和"欧拉通路",遂Google了一下,得知"Trie"俗称字典树,具体内容完了发到博客上...欧拉通路完了也发博客上...本文发表2 weeks后应该可以搜索到...
对于知道以上概念者,可以看出本题就是将所有的颜色看做节点,连接两种颜色的木棍看做节点之间的连边,判断无向图中是否存在欧拉通路,判断条件是:
1、有且只有两个度为奇数的节点
2、图是连通的
由于节点是字符串,因此我们可以利用字典树将其转换成一个颜色序号。这样,统计每种颜色的出现次数就可以了。判断图是否连通,可以利用并查集:若最后所有节点在同一个集合,则图是连通的。
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
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; int p[520000],q[520000]; int top; struct node { int flag; struct node *next[27]; }*head; node *newnode() { int i; node *p=new node; p->flag=0; for(i=0; i<27; i++) p->next[i]=NULL; return p; } int zdsh(node *head,char *s) { int i; node *p= head; int l=strlen(s); for(i=0; i<l; i++) { int k=s[i]-'a'; if(p->next[k]==NULL) p->next[k]=newnode(); p=p->next[k]; } if(p->flag==0) p->flag=top++; return p->flag; } int Find(int x) { int r=x,i=x,j; while(r!=p[r]) r=p[r]; while(i!=r) { j=p[i]; p[i]=r; i=j; } return r; } void Search(int x,int y) { int xx,yy; xx=Find(x); yy=Find(y); if(xx!=yy) p[xx]=yy; } int main() { char s1[11],s2[11]; int i,n; memset(q,0,sizeof(q)); head=newnode(); for(i=0; i<=520000; i++) p[i]=i; top=1; while(~scanf("%s %s",s1,s2)) { int k1=zdsh(head,s1); int k2=zdsh(head,s2); q[k1]++; q[k2]++; Search(k1,k2); } for(i=2; i<top; i++) if(Find(i)!=Find(1)) break; if(i<top) printf("Impossible\n"); else { int s=0; for(i=1; i<top; i++) if(q[i]%2) s++; if(s==0||s==2) printf("Possible\n"); else printf("Impossible\n"); } return 0; }
以前一道比赛的题目竟然忘了做了,刚想起来,于是乎就A了它
先用字典树给棍子编号然后用并查集进行合并最后再进行欧拉图判断