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 redred violetcyan blueblue magentamagenta cyan
Sample Output
Possible
并查集①
code:
View Code
#include#include #define maxn 500005 int de[maxn]; int f[maxn]; int v[maxn]; int find(int x) { int r=x; while(r!=f[r]) r=f[r]; int i=x; int j; while(i!=r) { j=f[i]; f[i]=r; i=j; } return r; } void join(int x,int y) { int fx=find(x); int fy=find(y); if(fx!=fy) { if(fx 2) { printf("Impossible\n"); return 0; } } tot=0; for(i=1;i 1) { printf("Impossible\n"); return 0; } } printf("Possible\n"); return 0; }
并查集②:
View Code
#include#include #define maxn 500005 int de[maxn]; int f[maxn]; int find(int x) { int r=x; while(r!=f[r]) r=f[r]; int i=x; int j; while(i!=r) { j=f[i]; f[i]=r; i=j; } return r; } void join(int x,int y) { if(find(x)==0) f[x]=x; if(find(y)==0) f[y]=y; f[find(x)]=find(y); } int Hash(char s[]) { int i,hash=1; int len=strlen(s); for(i=0;i 2) { printf("Impossible\n"); return 0; } } i=1; for(i=1;i
字典树:
View Code
#include#include #define maxn 500005 int de[maxn]; int f[maxn]; int num; struct node { int id,i; node *next[26]; node() { id=-1; for(i=0;i<26;i++) next[i]=NULL; } }*root; int find(int x) { int r=x; while(r!=f[r]) r=f[r]; int i=x; int j; while(i!=r) { j=f[i]; f[i]=r; i=j; } return r; } void join(int x,int y) { if(find(x)==0) f[x]=x; if(find(y)==0) f[y]=y; f[find(x)]=find(y); } int insert(char s[]) { int i; node *p=root; int len=strlen(s); for(i=0;i next[s[i]-'a']==NULL) p->next[s[i]-'a']=new node; p=p->next[s[i]-'a']; } if(p->id==-1) p->id=num++; return p->id; } int main() { num=0; root=new node; char a[11],b[11]; int p,q,flag; int i,sum; for(i=0;i 2||flag!=find(i)) { printf("Impossible\n"); return 0; } } printf("Possible\n"); return 0; }