【树形DP】 HDU 1520 Anniversary party 裸题

裸树形DP 练手必备

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <cctype>
#include <cmath>
#include <string>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <iomanip>
using namespace std;
#include <queue>
#include <stack>
#include <vector>
#include <deque>
#include <set>
#include <map>
typedef long long LL;
#define pi acos(-1.0)
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
const int maxn=6006;
const int maxm=6000*100;
int edgenum,head[maxn],a[maxn],dp[maxn][2];
bool vis[maxn];
struct node
{
    int v,next;
} edge[maxm];
void addedge(int u,int v)
{
    edge[edgenum].v=v;
    edge[edgenum].next=head[u];
    head[u]=edgenum++;
    edge[edgenum].v=u;
    edge[edgenum].next=head[v];
    head[v]=edgenum++;
}
void init()
{
    edgenum=0;
    memset(dp,0,sizeof(dp));
    memset(head,-1,sizeof(head));
    memset(vis,false,sizeof(vis));
}
void dfs(int u)
{
    if(vis[u]) return ;
    vis[u]=true;
    dp[u][1]=a[u];
    for(int i=head[u]; ~i; i=edge[i].next)
    {
        int v=edge[i].v;
        if(!vis[v])
        {
            dfs(v);
            dp[u][1]+=dp[v][0];
            dp[u][0]+=max(dp[v][1],dp[v][0]);
        }
    }
}
int main()
{
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
//    freopen("out.txt", "w", stdout);
#endif
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        init();
        for(int i=1; i<=n; i++)
            scanf("%d",&a[i]);
        int x,y;
        while(scanf("%d%d",&x,&y),x&&y)
            addedge(x,y);
        dfs(1);
        printf("%d\n",max(dp[1][0],dp[1][1]));
    }
    return 0;
}


posted @ 2014-10-03 21:53  kewowlo  阅读(168)  评论(0编辑  收藏  举报