题目链接
思路:只要求一下每个环上的点的最小值就行了,用并查集维护连通块。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2e5+5 ;
int a[maxn],father[maxn];
int findfather(int x)
{
if(x==father[x]) return x;
int i=findfather(father[x]);
a[x]=min(a[x],a[father[x]]);
return father[x]=i;
}
void unit(int x,int y)
{
int aa=findfather(x),b=findfather(y);
if(aa!=b) father[aa]=b;
a[x]=min(a[x],a[y]);
}
int main()
{
int n,t,ans=0;
scanf("%d",&n);
for(int i=1;i<=n;++i) scanf("%d",&a[i]),father[i]=i;
for(int i=1;i<=n;++i) scanf("%d",&t),unit(i,t);
for(int i=1;i<=n;++i)
if(father[i]==i) ans+=a[i];
printf("%d\n",ans);
}