【题目链接】
【算法】
如果(u,v)的距离为2,那么有两种可能 :
1.u和v为祖孙关系
2.u和v为兄弟关系
树形DP即可,详见代码
【代码】
#include<bits/stdc++.h> using namespace std; #define MAXN 200000 #define MOD 10007 int i,u,v,N,ans1,ans2; int w[MAXN+10],max1[MAXN+10],max2[MAXN+10],fa[MAXN+10],sum[MAXN+10]; vector<int> E[MAXN+10]; template <typename T> inline void read(T &x) { int f=1; x=0; char c = getchar(); for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; } for (; isdigit(c); c = getchar()) x = x * 10 + c - '0'; x *= f; } template <typename T> inline void write(T x) { if (x < 0) { putchar('-'); x = -x; } if (x > 9) write(x/10); putchar(x%10+'0'); } template <typename T> inline void writeln(T x) { write(x); puts(""); } inline void dfs(int root) { int i,son,cnt=0; for (i = 0; i < E[root].size(); i++) { son = E[root][i]; if (son != fa[root]) { fa[son] = root; dfs(son); cnt = (cnt + w[son] * w[son]) % MOD; ans1 = max(ans1,w[root]*max1[son]); ans2 = (ans2 + (w[root] * sum[son] * 2) % MOD) % MOD; sum[root] = (sum[root] + w[son]) % MOD; if (w[son] > max1[root]) { max2[root] = max1[root]; max1[root] = w[son]; } else if (w[son] > max2[root]) max2[root] = w[son]; } } ans1 = max(ans1,max1[root]*max2[root]); ans2 = (ans2 + (sum[root] * sum[root] % MOD - cnt + MOD) % MOD) % MOD; } int main() { read(N); for (i = 1; i < N; i++) { read(u); read(v); E[u].push_back(v); E[v].push_back(u); } for (i = 1; i <= N; i++) read(w[i]); dfs(1); write(ans1); putchar(' '); write(ans2); puts(""); return 0; }