POJ 1050 解题报告

这道题有O(N^3)的解法,具体见:http://www.geeksforgeeks.org/dynamic-programming-set-27-max-sum-rectangle-in-a-2d-matrix/

Accepted 288K 16MS C++ 1513B
/* 
ID: thestor1 
LANG: C++ 
TASK: poj1050 
*/
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <limits>
#include <cassert>
#include <string>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <cassert>

using namespace std;

int kadane(const std::vector<int> &nums)
{
	int maxsum = numeric_limits<int>::min(), sum = 0;
	for (int i = 0; i < nums.size(); ++i)
	{
		sum += nums[i];
		if (sum > maxsum)
		{
			maxsum = sum;
		}
		if (sum < 0)
		{
			sum = 0;
		}
	}
	return maxsum;
}

int main()
{
	int N;
	cin >> N;
	std::vector<std::vector<int> > square(N, std::vector<int>(N, 0));
	for (int r = 0; r < N; ++r)
	{
		for (int c = 0; c < N; ++c)
		{
			cin >> square[r][c];
		}
	}

	// cout << "square:" << endl;
	// for (int r = 0; r < N; ++r)
	// {
	// 	for (int c = 0; c < N; ++c)
	// 	{
	// 		cout << square[r][c] << " ";
	// 	}
	// 	cout << endl;
	// }

	int maxsum = numeric_limits<int>::min(), sum;
	std::vector<int> rowsum(N, 0);
	for (int lcol = 0; lcol < N; ++lcol)
	{
		for (int r = 0; r < N; ++r)
		{
			rowsum[r] = 0;
		}
		for (int rcol = lcol; rcol < N; ++rcol)
		{
			for (int r = 0; r < N; ++r)
			{
				rowsum[r] += square[r][rcol];
			}

			sum = kadane(rowsum);
			if (sum > maxsum)
			{
				maxsum = sum;
			}
		}
	}

	cout << maxsum << endl;

	return 0;  
}


你可能感兴趣的:(POJ 1050 解题报告)