博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
浙大 pat 1007题解
阅读量:4977 次
发布时间:2019-06-12

本文共 2101 字,大约阅读时间需要 7 分钟。

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"iostream"

#include "string"
#include<vector>
#include"algorithm"
#include "stdlib.h"
#include "cmath"
using namespace std;

struct Node

{
int num;
int start;
int sum;
};
vector <Node> d;
int main()
{
int k;
cin >> k;
d.resize(k);

for(int i=0;i<k;i++)

{
cin >> d[i].num;
}
d[0].sum = d[0].num;
d[0].start = 0;

for(int i=1;i<k;i++)

{
if(d[i-1].sum >= 0)
{
d[i].sum = d[i-1].sum+d[i].num;//当前项的和=前一项的和加当前的数
d[i].start = d[i-1].start;//当前项的起点=前一项的起点
}
else
{
d[i].sum = d[i].num;
d[i].start = i;
}
}
int max = d[0].sum;
int temp=0,i;
for( i=0;i<k;i++)
{
if(d[i].sum>max)
{
max = d[i].sum;
temp = i;
}
}
if(max<0)
cout<<"0"<<" "<<d[0].num<<" "<<d[k-1].num<<endl;
else
cout<<d[temp].sum<<" "<<d[d[temp].start].num<<" "<<d[temp].num<<endl;

 

return 0;

}

转载于:https://www.cnblogs.com/luxiao/p/pat1007.html

你可能感兴趣的文章
laravel5.2 移植到新服务器上除了“/”路由 ,其它路由对应的页面显示报404错误(Object not found!)———新装的LAMP没有加载Rewrite模块...
查看>>
编写高质量代码--改善python程序的建议(六)
查看>>
windows xp 中的administrator帐户不在用户登录内怎么解决?
查看>>
接口和抽象类有什么区别
查看>>
Codeforces Round #206 (Div. 2)
查看>>
**p
查看>>
优先队列详解
查看>>
VS2012 创建项目失败,,提示为找到约束。。。。
查看>>
设计类图
查看>>
类对象
查看>>
[Voice communications] 声音的滤波
查看>>
SQL语言之概述(一)
查看>>
软件建模——第9章 毕业论文管理系统—面向对象方法
查看>>
[SDOI2008]洞穴勘测
查看>>
Difference between Linearizability and Serializability
查看>>
IDEA使用操作文档
查看>>
UIView
查看>>
添加日期选择控件
查看>>
bzoj4765: 普通计算姬 (分块 && BIT)
查看>>
看完漫画秒懂区块链
查看>>