Problem description
There is a tree of n nodes, each node in the tree has a positive integer weight. If a point is selected, then the points adjacent to it in the tree cannot be selected. What is the weight and maximum of the selected points?
Input format
The first line contains an integer n.
The next line contains n positive integers, and the second positive integer represents the weight of the point I.
The next line is n-1, each of which describes an edge on the tree.
Output format
Outputs an integer representing the maximum value of the selected point's weights and values.
Sample input
5
1 2 3) 4 5
1 2
1 3
2 4
2 5
Sample output
12
Sample Description
Select Points 3, 4, 5th, weights and 3+4+5 = 12.
Data size and conventions
For 20% of data, N <= 20.
For 50% of data, n <= 1000.
For 100% of data, n <= 100000.
A positive integer with a weight of not more than 1000
Without the boss's prom question.
#include <cstdio>#include<cstring>#include<algorithm>#include<vector>using namespacestd;Const intmaxn=100005;intW[maxn];vector<int>TREE[MAXN];intN;intdp[maxn][2];intVIS[MAXN];voidDfsintu) {Vis[u]=1; dp[u][0]=0; dp[u][1]=W[u]; ints0=0, s1=0; for(intI=0; I<tree[u].size (); i++) { intv=Tree[u][i]; if(!Vis[v]) {DFS (v); S0+=max (dp[v][0],dp[v][1]); S1+=dp[v][0]; }} dp[u][0]+=S0; dp[u][1]+=S1;}intMain () {scanf ("%d",&N); for(intI=1; i<=n;i++) scanf ("%d",&W[i]); for(intI=1; i<=n-1; i++) { intu,v; scanf ("%d%d",&u,&v); Tree[u].push_back (v); Tree[v].push_back (U); } DFS (1); printf ("%d\n", Max (dp[1][0],dp[1][1])); return 0;}
Blue Bridge Cup: node selection