Advertisement
Korotkodul

bfs

Jan 22nd, 2023
977
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.08 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <vector>
  4. #include <queue>
  5. #include <algorithm>
  6. #include <string>
  7. #include <stack>
  8. #include <set>
  9. #include <map>
  10. #define pii pair <int, int>
  11. #define pb(x) push_back(x)
  12. using namespace std;
  13. using ll = long long;
  14. using ld = long double;
  15. using db = double;
  16. void cv(vector <int> &v) {
  17.     for (auto x : v) cout << x << ' ';
  18.     cout << "\n";
  19. }
  20.  
  21. void cvl(vector <ll> &v) {
  22.     for (auto x : v) cout << x << ' ';
  23.     cout << "\n";
  24. }
  25.  
  26.  
  27. void cvv(vector <vector <int> > &v) {
  28.     for (auto x : v) cv(x);
  29.     cout << "\n";
  30. }
  31.  
  32. void cvb(vector <bool> v) {
  33.     for (bool x : v) cout << x << ' ';
  34.     cout << "\n";
  35. }
  36.  
  37. void cvs(vector <string>  v) {
  38.     for (auto a : v) {
  39.         cout << a << "\n";
  40.     }
  41. }
  42.  
  43. void cvp(vector <pii> a) {
  44.     for (auto p : a) {
  45.         cout << p.first << ' ' << p.second << "\n";
  46.     }
  47.     cout << "\n";
  48. }
  49.  
  50. int n, m;
  51.  
  52. vector <pii> G;
  53. vector <int> d;
  54. int inf = 2e9;
  55.  
  56. void bfs() {
  57.     d[0] = 0;
  58.     deque <int> Q;
  59.     Q.push_back(0);
  60.     while (!Q.empty()) {
  61.         int v = Q.front();
  62.         Q.pop_front();
  63.         for (pii e: G[v]) {
  64.             int u = e.first, w = e.second;
  65.             if (d[u] != inf) {
  66.                 continue;
  67.             }
  68.             if (d[u] > d[v] + w) {
  69.                 d[u] = d[v] + w;
  70.                 if (w == 0) {
  71.                     Q.push_front(u);
  72.                 } else {
  73.                     Q.push_back(u);
  74.                 }
  75.             }
  76.         }
  77.     }
  78. }
  79.  
  80. int main() {
  81.     ios::sync_with_stdio(0);
  82.     cin.tie(0);
  83.     cout.tie(0);
  84.     cin >> n >> m;
  85.     vector <int> kng(n,-1);
  86.     for (int &i: kng) cin >> i;
  87.     G.resize(n);
  88.     d.assign(n, inf);
  89.     for (int i = 0; i < n; ++i) {
  90.         int a, b; cin >> a >> b;
  91.         a--;
  92.         b--;
  93.         int w = 1;
  94.         if (kng[a] == kng[b]) {
  95.             w = 0;
  96.         }
  97.         pii ab = {b, w};
  98.         pii ba = {a, w};
  99.         G[a].pb(ab);
  100.         G[b].pb(ba);
  101.     }
  102.    
  103.     bfs();
  104.     if (d[n - 1] == inf) {
  105.         cout << "impossible";
  106.         exit(0);
  107.     }
  108.    
  109. }
  110.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement