読者です 読者をやめる 読者になる 読者になる

mayoko’s diary

プロコンとかいろいろ。

yukicoder No.367 ナイトの転身

解法

2*H*W の頂点を作って適切に辺を貼ってダイクストラすれば良いです。

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;
}