P2213 [USACO14MAR]懒惰的牛The Lazy Cow_Sliver
题目描述
It's a hot summer day, and Bessie the cow is feeling quite lazy. She wants
to locate herself at a position in her field so that she can reach as much
delicious grass as possible within only a short distance.
The field Bessie inhabits is described by an N by N grid of square cells
(1 <= N <= 400). The cell in row r and column c (1 <= r,c <= N) contains
G(r,c) units of grass (0 <= G(r,c) <= 1000). From her initial square in
the grid, Bessie is only willing to take up to K steps (0 <= K <= 2*N).
Each step she takes moves her to a cell that is directly north, south,
east, or west of her current location.
For example, suppose the grid is as follows, where (B) describes Bessie's
50 5 25* 6 17
14 3* 2* 7* 21
99* 10* 1*(B) 2* 80*
8 7* 5* 23* 11
10 0 78* 1 9
initial position (here, in row 3, column 3):
If K=2, then Bessie can only reach the locations marked with *s.
Please help Bessie determine the maximum amount of grass she can reach, if
she chooses the best possible initial location in the grid.
奶牛贝西非常懒惰,她希望在她的地盘内找到一点最佳位置居住,以便在有限的步数内可以吃到尽量多的青草。
她的地盘是一个N行N列(1 <= N <= 400)的矩阵,第r行c列包含G(r,c)单位的青草(0 <= G(r,c) <= 1000)。从她的居住点,她最多愿意走K步(0 <= K <= 2*N),每一步她可以找到上、下、左、右直接相邻的某个格子。
输入格式
* Line 1: The integers N and K.
* Lines 2..1+N: Line r+1 contains N integers describing row r of the
grid.
输出格式
* Line 1: The maximum amount of grass Bessie can reach, if she chooses
the best possible initial location (the location from which
she can reach the most grass).
输入输出样例
5 2 50 5 25 6 17 14 3 2 7 21 99 10 1 2 80 8 7 5 23 11 10 0 78 1 9
342
说明/提示
OUTPUT DETAILS:
In the example above, Bessie can reach 342 total units of grass if she
locates herself in the middle of the grid.
Source: USACO 2014 March Contest, Silver
代码
#include<cmath> #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; const int N=1010; int n,m,k,x,y,xl,yl,xr,yr; int ans=-0x7fffffff,a[N][N],b[N*2][N*2]; int main () { scanf("%d%d",&n,&k); for(int i=1; i<=n; i++) for(int j=1; j<=n; j++) scanf("%d",&a[i][j]); m=n*2-1; for(int i=1; i<=n; i++) for(int j=1; j<=n; j++) b[i+j-1][n-i+j]=a[i][j]; for(int i=1; i<=m; i++) for(int j=1; j<=m; j++) b[i][j]+=b[i][j-1]; for(int i=1; i<=m; i++) for(int j=1; j<=m; j++) b[i][j]+=b[i-1][j]; for(int i=1; i<=n; i++) for(int j=1; j<=n; j++) { x=i+j-1,y=n-i+j; xl=x-k,yl=y-k,xr=x+k,yr=y+k; if(xl<1) xl=1; if(yl<1) yl=1; if(xr>m) xr=m; if(yr>m) yr=m; ans=max(ans,b[xr][yr]-b[xr][yl-1]-b[xl-1][yr]+b[xl-1][yl-1]); } printf("%d\n",ans); return 0; }