hdu 1003 Max Sum(简单DP)

http://acm.hdu.edu.cn/showproblem.php?pid=1003

题意:求连续子区间的最大和。

思路:dp[ i ]表示以i结尾的序列的最大和。那么 dp[ i ] = max( dp[i-1] + a[i], a[i])。

#include <stdio.h>
#include <string.h>

int dp[100010],a[100010];
int main()
{
	int test;
	scanf("%d",&test);
	for(int item = 1; item <= test; item++)
	{
		int n;
		scanf("%d",&n);
		for(int i = 1; i <= n; i++)
			scanf("%d",&a[i]);

		dp[1] = a[1];
		for(int i = 2; i <= n; i++)
		{
			if(dp[i-1] < 0)
				dp[i] = a[i];
			else dp[i] = dp[i-1]+a[i];
		}

		int maxsum = dp[1];
		int end = 1;
		for(int i = 2; i <= n; i++)
		{
			if(dp[i] >= maxsum)
			{
				maxsum = dp[i];
				end = i;
			}
		}

		int sum = 0;
		int start = end;
		for(int i = end; i >= 1; i--)
		{
			sum += a[i];
			if(sum == maxsum)
				start = i;
		}
		printf("Case %d:\n",item);
		printf("%d %d %d\n",maxsum,start,end);
		if(item < test)
			printf("\n");
	}
	return 0;
}


你可能感兴趣的:(dp)