杭电ACM-HDU1003-Max Sum

题目来自杭电ACM: acm.hdu.edu.cn

Max Sum

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 188070    Accepted Submission(s): 43819



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

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
 

Author
Ignatius.L

C语言代码如下:

#include 
#define N 100010
int a[N], sum[N];
int main()
{
	int count, n, i, maxSum, x, y;
	scanf("%d", &count);
	int k = count;
	while(count--){
		scanf("%d", &n);
		for (i = 1; i <= n; i++)
			scanf("%d", &a[i]);
		sum[1] = a[1];
		maxSum = sum[1];
		y = 1;
		for (i = 2; i <= n; i++){
			if (sum[i-1] > 0)
				sum[i] = sum[i-1] + a[i];
			else
				sum[i] = a[i];
		}
		for (i = 2; i <= n; i++){
			if (sum[i] > maxSum){
				maxSum = sum[i];
				y = i;
			}		
		}
		int t = 0;
		x = y;
		for(i = y; i > 0; i--)
        {
            t += a[i];
            if(t == maxSum)
				x = i;
        }
		printf("Case %d:\n", k - count);
		printf("%d %d %d\n", maxSum, x, y);
		if (count)
			printf("\n");
	}
	return 0;
}

C++代码如下:

#include 
using namespace std;
const int maxn = 1000010;
const int INF = 1000000000; 
int s[maxn],dp[maxn],pre[maxn];
int main()
{
	int t;
	cin >> t;
	for(int i = 1 ; i <= t ; ++ i) {
		if(i > 1) {
			cout << endl;
		} 
		int n;
		cin >> n;
		for(int j = 1 ; j <= n ; ++ j) {
			cin >> s[j];
		}
		dp[1] = s[1];
		pre[1] = 1;
		for(int j = 2 ; j <= n ; ++ j) {
			if(dp[j-1] > 0) {
				dp[j] = dp[j-1] + s[j];
			} else {
				dp[j] = s[j];
			}
			if(dp[j-1] >= 0) {
				pre[j] = pre[j-1];
			}else {
				pre[j] = j;
			} 
		}
		cout << "Case " << i << ":" << endl;
		int max = -INF;
		int end = 1;
		for(int j = 1 ; j <= n ; ++ j) {
			if(dp[j] > max) {
				max = dp[j];
				end = j;
			}
		}
		cout << max << " " << pre[end] << " " << end << endl;
	}
	return 0;
}


本题涉及到动态规划(DP)的算法,如果使用枚举的话,算法的时间复杂度太大,关于动态规划算法的详细,可百度或查找有关书籍进行了解,我也是通过这道题第一次接触DP算法,今后有更多这样的题目,待熟悉后再写一篇详细的关于动态规划的文章。

你可能感兴趣的:(C++,C,ACM,算法-动态规划)