您的位置:首页 > 其它

UVA--10827 Maximum sum on a torus

2014-11-23 09:22 357 查看
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.

[align=center][/align]
这道题其实就是把一个数组加成了四个数组,例如:
1 2

1 2 1 2

1 2 1 2 但是每次压缩的时候要控制在n以内。

<span style="font-size:14px;">#include<stdio.h>
#include<string.h>
int a[160][160];
int max1d(int a[],int n){
int sum,max_sum=0;
for(int i=0;i<n;i++){
sum=0;
for(int j=i;j<i+n;j++){
sum+=a[j];
if(sum<0)
sum=0;
if(sum>max_sum)
max_sum=sum;
}
}
return max_sum;
}
int main(){
int t;
scanf("%d",&t);
while(t--){
int n;
int max_sum=0;
int s[160];
scanf("%d",&n);
for(int i=0;i<n;i++){
for(int j=0;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];
}
}
/*for(int i=0;i<2*n;i++){
for(int j=0;j<2*n;j++)
printf("%d ",a[i][j]);
printf("\n");
}
printf("\n");*/
for(int i=0;i<n;i++){
memset(s,0,sizeof(s));
for(int j=i;j<i+n;j++){
for(int k=0;k<2*n;k++)
s[k]+=a[j][k];
/*for(int k=0;k<2*n;k++)
printf("%d ",s[k]);
printf("\n");*/
int sum=max1d(s,n);
if(sum>max_sum)
max_sum=sum;
//printf("%d %d\n",sum,max_sum);
}
}
printf("%d\n",max_sum);
}
}
</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: