Facebook
From Viktor varbanov, 3 Years ago, written in C++.
Embed
Download Paste or View Raw
Hits: 289
  1. #include <cmath>
  2. #include <cstdio>
  3. #include <vector>
  4. #include <iostream>
  5. #include <algorithm>
  6. #include<queue>
  7. #include<map>
  8. using namespace std;
  9. class Node
  10. {
  11.     public:
  12.     int left;
  13.     int right;
  14.     int hd;
  15.     int data;
  16.     Node(int data, int left, int right): data(data),right(right),left(left){}
  17. };
  18. vector<Node> v;
  19. void topview(Node root)
  20. {
  21.     if(root.data==-1)  return;
  22.      queue<Node>q;
  23.      map<int,int> m;  
  24.      int hd=0;
  25.      root.hd=hd;
  26.        
  27.     q.push(root);
  28.      
  29.     while(q.size())
  30.     {
  31.         hd=root.hd;
  32.        
  33.         if(m.count(hd)==0)  m[hd]=root.data;
  34.         if(root.left!=-1)
  35.         {
  36.             v[root.left].hd=hd-1;
  37.             q.push(v[root.left]);
  38.         }
  39.         if(root.right!=-1)
  40.         {
  41.             v[root.right].hd=hd+1;
  42.             q.push(v[root.right]);
  43.         }
  44.         q.pop();
  45.         root=q.front();  
  46.     }
  47.      
  48.      for(auto i=m.begin();i!=m.end();i++)
  49.     {
  50.         cout<<i->second<<" ";
  51.     }
  52.      
  53. }
  54.  
  55. int main() {
  56.     /* Enter your code here. Read input from STDIN. Print output to STDOUT */  
  57.     int n,a,b;
  58.     cin>>n;
  59.     for(int i=0;i<n;i++){
  60.         cin>>a>>b;
  61.         Node curr(i,a,b);
  62.         v.push_back(curr);
  63.     }
  64.     topview(v[0]);
  65.     return 0;
  66. }
  67.