D_L3

SDA - 2018 2019 - test5 - task 2

Dec 11th, 2023
771
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 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 <unordered_set>
  8. #include <queue>
  9.  
  10. using namespace std;
  11.  
  12. unordered_map<int, unordered_set<int>> graph;
  13. unordered_map<int, int> path;
  14.  
  15. void bfs(){
  16.     queue<int> next;
  17.     next.push(0);
  18.     path[0] = 0;
  19.     while(!next.empty()) {
  20.         int current = next.front();
  21.         next.pop();
  22.         for(auto i : graph[current]){
  23.             if(path.count(i) == 0){
  24.                 path[i] = path[current] + 1;
  25.                 next.push(i);
  26.             }
  27.         }
  28.     }
  29. }
  30.  
  31. int main() {
  32.     int k, a, b;
  33.     cin >> k;
  34.     for(int i = 0; i < k; i++){
  35.         cin >> a >> b;
  36.         graph[a].insert(b);
  37.         graph[b].insert(a);
  38.     }
  39.     bfs();
  40.    
  41.     int sum = 0;
  42.    
  43.     for(auto i : path)
  44.         sum += i.second;
  45.    
  46.     cout << sum;
  47.    
  48.    
  49.    
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment