Cod sursa(job #2769520)

Utilizator victorgoreanuGoreanu Victor victorgoreanu Data 16 august 2021 14:42:55
Problema Elementul majoritar Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <bits/stdc++.h>
using namespace std;
string __fname = "elmaj"; ifstream in (__fname + ".in"); ofstream out (__fname + ".out"); 
#define cin in 
#define cout out
vector <int> a;

int binarys(int target){
    int l = 0, r = a.size() - 1, mid = 0;
    while (l <= r){
        mid = l + (r - l) / 2;
        if (a[mid] == target) return mid;
        if (a[mid] > target) r = mid - 1;
        if (a[mid] < target) l = mid + 1;
    }
    return 0;
}

int count(int target, int n){
    int count = 1;
    int c = binarys(target);
    if (c == 0) return 0;
    else {
        int y = c - 1;
        while (a[y] == target && y >= 0){
            count++;
            y--;
        }
        int u = c + 1;
        while (a[u] == target && u < n){
            count++;
            u++;
        }
    }
    return count;
}

int main(){
    int n;
    cin >> n;
    for (int i = 0; i < n; i++){
        int t;
        cin >> t;
        a.push_back(t);
    }
    sort (a.begin(), a.end());
    int c = -1;
    int b = 0;
    for (int i = 0; i < n; i++){
        int r = count(a[i], n);
        if (r != 0){
            if (r >= (n / 2 + 1)){
                c = r;
                b = i;
            }
        }
    }
    if (c > -1) cout << a[b] << " " << c;
    else cout << "-1";
    return 0;
}