P2607 题解

· · 题解

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

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

f_{u,0}=\sum\limits_{v\in s_u}\max\{f_{v,0},f_{v,1}\} f_{u,1}=a_u+\sum\limits_{v\in s_u}f_{v,0}

其中 s_u 表示 u 的儿子集合,a_u 表示 u 的战斗力。

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

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

代码如下:

#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;
}