답안 #55981

# 제출 시각 아이디 문제 언어 결과 실행 시간 메모리
55981 2018-07-09T09:01:53 Z 노영훈(#1562) Sushi (JOI16_sushi) C++11
0 / 100
49 ms 13356 KB
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
const int MX=100010, inf=2e9;
const ll linf=2e17;

ll n, A[MX], C[MX];
vector<int> G0[MX], G1[MX];

bool done[MX];

void dfs1(int v, vector<int> &V){
    done[v]=true;
    V.push_back(v);
    for(int x:G0[v]) if(!done[x]) dfs1(x,V);
}

bool vis[MX];

int found=-1;
void dfs2(int v, vector<int> &R){
    vis[v]=true;
    int x=A[v];
    if(vis[x]) found=x;
    else dfs2(x,R);
    if(found>=0){
        R.push_back(v);
        if(v==found) found=-1;
    }
}

bool incyc[MX];
ll adj[MX];

ll D[MX];

void dfs3(int v){
    ll &res=D[v], mx=0; res=0;
    for(int x:G1[v]){
        dfs3(x);
        res+=D[x]+C[x]; mx=max(mx, (ll)C[x]);
    }
    res-=mx;
    // cout<<v<<": "<<D[v]<<'\n';
}

bool wasfullcyc;

ll X[MX], Y[MX];

ll solve(int s){
    vector<int> V, cyc;
    dfs1(s,V);

    for(int v:V) vis[v]=false;
    found=-1; dfs2(s, cyc);

    for(int v:V) incyc[v]=false;
    for(int v:cyc) incyc[v]=true;

    wasfullcyc=V.size()==cyc.size();

    bool bettercut=false;
    for(int v:cyc) adj[A[v]]=C[v];

    for(int v:cyc){
        ll now=0, mx=0;
        for(int x:G1[v]){
            if(incyc[x]) continue;
            dfs3(x);
            now+=D[x]+C[x];
            mx=max(mx, C[x]);
        }
        X[v]=now, Y[v]=now+adj[v]-mx;
        bettercut|=X[v]>=Y[v];
    }
    ll ans=0;
    if(bettercut){
        for(int v:cyc) ans+=min(X[v], Y[v]);
        return ans;
    }
    else{
        ll mn=linf;
        for(int v:cyc) mn=min(mn, (ll)C[v]);
        for(int v:cyc) ans+=X[v], mn=min(mn, Y[v]-X[v]);
        return ans+mn;
    }
}

int main(){
    ios::sync_with_stdio(0); cin.tie(0);
    cin>>n;
    for(int i=1; i<=n; i++) cin>>A[i]>>C[i];
    for(int i=1; i<=n; i++){
        G0[A[i]].push_back(i), G0[i].push_back(A[i]);
        G1[A[i]].push_back(i);
    }

    ll ans=0, cnt=0;
    for(int i=1; i<=n; i++){
        if(!done[i])
            ans+=solve(i), cnt++;
    }
    if(cnt==1 && wasfullcyc) ans=0;
    cout<<ans;
    return 0;
}
# 결과 실행 시간 메모리 Grader output
1 Runtime error 12 ms 9976 KB Execution killed with signal 11 (could be triggered by violating memory limits)
2 Halted 0 ms 0 KB -
# 결과 실행 시간 메모리 Grader output
1 Runtime error 49 ms 13356 KB Execution killed with signal 11 (could be triggered by violating memory limits)
2 Halted 0 ms 0 KB -
# 결과 실행 시간 메모리 Grader output
1 Runtime error 12 ms 9976 KB Execution killed with signal 11 (could be triggered by violating memory limits)
2 Halted 0 ms 0 KB -