zoukankan      html  css  js  c++  java
  • 最大子树和(树形dp)

    传送门

    树形dp入门题,先放代码

    #include <bits/stdc++.h>
    using namespace std;
    
    const int N = 1e5 + 10;
    struct Edge{
    	int v, w, next;
    }edge[N];
    int tot, head[N], maxn = -2147483647, f[N], value[N];
    
    void add(int u, int v){
    	edge[tot].v = v;
    	edge[tot].next = head[u];
    	head[u] = tot ++;
    }
    
    void dfs(int now, int pre){
    	f[now] = value[now];
    	for(int i = head[now]; i != -1; i = edge[i].next){
    		int v = edge[i].v;
    		if(v == pre)
    			continue;
    		dfs(v, now);
    		if(f[v] > 0)
    			f[now] += f[v]; 
    	}
    }
    int main(){
    	int n;
    	cin >> n;
    	for(int i = 1; i <= n; i ++)
    		cin >> value[i];
    	memset(head, -1, sizeof head);
    	for(int i = 1; i < n; i ++){
    		int a, b;
    		cin >> a >> b;
    		add(a, b);
    		add(b, a);
    	}
    	dfs(1, 0);	
    	for(int i = 1; i <= n; i ++)
    		maxn = max(maxn, f[i]);
    	cout << maxn << endl;
    	return 0;
    }
    
  • 相关阅读:
    WEB
    Python
    Git
    JavaScript
    鸡汤
    面向对象
    Python
    Python
    MongoDB
    Oracle 11g 安装
  • 原文地址:https://www.cnblogs.com/pureayu/p/14979675.html
Copyright © 2011-2022 走看看