/*Colored Sticks
Time Limit : 10000/5000ms (Java/Other) Memory Limit : 256000/128000K (Java/Other)
Total Submission(s) : 0 Accepted Submission(s) : 0
Problem 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
Source
PKU
*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct Tree
{
bool flag;
int id;
Tree * next[27];
}Tree;
Tree root;
int colorid, colornum, f[500010], color[500010];
int getid(char *s)
{
Tree *p = &root, *q;
int i, j, k;
k = strlen(s);
for(i = 0; i < k; ++i)
{
j = s[i] - 'a';//id
if(p->next[j] == NULL)
{
q = (Tree *)malloc(sizeof(root));
q->flag = false;
for(int l = 0; l < 26; ++l)
q->next[l] = NULL;
p->next[j] = q;
}
p = p->next[j];
if(i == k-1)
break;
}
if(!p->flag)
{
p->flag = true;
p->id = ++colorid;
}
return p->id;
}
int find(int x)
{
if(x != f[x])
f[x] = find(f[x]);
return f[x];
}
bool merge(int x, int y)
{
x = find(x);
y = find(y);
if(x != y)
{
f[x] = y;
return true;
}
return false;
}
int main()
{
char s1[11], s2[11];
int i, j, k;
for(i = 1; i <= 500001; ++i)
f[i] = i;
colorid = 0;
colornum = 0;
memset(color, 0, sizeof(color));
for(i = 0; i < 26; ++i)//字典树根节点初始化
root.next[i] = NULL;
while(scanf("%s%s", s1, s2) != EOF)
{
i = getid(s1);
j = getid(s2);
color[i]++;//保存度数
color[j]++;
if(merge(i, j))//如果合并成功
colornum++;
}
if(colorid == 0)
{
printf("Possible\n");
return 0;
}
if(colornum != colorid-1)//如果不连通
{
printf("Impossible\n");
}
else//连通
{
j = 0;
for(i = 1; i <= colorid; ++i)
{
if(color[i] & 1)//记录奇数度数个数
j++;
}
if(j == 1 || j >= 3)
printf("Impossible\n");
else
printf("Possible\n");
}
return 0;
}
题意:给出一个筷子,筷子的两端都涂有一种颜色,现在给出n根两端都涂有颜色的筷子,当2根筷子的一端具有同种颜色时,两根筷子可以连成一条直线,问这n根筷子是否能连成一条直线。
思路:本题可以将颜色看做是一个节点,筷子看做是边,则题目的要求就类似于,给出n个节点,和m条边,问是否能一笔画走完每一条边一次。这就是欧拉回路,所以根据定义,若是所有的颜色的边的个数全为偶数,或是只有2个颜色的边数为奇数,则可以一笔画走完。现在就要开始模拟这种思想。但是这里还有一个难点就是怎么给颜色字符串编号的问题,如果按照常规的方法必定超时,所以这里又要用到字典树,对颜色进行编号,可以大大提高效率。对每种颜色进行编号的同时可以进行边数的统计,以及并查集的操作,最后用来判断这n种颜色是否能够连通,并且边数是否符合要求,最终判定是否是欧拉回路。
体会:第一做这种综合性的题目,难度好大0.0