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;
struct query
{
int a, b, id, ans;
} queries[N];
int k, n, m, o, cost[N][5][5];
void dnc(int l, int r, int level = 0)
{
if (l == r) return;
int mid = (l+r)/2, L[n/k+1][k][k], R[n/k+1][k][k];
for (int i = l; i <= r; i++)
for (int a = 0; a < k; a++)
for (int b = 0; b < k; b++)
L[i][a][b] = R[i][a][b] = 1e9;
for (int a = 0; a < k; a++)
L[mid][a][a] = 0;
for (int i = mid-1; i >= l; i--)
for (int a = 0; a < k; a++)
for (int b = 0; b < k; b++)
for (int c = 0; c < k; c++)
L[i][a][c] = min(L[i][a][c], L[i+1][b][c]+cost[i][a][b]);
for (int a = 0; a < k; a++)
for (int b = 0; b < k; b++)
R[mid+1][a][b] = cost[mid][a][b];
for (int i = mid+2; i <= r; i++)
for (int a = 0; a < k; a++)
for (int b = 0; b < k; b++)
for (int c = 0; c < k; c++)
R[i][c][a] = min(R[i][c][a], R[i-1][c][b]+cost[i-1][b][a]);
for (int i = 0; i < o; i++)
{
int a = queries[i].a, b = queries[i].b;
if (l <= a/k && a/k <= mid && mid+1 <= b/k && b/k <= r)
for (int j = 0; j < k; j++)
queries[i].ans = min(queries[i].ans, L[a/k][a%k][j]+R[b/k][j][b%k]);
}
dnc(l, mid, level+1);
dnc(mid+1, r, level+1);
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> k >> n >> m >> o;
for (int i = 0; i < n; i++)
for (int a = 0; a < k; a++)
for (int b = 0; b < k; b++)
cost[i][a][b] = 1e9;
for (int i = 0; i < m; i++)
{
int a, b, t;
cin >> a >> b >> t;
cost[a/k][a%k][b%k] = t;
}
for (int i = 0; i < o; i++)
cin >> queries[i].a >> queries[i].b, queries[i].id = i, queries[i].ans = 1e9;
dnc(0, n/k);
for (int i = 0; i < o; i++)
cout << (queries[i].ans == 1e9 ? -1 : queries[i].ans) << '\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... |