Cod sursa(job #639552)

Utilizator darkseekerBoaca Cosmin darkseeker Data 23 noiembrie 2011 15:46:00
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.93 kb
#include <fstream>
using namespace std;

struct hash{
	hash *next;
	int value, count;
};

hash* H[1000005];
int mod = (1 << 19) - 1;
int elmaj;

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

int maxim = 0,i,N,emaj;

inline void push(int val)
{
	int key = (val & mod);
	hash *q = H[key];
	while(q)
	{
		if(q->value == val)
			{
				q->count++;
				if(q->count > maxim)
					{
						maxim = q->count;
						if(maxim > N/2)
							elmaj = val;
					}
				return;
			}
		q = q->next;
	}
	q = new hash;
	q->next = H[key];
	q->value = val;
	q->count = 1;
	H[key] = q;
	if(q->count > maxim)
		maxim = q->count;
}

int main()
{
	int i,value;
	
	for(i = 0; i <= mod + 1; i++)
		H[i] = NULL;
	
	fin>>N;
	
	for(i = 1; i <= N; i++)
		{
			fin>>value;
			push(value);
		}
	
	if(maxim > N/2)
		fout<<elmaj<<' '<<maxim<<'\n';
	else
		fout<<'-1\n';
	
	fin.close();
	fout.close();
	
	return 0;
}