【并查集+字典树】poj2513 Colored Sticks

32 篇文章 0 订阅
31 篇文章 0 订阅

http://poj.org/problem?id=2513

分析:形成欧拉通路,即:无向图每个点的度数为偶数或有2个奇数,Trie+并查集

欧拉回路的定义;图G的一个回路,若它恰通过G中每条边一次,则称该回路为欧拉(Euler)回路,具有欧拉回路的图称为欧拉图(简称E图)。

类似:NYOJ42 一笔画问题


#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

const int NM=500010;
int father[NM],indu[NM],k;
struct Node{
	Node *next[26];
	int id;
	Node(){
		for(int i=0;i<26;i++)
			next[i]=NULL;
		id=-1;
	}
};

int Find(int x){
	while(x!=father[x])
		x=father[x];
	return x;
}

int BuildT(Node *pt,char *s){
	int i,t,len;
	len=strlen(s);
	for(i=0;i<len;i++){
		t=s[i]-'a';
		if(pt->next[t]==NULL)
			pt->next[t]=new Node();
		pt=pt->next[t];
	}
	if(pt->id==-1) pt->id=k++;
	return pt->id;
}

int main()
{
	char str1[20],str2[20];
	int cc,i,x,y;
	Node *pt=new Node();
	k=1;
	for(i=1;i<NM;i++){
		father[i]=i;indu[i]=0;
	}
	while(~scanf("%s%s",str1,str2)){
		x=BuildT(pt,str1);
		y=BuildT(pt,str2);
		indu[x]++;indu[y]++;
		x=Find(x);y=Find(y);
		father[y]=x;
	}

	cc=0;
	for(i=1;i<k;i++){  //欧拉函数性质
		if(indu[i]%2!=0) cc++;
	}
	x=Find(1);
	for(i=1;i<k;i++){  //连通性
		if(Find(i)!=x){
			cc=-1;break;
		}
	}
	if(cc==0 || cc==2) printf("Possible\n");
	else printf("Impossible\n");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值