最长上升子序列1002
来源:互联网 发布:周扬青买化妆淘宝店名 编辑:程序博客网 时间:2024/05/17 08:17
最大连续子序列
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 3 Accepted Submission(s) : 3
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
给定K个整数的序列{ N1, N2, ..., NK },其任意连续子序列可表示为{ Ni, Ni+1, ...,
Nj },其中 1 <= i <= j <= K。最大连续子序列是所有连续子序列中元素和最大的一个,
例如给定序列{ -2, 11, -4, 13, -5, -2 },其最大连续子序列为{ 11, -4, 13 },最大和
为20。
在今年的数据结构考卷中,要求编写程序得到最大和,现在增加一个要求,即还需要输出该
子序列的第一个和最后一个元素。
Nj },其中 1 <= i <= j <= K。最大连续子序列是所有连续子序列中元素和最大的一个,
例如给定序列{ -2, 11, -4, 13, -5, -2 },其最大连续子序列为{ 11, -4, 13 },最大和
为20。
在今年的数据结构考卷中,要求编写程序得到最大和,现在增加一个要求,即还需要输出该
子序列的第一个和最后一个元素。
Input
测试输入包含若干测试用例,每个测试用例占2行,第1行给出正整数K( < 10000 ),第2行给出K个整数,中间用空格分隔。当K为0时,输入结束,该用例不被处理。
Output
对每个测试用例,在1行里输出最大和、最大连续子序列的第一个和最后一个元
素,中间用空格分隔。如果最大连续子序列不唯一,则输出序号i和j最小的那个(如输入样例的第2、3组)。若所有K个元素都是负数,则定义其最大和为0,输出整个序列的首尾元素。
素,中间用空格分隔。如果最大连续子序列不唯一,则输出序号i和j最小的那个(如输入样例的第2、3组)。若所有K个元素都是负数,则定义其最大和为0,输出整个序列的首尾元素。
Sample Input
6-2 11 -4 13 -5 -210-10 1 2 3 4 -5 -23 3 7 -2165 -8 3 2 5 01103-1 -5 -23-1 0 -20
Sample Output
20 11 1310 1 410 3 510 10 100 -1 -20 0 0
思路:开一个数组b[j]来记录含有a[j]的和的最大值,然后找出最大值即可;
代码:
#include <iostream>#include <string.h>#include <algorithm>#include <stdio.h>#include <queue>#include <cmath>#include <stdlib.h>using namespace std;int dp[40005];int a[40005],b[40005],c[10000];int main(){ int n; while(cin>>n&&n) { int i,j; int fs=0; int li=0; for(i=1;i<=n;i++) { cin>>a[i]; if(a[i]<0)fs++; else if(a[i]==0)li++; } if(fs==n) { cout<<0<<' '<<a[1]<<' '<<a[n]<<endl; continue; } else if(fs+li==n&&li!=0) { cout<<0<<' '<<0<<' '<<0<<endl; continue; } b[1]=a[1]; int sum=b[1]; for(i=2;i<=n;i++) { if(b[i-1]+a[i]>a[i]) b[i]=b[i-1]+a[i]; else b[i]=a[i]; if(b[i]>sum) { sum=b[i]; } } int z=1; for(i=1;i<=n;i++) { if(b[i]==sum) { for(j=i;j>=1;j--) { b[i]-=a[j]; if(b[i]>0) { c[z]=a[j]; z++; } else if(b[i]==0) { c[z]=a[j]; z++; break; } } break; } } cout<<sum<<' '; if(z==1) { cout<<c[1]<<' '<<c[1]<<endl; } else cout<<c[z-1]<<' '<<c[1]<<endl; } return 0;}
阅读全文
0 0
- 最长上升子序列1002
- 最长上升子序列
- 最长上升子序列
- 最长上升子序列
- 最长上升子序列
- 最长上升子序列
- 最长上升子序列
- 最长上升子序列
- 最长上升子序列
- 最长上升子序列
- 最长上升子序列
- 最长上升子序列
- 最长上升子序列
- 最长上升子序列
- 最长上升子序列
- 最长上升子序列
- 最长上升子序列
- 最长上升子序列
- list转json Gson中list转json
- android获取APK文件,及应用内部签名信息方法
- Java 并发工具包 java.util.concurrent 用户指南
- 莫队算法—【清ojA1206】【bzoj2038】小Z的袜子
- GDB调试器使用总结
- 最长上升子序列1002
- Lua脚本之语法基础快速入门
- 异常抛出throw与throws的区别
- enum和#define共存
- Fiddler抓取Android真机上的HTTPS包
- POJ 1222 EXTENDED LIGHTS OUT 开关问题
- python 接口实现 供第三方调用
- 解决ADO控件遍历数据集超慢的问题
- 香甜的黄油 Sweet Butter