DP 1001

来源:互联网 发布:阿里云ecs适合hdfs吗 编辑:程序博客网 时间:2024/06/07 15:46
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.<br>
 

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).<br>
 

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.<br>
 

Sample Input
25 6 -1 5 4 -77 0 6 -1 1 -6 7 -5
 

Sample Output
Case 1:14 1 4Case 2:7 1 6
 
简单题意:求最大子序列和,并记录序列的起点和终点
解题思路:dp[1]=a[1]  dp[i] = max(dp[i-1]+a[i],a[i]) 如果dp[i-1] < 0起点换为 a[i]
终点为最大的dp[i]的下标,起点为从终点往前第一个小于0的dp[i]的下标
AC代码:
//#include<iostream>#include<cstdio>#include<fstream>#include<algorithm>using namespace std;const int N = 100003;int a[N];int dp[N];int main(){//ifstream cin("1001.txt");int n , t , i , j = 0;scanf("%d",&n);int k = n;while(n --){int imax;int flag = 1,p = 1;scanf("%d",&t);for(i = 1;i <= t;i ++)scanf("%d",&a[i]);dp[1] = a[1];imax = dp[1];for(i = 2;i <= t;i ++)dp[i] = max(dp[i - 1] + a[i],a[i]);for(i = 1;i <= t;i ++)if(dp[i] > imax) {imax = dp[i] ;flag = i;}for(i = flag;i != 0; i--){if(dp[i] <= a[i]){p = i;break;}}printf("Case %d:\n%d %d %d\n",++j,imax,p,flag);if(j != k) printf("\n");}return 0;}


0 0
原创粉丝点击