树上斜率优化问题。
设 表示答案, 表示点 到根的距离。
于是状态转移方程为:
就是斜率优化的板子了。其中, 为 祖先的集合(不含 本身)。
由于斜率 不单调,可以在下凸壳上二分。
注意到是树上求解,考虑使用栈记录增删情况并还原。
时间复杂度 ,空间复杂度 。
Tip
题目里提到答案不会大于 ,但不代表过程中计算结果不会大于 。
虽然 long long 可过,但理论上应使用 __int128。
高速公路 - P3994.cpp
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e6+10;
int fath[maxn],p[maxn],q[maxn],sta[maxn],upd[maxn],top,n,pl,pr;
ll dep[maxn];
__int128 dp[maxn];
vector<int>edge[maxn];
void dfs(int u,int dad){
dep[u]+=dep[dad];
int tmp=top,l=pl+1,r=pr,mid,res=pl;
while(l<=r){
mid=(l+r)>>1;
if(dp[sta[mid-1]]-p[u]*dep[sta[mid-1]]
>=dp[sta[mid]]-p[u]*dep[sta[mid]]) res=mid,l=mid+1;
else r=mid-1;
}
dp[u]=dp[sta[res]]-p[u]*dep[sta[res]]+p[u]*dep[u]+q[u];
while(pl<pr and
(dp[sta[pr]]-dp[sta[pr-1]])*(dep[u]-dep[sta[pr]])
>(dp[u]-dp[sta[pr]])*(dep[sta[pr]]-dep[sta[pr-1]])){
upd[++top]=sta[pr--];
}
sta[++pr]=u;
for(int v:edge[u]) dfs(v,u);
pr--;
while(top>tmp) sta[++pr]=upd[top--];
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin>>n;
for(int i=2;i<=n;i++){
cin>>fath[i]>>dep[i]>>p[i]>>q[i];
edge[fath[i]].push_back(i);
}
pl=1,pr=1;
dfs(1,0);
for(int i=2;i<=n;i++) cout<<(ll)dp[i]<<"\n";
return 0;
}