acwing 周赛19
链接:树上有猴

题意:让任意时刻猴子数量都在[0,w]
题解:我们让猴子初始数量为x ,那么x就在0到w范围活动,每输入一个猴子变动的数量s,
那么0 <= x + s <= w ,也就是 -s <= x <= w - s。因此 后续不断输入s,要想维护这个不等式,左边的数值要取最大,右边的数值要取最小,来维持这个弹性区间,使得 x 一直在[0,w]
代码:
# include <iostream>
# include <algorithm>
# include <cstring>
# include <math.h>
using namespace std;
int main(){
int n,w,a;
cin >> n >> w;
int l = 0, r = w , s = 0;
while (n --){
cin >> a;
s += a;
l = max (l , -s);
r = min (r , w - s);
}
cout << max (0,r - l + 1);
return 0;
}

浙公网安备 33010602011771号