Skip to content

Instantly share code, notes, and snippets.

@estelabn
Created May 22, 2023 00:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save estelabn/af50b01f8373d6cc555f5e7b03e001a3 to your computer and use it in GitHub Desktop.
Save estelabn/af50b01f8373d6cc555f5e7b03e001a3 to your computer and use it in GitHub Desktop.
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> adj;
vector<int> dist;
int bfs(int a, int b){
dist[a] = 0;
queue<int> q;
q.push(a);
while(!q.empty()){
int x = q.front(); q.pop();
for(int i=0; i<adj[x].size(); i++){
int viz = adj[x][i];
if(dist[viz] != -1) continue;
dist[viz] = dist[x] + 1;
q.push(viz);
}
}
return dist[b];
}
int main(){
int n,a,b; cin >> n >> a >> b;
a--; b--;
adj.resize(n+5);
for(int i=1; i<n; i++){
int p,q;
cin >> p >> q;
p--;q--;
adj[p].push_back(q);
adj[q].push_back(p);
}
dist.assign(n,-1);
cout << bfs(a,b) << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment