Cod sursa(job #639553)

Utilizator darkseekerBoaca Cosmin darkseeker Data 23 noiembrie 2011 15:49:10
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 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,key,found = 0;
	
	for(i = 0; i <= mod + 1; i++)
		H[i] = NULL;
	
	fin>>N;
	
	for(i = 1; i <= N; i++)
		{
			fin>>value;
			found = 0;
			key = (value & mod);
			hash *q = H[key];
			while(q)
			{
				if(q->value == value)
					{
						found = 1;
						q->count++;
						if(q->count > maxim)
							{
								maxim = q->count;
								if(maxim > N/2)
									elmaj = value;
							}
				}
				q = q->next;
			}
			if(!found)
			{
				q = new hash;
				q->next = H[key];
				q->value = value;
				q->count = 1;
				H[key] = q;
				if(q->count > maxim)
					maxim = q->count;
			}
		}
			
			if(maxim > N/2)
				fout<<elmaj<<' '<<maxim<<'\n';
			else
				fout<<'-1\n';
	
	fin.close();
	fout.close();
	
	return 0;
}