记录编号 583450 评测结果 AWWWWWWWWWW
题目名称 3810.[USACO22 Open Silver]Visits 最终得分 9
用户昵称 ┭┮﹏┭┮ 是否通过 未通过
代码语言 C++ 运行时间 0.182 s
提交时间 2023-10-14 16:52:53 内存使用 0.00 MiB
显示代码纯文本
#include <bits/stdc++.h> 
using namespace std;
//1.拓扑序找环,减去
//2.tarjan求强连通分量找环,减去(本代码)
//由题知,在一个环中只有一个权值会被浪费,贪心求每个强连通分量中最小,总数减去即为答案 
const int N = 1e5+10; 
int n,ans; 
int a[N];//原数组 
struct made{
    int ver,nx;
}e[N];
int hd[N],tot,cnt,top,num;
int dfn[N],low[N],st[N],mi[N],color[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;
        do{
            y = st[top--];color[y] = num;
            v[y] = 0,mi[num] = min(mi[num],a[x]);
        }while(x != y);
    }
}
int main(){
    freopen("prob1_silver_22open.in","r",stdin);
    freopen("prob1_silver_22open.out","w",stdout);
    scanf("%d",&n);
    for(int i = 1;i <= n;i++){
        int x;
        scanf("%d%d",&x,&a[i]);
        add(i,x);
        ans += a[i];//全部 
    }
    memset(mi,0x3f,sizeof(mi));//原最大 
    for(int i = 1;i <= n;i++)
        if(!color[i])tarjan(i);
    for(int i = 1;i <= num;i++)ans -= mi[i];//减去 
    printf("%d\n",ans);
    
    return 0;
    
}