POJ 2513 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

Hint

Huge input,scanf is recommended.

题解

trie树+并查集+欧拉路。

字符串哈希我从没写过感觉比较麻烦,所以用trie,不过据说hash会T。并查集是为了确定只练成一条线。否则欧拉路是简单的判定是否不重复地用了所有的棍子。

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
char a[15],b[15];
int trie[500005][26],num[500005],size,ct;
int fa[500005],e[500005];
int search(char ch[])
{
	int w=0,p=0,l=strlen(ch),k;
	while(p<=l)
	   {k=ch[p]-'a';
	    if(!trie[w][k]) return 0;
	    w=trie[w][k]; p++;
	   }
	return num[w];
}
void insert(char ch[])
{
	int w=0,p=0,l=strlen(ch),k;
	while(p<=l)
	   {k=ch[p]-'a';
	    if(!trie[w][k]) trie[w][k]=++size;
	    w=trie[w][k]; p++;
	   }
	num[w]=++ct;
}
int find(int x)
{
	if(fa[x]!=x) fa[x]=find(fa[x]);
	return fa[x];
}
void init()
{
	int i,x,y,r1,r2;
	for(i=1;i<=500001;i++) fa[i]=i;
	while(scanf("%s%s",a,b)!=EOF)
	   {x=search(a);
	    y=search(b);
	    if(x==0) {insert(a); x=ct;}
	    if(y==0) {insert(b); y=ct;}
	    e[x]++; e[y]++;
	    r1=find(x),r2=find(y);
	    if(r1!=r2) fa[r1]=r2;
	   }
}
void work()
{
	int i,s=0,j,k;
	for(i=1;i<=ct;i++)
	   {if(e[i]&1) s++;}
	if(s!=0&&s!=2) {printf("Impossible\n"); return;}
	j=find(1);
	for(i=2;i<=ct;i++)
	   {k=find(i);
	    if(j!=k) {printf("Impossible\n"); return;}
	   }
	printf("Possible\n");
}
int main()
{
	init(); work();
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值