当前位置:网站首页>第6届蓝桥杯
第6届蓝桥杯
2022-06-27 07:35:00 【#math.h】
第10题 生命之树(树形dp)
给定一颗无根树,求出一个字数,所有节点的权值之和最大。求出最大的数是多少。
题目思路:
对于每个结点的决策有2种,分别是选择和不选择,那么我们定义dp[ i ][ 0 ] 和 dp[ i ][ 1 ]分别表示不选择(选择) i 结点能得到的最大权值和。
状态转移方程是:dp [ i ] [ 1 ] = sum(max(dp[ j ][ 1 ] , dp[ j ][ 0 ])); j 是 i 的孩子结点 。
dp[ i ][ 0 ] = 0;
#include<cstdio>
#include<cstring>
#include<vector>
#define N 100005
using namespace std;
vector<int> node[N];
// dp[i][0],dp[i][1];
// 分别表示选i结点和不选能得到的最大分数
int dp[N][2];
int v[N],vis[N];
int n,a,b;
void dfs(int u){
dp[u][1] = v[u];
dp[u][0] = 0;
vis[u]=1;
for(int i=0 ;i<node[u].size();i++){
if(!vis[node[u][i]]){
dfs(node[u][i]);
dp[u][1] += max(dp[node[u][i]][1],dp[node[u][i]][0]);
}else{
dp[u][1] = max(dp[u][1],v[u]);
dp[u][0] = max(dp[u][0],0);
}
}
}
void init(){
memset(v,0,sizeof(v));
memset(dp,0,sizeof(dp));
scanf("%d",&n);
for(int i=1 ;i<=n ;i++){
scanf("%d",&v[i]);
}
for(int i=1 ;i<n ;i++){
scanf("%d%d",&a,&b);
node[a].push_back(b);
node[b].push_back(a);
}
}
int main(){
init();
dfs(1);
int ans = -1;
for(int i=1 ;i<=n ;i++){
// printf("dp[%d][1]:%d\n",i,dp[i][1]);
// printf("dp[%d][0]:%d\n",i,dp[i][0]);
ans = max(ans,dp[i][1]);
ans = max(ans,dp[i][0]);
}
printf("%d\n",ans);
return 0;
}
边栏推荐
- js用switch语句根据1-7输出对应英文星期几
- Idea method template
- js来打印1-100间的质数并求总个数优化版
- js中输入三个值,并且由小到大输出
- JDBC reads MySQL data list
- 正斜杠反斜杠的由来
- js判断用户输入的数是否为质数(多种方法)
- How to bind SQL statements to web buttons
- How can the flower e-commerce 2.0 era go after the breakthrough from 0 to 1?
- Construction of defense system for attack and defense exercises part II common strategies for responding to attacks
猜你喜欢

js中输入三个值,并且由小到大输出

JS uses the while cycle to calculate how many years it will take to grow from 1000 yuan to 5000 yuan if the interest rate for many years of investment is 5%

js求所有水仙花数

JS performance reward and punishment examples

(resolved) NPM suddenly reports an error cannot find module 'd:\program files\nodejs\node_ modules\npm\bin\npm-cli. js‘

JS use switch to output whether the result is qualified

js中判断成绩是否合格,范围在0-100,否则重新输入

Common operation and Principle Exploration of stream

Gérer 1000 serveurs par personne? Cet outil d'automatisation o & M doit être maîtrisé

JS, and output from small to large
随机推荐
程序人生 - 程序员三十五岁瓶颈你怎么看?
js来打印1-100间的质数并求总个数优化版
JS to determine whether the number entered by the user is a prime number (multiple methods)
What are the specialties of database system engineers?
js输出1-100之间所有的质数并求总个数
JDBC事务提交事例
Vs how to configure opencv? 2022vs configuration opencv details (multiple pictures)
JS to determine whether the result is qualified, the range is 0-100, otherwise re-enter
Hutool symmetric encryption
R language analyzing wine data
基础知识 | js基础
Mobile security tools -jad
Cookie encryption 6
Sword finger offer 07 Rebuild binary tree
Remote connection raspberry pie in VNC Viewer Mode
Coggle 30 Days of ML 7月竞赛学习
2022 cisp-pte (II) SQL injection
JDBC operation MySQL example
hutool对称加密
JDBC参数化查询示例