Time Limit: 5000MS | Memory Limit: 128000K | |
Total Submissions: 39360 | Accepted: 10260 |
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.
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string>
#include <string.h>
#include <queue>
#include <map>
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string>
#include <string.h>
#include <queue>
#include <map>
int trie[500000][26],flag[500000],r[500000],pre[500000],num[500000],s,n;
char ss[15];
void insert(int w,int k){
++s;
flag[s] = 0;
memset(trie[s], 0, sizeof(trie[s]));
trie[w][k]=s;
}
int add(char we[]){
int c=0;
int len=strlen(we);
for(int i=0;i<len;i++){
int k=we[i]-'a';
if(trie[c][k]==0){
insert(c,k);
}
c=trie[c][k];
}
if(flag[c])
++ num[r[c]];
else
{
flag[c] = 1;
r[c]=++n;
num[n] = 1;
}
return r[c];
}
int find(int x){
if(pre[x]==x)
return x;
return pre[x]=find(pre[x]);
}
int main(){
char a[15],b[15];
for(int i=0;i<500000;i++)
pre[i]=i;
n=0;
s=0;
memset(num, 0, sizeof(num));
while(scanf("%s %s",a,b)!=EOF){
int x=add(a);
int y=add(b);
int tx = find(x), ty = find(y);
if(tx != ty)
pre[tx] = ty;
}
int gg=find(1);
int f=0,k=0;
for(int i=2;i<=n;i++){
if(find(i)!=gg){
f=1;
break;
}
if(num[i] % 2)
++k;
if(k>2){
f=1;
break;
}
}
if(f==1){
printf("Impossible\n");
}
else {
printf("Possible\n");
}
}