显示代码纯文本
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
//1.拓扑序找环,减去
//2.tarjan求强连通分量找环,减去(本代码)
//由题知,在一个环中只有一个权值会被浪费,贪心求每个强连通分量中最小,总数减去即为答案
const int N = 1e5+10;
ll n,ans;
ll a[N];//原数组
struct made{
int ver,nx;
}e[N];
int hd[N],tot,cnt,top,num;
int dfn[N],low[N],st[N],color[N];
ll mi[N],size[N];//m为第i个强连通分量最小值
bool v[N];
void add(int x,int y){
tot++;
e[tot].ver = y,e[tot].nx = hd[x],hd[x] = tot;
}
void tarjan(int x){
low[x] = dfn[x] = ++cnt;
st[++top] = x,v[x] = 1;
for(int i = hd[x];i;i = e[i].nx){
int y = e[i].ver;
if(!dfn[y])tarjan(y),low[x] = min(low[x],low[y]);
else if(v[y])low[x] = min(low[x],dfn[y]);
}
if(low[x] == dfn[x]){
num++;int y;
mi[num] = 1e9+10;//原最大,开大点!!!!
do{
y = st[top--];color[y] = num;
v[y] = 0;
mi[num] = min(mi[num],a[y]),size[num]++;
}while(x != y);
}
}
int main(){
freopen("prob1_silver_22open.in","r",stdin);
freopen("prob1_silver_22open.out","w",stdout);
scanf("%lld",&n);
for(int i = 1;i <= n;i++){
int x;
scanf("%d%lld",&x,&a[i]);
add(i,x);
ans += a[i];//全部
}
for(int i = 1;i <= n;i++)
if(!color[i])tarjan(i);
for(int i = 1;i <= num;i++)
if(size[i] > 1)ans -= mi[i];//减去,强连通分量中为大小为1的不用减!
printf("%lld\n",ans);
return 0;
}