题目描述:
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
You have discovered nn mysterious particles on a line with integer charges of c1,…,cnc1,…,cn. You have a device that allows you to perform the following operation:
- Choose a particle and remove it from the line. The remaining particles will shift to fill in the gap that is created. If there were particles with charges xx and yy directly to the left and right of the removed particle, they combine into a single particle of charge x+yx+y.
For example, if the line of particles had charges of [−3,1,4,−1,5,−9][−3,1,4,−1,5,−9], performing the operation on the 44th particle will transform the line into [−3,1,9,−9][−3,1,9,−9].
If we then use the device on the 11st particle in this new line, the line will turn into [1,9,−9][1,9,−9].
You will perform operations until there is only one particle left. What is the maximum charge of this remaining particle that you can obtain?
Input
Each test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.
The first line of each test case contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105).
The second line of each test case contains nn integers c1,…,cnc1,…,cn (−109≤ci≤109−109≤ci≤109).
It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.
Output
For each test case, output one integer, the maximum charge of the remaining particle.
input
3
6
-3 1 4 -1 5 -9
5
998244353 998244353 998244353 998244353 998244353
1
-2718
output
9
2994733059
-2718
题目大意:给你一个长为n的数组,对于数组中的每一个数,若它在数组的边上,那么我们可以直接移除它,若它位于两数中间,则用两数之和替代他。求我们不断对数组进行以上操作直至数组只剩一个数时的最大值。
思路分析:奇数位置上的数只能和奇数位置上的数合并,得到的值可以继续放在奇数位置上再和其它奇数位置上的数合并,偶数位置同理。我们可以将数组分为奇偶两个部分,对于每一个部分,我们只需要记录正整数的和(因为负数会被另一个序列中的两数和代替后转换到另一个序列当中去),最后的结果就是两个部分正整数和的较大值。若数组中都为负数,那么为最大负数。
代码:
#include<iostream>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n;
long long int m1=0,m2=0,count=0,maxs=-1e9;
cin>>n;
for(int i=1;i<=n;i++){
int a;
cin>>a;
if(i%2==0){
if(a>0)
m1+=a;
else{
count++;
if(a>maxs)
maxs=a;
}
}
else{
if(a>0)
m2+=a;
else{
count++;
if(a>maxs)
maxs=a;
}
}
}
if(count==n)
cout<<maxs<<endl;
else
cout<<max(m1,m2)<<endl;
}
}