poj2513 Colored Sticks 字典树+并查集+欧拉路

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
 
 
就是让你把这几根棒子排在一起看能不能成环,先存着,下次来写
 
 
 
 
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
struct trie{
	bool flag;
	int id;
	trie* next[27];
};
int color=0,du[500001]={0},f[500001];
int find(int x)
{
	if(f[x]!=x)f[x]=find(f[x]);
	return f[x];
}
void union1(int a,int b)
{
	f[find(b)]=find(a);
}
trie* built()
{
	trie* leaf=new trie;
	leaf->flag=false;
	leaf->id=0;
	memset(leaf->next,0,sizeof(leaf->next));
	return leaf;
}
int build(trie *&root,char* s)
{
	trie* p=root;
	int len=0;
	while(s[len]!='\0')
	{
		int x=s[len++]-'a';
		if(!p->next[x])p->next[x]=built();
		p=p->next[x];
	}
	if(p->flag)return p->id;
	else{
		p->flag=true;
		p->id=++color;
		return p->id;
	}
}
int main()
{
	trie* root=built();
	for(int k=1;k<=500000;k++)f[k]=k;
	char a[20],b[20];
	while(cin>>a>>b)
	{
		int i=build(root,a),j=build(root,b);
		du[i]++,du[j]++;
		union1(i,j);
	}
	int num=0,s=find(1);
	for(int i=1;i<=color;i++)
	{
		if(du[i]%2==1)num++;
		if(num>2||find(i)!=s)
		{
			cout<<"Impossible\n";
			return 0;
		}
	}
	if(num==1)cout<<"Impossible\n";
	else cout<<"Possible\n";
	return 0;
}


猜你喜欢

转载自blog.csdn.net/yslcl12345/article/details/50700472