poj2492 A Bug's Life —— 并查集

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaohaibo_/article/details/80330925

A Bug’s Life

Time Limit: 10000MS Memory Limit: 65536K
Total Submissions: 41804 Accepted: 13576

- 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

2
3 3 //虫子个数和交配数
1 2
2 3
1 3

4 2
1 2
3 4
  • Sample Output
Scenario #1:
Suspicious bugs found!

Scenario #2:
No suspicious bugs found!

Hint

Huge input,scanf is recommended.

WA????

#include <iostream>
#include <map>
#include <iterator>
#include <algorithm>
#include <vector>
#include <queue>
#include <list>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <sstream>
#define INF 1e6
#define maxn 1e6
using namespace std;

struct DisjointSet{
    vector<int> father;
    DisjointSet(int n):father(n+1){
        for(int i=1;i<=n;i++){
            father[i] = i;
        }
    }

    int find(int v){
        return father[v] = father[v]==v?v:find(father[v]);
    }

    void merge(int x,int y){
        int a=find(x),b=find(y);
        if(a!=b){
            father[b] = a;
        }
    }
};
int main(){
    int N,num = 0;
    cin>>N;
    while(N--){
        num++;
        int n,m,a,b,sum=0;//n是虫子个数,m是交配次数
        cin>>n>>m;
        DisjointSet dis1(n);
        for(int i=0;i<m;i++){
            cin>>a>>b;
            dis1.merge(a,b);
        }
        for(int i=1;i<=n;i++){
            if(dis1.father[i]==i){
                sum++;
            }
        }
        if(sum==1)
            cout<<"Scenario #"<<num<<":\nSuspicious bugs found!\n";
        else
            cout<<"Scenario #"<<num<<":\nNo suspicious bugs found!\n";
    }

}

阅读更多
想对作者说点什么?
相关热词

博主推荐

换一批

没有更多推荐了,返回首页