Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- #include <algorithm>
- using namespace std;
- const int maxn = 1e5 + 5;
- int k;
- vector<int> graph[maxn];
- void bfs(int S, bool to_reverse) {
- queue<int> q;
- q.push(S);
- vector<bool> visited(k + 1, false);
- vector<int> path;
- path.push_back(S);
- visited[S] = true;
- while(!q.empty()) {
- int current_node = q.front();
- q.pop();
- for(int neighbour : graph[current_node]) {
- if(!visited[neighbour]) {
- path.push_back(neighbour);
- visited[neighbour] = true;
- q.push(neighbour);
- }
- }
- }
- if(to_reverse) {
- reverse(path.begin(), path.end());
- }
- for(int node: path) {
- cout << node << " ";
- }
- }
- int main() {
- ios_base::sync_with_stdio(false);
- cin >> k;
- for(int i = 0; i < k - 1; i++) {
- int a, b;
- cin >> a >> b;
- graph[a].push_back(b);
- graph[b].push_back(a);
- }
- bfs(0, false);
- bfs(k, true);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment