思路先算到一个点的最大值,再算以后停留在一个点的值,相加求最值。
#include<bits/stdc++.h>
using namespace std;
#pragma GCC optimize("O1,O2,O3,O4,O5,Og,Os,Ofast,inline")
#define int long long
int h,w,k,sx,sy,a[55][55],dp[55][55] = {{0}},vis[55][55] = {{0}},ans = 0;
struct point{
int x,y,step = 1;
};
queue<point> q;
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
void bfs(int x,int y){
point p;
p.x = x,p.y = y;
q.push(p);
while(!q.empty()){
point tmp = q.front();
q.pop();
if(tmp.step>k) continue;
for(int i = 0;i<4;i++){
point np = tmp;
np.x+=dx[i],np.y+=dy[i],np.step++;
if(np.x<1||np.x>h||np.y<1||np.y>w||(vis[np.x][np.y]<np.step&&vis[np.x][np.y]!=0)) continue;
if(!vis[np.x][np.y]) q.push(np);
dp[np.x][np.y] = max(dp[np.x][np.y],a[np.x][np.y]+dp[tmp.x][tmp.y]);
vis[np.x][np.y] = np.step;
}
}
}
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> h >> w >> k >> sx >> sy;
for(int i = 1;i<=h;i++)
for(int j = 1;j<=w;j++)
cin >> a[i][j];
vis[sx][sy] = 1;
bfs(sx,sy);
for(int i = 1;i<=h;i++)
for(int j = 1;j<=w;j++)
ans = max(ans,dp[i][j]+(k-abs(i-sx)-abs(j-sy))*a[i][j]);
cout << ans;
return 0;
}