Cod sursa(job #2922641)

Utilizator raresgherasaRares Gherasa raresgherasa Data 9 septembrie 2022 14:26:15
Problema Elementul majoritar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.57 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin ("elmaj.in");
ofstream fout ("elmaj.out");

int main(){
  int n; fin >> n;
  vector<int>a(n);
  for (int &x : a){
    fin >> x;
  }
  int e = a[0], cnt = 1;
  for (int i = 1; i < n; i++){
    if (a[i] == e){
      cnt += 1;
    }
    else{
      cnt -= 1;
    }
    if (cnt <= 0){
      cnt = 1;
      e = a[i];
    }
  }
  int ans = 0;
  for (int i = 0; i < n; i++){
    ans += (a[i] == e);
  }
  if (ans >= (n / 2 + 1)){
    fout << e << " " << ans;
  }
  else{
    fout << -1;
  }
}