Cod sursa(job #1008159)

Utilizator jupanubv92Popescu Marius jupanubv92 Data 10 octombrie 2013 13:37:14
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.98 kb
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <cstring>
#define Nmax 1000001

using namespace std;

int a[Nmax];
int n,k;

int partitioning(int left, int right)
{
	int pivot = a[left + (rand()%(right-left+1))];
	int i = left, j = right;
	while (1)
	{
		while (a[i] < pivot) ++i;
		while (a[j] > pivot) --j;
		if (i < j)
		{
			int aux = a[i];
			a[i] = a[j];
			a[j] = aux;
		}
		else return j;
		++i;
		--j;
	}
	return 0;
}

void majority(int st, int dr, int k)
{
	if (st == dr)
		return;

	int v = partitioning(st,dr);
	int dist = (v-st)+1;
	
	if (k <= dist)
		majority(st, v, k);
	else majority(v+1, dr, k-dist);
}

int main()
{
	srand(time(NULL));
	ifstream fin("elmaj.in");
	ofstream fout("elmaj.out");
	fin>>n;
	for (int i = 0; i < n; ++i)
		fin>>a[i];

	majority(0,n-1,n/2-1);
	int el = a[n/2-1];

	int nr = 0;
	for (int i = 0; i < n; ++i) {
		if (a[i] == el)
			++nr;
	}


	if (nr >= n/2 + 1)
		fout<<el<<" "<<nr<<"\n";
	else fout<<-1<<"\n";

	return 0;
}