Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <vector>
- #include <iostream>
- #include <algorithm>
- #include <limits.h>
- #include <assert.h>
- #include <set>
- #include <map>
- #include <math.h>
- #include <queue>
- #include <stack>
- #include <time.h>
- #include <stdlib.h>
- using namespace std;
- //typedef __int64 i64;
- typedef unsigned long long ull;
- const int MAXN = 100000;
- const int UNDEF = -1; // НЕОПРЕДЕЛЁННОСТЬ
- struct tree{ // МАССИВ - ДЕРЕВО
- int parent = UNDEF;
- int left = UNDEF;
- int right = UNDEF;
- int value;
- int cnt = 0; // КОЛ - ВО ЭЛЕМЕНТОВ СО ЗНАЧЕНИЕМ VALUE
- };
- class binary_tree{
- private :
- tree t[MAXN]; // ДЕРЕВО
- int index = 0; // ПОСЛЕДНИЙ ИНДЕКС
- public :
- //int height = 0; // ВЫСОТА
- int get_index(int x){ // ПОИСК КРАЙНЕГО ИНДЕКСА
- int i = 0;
- while(true){
- if(x < t[i].value){
- if(t[i].left == UNDEF){
- return i;
- }
- else{
- i = t[i].left;
- }
- }
- else{
- if(t[i].value < x){
- if(t[i].right == UNDEF){
- return i;
- }
- else{
- i = t[i].right;
- }
- }
- else{
- return i;
- }
- }
- }
- }
- void ins(int x){
- if(index == 0){ // ПЕРВЫЙ ЭЛЕМЕНТ
- t[index].value = x;
- t[index].cnt = 1;
- index++;
- return;
- }
- int i = get_index(x);
- if(t[i].value == x){ // ТАКОЙ ЭЛЕМЕНТ УЖЕ ЕСТЬ
- t[i].cnt++;
- }
- else{
- t[index].cnt = 1;
- t[index].parent = i;
- t[index].value = x;
- if(x < t[i].value){
- t[i].left = index;
- }
- else{
- t[i].right = index;
- }
- index++;
- }
- }
- void rec(int i){ // ЛЕВЫЙ ОБХОД ИЗ I-ОЙ ВЕРШИНЫ С ВЫВОДОМ ЭЛЕМЕНТОВ В ОТСОРТИРОВАННОМ ПОРЯДКЕ
- if(i == UNDEF){
- return;
- }
- rec(t[i].left);
- for(int k = 0; k < t[i].cnt; k++){
- printf("%d ", t[i].value);
- }
- rec(t[i].right);
- }
- int get_left_index(int i){ // САМЫЙ ЛЕВЫЙ ИНДЕКС I-ОЙ ВЕРШИНЫ
- int pos = i;
- while(t[pos].left != UNDEF){
- pos = t[pos].left;
- }
- return pos;
- }
- int get_right_index(int i){ // САМЫЙ ПРАВЫЙ ИНДЕКС I-ОЙ ВЕРШИНЫ
- int pos = i;
- while(t[pos].right != UNDEF){
- pos = t[pos].right;
- }
- return pos;
- }
- };
- int main(){
- int n;
- scanf("%d", &n);
- binary_tree T;
- int x;
- for(int i = 0; i < n; i++){
- scanf("%d", &x);
- T.ins(x);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement