[poj2513]Colored Sticks Trie +并查集 + 欧拉回路判断

第一眼以为要建图去跑,但马上反应过来可以直接判度数就好

除此之外,还要判图是否联通,用并查集解决

最后,对颜色编号,因为在Trie的分类下看到的,所以直接拿红书板子敲了一个

(250000个棍子,5000000个颜色,数组开小WA了一发)

#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <algorithm>

using namespace std;

const int maxn = 500100;

struct Trie
{
	int tot,root,child[maxn][26],cnt;
	int fa[maxn];
	int flag[maxn],p[maxn];
	Trie()
	{
		memset(child[1],0,sizeof(child[1]));
		memset(flag,0,sizeof(flag));
		memset(p,0,sizeof(p));
		root = tot = 1;
		cnt = 0;
	}
	int insert(const char *str)
	{
		int *cur = &root;
		for(const char *pp = str; *pp; pp++)
		{
			cur = &child[*cur][*pp - 'a'];
			if(*cur == 0)
			{
				*cur = ++tot;
				memset(child[tot],0,sizeof(child[tot]));
				flag[tot] = false;
			}
		}
		if(!flag[*cur])
		{
			flag[*cur] = ++cnt;
			fa[cnt] = cnt;
		}
		p[flag[*cur]]++;
		return flag[*cur];
	}
	int getfa(int x)
	{
		if(x == fa[x])
			return x;
		fa[x] = getfa(fa[x]);
		return fa[x];
	}
	void merge(int x,int y)
	{
		int fx = getfa(x);
		int fy = getfa(y);
		fa[fx] = fy;
	}
}trie;
char str1[11],str2[11];
int x,y,father = 0;
bool ans;

int main()
{
	while(~scanf("%s %s",str1,str2))
	{
		x = trie.insert(str1);
		y = trie.insert(str2);
		trie.merge(x,y);
	}
	int cnt = 0;
	for(int i = 1; i <= trie.cnt; i++)
		if(trie.p[i] & 1)
			cnt++;
	if(cnt == 0 || cnt == 2)
		ans = true;
	else
		ans = false;
	for(int i = 1; i <= trie.cnt; i++)
	{
		x = trie.getfa(i);
		if(!father)
			father = x;
		else
		{
			if(father != x)
			{
				ans = false;
				break;
			}
		}
	}
	printf("%s\n",ans ? "Possible" : "Impossible");
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值