Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- #include <limits>
- using namespace std;
- struct Edge {
- int from;
- int to;
- int weight;
- };
- int main() {
- int N, M, S, T;
- cin >> N >> M >> S >> T;
- vector<vector<Edge>> graph(N + 1);
- for (int i = 0; i < M; i++) {
- int a, b, w;
- cin >> a >> b >> w;
- graph[a].push_back({a, b, w});
- }
- vector<int> dist(N + 1, numeric_limits<int>::max());
- dist[S] = 0;
- priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;
- pq.push({0, S});
- while (!pq.empty()) {
- int current_dist = pq.top().first;
- int current_vertex = pq.top().second;
- pq.pop();
- if (current_dist > dist[current_vertex]) continue;
- for (const Edge& edge: graph[current_vertex]) {
- int new_dist = current_dist + edge.weight;
- if (new_dist < dist[edge.to]) {
- dist[edge.to] = new_dist;
- pq.push({new_dist, edge.to});
- }
- }
- }
- if (dist[T] == numeric_limits<int>::max()) {
- cout << -1 << endl;
- } else {
- cout << dist[T] << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement