Pagini recente » Cod sursa (job #2606513) | Cod sursa (job #1753096) | Cod sursa (job #3169609) | Cod sursa (job #2957756) | Cod sursa (job #1209471)
#include <fstream>
#define NMAX 1000000
using namespace std;
ifstream f("elmaj.in");
ofstream g("elmaj.out");
int n, v[NMAX];
int numberVotesMajority(int candidate) {
int votes = 0;
for (int i = 0; i < n; ++i) {
if (v[i] == candidate) {
votes++;
}
}
if (votes > n / 2) {
return votes;
}
return -1;
}
int main() {
f >> n;
f >> v[0];
// first candidate standing
int index = 0, count = 1;
// read data and find candidate to stand up after voting for majority
for (int i = 1; i < n; ++i) {
f >> v[i];
if (v[index] == v[i]) {
// voters sustain same candidate
count++;
}
else {
// voters sustain different candidates
count--;
}
// new candidate to take into account
if (count == 0) {
index = i;
count = 1;
}
}
int noVotes = numberVotesMajority(v[index]);
if (noVotes > 0) {
g << v[index] << " " << noVotes << "\n";
}
else {
g << "-1\n";
}
return 0;
}