This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#pragma GCC optimize("unroll-loops,Ofast,O3")
#include <bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define spc << " " <<
#define endl "\n"
#define all(x) x.begin(), x.end()
#define int long long
#define ii pair<int,int>
#define vi vector<int>
#define vii vector<ii>
#define st first
#define nd second
#define inf 1000000009
#define MOD 1000000007
#define MX 50005
using namespace std;
int k,n,m,o;
int edge[MX][5], dat[16][MX][5], mask[MX];
void divi(int l, int r, int lev){
if(l>=r) return;
int m = (l+r)/2;
for(int i=0; i<k; i++){
dat[lev][m*k+i][i] = 0;
//dat[lev][m*k+i] = 0;
}
for(int i=m-1; i>=l; i--){
for(int j=0; j<k; j++){
for(int ww=0; ww<k; ww++){
for(int uwu=0; uwu<k; uwu++){
dat[lev][i*k+j][uwu] = min(dat[lev][i*k+j][uwu], dat[lev][(i+1)*k+ww][uwu] + edge[i*k+j][ww]);
}
}
}
}
for(int i=m+1; i<=r; i++){
for(int j=0; j<k; j++){
for(int ww=0; ww<k; ww++){
for(int uwu=0; uwu<k; uwu++){
dat[lev][i*k+j][uwu] = min(dat[lev][i*k+j][uwu], dat[lev][(i-1)*k+ww][uwu] + edge[(i-1)*k+ww][j]);
}
}
}
}
for(int i=m+1; i<=r; i++){
mask[i] ^= (1<<lev);
}
divi(l, m, lev+1);
divi(m+1, r, lev+1);
}
void solve(){
cin >> k >> n >> m >> o;
n += k-(n%k)-1;
for(int i=0; i<n; i++) for(int j=0; j<k; j++) edge[i][j] = inf;
for(int i=0; i<16; i++) for(int j=0; j<n; j++) for(int ww=0; ww<5; ww++) dat[i][j][ww] = inf;
for(int i=0; i<m; i++){
int a,b,c; cin >> a >> b >> c;
edge[a][b%k] = c;
}
divi(0, n/k, 0);
/*for(int i=0; i<n; i++){
cerr << "---" spc i spc "---\n";
for(int j=0; j<k; j++) cerr << j spc dat[0][i][j] << endl;
}
for(int i=0; i<n; i++) cerr << i spc mask[i] << endl;
cerr << "::: TO QUERIES :::\n";*/
while(o--){
int a,b; cin >> a >> b;
if(a == b){
cout << 0 << endl;
continue;
}
if(b/k <= a/k){
cout << -1 << endl;
continue;
}
int bits = __builtin_ctz(mask[a/k] ^ mask[b/k]);
//cerr << bits << endl;
int ans = inf;
for(int i=0; i<k; i++) ans = min(ans, dat[bits][a][i] + dat[bits][b][i]);
if(ans >= inf){
cout << -1 << endl;
}
else{
cout << ans << endl;
}
}
}
signed main(){
ios_base::sync_with_stdio(false);cin.tie(0);
#ifdef Local
freopen("in","r",stdin);
freopen("out","w",stdout);
#endif
/*freopen("fcolor.in","r",stdin);
freopen("fcolor.out","w",stdout);*/
int t=1;
//cin >> t;
while(t--) solve();
}
# | 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... |