KillCode's Wish

KillCode is very thrilled to have won unlimited ladoos in a programming competition. But being a generous programmer he decided to give away all his ladoos to small children. Now there are n children standing in a queue where a[i] denotes the hunger of ith child. KillCode can give a maximum of M ladoos to a child at a time. Now there are 2 conditions :

1- If a child gets equal to or more ladoos than his hunger, then he will return back to his home.

2- If a child gets fewer ladoos, he will take m ladoos and will move to last in the queue to get his turn again.

Example:

Input:  n = 5, m = 2, a = {1, 3, 1, 4, 2}
Output: 4

Approach

C++

#include <bits/stdc++.h>
using namespace std;

bool cmp(pair<int, int> a, pair<int, int> b)
{
    if (a.first == b.first)
        return a.second < b.second;
    return a.first < b.first;
}

int killcodeWish(int n, int m, int a[])
{

    queue<pair<int, int>> q;
    for (int i = 0; i < n; i++)
        q.push({a[i], i + 1});
    while (q.size() > 1)
    {
        pair<int, int> p = q.front();
        q.pop();
        int x = p.first;
        x = x - m;
        if (x > 0)
            q.push({x, p.second});
    }
    pair<int, int> p1 = q.front();
    return p1.second;
}
int main()
{
    int n = 5, m = 2;

    int a[n] = {1, 3, 1, 4, 2};

    cout << killcodeWish(n, m, a) << "\n";

    return 0;
}


No comments:

Post a Comment