Time Limit: 5000MS | Memory Limit: 128000K | |
Total Submissions: 27704 | Accepted: 7336 |
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.
题意:给定若干个棒,棒的两端涂上不同的颜色,问是否能将棒首尾相连且不同棒相接的一端颜色相同;
思路:题意容易理解,但开始完全没思路,经大神指点后,可以用欧拉路的思想;可以把涂颜色的棒的两端看成结点,
把木棒看成边,相同颜色的就是一个结点,要将木棒连成一个直线,也就是“一笔画”问题;
无向图存在欧拉路的充要条件是:
>图是连通的(可以用并查集判断,开始将每个点初始化一棵树,经过输入将有相同祖先的结点合并到一个集合中,
最后任意枚举一个节点,若他们有共同的祖先,说明图是连通的);
>度数为奇数的结点有0个或两个;
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int degree[],set[],id = ; struct node
{
int flag;
int id;
struct node* next[];
};
struct node* root; //开辟新结点
struct node* creat()
{
struct node *p = (struct node*)malloc(sizeof(struct node));
p->flag = ;
for(int i = ; i < ; i++)
p->next[i] = NULL;
return p;
} int find(int x)
{
if(set[x] != x)
set[x] = find(set[x]);//路径压缩;
return set[x];
} //字典树哈希
int Hash(char s[])
{
struct node *p = root;
for(int i = ; s[i]; i++)
{
if(p->next[s[i]-'a'] == NULL)
p->next[s[i]-'a'] = creat();
p = p->next[s[i]-'a'];
}
if(p->flag != )
{
p->flag = ;
p->id = id++;
}
return p->id;
} int check()
{
int sum = ;
int x = find();
for(int i = ; i < id; i++)
if(find(i) != x)//没有共同祖先,图是不连通的,直接返回;
return ;
for(int i = ; i < id; i++)
{
if(degree[i]%)
sum++;
}
if(sum == || sum == )
return ;//图是连通的并且奇度数是0或2,说明有欧拉路;
return ;//图是连通的但奇度数不是0或2也不存在欧拉路;
} int main()
{
memset(degree,,sizeof(degree));
for(int i = ; i <= ; i++)
set[i] = i;//所有节点初始化为一棵树
char s1[],s2[];
int u,v;
root = creat();
while(scanf("%s %s",s1,s2) != EOF)
{
u = Hash(s1);
v = Hash(s2);
degree[u]++;
degree[v]++;
int x = find(u);
int y = find(v);
if(x != y)
set[x] = y;
}
if(check()) printf("Possible\n");
else printf("Impossible\n");
return ;
}