This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#define rep(i,n)for(int i=0;i<(n);i++)
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
vector<int>E[200000],G[200000];
int deg[200000];
int a[200000],c[200000];
bool loop[200000];
int id[200000];
int loopMax[200000],loopcnt[200000],loopsz[200000];
void dfs(int v,int k){
id[v]=k;
for(int u:E[v]){
if(id[u]==-1){
dfs(u,k);
}
}
}
ll ans=0;
void dfs2(int v){
int Max=0;
int Max2=0;
for(int u:E[v]){
if(loop[u]){
Max2=c[u];
}
else{
dfs2(u);
Max=max(Max,c[u]);
}
}
if(Max2>Max){
loopMax[id[v]]=max(loopMax[id[v]],Max-Max2);
loopcnt[id[v]]++;
}
ans+=max(Max,Max2);
}
int main(){
int n;cin>>n;
rep(i,n){
scanf("%d%d",&a[i],&c[i]);a[i]--;
deg[a[i]]++;deg[i]++;
E[a[i]].push_back(i);
G[a[i]].push_back(i);
G[i].push_back(a[i]);
}
queue<int>que;
rep(i,n){
if(deg[i]==1){
que.push(i);
}
}
memset(loop,1,sizeof(loop));
while(!que.empty()){
int p=que.front();que.pop();
loop[p]=false;
for(int u:G[p]){
if(deg[u]>1){
deg[u]--;
if(deg[u]==1){
que.push(u);
}
}
}
}
memset(id,-1,sizeof(id));
int cnt=0;
rep(i,n){
if(loop[i]&&id[i]==-1){
dfs(i,cnt++);
}
}
bool ok=true;
rep(i,n){
if(!loop[i])ok=false;
}
if(ok&&cnt==1){
puts("0");
return 0;
}
rep(i,cnt)loopMax[i]=INT_MIN;
rep(i,n){
if(loop[i]){
dfs2(i);
loopsz[id[i]]++;
}
}
rep(i,cnt){
if(loopsz[i]&&loopsz[i]==loopcnt[i]){
ans+=loopMax[i];
}
}
ll ans2=0;
rep(i,n)ans2+=c[i];
cout<<ans2-ans<<endl;
}
Compilation message (stderr)
telegraph.cpp: In function 'int main()':
telegraph.cpp:47:8: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
scanf("%d%d",&a[i],&c[i]);a[i]--;
~~~~~^~~~~~~~~~~~~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |