就是有n个点n条边,那么有且只有一个环那么用Dfs把在环上的两个点找到。然后拆开,从这条个点分别作树形Dp即可.
#include <cstdio>
#include <cstring>
#define LL long long
const LL Maxn=;
struct Edge{LL to,next;}edge[Maxn<<];
LL head[Maxn],F[Maxn],G[Maxn],cnt,U,V,E,vis[Maxn],a[Maxn],n,Ans;
inline void Add(LL u,LL v) {edge[++cnt].to=v;edge[cnt].next=head[u];head[u]=cnt;}
inline LL Max(LL x,LL y) {return x>y?x:y;}
void Dfs(LL u,LL fa)
{
vis[u]=true;
for (LL i=head[u];i!=-;i=edge[i].next)
{
if (edge[i].to==fa) continue;
if (vis[edge[i].to])
{
U=u,V=edge[i].to;
E=i;
continue;
}
Dfs(edge[i].to,u);
}
}
void Dp(LL u,LL fa,LL Ban)
{
F[u]=a[u],G[u]=;
for (LL i=head[u];i!=-;i=edge[i].next)
{
if (i==Ban || (i^)==Ban || edge[i].to==fa) continue;
Dp(edge[i].to,u,Ban);
F[u]+=G[edge[i].to];
G[u]+=Max(F[edge[i].to],G[edge[i].to]);
}
} int main()
{
scanf("%lld",&n);
memset(head,-,sizeof(head)); cnt=;
for (LL i=;i<=n;i++)
{
LL u;
scanf("%lld%lld",&a[i],&u);
Add(u,i),Add(i,u);
} for (LL i=;i<=n;i++)
if (!vis[i])
{
Dfs(i,);
Dp(U,,E);
LL Ret=G[U];
Dp(V,,E);
Ret=Max(Ret,G[V]);
Ans+=Ret;
}
printf("%lld\n",Ans);
return ;
}
C++