POJ-2513 Colored Sticks

Time Limit: 5000MS Memory Limit: 128000K
Total Submissions: 34372 Accepted: 8976

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


分析: 把每个颜色看成一个点,转换成一笔画问题,要用到并查集。


#include <cstdio>
#include <string>
#include <cstring>
#include <cmath>
#include <iostream>
#define maxnode 1000002
using namespace std;
char a[11],b[11];
int d[500002],f[500002],num;
int Find(int x)
{
	if(f[x] == x) return x;
	f[x]=Find(f[x]);
	return f[x]; 
}
struct trie
{
	int ch[maxnode][26];
	int val[maxnode];
	int tot;
	void build()
	{
		tot=1;
		memset(ch[0],0,sizeof(ch[0]));
	}
	int idx(char c) 
	{
		return c-'a';
	}
	int insert(char s[11])
	{
		int u=0,n=strlen(s);
		for(int i=0;i < n;i++)
		{
			int c=idx(s[i]);
			if(!ch[u][c])
			{
				memset(ch[tot],0,sizeof(ch[tot]));
				val[tot]=0;
				ch[u][c]=tot++;	
			}	
			u=ch[u][c];
		} 
		if(val[u] == 0) val[u]=++num;
		d[val[u]]++;
		return val[u];
	}
} tree;
int main()
{
	tree.build();
	for(int i=1;i <= 500001;i++) f[i]=i;
	while(~scanf("%s %s",a,b))
	{
	 	f[Find(tree.insert(a))]=Find(tree.insert(b));	
	}
	for(int i=2;i <= num;i++)
	 if(Find(i) != Find(1)) 
	 {
	 	printf("Impossible\n");
	 	return 0;
	 }
	int now=0;
	for(int i=1;i <= num;i++) if(d[i] & 1 == 1) now++;
	if(now == 0 || now == 2) printf("Possible\n");
	else printf("Impossible\n");
 } 


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值