Josif_tepe

Untitled

Oct 8th, 2025
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. #include <iostream>
  2. #include <set>
  3. #include <queue>
  4. #include <vector>
  5. using namespace std;
  6. const int maxn = 1e5 + 5;
  7. typedef long long ll;
  8. int n, m;
  9. vector<pair<int, int>> graph[maxn];
  10. vector<bool> visited(maxn, false);
  11.  
  12. ll bfs(int S, int E){
  13.     queue<pair<int, ll>> q;
  14.     q.push({S, 0});
  15.  
  16.     visited[S] = true;
  17.  
  18.     while(!q.empty()){
  19.         int node = q.front().first;
  20.         ll total = q.front().second;
  21.         q.pop();
  22.  
  23.         if(node == E){
  24.             return llabs(total);
  25.         }
  26.  
  27.         for(pair<int,int> edge : graph[node]){
  28.             int neighbour = edge.first;
  29.             int w = edge.second;
  30.  
  31.             if(!visited[neighbour]){
  32.                 visited[neighbour] = true;
  33.  
  34.                 ll nov_total = total;
  35.                 if(neighbour > node){               //poradi tezinata, odam so ovoj nacin, ne so nova varijabla koja ja stavam vo queue
  36.                     nov_total += w;
  37.                 }
  38.                 else{
  39.                     nov_total -= w;
  40.                 }
  41.  
  42.                 q.push({neighbour, nov_total});
  43.             }
  44.         }
  45.     }
  46.  
  47.     return -1;
  48. }
  49.  
  50. int main() {
  51.     ios::sync_with_stdio(false);
  52.  
  53.     int t1, t2;
  54.     cin >> t1 >> t2;
  55.  
  56.  
  57.     cin >> n >> m;
  58.  
  59.      for(int i = 0; i < m; i++){
  60.         int a, b, c;
  61.         cin >> a >> b >> c;
  62.  
  63.         graph[a].push_back({b, c});
  64.         graph[b].push_back({a, c});
  65.     }
  66.  
  67.     cout << bfs(t1, t2);
  68.  
  69.  
  70.     return 0;
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment