Cod sursa(job #2253009)

Utilizator test_accNo Name test_acc Data 3 octombrie 2018 15:47:06
Problema Elementul majoritar Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 0.73 kb
#include <fstream>
#include <vector>

using namespace std;

ifstream f("elmaj.in");
ofstream g("elmaj.out");

int main() {
	int n;
	f >> n;

	vector<int> elems;
	int elem;
	for (int i = 0; i < n; i++) {
		f >> elem;
		elems.push_back(elem);
	}

	pair<int, int> possib = make_pair(elems.front(), 1);
	for (auto it = elems.begin() + 1; it != elems.end(); ++it) {
		if (*it == possib.first)
			possib.first = *it;
		else {
			possib.second -= 1;
			if (possib.second == 0) {
				possib.first = *it;
				possib.second = 1;
			}
		}
	}

	int count = 0;
	for (auto el : elems) {
		if (el == possib.first)
			count += 1;
	}
	if (count >= elems.size() / 2 + 1)
		g << possib.first << ' ' << count;
	else
		g << -1;
}