hdu1081 To The Max (dp)

这题要会做前提要会动一行的矩阵如何求最大连续和,然后转换到二维,其实用到了矩阵的压缩,先求出每行到第一行的累加值,然后暴力枚举任意两行,对这两行的压缩完的单行矩阵进行求连续最大和。

#include<iostream>
#include<math.h>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<string>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<stack>
#define B(x) (1<<(x))
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int oo = 0x3f3f3f3f;
const ll OO = 0x3f3f3f3f3f3f3f3f;
const double eps = 1e-9;
#define lson rt<<1
#define rson rt<<1|1
void cmax(int& a, int b){ if (b>a)a = b; }
void cmin(int& a, int b){ if (b<a)a = b; }
void cmax(ll& a, ll b){ if (b>a)a = b; }
void cmin(ll& a, ll b){ if (b<a)a = b; }
void cmax(double& a, double b){ if (a - b < eps) a = b; }
void cmin(double& a, double b){ if (b - a < eps) a = b; }
void add(int& a, int b, int mod){ a = (a + b) % mod; }
void add(ll& a, ll b, ll mod){ a = (a + b) % mod; }
const int MOD = 100007;
const int maxn = 110;
int a[maxn][maxn];

int main(){
	//freopen("E:\\read.txt", "r", stdin);
	int n, b, c;
	while (scanf("%d", &n) != EOF){
		for (int i = 1; i <= n; i++){
			for (int j = 1; j <= n; j++){
				scanf("%d", &a[i][j]);
				a[i][j] += a[i - 1][j];
			}
		}
		int ans = 0;
		for (int i = 1; i <= n; i++){
			for (int j = 1; j <= i; j++){
				int sum = 0, res = 0;
				for (int k = 1; k <= n; k++){
					sum += a[i][k] - a[j - 1][k];
					if (sum < 0)
						sum = 0;
					cmax(res, sum);
				}
				cmax(ans, res);
			}
		}
		printf("%d\n", ans);
	}
	return 0;
}


你可能感兴趣的:(dp,HDU)