Cod sursa(job #2548558)

Utilizator Ionut228Ionut Calofir Ionut228 Data 16 februarie 2020 19:56:45
Problema Statistici de ordine Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <bits/stdc++.h>

using namespace std;

class Solution {
public:
  int qs(vector<int>& nums, int lt, int rt) {
    int i = lt, j = rt;
    int pos_pivot = lt + rand() % (rt - lt + 1);
    int pivot = nums[pos_pivot];

    while (i <= j) {
      while (nums[i] < pivot) {
        i++;
      }

      while (nums[j] > pivot) {
        j--;
      }

      if (i <= j) {
        swap(nums[i], nums[j]);
        i++;
        j--;
      }
    }

    return j;
  }

  void nth_el(vector<int>& nums, int k, int lt, int rt) {
    if (lt == rt) {
      return;
    }

    int pos_pivot = qs(nums, lt, rt);
    int small_than_pivot = pos_pivot - lt + 1;

    if (small_than_pivot > k) {
      nth_el(nums, k, lt, pos_pivot);
    } else if (small_than_pivot < k) {
      nth_el(nums, k - small_than_pivot, pos_pivot + 1, rt);
    }
  }

  int majorityElement(vector<int>& nums, int k) {
    nth_el(nums, k, 0, nums.size() - 1);

    return nums[nums.size() / 2];
  }
};

int main() {
  ifstream cin("sdo.in");
  ofstream cout("sdo.out");

  int n, k;
  cin >> n >> k;
  vector<int> v;
  for (int i = 1, nr; i <= n; i++) {
    cin >> nr;
    v.push_back(nr);
  }

  /* for (auto it = v.begin(); it != v.end(); it++) { */
  /*   cout << *it << ' '; */
  /* } */

  Solution sol;
  int nr = sol.majorityElement(v, k);

  /* cout << nr << '\n'; */
  cout << v[k - 1] << '\n';

  return 0;
}