码迷,mamicode.com
首页 > 其他好文 > 详细

【转】POJ 2492 A Bug's Life:基础并查集进阶

时间:2015-07-31 01:02:48      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

思路参考这里(较详细)

一开始总是WA调了一晚上原来···Init初始化写在scanf上面了···哎╮(╯▽╰)╭anyway!对并查集的理解更深了一步!

#include<cstdio>
#include<cstring>
using namespace std;
#define Size 2000

struct node
{
        int Pre;
        int Relation;// 与父节点的关系 0同性 1异性
}Bug[Size+1];

 int N, M;
 bool found;

void Init()
{
                for( int i=1; i<=N; i++ )
                {
                        Bug[i].Relation = 0;// 自身与自身性别相同
                        Bug[i].Pre = i;
                }
                found = false;
}

int GetPre( int n )
{
        if( Bug[n].Pre == n )
            return n;

        int t = GetPre( Bug[n].Pre );
        Bug[n].Relation = Bug[n].Relation^Bug[Bug[n].Pre].Relation;
        Bug[n].Pre = t;
        return Bug[n].Pre;
}

void Union( int a, int b )
{
        int Pa = GetPre(a);
        int Pb = GetPre(b);

        if( Pa == Pb ){
                if( Bug[a].Relation == Bug[b].Relation )
                        found = true;
                return;
        }

        Bug[Pa].Pre = Pb;
        Bug[Pa].Relation = ~(Bug[a].Relation^Bug[b].Relation);
}

int main()
{
        int Snr;
      scanf("%d", &Snr);
        int i=1;
        for( i=1; i<=Snr; i++ )
        {
                scanf("%d%d",&N, &M);
                Init();
                while( M-- )
                {
                        int a, b;
                        scanf("%d%d", &a, &b);

                        if(!found)
                            Union(a, b);
                }
                printf("Scenario #%d:\n",i);
                if( found )
                    printf("Suspicious bugs found!\n\n");
                else
                    printf("No suspicious bugs found!\n");
        }
        return 0;
}

  

【转】POJ 2492 A Bug's Life:基础并查集进阶

标签:

原文地址:http://www.cnblogs.com/FightForCMU/p/4690858.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!