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>
#define F first
#define S second
using namespace std;
const int maxn = 50005;
struct Query {
int u, v, id;
};
int n, m, o, k;
vector<pair<int, int> > adj[maxn], rev_adj[maxn];
int ans[maxn], dis[5][maxn][5]; // [start, block, position]
void divide_and_conquer(int l, int r, vector<Query> query) {
if (l == r) {
for (auto x : query) {
ans[x.id] = -1;
}
return;
}
int mid = (l + r) >> 1;
for (int i = 0; i < k; ++ i) {
for (int j = 0; j < k; ++ j) dis[i][mid][j] = 1e9;
dis[i][mid][i] = 0;
}
for (int i = mid; i > l; -- i) {
for (int j = 0; j < k; ++ j) {
for (int j1 = 0; j1 < k; ++ j1) dis[j][i - 1][j1] = 1e9;
for (int j1 = 0; j1 < k; ++ j1) {
int u = i * k + j1;
for (auto v : rev_adj[u]) {
int j2 = v.F % k;
dis[j][i - 1][j2] = min(dis[j][i - 1][j2], dis[j][i][j1] + v.S);
}
}
}
}
for (int i = 0; i < k; ++ i) {
for (int j = 0; j < k; ++ j) dis[i][mid + 1][j] = 1e9;
dis[i][mid + 1][i] = 0;
}
for (int i = mid + 1; i < r; ++ i) {
for (int j = 0; j < k; ++ j) {
for (int j1 = 0; j1 < k; ++ j1) dis[j][i + 1][j1] = 1e9;
for (int j1 = 0; j1 < k; ++ j1) {
int u = i * k + j1;
for (auto v : adj[u]) {
int j2 = v.F % k;
dis[j][i + 1][j2] = min(dis[j][i + 1][j2], dis[j][i][j1] + v.S);
}
}
}
}
vector<Query> shorter_query[2];
for (auto p : query) {
int u = p.u, v = p.v, id = p.id;
int L = u / k, R = v / k;
if (L > mid) shorter_query[1].push_back(p);
else if (R <= mid) shorter_query[0].push_back(p);
else {
ans[id] = 1e9;
for (int i = 0; i < k; ++ i) {
int u1 = mid * k + i;
for (auto x : adj[u1]) {
int v1 = x.F;
int j = v1 % k;
ans[id] = min(ans[id], dis[i][L][u % k] + dis[j][R][v % k] + x.S);
}
}
if (ans[id] == 1e9) ans[id] = -1;
}
}
divide_and_conquer(l, mid, shorter_query[0]);
divide_and_conquer(mid + 1, r, shorter_query[1]);
}
void solve() {
cin >> k >> n >> m >> o;
for (int i = 1; i <= m; ++ i) {
int u, v, w; cin >> u >> v >> w;
adj[u].push_back({v, w});
rev_adj[v].push_back({u, w});
}
vector<Query> query;
for (int i = 1; i <= o; ++ i) {
int u, v; cin >> u >> v;
query.push_back({u, v, i});
}
divide_and_conquer(0, (n - 1) / k, query);
for (int i = 1; i <= o; ++ i) {
cout << ans[i] << "\n";
}
}
signed main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
solve();
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... |