Cod sursa(job #1326495)

Utilizator charmpitzAndrei Pit charmpitz Data 25 ianuarie 2015 15:36:10
Problema Elementul majoritar Scor 80
Compilator c Status done
Runda Arhiva educationala Marime 1.89 kb

/*
Enunt:
Elementul majoritar.
Se da un vector cu n elemente si se cere sa gasiti elementul sau majoritar. 
Un element este considerat majoritar daca apare de cel putin n/2+1 ori in vector.
În fişierul de ieşire elmaj.out trebuie sa afisati pe un singur rand 2 numere: elementul majoritar, urmat de numarul sau de aparitii in vector. 
In caz ca vectorul nu are element majoritar afisati doar -1.
*/

/*
Rezolvare:
Ordonam crescator astfel pe pozitiile n/2, n/2+1 se afla elementul majoritar si apoi verificam

n=8
6 3 2 7 9 4 8 1
3 6 2 7  f(1,2) f(3,4)
2 3 6 7  f(1,4)
4 9 1 8
1 4 8 9

f(1,8)
f(1,4) - f(5,8)
f(1,2) f(3,4) - f(5,6) f(7,8)

*/

#include <stdio.h>

FILE *in, *out;
int n, v[1000001], w[1000001];

void mergesort(int *v, int *w, int x, int y) {
	int h, i, j, k;

	if (x<y)
	{
		h = x+(y-x)/2;
		mergesort(v, w, x, h);
		mergesort(v, w, h+1, y);

		i = x;
		j = h+1;
		k = 0;

		while(i<=h && j<=y)
		{
			if (v[i] > v[j])
			{
				k++;
				w[k] = v[j];
				j++;
			}
			else
			{
				k++;
				w[k] = v[i];
				i++;	
			}
		}

		// Aducem ce a mai ramas la stanga
		while (i<=h)
		{
			k++;
			w[k] = v[i];
			i++;
		}

		// Aducem ce a mai ramas la dreapta
		while (j<=y)
		{
			k++;
			w[k] = v[j];
			j++;
		}

		// Scriem peste
		for (i=x; i<=y; i++)
			v[i] = w[i-x+1];
	}
}


int main ()
{
	int maj, cmax, x, c, i;

	in = fopen("elmaj.in", "r");
	out = fopen("elmaj.out", "w");

	fscanf(in, "%d", &n);

	for (i=1; i<=n; i++)
	{
		fscanf(in, "%d", &v[i]);
	}

	mergesort(v, w, 1, n);

	if (v[n/2] != v[n/2+1])
	{
		fprintf(out, "%d\n", -1);
	}
	else
	{
		cmax = 0;
		c = 0;
		x = v[1];

		for (i=1; i<=n; i++)
		{
			if (x == v[i])
			{
				c++;
			}
			else
			{
				if (cmax < c)
				{
					cmax = c;
					maj = x;
				}

				c = 1;
				x = v[i];
			}
		}

		if (cmax >= n/2+1)
		{
			fprintf(out, "%d %d\n", maj, cmax);
		}
		else
		{
			fprintf(out, "%d\n", -1);
		}
	}
	
	fclose(out);
	fclose(in);

	return 0;
}