結果
| 問題 |
No.1323 うしらずSwap
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2020-12-16 01:29:24 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 1,543 ms / 3,000 ms |
| コード長 | 3,092 bytes |
| コンパイル時間 | 3,806 ms |
| コンパイル使用メモリ | 206,672 KB |
| 最終ジャッジ日時 | 2025-01-17 01:35:47 |
|
ジャッジサーバーID (参考情報) |
judge2 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 59 |
ソースコード
#include <bits/stdc++.h>
using namespace std;
constexpr int inf = 1001001001;
constexpr int dy[] = {-1, 0, 1, 0};
constexpr int dx[] = {0, 1, 0, -1};
using Graph = vector< vector< int > >;
int main() {
int h, w;
cin >> h >> w;
auto to_v = [w](int y, int x) {
return y * w + x;
};
auto from_v = [w](int v, int &y, int &x) {
y = v / w;
x = v % w;
};
int Ya, Xa, Yb, Xb;
cin >> Ya >> Xa >> Yb >> Xb;
Ya -= 1; Xa -= 1;
Yb -= 1; Xb -= 1;
int a = to_v(Ya, Xa);
int b = to_v(Yb, Xb);
vector< string > ss(h);
for (auto &s : ss) cin >> s;
ss[Ya][Xa] = 'A';
ss[Yb][Xb] = 'B';
int V = to_v(h, w);
auto make_graph = [&](const vector< string > &ss) {
Graph G(V);
for (int y = 1; y + 1 < h; y++) {
for (int x = 1; x + 1 < w; x++) {
if (ss[y][x] == '#') continue;
int v = to_v(y, x);
for (int i = 0; i < 4; i++) {
int ny = y + dy[i];
int nx = x + dx[i];
if (ss[ny][nx] == '#') continue;
int u = to_v(ny, nx);
G[v].emplace_back(u);
}
}
}
return G;
};
vector< int > pre(V, -1);
auto bfs = [&](int s, const Graph &G) {
int n = G.size();
vector< pair< int, int > > d(n, {inf, 0});
queue< int > que;
que.push(s);
d[s] = make_pair(0, 1);
while (not que.empty()) {
int v = que.front();
que.pop();
for (auto &u : G[v]) {
if (d[u].first < d[v].first + 1) continue;
if (d[u].first == d[v].first + 1) {
d[u].second = 2;
continue;
}
d[u] = d[v];
d[u].first += 1;
que.push(u);
pre[u] = v;
}
}
return d;
};
auto G = make_graph(ss);
auto bs = bfs(b, G);
auto as = bfs(a, G);
int ans = inf;
if (as[b].second == 0) {
ans = -1;
}
if (as[b].second >= 2) {
ans = 2 * as[b].first;
}
if (as[b].second != 0) {
int v = pre[b];
while (v != a) {
int y, x;
from_v(v, y, x);
ss[y][x] = 'x';
v = pre[v];
}
}
for (int y = 1; y + 1 < h; y++) {
for (int x = 1; x + 1 < w; x++) {
if (ss[y][x] != 'x') continue;
for (int i = 0; i < 4; i++) {
int ny = y + dy[i];
int nx = x + dx[i];
if (ss[ny][nx] == '.') {
ans = min(ans, 2 * as[b].first + 2);
}
}
}
}
for (int v = 0; v < V; v++) {
if (as[v].second == 0) continue;
if ((int)G[v].size() < 3) continue;
int cost = 2 * (as[v].first + bs[v].first) + 4;
ans = min(ans, cost);
}
{
for (int y = 1; y + 1 < h; y++) {
for (int x = 1; x + 1 < w; x++) {
if (ss[y][x] != 'x') continue;
ss[y][x] = '#';
}
}
ss[Yb][Xb] = '#';
G = make_graph(ss);
auto nas = bfs(a, G);
for (int i = 0; i < 4; i++) {
int y = Yb + dy[i];
int x = Xb + dx[i];
int v = to_v(y, x);
if (v == a) continue;
if (nas[v].second == 0) continue;
ans = min(ans, as[b].first + nas[v].first + 1);
}
}
if (ans == inf) ans = -1;
cout << ans << endl;
}