#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<vector>
using namespace std;
typedef long long LL;
inline LL read()
{
LL x=0;bool f=0;char c=getchar();
for (;c<'0'||c>'9';c=getchar()) f=c=='-'?1:0;
for (;c>='0'&&c<='9';c=getchar()) x=x*10+c-'0';
return f?-x:x;
}
const int N=200010;
int n,ll=1,to[N],next[N],head[N],fa[N];
LL p[N],q[N],lv[N],fl[N],dis[N],dp[N],_ans,_k;
int ct,id[N],ln[N<<2],rn[N<<2],_l,_r;
struct na
{
LL x,y;
na (LL a,LL b) {x=a;y=b;}
};
inline bool cmp(const na &a,const na &b,const na &c)
{
return ((double)b.y-a.y)/(b.x-a.x)<((double)c.y-a.y)/(c.x-a.x);
}
struct pch
{
na *h,*dh;
int *pos,*tp,top;
void init(int len)
{
top=0;
h=(na*)malloc(sizeof(na)*(len+1));
dh=(na*)malloc(sizeof(na)*(len+1));
pos=(int*)malloc(sizeof(int)*(len+1));
tp=(int*)malloc(sizeof(int)*(len+1));
}
void ins(const na &a)
{
if (top<2||cmp(h[top-2],h[top-1],a))
*(dh++)=h[top],*(pos++)=*(tp++)=top,h[top++]=a;
else if (!cmp(h[0],h[1],a))
*(dh++)=h[1],*(pos++)=1,*(tp++)=top,h[1]=a,top=2;
else
{
int l=0,r=top-2,mid;
while (l+1<r)
{
mid=l+r>>1;
if (cmp(h[mid],h[mid+1],a)) l=mid;
else r=mid;
}
*(dh++)=h[r+1],*(pos++)=r+1,h[r+1]=a;
*(tp++)=top,top=r+2;
}
}
void del()
{
int p=*(--pos);
h[p]=*(--dh);top=*(--tp);
}
inline double calk(int i)
{
if (!i) return -1e18;
if (i==top) return 1e18;
return ((double)(h+i)->y-(h+i-1)->y)/((double)(h+i)->x-(h+i-1)->x);
}
LL cal(LL k)
{
int l=0,r=top,mid;
while (l+1<r)
{
if (calk(mid=l+r>>1)<=k) l=mid;
else r=mid;
}
return (h+l)->y-k*(h+l)->x;
}
}e[N<<2];
inline void adde(int u,int v,LL w)
{
to[++ll]=v;next[ll]=head[u];head[u]=ll;fl[ll]=w;
}
int find(LL x)
{
int l=0,r=ct-1,mid;
while (l+1<r)
{
if (x<=dis[id[mid=l+r>>1]]) r=mid;
else l=mid;
}
return r;
}
void build(int o,int l,int r)
{
ln[o]=l;rn[o]=r;
e[o].init(r-l+1);
if (l==r) return;
int mid=l+r>>1;
build(o<<1,l,mid);
build(o<<1|1,mid+1,r);
}
void query(int o)
{
if (_l<=ln[o]&&rn[o]<=_r)
{
_ans=min(_ans,e[o].cal(_k));
return;
}
int mid=ln[o]+rn[o]>>1;
if (_l<=mid) query(o<<1);
if (_r>mid) query(o<<1|1);
}
void ins(int p,LL x,LL y)
{
int o=1,l=1,r=n,mid;
na pt(x,y);
e[o].ins(pt);
while (l!=r)
{
if (p<=(mid=l+r>>1)) o=o<<1,r=mid;
else o=o<<1|1,l=mid+1;
e[o].ins(pt);
}
}
void del(int x)
{
int o=1,l=1,r=n,mid;
e[o].del();
while (l!=r)
{
if (x<=(mid=l+r>>1)) o=o<<1,r=mid;
else o=o<<1|1,l=mid+1;
e[o].del();
}
}
void dfs(int u)
{
id[++ct]=u;
int lim=find(dis[u]-lv[u]);
_l=lim;_r=ct-1;_ans=(LL)1e18;_k=p[u];
query(1);dp[u]=_ans+p[u]*dis[u]+q[u];
ins(ct,dis[u],dp[u]);
for (int i=head[u];i;i=next[i])
dis[to[i]]=dis[u]+fl[i],dfs(to[i]);
del(ct--);
}
int main()
{
n=read();read();
for (int i=2;i<=n;i++)
{
fa[i]=read();
adde(fa[i],i,read());
p[i]=read();q[i]=read();lv[i]=read();
}
build(1,1,n);
id[ct=1]=1;ins(1,0,0);
for (int i=head[1];i;i=next[i])
dis[to[i]]=fl[i],dfs(to[i]);
for (int i=2;i<=n;i++) printf("%lld\n",dp[i]);
return 0;
}
NOI2014 购票
最新推荐文章于 2024-06-29 17:09:13 发布