Cod sursa(job #946012)

Utilizator robert_stefanRobert Stefan robert_stefan Data 3 mai 2013 17:22:14
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include<fstream>

using namespace std;

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

const int MAX=1000000;

int N, v[MAX];

void citire();

void scrie();

void qSort(int left, int right);

void verifica();

int main()
{
	citire();
	//scrie();
	qSort(0, N-1);
	//scrie();
	verifica();
	in.close();
	out.close();
	return 0;
}

void citire()
{
	int i;
	in>>N;
	for(i=0; i<N; i++)
		in>>v[i];
}

void scrie()
{
	int i;
	for(i=0; i<N; i++)
		out<<v[i]<<' ';
	out<<'\n';
}

void qSort(int left, int right)
{
    int min=left, max=right, pivot=v[(left+right)/2], tmp;
    while(min<=max)
    {
        while(v[min]<pivot)
            min++;
        while(v[max]>pivot)
            max--;
        if(min<=max)
            tmp=v[min], v[min]=v[max], v[max]=tmp, min++, max--;
    }
    if(left<max)
        qSort(left,max);
    if(right>min)
        qSort(min,right);
}

void verifica()
{
	int i, ap=1, val=v[0];
	float e=(N+1)/2;
	bool gasit=0;
	for(i=1;i<N;i++)
		if(v[i]==val)
			ap++;
		else
		{
			if(e<=ap)
			{
				out<<val<<' '<<ap; 
				gasit=1;
				break;
			}
			else
				val=v[i], ap=1;
		}
	if(!gasit)
		out<<-1;
	out<<'\n';
}