// 1007_Maximum Subsequence Sum.cpp : 定义控制台应用程序的入口点。
//1007. Maximum Subsequence Sum (25)
//
//时间限制
//400 ms
//内存限制
//65536 kB
//代码长度限制
//16000 B
//判题程序
//Standard
//作者
//CHEN, Yue
//Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is defined to be { Ni, Ni+1, ..., Nj } where 1 <= i <= j <= K. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.
//
//Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.
//
//Input Specification:
//
//Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (<= 10000). The second line contains K numbers, separated by a space.
//
//Output Specification:
//
//For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.
//
//Sample Input:
//10
//-10 1 2 3 4 -5 -23 3 7 -21
//Sample Output:
//10 1 4
#include "stdafx.h"
#include "stdio.h"
#include "iostream"
#include "string.h"
#include "stdlib.h"
#include "string"
#include "algorithm"
#include "limits.h"
using namespace std;
//void AC_code();
//void my_match();
//void rand_num();
int a[10010],dp[10010];
int main()
{
//rand_num();
//freopen("data.in","r",stdin);
//freopen("data1.out","w",stdout);
int n;
while(cin>>n){
int flag = 0;
for(int i =1;i<=n;i++){
cin>>a[i];
if(a[i]>=0)
flag = 1;
}
if(!flag){
cout<<"0 "<<a[1]<<" "<<a[n]<<endl;
}
else{
int start,end,max_sum,temp_start;
start = end = temp_start = a[1];
max_sum = INT_MIN;
memset(dp,0,sizeof(dp));
for(int i = 1;i<=n;i++){
if(a[i]>a[i]+dp[i-1]){
dp[i] = a[i];
temp_start = a[i];
if(dp[i]>max_sum){
start = end = a[i];
max_sum = dp[i];
}
}
else{
dp[i] = dp[i-1] + a[i];
if(dp[i]>max_sum){
start = temp_start;
end = a[i];
max_sum = dp[i];
}
}
}
cout<<max_sum<<" "<<start<<" "<<end<<endl;
}
}
//fclose(stdout);
//fclose(stdin);
//AC_code();
//my_match();
return 0;
}
/*
1.注意是>还是>= ,常见疏忽
2.这题调试时,从网上已有的已经AC的代码copy下来新建一个函数,
写一个随机函数批量生成测试数据,然后把自己写的代码和别人
已经AC的代码运行的结果重定向到文件中,再写一个函数判断两个
代码运行的结果的结果是否相同,不同的话定位到该测试数据。
这题当然没必要这么调试,熟悉一下文件操作而已
3.随机函数:
srand((unsigned int)time(0));
rand()%10;
4.fwrite(fp,"%d",x);
FILE *p1;
p1 = fopen("data1.out","r");
5.调用其他文件的函数,在main()之前声明一下
*/
05-03
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交