Pagini recente » Cod sursa (job #1981428) | Cod sursa (job #2220351) | Cod sursa (job #1477594) | Cod sursa (job #2227436) | Cod sursa (job #1499748)
/*
Moore’s Voting Algorithm - implemented by Je
*/
#include<fstream>
#define MAXN 1000001
#define FIN "elmaj.in"
#define FOUT "elmaj.out"
using namespace std;
ifstream f(FIN);
ofstream g(FOUT);
int v[MAXN];
int n;
int main()
{
f >> n;
int x;
//init first element
f >> x;
int candidate = 1;
v[candidate] = x;
int votes = 1;
for(int i=2; i<=n; i++)
{
f >> v[i];
if(v[candidate] == x)
{
votes++;
}
else if(votes > 1)
{
votes--;
}
else
{
candidate = x;
votes = 1;
}
}
int counter = 0;
//cehck if is majority
for(int i=1; i<=n; i++)
{
if(v[i] == v[candidate])
counter++;
}
if(counter >= (n/2)+1)
{
g << v[candidate] << " " << counter;
}
else
{
g << "-1";
}
return 0;
}