题目
Today, Yasser and Adel are at the shop buying cupcakes. There are 𝑛 cupcake types, arranged from 1 to 𝑛 on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type 𝑖 is an integer 𝑎𝑖. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.
Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.
On the other hand, Adel will choose some segment [𝑙,𝑟] (1≤𝑙≤𝑟≤𝑛) that does not include all of cupcakes (he can’t choose [𝑙,𝑟]=[1,𝑛]) and buy exactly one cupcake of each of types 𝑙,𝑙+1,…,𝑟.
After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel’s choice.
For example, let the tastinesses of the cupcakes be [7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=10. Adel can choose segments [7],[4],[−1],[7,4] or [4,−1], their total tastinesses are 7,4,−1,11 and 3, respectively. Adel can choose segment with tastiness 11, and as 10 is not strictly greater than 11, Yasser won’t be happy .Find out if Yasser will be happy after visiting the shop.
Input
Each test contains multiple test cases. The first line contains the number of test cases 𝑡 (1≤𝑡≤104). The description of the test cases follows.
The first line of each test case contains 𝑛 (2≤𝑛≤105).
The second line of each test case contains 𝑛 integers 𝑎1,𝑎2,…,𝑎𝑛 (−109≤𝑎𝑖≤109), where 𝑎𝑖 represents the tastiness of the 𝑖-th type of cupcake.
It is guaranteed that the sum of 𝑛 over all test cases doesn’t exceed 105.
Output
For each test case, print “YES”, if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel’s choice. Otherwise, print “NO”.
Example
input
3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
output
YES
NO
NO
题意
有N的蛋糕,每个蛋糕都有一个口味程度,越好吃的数值越大。有两个人购买蛋糕,A买走了所有的蛋糕,B只买走了一部分。问B的蛋糕总的口味程度能不能比A的要高。(口味比较差的,数值为负数)
思路
这显然是个求最大子序列的题目,只是求出最大子序列之后,需要求和然后和序列总和做比较。但是这道题目可以用另一个思路来解,从第一个蛋糕开始往后累加,只要有一刻蛋糕的口味值为负数,就能说明A的口味口味程度一定比部分的差(仔细思考一下)。从后往前在累加一次,同理。
代码如下:
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int a[100001];
int main()
{
int t;
cin >>t;
while(t--)
{
int n;
long long sum=0;
cin >>n;
int m=0;
for(int i=1;i<=n;i++)
{
cin >>a[i];
}
for(int i=1;i<=n;i++)
{
sum +=a[i];
if(sum <=0)
{
cout <<"NO"<<endl;
m =1;
break;
}
}
sum =0;
for(int i=n;i>0;i--)
{
sum +=a[i];
if(sum<=0 && m==0)
{
cout <<"NO"<<endl;
m =1;break;
}
}
if(m==0)
{
cout <<"YES"<<endl;
}
}
return 0;
}