CF Round 481 (Div. 3)--E. Bus Video System(二分)

The busses in Berland are equipped with a video surveillance system. The system records information about changes in the number of passengers in a bus after stops.

If x is the number of passengers in a bus just before the current bus stop and y is the number of passengers in the bus just after current bus stop, the system records the number y−x. So the system records show how number of passengers changed.

The test run was made for single bus and n bus stops. Thus, the system recorded the sequence of integers a1,a2,…,an (exactly one number for each bus stop), where ai is the record for the bus stop i. The bus stops are numbered from 1 to n in chronological order.

Determine the number of possible ways how many people could be in the bus before the first bus stop, if the bus has a capacity equals to w (that is, at any time in the bus there should be from 00 to w passengers inclusive).

Input

The first line contains two integers n and w (1≤n≤1000,1≤w≤10^9) — the number of bus stops and the capacity of the bus.

The second line contains a sequence a1,a2,…,an (−10^6≤ai≤10^6), where ai equals to the number, which has been recorded by the video system after the i-th bus stop.

Output

Print the number of possible ways how many people could be in the bus before the first bus stop, if the bus has a capacity equals to w. If the situation is contradictory (i.e. for any initial number of passengers there will be a contradiction), print 0.

input 1

3 5
2 1 -3

output 1

3

input 2

2 4
-1 1

output 2

4

Note

In the first example initially in the bus could be 0, 1 or 2 passengers.

In the second example initially in the bus could be 1, 2, 3 or 4 passengers.

题意:给定n个车站的上下车人数(负数表示下车人数),公交车的最大容量为m,问你公交车初始发车前已经存在的人数有多少种可能。

解析:分析可知,满足条件的人数肯定是一段区间,但上下界不知道,但是下界我们是好求的,因此我们求出下界,再二分答案即可,此题细节比较多,许多地方需要判断,尤其是判断下界的一处,详见代码。

#include 
using namespace std;
const int N=1e3+5;
int a[N],n,m;
bool check(int x)//判断是否合法
{
    if(x>m) return false;//特判1,已经超出最大容量
    for(int i=1;i<=n;i++)
    {
        x+=a[i];
        if(x<0||x>m) return false;//基础的不合法情况
    }
    return true;
}
void solve()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++) scanf("%d",&a[i]);
    int l=0,sum=0,mx=0;
    for(int i=1;i<=n;i++)
    {
        sum+=a[i];
        mx=max(mx,sum);
        if(sum<0) l+=-sum,sum=0;
        if(l+mx>m)//特判2,如果初始人数+之前最大人数>m就不合法了
        {
            printf("0\n");
            return;
        }
    }
    int r=1e9,ansl=l,ansr=l;//分别为答案上下界
    while(l<=r)
    {
        int mid=l+r>>1;
        if(check(mid)) ansr=mid,l=mid+1;
        else r=mid-1;
    }
    printf("%d\n",ansr-ansl+1);
}
int main()
{
    int t=1;
    //scanf("%d",&t);
    while(t--) solve();
    return 0;
}

你可能感兴趣的:(算法,c++,c语言)