PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs withk vertices and k - 1 edges, wherek 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 from1 to n. For each Balli 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?
The 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 lengthn, where (1 ≤ pi ≤ n) holds andpi denotes the most distant from Balli 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 acorrect 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 integerm (0 ≤ m < n) — the total number of edges in the forest. Thenm lines should follow. The i-th of them should contain two integers ai andbi and represent an edge between vertices in which relativesai andbi live. For example, the first sample is written as follows:
5 3 1 2 3 4 4 5
You should output the number of trees in the forest where PolandBall lives.
From the technical side, this problem is interactive. However, it should not affect you (except hacking) since there is no interaction.
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个点,接下来N个数,第i个数表示距离点i最远的点的编号,如果有相同距离最远的点,那么这个编号将是最小编号。
问这个图有几棵树。
思路:
很显然,如果对于一个点,其在树上有距离这个点最远的点,那么他两个一定属于一棵树,而非一个孤立点,那么我们将这个点和最远点进行合并,那么我们找到f【i】==i的点就是一棵树的根。
问题就是要统计根的个数啦。
Ac代码:
#include<stdio.h>
#include<string.h>
using namespace std;
int f[100550];
int a[100550];
int find(int a)
{
int r=a;
while(f[r]!=r)
r=f[r];
int i=a;
int j;
while(i!=r)
{
j=f[i];
f[i]=r;
i=j;
}
return r;
}
int merge(int a,int b)
{
int A,B;
A=find(a);
B=find(b);
if(A!=B)
{
f[B]=A;
}
}
int main()
{
int n;
while(~scanf("%d",&n))
{
for(int i=1;i<=n;i++)f[i]=i;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
int output=0;
for(int i=1;i<=n;i++)
{
merge(i,a[i]);
}
for(int i=1;i<=n;i++)
{
if(f[i]==i)output++;
}
printf("%d\n",output);
fflush(stdout);
}
}