牛客练习赛78 CCA的子树

CCA的子树

题意

一棵 n n n 个点的带权树,根节点为 1 1 1 。要求选出两个节点,两个节点子树没有交集,最大化两个节点的子树点权和,如果找不到合法的子树,输出Error

题解

  • 如果两个节点子树没有交集,那么必然可以向上找到两个兄弟节点,使得这两个节点分别是两棵子树根的祖先。
  • 维护 b [ u ] b[u] b[u] 表示以 u u u 为根的子树中,可以找到的最大的子树权值和。
  • 在遍历节点 u u u 的所有孩子节点的时候,维护答案等于这个孩子节点的 b [ v ] b[v] b[v] + 最大的兄弟节点 b [ v v ] b[vv] b[vv]

代码

#pragma region
//#pragma optimize("Ofast")
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <vector>
using namespace std;
typedef long long ll;
#define tr t[root]
#define lson t[root << 1]
#define rson t[root << 1 | 1]
#define rep(i, a, n) for (int i = a; i <= n; ++i)
#define per(i, a, n) for (int i = n; i >= a; --i)
#pragma endregion
const int maxn = 2e5 + 5;
const ll inf = 1e18;
vector<int> g[maxn];
ll a[maxn], b[maxn], ans = -inf;
void dfs(int u, int f) {
    
    
    ll maxx = -inf;
    for (auto v : g[u]) {
    
    
        if (v == f) continue;
        dfs(v, u);
        a[u] += a[v];
        if (maxx != -inf) ans = max(ans, b[v] + maxx);
        maxx = max(maxx, b[v]);
    }
    b[u] = max(a[u], maxx);
}
int main() {
    
    
    int n;
    scanf("%d", &n);
    rep(i, 1, n) scanf("%lld", &a[i]);
    rep(i, 1, n - 1) {
    
    
        int u, v;
        scanf("%d%d", &u, &v);
        g[u].push_back(v);
        g[v].push_back(u);
    }
    dfs(1, 0);
    if (ans == -inf)
        puts("Error");
    else
        printf("%lld\n", ans);
}

/**
5
10 -5 5 6 7
1 2
2 3
3 4
4 5
**/

猜你喜欢

转载自blog.csdn.net/weixin_43860866/article/details/114745382