D_L3

SDA - 2019 2020 - test5 - task 2

Dec 11th, 2023
843
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 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. #include <set>
  10.  
  11. using namespace std;
  12.  
  13. unordered_map<int, unordered_set<int>> graph;
  14. set<int> result;
  15. bool visited[100000] {false};
  16.  
  17. void bfs(int start, int distance){
  18.     queue<pair<int, int>> next;
  19.     next.push({start, 0});
  20.     visited[start] = true;
  21.     while(!next.empty()){
  22.         auto curr = next.front();
  23.         next.pop();
  24.         auto neighbours = graph[curr.first];
  25.         if(curr.second == distance - 1) {
  26.             for(auto i : neighbours) {
  27.                 if(!visited[i]){
  28.                     result.insert(i);
  29.                 }
  30.             }
  31.         }
  32.         else {
  33.             for(auto i : neighbours) {
  34.                 if(!visited[i]){
  35.                     next.push({i, curr.second + 1});
  36.                     visited[i] = true;
  37.                 }
  38.             }
  39.         }
  40.     }
  41. }
  42.  
  43. int main() {
  44.     int n, m, k, a, b;
  45.     cin >> n >> m >> k;
  46.    
  47.     for(int i = 0; i < m; i++){
  48.         cin >> a >> b;
  49.         graph[a].insert(b);
  50.         graph[b].insert(a);
  51.     }
  52.     if(k == 0){
  53.         cout << n;
  54.         return 0;
  55.     }
  56.    
  57.     bfs(n, k);
  58.    
  59.     if(result.empty()){
  60.         cout << -1;
  61.         return 0;
  62.     }
  63.    
  64.     for(int i : result)
  65.         cout << i << " ";
  66.     return 0;
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment