周年纪念晚会
人事关系是一棵树,职员与其直接上司不能同时参
正文
/*
原题:周年纪念晚会(一本通 5.2 练习3)
题意:人事关系是一棵树,职员与其直接上司不能同时参会,求参会最大欢乐度(最大独立集)。
思路:树形 DP。dp[u][0] 不选 u,取儿子最大值之和;dp[u][1] 选 u,累加儿子不选的值。根取最大。
复杂度:O(N) 时间,O(N) 空间。
易错点:欢乐度可能为负,初值取 0 而非负无穷;根为未出现在下属位置的人。
*/
#include <bits/stdc++.h>
using namespace std;
const int N=6005;
vector<int> g[N];
int happy[N];
int dp[N][2];
bool has_boss[N];
void dfs(int u){
dp[u][0]=0;
dp[u][1]=happy[u];
for(int v:g[u]){
dfs(v);
dp[u][0]+=max(dp[v][0],dp[v][1]);
dp[u][1]+=dp[v][0];
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin>>n;
for(int i=1;i<=n;i++)cin>>happy[i];
for(int l,k;cin>>l>>k;){
if(l==0&&k==0)break;
g[k].push_back(l);
has_boss[l]=true;
}
int root=1;
while(root<=n&&has_boss[root])root++;
dfs(root);
cout<<max(dp[root][0],dp[root][1])<<"\n";
return 0;
}
一本通·提高篇的其它内容
- 活动安排
- 种树
- 喷水装置
- 加工生产调度
- 智力大冲浪
- 数列极差
- 数列分段
- 线段
- 家庭作业
- 钓鱼
- 糖果传递
- 愤怒的牛
- Best Cow Fences
- 曲线
- 数列分段 II
- 扩散
- 灯泡
- 传送带
- 数的划分
- 生日蛋糕
- 小木棍
- Addition Chains
- 埃及分数
- 平板涂色
- 质数方阵
- 靶形数独
- 电路维修
- 魔板
- Knight Moves
- 棋盘游戏
- Keyboarding
- 移动玩具
- 山峰和山谷
- Oulipo
- 图书管理
- Power Strings
- Seekthe Name, Seek the Fame
- Friends
- A Horrible Poem
- Beads
- Antisymmetry
- 门票
- 收集雪花
- 剪花布条
- Power Strings
- Radio Transmission
- OKR-Periods of Words
- 似乎在梦中见过的样子
- Censoring
- Phone List
- The XOR Largest Pair
- Nikitosh 和异或
- Immediate Decodability
- L 语言
- Secret Message 秘密信息
- 背单词
- The Xor-longest Path
- Keywords Search
- 玄武密码
- Censoring