D_L3

Пътна проверка

Jan 25th, 2024
1,121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.94 KB | None | 0 0
  1. #include <cmath>
  2. #include <cstdio>
  3. #include <vector>
  4. #include <iostream>
  5. #include <algorithm>
  6. #include <unordered_map>
  7. #include <set>
  8. #include <queue>
  9.  
  10.  
  11. using namespace std;
  12.  
  13. unordered_map<int, unordered_map<int, int>> graph;
  14.  
  15. int isPath(queue<int>& path) {
  16.     int current = path.front();
  17.     path.pop();
  18.     int sum = 0;
  19.     while(!path.empty()){
  20.         int top = path.front();
  21.         path.pop();
  22.         if(graph[current].find(top) == graph[current].end()){
  23.             return -1;
  24.         }
  25.         sum += graph[current][top];
  26.  
  27.         current = top;
  28.     }
  29.     return sum;
  30. }
  31.  
  32. int main() {
  33.     int n, m, x, y, w, k;
  34.     cin >> n >> m;
  35.    
  36.     for(int i =0; i < m; i++){
  37.         cin >> x >> y >> w;
  38.         graph[x][y] = w;
  39.         graph[y][x] = w;
  40.     }
  41.     cin >> k;
  42.     queue<int> path;
  43.     for(int i = 0; i < k; i++){
  44.         cin >> x;
  45.         path.push(x);
  46.     }
  47.     cout << isPath(path);
  48.     return 0;
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment