Cod sursa(job #1209471)

Utilizator R4DIC4LTeodorescu Oana Maria R4DIC4L Data 17 iulie 2014 19:33:17
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.96 kb
#include <fstream>
#define NMAX 1000000
using namespace std;

ifstream f("elmaj.in");
ofstream g("elmaj.out");

int n, v[NMAX];

int numberVotesMajority(int candidate) {
	int votes = 0;

	for (int i = 0; i < n; ++i) {
		if (v[i] == candidate) {
			votes++;
		}
	}

	if (votes > n / 2) {
		return votes;
	}
	return -1;
}

int main() {
	f >> n;
	f >> v[0];

	// first candidate standing
	int index = 0, count = 1;

	// read data and find candidate to stand up after voting for majority
	for (int i = 1; i < n; ++i) {
		f >> v[i];
		if (v[index] == v[i]) {
			// voters sustain same candidate
			count++;
		}
		else {
			// voters sustain different candidates
			count--;
		}
		// new candidate to take into account
		if (count == 0) {
			index = i;
			count = 1;
		}
	}

	int noVotes = numberVotesMajority(v[index]);
	if (noVotes > 0) {
		g << v[index] << " " << noVotes << "\n";
	}
	else {
		g << "-1\n";
	}

	return 0;
}