uva 10827 - Maximum sum on a torus

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

Problem setter: Jimmy Mårdell

Special Thanks: Derek Kisman, Md. Kamruzzaman

uva108加强版,矩形是循环的,补上三个,直觉让我们想到先枚举所有可能出现的矩形,然后套上108的代码,果断TLD,稍微优化了下,还是枚举所有行的组合,再枚举计算最大子序列的起始点,卡着时间过去了
#include<stdio.h>
#include<string.h>
#define inf -9999999
int b[200],n;
int count()
{
 int i,j,f=1,max=inf,sum;
 for (i=1;i<=n;i++)
 {
  if  (b[i]>max) max=b[i];
  if (b[i]>=0)  f=0;
 }
 if (f) return max;
 for (j=1;j<=n;j++)
 {
  sum=0;
  for (i=0;i<n;i++)
  {
   sum=sum+b[i+j];
   if (sum>max) max=sum;
   if (sum<0) sum=0;
  }
 }
 return max;
}
int main()
{
 int T,i,j,p,q,k,t,a[200][200],max,ans,m;
 scanf("%d\n",&T);
 while (T--)
 {
  scanf("%d",&n);
  for (i=1;i<=n;i++)
  for (j=1;j<=n;j++)
  {
   scanf("%d",&a[i][j]);
   a[i+n][j]=a[i][j];
   a[i][j+n]=a[i][j];
   a[i+n][j+n]=a[i][j];
  }
  max=inf;
  for (k=0;k<n;k++)
  {
   for (i=1;i<=2*n;i++)
   {
    if (i+k<=2*n)
    {
      memset(b,0,sizeof(b));
      for (j=i;j<=i+k;j++)
      for (t=1;t<=2*n;t++)
      b[t]+=a[j][t];
      ans=count();
      if (ans>max) max=ans;
    }
   }
  }
  printf("%d\n",max);
 }
 return 0;
}

你可能感兴趣的:(优化,Integer,input,each,setter,output)