poj 字符串相关之2513 Colored Sticks

poj 字符串相关之2513 Colored Sticks
方法:Trie树+并查集+欧拉回路相关知识(度为0/2)
Accepted 73336K 1344MS

#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
//#include<math.h>
#include<algorithm>
#include<vector>
#include<map>
#define MAXNUM 500020
#define LL long long
using namespace std;
int n, degree[MAXNUM], Pre[MAXNUM];
class node
{
public:
    int idx;
    node* next[26];
    node()
    {
        idx = -1;
        for (int i = 0; i < 26; i++)
            next[i] = NULL;
    }
};
class Trie
{
public:
    node* root;
    Trie()
    {
        root = new node();
    }
    int Find(char * s)
    {
        int i, len, tmp;
        node * cur;
        cur = root;
        len = strlen(s);

        for (i = 0; i < len; i++)
        {
            tmp = s[i] - 'a';
            if (cur->next[tmp] == NULL)
                cur->next[tmp] = new node();
            cur = cur->next[tmp];
        }
        if (cur->idx == -1)
        {
            cur->idx = n++;
        }
        return cur->idx;            
    }   
};
int find(int x)
{
    while (Pre[x] != x) x = Pre[x];
    return x;
}
void Union(int i, int j)
{
    int a, b;
    a = find(i);
    b = find(j);
    if (a != b)
        Pre[b] = a;
}
int main(void)
{
    //freopen("1.txt", "r", stdin);
    int i, j, k, count;
    char str1[20], str2[20];
    Trie tree;
    n = 1;
    memset(degree, 0, sizeof(degree));
    for (k = 1; k < MAXNUM; k++)
        Pre[k] = k;
    while (scanf("%s%s", str1, str2) != EOF)
    {
        i = tree.Find(str1);
        j = tree.Find(str2);
        degree[i]++;
        degree[j]++;
        Union(i, j);
    }
    //检查度
    count = 0;
    for (i = 1; i < n; i++)
    {
        if (degree[i] % 2 == 1)
            count++;
    }
    if (count != 2 && count != 0)
    {
        printf("Impossible\n");
        return 0;
    }
    //检查连通性
    k = find(1);
    for (i = 2; i < n; i++)
    {
        if (find(i) != k)
        { 
            printf("Impossible\n");
            return 0;
        }
    }
    printf("Possible\n");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值