P3994 高速公路

· · 题解

树上斜率优化问题。

设 dp_u 表示答案,dep_u 表示点 u 到根的距离。

于是状态转移方程为:

\begin{aligned}dp_u&=\min_{v\in \text{fore}(u)}(dp_v+p_u\cdot(dep_u-dep_v)+q_u)\\&=\min_{v\in \text{fore}(u)}(dp_v-p_u\cdot dep_v)+p_u \cdot dep_u+q_u\end{aligned}

就是斜率优化的板子了。其中,\text{fore}(u) 为 u 祖先的集合(不含 u 本身)。

由于斜率 p_u 不单调,可以在下凸壳上二分。

注意到是树上求解,考虑使用栈记录增删情况并还原。

时间复杂度 \mathcal{O}(n\log n),空间复杂度 \mathcal{O}(n)。

:::warning[Tip]{open} 题目里提到答案不会大于 2^{63}-1,但不代表过程中计算结果不会大于 2^{63}-1。

虽然 long long 可过,但理论上应使用 __int128。

:::success[高速公路 - 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];
inline bool check(int i,int j,int k){
    return dp[j]-p[i]*dep[j]>=dp[k]-p[i]*dep[k];
}
inline bool solve(int u,int v,int w){
    return (dp[v]-dp[u])*(dep[w]-dep[v])>(dp[w]-dp[v])*(dep[v]-dep[u]);
}
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(check(u,sta[mid-1],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 solve(sta[pr-1],sta[pr],u)) 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;
}

:::