Cod sursa(job #769317)

Utilizator igsifvevc avb igsi Data 18 iulie 2012 23:16:59
Problema Elementul majoritar Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 0.91 kb
#include<stdio.h>
#include<stdlib.h>

const unsigned int Multiplier = 0x6b43a9b5; /* 2^30 < M < 2^31, M prime*/
struct list{
    unsigned int value;
    unsigned int nr;
    struct list *next;
} *hash[131072];/* 131072 = 2^17 */
FILE *file;
unsigned int maxNr, maxVal, N;

int main()
{
	unsigned int hashVal, x;
	struct list *p;
	
	file = fopen("elmaj.in", "r");
	fscanf(file, "%d", &N);
	while(EOF != fscanf(file, "%d", &x))
	{
		hashVal = (x * Multiplier) >> 15;
		for(p = hash[hashVal]; p && p->value != x; p = p->next);
		
		if(p)
		{
			p->nr++;
			if(p->nr > maxNr) 
				maxNr = p->nr,
				maxVal = p->value;
		}		
		else
		{
			p = malloc(sizeof(struct list));
			p->value = x;
			p->nr = 1;
			p->next = hash[hashVal];
			hash[hashVal] = p;
		}
	}
	fclose(file);
	
	file = fopen("elmaj.out", "w");
	if(maxNr > (N>>1))
		fprintf(file, "%d %d\n", maxVal, maxNr);
	else
		fprintf(file, "-1\n");
	fclose(file);
	
	return 0;
}