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>
#pragma GCC optimize("Ofast", "unroll-loops")
using namespace std;
#define ll long long
#define int ll
#define FOR(i, a, b) for (int i=(a); i<(b); i++)
#define REP(i, n) FOR(i, 0, n)
#define REP1(i, n) FOR(i, 1, n+1)
#define RREP(i, n) for (int i=(n)-1; i>=0; i--)
#define RREP1(i, n) for(int i=(n); i>=1; i--)
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) (int)((x).size())
#define SQ(x) (x)*(x)
#define f first
#define s second
#define pii pair<int, int>
// #define endl '\n'
#define pb push_back
const ll mod = 1e9+7;
const ll maxn = 5e4+5;
const ll inf = (1ll<<60);
ll pw(ll x, ll p){
ll ret=1;
while(p>0){
if (p&1){
ret*=x;
ret%=mod;
}
x*=x;
x%=mod;
p>>=1;
}
return ret;
}
ll inv(ll x){
return pw(x, mod-2);
}
int k, n, m, q;
int dp[maxn][5][5];
struct quer{
int a, b;
int id;
};
int res[maxn];
vector<pii> graph[maxn], rgraph[maxn];
void run(int l, int r, vector<quer>& orders){
if (SZ(orders) == 0) return;
if (l==r){
REP(i, SZ(orders)){
if (orders[i].a!=orders[i].b||orders[i].a/k!=l){
res[orders[i].id]=-1;
}
else res[orders[i].id]=0;
}
return;
}
int mid = (l+r)>>1;
vector<quer> L, R;
REP(j, k){
REP(z, k){
if (j==z) dp[mid][j][z]=0;
else dp[mid][j][z]=inf;
}
}
for (int i=mid-1; i>=l; i--){
REP(y, k){
REP(j, k){
dp[i][j][y]=inf;
REP(z, SZ(graph[i*k+j])){
dp[i][j][y]=min(dp[i][j][y], dp[i+1][graph[i*k+j][z].f%k][y]+graph[i*k+j][z].s);
}
}
}
}
for (int i=mid+1; i<=r; i++){
REP(y, k){
REP(j, k){
dp[i][j][y]=inf;
REP(z, SZ(rgraph[i*k+j])){
dp[i][j][y]=min(dp[i][j][y], dp[i-1][rgraph[i*k+j][z].f%k][y]+rgraph[i*k+j][z].s);
}
}
}
}
REP(i, SZ(orders)){
if (orders[i].b<orders[i].a||!(orders[i].b/k<=r&&orders[i].a/k>=l)){
res[orders[i].id]=-1;
continue;
}
if (orders[i].b/k<=mid){
L.pb(orders[i]);
}
else if (orders[i].a/k>mid){
R.pb(orders[i]);
}
else{
// cout<<l<<' '<<r<<' '<<orders[i].id<<endl;
res[orders[i].id]=inf;
REP(j, k){
res[orders[i].id] = min(res[orders[i].id], dp[orders[i].a/k][orders[i].a%k][j]+dp[orders[i].b/k][orders[i].b%k][j]);
}
if (res[orders[i].id]==inf) res[orders[i].id]=-1;
}
}
run(l, mid, L);
run(mid+1, r, R);
}
signed main(){
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin>>k>>n>>m>>q;
REP(i, m){
int u, v, w; cin>>u>>v>>w;
graph[u].pb({v, w});
rgraph[v].pb({u, w});
}
vector<quer> Q;
REP(i, q){
int a, b; cin>>a>>b;
Q.pb({a, b, i});
}
int wo = (n-1)/k;
run(0, wo, Q);
REP(i, q){
cout<<res[i]<<endl;
}
}
/*
2
3 5
3 5
*/
# | 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... |