HDOJ 1829 A Bug's Life (并查集)

来源:互联网 发布:数易生日计算法 编辑:程序博客网 时间:2024/05/16 02:01

A Bug's Life

Time Limit: 15000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1159 Accepted Submission(s): 428 
Problem Description
Background 
Professor Hopper is researching the sexual behavior of a rare species of bugs. He assumes that they feature two different genders and that they only interact with bugs of the opposite gender. In his experiment, individual bugs and their interactions were easy to identify, because numbers were printed on their backs. 

Problem 
Given a list of bug interactions, decide whether the experiment supports his assumption of two genders with no homosexual bugs or if it contains some bug interactions that falsify it.
 
Input
The first line of the input contains the number of scenarios. Each scenario starts with one line giving the number of bugs (at least one, and up to 2000) and the number of interactions (up to 1000000) separated by a single space. In the following lines, each interaction is given in the form of two distinct bug numbers separated by a single space. Bugs are numbered consecutively starting from one.
 
Output

            The output for every scenario is a line containing "Scenario #i:", where i is the number of the scenario starting at 1, followed by one line saying either "No suspicious bugs found!" if the experiment is consistent with his assumption about the bugs' sexual behavior, or "Suspicious bugs found!" if Professor Hopper's assumption is definitely wrong.
 
Sample Input
23 31 22 31 34 21 23 4
 
Sample Output
Scenario #1:Suspicious bugs found!Scenario #2:No suspicious bugs found!
Hint
Huge input,scanf is recommended.
 
 
Source
TUD Programming Contest 2005, Darmstadt, Germany
 
Recommend
linle
 

题意:所给的信息中,是否出现同性恋。

因为所给的信息是两者不是同一组的。

分为两组,0-N为一组,N-n为一组。

如果没有冲突,即x和y为异性。x和y+N为一组,表示他们同性。x+N和y为一组,表示他们同性。


如果给的信息是同一组的,直接合并,就好了。

#include<iostream>  #include<cstdio>  #include<cstring>  #include<algorithm>  #include<cmath>  using namespace std;#define N 2010int father[N*2];int rank1[N*2];int x;int y;void init(int n){for (int i = 0; i < N+n; i++){father[i] = i;rank1[i] = 0;}}int find(int x){if (father[x] == x)return x;else return father[x] = find(father[x]);}void unite(int x, int y){x = find(x);y = find(y);if (x == y)return;if (rank1[x] < rank1[y]){father[x] = y;}else{father[y] = x;if (rank1[x] == rank1[y])rank1[x]++;}}bool same(int x, int y){return find(x) == find(y);}int main(){int t;scanf("%d", &t);int cnt = 0;while (t--){int n, m;scanf("%d%d", &n, &m);init(n);bool flag = true;for (int i = 0; i < m; i++){scanf("%d%d", &x, &y);x--;//因为从1开始y--;if (!flag)continue;if (same(x,y)||same(x+N,y+N)){flag = false;continue;}else{unite(x, y + N);unite(x + N, y);}}cnt++;printf("Scenario #%d:\n",cnt);if (flag)printf("No suspicious bugs found!\n");else printf("Suspicious bugs found!\n");printf("\n");}return 0;}



原创粉丝点击