Colored Sticks
Time Limit: 5000MS | Memory Limit: 128000K | |
Total Submissions: 27266 | Accepted: 7211 |
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
题意:给n条棍,每条棍2边有颜色,若2条棍的一边颜色相同则可以连起来,问是否能将所有棍连在一起
题解:可以把没种颜色看作一个点,然后这就是一个欧拉路问题(一笔画问题)。用字典树来分配并对应其颜色的下标,用并查集来判是否连通图,然后易知有奇数条边相连的点不能超过2个则存在欧拉路
#include<stdio.h>
#include<string.h>
struct tree{
int next[26],data;
}tire[1000005];
int v[1000005],cnt[1000005];
int cou=0,cou2=1;
int fin(int x)
{
if(x==v[x]) return x;
return v[x]=fin(v[x]);
}
int inter(char *s)
{
int p=0;
while(*s)
{
if(tire[p].next[*s-'a']==-1)
{
tire[p].next[*s-'a']=cou;
p=cou++;
}
else p=tire[p].next[*s-'a'];
s++;
}
if(tire[p].data!=-1) return tire[p].data;
v[cou2]=cou2;
return tire[p].data=cou2++;
}
int main()
{
char a[13],b[13];
int x,y,i;
memset(tire,-1,sizeof(tire));
memset(cnt,0,sizeof(cnt));
while(scanf("%s%s",a,b)>0)
{
x=inter(a),y=inter(b);
cnt[x]++,cnt[y]++;
x=fin(x),y=fin(y);
if(x!=y) v[x]=y;
}
x=y=0;
for(i=1;i<cou2;i++)
{
if(cnt[i]&1) x++;
if(fin(i)==i) y++;
if(y>1||x>2) break;
}
if(y<=1&&x<=2) printf("Possible\n");
else printf("Impossible\n");
return 0;
}