1、http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1768
2、题目大意:
给定一个数字矩阵,求一个最大子矩阵,注意最左边可以和最右边可以作为一个子矩阵,所以需要将原来的矩阵复制成四个矩阵,例如原矩阵为
123
456
789
复制完的矩阵为
123 123
456 456
789 789
123 123
456 456
789 789
然后按照最大子矩阵求,注意控制子矩阵的长度不大于n
2、题目:
Problem H
Maximum sum on a torus
Input: Standard Input
Output: Standard Output
A grid that wraps both horizontally and vertically is called a torus. Given a torus where each cell contains an integer, determine the sub-rectangle with the largest sum. The sum of a sub-rectangle is the sum of all the elements in that rectangle. The grid below shows a torus where the maximum sub-rectangle has been shaded.
1 | -1 | 0 | 0 | -4 |
2 | 3 | -2 | -3 | 2 |
4 | 1 | -1 | 5 | 0 |
3 | -2 | 1 | -3 | 2 |
-3 | 2 | 4 | 1 | -4 |
Input
The first line in the input contains the number of test cases (at most 18). Each case starts with an integer N (1≤N≤75) specifying the size of the torus (always square). Then follows N lines describing the torus, each line containing N integers between -100 and 100, inclusive.
Output
For each test case, output a line containing a single integer: the maximum sum of a sub-rectangle within the torus.
Sample Input Output for Sample Input
2 5 1 -1 0 0 -4 2 3 -2 -3 2 4 1 -1 5 0 3 -2 1 -3 2 -3 2 4 1 -4 3 1 2 3 4 5 6 7 8 9 | 15 45 |
3、代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[160][160];
int dp[160];
int b[160];
int maxsum(int *bb,int n)
{
int maxx=-9999999;
int max=-9999999;
int i,j;
for(j=1; j<=n; j++)
{
memset(b,0,sizeof(b));
b[j-1]=maxx;
for(i=j; i<j+n&&j+n<=2*n; i++)
{
if(b[i-1]>0)
b[i]=b[i-1]+bb[i];
if(b[i-1]<0)
b[i]=bb[i];
if(b[i]>max)
max=b[i];
}
//printf("&&&%d %d %d %d\n",j,i-1,max,b[i-1]);
}
//printf("\n");
return max;
}
int main()
{
int n,t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
int max=-99999999;
memset(dp,0,sizeof(dp));
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
scanf("%d",&a[i][j]);
a[i][j+n]=a[i+n][j]=a[i+n][j+n]=a[i][j];
}
}
// for(int i=1;i<=n+n;i++)
// {
// for(int j=1;j<=n+n;j++)
// printf("%d ",a[i][j]);
// printf("\n");
// }
for(int i=1; i<=2*n; i++)
{
memset(dp,0,sizeof(dp));
for(int j=i; j<i+n&&i+n<=2*n; j++)
{
for(int k=1; k<=2*n; k++)
{
dp[k]+=a[j][k];
//printf("$$$%d %d %d \n",i,j,dp[k]);
}
//printf("\n");
int sum=maxsum(dp,n);
if(sum>max)
max=sum;
}
memset(dp,0,sizeof(dp));
}
printf("%d\n",max);
}
return 0;
}
/*
2
5
1 -1 0 0 -4
2 3 -2 -3 2
4 1 -1 5 0
3 -2 1 -3 2
-3 2 4 1 -4
3
1 2 3
4 5 6
7 8 9
*/