C++ | Intuitive | map | heap | set | binary search
Servers : The available servers right now\npq : Busy servers right now\nbusy : a map which contains the number of requests a servere handles\n\nIntuition : We c
Servers : The available servers right now\npq : Busy servers right now\nbusy : a map which contains the number of requests a servere handles\n\nIntuition : We compare the end time of currently busy servers with the arrival time of the new request. If the arrival time is greater, that means our server has finished its task and is now free to use.\n\nHow to handle next request?\nSince the set is sorted, we search the next element which is greater than or equal to the required server. If we can\'t find any such server, then we go back to the begining of the set to find the first free server.\n\nWe can further optimize it using unordered_map for busy.\n\n```\nclass Solution {\npublic:\n    vector<int> busiestServers(int k, vector<int>& arrival, vector<int>& load) {\n        set<int> servers;\n        priority_queue< pair<int,int> ,vector<pair<int,int>> ,greater<pair<int,int>> > pq;\n        \n        for(int i=0;i<k;i++)\n            servers.insert(i);\n        \n        map<int ,int> busy;\n        int n=arrival.size();\n        for(int i=0;i<n;i++)\n        {\n            int start=arrival[i],end=arrival[i]+load[i];\n            while(!pq.empty() and pq.top().first<=start)\n            {\n                auto it=pq.top();\n                pq.pop();\n                servers.insert(it.second);\n            }\n            if(servers.empty())\n                continue;\n            auto ser=servers.lower_bound(i%k);\n            if(ser==servers.end())\n                ser=servers.begin();\n            \n            int serverNo=*ser;\n            cout<<serverNo<<" ";\n            pq.push({end,serverNo});\n            busy[serverNo]++;\n            servers.erase(ser);\n        }\n        int maxBusy=0;\n        for(auto it:busy)\n            maxBusy=max(maxBusy,it.second);\n        vector<int> res;\n        for(auto it:busy)\n        {\n            if(it.second==maxBusy)\n                res.push_back(it.first);\n        }\n        return res;\n    \n    }\n};\n```
['C', 'Heap (Priority Queue)', 'Binary Tree', 'Ordered Set']