Cod sursa(job #2548690)

Utilizator Ionut228Ionut Calofir Ionut228 Data 16 februarie 2020 21:57:10
Problema Statistici de ordine Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h>

using namespace std;

class Solution {
public:
  pair<int, int> qs(vector<int>& nums, int lt, int rt) {
    int i = lt, j = rt;
    int pos_pivot = rt;
    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 make_pair(i, j);
  }

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

    pair<int, int> p;
    p = qs(nums, lt, rt);
    int pos_i = p.first;
    int pos_j = p.second;

    if (pos_j >= k && lt < pos_j) {
      nth_el(nums, k, lt, pos_j);
    } else if (pos_i <= k && pos_i < rt) {
      nth_el(nums, k, pos_i, 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;
  cin >> n;
  int k;
  cin >> k;
  k--;
  vector<int> v;
  for (int i = 1, nr; i <= n; i++) {
    cin >> nr;
    v.push_back(nr);
  }

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

  cout << v[k] << '\n';

  return 0;
}