Maximum Sum

链接:http://acm.timus.ru/problem.aspx?space=1&num=1146
题目:
Given a 2-dimensional array of positive and negative integers, find the sub-rectangle with the largest sum. The sum of a rectangle is the sum of all the elements in that rectangle. In this problem the sub-rectangle with the largest sum is referred to as the maximal sub-rectangle. A sub-rectangle is any contiguous sub-array of size 1 × 1 or greater located within the whole array.
As an example, the maximal sub-rectangle of the array:
0 −2 −7 0
9 2 −6 2
−4 1 −4 1
−1 8 0 −2
is in the lower-left-hand corner and has the sum of 15.
题意:给一个数字矩阵,用一个矩形框几个数字,求这几个数字的和的最大值为多少。
分析:这道题用到了很巧妙的前缀和用法+尺取法。用二维数组存数据,存的是本列从头到这一项的和。之后枚举矩形的左右两边,尺取上下两边得到最大值。
题解:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <cstring>
#include <functional>
#include <cmath>
using namespace std;


int s[110][110];
int main()
{
	//freopen("in.txt", "r", stdin);
	int n;
	while (~scanf("%d", &n))
	{
		for (int i = 0; i < n; i++)
			for (int j = 0; j < n; j++)
			{
				scanf("%d", &s[i][j]);
				if(j>=1)
					s[i][j] += s[i][j - 1];
			}
		int ans = -10000000;
		
		for (int i = 0; i < n; i++)
			for (int j = i; j < n; j++)
				for (int k = 0, temp = 0; k < n;k++)
				{
					temp += s[k][j] - s[k][i - 1];
					ans = (ans > temp) ? ans : temp;
					if (temp < 0)temp = 0;
				}
		printf("%d\n", ans);
	}
}

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/veget_chicken/article/details/52346196
文章标签: acm 尺取 前缀和
个人分类: 尺取 前缀和
上一篇Chess
下一篇Fourth Point !!
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭