A Queue Problem

View as PDF

Submit solution

Points: 5
Time limit: 2.0s
Memory limit: 256M

Author:
Problem type

There are N people in a line buying tickets, where the person at index 0 is at the front of the line and index N-1 is at the back of the line. Every person i (0-indexed) would like to buy a_i tickets.

Each person takes exactly 1 second to buy a ticket, and only one ticket at a time. After purchasing a ticket, they have to go to the end of the line (which takes 0 seconds) to buy more tickets. A person leaves the line entirely when they have no more tickets to buy. Find the time it takes for the person initially at position K (0-indexed) to finish buying tickets.

Input Specification

The first line of input will contain two space-separated integers N and K, representing the number of people in the line and the initial index of the person.

The second line of input will contain N space-separated integers a_i, representing the number of tickets each person would like to buy.

Output Specification

Output one integer, representing the time it takes for the person originally at K to finish buying their tickets.

Constraints

1 \le N \le 2 \times 10^5

0 \le K \le N-1

1 \le a_i \le 100

Sample Input 1

4 0
5 1 1 1

Sample Output 1

8

Sample Explanation

The queue starts at person 0, which moves to the back of the line after 1 second (array: [1,1,1,4]).

After another 3 seconds, the array will be [4] (the person 0 still needs to purchase 4 tickets).

After another 4 seconds, the array will be empty. In total, it took 1 + 3 + 4 = 8 seconds.

Sample Input 2

3 2
2 3 2

Sample Output 2

6

Comments

There are no comments at the moment.