I solved the question described below using priority queue and got a solution, but it is not optimal. Can someone help me with a better approach?

Viewed 885

There are K burners in the lab and N gas cylinders for the fuel. Each cylinder has a different capacity. Now in each lab K students come to use the K burners. When lab starts all students connect their burner to a cylinder and start the burner. Students can change the cylinder in between themselves and with the cylinder which is idle, exchange takes negligible time. Now find the maximum time possible for which all K burners can burn simultaneously. Exchange can be done only in integral units not fractional. (you can exchange at 1 second or 2 seconds, not at 1.5 seconds).

Example: N=3, K=2, X=[3,3,3] The solution is 4 seconds.

My code implementation is as follows:

#include <iostream>
#include <queue>
#include <vector>

int main() {
    std::vector<int> A = {3, 3, 3};
    std::size_t k = 2;

    std::priority_queue<int> pq;

    for (std::size_t i = 0; i < A.size(); i++) {
        pq.push(A[i]);
    }
    int time = 0;

    while (pq.size() >= k) {
        std::vector<int> arr;
        while (arr.size() < k) {
            arr.push_back(pq.top());
            pq.pop();
        }

        time += 1;
        for (std::size_t i = 0; i < arr.size(); i++) {
            arr[i] -= 1;
            if (arr[i] != 0) pq.push(arr[i]);
        }
    }

    std::cout << time << std::endl;
}

It is not optimal as the time complexity is O(time * K * log(K)).

0 Answers
Related