POJ - Colored Sticks - 并查集+字典树

这道题主要还是要判断是不是欧拉图

说白了就是能不能这幅图能不能用一笔画下来,那么就可以知道了,如果是一个环状的,说明奇数度就不存在,否则就只能用两个奇数度(起点终点)//我的理解这是

只需要用字典树将单词变为对应的一个数字,然后并查集操作就可以,需要维护一个度变量

#include<stdio.h>
#include<string.h>
int du[500010],p[500010];
int tot=1;
struct tree
{
	tree *next[30];
	int id;
	tree()
	{
		id=0;
		for(int i=0;i<30;i++)
		{
			next[i]=NULL;
		}
	}
}*root;
int find(int n)
{
	if(p[n]!=n)
	{
		p[n]=find(p[n]);
	}
	return p[n];
}
int set(char *s)
{
	tree *tmp;
	tmp=root;
	for(int i=0;s[i];i++)
	{
		int j=s[i]-'a';
		if(tmp->next[j]==NULL)
		{
			tmp->next[j]=new tree;
		}
		tmp=tmp->next[j];
	}
	if(tmp->id==0)
	{
		return tmp->id=tot++;
	}
	return tmp->id;
}
int main()
{
	root=new tree;
	char color1[50],color2[50];
	int i;
	for(int i=0;i<500010;i++)
	{
		p[i]=i;
		du[i]=0;
	}
	while(scanf("%s%s",color1,color2)!=EOF)
	{
		int c1=set(color1);
		int c2=set(color2);
		du[c1]++;
		du[c2]++;
		int C1=find(c1);
		int C2=find(c2);
		p[C1]=C2;
	}
	int rnum=0,onum=0;
	for(i=1;i<tot;i++)
	{
		if(p[i]==i)
		{
			rnum++;
		}
		if(rnum>1)
		{
			puts("Impossible");
			return 0;
		}
	}
	for(i=1;i<tot;i++)
	{
		if(du[i]&1)
		{
			onum++;
		}
	}
	if(onum==0||onum==2)
	{
		puts("Possible");
	}
	else
	{
		puts("Impossible");
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值