如果m=n-1,显然这就是一个经典的树形dp。
现在是m=n,这是一个环套树森林,破掉这个环后,就成了一个树,那么这条破开的边连接的两个顶点不能同时选择。我们可以对这两个点进行两次树形DP根不选的情况。
那么答案就是每个森林的max()之和。
# include <cstdio>
# include <cstring>
# include <cstdlib>
# include <iostream>
# include <vector>
# include <queue>
# include <stack>
# include <map>
# include <set>
# include <cmath>
# include <algorithm>
using namespace std;
# define lowbit(x) ((x)&(-x))
# define pi acos(-1.0)
# define eps 1e-
# define MOD
# define INF (LL)<<
# define mem(a,b) memset(a,b,sizeof(a))
# define FOR(i,a,n) for(int i=a; i<=n; ++i)
# define FO(i,a,n) for(int i=a; i<n; ++i)
# define bug puts("H");
# define lch p<<,l,mid
# define rch p<<|,mid+,r
# define mp make_pair
# define pb push_back
typedef pair<int,int> PII;
typedef vector<int> VI;
# pragma comment(linker, "/STACK:1024000000,1024000000")
typedef long long LL;
int Scan() {
int res=, flag=;
char ch;
if((ch=getchar())=='-') flag=;
else if(ch>=''&&ch<='') res=ch-'';
while((ch=getchar())>=''&&ch<='') res=res*+(ch-'');
return flag?-res:res;
}
void Out(int a) {
if(a<) {putchar('-'); a=-a;}
if(a>=) Out(a/);
putchar(a%+'');
}
const int N=;
//Code begin... struct Edge{int p, next, flag;}edge[N<<];
int head[N], cnt=, node[N], res[], p;
bool vis[N];
LL dp[][N][]; void add_edge(int u, int v){edge[cnt].p=v; edge[cnt].next=head[u]; head[u]=cnt++;} void dfs(int x, int fa)
{
vis[x]=true;
for (int i=head[x]; i; i=edge[i].next) {
int v=edge[i].p;
if (v==fa) continue;
if (vis[v]==true) {
if (p==) res[]=x, res[]=v, p=, edge[i].flag=edge[i^].flag=;
continue;
}
dfs(v,x);
}
}
void dfs_dp(int x, int fa, int flag)
{
for (int i=head[x]; i; i=edge[i].next) {
int v=edge[i].p;
if (v==fa||edge[i].flag) continue;
dfs_dp(v,x,flag);
dp[flag][x][]+=max(dp[flag][v][],dp[flag][v][]);
dp[flag][x][]+=dp[flag][v][];
}
dp[flag][x][]+=node[x];
}
int main ()
{
int n, u, w;
LL ans=;
scanf("%d",&n);
FOR(i,,n) scanf("%d%d",&w,&u), add_edge(u,i), add_edge(i,u), node[i]=w;
FOR(i,,n) {
if (vis[i]) continue;
p=; dfs(i,);
dfs_dp(res[],,); dfs_dp(res[],,);
ans+=max(dp[][res[]][],dp[][res[]][]);
}
printf("%lld\n",ans);
return ;
}