题目
https://loj.ac/problem/2249
思路
首先写出30分的DP,发现可以斜率优化
然后发现p是无序的,咋办呢?cdq呗
树上?点分治啊
但是这个好难写啊,写了好久
代码
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=2e5+77;
int n,num;
int fa[N];
ll s[N],x[N],y[N],l[N];
vector<int> e[N];
void add(int f,int t) { e[f].push_back(t); }
int root,tot;
int vis[N],sz[N],mx[N];
void dfs1(int u) {
sz[u]=1,mx[u]=0;
for(int i=e[u].size() - 1,v; i >= 0; --i)
if (!vis[v=e[u][i]])
dfs1(v),sz[u] += sz[v],mx[u]=max(mx[u],sz[v]);
if (root < 0 || max(mx[u],tot - sz[u]) < max(mx[root],tot - sz[root]))
root=u;
return;
}
struct P {
ll x,y;
P operator-(P a) { return (P){x - a.x,y - a.y}; }
} st1[N],st2[N];
int top1,top2;
ll d[N];
void dfs2(int u) {
if (l[u] - d[u] > 0) st1[++top1]=(P){l[u] - d[u],u};
for(int i=e[u].size() - 1,v; i >= 0; --i)
if (!vis[v=e[u][i]]) d[v]=d[u] + s[v],dfs2(v);
}
bool cmp(P a,P b) { return a.x < b.x; }
ll f[N];
double slope(P a,P b) { return (double)(a.y - b.y) / (a.x - b.x); }
double sl[N];
void ins(P a) {
while (top2 > 1 && slope(a,st2[top2]) <= sl[top2]) --top2;
st2[++top2]=a;
sl[top2]=top2 > 1 ? slope(st2[top2],st2[top2 - 1]) : -1e18;
}
ll qry(ll k) {
int l=1,r=top2;
ll rt=0;
while (l <= r) {
int mid=l + r >> 1;
if (sl[mid] <= k) {
rt=st2[mid].y - st2[mid].x * k,l=mid + 1;
} else
r=mid - 1;
}
return rt;
}
void work(int u) {
root=-1,dfs1(u),vis[root]=1;
int trt=root;
if (trt != u) tot=tot - sz[trt],work(u);
int v=trt;
ll dis=0;
top1=top2=d[trt]=0,dfs2(trt);
sort(st1 + 1,st1 + 1 + top1,cmp);
for(int i=1; i <= top1; ++i) {
ll lim=st1[i].x;
int w=st1[i].y;
while (v != fa[u] && dis + s[v] <= lim && fa[v])
ins((P){(dis += s[v]),f[fa[v]]}),v=fa[v];
if (top2) f[w]=min(f[w],qry(-x[w]) + d[w] * x[w] + y[w]);
}
for(int i=e[trt].size() - 1; i >= 0; --i)
if (!vis[v=e[trt][i]]) tot=sz[v],work(v);
}
int main()
{
scanf("%d%d",&n,&num);
for(int i=2; i <= n; ++i)
{
scanf("%d%lld%lld%lld%lld",&fa[i],&s[i],&x[i],&y[i],&l[i]);
add(fa[i],i),f[i]=1000000000000000000ll;
}
tot=n,vis[0]=1,work(1);
for(int i=2; i <= n; ++i) printf("%lld\n",f[i]);
return 0;
}