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