Cod sursa(job #823038)

Utilizator OpportunityVlad Negura Opportunity Data 24 noiembrie 2012 15:23:04
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.64 kb
#include <fstream>
#include <iostream>
#include <stdio.h>
using namespace std;

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

int a[1000010],i,n,nr=0;

void readData(){
	in >> n;
	for (i=0; i<n; i++) in >> a[i];
}

int majorElement(){
	int cand=-1, k=0;
	for (i=0; i<n; i++)
		if (k==0){
			cand=a[i];
			k=1;
		}else if (a[i]==cand){
			k++;
		}else{
			k--;
		}
	if (cand<0) return cand;
	for (i=0; i<n; i++)
		if (a[i]==cand)
			nr++;
	if (nr>n/2)
		return cand;
	else
		return -1;
}

int main() {

	readData();
	int elmaj=majorElement();
	if (elmaj>0) {
		out << elmaj << " " << nr;
	}else
		out << elmaj;

	out.close(); in.close(); return 0;
}