Advertisement
Josif_tepe

Untitled

Apr 21st, 2021
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. #include <iostream>
  2. #include<queue>
  3. #include <vector>
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8.     int k;
  9.     cin >> k;
  10.     vector<int> graph[k + 1];
  11.     vector<int>v1;
  12.     for(int i = 0; i < k - 1; i++) {
  13.         int a, b;
  14.         cin >> a >> b;
  15.         graph[a].push_back(b);
  16.         graph[b].push_back(a);
  17.     }
  18.     queue<int>q;
  19.     bool niza[k+1];
  20.     for(int y=0; y<k; y++){
  21.         niza[y]=false;
  22.  
  23.  
  24.     }
  25.     q.push(0);
  26.  
  27.     while(!q.empty()){
  28.     int c=q.front();
  29.     q.pop();
  30.     cout<<c<<" ";
  31.     niza[0]=true;
  32.     for(int k1=0; k1<graph[c].size(); k1++){
  33.     int cc=graph[c][k1];
  34.     if(niza[cc]==false){
  35.     q.push(cc);
  36.     niza[cc]=true;
  37.     }
  38.     }
  39.     }
  40.  
  41.     q.push(k);
  42.  
  43.     while(!q.empty()){
  44.     int c=q.front();
  45.     q.pop();
  46.     v1.push_back(c);
  47.     niza[k]=true;
  48.     for(int k1=0; k1<graph[c].size(); k1++){
  49.     int cc=graph[c][k1];
  50.     if(niza[cc]==false){
  51.     q.push(cc);
  52.     niza[cc]=true;
  53.     }
  54.     }
  55.     }
  56.     for(int m=v1.size()-1; m>=0; m--){
  57.     cout<<v1[m]<<" ";
  58.     }
  59.     return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement