Josif_tepe

Untitled

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