联合权值

题目地址:

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

基本思路:

要找距离为的点对,我们考虑枚举中间点,
那么每次能产生联合权值的点,必然在这个点的儿子和儿子或者儿子和父亲之间,
所以每次我们用其中权值最大的两个点就能更新出最大值,
然后权值之和实际上就是每次求一个序列中任意两点乘积之和的计算,
这部分实际上每次乘一下前缀和就能搞定,
注意,这样算两个,所以最后要乘个

ps. 的过程好像直接用循环代替就行了XD

参考代码:

#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 ull unsigned 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 mod = 10007;
const int maxn = 2e5 + 10;
vector<int> G[maxn];
int n,w[maxn],ans,mx;
void dfs(int u,int par) {
  int sum = 0,mx1 = -1,mx2 = -1;
  if(par != -1){
    mx1 = w[par];
    ans = (ans + w[par] * sum % mod) % mod;
    sum = (sum + w[par]) % mod;
  }
  for (auto to : G[u]) {
    if (to == par) continue;
    dfs(to, u);
    if(w[to] > mx1){
      mx2 = mx1;
      mx1 = w[to];
    }else if(w[to] > mx2) mx2 = w[to];
    ans = (ans + w[to] * sum % mod) % mod;
    sum = (sum + w[to]) % mod;
  }
  if(mx2 != -1) mx = max(mx,mx1 * mx2);
}
signed main() {
  IO;
  cin >> n;
  rep(i,1,n - 1){
    int u,v;
    cin >> u >> v;
    G[u].push_back(v);
    G[v].push_back(u);
  }
  rep(i,1,n) cin >> w[i];
  ans = 0,mx = 0;
  dfs(1,-1);
  ans = ans * 2ll % mod;
  cout << mx << ' ' << ans << '\n';
  return 0;
}