#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
const int MX=500010, inf=2e9;
const ll linf=2e17;
int 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, int p, vector<int> &R){
vis[v]=true;
for(int x:G1[v]){
if(vis[x]) found=x;
else dfs2(x,v,R);
if(found>=0){
R.push_back(v);
if(v==found) found=-1;
return;
}
}
}
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 solve(int s){
vector<int> V, cyc;
dfs1(s,V);
for(int v:V) vis[v]=false;
found=-1; dfs2(s, -1, cyc);
for(int v:V) incyc[v]=false;
for(int v:cyc) incyc[v]=true;
wasfullcyc=V.size()==cyc.size();
ll sum=0, mn=linf;
// rly?
for(int v:cyc) adj[A[v]]=C[v];
for(int v:cyc) mn=min(mn, (ll)C[v]);
for(int v:cyc){
for(int x:G1[v]){
if(incyc[x]) continue;
dfs3(x);
sum+=D[x]+C[x];
mn=min(mn, adj[v]-C[x]);
}
}
// cout<<sum<<' '<<mn<<'\n';
return mn+sum;
}
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 |
Incorrect |
24 ms |
23800 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
24 ms |
23800 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
24 ms |
23800 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
24 ms |
23800 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |