結果
問題 |
No.2786 RMQ on Grid Path
|
ユーザー |
|
提出日時 | 2024-06-14 23:47:26 |
言語 | C++23 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 652 ms / 6,000 ms |
コード長 | 2,978 bytes |
コンパイル時間 | 2,057 ms |
コンパイル使用メモリ | 126,832 KB |
実行使用メモリ | 63,528 KB |
最終ジャッジ日時 | 2024-06-14 23:47:48 |
合計ジャッジ時間 | 17,935 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 2 |
other | AC * 35 |
ソースコード
#include <iostream> #include <vector> #include <tuple> #include <atcoder/dsu> using namespace std; using namespace atcoder; using ll = long long; constexpr int iINF = 1'000'000'000; constexpr ll llINF = 1'000'000'000'000'000'000; int main () { int H, W; cin >> H >> W; vector<vector<int>> A(H, vector<int>(W)); for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { cin >> A[i][j]; } } auto conv = [&](int i, int j) { return W * i + j; }; vector<vector<pair<int, int>>> inv(H * W + 1); for (int i = 0; i < H; i++) for (int j = 0; j < W; j++) inv[A[i][j]].push_back(make_pair(i, j)); // クエリにオフラインで答えることを考える。小さいコストからマージしていく過程で解がわかればそこで確定させる。 // 更新される可能性があるのはmergeされた連結成分に属するものだけだから、クエリのマージテクみたいなものをするといい感じに解ける気がする。 int Q; cin >> Q; vector<vector<tuple<int, int, int, int, int>>> query(H * W + 1); for (int i = 0; i < Q; i++) { int rs, cs, rt, ct; cin >> rs >> cs >> rt >> ct; rs--, cs--, rt--, ct--; query[conv(rs, cs)].push_back(make_tuple(i, rs, cs, rt, ct)); query[conv(rt, ct)].push_back(make_tuple(i, rs, cs, rt, ct)); } dsu d(H * W); const vector<vector<int>> dxy({ vector<int>({0, 1}), vector<int>({1, 0}), vector<int>({0, -1}), vector<int>({-1, 0}), }); auto is_in = [&](int i, int j) { return 0 <= i && i < H && 0 <= j && j < W; }; vector<int> ans(Q, -1); for (int v = 1; v <= H * W; v++) { // 接続 for (auto pos: inv[v]) { for (auto di: dxy) { if (!is_in(pos.first + di[0], pos.second + di[1])) continue; if (A[pos.first + di[0]][pos.second + di[1]] <= v) { if (d.same(conv(pos.first, pos.second), conv(pos.first + di[0], pos.second + di[1]))) continue; // クエリ回答チャンス int U = d.leader(conv(pos.first, pos.second)), V = d.leader(conv(pos.first + di[0], pos.second + di[1])); d.merge(conv(pos.first, pos.second), conv(pos.first + di[0], pos.second + di[1])); if (U == d.leader(conv(pos.first, pos.second))) swap(U, V); for (auto q: query[U]) { if (ans[get<0>(q)] != -1) continue; if (d.same(conv(get<1>(q), get<2>(q)), conv(get<3>(q), get<4>(q)))) { ans[get<0>(q)] = v; } } // クエリのマージ for (auto q: query[U]) query[V].push_back(q); } } } } for (int i = 0; i < Q; i++) { cout << ans[i] << "\n"; } }