HDU 1003 最大连续字数段问题
来源:互联网 发布:2015年癌症数据 编辑:程序博客网 时间:2024/05/16 12:02
Problem Description
Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.
Sample Input
35 6 -1 5 4 -77 0 6 -1 1 -6 7 -513 1 2 3 -100 1 2 3 -100 1 2 1 1 1
Sample Output
Case 1:14 1 4Case 2:7 1 6Case 3:6 1 3这个题要注意一句:如果有相等的,输出最靠前的一个这个是正确的代码:#include <stdio.h>#include <iostream>using namespace std;int a[100005];int main(){ int t; cin >> t; for(int j=1;j<=t;j++) { int n; cin >> n; for(int i=0;i<n;i++) { cin >> a[i]; } int x=0;//必须初始化,防止全是负数的数据 int y=0; int start=0; int end=0; int max=a[0]; int sum=a[0]; for(int i=1;i<n;i++) { if(sum<0) { sum=a[i]; x=y=i; } else { sum+=a[i]; y++; } if(sum>max) { max=sum; start=x; end=y; } } cout << "Case "<<j<<":\n"; if(j==t) cout << max<<" "<<start+1 << " "<< end+1 <<endl; else cout << max<<" "<<start+1 << " "<< end+1 <<endl << endl; } return 0;}
如果没有这句话,代码可以写为:#include <stdio.h>#include <iostream>using namespace std;int a[100005];int main(){ int t; cin >> t; for(int j=1;j<=t;j++) { int n; cin >> n; for(int i=0;i<n;i++) { cin >> a[i]; } int start=0; int end=0; int max=a[0]; int sum=a[0]; for(int i=1;i<n;i++) { if(sum<0) { start=i; sum=0; } sum+=a[i]; if(sum>=max) { max=sum; end=i; // cout << end << endl; } } cout << "Case"<<" "<<j<<":\n"; if(j==t) cout << max<<" "<<start+1 << " "<< end+1 <<endl; else cout << max<<" "<<start+1 << " "<< end+1 <<endl << endl; } return 0;}
0 0
- HDU 1003 最大连续字数段问题
- HDU 1003 最大连续子段和
- HDU 1244 最大m段连续子串问题
- 最大连续字数列和的问题
- HDU-1003 Max Sum(最大连续子段和)
- HDU 1003 MAX SUM 最大连续子段和DP
- HDU 1003 Max Sum(最大连续子段和)
- 【m段最大连续子段和的和】HDU
- DP训练 hdu 1003 Max Sum 最大连续子段和
- hdu(1003)——Max Sum(最大连续子段和)
- HDU 2845 最大非连续子段和 二维dp
- hdu(5586)——Sum(最大连续子段和)
- HDU 5586 Sum (最大连续子段和)
- HDU 1231 最大连续子序列(最大连续子段和)
- [DP]FJSDFZOJ 1386 最大连续子段和问题
- Problem I: 最大连续子段和问题
- 51nod 1050 循环数组最大子段和(最大连续子段问题)
- 求最大连续字数组和
- 使用JConsole监控进程、线程、内存、cpu、类情况
- Java学习第20天:IO流中的File对象和一些只是(如Properties)
- 手把手教你用U盘安装Ubuntu
- windows 7与Virtual Box中的Ubuntu共享文件的方法
- 解决无法创建txt文档
- HDU 1003 最大连续字数段问题
- basil折腾emacs:02:字体配置
- Java归并排序
- cocos2d-x 2.x在android上使用C++11时的设定
- [原创]传递UIScrollView的滑动事件到其子视图中
- [原创]使用iOS端Safari查看设备UDID
- [原创]控制iphone震动强度和时间的private api
- equals()和hashcode()的探讨和重写
- Greedy is Good