hdu -1231最大连续子序列

题目:http://acm.hdu.edu.cn/showproblem.php?pid=1231

思路:区间最大子序列的想法,从sum=0,(左边界)l=0开始,sum+=a[i],如果得到sum值小于0,就将sum清零,并将左边界更新为l=i+1,dp的思维方式。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <cstring>
#include <set>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long ll;
int a[100010];
int main()
{
	int n;
	while (cin >> n&&n)
	{
		for (int i = 1; i <= n; i++)
			cin >> a[i];
		int wei = 2;
		int l, r;
		int sum = 0;
		int MAX = -11111;
		for (int i = 1; i <= n; i++)
		{
			sum += a[i];
			if (sum > MAX)
			{
				MAX = sum;
				r = wei;
				l = i + 1;
			}
			if (sum < 0)
			{
				sum = 0;
				wei = i + 2;
			}
		}
		if (MAX < 0)
			cout << 0 << " " << a[1] << " " << a[n] << endl;
		else

			cout << MAX << " " << a[r - 1] << " " << a[l - 1] << endl;
	}
	//system("pause");
}

猜你喜欢

转载自blog.csdn.net/qq_42792291/article/details/85300921