Poj 2513 Colored Sticks(字典树+欧拉回路)

Colored Sticks
Time Limit: 5000MS Memory Limit: 128000K
Total Submissions: 31553 Accepted: 8339

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.

题意:

给定一些木棒,木棒两端都涂上颜色,求是否能将木棒首尾相接,连成一条直线,要求不同木棒相接的一边必须是相同颜色的


#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

struct node{
    int flag;
    int no;
    node *next[26];
}*head;

int degree[250050];
int bin[150050];
int color;

int Search(char *s){
    node *p=head;
    node *q;
    int i=0;

    while(s[i]!='\0'){
        if(p->next[ s[i]-'a' ]==NULL){
            q=new node;
            for(int j=0;j<26;j++){
                q->next[j]=NULL;
            }
            q->flag=0;
            q->no=0;

            p->next[ s[i]-'a' ]=q;
        }
        p=p->next[ s[i]-'a' ];
        i++;

    }
    if(p->flag)
        return p->no;
    else{
        p->flag=1;
        p->no=color++;
        return p->no;
    }

}

int Find(int x){
    if(bin[x]==-1){
        return x;
    }
    return x==bin[x]?x:Find(bin[x]);
}

void Merge(int x,int y){
    int f1,f2;
    f1=Find(x);
    f2=Find(y);
    if(f1!=f2)
        bin[f1]=f2;
}

int main(){
    char str1[15],str2[15];

    memset(degree,0,sizeof(degree));
    memset(bin,-1,sizeof(bin));

    head=new node;
    for(int i=0;i<26;i++){
        head->next[i]=NULL;
    }
    head->flag=0;
    head->no=0;

    color=0;

    while(scanf("%s%s",str1,str2)!=EOF){
        int x=Search(str1);
        int y=Search(str2);

        degree[x]++;
        degree[y]++;

        Merge(x,y);

    }

    int odd=0,null=0;
    int i;

    for(i=0;i<color;i++){
        if(degree[i]%2)
            odd++;
        if(bin[i]==-1)
            null++;
        if(odd==3)
            break;
        if(null==2)
            break;
    }

    if(i==color)
        cout<<"Possible"<<endl;
    else
        cout<<"Impossible"<<endl;

    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值