Created
October 2, 2015 21:57
-
-
Save GnsP/18c9bf8da2ac70770055 to your computer and use it in GitHub Desktop.
Another problem from a placement test, based on modified BFS, done for a friend.
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 <iostream> | |
#include <vector> | |
#include <queue> | |
#define INF 1000000007 | |
using namespace std; | |
typedef vector<vector<int> > graph; | |
void updateDist(graph &g, vector<int> &dist, int src){ | |
queue<int> q; | |
vector<bool> visited(g.size(), false); | |
int v; | |
q.push(src); | |
dist[src] = 0; | |
while(! q.empty()){ | |
v = q.front(); | |
q.pop(); | |
for(int i=0; i<g[v].size(); ++i){ | |
if(!visited[g[v][i]]){ | |
if(dist[g[v][i]] > dist[v]+1){ | |
dist[g[v][i]] = dist[v]+1; | |
q.push(g[v][i]); | |
} | |
} | |
} | |
} | |
} | |
int main(){ | |
int n, m, u, v; | |
cin >> n >> m; | |
vector<int> dist(n+1, INF); | |
graph g(n+1, vector<int>()); | |
for(int a=0; a<n-1; a++){ | |
cin >> u >> v; | |
g[u].push_back(v); | |
g[v].push_back(u); | |
} | |
updateDist(g, dist, 1); | |
for(int a=0; a<m; a++){ | |
cin >> u >> v; | |
if(u==1) updateDist(g, dist, v); | |
else cout << dist[v] << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment