Colored Sticks(poj 2513) (字典树+欧拉回路+并查集)

Time limit

5000 ms

Memory limit

128000 kB

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.

题意:是否存在欧拉回路。一个无向图存在欧拉回路,当且仅当该图所有顶点度数都为偶数,且该图是连通图。判断是否连通,用并查集。由于单词量大,map建立单词索引会T,可以采用字典树。

#include<bits/stdc++.h>
using namespace std;
const int maxn=5e5;
int color=0,degree[maxn+1]={0},fa[maxn+1];
struct node
{
    bool flag;
    int id;
    node* next[27];
    node()
    {
        flag=false;
        id=0;
        memset(next,0,sizeof(next));
    }
}root;
int Find(int x)
{
    while(x!=fa[x]) x=fa[x];
    return x;
}
void mer(int a,int b)
{
    int pa=Find(a);
    int pb=Find(b);
    fa[pb]=pa;
}
int Hash(char *s)
{
    node* p=&root;
    int len=0;
    while(s[len]!='\0')
    {
        int index=s[len++]-'a';
        if(!p->next[index]) p->next[index]=new node;
        p=p->next[index];
    }
    if(p->flag) return p->id;
    else
    {
        p->flag=true;
        p->id=++color;
        return p->id;
    }
}
int main()
{
    char a[11],b[11];
    for(int i=1;i<=maxn;i++) fa[i]=i;
    while(~scanf("%s%s",a,b))
    {
        int i=Hash(a);
        int j=Hash(b);
        degree[i]++;
        degree[j]++;
        mer(i,j);
    }
    int Root=Find(1);
    int cnt=0;
    for(int i=1;i<=color;i++)
    {
        if(degree[i]&1) cnt++;
        if(cnt>2||Find(i)!=Root)
        {
            printf("Impossible\n");
            return 0;
        }
    }
    printf("%s\n",cnt==1?"Impossible":"Possible");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值