POJ2513 Colored Sticks(字典树+并查集+欧拉回路)

9 篇文章 0 订阅
7 篇文章 0 订阅

Colored Sticks
Time Limit: 5000MS Memory Limit: 128000K
Total Submissions: 33185 Accepted: 8729

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.



问你字符串能不能欧拉回路。简单明了的题用到了三个知识点。。


首先要考虑的是数据范围,给出的范围过大用字典树hash为int,而后判断是不是欧拉回路(图连通且结点的度均为偶数或有两个奇数度

的点)。


AC代码:


#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
using namespace std;
const int MAXN = 5e5 + 5;
int par[MAXN], deg[MAXN], ran[MAXN], n = 1;
struct node
{
	/* data */
	int id;
	bool vis;
	node *next[30];
	node() {
		id = 0;
		vis = false;
		for(int i = 0; i < 27; ++i)
			next[i] = NULL;
	}
}*root;
int hashint(char *s)
{
	node *p = root;
	int k;
	while(*s != 0) {
		k = *s - 'a';
		if(p -> next[k] == NULL) p -> next[k] = new node();
		p = p -> next[k];
		s++;
	} 
	if(!p -> vis) {
		p -> id = n;
		n++;
		p -> vis = true;
		return p -> id;
	}
	else return p -> id;
}
int find(int x)
{
	if(x == par[x]) return x;
	return par[x] = find(par[x]);
}
void merge(int x, int y)
{
	if(ran[x] < ran[y]) par[x] = y;
	else {
		par[y] = x;
		if(ran[x] == ran[y]) x++;
	}
}
int main(int argc, char const *argv[])
{
	char a[15], b[15];
	root = new node();
	for(int i = 1; i < MAXN; ++i)
		par[i] = i;
	while(scanf("%s%s", a, b) != EOF) {
		int x = hashint(a), y = hashint(b);
		deg[x]++, deg[y]++;
		int fx = find(x), fy = find(y);
		if(fx != fy) merge(fx, fy);
	}
	int tmp = find(1), num = 0;
	for(int i = 1; i < n; ++i) {
		if(find(i) != tmp) {
			printf("Impossible\n");
			return 0;
		}
		if(deg[i] % 2) num++;
		if(num > 2) {
			printf("Impossible\n");
			return 0;
		}
	}
	if(num == 1) printf("Impossible\n");
	else printf("Possible\n");
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值