树上子链

题目地址:

https://ac.nowcoder.com/acm/problem/202475

基本思路:

基本上类似树的直径的求法,
我们每次找子树中的次长链和最长链相连取最大就是了,
注意由于有负数的情况,可能取了次长链反而更不优,
所以要再对只取最长链的情况多取一个
其余地方就和树的直径部分相差无几了。

参考代码:

#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std;
#define IO std::ios::sync_with_stdio(false); cin.tie(0)
#define int long long
#define SZ(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define rep(i, l, r) for (int i = l; i <= r; i++)
#define per(i, l, r) for (int i = l; i >= r; i--)
#define mset(s, _) memset(s, _, sizeof(s))
#define pb push_back
#define pii pair <int, int>
#define mp(a, b) make_pair(a, b)
#define INF 0x3f3f3f3f

inline int read() {
  int x = 0, neg = 1; char op = getchar();
  while (!isdigit(op)) { if (op == '-') neg = -1; op = getchar(); }
  while (isdigit(op)) { x = 10 * x + op - '0'; op = getchar(); }
  return neg * x;
}
inline void print(int x) {
  if (x < 0) { putchar('-'); x = -x; }
  if (x >= 10) print(x / 10);
  putchar(x % 10 + '0');
}

const int maxn = 1e5 + 10;
struct Edge{
    int to,next;
}edge[maxn << 1];
int n,cnt,head[maxn],w[maxn];
void add_edge(int u,int v){
  edge[++cnt].next = head[u];
  edge[cnt].to = v;
  head[u] = cnt;
}
int dp[maxn],ans;
void dfs(int u,int par) {
  dp[u] = w[u];
  for (int i = head[u]; i != -1; i = edge[i].next) {
    int to = edge[i].to;
    if (to == par) continue;
    dfs(to, u);
    ans = max(ans, dp[u] + dp[to]);
    dp[u] = max(dp[u], dp[to] + w[u]);
  }
  ans = max(ans,dp[u]);
}
signed main() {
  IO;
  cnt = 0;
  mset(head,-1);
  cin >> n;
  rep(i,1,n) cin >> w[i];
  for(int i = 1 ; i < n ; i++){
    int u,v;
    cin >> u >> v;
    add_edge(u,v);
    add_edge(v,u);
  }
  ans = -INF;
  dfs(1,0);
  cout << ans << '\n';
  return 0;
}