跳到正文

题解

P2607 题解

rainygame约 4 分钟
原文
文章信息与版本

文章信息

发布
2023年12月30日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 4 分钟
获赞
34
题目
P2607

版本

  1. v1当前

考虑按仇恨关系建立无向图,可以发现这是一个基环树森林。每个连通块都是一颗基环树。然后本题就类似基环树上“没有上司的舞会”。

那么先考虑一棵树的情况,令 fi,0/1f_{i,0/1} 表示在 ii 的子树内且 ii 不选/选的战斗力总和,有状态转移方程:

fu,0=∑v∈sumax⁡{fv,0,fv,1}f_{u,0}=\sum\limits_{v\in s_u}\max\{f_{v,0},f_{v,1}\} fu,1=au+∑v∈sufv,0f_{u,1}=a_u+\sum\limits_{v\in s_u}f_{v,0}

其中 sus_u 表示 uu 的儿子集合,aua_u 表示 uu 的战斗力。

对于每个连通块,考虑其在环上的任意两个直接相连的点 x,yx,y。如果把中间这条边断开,那么它就会变成一棵树。考虑分别以 xx 和 yy 做两次树形 DP,这个连通块的答案就是第一次的 fx,0f_{x,0} 和第二次的 fy,0f_{y,0} 的最大值。因为两个不能同时取,所以必定有一个不取,要么是 xx 不取(fx,0f_{x,0}),要么是 yy 不取(fy,0f_{y,0})。

对于找环上两个直接相连点,可以使用并查集。如果一次加边中发现它们本来就在一个连通块了,就把它们记下来,它们就是环上两个直接相连点。等图建完后,对记下来的点对分别求出答案,最后求和即可。

代码如下:

C++
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define MAXN 1000001

int n, x, s, t, ans, res;
int a[MAXN], fa[MAXN];
int f[MAXN][2];
list<pair<int, int>> cir;
list<int> e[MAXN];

int find(int x){
    if (fa[x] == x) return x;
    return fa[x] = find(fa[x]);
}

void unite(int x, int y){
    fa[find(x)] = find(y);
}

void dfs(int x, int fa){
    f[x][1] = a[x];
    f[x][0] = 0;
    for (auto i: e[x]){
        if (i ^ fa){
            dfs(i, x);
            f[x][0] += max(f[i][0], f[i][1]);
            f[x][1] += f[i][0];
        }
    }
}

signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    cin >> n;
    iota(fa+1, fa+n+1, 1);
    for (int i(1); i<=n; ++i){
        cin >> a[i] >> x;
        if (find(i) == find(x)){
            cir.push_back({i, x});
            continue;
        }
        e[i].push_back(x);
        e[x].push_back(i);
        unite(i, x);
    }
    for (auto i: cir){
        dfs(i.first, 0);
        res = f[i.first][0];
        dfs(i.second, 0);
        ans += max(res, f[i.second][0]);
    }
    cout << ans << '\n';

    return 0;
}