Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- #include <vector>
- #include <queue>
- using namespace std;
- typedef long long ll;
- const int maxn = 1e5 + 10;
- const int INF = 2e9 + 10;
- vector<pair<int, int>> graph[maxn]; // graph[i].first - node, graph[i].second - weight
- int n, m;
- struct node {
- int idx, shorest_path_till_idx;
- node () {}
- node(int _idx, int _sh) {
- idx = _idx;
- shorest_path_till_idx = _sh;
- }
- // < a < b
- bool operator < (const node &t) const {
- return shorest_path_till_idx > t.shorest_path_till_idx;
- }
- };
- int dijkstra(int S, int E) {
- vector<bool> visited(n + 1, false);
- vector<int> dist(n + 1, INF);
- dist[S] = 0; // shortest distance from source to source = 0
- priority_queue<node> pq;
- pq.push(node(S, 0));
- while(!pq.empty()) {
- node current = pq.top();
- pq.pop();
- if(visited[current.idx]) {
- continue;
- }
- visited[current.idx] = true;
- if(current.idx == E) {
- return current.shorest_path_till_idx;
- }
- for(int i = 0; i < (int) graph[current.idx].size(); ++i) {
- int neighbour = graph[current.idx][i].first;
- int neighbour_weight = graph[current.idx][i].second;
- if(!visited[neighbour] and neighbour_weight + current.shorest_path_till_idx < dist[neighbour]) {
- dist[neighbour] = current.shorest_path_till_idx + neighbour_weight;
- pq.push(node(neighbour, dist[neighbour]));
- }
- }
- }
- return -1;
- }
- int main()
- {
- ios_base::sync_with_stdio(false);
- cin >> n >> m;
- for(int i = 0; i < m; ++i) {
- int a, b, c;
- cin >> a >> b >> c;
- graph[a].push_back(make_pair(b, c));
- graph[b].push_back(make_pair(a, c));
- //undirected graph
- }
- int start, end;
- cin >> start >> end;
- cout << dijkstra(start, end) << endl;
- return 0;
- }
- /*
- tp:
- 5 6
- 1 2 5
- 2 3 6
- 3 4 8
- 1 5 2
- 3 5 3
- 4 2 9
- 2 5
- */
Advertisement
Add Comment
Please, Sign In to add comment