Josif_tepe

Untitled

Feb 25th, 2026
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. using namespace std;
  5. const int maxn = 1e5 + 5;
  6. int n, m;
  7. vector<int> graph[maxn];
  8.  
  9. vector<int> bfs(int S, int E) {
  10.     queue<int> q;
  11.     q.push(S);
  12.     q.push(0);
  13.    
  14.     vector<bool> visited(n + 1, false);
  15.     visited[S] = true;
  16.     vector<int> path(n, -1);
  17.    
  18.     while(!q.empty()) {
  19.         int node = q.front();
  20.         q.pop();
  21.         int dist = q.front();
  22.         q.pop();
  23.        
  24.      
  25.        
  26.         for(int neighbour : graph[node]) {
  27.             if(!visited[neighbour]) {
  28.                 visited[neighbour] = true;
  29.                 q.push(neighbour);
  30.                 q.push(dist + 1);
  31.                
  32.                 path[neighbour] = node;
  33.             }
  34.         }
  35.        
  36.     }
  37.     return path;
  38. }
  39. int main() {
  40.     ios_base::sync_with_stdio(false);
  41.    
  42.     cin >> n >> m;
  43.    
  44.     for(int i = 0; i < m; i++) {
  45.         int a, b;
  46.         cin >> a >> b;
  47.         graph[a].push_back(b);
  48.         graph[b].push_back(a);
  49.     }
  50.    
  51.     int S, E;
  52.     cin >> S >> E;
  53.    
  54.     vector<int> p = bfs(S, E);
  55.    
  56.     while(E != S) {
  57.         cout << E << " ";
  58.         E = p[E];
  59.     }
  60.     cout << S << endl;
  61.     return 0;
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment