Pagini recente » Cod sursa (job #3321489) | Cod sursa (job #2025628) | Cod sursa (job #858973) | Cod sursa (job #1310280) | Cod sursa (job #3318241)
#include <iostream>
#include <fstream>
#include <random>
#include <ctime>
using namespace std;
mt19937 rng(time(nullptr));
struct Node {
int val;
int prio;
Node* left = nullptr;
Node* right = nullptr;
Node(const int value) {
val = value;
prio = rng() % 50;
}
};
ostream& operator<<(ostream& out, const Node& a) {
out << "( " << a.val << ", " << a.prio << " )";
return out;
}
pair<Node*, Node*> split(Node* node, const int split_val) {
if (node == nullptr) { return {nullptr, nullptr}; }
if (node->val <= split_val) {
auto [mid, right] = split(node->right, split_val);
node->right = mid;
return {node, right};
} else {
auto [left, mid] = split(node->left, split_val);
node->left = mid;
return {left, node};
}
}
Node* join(Node* left, Node* right) {
if (left == nullptr) {
return right;
} else if (right == nullptr) {
return left;
}
if (left->prio > right->prio) {
left->right = join(left->right, right);
return left;
} else {
right->left = join(left, right->left);
return right;
}
}
Node* insert(Node* root, const int val) {
Node* new_node = new Node(val);
auto [left, right] = split(root, val);
return join(left, join(new_node, right));
}
Node* erase(Node* root, const int val) {
auto [midleft, right] = split(root, val);
auto [left, mid] = split(midleft, val - 1);
if (mid != nullptr) {
delete mid;
}
return join(left, right);
}
void print(ostream& out, Node* node, int lvl = 0) {
if (node == nullptr) { return; }
print(out, node->left, lvl + 1);
// for (int i = 0; i < lvl; i++) {
// cout << " ";
// }
// cout << (*node) << "\n";
out << node->val << " ";
print(out, node->right, lvl + 1);
}
int main() {
ifstream cin("algsort.in");
ofstream cout("algsort.out");
Node* root = nullptr;
int n; cin >> n;
for (int i = 0; i < n; i++) {
int x; cin >> x;
root = insert(root, x);
}
print(cout, root);
cout << "\n";
}