Cod sursa(job #1081783)

Utilizator razvan9310FMI - Razvan Damachi razvan9310 Data 13 ianuarie 2014 21:44:21
Problema Elementul majoritar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
#include <iostream>
#include <unordered_map>
#define MAXN 1000000
using namespace std;

int v[MAXN];

int main() {
	int N;
	ifstream in("elmaj.in");
	in >> N;

	int k = 0, no = 0;
	string input;
	getline(in, input);
	getline(in, input);
	int size = input.size();

	for (int j = 0; j <= size; ++j) {
		if (j == size || input[j] == ' ') {
			v[k++] = no;
			no = 0;
		} else {
			no = no * 10 + input[j] - '0';
		}
	}

	unordered_map<unsigned, unsigned> hashmap;

	for (int i = 0; i < N; ++i) {
		unordered_map<unsigned, unsigned>::iterator found = hashmap.find(v[i]);

		if (found == hashmap.end()) {
			hashmap.insert(make_pair(v[i], 1));
		} else {
			int count = found->second;
			hashmap.erase(found);
			hashmap.insert(make_pair(v[i], count + 1));
		}
	}
	in.close();

	int best = -1, count = 0;
	unordered_map<unsigned, unsigned>::iterator i = hashmap.begin(), stop = hashmap.end();

	while (i != stop) {
		if (i->second >= N / 2 + 1) {
			best = i->first;
			count = i->second;
		}
		++i;
	}

	ofstream out("elmaj.out");
	out << best << " ";
	if (best != -1) {
		out << count;
	}
	out.close();

	return 0;
}