01-复杂度1 最大子列和问题(20 分)
给定K个整数组成的序列{ N1, N2, ..., NK },“连续子列”被定义为{ Ni, Ni+1, ..., Nj },其中 1≤i≤j≤K。“最大子列和”则被定义为所有连续子列元素的和中最大者。例如给定序列{ -2, 11, -4, 13, -5, -2 },其连续子列{ 11, -4, 13 }有最大的和20。现要求你编写程序,计算给定整数序列的最大子列和。
本题旨在测试各种不同的算法在各种数据情况下的表现。各组测试数据特点如下:
- 数据1:与样例等价,测试基本正确性;
- 数据2:102个随机整数;
- 数据3:103个随机整数;
- 数据4:104个随机整数;
- 数据5:105个随机整数;
输入格式:
输入第1行给出正整数K (≤100000);第2行给出K个整数,其间以空格分隔。
输出格式:
在一行中输出最大子列和。如果序列中所有整数皆为负数,则输出0。
输入样例:
6
-2 11 -4 13 -5 -2
输出样例:
20
作者: DS课程组
单位: 浙江大学
时间限制: 50000ms
内存限制: 64MB
#include <iostream>
#include <fstream>
using namespace std;
#define useIostream 1
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) :val(x), next(nullptr) { }
};
int main()
{
ListNode *head = new ListNode(0);
ListNode *tail = head;
int length = 0;
#if useIostream
cin >> length;
#else
fstream f("data.txt");
f >> length;
#endif
for (int i = 0; i<length; i++)
{
int val = 0;
#if useIostream
cin >> val;
#else
f >> val;
#endif
tail->next = new ListNode(val);
tail = tail->next;
}
ListNode *cur = head;
ListNode *maxHead = nullptr;
ListNode *maxTail = nullptr;
int leftSum = 0;
int maxSum = 0;
while (cur)
{
if (leftSum < 0)
leftSum = cur->val;
else
leftSum += cur->val;
if (leftSum >= maxSum)
{
maxSum = leftSum;
maxTail = cur;
}
cur = cur->next;
}
cout << maxSum << " " << maxHead->val << " " << maxTail->val;
cur = head;
while (cur)
{
ListNode *tmp = cur->next;
delete cur;
cur = tmp;
}
#if !useIostream
f.close();
system("pause");
#endif
return 0;
}