跳到正文

个人记录

6767

yxyxyx_约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年9月5日
收录
2026年9月5日
更新
2026年9月5日
篇幅
约 3 分钟

版本

  1. v1当前
C++
#include<bits/stdc++.h>
#define int long long
#define endl "\n"
using namespace std;

const int N=2e5+5;

int a[N],w[N],p[N],vis[N];
vector<int>q[N];

void dfs(int u)
{
	vis[u]=1;
	for(int i=0;i<q[u].size();i++)
	{
		int v=q[u][i];
		if(vis[v]) continue;
		dfs(v);
	}
	return ;
}
void clean(int n)
{
	for(int i=0;i<=n;i++)
	{
		vis[i]=w[i]=p[i]=0;
		q[i].clear();
	}
	return ;
}
void L6767()
{
	int n;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		int x;
		cin>>x;
		q[x].push_back(i);
		q[i].push_back(x);
		if(p[i]!=x) w[i]++;
		if(p[x]!=i) w[x]++;
		p[i]=x;
		p[x]=i;
	}
	int sum=0,cnt=0,lst=0;
	for(int i=1;i<=n;i++)
	{
		if(vis[i]) continue;
		dfs(i);
		sum++;
	}
	for(int i=1;i<=n;i++)
	{
		if(w[i]==1)
		{
			if(lst!=0)
			{
				q[i].push_back(lst);
				q[lst].push_back(i);
			}
			lst=i;
		}
	}
	for(int i=0;i<=n;i++) vis[i]=0;
	for(int i=1;i<=n;i++)
	{
		if(vis[i]) continue;
		dfs(i);
		cnt++;
	}
	cout<<cnt<<" "<<sum<<endl;
	clean(n);
	return ;
}
signed main()
{
//	freopen("t3.in","r",stdin);
//	freopen("t3.out","w",stdout);
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	int T;
	cin>>T;
	while(T--)
	{
		L6767();
	}
	return 0;
}
/*
10 
6 
2 1 4 3 6 5 
6 
2 3 1 5 6 4 
9 
2 3 2 5 6 5 8 9 8 
2 
2 1 
4 
4 3 2 1 
5 
2 3 4 5 1 
6
5 3 4 1 1 2 
5 
3 5 4 1 2 
6 
6 3 2 5 4 3 
6 
5 1 4 3 4 2
*/
原文