Cod sursa(job #1021426)

Utilizator cioionutFMI Ionut Ciocoiu cioionut Data 3 noiembrie 2013 20:08:01
Problema Elementul majoritar Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include<iostream>
#include<fstream>
using namespace std;
ifstream in("elmaj.in");
ofstream out("elmaj.out");
struct nod
{
    int inf;
    nod *urm;
};
void push (int a, nod *&s)
{
    nod *q;
    if (s) {q=new nod;
            q->inf=a;
            q->urm=s;
            s=q;
            }
        else{s=new nod;
            s->inf=a;
            s->urm=NULL;
            }
}
int pop(nod *&s)
{
    int x=s->inf;
    nod *q;
    q=s;
    s=s->urm;
    delete(q);
    return x;
}
int peek(nod *s)
{
    return s->inf;
}
void afiseaza(nod *s)
{
    cout<<"stiva=";
    while(s) {cout<<s->inf<<" ";s=s->urm;}
    cout<<"\n";
}
bool goala(nod *s)
{
    if (s) return 1;
    else return 0;
}
int main()
{
    nod *s=NULL;
    int n,i,k,c=0,x;
    in>>n;
    for(i=0;i<n;i++)
    {
        in>>x;
        if(goala(s)) {if(peek(s)!=x) k=pop(s);else push(x,s);}
        else push(x,s);
    }
    in.close();
    ifstream in("elmaj.in");
    in>>n;
    if(goala(s)) {k=pop(s);
                  for(i=0;i<n;i++) {in>>x;if (x==k) c++;}
                  if (c>=n/2) out<<k<<" "<<c;
                  else out<<"-1";
                 }
                 else out<<"-1";
    in.close();
    out.close();
    return 0;
}