Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <algorithm>
- #include <vector>
- #include <queue>
- #include <functional>
- #include <string>
- #define x first
- #define y second
- using namespace std;
- typedef pair<int, int> pr;
- struct Node
- {
- Node* l;
- Node* r;
- int key;
- int prior;
- int index;
- Node(int key, int prior, int index) : key(key), prior(prior), index(index), l(nullptr), r(nullptr) { };
- };
- pair<Node*, Node*> split(Node* t, int val) {
- if (t == nullptr) return make_pair(nullptr, nullptr);
- if (val > t->key) {
- auto p = split(t->r, val);
- t->r = p.x;
- return make_pair(t, p.y);
- }
- else {
- auto p = split(t->l, val);
- t->l = p.y;
- return make_pair(p.x, t);
- }
- }
- Node* merge(Node* t1, Node* t2) {
- if (t1 == nullptr) return t2;
- if (t2 == nullptr) return t1;
- if (t1->prior > t2->prior) {
- t1->r = merge(t1->r, t2);
- return t1;
- }
- else {
- t2->l = merge(t1, t2->l);
- return t2;
- }
- }
- int main() {
- ifstream fin("input.txt");
- ofstream fout("output.txt");
- int n;
- fin >> n;
- vector<pr> vec(n);
- for (int i = 0; i < n; i++) fin >> vec[i].x >> vec[i].y;
- sort(vec.begin(), vec.end(), [](pr a, pr b) {
- return a.first > b.first;
- });
- queue<Node*> q;
- for (int i = 0; i < n; i++) q.push(new Node(vec[i].x, vec[i].y, i+1));
- while (q.size() > 1) {
- auto p = make_pair(q.front(), q.front());
- q.pop();
- p.y = q.front();
- q.pop();
- q.push(merge(p.y, p.x));
- }
- vector<string> answ(n);
- function<void(Node*, int)> print = [&](Node* cur, int pr) {
- if (cur == nullptr) return;
- answ[cur->index-1] = to_string(pr) + " "
- + to_string((cur->l == nullptr ? 0 : cur->l->index)) + " "
- + to_string((cur->r == nullptr ? 0 : cur->r->index)) + "\n";
- print(cur->l, cur->index);
- print(cur->r, cur->index);
- };
- fout << "YES" << endl;
- print(q.front(), 0);
- for (string s : answ) fout << s;
- fin.close();
- fout.close();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment