P3994 高速公路
树上斜率优化问题。
设
于是状态转移方程为:
就是斜率优化的板子了。其中,
由于斜率
注意到是树上求解,考虑使用栈记录增删情况并还原。
时间复杂度
:::warning[Tip]{open}
题目里提到答案不会大于
虽然 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;
}
:::