POJ 2513 Colored Sticks

题目链接:http://poj.org/problem?id=2513


题意:有一些木棍,两端染有颜色,问能不能将所有的木棍首尾相连,并且使得每个连接处的位置颜色一致(如果a和b首尾相连,a尾部的颜色和b首部的颜色相同)。现在给出每根木棍首尾的颜色,求解问题。


思路:把每个颜色看做一个点,一根木棍看做两个点之间的边,那么问题就转化为图中是否有欧拉路( 1、 0/2个点的度数为奇数,其余点的度数都为偶数 2、判断图联通(dfs或并查集) )。至于给的两端颜色,如果直接丢进map里面会超时,所以我们用trie树去存一下。


#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <utility>
using namespace std;

#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)

#define Clean(x,y) memset(x,y,sizeof(x))
#define LL long long
#define ULL unsigned long long
const int maxn = 500009;


//************trie
struct trie
{
    trie *next[26];
    int p;
};

void init(trie *x)
{
    x->p = 0;
    rep(i,0,25) x->next[i] = NULL;
}
void insert(trie *x,char s[],int pos)
{
    int len = strlen(s);
    rep(i,0,len-1)
    {
        int index = s[i] - 'a';
        if ( x->next[index] == NULL )
        {
            x->next[index] = new trie;
            init( x->next[index] );
        }
        x = x->next[index];
    }
    x->p = pos;
}

int query(trie *x,char s[])
{
    int len = strlen(s);
    rep(i,0,len-1)
    {
        int index = s[i] - 'a';
        if ( x->next[index] == NULL ) return 0;
        x = x->next[index];
    }
    return x->p;
}
//************trie

int num = 0;   //记录点的个数
int sum = 0;   //记录并查集合并次数
int du[maxn];  //记录每个点的度数
int father[maxn];
char s1[20],s2[20];

//***************并查集
int getfather(int x)
{
    return (x==father[x]?x:father[x] = getfather(father[x]));
}
void unio(int a,int b)
{
    int fa  =getfather(a);
    int fb  =getfather(b);
    if ( fa!=fb )
    {
        sum++; //记录合并次数,如果合并了num-1 次,说明这num个点是联通的
        father[fa] = fb;
    }
}

//***************并查集

trie *root;

int main()
{
    int st,ed;
    Clean(father,0);
    Clean(du,0);
    root = new trie;
    init(root);
    while( (~scanf("%s %s",s1,s2)) )
    {
        getchar();
        if ( !query(root,s1) ) insert(root,s1,++num); //如果这个点不在trie中,就分配一个新的编号
        st = query(root,s1);
        if ( !query(root,s2) ) insert(root,s2,++num);
        ed = query(root,s2);
        if ( !getfather(st) ) father[ st ] = st; //并查集初始化,如果father[x]是0,说明没有用过这个点。
        if ( !getfather(ed) ) father[ ed ] = ed;
        du[st]++;
        du[ed]++;
        unio(st,ed);
    }
    int k = 0; //判断度数为奇数的点的个数
    rep(i,1,num)
            if ( du[i] & 1 ) k++;
     puts( ( ( sum == num-1 && ( k == 0 || k == 2 ) ) || (num == 0) )?"Possible":"Impossible");
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值