Created
August 22, 2018 10:25
-
-
Save ajx42/7e099beb0c3fd26a39ea568b148e94d6 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
vector <vector <int> > adj; // adjacency list vectors | |
void dfs(int i, int par){ | |
// set parent of i as the value passed in par | |
parent[i] = par; | |
if(par == -1) // means i is root | |
level[i] = 0; | |
else // otherwise | |
level[i] = level[parent[i]]+1 | |
for(auto j: adj[i]){ | |
if(j == par) // don't go to parent again! :/ | |
continue; | |
dfs(j, i); // go to children | |
} | |
} | |
int main(){ | |
int n; // n = # nodes, we don't need # edges | |
cin >> n; | |
adj.resize(n+1); | |
for(int i = 0, x, y; i < n-1; ++i){ // read n-1 edges | |
cin >> x >> y; | |
// push to adjacency list | |
adj[x].push_back(y); | |
adj[y].push_back(x); | |
} | |
// Let root be 1, so we pass the parent as -1 (see dfs function) | |
dfs(1, -1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment