Advertisement
tepyotin2

Message Route

May 10th, 2025
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.24 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. struct Comp{
  6.     int v;
  7.     vector<int> route;
  8. };
  9.  
  10. int n, m;
  11. vector<int> link[100001];
  12. queue<Comp> q;
  13. bool visited[100001];
  14.  
  15. int main(){
  16.     //freopen("message.in", "r", stdin);
  17.    
  18.     cin >> n >> m;
  19.     int a, b;
  20.     for(int i=0; i<m; i++){
  21.         cin >> a >> b;
  22.         link[a].push_back(b);
  23.         link[b].push_back(a);
  24.     }
  25.     vector<int> r;
  26.     r.push_back(1);
  27.     q.push({1, r});
  28.     visited[1] = true;
  29.     while(!q.empty()){
  30.         Comp cur = q.front();
  31.         q.pop();
  32.         if(cur.v == n){
  33.             cout << cur.route.size() << '\n';
  34.             string p = "";
  35.             //int ans = 1;
  36.             for(int i=0; i<cur.route.size(); i++){
  37.                 //if(cur.route[i] == ' ') ans++;
  38.                 cout << p << cur.route[i];
  39.                 p = " ";
  40.             }
  41.             //cout << ans << '\n';
  42.             //cout << cur.route << '\n';
  43.             cout << '\n';
  44.             return 0;
  45.         }
  46.         for(auto v: link[cur.v]){
  47.             if(!visited[v]){
  48.                 visited[v] = true;
  49.                 cur.route.push_back(v);
  50.                 //cout << cur.route << '\n';
  51.                 q.push({v, cur.route});
  52.                 cur.route.pop_back();
  53.                 //!!!use vector because saves a lot of run time instead of string
  54.                 //visited[v] = false;
  55.                 //do not need to turn visited back because it will cause double check which is not needed
  56.             }
  57.         }
  58.     }
  59.     cout << "IMPOSSIBLE" << '\n';
  60.    
  61.     return 0;
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement