Untitled

 avatar
unknown
c_cpp
4 years ago
1.3 kB
4
Indexable
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
 
int main()
{
    ios_base::sync_with_stdio(false);
    int n;
    cin >> n;
    vector<int> graph[n + 1], niza, niza2;
    for(int i = 0; i < n-1; i++){
        int a, b;
        cin >> a >> b;
        graph[a].push_back(b);
        graph[b].push_back(a);
    }
    queue<int> q;
    q.push(0);
    vector<bool> visited(n, false);
    visited[0] = true;
    while(!q.empty()){
        int vert = q.front();
        q.pop();
        niza.push_back(vert);
        for(int i = 0; i < graph[vert].size(); i++){
            int k = graph[vert][i];
            if(visited[k]) continue;
            visited[k] = true;
            q.push(k);
        }
    }

    q.push(n);
    visited[n] = true;
    while(!q.empty()){
        int vert = q.front();
        q.pop();
        niza2.push_back(vert);
        for(int i = 0; i < graph[vert].size(); i++){
            int k = graph[vert][i];
            if(visited[k]) continue;
            visited[k] = true;
            q.push(k);
        }
    }

    for(int i = 0; i < niza.size(); i++){
        cout << niza[i] << " ";
    }

    for(int i = niza2.size() - 1; i >= 0; i--){
        cout << niza2[i] << " ";
    }

    return 0;
}
Editor is loading...