poj2513

Colored Sticks
Time Limit: 5000MS Memory Limit: 128000K
Total Submissions: 27346 Accepted: 7235

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.
#include <iostream>
using namespace std;

const int kind = 26;
const int MAX = 500005;
int color[MAX], father[MAX];
int node_num = 0, color_id = 0;

struct Tree
{
	int key;
	Tree *next[kind];
} node[1000005], root;

int Insert ( char* word )
{
	Tree *location = &root;
	int i = 0, id;
	while ( word[i] )
	{
		id = word[i] - 'a';
		if ( location->next[id] == NULL )
			location->next[id] = &node[++node_num];
		location = location->next[id];
		++i;
	}
	if ( location->key == 0 )
		location->key = ++color_id;
	return location->key;
}

int find_set( int x )  /*此处改了一个多小时,痛苦!仔细和下一段代码的并查集做比较*/
{
	if ( father[x] >= 0 )
		father[x] = find_set(father[x]);
	if ( father[x] < 0 )
		return x;
	else
		return father[x];
}

void Union ( int x, int y )
{
	int tx=find_set(x);
    int ty=find_set(y);
    if( tx == ty  ) return; /*根节点储存节点的个数,其余子节点储存其父节点*/
	if ( father[tx] < father[ty] )
	{
		father[tx] += father[ty];
		father[ty] = tx;
	}
	else
	{
		father[ty] += father[tx];
		father[tx] = ty;
	}
}

bool check ()
{
	int cnt1 = 0, cnt2 = 0;
	for ( int i = 1; i <= color_id; ++i )
	{
		if ( father[i] < 0 ) ++cnt1; //cnt1 = 1保证只存在一个联通分支
		if ( color[i] % 2 != 0 ) ++cnt2; //cnt2 = 0,2保证存在欧拉路径或者欧拉回路
	}
	if ( (cnt2 != 2 && cnt2 != 0) || cnt1 > 1 )
		return false;
	return true;
}

int main()
{
	int a, b;
	char str1[11], str2[11];
	memset(father,-1,sizeof(father));
	memset(color,0,sizeof(color));
	memset(node,NULL,sizeof(node));
	root = node[0];

	while ( scanf("%s%s",str1,str2) != EOF ) 
	{
		a = Insert(str1); 
		b = Insert(str2); 
		color[a]++;
		color[b]++;
		Union(a,b);	
	
	}
	if ( check() )
		printf("Possible\n");
	else
		printf("Impossible\n");
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值