Cod sursa(job #1326507)

Utilizator charmpitzAndrei Pit charmpitz Data 25 ianuarie 2015 15:53:59
Problema Elementul majoritar Scor 0
Compilator c Status done
Runda Arhiva educationala Marime 2.14 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];
	}
}


void quicksort(int *v, int x, int y) {
	int h, i, j, aux, com;

	if (x < y)
	{
		i = x;
		j = y;
		com = 0;
		
		while(i != j)
		{
			if (v[i] > v[j])
			{
				aux = v[i];
				v[i] = v[j];
				v[j] = aux;

				com = 1-com;
			}

			if (com == 0) 
				i++;
			else
				j--;
		}

		h = i;

		quicksort(v, x, h);
		quicksort(v, h+1, y);
	}
}

int main ()
{
	int maj, 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);
	quicksort(v, 1, n);

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

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

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

	return 0;
}