Cod sursa(job #1255016)

Utilizator AndrewTheGreatAndrei Alexandrescu AndrewTheGreat Data 3 noiembrie 2014 23:40:11
Problema Elementul majoritar Scor 30
Compilator c Status done
Runda Arhiva educationala Marime 0.83 kb
#include <stdio.h>

int vot[1024];

int main() {
	freopen("elmaj.in", "r", stdin);
	freopen("elmaj.out", "w", stdout);

	int n, elem, cnt = 0, myElem = - 1;

	// Ignor cazu in care nu ai element majoritar
	scanf("%d", &n);
	for(int i = 0; i < n; i++){		
		scanf("%d", &elem);
		vot[i] = elem;

		// Alegem alt candidat
		if(cnt == 0) {
			cnt = 1;
			myElem = elem;
		}
		else {
			// Am mai gasit un vot
			if(elem == myElem) {
				cnt++;
			}
			else {
				// Anulez un vot -> imaginaeaza-ti ca se impereacheaza voturile 
				cnt--;
			}	
		}
	}

	int count = 0;
	for(int i = 0; i < n; i++) 
		if(myElem == vot[i])
			count++;

	if(count >= (n / 2 + n % 2)) {
		//printf("Elementul majoritar e %d cu %d voturi\n", myElem, count);
		printf("%d %d\n", myElem, count);
	}
	//else printf("Nu exista majoritar.\n");
	else printf("-1\n");

	return 0;
}