#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
#include <climits>
using namespace std;
const int INF = 1e9;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int K, N, M, O;
cin >> K >> N >> M >> O;
vector<vector<pair<int, int>>> graph(N);
for (int i = 0; i < M; ++i) {
int a, b, c;
cin >> a >> b >> c;
if (b / K == a / K + 1) {
graph[a].emplace_back(b, c);
}
}
vector<pair<int, int>> orders(O);
unordered_map<int, vector<int>> orders_by_origin;
for (int i = 0; i < O; ++i) {
int a, b;
cin >> a >> b;
orders[i] = {a, b};
orders_by_origin[a].push_back(i);
}
auto dijkstra = [&](int start) -> vector<int> {
vector<int> dist(N, INF);
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;
dist[start] = 0;
pq.emplace(0, start);
while (!pq.empty()) {
auto [d, u] = pq.top();
pq.pop();
if (d > dist[u]) continue;
for (auto &[v, cost] : graph[u]) {
if (dist[v] > dist[u] + cost) {
dist[v] = dist[u] + cost;
pq.emplace(dist[v], v);
}
}
}
return dist;
};
vector<int> answers(O, -1);
unordered_map<int, vector<int>> dist_cache;
for (auto &[origin, order_indices] : orders_by_origin) {
if (dist_cache.find(origin) == dist_cache.end()) {
dist_cache[origin] = dijkstra(origin);
}
vector<int>& dist_from_origin = dist_cache[origin];
for (int idx : order_indices) {
int a = orders[idx].first;
int b = orders[idx].second;
if (dist_from_origin[b] < INF) {
answers[idx] = dist_from_origin[b];
}
}
}
for (int ans : answers) {
cout << ans << '\n';
}
return 0;
}
# | 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... |