F. Gardening Friends
题解
最大深度·k-与节点1的距离·c
其中最大深度只要知道了节点1的最大深度,其子节点的最大深度可分类讨论得出
code
#include<bits/stdc++.h>
#define ll long long
using namespace std;
vector<ll> G[200005];
ll height1[200005] = {0};
ll height2[200005] = {0};
ll rec[200005] = {0};
ll cnt[200005] = {0};
inline void read(ll &x) {
x = 0;
ll flag = 1;
char c = getchar();
while(c < '0' || c > '9'){
if(c == '-')flag = -1;
c = getchar();
}
while(c >= '0' && c <= '9') {
x = (x << 3) + (x << 1) + (c ^ 48);
c = getchar();
}
x *= flag;
}
inline void write(ll x)
{
if(x < 0){
putchar('-');
x = -x;
}
if(x > 9)
write(x / 10);
putchar(x % 10 + '0');
}
void dfs1(ll now, ll fa)
{
height1[now] = height2[now] = 0;
for(auto next : G[now])
{
if(next == fa) continue;
dfs1(next, now);
if(height1[next] + 1 > height1[now])
{
height1[now] = height1[next] + 1;
}
else if(height1[next] + 1 > height2[now])
{
height2[now] = height1[next] + 1;
}
}
}
void dfs2(ll now, ll fa, ll op)
{
rec[now] = height1[now];
cnt[now] = op;
for(auto next : G[now])
{
if(next == fa) continue;
ll tem2 = height1[next];
if(height1[next] + 1 == height1[now])
{
ll tem1 = height1[now];
height1[next] = max(height1[next], height2[now] + 1);
height1[now] = height2[now];
dfs2(next, now, op + 1);
height1[now] = tem1;
height1[next] = tem2;
}
else
{
height1[next] = height1[now] + 1;
dfs2(next, now, op + 1);
height1[next] = tem2;
}
}
}
int main()
{
ll t;
read(t);
while(t--)
{
ll n, k, c;
read(n); read(k); read(c);
for(ll i = 1; i < n; i++)
{
ll x, y;
read(x); read(y);
G[x].push_back(y);
G[y].push_back(x);
}
dfs1(1, 1);
dfs2(1, 1, 0);
ll ans = 0;
for(ll i = 1; i <= n; i++)
{
ans = max(ans, rec[i] * k - cnt[i] * c);
G[i].clear();
}
write(ans);
putchar('\n');
}
return 0;
}

浙公网安备 33010602011771号