等一下,先等我把题目搬过来……
点赞收藏不迷路~
Chapter 01 题意
先理解题意。
题目给出的所谓联合权值,其实就是一对在树上距离为 的节点的权值积。
联合权值最大值就是树上距离为 的两个点的权值积的最大值。
联合权值总和就是树上距离为 的两个点的权值积的和。
Chapter 02 思路
特别鸣谢题解区提供的思路。
f1:朴素算法
最好想的办法是什么呢?
没错,就是直接枚举对于一个点 ,与其距离为 的节点,计算两者权值积,求最大值和总和即可。
但是,这样的话……
如果一个树长成这个样……
那对于节点 至节点 的话,找和其距离为 的节点可就不太稳定了。
f2:因式分解
思考一下,如果有一对距离为 的节点,那么他们一定会经过一个“中转点”。
那么我们社这个中转点为 ,如果这个中转点周围有 个节点,每个节点的权值分别为 ,那么经过这个中转点的联合权值最大值就是这些节点的最大值和次大值的积,联合权值和 就是这样的:
我们来探究一下这个式子有什么特别的地方。
所以懂了吗?联合权值和 也等于这样的一个式子:
这样我们就可以很好的优化时间复杂度了,明白了吗?
时间复杂度:
Chapter 03 代码
f1:朴素算法——70pts
#include<bits/stdc++.h>
using namespace std;
vector<int> v[200005];
int a[200005];
int d[200005];
int maxn = 0;
int summ = 0;
bool vis[200005];
void dfs(int e,int u,int s,int dep){
if(dep==2){
maxn = max(maxn,a[s] * a[e]);
summ = summ + a[s] * a[e];
summ = summ % 10007;
return;
}
for(auto x : v[e]){
if(x==u) continue;
dfs(x,e,s,dep+1);
}
}
signed main(){
int n;
cin >> n;
for(int i = 1;i < n;i++){
int x,y;
cin >> x >> y;
v[x].push_back(y);
v[y].push_back(x);
}
for(int i = 1;i <= n;i++) cin >> a[i];
for(int i = 1;i <= n;i++){
dfs(i,0,i,0);
}
cout << maxn << " " << summ;
}f2:因式分解——100pts
#include<bits/stdc++.h>
using namespace std;
vector<int> v[200005];
int a[200005];
int maxn = 0;
int summ = 0;
const int mod = 10007;
signed main(){
int n;
cin >> n;
for(int i = 1;i < n;i++){
int x,y;
cin >> x >> y;
v[x].push_back(y);
v[y].push_back(x);
}
for(int i = 1;i <= n;i++) cin >> a[i];
for(int i = 1;i <= n;i++){
int maxa = 0,maxb = 0;
int s1 = 0,s2 = 0;
for(auto x : v[i]){
if(a[x] > maxa){
maxb = maxa;
maxa = a[x];
}
else if(a[x] > maxb) maxb = a[x];
s1 = (s1 + a[x]) % mod;
s2 = (s2 + a[x] * a[x]) % mod;
}
s1 = s1 * s1 % mod;
summ = (summ + s1 + mod - s2) % mod;
maxn = max(maxn,maxa * maxb);
}
cout << maxn << " " << summ;
} 
