poj 2513 Colored Sticks

Colored Sticks
Time Limit: 5000MS Memory Limit: 128000K
Total Submissions: 30933 Accepted: 8151

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.

这道题和单词游戏类似,求一个无向图的欧拉通路或者回路,由于要判断图是否连通,需用并查集,这题节点是字符串,因此查询有点麻烦,这题不可用STL中的map,输入数据量是在太大了,因此我写了个trie。不过庆幸的是poj的内存可以随便开,上亿了都还没超内存。。。


代码:

#include<cstdio>
#include<iostream>
#include<cstring>
#define Maxn 500010
using namespace std;

char s1[20],s2[20];
int fa[Maxn],deg[Maxn];
void init(){
    for(int i=1;i<Maxn;i++)
        fa[i]=i;
}
int findset(int x){
    return fa[x]==x?x:(fa[x]=findset(fa[x]));
}
void unionset(int x,int y){
    x=findset(x),y=findset(y);
    fa[x]=y;
}
int tot=0;
struct trie{
    int ch[Maxn*10][26];
    int v[Maxn*10];
    int sz;
    trie(){sz=0;memset(ch[0],0,sizeof ch[0]);}
    int insert(char *s){
        int u=0;
        for(int i=0;s[i];i++){
            int c=s[i]-'a';
            if(!ch[u][c]){
                ch[u][c]=++sz;
                v[sz]=0;
                memset(ch[sz],0,sizeof(ch[0]));
            }
            u=ch[u][c];
        }
        if(!v[u]) v[u]=++tot;
        return v[u];
    }
}tr;
int main()
{
    int id1,id2,i;
    bool flag=true;
    memset(deg,0,sizeof deg);
    init();
    while(~scanf("%s%s",s1,s2)){
        int id1=tr.insert(s1),id2=tr.insert(s2);
        deg[id1]++,deg[id2]++;
        unionset(id1,id2);
    }
    int in=0;
    flag=true;
    for(i=1;i<=tot;i++){
        if(deg[i]&1) in++;
        if(in>2) {flag=false;break;}
    }
    if(!flag) {puts("Impossible");return 0;}
    int t=findset(1);
    for(i=2;i<=tot;i++)
        if(findset(i)!=t) {flag=false;break;}
    if(flag) puts("Possible");
    else puts("Impossible");
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值