分治问题,求最大子序列HDU1231
来源:互联网 发布:js正则表达式验证邮箱 编辑:程序博客网 时间:2024/05/29 12:16
写的时候也没刻意注意是分治,写完了发现是分治
给定K个整数的序列{ N1, N2, …, NK },其任意连续子序列可表示为{ Ni, Ni+1, …,
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,输出整个序列的首尾元素。
Sample Input
6
-2 11 -4 13 -5 -2
10
-10 1 2 3 4 -5 -23 3 7 -21
6
5 -8 3 2 5 0
1
10
3
-1 -5 -2
3
-1 0 -2
0
Sample Output
20 11 13
10 1 4
10 3 5
10 10 10
0 -1 -2
0 0 0
Huge input, scanf is recommended.
Hint
Hint
import java.util.ArrayList;import java.util.Scanner;/** * Created by 95112 on 10/20/2017. */public class B { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); ArrayList<String> answers = new ArrayList<>(); int n; do { n = scanner.nextInt(); if (n == 0) break; int[] input = new int[n]; for (int i = 0; i < n; i++) input[i] = scanner.nextInt(); int answerFirst = 0; int answerLast = 0; int answerSum = 0; int answerLength = 0; int first = 0; int last = 0; int sum = 0; int changeKey = 0; for (int i = 0 ; i < n; i++){ if (input[i]>=0) changeKey = 1; sum+= input[i]; if (sum < 0){ sum = 0; first = i+1; last = i+1; } else { last = i; } if(sum > answerSum || (input[i] == 0 && answerSum == 0)){ answerSum = sum; answerLast = last; answerFirst = first; answerLength = last - first + 1; } } if (changeKey == 1) answers.add( answerSum+" "+input[answerFirst]+" "+input[answerLast]); else answers.add( 0+" "+input[0]+" "+input[input.length-1]); }while(true); for (String output : answers) System.out.println(output); }}
阅读全文
0 0
- 分治问题,求最大子序列HDU1231
- HDU1231(求最大子序列和)
- 最大子序列和问题 hdu1231
- hdu1231 最大子序列
- hdu1231最大子序列
- hdu1231最大子序列
- HDU1231--最大连续子序列
- hdu1231(最大连续子序列)
- hdu1231 最大连续子序列
- hdu1231-最大连续子序列
- hdu1231最大连续子序列
- HDU1231:最大连续子序列
- HDU1231最大连续子序列
- HDU1231 最大连续子序列
- 最大连续子序列HDU1231
- hdu1231 最大连续子序列
- hdu1231 最大连续子序列
- HDU1231 最大连续子序列
- 三人行-某栈-两周心得
- echarts实现气泡图(气泡之间不叠加)
- C++利用链表将英文单词排序
- java.util.concurrent中的Callable,Future
- Web Service (011---webservice自定义拦截器)
- 分治问题,求最大子序列HDU1231
- 传奇大亨———拉里·埃里森
- c程序设计p82-p83
- QTableWidget中表格显示图片
- MySQL 事务问题及隔离级别
- 随机森林算法学习(RandomForest)
- 洛谷P2680 运输计划(NOIp2015)(BZOJ4326)
- 查找和二分查找 lower_bound upper_bound
- linux下deb安装包的运行