Algorithm training node selection time limit: 1.0s memory limit: 256.0MB 1 Use tree-type dynamic planning. Kam SAC 2
Using f[i] means to select a node from the subtree I, and the node I must be selected maximum value, with G[i] represents the selection of nodes from the subtree I, and node I must not be selected maximum.
F[i]=a[i]+\sum (G[j]), where a[i] represents the weight of node I, J is the sub-node of I.
G[i]=\sum (Max (F[j], g[j]), where j is the child node of I. 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. The weights and the maximum number of points to be chosen. 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. The 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 3, 4, 5th points, 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.
The weights are positive integers that do not exceed 1000.
/************************************************************************* > File name:selectpoint.c > Auth Or:litingdong > Mail:litingdong2012@gmail.com > Created time:2014 May 18 Sunday 19:39 55 seconds **************** /#include <stdio.h> #include <stdlib.h> # include<string.h> #define N 100000 #define MAX (x, y) > (y)? (
x):(y)) int head[n+1];
int val[n+1];
int vis[n+1]; struct EDGE {int to,next;}
EDGE[N*2];
The struct node {int Yes,no;//yes represents the selection of the root node, no means the root node is not selected, and the child node is selected}node[n];
int m=0; void Add_edge (int u,int v) {edge[m].to=v; edge[m].next=head[u]; head[u]=m++;} void MaxValue (int x)//similar to depth-first traversal {vis[x]=
1;
int i;
NODE[X].YES=VAL[X];
node[x].no=0;
for (i=head[x];i!=-1;i=edge[i].next) {int v=edge[i].to;
if (Vis[v]) continue;
MaxValue (v); node[x].yes+=node[v].no;//The parent node is selected, the child node can no longer select Node[x].no+=max (node[v].yes,node[v].no);//If the parent node is not selected, the child nodes may or may not be selected,
Choose one of the best values from both cases.
}} int Main (){//freopen ("Input1.txt", "R", stdin); int n; memset (head,-1,sizeof (head)); Memset (Vis,0,sizeof (head)); scanf ("%d",
&N);
int i;
for (i=1;i<=n;i++) scanf ("%d", &val[i]);
int A, B;
for (i=0;i<n-1;i++) {scanf ("%d%d", &a,&b);
Add_edge (A, b);
Add_edge (B,a);
} maxValue (1);
printf ("%d\n", Max (node[1].yes,node[1].no));
return 0; }