1. 程式人生 > 其它 >CF755C PolandBall and Forest 題解

CF755C PolandBall and Forest 題解

CF755C PolandBall and Forest 題解

Content

給定無向圖的 \(n\) 個點的父親節點,求無向圖的聯通塊個數。

資料範圍:\(1\leqslant n\leqslant 10^4\)

Solution

並查集模板題。

我們將在當前節點和它的父親節點連在一起,然後看不同的祖先節點的個數即可。

沒學過並查集的同學建議先去做 P3367 【模板】並查集

Code

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <iostream>
using namespace std;

int n, a[10007], f[10007], vis[10007], ans;

int getfa(int x) {
	return (x == f[x]) ? x : f[x] = getfa(f[x]);
}
void unionn(int x, int y) {
	x = getfa(x), y = getfa(y);
	if(x != y) f[x] = y;
}

int main() {
	scanf("%d", &n);
	for(int i = 1; i <= n; ++i) f[i] = i;
	for(int i = 1; i <= n; ++i) {
		int x;
		scanf("%d", &x);
		unionn(x, i);
	}
	for(int i = 1; i <= n; ++i)
		if(!vis[getfa(i)]) ans++, vis[getfa(i)] = 1;
	printf("%d", ans);
	return 0;
}