Naxocist

penginhenmhee

Apr 29th, 2023
637
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.83 KB | Source Code | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N = 1e6 + 3;
  5. using pi = pair<int, int>;
  6. vector<int> adj[N];
  7. bool vis[N];
  8.  
  9. int main() {
  10.     cin.tie(nullptr)->sync_with_stdio(false);
  11.     int n, m; cin >> n >> m;
  12.     for(int i=0; i<n; ++i) {
  13.         adj[i].emplace_back(i+1); adj[i+1].emplace_back(i);
  14.     }
  15.  
  16.     for(int i=0; i<m; ++i) {
  17.         int l, r; cin >> l >> r;
  18.         l--;
  19.         adj[l].emplace_back(r); adj[r].emplace_back(l);
  20.     }
  21.  
  22.     queue<pi> q;
  23.     q.emplace(0, 0);
  24.     vis[0] = 1;
  25.     while(q.size()) {
  26.         int d, u; tie(d, u) = q.front(); q.pop();
  27.         if(u == n) {
  28.             cout << d;
  29.             return 0;
  30.         }
  31.         for(int v : adj[u]) {
  32.             if(vis[v]) continue ;
  33.             vis[v] = 1;
  34.             q.emplace(d+1, v);
  35.         }
  36.     }
  37.  
  38.     return 0;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment