pku 2513 Colored Sticks(字典树+并查集)

Colored Sticks
Time Limit: 5000MS Memory Limit: 128000K
Total Submissions: 27266 Accepted: 7211

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.

Source


题意:给n条棍,每条棍2边有颜色,若2条棍的一边颜色相同则可以连起来,问是否能将所有棍连在一起
题解:可以把没种颜色看作一个点,然后这就是一个欧拉路问题(一笔画问题)。用字典树来分配并对应其颜色的下标,用并查集来判是否连通图,然后易知有奇数条边相连的点不能超过2个则存在欧拉路

#include<stdio.h>
#include<string.h>
struct tree{
    int next[26],data;
}tire[1000005];
int v[1000005],cnt[1000005];
int cou=0,cou2=1;
int fin(int x)
{
    if(x==v[x]) return x;
    return v[x]=fin(v[x]);
}
int inter(char *s)
{
    int p=0;

    while(*s)
    {
        if(tire[p].next[*s-'a']==-1)
        {
            tire[p].next[*s-'a']=cou;
            p=cou++;
        }
        else p=tire[p].next[*s-'a'];
        s++;
    }
    if(tire[p].data!=-1) return tire[p].data;
    v[cou2]=cou2;

    return tire[p].data=cou2++;
}
int main()
{
    char a[13],b[13];
    int x,y,i;

    memset(tire,-1,sizeof(tire));
    memset(cnt,0,sizeof(cnt));
    while(scanf("%s%s",a,b)>0)
    {
        x=inter(a),y=inter(b);
        cnt[x]++,cnt[y]++;
        x=fin(x),y=fin(y);
        if(x!=y) v[x]=y;
    }
    x=y=0;
    for(i=1;i<cou2;i++)
    {
        if(cnt[i]&1) x++;
        if(fin(i)==i) y++;
        if(y>1||x>2) break;
    }
    if(y<=1&&x<=2) printf("Possible\n");
    else printf("Impossible\n");

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值