poj 2513 Colored Sticks(trie+并查集+欧拉通路)

Colored Sticks
Time Limit: 5000MS Memory Limit: 128000K
Total Submissions: 30391 Accepted: 8031

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


题意:给定一些木棒,木棒两端都有颜色,不同木棒能够相接的条件是相接的两端颜色要相同。问所给出的木棒是否可以全都首尾相接,连成一条直线。

分析:要想能够依次相连,每个颜色出现的次数尽量都是偶数较好(至少要前一根上出现一次,后一根上出现一次才可以首尾相连),若是奇数也是可能的,出现在最终的构成的直线上的第一根木棍或是最后一根木棍上是可以的。所以,将出现的颜色都插入字典树中,每一次沿着字母顺序发现颜色是相同的就累加出现的次数,输完也就统计完了。判断一下是否构成欧拉回路即可了~

本来以为这样子就好了。后来发现还是不行的,因为若是一根木棍上两端颜色是一样的,这样统计起来虽然是偶数,但这根仍旧无法插入进去。(或者还有其他情况我没想到的。。反正就是光这样子做还不行。)还是要用到并查集的。出现在一根木棒上的颜色可以放到一个集合中,保证首尾相连的可能性,最终若是所有颜色不同时在一个集合中,就是不可联通的情况,是impossible。

最终判断的输出条件:

POSSIBLE:  奇度数结点个数==0 或 ==2  且  图连通(只有一个根节点)

IMPOSSIBLE:奇度数结点个数==1 或 >=3  或  图不连通(有多个根节点)


#include 
   
   
    
    
#include 
    
    
     
     
#include 
     
     
      
      
#include 
      
      
       
       
using namespace std;

int fa[500010],sum[500010];

int find(int x)
{
	if(x==fa[x])
	{
		return x;
	}
	int t=fa[x];
	fa[x]=find(fa[x]);
	return fa[x];
}

struct trie{
	int next[26];
	int end;
}tree[1000010];/*字典树应该开到2500000*10这么大,但是太大会MLE。
                 于是选择一个不会RE(开的太小会数组越界)
                 以满足条件,且不会MLE的。*/

int cnt,flag;

int insert(char *s,int now)
{
	for(;*s;s++)
	{
		int p=*s-'a';
		if(tree[now].next[p]==0)
		{
			tree[now].next[p]=cnt++;
		}
		now=tree[now].next[p];
	}
	if(tree[now].end==0)        // 每到单词结尾的时候判断一下是否出现过这个单词。
	{
		tree[now].end=flag++; // flag相当于一个标号。没出现过的给一个新的大的标号。出现过则返回其之前给的那个标号。
	}
	return tree[now].end;  // 返回标号。
}

int main()
{
	char a[12],b[12];
	for(int i=0;i<500010;i++)
	{
		fa[i]=i;
	}
	flag=1;
	cnt=2;
	while(scanf("%s%s",a,b)!=EOF)
	{
		int x=insert(a,1);//插入单词,并返回得到这个颜色的标号。
		int y=insert(b,1);
		sum[x]++; //统计单词出现的次数。每来一次就加一。
		sum[y]++;
		int fx=find(x);//查找根节点,看是否在一个集合中
		int fy=find(y);
		if(fx!=fy)
		{
			fa[fx]=fy;//不在一个集合里就合并两个集合。
		}
	}
	int num=0,odd=0;
	int ttt=1;
	for(int i=1;i
       
       
         =2 && ttt) //刚开始写的时候居然没有写&&ttt,于是OLE了!!!还一直找不到问题。。 { //如果不写&&ttt,在发现这个之后break也可以。 printf("Impossible\n"); ttt=0; } } } if(ttt) { for(int i=1;i 
         
       
      
      
     
     
    
    
   
   

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值