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
题解:就是判断欧拉回路。这是无向图。一个欧拉回路每条边经过一次,那么依次把边拉直,刚好就是一根直线(半欧拉回路)。判断欧拉回路需要在连通图的条件下判断度数是基数的个数。为0是欧拉回路,2是半欧拉回路。判断是否联通肯定就是用并查集了。此题用map超时。所以需要用字典树为每个字符串一个编号。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <map>
using namespace std;
struct Node
{
int num;
Node* next[26];
Node()
{
num = 0;
for(int i = 0;i < 26;i++)
{
next[i] = NULL;
}
}
};
Node* root;
int degree[3000006];
int pre[3000006];
int k = 1;
int insert(char* s)
{
int len = strlen(s);
Node* p = root;
for(int i = 0;i < len;i++)
{
int x = s[i] - 'a';
if(p->next[x] == NULL)
{
Node* q = new Node();
p->next[x] = q;
}
p = p->next[x];
}
if(p->num == 0)
{
p->num = k++;
}
degree[p->num]++;
return p->num;
}
int find(int x)
{
return x == pre[x] ? x : pre[x] = find(pre[x]);
}
int main()
{
char s1[100];
char s2[100];
root = new Node();
memset(degree,0,sizeof(degree));
for(int i = 1;i <= 250000;i++)
{
pre[i] = i;
}
while(scanf("%s%s",s1,s2) != EOF)
{
int x = insert(s1);
int y = insert(s2);
x = find(x);
y = find(y);
pre[x] = y;
}
int x = find(1);
for(int i = 1;i < k;i++)
{
if(x != find(pre[i]))
{
printf("Impossible\n");
return 0;
}
}
int cnt = 0;
for(int i = 1;i < k;i++)
{
//cout<<degree[i]<<endl;
if((degree[i] & 1) != 0)
{
cnt++;
}
}
if(cnt == 0 || cnt == 2)
{
printf("Possible\n");
}
else
{
printf("Impossible\n");
}
return 0;
}