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 ll long long
#define endl "\n"
const int MOD = 998244353;
void solve(){
int n, o, k, m; cin >> k >> n >> m >> o;
vector<vector<pair<int, int>>> adj(n);
for(int i = 0; i < m; i++){
int a, b, t; cin >> a >> b >> t;
adj[a].push_back({b, t});
}
int groups = n / k + 1;
int sqr = sqrt(groups);
vector<vector<int>> calc(n, vector<int> (k, 1e9));
for(int i = 0; i < groups; i += sqr){
for(int j = i * k; j < (i + 1) * k && j < n; j++){
queue<int> q;
q.push(j);
map<int, int> d; d[j] = 0;
while(!q.empty()){
int x = q.front(); q.pop();
if(x / k == i + sqr){
calc[j][x % k] = d[x];
continue;
}
if((x / k) % sqr != 0){
calc[x][j % k] = d[x];
}
for(auto p : adj[x]){
int node = p.first;
bool gd = d.count(node);
if(!gd) {d[node] = d[x] + p.second; q.push(node);}
else d[node] = min(d[node], d[x] + p.second);
}
}
}
}
while(o--){
int a, b; cin >> a >> b;
if(a / k >= b / k){
cout << -1 << endl;
return;
}
queue<int> q;
q.push(a);
map<int, int> d; d[a] = 0;
vector<int> dist(k, 1e9);
int gr;
while(!q.empty()){
int x = q.front(); q.pop();
if((x / k) % sqr == 0){
gr = x / k;
dist[x % k] = d[x];
continue;
}
for(auto p : adj[x]){
int node = p.first;
bool gd = d.count(node);
if(!gd) {d[node] = d[x] + p.second; q.push(node);}
else d[node] = min(d[node], d[x] + p.second);
}
}
while((gr + sqr) * k <= b){
vector<int> nw(k, 1e9);
for(int i = 0; i < k && gr * k + i < n; i++){
for(int j = 0; j < k; j++){
nw[j] = min(nw[j], dist[i] + calc[gr * k + i][j]);
}
}
dist = nw;
gr += sqr;
}
if((b / k) % sqr == 0) cout << (dist[b % k] >= 1e9 ? -1 : dist[b % k]) << endl;
else{
int ans = 1e9;
for(int i = 0; i < k; i++){
ans = min(ans, dist[i] + calc[b][i]);
}
if(ans >= 1e9) cout << -1 << endl;
else cout << ans << endl;
}
}
}
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
//freopen("inpt.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
//int tt; cin >> tt;
int tt = 1;
for(int t = 1; t <= tt; t++){
solve();
}
}
Compilation message (stderr)
toll.cpp: In function 'void solve()':
toll.cpp:68:13: warning: 'gr' may be used uninitialized in this function [-Wmaybe-uninitialized]
68 | while((gr + sqr) * k <= b){
| ~~~~^~~~~~
# | 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... |