题意: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? 给你n条目棒 每条木棒端点有颜色 如果每两条端点的颜色相同 那么 这两个木棒可以连接成一个 最后问 给你的木棒 最后是否可以连接成一根。
思路:把每个木棒看成一条有端点的线段 且 每条线段又是独立的 判断是否这些线段可以连接在一起 端点的每种颜色必须为偶数 只有这样才可以匹配
同时他们必须有公共的祖先,联通。这样才满足条件
#include<stdio.h>
#include<string.h>
#define max 5000000
struct node
{
bool isLeaf;
int key;
struct node *next[26];
} Node,Root[max];
int step=0;
int color[max];
int far[max];
int color_cnt=1;
void Set()//利用并查集
{
for(int i=1;i<=max;i++)
far[i]=i;
}
int find(int x)//路径压缩
{
if(far[x]!=x)
far[x]=find(far[x]);
return far[x];
}
void unionSet(int a, int b)
{
int pa,pb;
pa=find(a);
pb=find(b);
far[pb]=pa;
}
int BuildTree(char *word)//建立字典树 判断颜色的奇偶性和木棒独立的个数
{
node *p=&Node, *temp;
while(*word)
{
if(p->next[*word-'a']==NULL)
{
Root[step].isLeaf=false;
Root[step].key=1;
p->next[*word-'a']=&Root[step++];
}
p=p->next[*word-'a'];
word++;
}
if(p->isLeaf)//判断该单词是不是存在
return p->key;
p->isLeaf=true;
p->key=color_cnt;
color_cnt++;
return p->key;
}
int main()
{
char str1[15], str2[15];
int a,b;
int m=0;
int pa;
int num=0;
Set();
while(scanf("%s%s",str1, str2)!=EOF)
{
a=BuildTree(str1);
b=BuildTree(str2);
color[a]++;
color[b]++;
unionSet(a,b);
// num++;
// if(num==5) break;
}
for(int i=1; i<color_cnt; i++)//判断两个节点是否出现了偶数次
{
if(color[i]%2!=0)
m++;
}
pa=find(1);
for(int i=2; i<color_cnt; i++)//判断是否连通。
{
if(pa!=find(i))
{
m=-1;
break;
}
}
if(m == 2 || m == 0)//判断两边颜色是否一样,一样时为0,不一样为2;
printf("Possible\n");
else
printf("Impossible\n");
return 0;
}