POJ2492 并查集

来源:互联网 发布:易到打车软件 编辑:程序博客网 时间:2024/05/14 11:33

2017年3月16日 | ljfcnyali
题目大意:
有点bt,就是正常昆虫是异性交配,输入一对就代表这一对交配了,让你看这一群昆虫是否有同性恋!
Input:
输入的第一行包含方案数量。每个方案以一行给出错误数量(至少一个,最多2000)和由单个空间分隔的交互数量(最多1000000)开始。在下面的行中,每个交互以两个不同的bug编号的形式给出,由一个空格分隔。错误从一个开始连续编号。
Output:
每个场景的输出是包含”Scenario #i:”的行,其中i是从1开始的场景的编号,后面是一行说”No suspicious bugs found!”如果实验符合他对错误的性行为的假设,或”Suspicious bugs found!”
Sample Input

23 31 22 31 34 21 23 4

Sample Output

Scenario #1:Suspicious bugs found!Scenario #2:No suspicious bugs found!

题目分析:
这道题也就是一道有权值的并查集,需要添加一个权值数组。如果跟它”爸爸”是同性则为0;否则为1。
所以说,这道题也就可以使用简单的并查集A掉了!
陷阱提醒:
此题有一个两个陷阱:
一、数组限制很严格,只可以开到5000
二、注意输出有换行,要换两个行(我就是在这里被坑了很久,POJ显示的是Presentation Error)
代码很简单,如下:

/*************************************************************************    > File Name: POJ2492.cpp    > Author: ljf-cnyali    > Mail: ljfcnyali@gmail.com     > Created Time: 2017/3/16 19:02:47 ************************************************************************/#include<iostream>#include<cstdio>#include<cstdlib>#include<cmath>#include<cstring>#include<algorithm>#include<map>#include<set>#include<vector>#include<queue>using namespace std;#define REP(i, a, b) for(int i = (a), _end_ = (b);i <= _end_; ++ i)#define mem(a) memset((a), 0, sizeof(a))#define str(a) strlen(a)const int maxn = 5005;int n, m;int f[maxn], w[maxn];int cha(int x) {    int t = f[x];    if(t == x)        return x;    f[x] = cha(t);    w[x] = (w[x] + w[t]) % 2;    return f[x];}int main() {#ifndef ONLINE_JUDGE    freopen("input.txt", "r", stdin);    freopen("output.txt", "w", stdout);#endif    int T;    scanf("%d", &T);    REP(j, 1, T) {        mem(f);mem(w);        scanf("%d%d", &n, &m);        REP(i, 0, maxn - 1)            f[i] = i;        int x, y;        bool flag = false;        REP(i, 1, m) {            scanf("%d%d", &x, &y);            int fx = cha(x), fy = cha(y);            if(fx == fy) {                if(w[x] != (w[y] + 1) % 2)                    flag = true;            }            else {                if(fx == fy) continue;                f[fx] = fy;                w[fx] = (w[x] - w[y] + 1) % 2;              }        }        if(flag == true)            printf("Scenario #%d:\nSuspicious bugs found!\n\n", j);        else            printf("Scenario #%d:\nNo suspicious bugs found!\n\n", j);    }    return 0;}

本文转自:http://ljf-cnyali.cn/index.php/archives/28

原创粉丝点击