Problem Description Given a sequence with n elements, if the last element is also adjacent to the first element of the sequence, the sequence is called “circular sequence”. Now, here comes a simple problem: given a circular sequence, you should find a segment of the sequence, such that it contains at least one el Input Input may contain several test cases. The first line is a single integer t, the number of test cases below. Each test case is composed of two lines. The first line of each test case is a positive integer n (1<=n<=100000), denoting the number of elements in the circular sequence, and the second line has n integers; the absolute value of each integer is no more than 100000. Output For each test case, output the maximum segment sum in a single line. Sample Input 2 2 -1 -2 3 1 -2 3 Sample Output -1 4/* 题意: N个数围成一个环,求截取一段子序列,使截取的子序列,是所有子序列中的和中是最大的。 解题报告:求整个数列的 最大和(maxsum) 和 最小和(minsum),判断maxsum与sum(整个数列的和) - minsum, 如果最大和大则输出maxsum,否则输出sum - minsum(即所求序列是最后一个数能与第一个数相连的子串). 例如:1, -2, 3, -4, 2, 4, 6; sum = 10, maxsum = 12, minsum = -4; */
//标程: #include<iostream> #include<cstdio> using namespace std; const int inf = (1 << 31) - 1; int main() { // freopen("a.txt","r",stdin); int n, i, t, x; cin >> t; while(t --) { cin >> n; __int64 max = -inf, min = inf, s(0), maxsum(0), minsum(0); int flag(0); for(i = 1; i <= n; i ++) { scanf("%d",&x); if(x >= 0) flag = 1; s += x; maxsum += x; minsum += x; if(maxsum > max) max = maxsum; if(maxsum < 0) maxsum = 0; if(minsum < min) min = minsum; if(minsum > 0) minsum = 0; } if(flag == 0) printf("%I64d\n",max); else printf("%I64d\n",(max > s - min ? max : s - min)); } return 0; }
Circular Sequence
最新推荐文章于 2021-12-24 09:56:02 发布