Cod sursa(job #3225205)

Utilizator andreiqwerBesu-Roca Andrei andreiqwer Data 17 aprilie 2024 08:50:18
Problema Elementul majoritar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.63 kb
#include <fstream>

using namespace std;

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

#define nmax 1000000

int v[nmax+1], n;

pair<int, int> majority()
{
	int cand=-1, k=0;
	for(int i=1; i<=n; i++)
	{
		if(k==0)
			cand=v[i], k=1;
		else if(v[i]==cand)
			k++;
		else
			k--;
	}

	int cnt=0;
	for(int i=1; i<=n; i++)
	{
		if(v[i]==cand)
			cnt++;
	}

	if(cnt>n/2)
		return {cand, cnt};
	else 
		return {-1, -1};
}

int main()
{
	cin.tie(0);
	ios_base::sync_with_stdio(0);

	cin>>n;
	for(int i=1; i<=n; i++)
		cin>>v[i];

	pair<int, int> maj=majority();
	
	if(maj.first!=-1)
		cout<<maj.first<<' '<<maj.second;
	else
		cout<<-1;
}