g
unknown
c_cpp
7 months ago
983 B
1
Indexable
Never
#include <stdio.h> void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; } void heapify(int arr[], int n, int i) { int largest = i; int left = 2 * i + 1; int right = 2 * i + 2; if (left < n && arr[left] > arr[largest]) largest = left; if (right < n && arr[right] > arr[largest]) largest = right; if (largest != i) { swap(&arr[i], &arr[largest]); heapify(arr, n, largest); } } void heapSort(int arr[], int n) { for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); for (int i = n - 1; i >= 0; i--) { swap(&arr[0],&arr[i]); heapify(arr, i, 0); } } int main() { int n,k; scanf("%d %d", &n,&k); int arr[n]; for (int i = 0; i < n; i++) scanf("%d", &arr[i]); heapSort(arr, n); int sum=0; for (int i = 0; i < k; i++) sum+=arr[i]; printf("%d",sum); return 0; }