并查集水题
不知道为什么是绿题,这题顶多橙题吧。。。
直接用并查集求连通块即可。
\(Code:\)
#pragma GCC diagnostic error "-std=c++11"
#include <cstdio>
#include <iostream>
using namespace std;
template <class T>void r(T &a)
{
T s=0,w=1;a=0;char ch=getc(stdin);
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getc(stdin);}
while(ch>='0'&&ch<='9'){s=s*10+ch-'0';ch=getc(stdin);}
a=w*s;
}
template <class T,class... Y>void r(T& t,Y&... a){r(t);r(a...);}
struct bcj
{
int father[1000010];
void start(int n)
{for(int i=1;i<=n;i++)father[i]=i;}
int find(int x)
{if(father[x]!=x)father[x]=find(father[x]);return father[x];}
void unionn(int x,int y)
{x=find(x);y=find(y);if(x!=y)father[y]=x;}
bool judge(int x,int y)
{if(find(x)==find(y))return true;return false;}
};
int main()
{
bcj uf;
int n,ans=0;
r(n);
uf.start(n);
for(int i=1;i<=n;i++)
{
int a;
r(a);
uf.unionn(i,a);
}
for(int i=1;i<=n;i++)
if(uf.father[i]==i)ans++;
cout<<ans;
return 0;
}