Cod sursa(job #1651924)
| Utilizator | Data | 14 martie 2016 11:09:56 | |
|---|---|---|---|
| Problema | Elementul majoritar | Scor | 0 |
| Compilator | cpp | Status | done |
| Runda | Arhiva educationala | Marime | 0.71 kb |
#include <fstream>
using namespace std;
ifstream fin("elmaj.in");
ofstream fout("elmaj.out");
const int Ndim = 1000001;
int V[Ndim],N;
void read()
{
fin>>N;
for(int i=1;i<=N;i++)
fin>>V[i];
}
int elmaj()
{
int cand = -1,k=0,i;
for(i=1;i<=N;i++)
{
if(k==0)
{
cand = V[i];
k=1;
}
else if(V[i] == cand)
k++;
else
k--;
}
if(cand < 0)
return -1;
int nr = 0;
for(i=1;i<=N;i++)
{
if(V[i] == cand)
nr++;
}
if(nr > N/2)
return cand;
return -1;
}
int main()
{
read();
fout<<elmaj();
return 0;
}
