首页 技术 正文
技术 2022年11月21日
0 收藏 837 点赞 4,384 浏览 1138 个字

1353: 结点选择

时间限制: 1 Sec  内存限制: 128 MB
提交: 6  解决: 2
[提交][状态][讨论版]

题目描述

问题描述

有一棵 n 个节点的树,树上每个节点都有一个正整数权值。如果一个点被选择了,那么在树上和它相邻的点都不能被选择。求选出的点的权值和最大是多少?

选择3、4、5号点,权值和为 3+4+5 = 12 。数据规模与约定

对于20%的数据, n <= 20。

对于50%的数据, n <= 1000。

对于100%的数据, n <= 100000。

权值均为不超过1000的正整数。

输入

输入格式

第一行包含一个整数 n 。

接下来的一行包含 n 个正整数,第 i 个正整数代表点 i 的权值。

接下来一共 n-1 行,每行描述树上的一条边。

输出

输出格式输出一个整数,代表选出的点的权值和的最大值。

样例输入

5
1 2 3 4 5
1 2
1 3
2 4
2 5

样例输出

12

提示

本题n过大,用邻接表储存就行,注意判断后继节点的时候,不要在回溯到前驱节点

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
struct node{
int to,nex;
}edge[];
int head[];
int dp[][];
bool vis[];
int cnt;void addedge(int u,int v){
edge[cnt].to=v;
edge[cnt].nex=head[u];
head[u]=cnt++;
edge[cnt].to=u;
edge[cnt].nex=head[v];
head[v]=cnt++;
}void dfs(int v,int pre){
vis[v]=true;
for(int i=head[v];i!=-;i=edge[i].nex){
int tmp=edge[i].to;
if(tmp==pre)//注意
continue;
dfs(tmp,v);
dp[v][]+=max(dp[tmp][],dp[tmp][]);
dp[v][]+=dp[tmp][]; }
}int main(){
int n;
while(scanf("%d",&n)!=EOF){
memset(head,-,sizeof(head));
memset(dp,,sizeof(dp));
memset(vis,false,sizeof(vis));
for(int i=;i<=n;i++){
scanf("%d",&dp[i][]);
}
int a,b;
cnt=;
for(int i=;i<n;i++){
scanf("%d%d",&a,&b);
addedge(a,b);
}
dfs(,-);
int ans=max(dp[][],dp[][]);
printf("%d\n",ans);
}
return ;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,105
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,582
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,429
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,200
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,836
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,919