This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
const int N = 5e4 + 5;
const int O = 1e4 + 5;
const int K = 6;
const int INF = 1e9;
int k, n, m, o;
vector<array<int, 3>> g[K][N], rg[K][N];
int ans[O];
int d[K][N], rd[K][N];
void bfs(int row, int col, int r) {
for (int i = 0; i < k; i++) {
for (int j = col; j <= r; j++) {
d[i][j] = INF;
}
}
priority_queue<pair<int, pair<int, int>>> pq;
d[row][col] = 0;
pq.push({-d[row][col], {row, col}});
while (!pq.empty()) {
int cd = -pq.top().first;
int x = pq.top().second.first;
int y = pq.top().second.second;
pq.pop();
if (cd != d[x][y]) {
continue;
}
for (auto &nxt : g[x][y]) {
if (nxt[1] > r) {
continue;
}
if (d[nxt[0]][nxt[1]] > d[x][y] + nxt[2]) {
d[nxt[0]][nxt[1]] = d[x][y] + nxt[2];
pq.push({-d[nxt[0]][nxt[1]], {nxt[0], nxt[1]}});
}
}
}
}
void sfb(int row, int col, int l) {
for (int i = 0; i < k; i++) {
for (int j = col; j >= l; j--) {
rd[i][j] = INF;
}
}
priority_queue<pair<int, pair<int, int>>> pq;
rd[row][col] = 0;
pq.push({-rd[row][col], {row, col}});
while (!pq.empty()) {
int cd = -pq.top().first;
int x = pq.top().second.first;
int y = pq.top().second.second;
pq.pop();
if (cd != rd[x][y]) {
continue;
}
for (auto &nxt : rg[x][y]) {
if (nxt[1] < l) {
continue;
}
if (rd[nxt[0]][nxt[1]] > rd[x][y] + nxt[2]) {
rd[nxt[0]][nxt[1]] = rd[x][y] + nxt[2];
pq.push({-rd[nxt[0]][nxt[1]], {nxt[0], nxt[1]}});
}
}
}
}
void solve(int l, int r, vector<array<int, 5>> &q) {
if (q.empty()) {
return;
}
int m = (l + r) >> 1;
vector<array<int, 5>> ql, qr, qc;
for (auto &x : q) {
if (x[3] < m) {
ql.emplace_back(x);
} else if (x[1] > m) {
qr.emplace_back(x);
} else {
qc.emplace_back(x);
}
}
for (int row = 0; row < k; row++) {
bfs(row, m, r);
sfb(row, m, l);
for (auto &x : qc) {
ans[x[4]] = min(ans[x[4]], rd[x[0]][x[1]] + d[x[2]][x[3]]);
}
}
solve(l, m - 1, ql);
solve(m + 1, r, qr);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> k >> n >> m >> o;
for (int i = 0; i < m; i++) {
int a, b, t;
cin >> a >> b >> t;
g[a % k][a / k].push_back({b % k, b / k, t});
rg[b % k][b / k].push_back({a % k, a / k, t});
}
vector<array<int, 5>> que(o);
for (int i = 0; i < o; i++) {
int a, b;
cin >> a >> b;
que[i] = {a % k, a / k, b % k, b / k, i};
}
for (int i = 0; i < o; i++) {
ans[i] = INF;
}
solve(0, n - 1, que);
for (int i = 0; i < o; i++) {
if (ans[i] == INF) {
ans[i] = -1;
}
cout << ans[i] << '\n';
}
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |