Time limit
5000 ms
Memory limit
128000 kB
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.
题意:是否存在欧拉回路。一个无向图存在欧拉回路,当且仅当该图所有顶点度数都为偶数,且该图是连通图。判断是否连通,用并查集。由于单词量大,map建立单词索引会T,可以采用字典树。
#include<bits/stdc++.h>
using namespace std;
const int maxn=5e5;
int color=0,degree[maxn+1]={0},fa[maxn+1];
struct node
{
bool flag;
int id;
node* next[27];
node()
{
flag=false;
id=0;
memset(next,0,sizeof(next));
}
}root;
int Find(int x)
{
while(x!=fa[x]) x=fa[x];
return x;
}
void mer(int a,int b)
{
int pa=Find(a);
int pb=Find(b);
fa[pb]=pa;
}
int Hash(char *s)
{
node* p=&root;
int len=0;
while(s[len]!='\0')
{
int index=s[len++]-'a';
if(!p->next[index]) p->next[index]=new node;
p=p->next[index];
}
if(p->flag) return p->id;
else
{
p->flag=true;
p->id=++color;
return p->id;
}
}
int main()
{
char a[11],b[11];
for(int i=1;i<=maxn;i++) fa[i]=i;
while(~scanf("%s%s",a,b))
{
int i=Hash(a);
int j=Hash(b);
degree[i]++;
degree[j]++;
mer(i,j);
}
int Root=Find(1);
int cnt=0;
for(int i=1;i<=color;i++)
{
if(degree[i]&1) cnt++;
if(cnt>2||Find(i)!=Root)
{
printf("Impossible\n");
return 0;
}
}
printf("%s\n",cnt==1?"Impossible":"Possible");
}