Cod sursa(job #820233)
Utilizator | Cazacu Robert taigi100 | Data | 20 noiembrie 2012 15:37:02 |
---|---|---|---|
Problema | Elementul majoritar | Scor | 0 |
Compilator | cpp | Status | done |
Runda | Arhiva educationala | Marime | 0.55 kb |
#include <stdio.h>
int a[1000005];
int majoritar( int n)
{
int k=0, cand=-1;
for(int i=1;i<=n;i++)
{
if(k==0)
{
cand=a[i];
k=1;
}
else if(a[i]==cand)
k++;
else
k--;
}
if(cand<0)
return cand;
int nr=0;
for(int i=1;i<=n;i++)
if(cand==a[i])
nr++;
if(nr>(n/2))
return cand;
else
return -1;
}
int main()
{
FILE *f=fopen("elmaj.in","r");
int n;
fscanf(f,"%d",&n);
for(int i=1;i<=n;i++)
fscanf(f,"%d",a+i);
FILE *g=fopen("elmaj.out","w");
fprintf(g,"%d",majoritar(n));
}