Pagini recente » Cod sursa (job #1986080) | Cod sursa (job #42573) | Cod sursa (job #423507) | Cod sursa (job #254353) | Cod sursa (job #2070354)
#include <fstream>
#include <vector>
#include <iostream>
using namespace std;
unsigned long long GetTimeStamp() {
unsigned a, b;
asm("rdtsc;\n\t" : "=d"(a), "=a"(b));
return (unsigned long long)a << 32 | b;
}
unsigned RandInt() {
static unsigned x = 123456789, y = 362436069,
z = (unsigned)(GetTimeStamp() >> 32), w = (unsigned)GetTimeStamp();
unsigned t = x ^ (x << 11);
x = y; y = z; z = w;
return w = w ^ (w >> 19) ^ (t ^ (t >> 8));
}
class ShuffleTree {
private:
struct Node {
int key;
Node* son[2];
Node(const int _key = 0) : key(_key) { }
};
Node* root;
int weight;
public:
explicit ShuffleTree() : root(nullptr), weight(0) {
}
void Insert(const int key) {
root = Insert(root, key, RandInt() % (1 + weight));
}
void Erase(const int key) {
root = Remove(root, key, RandInt() % (1 + weight));
}
bool Find(const int key) const {
return Find(root, key);
}
vector<int> Inorder() const {
vector<int> answer;
Inorder(root, answer);
return answer;
}
private:
bool Find(Node* node, const int key) const {
if (node == nullptr) {
return false;
}
if (node->key == key) {
return true;
}
return Find(node->son[key < node->key], key);
}
Node* Rotate(Node* node, const int idx, const int lambda) {
if (lambda > 0 or node->son[idx] == nullptr) {
return node;
}
Node* ch = node->son[idx];
node->son[idx] = ch->son[1 - idx];
ch->son[1 - idx] = node;
return ch;
}
Node* Insert(Node* node, const int key, const int lambda) {
if (node == nullptr) {
weight += 1;
return new Node(key);
}
if (node->key == key) {
return node;
}
const int idx = key < node->key;
node->son[idx] = Insert(node->son[idx], key, (lambda - 1) / 2);
return Rotate(node, idx, lambda);
}
Node* RemoveMinimum(Node* node, int& value) {
if (node->son[0] == nullptr) {
value = node->key;
return node->son[1];
}
node->son[0] = RemoveMinimum(node->son[0], value);
return node;
}
Node* Remove(Node* node, const int key, const int lambda) {
if (node == nullptr) {
return node;
}
if (node->key == key) {
weight -= 1;
if (node->son[1] == nullptr) {
return node->son[0];
}
node->son[1] = RemoveMinimum(node->son[1], node->key);
return node;
}
int idx = key < node->key;
node->son[idx] = Remove(node->son[idx], key, (lambda - 1) / 2);
return Rotate(node, idx, lambda);
}
void Inorder(Node* node, vector<int>& vec) const {
if (node == nullptr) {
return;
}
Inorder(node->son[1], vec);
vec.push_back(node->key);
Inorder(node->son[0], vec);
}
};
int main() {
ifstream cin("algsort.in");
ofstream cout("algsort.out");
int n; cin >> n;
ShuffleTree tree = ShuffleTree();
for (int i = 0; i < n; i += 1) {
int x; cin >> x;
tree.Insert(x);
}
for (auto&& el : tree.Inorder()) {
cout << el << ' ';
}
return 0;
}