Cod sursa(job #1893533)

Utilizator dumitrualexAlex Dumitru dumitrualex Data 25 februarie 2017 19:12:42
Problema Elementul majoritar Scor 100
Compilator java Status done
Runda Arhiva educationala Marime 1.93 kb
import java.io.*;
import java.util.*;

public class Main {
	static int N;
	static int[] v;

	public static void main(String[] args) 
	 throws IOException
	 {
		Reader in = new Reader(new FileInputStream("elmaj.in"));
		PrintWriter out = new PrintWriter(new FileWriter("elmaj.out"));
		N = in.nextInt();
		v = new int[N];

		for (int i = 0; i < N; i++)
			v[i] = in.nextInt();

		int el = v[0];
		int cnt = 1;

		boolean ok = false;

		for (int i = 1; i < N; i++)
			if (v[i] != el)
			{
				cnt--;
				if (cnt == 0)
				{
					el = v[i];
					cnt = 1;
				}
			}
			else
				cnt++;

		cnt = 0;

		for (int x : v)
			if (x == el)
				cnt++;

		if (cnt >= N/2 + 1)
			out.printf("%d %d\n", el, cnt);
		else
			out.printf("-1\n");

		out.close();
	}

	private static class Reader {
        private BufferedInputStream stream;
        private byte[] buffer;
        int buffSize;
        private int buffPointer;
 
        protected final int BUFF_CAPACITY = 5000;
 
        protected Reader(FileInputStream file) {
            stream = new BufferedInputStream(file);
            buffer = new byte[BUFF_CAPACITY];
            buffPointer = buffSize = 0;
        }
 
        private void fillBuffer() throws IOException {
            buffSize = stream.read(buffer, 0, BUFF_CAPACITY);
            buffPointer = 0;
        }
 
        private byte readByte() throws IOException {
            if (buffPointer >= buffSize) {
                fillBuffer();
            }
            return buffer[buffPointer++];
        }
 
        protected int nextInt() throws IOException {
            byte b = readByte();
            while (b < '0' || b > '9') {
                b = readByte();
            }
 
            int num = 0;
            while (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
                b = readByte();
            }
            return num;
        }
    }
}