题解:P4383 [八省联考 2018] 林克卡特树
Mengguigui · · 题解
前言
模拟赛考到了 wqs 二分,学了一下,发现只剩这题有题解位了
题意简述
给定一棵
题意转化
切掉
最终选择的一条路径,在每个连通块内经过的部分一定是一条简单路径,因此其贡献不超过该连通块的最大路径和,即带权直径:
所以最终路径收益满足:
反过来,对每个连通块取一条最大路径,再把这些路径的端点用新加的
因此原题等价于:
恰好删除
K 条边,使所有连通块的带权直径之和最大。
记答案为
WQS 二分
考虑给每条被切的边一个罚分
设:
其中
当
转移
newA=A+X
newB=max(B+X,A+M)
newC=max(
C+X,//当前块已经有完整路径,儿子独立处理;
B+M,//把当前以 $ u $ 为端点的路径和儿子的开路径拼接,形成完整路径;
A+C[v]//路径完全位于儿子的连通块中,边 (u,v) 不作为路径的一部分。
)
复杂度分析
一次树形 DP 的时间复杂度为
二分范围取
总时间复杂度:
空间复杂度:
参考代码
//提示:不要抄代码,会有神秘的答案错误
#include<bits/stdc++.h>
using namespace std;
using ll=long long;
struct Edge{
int v;
ll w;
};
struct Node{
ll val;
int cut;
bool operator<(const Node& other)const
{
if(val==other.val)
{
return cut<other.cut;
}
return val<other.val;
}
Node friend operator+(const Node& a,const Node& b){
return {a.val+b.val,a.cut+b.cut};
}
};
struct DP{
Node A,B,C;
};
const int N=3e5+5;
vector<Edge> g[N];
int n,k;
ll L=0;
DP dfs(int u,int fa)
{
Node a0={0,0},a1={0,0},a2={0,0};
for(auto e:g[u])
{
int v=e.v;
ll w=e.w;
if(v==fa)continue;
DP son=dfs(v,u);
Node x=max(son.A,son.C+(Node){-L,1});
Node M=son.B+(Node){w,0};
Node na0=a0+x;
Node na1=max(a1+x,a0+M);
Node na2=max(a2+x,max(a1+M,a0+son.C));
a0=na0,a1=na1,a2=na2;
}
return {a0,a1,a2};
}
Node solve(ll x)
{
L=x;
return dfs(1,0).C;
}
int main()
{
cin>>n>>k;
for(int i=1;i<n;i++)
{
int u,v;
ll w;
cin>>u>>v>>w;
g[u].push_back({v,w});
g[v].push_back({u,w});
}
ll l=-1e12,r=1e12;
ll pos=0;
while(l<=r)
{
ll mid=l+(r-l)>>1;
Node cur=solve(mid);
if(cur.cut>=k)
{
pos=mid;
l=mid+1;
}
else{
r=mid-1;
}
}
Node ans=solve(pos);
cout<<ans.val+1LL*pos*k<<"\n";
}