結果
問題 | No.367 ナイトの転身 |
ユーザー |
|
提出日時 | 2021-02-14 01:15:04 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 78 ms / 2,000 ms |
コード長 | 2,906 bytes |
コンパイル時間 | 1,373 ms |
コンパイル使用メモリ | 141,288 KB |
最終ジャッジ日時 | 2025-01-18 20:16:01 |
ジャッジサーバーID (参考情報) |
judge3 / judge5 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 27 |
ソースコード
#include <iostream> #include <vector> #include <algorithm> #include <cmath> #include <queue> #include <string> #include <map> #include <set> #include <stack> #include <tuple> #include <deque> #include <array> #include <numeric> #include <bitset> #include <iomanip> #include <cassert> #include <chrono> #include <random> #include <limits> #include <iterator> #include <functional> #include <sstream> #include <fstream> #include <complex> #include <cstring> #include <unordered_map> #include <unordered_set> using namespace std; using ll = long long; constexpr int INF = 1001001001; constexpr int mod = 1000000007; // constexpr int mod = 998244353; template<class T> inline bool chmax(T& x, T y){ if(x < y){ x = y; return true; } return false; } template<class T> inline bool chmin(T& x, T y){ if(x > y){ x = y; return true; } return false; } constexpr int knight_dx[8] = {1, 1, -1, -1, 2, 2, -2, -2}; constexpr int knight_dy[8] = {2, -2, 2, -2, 1, -1, 1, -1}; constexpr int bishop_dx[4] = {1, 1, -1, -1}; constexpr int bishop_dy[4] = {1, -1, 1, -1}; int dp[505][505][2]; int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int H, W; cin >> H >> W; vector<string> s(H); int sx = 0, sy = 0, gx = 0, gy = 0; for(int i = 0; i < H; ++i){ cin >> s[i]; for(int j = 0; j < W; ++j){ if(s[i][j] == 'S') sx = i, sy = j; if(s[i][j] == 'G') gx = i, gy = j; } } for(int i = 0; i < H; ++i){ for(int j = 0; j < W; ++j){ for(int k = 0; k < 2; ++k){ dp[i][j][k] = INF; } } } dp[sx][sy][0] = 0; using node = tuple<int, int, int, int>; priority_queue<node, vector<node>, greater<node>> que; que.emplace(0, sx, sy, 0); while(!que.empty()){ auto [d, x, y, t] = que.top(); que.pop(); if(d > dp[x][y][t]) continue; if(t == 0){ for(int i = 0; i < 8; ++i){ int nx = x + knight_dx[i], ny = y + knight_dy[i]; if(nx < 0 || nx >= H || ny < 0 || ny >= W) continue; int nt = s[nx][ny] == 'R' ? (t ^ 1) : t; if(chmin(dp[nx][ny][nt], dp[x][y][t] + 1)){ que.emplace(dp[nx][ny][nt], nx, ny, nt); } } } else{ for(int i = 0; i < 4; ++i){ int nx = x + bishop_dx[i], ny = y + bishop_dy[i]; if(nx < 0 || nx >= H || ny < 0 || ny >= W) continue; int nt = s[nx][ny] == 'R' ? (t ^ 1) : t; if(chmin(dp[nx][ny][nt], dp[x][y][t] + 1)){ que.emplace(dp[nx][ny][nt], nx, ny, nt); } } } } int ans = min(dp[gx][gy][0], dp[gx][gy][1]); if(ans == INF) ans = -1; cout << ans << endl; return 0; }