這是一個好題。
剛開始看沒想深,沒發現什麼規律,感覺得直接爆,但這會超時。後來仔細想了想,奧祕就在這螺旋中。
由3層螺旋的值,可以得到5層螺旋的值,依次類推,條件是中心不變,依次向外擴。
那麼如何由3層值得到5層值呢?假設3層值爲A,擴到5層後,假設5層內的所有值的和爲B,則5層螺旋的值爲B-A,是不是很神奇,至於爲什麼是,你用筆畫畫就知道了,其餘層數依次類推。
我們可以O(n^2)的預處理,求出各個點的和,然後O(n^2*k)來求最優值。其中n^2來枚舉,k是每個點的擴展層數之和,我也估不出是多少,在極限情況下是250,但也是極限情況下一個點這樣,平均情況應該遠遠小於這個值,沒有別的方法,只能試試。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int mat[510][510], sum[510][510];
int n, m;
bool ok(int x, int y)
{
if(x >= 0 && x < n && y >= 0 && y < m)
return true;
return false;
}
int main()
{
//freopen("input.txt", "r", stdin);
scanf("%d %d", &n, &m);
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
scanf("%d", &mat[i][j]);
memset(sum, 0, sizeof(sum));
for(int i = n - 1; i >= 0; i--){
int t = 0;
for(int j = m - 1; j >= 0; j--){
t += mat[i][j];
sum[i][j] = sum[i + 1][j] + t;
}
}
int ans = -1000000000;
for(int i = 1; i < n; i++){
for(int j = 1; j < m; j++){
int x = i, y = j;
int t = mat[i][j];
int l = 1;
while(true){
x--, y--;
l += 2;
if(ok(x, y) && (x + l - 1) < n && (y + l - 1) < m){
t += mat[x + 1][y];
int s = sum[x][y] - sum[x + l][y] - sum[x][y + l] + sum[x + l][y + l];
t = s - t;
ans = max(ans, t);
}else break;
}
}
}
printf("%d\n", ans);
return 0;
}