D. Extreme Subtraction
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given an array a of n positive integers.
You can use the following operation as many times as you like: select any integer 1≤k≤n and do one of two things:
decrement by one k of the first elements of the array.
decrement by one k of the last elements of the array.
For example, if n=5 and a=[3,2,2,1,4], then you can apply one of the following operations to it (not all possible options are listed below):
decrement from the first two elements of the array. After this operation a=[2,1,2,1,4];
decrement from the last three elements of the array. After this operation a=[3,2,1,0,3];
decrement from the first five elements of the array. After this operation a=[2,1,1,0,3];
Determine if it is possible to make all the elements of the array equal to zero by applying a certain number of operations.
Input
The first line contains one positive integer t (1≤t≤30000) — the number of test cases. Then t test cases follow.
Each test case begins with a line containing one integer n (1≤n≤30000) — the number of elements in the array.
The second line of each test case contains n integers a1…an (1≤ai≤106).
The sum of n over all test cases does not exceed 30000.
Output
For each test case, output on a separate line:
YES, if it is possible to make all elements of the array equal to zero by applying a certain number of operations.
NO, otherwise.
The letters in the words YES and NO can be outputed in any case.
Example
inputCopy
4
3
1 2 1
5
11 7 9 6 8
5
1 3 1 3 1
4
5 2 1 10
outputCopy
YES
YES
NO
YES
题意: 就是给出你N个数,然后你可以进行两种操作:
- 前缀同-1
- 后缀同-1
是否能让这N个数去不归零
思路: 差分
被秀到了,真被秀到了,乍一看题解真没看懂,他为什么要用差分,感觉差分并没有什么用,但是慢慢细品。
(1) 在第一个位置-1,让后在[2,n+1]选择一个位置+1。
(2) 在[1,n]选择一个位置-1,让后在n+1的位置+1。
对于差分之后正数的位置我们不需要考虑,因为操作(2)就可以解决。对于负数的位置,只能由第一个位置来消去,那么只需要判断负数的大小和第一个位置大小即可。
(网上几乎都是这样的版本)
原本这里有我的理解让我删了,害怕误导各位巨巨。
这个画下图形,就是把数转成图就好理解点了。
可能是我还不够深层次的理解,写不出来我的理解,只能借用大佬们的语言了。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=2e5+7;
ll n,m,p;
int a[maxn],b[maxn];
int main(){
int t,T=0;
cin>>t;
while(t--){
ll sum=0;
scanf("%lld",&n);
for(int i=1;i<=n;i++){
scanf("%lld",&a[i]);
b[i]=a[i]-a[i-1];
}
for(int i=2;i<=n;i++){
if(b[i]<0) sum-=b[i];
}
if(a[1]>=sum) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}