Cod sursa(job #2384150)

Utilizator arcoC. Nicolae arco Data 20 martie 2019 13:45:45
Problema Elementul majoritar Scor 30
Compilator java Status done
Runda Arhiva educationala Marime 1.06 kb
import java.io.*;
import java.util.*;

public class Main 
{
	public static void main(String []args) throws IOException
	{
		Scanner fr = null;
		PrintWriter fw = null;
		try
		{
			fr = new Scanner(new BufferedReader(new FileReader("elmaj.in")));
			fw = new PrintWriter("elmaj.out");
			
			int n = Integer.parseInt(fr.nextLine());
			
			int count = 1;
			int last = fr.nextInt();
			
			for(int i = 1; i < n; i++)
			{
				int t = fr.nextInt();
				
				if(count == 0)
				{
					last = t;
					count = 1;
				}
				else
				{
					if(t == last)
						count++;
					else
						count--;
				}
			}
			fr = new Scanner(new File("elmaj.in"));
			fr.nextLine();
			
			int occ = 0;
			for(int i = 0; i < n; i++)
			{
				if(fr.nextInt() == last)
				{
					occ++;
				}
			}
			
			if(occ >= (n / 2 + 1))
				fw.printf("%d %d\n", last, occ);
			else
				fw.println(-1);
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			if(fr != null)
				fr.close();
			if(fw != null)
				fw.close();
		}
	}
}