HDU1520 TreeDp 入门

子绚写的程序:可以AC

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<vector>

using namespace std;

#define INF 0x7f7f7f7f
#define MAXN (6000+5)

int val[MAXN], f[MAXN][2];
bool vis[MAXN], flag[MAXN];
vector<int> map[MAXN];

void init(){
	memset(vis, 0, sizeof(vis));
	memset(flag, 0, sizeof(flag));
	for(int i = 0; i < MAXN; i++) map[i].clear();
}

void dp(int now){

	
	int ret0 = 0, ret1 = val[now];
	for(int i = 0; i < map[now].size(); i++){
		int v = map[now][i];
		dp(v);
		
		ret0 = max(ret0, ret0 + max(f[v][0], f[v][1]));
		ret1 = max(ret1, ret1 + f[v][0]);
	}
	
	f[now][0] = ret0; f[now][1] = ret1;
	return;
}

int main(){
	freopen("test.in", "r", stdin);
	freopen("test.out", "w", stdout);
	
	int n;
	while(scanf("%d", &n) != EOF){
		init();
		for(int i = 1; i <= n; i++) scanf("%d", &val[i]);
		
		int u, v;
		while(scanf("%d%d", &u, &v) == 2 && (u+v)){
			map[v].push_back(u);
			flag[u] = true;
		}
		
		int ans = 0;
		for(int i = 1; i <= n; i++)
		    if(!flag[i]){
		    	dp(i);
				ans += max(f[i][0], f[i][1]);
			}
		
		printf("%d\n", ans);
	}
	return 0;
}


你可能感兴趣的:(HDU1520 TreeDp 入门)