51nod 1488 帕斯卡小三角

f(1,j)=a[j], 1≤j≤n.
f(i,j)=min(f(i-1,j),f(i-1,j-1))+a[j], 2≤i≤n, i≤j≤n.
a是一个长度为n的数组。现在有若干个询问,输入x,y,求f(x,y)
n,q<=100000

分析

显然要求的是从第一层某个点(1,s)到(x,y)的最短路径。
yy一下不难发现路径必然是从某个(1,s)走到(x-y+s,s)然后再沿着对角线走到(x,y)。
那么ans=a[s]*(x-y+s)+c[y]-c[s]
把式子画一画,然后用单调栈维护一个凸壳。每次找答案的时候在上面二分即可。

代码

#include <bits/stdc++.h>

const int N = 100005;

int read()
{
    int x = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9') {if (ch == '-') f = -1; ch = getchar();}
    while (ch >= '0' && ch <= '9') {x = x * 10 + ch - '0'; ch = getchar();}
    return x * f;
}

struct Note
{
    int x,y,id;
}w[N];

bool cmp(Note a,Note b)
{
    return a.y < b.y;
}

int n,m;
int a[N];

int c[N],ans[N];

double getK(int j,int k)
{
    return (double)(a[j] * j - a[k] * k - c[j] + c[k]) / (a[k] - a[j]);
}

int getAns(int s,int x,int y)
{
    return a[s] * (x - y + s) + c[y] - c[s];
}

int q[N];

void solve()
{
    int head = 1, tail = 0, now = 1;
    for (int i = 1; i <= n; i++)
    {
        while (head <= tail && a[q[tail]] >= a[i])
            tail--;
        while (head < tail && getK(q[tail - 1], q[tail]) < getK(q[tail], i))
            tail--;
        q[++tail] = i;
        while (now <= m && w[now].y == i)
        {
            int x = w[now].x, y = w[now].y, l = head, r = tail - 1;
            while (l <= r)
            {
                int mid = (l + r) >> 1;
                if (getAns(q[mid], x, y) < getAns(q[mid + 1], x, y))
                    r = mid - 1;
                else l = mid + 1;
            }
            ans[w[now].id] = getAns(q[r + 1], x, y);
            now++;
        }
    }
}

int main()
{
    n = read();
    for (int i = 1; i <= n; i++)
        a[i] = read(), c[i] = a[i] + c[i - 1];
    m = read();
    for (int i = 1; i <= m; i++)
        w[i].x = read(), w[i].y = read(), w[i].id = i;
    std::sort(w + 1, w + m + 1, cmp);
    solve();
    for (int i = 1; i <= m; i++)
        printf("%d\n",ans[i]);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值