Cod sursa(job #2562391)

Utilizator radustn92Radu Stancu radustn92 Data 29 februarie 2020 13:58:36
Problema Sortare prin comparare Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.59 kb
#include <cstdio>
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;

struct node {
	int key, priority;
	int elemCnt;

	node* leftChild;
	node* rightChild;

	node() {}

	node(int _key) {
		key = _key;
		priority = rand();
		elemCnt = 1;
		leftChild = rightChild = NULL;
	}
};
typedef node* pnode;

pair<pnode, pnode> split(pnode root, int key) {
	if (root == NULL) {
		return {NULL, NULL};
	}

	if (key < root -> key) {
		pair<pnode, pnode> splitLeft = split(root -> leftChild, key);
		root -> leftChild = splitLeft.second;
		return {splitLeft.first, root};
	}
	pair<pnode, pnode> splitRight = split(root -> rightChild, key);
	root -> rightChild = splitRight.first;
	return {root, splitRight.second};
}

pnode merge(pnode leftTree, pnode rightTree) {
	if (leftTree == NULL || rightTree == NULL) {
		return leftTree == NULL ? rightTree : leftTree;
	}

	if (leftTree -> priority > rightTree -> priority) {
		leftTree -> rightChild = merge(leftTree -> rightChild, rightTree);
		return leftTree;
	}
	rightTree -> leftChild = merge(leftTree, rightTree -> leftChild);
	return rightTree;
}

pnode insert(pnode root, pnode toInsert) {
	if (root == NULL) {
		return toInsert;
	}

	if (toInsert -> priority > root -> priority) {
		pair<pnode, pnode> splitByInsertValue = split(root, toInsert -> key);
		toInsert -> leftChild = splitByInsertValue.first;
		toInsert -> rightChild = splitByInsertValue.second;
		return toInsert;
	} else if (toInsert -> key < root -> key) {
		root -> leftChild = insert(root -> leftChild, toInsert);
	} else {
		root -> rightChild = insert(root -> rightChild, toInsert);
	}

	return root;
}

pnode search(pnode root, int key) {
	if (root == NULL || root -> key == key) {
		return root;
	}

	if (key < root -> key) {
		return search(root -> leftChild, key);
	}
	return search(root -> rightChild, key);
}

void preOrderTraversal(pnode root) {
	if (root == NULL) {
		return;
	}
	preOrderTraversal(root -> leftChild);
	for (int entryIdx = 0; entryIdx < root -> elemCnt; entryIdx++) {
		cout << root -> key << " ";
	}
	preOrderTraversal(root -> rightChild);
}

pnode insert(pnode root, int elem) {
	pnode prevNode = search(root, elem);
	if (prevNode != NULL) {
		prevNode -> elemCnt++;
	} else {
		root = insert(root, new node(elem));
	}
	return root;
}

int main() {
	freopen("algsort.in", "r", stdin);
	freopen("algsort.out", "w", stdout);

	srand(time(0));
	cin.tie(NULL);
	ios_base::sync_with_stdio(false);

	pnode root = NULL;
	int N, elem;
	cin >> N;
	for (int i = 0; i < N; i++) {
		cin >> elem;
		root = insert(root, elem);
	}

	preOrderTraversal(root);
	cout << "\n";
	return 0;
}