POJ 2513 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
#include <stdio.h>
#include <iostream>
using namespace std; int id = , par[], degree[] = {}; int find_set(int x)
{
return par[x] != x ? par[x] = find_set(par[x]) : x;
} struct Trie_node
{
int flag, id;
struct Trie_node *next[];
Trie_node()
{
for(int i = ; i < ; i++)
next[i] = NULL;
flag = ;
}
}; int trie_insert(struct Trie_node *p, char s[])
{
for(int i = ; s[i]; i++)
{
if(p->next[s[i]-'a'] == NULL)
p->next[s[i]-'a'] = new Trie_node;
p = p->next[s[i]-'a'];
}
if(p->flag != )
{
p->flag = ;
p->id = ++id;
}
return p->id;
} bool check()
{
int x = find_set();
for(int i = ; i <= id; i++)
{
if(find_set(i) != x)
return ;
}
int degree_odd = ;
for(int i = ; i <= id; i++)
{
if(degree[i] & )
degree_odd++;
}
return (degree_odd == || degree_odd > ) ? : ;
} int main()
{
for(int i = ; i <= ; i++)
par[i] = i;
struct Trie_node *root = new Trie_node;
char s1[], s2[];
while(scanf("%s %s", s1, s2) != EOF)
{
int x = trie_insert(root, s1);
int y = trie_insert(root, s2);
degree[x]++;
degree[y]++;
int fx = find_set(x);
int fy = find_set(y);
if(fx != fy)
par[fx] = fy;
}
printf("%s\n", check() ? "Possible" : "Impossible");
return ;
}
上一篇:XAML 概述一


下一篇:ROS(indigo) turtlebot2 + android一些有趣应用