#include <bits/stdc++.h>
/*
    Phia ben kia dai duong cung chi co
    Bo cat nang niu bien thoi
*/
using namespace std;
using ll = long long;
#define int long long
#define pii pair<ll, ll>
#define fi first
#define se second
const ll N = 2e5 + 5, inf = 1e18, mod = 1e9 + 7, block = 320, lim = 19;
int k, n, m, q;
int dp[N][lim + 1][5][5];
int ans[5][5], tmp[5][5];
void combine(int t[5][5], int a[5][5], int b[5][5]) {
	for (int x = 0; x < k; x++) {
		for (int y = 0; y < k; y++) {
			for (int z = 0; z < k; z++) {
				t[x][y] = min(t[x][y], a[x][z] + b[z][y]);
			}
		}
	}
}
void make(int a[5][5], int b[5][5]) {
	for (int i = 0; i < k; i++) {
		for (int j = 0; j < k; j++) {
			a[i][j] = b[i][j];
		}
	}
}
signed main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    if (fopen(".inp", "r")) {
        freopen(".inp", "r", stdin);
        freopen(".out", "w", stdout);
    }
    cin >> k >> n >> m >> q;
	memset(dp, 0x3f3f3f3f, sizeof(dp));
	for (int i = 1; i <= m; i++) {
		int u, v, w;
		cin >> u >> v >> w;
		dp[u / k][0][u % k][v % k] = w;
	}
	for (int i = 1; i <= lim; i++) {
		for (int j = 0; j + (1 << i) - 1 <= (n + k - 1) / k; j++) {
			combine(dp[j][i], dp[j][i - 1], dp[j + (1 << (i - 1))][i - 1]);
		}	
	}
	while(q-- > 0) {
		int x, y;
		cin >> x >> y;
		int st = x / k;
		int ed = y / k;
		for (int i = 0; i < k; i++) ans[i][i] = 0;
		for (int i = lim; i >= 0; i--) {
			if (st + (1 << i) <= ed) {
				memset(tmp, 0x3f3f3f3f, sizeof(tmp));
				combine(tmp, ans, dp[st][i]);
				// memset(tmp, 0x3f3f3f3f, sizeof(tmp));
				make(ans, tmp);
				st += (1 << i);
			}
		}
		cout << (ans[x % k][y % k] >= 0x3f3f3f3f ? -1 : ans[x % k][y % k]) << '\n';
	}
    return 0;
}
Compilation message (stderr)
toll.cpp: In function 'int main()':
toll.cpp:42:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
   42 |         freopen(".inp", "r", stdin);
      |         ~~~~~~~^~~~~~~~~~~~~~~~~~~~
toll.cpp:43:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
   43 |         freopen(".out", "w", stdout);
      |         ~~~~~~~^~~~~~~~~~~~~~~~~~~~~| # | 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... |