结点选择---蓝桥杯算法集

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

输入格式
第一行包含一个整数 n 。
接下来的一行包含 n 个正整数,第 i 个正整数代表点 i 的权值。
接下来一共 n-1 行,每行描述树上的一条边。

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

样例输入
5
1 2 3 4 5
1 2
1 3
2 4
2 5

样例输出
12

样例说明
选择3、4、5号点,权值和为 3+4+5 = 12 。

数据规模与约定
对于20%的数据, n <= 20。
对于50%的数据, n <= 1000。
对于100%的数据, n <= 100000。
权值均为不超过1000的正整数。

#include <bits/stdc++.h>
using namespace std;
const int INF=100005;//最大结点数量
vector<vector<int> >tree(INF);//存储整棵树
int cost[INF][2];//存储权值和
bool visit[INF];//是否被访问

void DFS(int v)//深度优先遍历 
{
	visit[v]=true;//已访问
	for(int i=0;i<tree[v].size();i++)
	   if(!visit[tree[v][i]])//子节点没有访问过 
	   {
	   	DFS(tree[v][i]);//递归遍历
		cost[v][0]+=cost[tree[v][i]][1];//更新选中这个结点的整颗子树的最大权值和
		cost[v][1]+=max(cost[tree[v][i]][0],cost[tree[v][i]][1]);//更新没有选中这个结点的整棵树的最大权值和 
	   } 
} 

int main()
{
	int n;
	cin>>n;
	for(int i=1;i<=n;i++)
	    cin>>cost[i][0];
	for(int i=0;i<n-1;i++)
	{
		int a,b;
		cin>>a>>b;
		tree[a].push_back(b);
		tree[b].push_back(a);
	}
	DFS(1);
	cout<<max(cost[1][0],cost[1][1]);//输出整棵树最大权值和
	return 0; 
}
发布了106 篇原创文章 · 获赞 53 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_43595030/article/details/104094460