# Online Election in C++

Suppose in an election, the i-th vote was cast for persons[i] at time times[i]. Now, we have to implement the following query function: TopVotedCandidate.q(int t) this will find the number of the person that was leading the election at time t. Votes cast at time t will count towards our query. If there is a tie, the most recent vote (among tied candidates) wins.

So if we initialize this with TopVotedCandidate([0,1,1,0,0,1,0], [0,5,10,15,20,25,30]), then call q() like: q(3), q(12), q(25), q(15), q(24), q(8), then the result will be [0, 1, 1, 0, 0, 1] for each call of q(). This is because at time 3, the votes are [0], and 0 is leading. At time 12, the votes are [0,1,1], and here 1 is leading. At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.). This continues for 3 more queries at time 15, 24, and finally 8.

To solve this, we will follow these steps −

• Create two maps m and count

• In the initializer, do the following tasks

• for i in range 0 to size of times array

• x := times[i]

• increase the value of count[persons[i]] by 1

• the q() method will be like

• decrease the upper bound of t in m, and return the corresponding value

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class TopVotedCandidate {
public:
map <int, int> m;
map <int, int> count;
TopVotedCandidate(vector<int>& persons, vector<int>& times) {
for(int i = 0; i < times.size(); i++){
int x = times[i];
count[persons[i]]++;
}else{
}
}
}
int q(int t) {
return ((--m.upper_bound(t)) -> second);
}
};
main(){
vector<int> v1 = {0,1,1,0,0,1,0}, v2 = {0,5,10,15,20,25,30};
TopVotedCandidate ob(v1, v2);
cout << (ob.q(3)) << endl;
cout << (ob.q(12)) << endl;
cout << (ob.q(25)) << endl;
cout << (ob.q(15)) << endl;
cout << (ob.q(24)) << endl;
cout << (ob.q(8)) << endl;
}

### Input

Initialize the class using [0,1,1,0,0,1,0] and [0,5,10,15,20,25,30]. Call q()
method like below:
q(3)
q(12)
q(25)
q(15)
q(24)
q(8)

## Output

0
1
1
0
0
1