Created
May 22, 2023 00:21
-
-
Save estelabn/af50b01f8373d6cc555f5e7b03e001a3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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