poj 2513 Colored Sticks

http://poj.org/problem?id=2513

字典树+并查集+欧拉路

代码:

#include<iostream>

#include<cmath>

#include<cstdio>

#include<string>

#include<cstring>

#include<vector>

#include<stack>

#include<queue>

#include<map>

#include<set>

#include<algorithm>



#define long long LL



using namespace std;

const int INF=0x3f3f3f3f;

const int KC=26;

const int N=1000005;

int f[N];

int num[N];

struct node

{

    int k;

    struct node *next[KC];

}*root;

int value;

int fx(int x)

{

    if(f[x]!=x)

    f[x]=fx(f[x]);

    return f[x];

}

void ufsMerge(int l,int r)

{

    int L=fx(l);

    int R=fx(r);

    if(L!=R)

    f[L]=R;

}

int add(struct node *p,char s[],int n)

{

    struct node *t;

    for(int i=0;i<n;++i)

    {

        if(p->next[s[i]-'a']==NULL)

        {

            t=new node;

            t->k=-1;

            for(int j=0;j<KC;++j)

            t->next[j]=NULL;

            p->next[s[i]-'a']=t;

        }

        p=p->next[s[i]-'a'];

    }

    if(p->k==-1)

    p->k=value++;

    return p->k;

}



int main()

{

    //freopen("data.in","r",stdin);

    root=new node;

    root->k=-1;

    for(int i=0;i<KC;++i)

    root->next[i]=NULL;

    value=0;

    for(int i=0;i<N;++i)

    f[i]=i;

    memset(num,0,sizeof(num));

    char a[KC],b[KC];

    while(scanf("%s ",a)!=EOF)

    {//puts(a);

        scanf("%s ",b);

        int l=add(root,a,strlen(a));

        int r=add(root,b,strlen(b));

        //cout<<l<<" "<<r<<endl;

        ++num[l];

        ++num[r];

        ufsMerge(l,r);//cout<<l<<" "<<r<<endl;

    }

    int odd=0,oven=0;

    bool flag=true;

    for(int i=0;i<value;++i)

    {//cout<<f[i]<<endl;

        if(i>0&&fx(i)!=fx(i-1))

        {flag=false;break;}

        if((num[i]&1))

        ++odd;

        else

        ++oven;

    }

    if((odd==0||odd==2)&&flag==true)

    printf("Possible");

    else

    printf("Impossible");

    return 0;

}

  

你可能感兴趣的:(color)