最大权独立集,树形dp

HDU - 1520

There is going to be a party to celebrate the 80-th Anniversary of the Ural State University. The University has a hierarchical structure of employees. It means that the supervisor relation forms a tree rooted at the rector V. E. Tretyakov. In order to make the party funny for every one, the rector does not want both an employee and his or her immediate supervisor to be present. The personnel office has evaluated conviviality of each employee, so everyone has some number (rating) attached to him or her. Your task is to make a list of guests with the maximal possible sum of guests’ conviviality ratings.
Input
Employees are numbered from 1 to N. A first line of input contains a number N. 1 <= N <= 6 000. Each of the subsequent N lines contains the conviviality rating of the corresponding employee. Conviviality rating is an integer number in a range from -128 to 127. After that go T lines that describe a supervisor relation tree. Each line of the tree specification has the form:
L K
It means that the K-th employee is an immediate supervisor of the L-th employee. Input is ended with the line
0 0
Output
Output should contain the maximal sum of guests’ ratings.
Sample Input

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
7  
1
1
1
1
1
1
1
1 3
2 3
6 4
7 4
4 5
3 5
0 0

Sample Output

1
5

题意:

给你一颗树,表示一个公司员工的从属关系,每个员工有一个欢乐值。要求选择一些人,但其中没有直接的从属关系(即在树中不是父子),求最大的欢乐值。

题解:

其实就是求最大权独立集的权值大小。
我们定义dp[u][0]dp[u][0]表示在u这个子树不选u的最大值,dp[u][1]dp[u][1]表示在u这个子树选u的最大值。
故考虑转移(v是u的孩子):dp[u][0]=vmax(dp[v][0],dp[v][1])dp[u][0]=\sum_v max(dp[v][0],dp[v][1]) dp[u][1]=vdp[v][0]dp[u][1]=\sum_v dp[v][0]

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <bits/stdc++.h>
using namespace std;
const int N=10010;
int head[N],nxt[N<<1],pnt[N<<1],E;
int indeg[N],n,vl[N];
int dp[N][2],ans;
void add(int u,int v) {
indeg[v]++;
E++;pnt[E]=v;nxt[E]=head[u];head[u]=E;
}
void dfs(int u) {
dp[u][1]=vl[u];
for(int i=head[u];i;i=nxt[i]) {
int v=pnt[i];
dfs(v);
dp[u][1]+=dp[v][0];
dp[u][0]+=max(dp[v][0],dp[v][1]);
}
}
int main() {
while(scanf("%d",&n)!=EOF) {
memset(dp,0,sizeof dp);
memset(indeg,0,sizeof indeg);
memset(head,0,sizeof head);
E=0;
for(int i=1;i<=n;i++) scanf("%d",&vl[i]);
int a,b;
while(1) {
scanf("%d%d",&a,&b);
if(a==0||b==0) break;
add(b,a);
}
for(int i=1;i<=n;i++) {
if(indeg[i]==0) {
dfs(i);
ans=max(dp[i][1],dp[i][0]);
}
}
printf("%d\n",ans);
}

}