Buy the ticket
1. The first person (pi) in the queue requests for the ticket.
2. If there is another person present in the queue who has higher priority than pi, then ask pi to move at end of the queue without giving him the ticket.
3. Otherwise, give him the ticket (and don't make him stand in queue again).
The first line of input contains an integer, that denotes the value of total number of people standing in queue or the size of the array of priorities. Let us denote it with the symbol N.
The following line contains N space separated integers, that denote the value of the elements of the array of priorities.
The following contains an integer, that denotes the value of index of your priority. Let us denote it with symbol k.
The first and only line of output contains the time required for you to get the ticket.
Time Limit: 1 sec
3
3 9 4
2
2
Person with priority 3 comes out. But there is a person with higher priority than him. So he goes and then stands in the queue at the end. Queue's status : {9, 4, 3}. Time : 0 secs.
Next, the person with priority 9 comes out. And there is no person with higher priority than him. So he'll get the ticket. Queue's status : {4, 3}. Time : 1 secs.
Next, the person with priority 4 comes out (which is you). And there is no person with higher priority than you. So you'll get the ticket. Time : 2 secs.
5
2 3 2 2 4
3
4
#include<queue>#include<bits/stdc++.h>//given list of priorities of n people and index of our priority(k)#include <queue>// K is the person of interestint buyTicket(int *arr, int n, int k){ priority_queue<pair<int,int>> pq;
for(int i = 0; i<n; i++){ pq.push({arr[i], i});}
// cout<<ans<<endl;int cnt = 0;
while(pq.size() > 0){
pair<int,int> p = pq.top(); // cout<<p.first<<" "<<p.second<<endl; ++cnt; if(p.second != k) { pq.pop(); } else { break; }
}
return cnt;
}
Comments
Post a Comment