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;
#define int long long
const int MAXN = 2e5 + 10;
const int MOD = 998244353;
#define ll __int128
mt19937_64 rng((int)std::chrono::steady_clock::now().time_since_epoch().count());
int rnd(int x, int y) {
int u = uniform_int_distribution<int>(x, y)(rng); return u;
}
ll read() { int x; cin >> x; return (ll)x; }
long long bm(long long b, long long p) {
if(p==0) return 1 % MOD;
long long r = bm(b, p >> 1);
if(p&1) return (((r*r) % MOD) * b) % MOD;
return (r*r) % MOD;
}
long long inv(long long b) {
return bm(b, MOD-2);
}
long long f[MAXN];
long long nCr(int n, int r) {
long long ans = f[n]; ans *= inv(f[r]); ans %= MOD;
ans *= inv(f[n-r]); ans %= MOD; return ans;
}
void precomp() { for(int i=0; i<MAXN; i++) f[i] = (i == 0 ? 1 % MOD : (f[i-1] * i) % MOD); }
int fastlog(int x) {
return (x == 0 ? -1 : 32 - __builtin_clz(x) - 1);
}
void gay(int i) { cout << "Case #" << i << ": "; }
void solve(int tc) {
int k, n, m, q;
cin >> k >> n >> m >> q;
int st[16][k][n];
for(int i=0; i<16; i++) {
for(int j=0; j<k; j++) {
for(int l=0; l<n; l++) {
st[i][j][l] = 1e16;
}
}
}
for(int i=0; i<m; i++) {
int a, b, t;
cin >> a >> b >> t;
st[0][a % k][b] = min(st[0][a % k][b], t);
}
for(int i=1; i<16; i++) {
for(int j=0; j<k; j++) {
for(int l=0; l<n; l++) {
if(l / k >= (1 << i)) {
for(int g=0; g<k; g++) {
int block = l / k - (1 << (i-1));
st[i][j][l] = min(st[i][j][l], st[i-1][g][l] + st[i-1][j][block * k + g]);
}
}
}
}
}
for(int i=0; i<q; i++) {
int a, b;
cin >> a >> b;
int A = a / k, B = b / k;
int d = B - A;
int dp[k];
for(int j=0; j<k; j++) dp[j] = 1e16;
dp[b % k] = 0;
for(int j=15; j>=0; j--) {
if(d >= (1 << j)) {
int newdp[k];
for(int l=0; l<k; l++) newdp[l] = 1e16;
for(int l=0; l<k; l++) {
int rel = B * k + l;
for(int c=0; c<k; c++) {
newdp[c] = min(newdp[c], dp[l] + st[j][c][rel]);
}
}
d -= (1 << j);
B -= (1 << j);
for(int l=0; l<k; l++) dp[l] = newdp[l];
}
}
cout << (dp[a % k] == 1e16 ? -1 : dp[a % k]) << '\n';
}
}
int32_t main() {
precomp();
ios::sync_with_stdio(0); cin.tie(0);
int t = 1; //cin >> t;
for(int i=1; i<=t; i++) solve(i);
}
// I don't know geometry.
# | 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... |