[蓝桥杯2015初赛]生命之树
既然是“暴力杯”,那么就采取暴力的解法。
我们从下往上递归去找点就好了
dfs无根树转有根树,递归找最优。注意开LL
1 #include <iostream> 2 #include <algorithm> 3 #include <string> 4 #include <string.h> 5 #include <vector> 6 #include <map> 7 #include <stack> 8 #include <set> 9 #include <queue> 10 #include <math.h> 11 #include <cstdio> 12 #include <iomanip> 13 #include <time.h> 14 15 #define LL long long 16 #define INF 0x3f3f3f3f 17 #define ls nod<<1 18 #define rs (nod<<1)+1 19 20 const int maxn = 1e5 + 10 ; 21 const LL mod = 20010905; 22 23 std::vector<LL> tree[maxn]; 24 LL w[maxn],ww[maxn],ans; 25 26 void dfs(int u,int father) { 27 int len = tree[u].size(); 28 ww[u] = w[u]; 29 for (int i = 0;i < len;i++) { 30 int v = tree[u][i]; 31 if (v != father) { 32 dfs(v, u); 33 if (ww[v] > 0) 34 ww[u] += ww[v]; 35 } 36 } 37 if (ww[u] > ans) 38 ans = ww[u]; 39 } 40 41 int main() { 42 int n; 43 scanf("%d",&n); 44 for (int i = 1;i <= n;i++) { 45 scanf("%lld",&w[i]); 46 } 47 for (int i = 1;i <= n-1;i++) { 48 int u,v; 49 scanf("%d%d",&u,&v); 50 tree[u].push_back(v); 51 tree[v].push_back(u); 52 } 53 ans = 0; 54 dfs(1,0); 55 printf("%lld\n",ans); 56 return 0; 57 }