-
-
Save LifeMoroz/7391161 to your computer and use it in GitHub Desktop.
Added description
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdint.h> | |
#include <algorithm> | |
#include <vector> | |
int size = 0; | |
void Heapify(int* arr, int i) { | |
int left = 2 * i + 1; int right = 2 * i + 2; // Ищем большего сына, если такой есть. | |
int largest = i; | |
if (left < size && arr[left] > arr[i]) | |
largest = left; | |
if (right < size && arr[right] > arr[largest]) | |
largest = right; // Если больший сын есть, то проталкиваем корень в него. | |
if (largest != i) { | |
std::swap(arr[i], arr[largest]); | |
Heapify(arr, largest); | |
} | |
} | |
void BuildHeap(int *arr) { | |
for (int i = size / 2 - 1; i >= 0; --i) | |
Heapify(arr, i); | |
} | |
void add(int* arr, int element) { | |
arr[size++] = element; | |
int i = size - 1; | |
while (i > 0) { | |
int parent = (i - 1) / 2; | |
if (arr[i] <= arr[parent]) | |
return; | |
std::swap(arr[i], arr[parent]); | |
i = parent; | |
} | |
} | |
int64_t countEl(int *arr, int element, int i) { | |
//худшая глубина рекурсии - log(N) | |
int64_t count = 0; | |
//если вершина больше искомого элемента инкрементируем счетчик | |
if (arr[i] > element) | |
++count; | |
//если адрес левого листа выходит за пределы массива - возвращаем count | |
if (2 * i + 1 > size) | |
return count; | |
//если левый лист больше искомого элемента - проверяем соответствующее ему поддерево | |
if (arr[2 * i + 1] > element) | |
count += countEl(arr, element, 2 * i+1); | |
else //если нет - возвращаем счетчик | |
return count; | |
//если адрес правого листа выходит за пределы массива - возвращаем count | |
if (arr[2 * i + 1] > element) | |
++count; | |
return count; | |
//если правый лист больше искомого элемента - проверяем соответствующее ему поддерево | |
if (arr[2 * i+2] > element) | |
count+= countEl(arr, element, 2 * i+2); | |
//в любом случае возвращаем count | |
return count; | |
} | |
int main() { | |
int *a = new int[1000000]; | |
int64_t count = 0; | |
int temp /*= 30000*/; | |
while (scanf("%d",&temp )!= 0){ | |
//строим дерево, параллельно подсчитывая количество удовлетворяющих условию элементов | |
count += countEl(a, temp,0); | |
add(a, temp); | |
} | |
printf("%ld", count); | |
return 0; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment