码迷,mamicode.com
首页 > 其他好文 > 详细

HDU - 1003 - Max Sum && POJ - 1050 - To the Max (经典DP问题)

时间:2015-05-07 08:49:44      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:acm   poj   dp   


题目传送:HDU - 1003


思路:最大子序列和

dp[i]= a[i]   (dp[i-1]<0)

dp[i]= dp[i-1]+a[i]   (dp[i-1]>=0)


AC代码:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <deque>
#include <cctype>
#define LL long long
#define INF 0x7fffffff
using namespace std;

int n;

int main() {
	int T;
	int cas = 1;
	scanf("%d", &T);
	while(T --) {
		scanf("%d", &n);
		int sum = 0;
		int ans = -INF;
		int from, to;
		int qi = 1, zhong = 1;
		for(int i = 1; i <= n; i ++) {
			int t;
			scanf("%d", &t);
			sum += t;
			zhong = i;
			if(sum > ans) {
				ans = sum; from = qi; to = zhong; 
			}
			if(sum < 0) {
				qi = i + 1; sum = 0;
			}
		}
		printf("Case %d:\n%d %d %d\n", cas ++, ans, from, to);
		if(T != 0) printf("\n");
	}
	return 0;
}



题目传送:POJ - 1050


思路:最大子矩阵和,原理和上面那个题一样,就是把i~j行的列上的数加到一行去,再算该行的最大子序列和即可(0<=i<=j <n)


AC代码:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <deque>
#include <cctype>
#define LL long long
#define INF 0x7fffffff
using namespace std;

int a[105][105];
int tmp[105];
int n;

int fun() {
	int max = -1, sum = 0;
	for(int i = 0; i < n; i ++) {
		sum += tmp[i];
		if(sum > max) max = sum;
		if(sum < 0) sum = 0;
	}
	return max;
}

int main() {
	while(scanf("%d", &n) != EOF) {
		for(int i = 0; i < n; i ++) {
			for(int j = 0; j < n; j ++) {
				scanf("%d", &a[i][j]);
			}
		}
		
		int ans = -1;
		for(int i = 0; i < n; i ++) {
			memset(tmp, 0, sizeof(tmp));
			for(int j = i; j < n; j ++) {
				for(int k = 0; k < n; k ++) {
					tmp[k] += a[j][k];
				}
				int t = fun();
				if(ans < t) ans = t;
			}
		}
		cout << ans << endl;
	}
	return 0;
}













HDU - 1003 - Max Sum && POJ - 1050 - To the Max (经典DP问题)

标签:acm   poj   dp   

原文地址:http://blog.csdn.net/u014355480/article/details/45545861

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!