poj 2513 Colored Sticks 字典树 并查集

染色的树枝能否 相同颜色边连接成一个 欧拉回路

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <iostream>
using namespace std;
#define MAXN 5000050
struct node
{
    int num;
    node *next[26];
};
node *root,tree[MAXN];
int tot,totn=0;
int deg[MAXN];  //度数
int father[MAXN];
void init()
{
    for(int i=0;i<=MAXN;i++)
    {father[i]=i;deg[i]=0;}
    tot=0;
}
node* creat()
{
    node *temp=&tree[totn++];
    for(int i=0;i<26;i++)
    {
        temp->next[i]=NULL;
    }
    return temp;
};
void insert(char *str,int x)
{

    node *location = root;
    for(int i=0;str[i]!='\0';i++)
    {
        int num = str[i] - 'a';
        if(location->next[num] == NULL)
        {
            location->next[num] = creat();
        }
        location = location->next[num];
    }
    location->num=x;
}
int search(char *str)
{
    node *location = root;
    for(int i=0;str[i]!='\0';i++)
    {
        int num = str[i] - 'a';
        if(location->next[num] == NULL)
            return 0;
        location = location->next[num];
    }
    return location->num;
}
int find(int x)
{
    if(x != father[x])
    {
        return father[x] = find(father[x]);
    }
    return x;
}
bool judge()
{
    int odd=0,rot;
    for(int i=1;i<=tot;i++)
        if(deg[i]%2==1)odd++;
    if(odd!=0&&odd!=2)return false;
    rot=find(1);
    for(int i=2;i<=tot;i++)
        if(rot!=find(i))return false;
    return true;
}
int main()
{
    int x,y,fx,fy;
    char s1[12],s2[12];
    init();
    root=creat();
    while(scanf("%s %s",s1,s2)!=EOF)
    {

         x=search(s1);
         y=search(s2);
        if(x==0)insert(s1,x=++tot);
        if(y==0)insert(s2,y=++tot);
        deg[x]++;
        deg[y]++;
         fx=find(x);
         fy=find(y);
        if(fx!=fy)father[fx]=fy;
    }
    if(judge())printf("Possible\n");
    else printf("Impossible\n");

    return 0;
}
posted @ 2012-11-04 16:24  TO_Asia  阅读(122)  评论(0编辑  收藏  举报