HDU 1520 Anniversary Party (tree-shaped DP)

Source: Internet
Author: User

The key to a tree DP is how to handle recursive return information. This question Dp[i][0] indicates that the current maximum weight is not selected when I point. DP[I][1] Indicates the current maximum weight when I point is selected. State transition equation: Dp[u][[0]+=max (dp[v][0],dp[v][1]), dp[u][1]+=dp[v][0];

The code is as follows:

#include <iostream> #include <string.h> #include <math.h> #include <queue> #include < algorithm> #include <stdlib.h> #include <map> #include <set> #include <stdio.h>using namespace std; #define LL __int64#define Pi ACOs ( -1.0) const int Mod=100000000;const int Inf=0x3f3f3f3f;const double eqs=1e -8;int dp[7000][2], c[7000], Vis[7000];int head[7000], cnt, n;struct node{int u, V, next;}    edge[100000];void Add (int u, int v) {edge[cnt].v=v;    Edge[cnt].next=head[u]; head[u]=cnt++;}    void Dfs (int u) {vis[u]=1;    Dp[u][1]=c[u];        for (int i=head[u];i+1;i=edge[i].next) {int v=edge[i].v;            if (!vis[v]) {DFS (v);            Dp[u][0]+=max (dp[v][0],dp[v][1]);        DP[U][1]+=DP[V][0];    }}}void init () {memset (vis,0,sizeof (VIS));    memset (head,-1,sizeof (head));    cnt=0; Memset (Dp,0,sizeof (DP));}    int main () {int I, J, u, V; while (scanf ("%d", &n)!=eof) {for (i=1;i<=n;i++) {scanf ("%d", &c[i]);        } init ();            while (scanf ("%d%d", &u,&v)!=eof&&u&&v) {Add (u,v);        Add (V,u);        } dfs (1);    printf ("%d\n", Max (dp[1][0],dp[1][1])); } return 0;}


HDU 1520 Anniversary Party (tree-shaped DP)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.