【Code Chef】April Challenge 2019

Subtree Removal

很显然不可能选择砍掉一对有祖先关系的子树。令$f_i$表示$i$子树的答案,如果$i$不被砍,那就是$a_i + \sum\limits_j f_j$;如果$i$被砍,那就是$-x$。取个$max$就好了。

#include <bits/stdc++.h>

using namespace std;

const int N = 1e5 + 5;

int tc, n, xx;
int a[N];
vector<int> g[N];
long long f[N];

void Dfs(int x, int ft) {
  f[x] = a[x];
  for (int i = 0; i < g[x].size(); ++i) {
    int v = g[x][i];
    if (v == ft) continue;
    Dfs(v, x);
    f[x] += f[v];
  }
  f[x] = max(f[x], -(long long)xx);
}

int main() {
  scanf("%d", &tc);
  for (; tc--; ) {
    scanf("%d%d", &n, &xx);
    for (int i = 1; i <= n; ++i) {
      scanf("%d", &a[i]);
    }
    for (int i = 1, x, y; i < n; ++i) {
      scanf("%d%d", &x, &y);
      g[x].push_back(y);
      g[y].push_back(x);
    }

    Dfs(1, 0);
    printf("%lld\n", f[1]);
    
    // remember to clear up
    for (int i = 1; i <= n; ++i) {
      g[i].clear();
    }
  }
  
  return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/Dance-Of-Faith/p/10712425.html
今日推荐