poj2513 很好的一道题目 并查集+字典树

题意: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;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值