Description
给你n个节点,第i个节点不能与b[i]共存,权值为a[i],让你求一个集合使这个集合点权最大。
Sample Input
3
10 2
20 3
30 1
Sample Input
30
看到这道题首先会想到没有上司的晚会那题。
然后考虑做树形DP,然后我就不会做了,因为他有环。。。
然后我就上网查到了基环树这个东西,膜了一波。
你想这个图实际上是个无向图,且一个联通分量只存在一个环。
你把这个环其中的一条边断开,以断开的边的两个端点分别为根去做树形DP,且另一个端点不可存在,然后就像没有上司的晚会做。
#include <cstdio>
#include <cstring>
#include <climits>
using namespace std;
typedef long long LL;
const LL inf = LLONG_MAX;
int read() {
int x = 0, f = 1; char ch = getchar();
while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}
while(ch >= '0' && ch <= '9'){x = x * 10 + ch - '0'; ch = getchar();}
return x * f;
}
LL _max(LL x, LL y) {return x > y ? x : y;}
struct edge {
int x, y, next;
} e[2100000]; int len, last[1100000];
int now, v[1100000], a[1100000], fa[1100000];
int cutnow, cutk; LL dp[1100000][2];
int list[1100000];
void ins(int x, int y) {
e[++len].x = x; e[len].y = y;
e[len].next = last[x]; last[x] = len;
}
void dfs(int x, int fa) {
dp[x][1] = (LL)a[x];
for(int k = last[x]; k; k = e[k].next) {
int y = e[k].y;
if(y == fa || k == cutk || ((k - 1) ^ 1) + 1 == cutk) continue;
dfs(y, x);
dp[x][1] += dp[y][0];
dp[x][0] += _max(dp[y][0], dp[y][1]);
}
if(x == cutnow) dp[x][1] = -inf;
}
LL bfs(int st) {
int head = 1, tail = 2;
list[1] = st; v[st] = now; fa[st] = 0;
int cutx = -1, cuty = 0;
while(head != tail) {
int x = list[head];
for(int k = last[x]; k; k = e[k].next) {
int y = e[k].y;
if(fa[x] == y) continue;
if(v[y] == now) {cutx = x; cuty = y; cutk = k; continue;}
v[y] = now; fa[y] = x;
list[tail++] = y;
}
head++;
}
LL max1, max2;
memset(dp, 0, sizeof(dp));
cutnow = cuty; dfs(cutx, 0); max1 = _max(dp[cutx][1], dp[cutx][0]);
memset(dp, 0, sizeof(dp));
cutnow = cutx; dfs(cuty, 0); max2 = _max(dp[cuty][1], dp[cuty][0]);
return _max(max1, max2);
}
int main() {
int n = read();
for(int i = 1; i <= n; i++) {
a[i] = read(); int x = read();
ins(i, x); ins(x, i);
}
LL ans = 0; now = 0;
for(int i = 1; i <= n; i++) {
if(!v[i]) {
now++;
ans += bfs(i);
}
}
printf("%lld\n", ans);
return 0;
}