【题目链接】

点击打开链接

【算法】

如果(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+],max1[MAXN+],max2[MAXN+],fa[MAXN+],sum[MAXN+];
vector<int> E[MAXN+]; template <typename T> inline void read(T &x) {
int f=; x=;
char c = getchar();
for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; }
for (; isdigit(c); c = getchar()) x = x * + c - '';
x *= f;
} template <typename T> inline void write(T x) {
if (x < ) { putchar('-'); x = -x; }
if (x > ) write(x/);
putchar(x%+'');
} template <typename T> inline void writeln(T x) {
write(x);
puts("");
} inline void dfs(int root) {
int i,son,cnt=;
for (i = ; 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] * ) % 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 = ; i < N; i++) {
read(u); read(v);
E[u].push_back(v);
E[v].push_back(u);
}
for (i = ; i <= N; i++) read(w[i]);
dfs(); write(ans1); putchar(' '); write(ans2); puts(""); return ; }
04-18 01:48