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