1. 程式人生 > >POJ-1611-The Suspects

POJ-1611-The Suspects

一個 map i++ cpp stream poj 可能 sta get

鏈接:https://vjudge.net/problem/POJ-1611#author=SCU2018

題意:

警察抓販毒集團。有不同類型的犯罪集團,人員可能重復,集團內的人會相互接觸。現在警察在其中一人(0號)身上搜出毒品,認為與這個人直接接觸或通過其他人有間接接觸的人都是嫌疑犯。問包括0號犯人共有多少嫌疑犯?

思路:

並查集模板,在組內進行操作,先將每組第一個設為隊首,當找父親找到的為0時,

優先將0作為父親,這樣與0有間接和直接接觸的人父親都為0,

最後遍歷一遍每個點的父親就好。

代碼:

#include <iostream>
#include <memory.h>
#include <string>
#include <istream>
#include <sstream>
#include <vector>
#include <stack>
#include <algorithm>
#include <map>
#include <queue>
#include <math.h>
using namespace std;
const int MAXN = 30000+10;
int n,m;
int Father[MAXN];
int a[MAXN];

int Get_F(int x)
{
    return Father[x] = Father[x] == x ? x:Get_F(Father[x]);
}

int main()
{
    while (cin >> n >> m && n)
    {
        for (int i = 0;i<n;i++)
            Father[i] = i;
        int num;
        for (int i = 1;i<=m;i++)
        {
            cin >> num;
            for (int j = 0;j < num;j++)
                cin >> a[j];
            //sort(a,a+num);
            int f = Get_F(a[0]);
            for (int j = 1;j < num;j++)
            {
                int now = Get_F(a[j]);
                if (f != now && now != 0)
                {
                    Father[now] = f;
                }
                else if (f != now && now == 0)
                {
                    Father[f] = now;
                }
            }
        }

        int sum = 0;
        for (int i = 0;i<n;i++)
            if (Get_F(i) == 0)
                sum++;
        cout << sum << endl;
    }

    return 0;
}

  

POJ-1611-The Suspects