POJ2513——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

Hint

Huge input,scanf is recommended.

Source

The UofA Local 2000.10.14


把这些棒子接起来,每条边都经过。接点颜色一样
按颜色作为点建图,相当于问是不是存在一条欧拉通路(而且图要连通)

连通性可以用并查集来判断,每个点的度数的话,用个trie树

PS:一开始用map果断超时到印度去了

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>

using namespace std;

struct node
{
  int num;
  node *next[30];
  node():num(0){memset(next,0,sizeof(next));}
}*root;
int father[500010];
int degree[500010];
int cnt;
void init()
{
  memset(father,-1,sizeof(father));
  memset(degree,0,sizeof(degree));
}

int find(int x)
{
  if(father[x]==-1)
      return x;
  return father[x]=find(father[x]);
}

void merge(int a,int b)
{
  int x=find(a);
  int y=find(b);
  if(x!=y)
    father[x]=y;
}

int insert(char *s)
{
  int pos;
  int len=strlen(s);
  node *p=root,*q;
  for(int i=0;i<len;i++)
  {
    pos=s[i]-'a';
    if(p->next[pos]==0)
    {
      q=new node;
      p->next[pos]=q;
      p=q;
    }
    else
      p=p->next[pos];
  }
  if(p->num==0)
  	p->num=cnt++;
  degree[p->num]++;
  return p->num;
}

void Delete(node *p)
{
  for(int i=0;i<30;i++)
  {
    if(p->next[i]!=0)
      Delete(p->next[i]);
  }
  delete p;
}

int main()
{
  char s1[14],s2[14];
  init();
  root=new node;
  cnt=1;
  while(scanf("%s%s",s1,s2)==2)
  {
	  int n1=insert(s1);
	  int n2=insert(s2);
	  merge(n1,n2);
   }
    int ans=0;
    int odd=0;
    for(int i=1;i<cnt;i++)
    {
   	  if(degree[i]&1)
   	  	odd++;
      if(father[i]==-1)
      {
        ans++;
        if(ans>=2)
          break;
      }
    }
    if(ans>=2)
        printf("Impossible\n");
    else
    {
      if(odd>2 || odd==1)
        printf("Impossible\n");
      else
        printf("Possible\n");
    }
	Delete(root);      
  return 0;
}


你可能感兴趣的:(字典树)