Judge Info
- Memory Limit: 32768KB
- Case Time Limit: 10000MS
- Time Limit: 10000MS
- Judger: Number Only Judger
Description
Poseidon has N boxes with lock. What's inside the box? (hum..., think by yourself) Each box can either be opened with its corresponding key or smashed. Poseidon has put the keys in some of the boxes. He remembers which key has been placed in which box. Poseidon wants to access to all of the boxes. However, he wants to destroy as few of them as possible. Please write a Program to help Poseidon to determine how many boxes have to be smashed.
Input
The input will contains multiple test cases. The first line of the input is a single integer which is the number of test cases. T test cases follow.
Each test case contains a single integer - this is the number of boxes owned by Poseidon. The boxes (as well as their corresponding keys) are numbered from 1 to N. Next, there are N lines: the i+1st line contains a single integer - the number of the box which the ith key has been placed in.
Output
For each input test case, you are to output a single integer - the minimal number of boxes to be smashed in order to access to all of the boxes.
Sample Input
2 4 2 1 2 4 4 2 1 2 4
Sample Output
2 2
用户输入4接下来就有四个数字代表,第1个箱子的钥匙在第2个箱子里,第2个箱子的钥匙在第一个箱子里····
用并查集折腾一下就可以找出最少需要开几个箱子了
#include<stdio.h>
int father[1000050];
int mfind(int a)
{
return father[a]==a ? a:mfind(father[a]);
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
int a;
scanf("%d",&n);
for(int i=1;i<=n;i++)
father[i]=i;
for(int i=1;i<=n;i++)
{
scanf("%d",&a);
if(mfind(i)!=mfind(a))
father[mfind(i)]=father[mfind(a)];
}
int sum=0;
for(int i=1;i<=n;i++)
{
if(father[i]==i)
sum++;
}
printf("%d\n",sum);
}
return 0;
}