C. Alternating Subsequence
time limit per test:1 second
memory limit per test:256 megabytes
input:standard input
output:standard output
Recall that the sequence bbaabbaaa=[1,2,1,3,1,2,1]a=[1,2,1,3,1,2,1][1,1,1,1][1,1,1,1][3][3][1,2,1,3,1,2,1][1,2,1,3,1,2,1][3,2,3][3,2,3][1,1,1,1,2][1,1,1,1,2]You are given a sequence aannYour task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is kkkkYou have to answer ttInputThe first line of the input contains one integer tt1≤t≤1041≤t≤104ttThe first line of the test case contains one integer nn1≤n≤2⋅1051≤n≤2⋅105aanna1,a2,…,ana1,a2,…,an−109≤ai≤109,ai≠0−109≤ai≤109,ai≠0aiaiiiaa.It is guaranteed that the sum of nn2⋅1052⋅105∑n≤2⋅105∑n≤2⋅105OutputFor each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of aaExampleinputCopy4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
outputCopy2
-1
6
-2999999997
NoteIn the first test case of the example, one of the possible answers is [1,2,3–,−1–––,−2][1,2,3_,−1_,−2]In the second test case of the example, one of the possible answers is [−1,−2,−1–––,−3][−1,−2,−1_,−3]In the third test case of the example, one of the possible answers is [−2–––,8,3,8–,−4–––,−15,5–,−2–––,−3,1–][−2_,8,3,8_,−4_,−15,5_,−2_,−3,1_]In the fourth test case of the example, one of the possible answers is [1–,−1000000000–––––––––––––,1–,−1000000000–––––––––––––,1–,−1000000000–––––––––––––][1_,−1000000000_,1_,−1000000000_,1_,−1000000000_]
源代码:
// A code block
var foo = 'bar';
// ```
#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<cstdio>
#include <algorithm>
using namespace std;
long long a[200000]={0};
int main()
{
int t;
cin>>t;
while(t--)
{
long long int n,sum=0,i,max,j;
cin>>n;
long long int a[n];
for(i=0;i<n;i++)
scanf("%lld ",&a[i]);
for(i=0;i<n;)
{
max=a[i];
for(j=i+1;j<n;j++)
{
if(a[i]*a[j]>0)
{
if(a[j]>max)
max=a[j];
}
else
{
i=j;
break;
}
}
sum+=max;
if(j==n)
break;
}
cout<<sum<<endl;
}
return 0;
}
本文探讨了在给定序列中寻找最大长度的交替子序列(元素正负号交替出现)的问题,并在此基础上找到该子序列的最大元素和。通过算法解析,提供了具体的实现思路和示例,展示了如何在多种情况下选取最优解。
1万+

被折叠的 条评论
为什么被折叠?



