結果
問題 | No.367 ナイトの転身 |
ユーザー |
![]() |
提出日時 | 2016-04-29 23:17:06 |
言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 219 ms / 2,000 ms |
コード長 | 3,011 bytes |
コンパイル時間 | 1,061 ms |
コンパイル使用メモリ | 114,544 KB |
実行使用メモリ | 73,704 KB |
最終ジャッジ日時 | 2024-10-11 00:17:34 |
合計ジャッジ時間 | 2,687 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 27 |
ソースコード
#include<cstdio>#include<cstdlib>#include<cstring>#include<cmath>//#include<cctype>#include<climits>#include<iostream>#include<string>#include<vector>#include<map>//#include<list>#include<queue>#include<deque>#include<algorithm>//#include<numeric>#include<utility>#include<complex>//#include<memory>#include<functional>#include<cassert>#include<set>#include<stack>#include<random>using namespace std;typedef long long ll;typedef unsigned long long ull;typedef vector<int> vi;typedef vector<ll> vll;typedef pair<int, int> pii;int knightX[] = {2, 1, -1, -2, -2, -1, 1, 2};int knightY[] = {1, 2, 2, 1, -1, -2, -2, -1};int miniX[] = {1, -1, -1, 1};int miniY[] = {1, 1, -1, -1};const int MAXH = 555;string board[MAXH];struct edge {int v;ll w;edge() {}edge(int v, ll w) : v(v), w(w) {};};vector<ll> dijkstra(int n, vector<vector<edge> >& G, int s) {vector<ll> d(n, LLONG_MAX/10); d[s] = 0;priority_queue<pair<ll, int> > que;que.push(make_pair(0ll, s));while (!que.empty()) {auto p = que.top(); que.pop();int u = p.second;ll dist = -p.first;if (dist > d[u]) continue;for (edge e : G[u]) {if (d[e.v] > d[u]+e.w) {d[e.v] = d[u] + e.w;que.push(make_pair(-d[e.v], e.v));}}}return d;}int H, W;bool inRange(int y, int x) {return 0 <= y && y < H && 0 <= x && x < W;}int getIndex(int y, int x, int flag) {return flag*H*W+y*W+x;}int main() {cin.tie(0);ios::sync_with_stdio(false);cin >> H >> W;int sy = -1, sx = -1, gy = -1, gx = -1;for (int i = 0; i < H; i++) {cin >> board[i];for (int j = 0; j < W; j++) {if (board[i][j] == 'S') sy = i, sx = j;if (board[i][j] == 'G') gy = i, gx = j;}}vector<vector<edge> > G(2*H*W);for (int y = 0; y < H; y++) for (int x = 0; x < W; x++) {for (int flag = 0; flag < 2; flag++) {if (!flag) {for (int k = 0; k < 8; k++) {int ny = y+knightY[k], nx = x+knightX[k];if (!inRange(ny, nx)) continue;int nflag = flag;if (board[ny][nx] == 'R') nflag ^= 1;G[getIndex(y, x, flag)].emplace_back(getIndex(ny, nx, nflag), 1);}} else {for (int k = 0; k < 4; k++) {int ny = y+miniY[k], nx = x+miniX[k];if (!inRange(ny, nx)) continue;int nflag = flag;if (board[ny][nx] == 'R') nflag ^= 1;G[getIndex(y, x, flag)].emplace_back(getIndex(ny, nx, nflag), 1);}}}}auto d = dijkstra(2*H*W, G, getIndex(sy, sx, 0));ll ans = min(d[getIndex(gy, gx, 0)], d[getIndex(gy, gx, 1)]);if (ans > 1ll<<55) ans = -1;cout << ans << endl;return 0;}