Colored Sticks

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
题意:给定一些棍子,每个棍子的断点有颜色,如果端点颜色相同则可以将棍子连起来,问是否能将棍子连成一条线
题解:欧拉图。欧拉图的条件 1,是连通图。2,奇度定点为0或者2.
采用并查集判断连通图,用一个一位数组统计点的度。用字典树来保存点

#include<stdio.h>

#include<iostream>

#include<malloc.h>

#include<string.h>

using namespace std;

int father[500100];

int tongji[500100];

char s1[15],s2[15];

typedef struct lmx{

       int id;

       lmx *next[26];

}tree;

tree *head;

int cnt;

void init()

{

       int i;

       for(i=1;i<=500100;i++) father[i]=i;

}

int finder(int x)

{

       if(x==father[x]) return x;

       else return father[x]=finder(father[x]);

}

void unioner(int a,int b)

{

       int s1=finder(a);

       int s2=finder(b);

       if(s1==s2) return;

       else father[s1]=s2;

}

tree *make()

{

       tree *p;

       p=(tree*)malloc(sizeof(tree));

       int i;

       p->id=0;

       for(i=0;i<26;i++) p->next[i]=NULL;

       return p;

}

int insert(char *s)

{

       int i,len=strlen(s);

       tree *p=head;

       for(i=0;i<len;i++)

       {

          int temp=s[i]-'a';

          if(p->next[temp]==NULL) p->next[temp]=make();

          p=p->next[temp];

       }

       if(p->id==0) p->id=++cnt;

       return p->id;

}

int main()

{

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

//     freopen("out.txt","w",stdout);

       int i,flag=false;

       cnt=0;

       init();

       memset(tongji,0,sizeof(tongji));

       head=(tree*)malloc(sizeof(tree));

       for(i=0;i<26;i++) head->next[i]=NULL;

       head->id=0;

    while(scanf("%s %s",s1,s2)!=EOF)

       {

              int a=insert(s1);

              int b=insert(s2);

              tongji[a]++;

              tongji[b]++;

              unioner(a,b);

       }

    int temp=finder(1);

       int mm=0;

       for(i=1;i<=cnt;i++)

       {

       if(tongji[i]%2) mm++;

       }

       for(i=2;i<=cnt;i++)

       {

         if(finder(i)!=temp) {flag=true;break;}

       }

       if(flag==false&&(mm==0||mm==2)) printf("Possible\n");

       else printf("Impossible\n");

       return 0;

}

posted @ 2013-09-25 15:33  forevermemory  阅读(299)  评论(0编辑  收藏  举报