我的第一篇博客以及HDU 1003 Max Sum

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/h84121599/article/details/50808224

以前都是看别人博客,今天我终于有了自己的博客。我会把我在ACM的成长一篇篇记录下来。。fighting,厚积薄发。

接下来是正题了

先把题目贴上来:

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


2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5

SAMPLE OUTPUT


Case 1:
14 1 4

Case 2:
7 1 6


这题是经典的动态规划,还不是很难。我刚接触动态规划没多久,这题正好练练手熟悉一下。

毕竟英文题比较多,以前看别人博客的时候,有些英文题博主没翻译,我英语又不好,看得很麻烦。所以 我以后写英文题的话,尽量把每道题的题目翻译都一起写下来。

题目大概是是说给你一串数字,你选择两个数字,把它们之间所有的数相加,使得到的和最大,输出最大值以及开始的加的数以及结束的数。比如第一组6 -1 5 4 -7,从第一个6加到第四个4,6+(-1)+5+4+(-7)=14。

可以从第一个开始每个位置能得到的最大的和依次算出来。除了第一个位置,其他位置都能选择的加上或者不加前一个数的最大和来得到自己的最大和。同时我用m标记最大的位置。

代码如下:
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
#define MAX 100005
int a[MAX] = { 0 };//储存数字
int dp[MAX]={ 0 };//储存每个数能得到的最大和
int s[MAX];//当前位置得到的最大和是从哪个数字开始的
int main()
{
	int N,o;
	cin >> N;
	for (o = 1; o <= N; o++){
		int n, i,m=0,ans=0;
		cin >> n;
		for (i = 0; i < n; i++){
			cin >> a[i];
		}
		for (i = 0; i < n; i++)
		{
			if (i > 0){
				if (dp[i - 1] >= 0){
					dp[i] = dp[i - 1] + a[i];
					s[i] = s[i - 1];
				}
				else {
					dp[i] = a[i];
					s[i] = i;
				}
			}
			else{
				dp[i] = (0, a[i]);
				s[i] = 0;
			}
			if (dp[m] < dp[i]){
				m = i;
			}
		}
		if (o-1)cout<<endl;//每两组数据之间隔一行
		cout << "Case " << o << ':'<< endl << dp[m] << ' ' << s[m]+1 << ' ' << m+1 << endl;

	}
	return 0;
}

我方法还不够简便,代码也不够简洁,希望以后越做越好。

坚持就是胜利!

猜你喜欢

转载自blog.csdn.net/h84121599/article/details/50808224
今日推荐