传送门
解题思路
和上一题很像,不过这是个基环森林。
还是一样要注意是否是二元环(可以通过删边和反向边来处理)。
AC代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<vector>
using namespace std;
const int maxn=1e6+5;
int p[maxn],n,a[maxn],in[maxn],s,t,cnt=1,del1,del2;
long long ans,dp[maxn][2];
struct node{
int v,next;
}e[maxn*2];
void insert(int u,int v){
cnt++;
e[cnt].v=v;
e[cnt].next=p[u];
p[u]=cnt;
}
void topo(){
queue<int> q;
for(int i=1;i<=n;i++) if(in[i]==1) q.push(i),in[i]--;
while(!q.empty()){
int u=q.front();q.pop();
for(int i=p[u];i!=-1;i=e[i].next){
int v=e[i].v;
in[v]--;
if(in[v]==1) q.push(v);
}
}
}
int dfs(int u){
in[u]--;
int res=0;
for(int i=p[u];i!=-1;i=e[i].next){
int v=e[i].v;
if(in[v]==0||in[v]==1) continue;
res=i;
dfs(v);
}
return res;
}
void DP(int u,int fa){
dp[u][0]=0;dp[u][1]=a[u];
for(int i=p[u];i!=-1;i=e[i].next){
int v=e[i].v;
if(v==fa||i==del1||i==del2) continue;
DP(v,u);
dp[u][0]+=max(dp[v][0],dp[v][1]);
dp[u][1]+=dp[v][0];
}
}
int main(){
ios::sync_with_stdio(false);
memset(p,-1,sizeof(p));
cin>>n;
for(int i=1;i<=n;i++){
int v;
cin>>a[i]>>v;
insert(i,v);insert(v,i);
in[i]++;in[v]++;
}
topo();
for(int i=1;i<=n;i++){
if(in[i]>=2){
s=i;
int k=dfs(i);
del1=k;del2=k^1;
t=e[k].v;
DP(s,-1);
long long res=dp[s][0];
DP(t,-1);
res=max(res,dp[t][0]);
ans+=res;
}
}
cout<<ans;
return 0;
}