D.Extreme Subtraction
Title Portal:
Extreme Subtraction
Main idea:
There is an array a of length n. You can perform the following operations numerous times:
- a1~ai minus 1
- ai ~ an 减 1
Ask whether you can make all the elements in the array 0;
Ideas:
Turned into a difference problem. (Assuming that the difference array is ans) To make all the numbers in the array 0, then the difference array must also be 0 and ans[1]=0.
So let's see how the two operations affect the difference array:
Operation 1: ans[1]-1 and ans[i+1]+1. Then we can rely on operation 1 to change the negative number in the difference array to 0 and reduce ans[1].
Operation 2: ans[i+1]-1 and ans[n+1]+1. Then we can rely on operation 2 to change the positive number in the difference array to 0, and the number of ans[n+1] has nothing to do with us.
At the beginning ans[1]=a[1], so as long as the absolute value of the negative sum of the difference array is less than or equal to a[1], it outputs YES, otherwise it outputs NO.
Because if the absolute value of the negative sum of the difference array is greater than a[1], then to make the following numbers all become 0, ans[1] will become a negative number, and ans[1] will not change from a negative number to 0 Operation 2 can only make ans[1] change from a positive number to 0, so this does not meet the requirements.
AC Code
#include<bits/stdc++.h>
using namespace std;
const int N=3e4+10;
int a[N];
int ans[N];
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
a[0]=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
ans[i]=a[i]-a[i-1];
}
int res=0;
for(int i=2;i<=n;i++)
if(ans[i]<0) res=res+(-1)*ans[i];
if(res<=a[1]) printf("YES\n");
else printf("NO\n");
}
//system("pause");
return 0;
}