当前位置: 首页 > news >正文

【洛谷】P1352 没有上司的舞会 的题解

【洛谷】P1352 没有上司的舞会 的题解

题目传送门

题解

经典的树形 DP,典中典qaq

树形 dp,由于一个人去与不去会影响到下一位,所以我们多开一维。

就可以推得两个转移方程:

d p [ r o o t ] [ 0 ] = ∑ s o n ( x ) max ⁡ ( d p [ r o o t ] [ 0 ] , d p [ r o o t ] [ 1 ] ) dp[root][0] = \sum_{son(x)} \max(dp[root][0], dp[root][1]) dp[root][0]=son(x)max(dp[root][0],dp[root][1])

d p [ r o o t ] [ 1 ] = h [ r o o t ] + ∑ s o n ( x ) d p [ r o o t ] [ 0 ] dp[root][1] = h[root] + \sum_{son(x)} dp[root][0] dp[root][1]=h[root]+son(x)dp[root][0]

这样的话,我们只需要找到没有上司的节点 r o o t root root 为跟,然后通过 fa() 函数进行 dp 的更新就可以了。时间复杂度 O ( n ) O(n) O(n)

代码

#include <bits/stdc++.h>
#define lowbit(x) x & (-x)
#define endl "\n"
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
namespace fastIO {inline int read() {register int x = 0, f = 1;register char c = getchar();while (c < '0' || c > '9') {if(c == '-') f = -1;c = getchar();}while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();return x * f;}inline void write(int x) {if(x < 0) putchar('-'), x = -x;if(x > 9) write(x / 10);putchar(x % 10 + '0');return;}
}
using namespace fastIO;
vector <int> son[10005];
int dp[10005][2], vis[10005], h[10005], n;
void fa(int x) {dp[x][0] = 0;dp[x][1] = h[x];for(int i = 0; i < son[x].size(); i ++) {int y = son[x][i];fa(y);dp[x][0] += max(dp[y][0], dp[y][1]);dp[x][1] += dp[y][0]; }
}
int main() {//freopen(".in","r",stdin);//freopen(".out","w",stdout);ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);n = read();for(int i = 1; i <= n; i ++) {h[i] = read();}for(int i = 1; i < n; i ++) {int x, y;x = read(), y = read();vis[x] = 1;son[y].push_back(x);}int root;for(int i = 1; i <= n; i ++) {if(!vis[i]) {root = i;break;}}fa(root);cout << max(dp[root][0], dp[root][1]);return 0;
}

http://www.mrgr.cn/news/42498.html

相关文章:

  • SpringBoot开发:古典舞在线交流平台的架构与实现
  • dns服务器部署
  • CSS计数器
  • ssh连接阿里云长连接
  • HISAT 软件比对算法及性能简介
  • Python的file.read方法
  • 工业物联网在能源管理中的应用
  • vscode报错No module named ‘Crypto‘
  • python爬虫 - 初识爬虫
  • SF-HCI-SAP问题收集20:Metadata导入的时间格式错误问题
  • 程序猿成长之路之设计模式篇——设计模式简介
  • python如何比较字符串
  • 【Git】vscode链接github拉去镜像
  • 梗百科——信号和槽机制
  • 【高频SQL基础50题】21-25
  • 【Docker从入门到进阶】06.常见问题与解决方案 07.总结与资源
  • 民峰:助力投资者实现财务自由
  • 【LeetCode】每日一题 2024_10_4 飞机座位分配概率(数学)
  • 浅谈memset和memcpy的区别
  • C++-容器适配器- stack、queue、priority_queue和仿函数