Cod sursa(job #2662780)

Utilizator dream3rDavid Pop dream3r Data 24 octombrie 2020 14:28:46
Problema Elementul majoritar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <climits>
#include <string>
#include <queue>
#define max(a,b) a > b ? a : b
#define ll long long int
using namespace std;
ifstream f("elmaj.in");
ofstream o("elmaj.out");
vector<int>v;
int n;

void elMaj(int &candidate, int &aparitii)
{
	int appears = 0;
	int elmaj = -1;
	for (size_t i = 0; i < v.size(); i++)
	{
		if (elmaj != v[i])
		{
			appears--;
		}
		else
		{
			appears++;
		}
		if (appears <= 0)
		{
			appears = 1;
			elmaj = v[i];
		}
	}

	int ans = 0;

	for (size_t i = 0; i < v.size(); i++)
	{
		if (v[i] == elmaj)
		{
			ans++;
		}
	}

	if (ans >= (v.size() / 2) + 1)
	{
		candidate = elmaj;
		aparitii = ans;
	}
	else
	{
		candidate = -1;
		aparitii = -1;
	}
}

int main()
{
	f >> n;
	for (size_t i = 0; i < n; i++)
	{
		int x;
		f >> x;
		v.push_back(x);
	}

	int elmaj, appears;
	elmaj = appears = 0;
	elMaj(elmaj, appears);
	if (elmaj == -1)
	{
		o << "-1";
	}
	else
	{
		o << elmaj << " " << appears;
	}

}