本文主要是介绍POJ 1611 The Suspects,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
并查集的同时记录这个集合里面的元素个数。用cnt来表示,初始时cnt[i] = 1;{ 0<= i <= n}.当合并的时候,假设x向y合并, 则需要cnt[y] += cnt[x]
/************************************************ Author: fisty* Created Time: 2015/2/26 19:13:23* File Name : B.cpp*********************************************** */
#include <iostream>
#include <cstring>
#include <deque>
#include <cmath>
#include <queue>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <string>
#include <vector>
#include <cstdio>
#include <bitset>
#include <algorithm>
using namespace std;
#define Debug(x) cout << #x << " " << x <<endl
#define Memset(x, a) memset(x, a, sizeof(x))
const int INF = 0x3f3f3f3f;
typedef long long LL;
typedef pair<int, int> P;
#define FOR(i, a, b) for(int i = a;i < b; i++)
#define MAX_N 31000
int n, m;
int par[MAX_N],cnt[MAX_N];
void init(){for(int i = 0;i < n; i++){par[i] = i;cnt[i] = 1;}
}
int find(int x){return x == par[x] ? x : par[x] = find(par[x]);
}
void unio(int x, int y){x = find(x);y = find(y);if(x != y) {par[x] = y;cnt[y] += cnt[x];}
}
int main() {//freopen("in.cpp", "r", stdin);cin.tie(0);ios::sync_with_stdio(false);while(cin >> n >> m){ if(!n && !m) break;Memset(par, 0);Memset(cnt, 0);init();for(int i = 0;i < m; i++){int k;int arr[MAX_N];Memset(arr, 0);cin >> k;FOR(j, 0, k){cin >> arr[j];}for(int j = 1;j < k; j++){unio(arr[0], arr[j]);}}cout << cnt[find(0)] << endl;}return 0;
}
这篇关于POJ 1611 The Suspects的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!