详解 并查集点击打开链接
PolandBall and Forest
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.
There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.
How many trees are there in the forest?
InputThe first line contains single integer n (1 ≤ n ≤ 104) — the number of Balls living in the forest.
The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id.
It's guaranteed that the sequence p corresponds to some valid forest.
Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format:
In the first line, output the integer n (1 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows:
5 3 1 2 3 4 4 5
Output
You should output the number of trees in the forest where PolandBall lives.
Example
5 2 1 5 3 3
2
1 1
1
In the first sample testcase, possible forest is: 1-2 3-4-5.
There are 2 trees overall.
In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree.
分析:可以用并查集,每一个点与其相距最远的点一定在同一个树上,所以只要将这n个点将同一个树上的点指向同一个根节点就行,最后有多少个点其父节点是其自己说明就有几棵树。
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <set>
#include <map>
using namespace std;
int f[10005];
int Find(int x)
{
if(x==f[x]) return x;
return f[x]=Find(f[x]);
}
int main()
{
int n;
scanf("%d",&n);
for(int i=1; i<=n; i++)
f[i]=i;
int x;
for(int i=1; i<=n; i++)
{
scanf("%d",&x);
int f1=Find(i),f2=Find(x);
if(f1!=f2) f[f2]=f1;
}
int cnt=0;
for(int i=1; i<=n; i++)
if(f[i]==i) cnt++;
printf("%d\n",cnt);
return 0;
}