Locked Boxes (并查集)

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 T (1 \leq T \leq 30) which is the number of test cases. T test cases follow.


Each test case contains a single integer N (1 \leq N \leq 1,000,000) - 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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值