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.
题解
trie树+并查集+欧拉路。
字符串哈希我从没写过感觉比较麻烦,所以用trie,不过据说hash会T。并查集是为了确定只练成一条线。否则欧拉路是简单的判定是否不重复地用了所有的棍子。
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
char a[15],b[15];
int trie[500005][26],num[500005],size,ct;
int fa[500005],e[500005];
int search(char ch[])
{
int w=0,p=0,l=strlen(ch),k;
while(p<=l)
{k=ch[p]-'a';
if(!trie[w][k]) return 0;
w=trie[w][k]; p++;
}
return num[w];
}
void insert(char ch[])
{
int w=0,p=0,l=strlen(ch),k;
while(p<=l)
{k=ch[p]-'a';
if(!trie[w][k]) trie[w][k]=++size;
w=trie[w][k]; p++;
}
num[w]=++ct;
}
int find(int x)
{
if(fa[x]!=x) fa[x]=find(fa[x]);
return fa[x];
}
void init()
{
int i,x,y,r1,r2;
for(i=1;i<=500001;i++) fa[i]=i;
while(scanf("%s%s",a,b)!=EOF)
{x=search(a);
y=search(b);
if(x==0) {insert(a); x=ct;}
if(y==0) {insert(b); y=ct;}
e[x]++; e[y]++;
r1=find(x),r2=find(y);
if(r1!=r2) fa[r1]=r2;
}
}
void work()
{
int i,s=0,j,k;
for(i=1;i<=ct;i++)
{if(e[i]&1) s++;}
if(s!=0&&s!=2) {printf("Impossible\n"); return;}
j=find(1);
for(i=2;i<=ct;i++)
{k=find(i);
if(j!=k) {printf("Impossible\n"); return;}
}
printf("Possible\n");
}
int main()
{
init(); work();
return 0;
}