Colored Sticks
Time Limit: 5000MS | Memory Limit: 128000K | |
Total Submissions: 30933 | Accepted: 8151 |
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.
这道题和单词游戏类似,求一个无向图的欧拉通路或者回路,由于要判断图是否连通,需用并查集,这题节点是字符串,因此查询有点麻烦,这题不可用STL中的map,输入数据量是在太大了,因此我写了个trie。不过庆幸的是poj的内存可以随便开,上亿了都还没超内存。。。
代码:
#include<cstdio>
#include<iostream>
#include<cstring>
#define Maxn 500010
using namespace std;
char s1[20],s2[20];
int fa[Maxn],deg[Maxn];
void init(){
for(int i=1;i<Maxn;i++)
fa[i]=i;
}
int findset(int x){
return fa[x]==x?x:(fa[x]=findset(fa[x]));
}
void unionset(int x,int y){
x=findset(x),y=findset(y);
fa[x]=y;
}
int tot=0;
struct trie{
int ch[Maxn*10][26];
int v[Maxn*10];
int sz;
trie(){sz=0;memset(ch[0],0,sizeof ch[0]);}
int insert(char *s){
int u=0;
for(int i=0;s[i];i++){
int c=s[i]-'a';
if(!ch[u][c]){
ch[u][c]=++sz;
v[sz]=0;
memset(ch[sz],0,sizeof(ch[0]));
}
u=ch[u][c];
}
if(!v[u]) v[u]=++tot;
return v[u];
}
}tr;
int main()
{
int id1,id2,i;
bool flag=true;
memset(deg,0,sizeof deg);
init();
while(~scanf("%s%s",s1,s2)){
int id1=tr.insert(s1),id2=tr.insert(s2);
deg[id1]++,deg[id2]++;
unionset(id1,id2);
}
int in=0;
flag=true;
for(i=1;i<=tot;i++){
if(deg[i]&1) in++;
if(in>2) {flag=false;break;}
}
if(!flag) {puts("Impossible");return 0;}
int t=findset(1);
for(i=2;i<=tot;i++)
if(findset(i)!=t) {flag=false;break;}
if(flag) puts("Possible");
else puts("Impossible");
return 0;
}