josiftepe

Untitled

Nov 28th, 2020
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.04 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <vector>
  4. #include <queue>
  5. using namespace std;
  6. typedef long long ll;
  7. const int maxn = 1e5 + 10;
  8. const int INF = 2e9 + 10;
  9. vector<pair<int, int>> graph[maxn]; // graph[i].first - node, graph[i].second - weight
  10. int n, m;
  11. struct node {
  12.     int idx, shorest_path_till_idx;
  13.     node () {}
  14.     node(int _idx, int _sh) {
  15.         idx = _idx;
  16.         shorest_path_till_idx = _sh;
  17.     }
  18.     // < a < b
  19.     bool operator < (const node &t) const {
  20.         return shorest_path_till_idx > t.shorest_path_till_idx;
  21.     }
  22. };
  23. int dijkstra(int S, int E) {
  24.     vector<bool> visited(n + 1, false);
  25.     vector<int> dist(n + 1, INF);
  26.     dist[S] = 0; // shortest distance from source to source = 0
  27.     priority_queue<node> pq;
  28.     pq.push(node(S, 0));
  29.     while(!pq.empty()) {
  30.         node current = pq.top();
  31.         pq.pop();
  32.         if(visited[current.idx]) {
  33.             continue;
  34.         }
  35.         visited[current.idx] = true;
  36.         if(current.idx == E) {
  37.             return current.shorest_path_till_idx;
  38.         }
  39.         for(int i = 0; i < (int) graph[current.idx].size(); ++i) {
  40.             int neighbour = graph[current.idx][i].first;
  41.             int neighbour_weight = graph[current.idx][i].second;
  42.             if(!visited[neighbour] and neighbour_weight + current.shorest_path_till_idx < dist[neighbour]) {
  43.                 dist[neighbour] = current.shorest_path_till_idx + neighbour_weight;
  44.                 pq.push(node(neighbour, dist[neighbour]));
  45.                
  46.             }
  47.         }
  48.     }
  49.  
  50.     return -1;
  51. }
  52. int main()
  53. {
  54.     ios_base::sync_with_stdio(false);
  55.     cin >> n >> m;
  56.     for(int i = 0; i < m; ++i) {
  57.         int a, b, c;
  58.         cin >> a >> b >> c;
  59.         graph[a].push_back(make_pair(b, c));
  60.         graph[b].push_back(make_pair(a, c));
  61.         //undirected graph
  62.     }
  63.     int start, end;
  64.     cin >> start >> end;
  65.     cout << dijkstra(start, end) << endl;
  66.     return 0;
  67. }
  68. /*
  69.  tp:
  70.   5 6
  71.   1 2 5
  72.   2 3 6
  73.   3 4 8
  74.   1 5 2
  75.   3 5 3
  76.   4 2 9
  77.   2 5
  78.  
  79.  */
  80.  
Advertisement
Add Comment
Please, Sign In to add comment