luogu P4085 [USACO17DEC]Haybale Feast(尺取法 + 线段树)

C、luogu P4085 [USACO17DEC]Haybale Feast

题目链接
luogu P4085 [USACO17DEC]Haybale Feast(尺取法 + 线段树)_第1张图片
直接开一个线段树维护即可。
注意开ll
线段树维护最大值。注意下标别写错了,比如tr[r]

#include
#include
#include

using namespace std;
typedef long long ll;
const int N = 500007, INF = 0x3f3f3f3f;

int n;
ll m;
ll a[N], b[N];
struct node{
    int l, r;
    ll fun;
}tr[N * 4];
ll sum[N];

void pushup(int p)
{
    tr[p].fun = max(tr[p << 1].fun, tr[p << 1 | 1].fun);
}

void build(int p, int l, int r)
{
    tr[p] = {l, r};
    if(l == r){tr[p].fun = a[r];return ;}
    int mid = l + r >> 1;
    build(p << 1, l, mid);
    build(p << 1 | 1, mid + 1, r);
    pushup(p);
}

ll query(int p, int l, int r)
{
    if(tr[p].l >= l && tr[p].r <= r)return tr[p].fun;
    int mid = tr[p].l + tr[p].r >> 1;
    ll res = 0;
    if(l <= mid)res = query(p << 1, l, r);
    if(r > mid)res = max(res, query(p << 1 | 1, l, r));
    return res;
}

int main(){
    scanf("%d%lld", &n, &m);

    for(int i = 1;i <= n; ++ i)
        scanf("%lld%lld", &b[i], &a[i]);

    build(1, 1, n);

    for(int i = 1;i <= n; ++ i)
        sum[i] = sum[i - 1] + b[i];

    ll ans = INF;
    for(int l = 1, r = 1; l <= n; ++ l)
    {
        for(; sum[r] - sum[l - 1] < m && r <= n; r ++ );
        if(sum[r] - sum[l - 1] < m)break;
        ans = min(ans, query(1, l, r));
    }
    printf("%lld\n", ans);
    return 0;
}

你可能感兴趣的:(#,尺取法,#,线段树)