Raslboyy

2781

Oct 11th, 2019
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.90 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <algorithm>
  4. #include <vector>
  5. #include <queue>
  6. #include <functional>
  7. #include <string>
  8. #define x first
  9. #define y second
  10.  
  11. using namespace std;
  12.  
  13. typedef pair<int, int> pr;
  14.  
  15. struct Node
  16. {
  17.     Node* l;
  18.     Node* r;
  19.     int key;
  20.     int prior;
  21.     int index;
  22.     Node(int key, int prior, int index) : key(key), prior(prior), index(index), l(nullptr), r(nullptr) {  };
  23. };
  24.  
  25. pair<Node*, Node*> split(Node* t, int val) {
  26.     if (t == nullptr) return make_pair(nullptr, nullptr);
  27.     if (val > t->key) {
  28.         auto p = split(t->r, val);
  29.         t->r = p.x;
  30.         return make_pair(t, p.y);
  31.     }
  32.     else {
  33.         auto p = split(t->l, val);
  34.         t->l = p.y;
  35.         return make_pair(p.x, t);
  36.     }
  37. }
  38.  
  39. Node* merge(Node* t1, Node* t2) {
  40.     if (t1 == nullptr) return t2;
  41.     if (t2 == nullptr) return t1;
  42.     if (t1->prior > t2->prior) {
  43.         t1->r = merge(t1->r, t2);
  44.         return t1;
  45.     }
  46.     else {
  47.         t2->l = merge(t1, t2->l);
  48.         return t2;
  49.     }
  50. }
  51.  
  52.  
  53.  
  54. int main() {
  55.     ifstream fin("input.txt");
  56.     ofstream fout("output.txt");
  57.  
  58.     int n;
  59.     fin >> n;
  60.     vector<pr> vec(n);
  61.     for (int i = 0; i < n; i++) fin >> vec[i].x >> vec[i].y;
  62.     sort(vec.begin(), vec.end(), [](pr a, pr b) {
  63.         return a.first > b.first;
  64.         });
  65.     queue<Node*> q;
  66.     for (int i = 0; i < n; i++) q.push(new Node(vec[i].x, vec[i].y, i+1));
  67.     while (q.size() > 1) {
  68.         auto p = make_pair(q.front(), q.front());
  69.         q.pop();
  70.         p.y = q.front();
  71.         q.pop();
  72.         q.push(merge(p.y, p.x));
  73.     }
  74.     vector<string> answ(n);
  75.     function<void(Node*, int)> print = [&](Node* cur, int pr) {
  76.         if (cur == nullptr) return;
  77.         answ[cur->index-1] = to_string(pr) + " "
  78.              + to_string((cur->l == nullptr ? 0 : cur->l->index)) + " "  
  79.              + to_string((cur->r == nullptr ? 0 : cur->r->index)) + "\n";
  80.         print(cur->l, cur->index);
  81.         print(cur->r, cur->index);
  82.     };
  83.     fout << "YES" << endl;
  84.     print(q.front(), 0);
  85.     for (string s : answ) fout << s;
  86.  
  87.     fin.close();
  88.     fout.close();
  89.     return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment