Cod sursa(job #1077455)

Utilizator pulseOvidiu Giorgi pulse Data 11 ianuarie 2014 13:12:06
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.7 kb
#include <fstream>
#define NMAX 1000002
using namespace std;

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

int n, v[NMAX], count = 0, maj = -1;

void ReadData ()
{
	fin >> n;
	for (int i = 1; i <= n; ++i)
		fin >> v[i];
}

void Solve ()
{
	for (int i = 1; i <= n; ++i)
	{
		if (count == 0)
		{
			maj = v[i];
			count = 1;
		}
		else if (v[i] == maj)
			++count;
		else
			--count;
	}
	if (maj < 0)
		fout << "-1\n";
	else
	{
		count = 0;
		for (int i = 1; i <= n; ++i)
		{
			if (v[i] == maj)
				++count;
		}
		if (count >= (n / 2) + 1)
			fout << maj << " " << count << "\n";
		else
			fout << "-1\n";
	}
}

int main ()
{
	ReadData ();
	Solve ();
}