P2607 题解
考虑按仇恨关系建立无向图,可以发现这是一个基环树森林。每个连通块都是一颗基环树。然后本题就类似基环树上“没有上司的舞会”。
那么先考虑一棵树的情况,令
其中
对于每个连通块,考虑其在环上的任意两个直接相连的点
对于找环上两个直接相连点,可以使用并查集。如果一次加边中发现它们本来就在一个连通块了,就把它们记下来,它们就是环上两个直接相连点。等图建完后,对记下来的点对分别求出答案,最后求和即可。
代码如下:
#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;
}