【点分治+cdq分治+斜率优化】[NOI2014]购票

题目

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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值