Escape from the Hell
Posted smallocean
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Escape from the Hell相关的知识,希望对你有一定的参考价值。
Escape from the Hell
[JAG Asia 2016]
容易证明优先选择差值大的更优
对于最后一瓶我们可以枚举
枚举最后一瓶,然后在树状数组上消去它的影响,然后线段树check是否出现被追上的情况,即查询区间最小值。
需要用到两个线段树,因为当二分找到的位置在最后一瓶后面,需要在线段树上消去最后一瓶的影响。
特别注意当差值为负数的时候前缀和就没有单调性了,所以二分要在单调递增区间二分。
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn = 1e5 + 7;
const ll inf = 0x3f3f3f3f3f3f3f3f;
int n;
int C[maxn];
struct node
int a, b;
s[maxn];
bool cmp(node x, node y)
return x.a - x.b > y.a - y.b;
ll c[maxn];
ll sum[maxn];
struct tree
int l, r;
ll min1, min2;
t[maxn << 2];
int lowbit(int x)
return x & (-x);
ll getsum(int i)
ll res = 0;
while (i > 0)
res += c[i];
i -= lowbit(i);
return res;
void update(int i, ll val)
while (i < maxn)
c[i] += val;
i += lowbit(i);
void build(int p, int l, int r)
t[p].l = l, t[p].r = r;
if (l == r)
t[p].min1 = getsum(l) - sum[l];
t[p].min2 = getsum(l) - sum[l - 1];
return;
int mid = (l + r) >> 1;
build(p << 1, l, mid);
build(p << 1 | 1, mid + 1, r);
t[p].min1 = min(t[p << 1].min1, t[p << 1 | 1].min1);
t[p].min2 = min(t[p << 1].min2, t[p << 1 | 1].min2);
ll ask1(int p, int l, int r)
if (l <= t[p].l && r >= t[p].r) return t[p].min1;
int mid = (t[p].l + t[p].r) >> 1;
ll val = inf;
if (l <= mid) val = min(val, ask1(p << 1, l, r));
if (r > mid) val = min(val, ask1(p << 1 | 1, l, r));
return val;
ll ask2(int p, int l, int r)
if (l <= t[p].l && r >= t[p].r) return t[p].min2;
int mid = (t[p].l + t[p].r) >> 1;
ll val = inf;
if (l <= mid) val = min(val, ask2(p << 1, l, r));
if (r > mid) val = min(val, ask2(p << 1 | 1, l, r));
return val;
int erfen(int z, int y, ll x)
int l = z, r = y;
while (l < r)
int mid = (l + r) >> 1;
if (getsum(mid) >= x)r = mid;
else l = mid + 1;
return l;
void dubug()
for (int i = 1; i <= n; ++i)
cout << ask1(1, i, i) << " " << ask2(1, i, i) << endl;
int main()
ll L;
scanf("%d%lld", &n, &L);
for (int i = 1; i <= n; ++i)
scanf("%d%d", &s[i].a, &s[i].b);
sort(s + 1, s + 1 + n, cmp);
int k=-1;
for (int i = 1; i <= n; ++i)
if(s[i].a-s[i].b>=0) update(i, s[i].a - s[i].b);
else if(k==-1)
k=i-1;
scanf("%d", &C[i]);
sum[i] = sum[i - 1] + C[i];
if(k==-1) k=n;
build(1, 1, n);
int minn = n + 1;
for (int i = 1; i <= n; ++i)
if(s[i].a-s[i].b>0) update(i, s[i].b - s[i].a);
int pp = erfen(1, k + 1, L - s[i].a);
if (pp != k + 1)
if (pp < i)
if (ask1(1, 1, pp) > 0)
minn = min(minn, pp + 1);
else
if (i==1||ask1(1, 1, i - 1) > 0)
if (pp==1||ask2(1, i + 1, pp) - (s[i].a - s[i].b) > 0)
minn = min(minn, pp);
if(s[i].a-s[i].b>0)
update(i, s[i].a - s[i].b);
if (minn == n + 1)
printf("-1\n");
else
printf("%d\n", minn);
return 0;
以上是关于Escape from the Hell的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 789. Escape The Ghosts
[LeetCode] Escape The Ghosts 逃离鬼魂