Colored Sticks
Time Limit: 5000MS | Memory Limit: 128000K | |
Total Submissions: 28036 | Accepted: 7428 |
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
The UofA Local 2000.10.14
无向图欧拉通路:连通图+两个点的度数是奇数。。。。。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 5 using namespace std; 6 7 const int maxnode=10000000; 8 int worldnum=0,Father[510000],USize[510000],degree[510000]; 9 10 struct Trie 11 { 12 int tot,root,child[maxnode][26]; 13 int flag[maxnode]; 14 Trie() 15 { 16 memset(child[1],0,sizeof(child[1])); 17 memset(flag,-1,sizeof(flag)); 18 root=tot=1; 19 } 20 void Insert(const char* str) 21 { 22 int *cur=&root; 23 for(const char* p=str;*p;*p++) 24 { 25 cur=&child[*cur][*p-'a']; 26 if(*cur==0) 27 { 28 *cur=tot++; 29 memset(child[tot],0,sizeof(child[tot])); 30 flag[tot]=-1; 31 } 32 } 33 flag[*cur]=worldnum++; 34 } 35 36 int Query(const char*str) 37 { 38 int* cur=&root; 39 for(const char* p=str;*p&&*cur;p++) 40 { 41 cur=&child[*cur][*p-'a']; 42 } 43 if(*cur&&~flag[*cur]) 44 { 45 return flag[*cur]; 46 } 47 else 48 { 49 Insert(str); 50 return worldnum-1; 51 } 52 } 53 }T; 54 55 int Findfather(int x) 56 { 57 if(Father[x]==x) 58 { 59 return x; 60 } 61 else 62 { 63 Father[x]=Father[Father[x]]; 64 return Findfather(Father[x]); 65 } 66 } 67 68 void Disjoin() 69 { 70 for(int i=0;i<510000;i++) 71 { 72 Father[i]=i; USize[i]=1; 73 } 74 } 75 76 void Unionset(int a,int b) 77 { 78 int Fa=Findfather(a); 79 int Fb=Findfather(b); 80 if(Fa==Fb) return ; 81 if(USize[Fa]>=USize[Fb]) 82 { 83 Father[Fa]=Fb; 84 USize[Fb]+=USize[Fa]; 85 } 86 else 87 { 88 Father[Fb]=Fa; 89 USize[Fa]+=USize[Fb]; 90 } 91 } 92 93 int main() 94 { 95 char str1[15],str2[15]; 96 Disjoin(); 97 while(scanf("%s %s",str1,str2)!=EOF) 98 { 99 int a=T.Query(str1); 100 int b=T.Query(str2); 101 degree[a]++; degree[b]++; 102 Unionset(a,b); 103 } 104 int sum=0; 105 for(int i=0;i<worldnum;i++) 106 { 107 if(degree[i]%2==1) sum++; 108 } 109 if(sum>2) { puts("Impossible"); return 0;} 110 for(int i=1;i<worldnum;i++) 111 { 112 if(Findfather(0)!=Findfather(i)) 113 { puts("Impossible"); return 0;} 114 } 115 puts("Possible"); 116 return 0; 117 }