Time Limit: 5000MS | Memory Limit: 128000K | |
Total Submissions: 36032 | Accepted: 9427 |
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
1 /*by SilverN*/ 2 #include<algorithm> 3 #include<iostream> 4 #include<cstring> 5 #include<cstdio> 6 #include<cmath> 7 #include<vector> 8 using namespace std; 9 const int mxn=2400; 10 const int mxm=250010; 11 int read(){ 12 int x=0,f=1;char ch=getchar(); 13 while(ch<'0' || ch>'9'){if(ch=='-')f=-1;ch=getchar();} 14 while(ch>='0' && ch<='9'){x=x*10+ch-'0';ch=getchar();} 15 return x*f; 16 } 17 int id=0; 18 struct trie{ 19 int a[mxn][26]; 20 int end[mxn]; 21 int cnt; 22 int hash(char s[]){ 23 int len=strlen(s); 24 int now=1; 25 for(int i=0;i<len;i++){ 26 if(!a[now][s[i]-'a'])a[now][s[i]-'a']=++cnt; 27 now=a[now][s[i]-'a']; 28 } 29 if(!end[now])end[now]=++id; 30 return end[now]; 31 } 32 }; 33 trie t; 34 // 35 int fa[mxm]; 36 void init(int n){for(int i=1;i<=n;i++)fa[i]=i;} 37 int find(int x){ 38 if(fa[x]==x)return x; 39 return fa[x]=find(fa[x]); 40 } 41 char s[mxm][mxn]; 42 char c1[mxn],c2[mxn]; 43 int deg[mxm]; 44 int main(){ 45 int i,j; 46 init(mxm-1);t.cnt=1; 47 while(scanf("%s%s",c1,c2)!=EOF){ 48 int x=t.hash(c1); 49 int y=t.hash(c2); 50 deg[x]++;deg[y]++; 51 x=find(x);y=find(y); 52 if(x!=y)fa[x]=y; 53 } 54 int c=0; 55 for(i=1;i<=id;i++){ 56 if(deg[i]&1)c++; 57 } 58 bool flag=1; 59 if(c>2)flag=0; 60 else{ 61 int x=find(1); 62 for(i=2;i<=id;i++){ 63 int y=find(i); 64 if(x!=y){ 65 flag=0; 66 break; 67 } 68 } 69 } 70 if(flag)printf("Possible "); 71 else printf("Impossible "); 72 return 0; 73 }