Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <bits/stdc++.h>
using namespace std;
//#define int long long
#define FOR(i, j, k) for(int i = j; i < k; ++i)
#define rep(i, j) FOR(i, 0, j)
#define INF 1e9
#define LINF 1e18
#define fi first
#define se second
typedef unsigned long long ull;
typedef pair<int, int> P;
typedef pair<int, P> Pi;
typedef pair<P, P> PP;
const int MOD = 1e9 + 7;
const int dy[] = { 0, 0, 1, -1 };
const int dx[] = { 1, -1, 0, 0 };
template <class T> void chmin(T& a, const T& b) { a = min(a, b); }
template <class T> void chmax(T& a, const T& b) { a = max(a, b); }
int H, W, A[30][30];
P dist[31][31];
int bfs() {
queue<P> que;
que.push(P(0, 0));
while(!que.empty()) {
P p = que.front(); que.pop();
int x = p.second, y = p.first;
rep(i, 4) {
int nx = x + dx[i], ny = y + dy[i];
if(0 <= nx && nx < W && 0 <= ny && ny < H) {
if(dist[ny][nx].fi > dist[y][x].fi + dist[y][x].se * A[ny][nx] * 2 + A[ny][nx]) {
dist[ny][nx].fi = dist[y][x].fi + dist[y][x].se * A[ny][nx] * 2 + A[ny][nx];
dist[ny][nx].se = dist[y][x].se + 1;
que.push(P(ny, nx));
}
}
}
}
return dist[H - 1][W - 1].fi;
}
signed main() {
cin.tie(0);
ios::sync_with_stdio(false);
cin >> H >> W;
rep(i, H) rep(j, W) {
dist[i][j].fi = INF;
cin >> A[i][j];
}
dist[0][0].fi = 0;
cout << bfs() << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.