Cpp Simple Solutions
Cpp Simple Solutions
C++ Solutions
1. Server Upgrade Planning
Problem: Two servers require upgrades taking t1 and t2 seconds. Upgrades pause during
seconds when requests arrive (multiples of req1 for server 1, req2 for server 2). Only one
server can be upgraded at a time. Find the minimum total time to complete upgrades.
Approach: Use binary search over total time and inclusion-exclusion principle to calculate
blocked seconds.
C++ Code:
#include <iostream>
#include <algorithm>
using namespace std;
long long getMinUpgradationTime(long long req1, long long t1, long long req2, long long t2)
{
long long lo = 1, hi = 1000000000000000LL, ans = hi;
long long lcm = (req1 / gcd(req1, req2)) * req2;
int main() {
long long req1, t1, req2, t2;
cin >> req1 >> t1 >> req2 >> t2;
cout << getMinUpgradationTime(req1, t1, req2, t2) << "\n";
return 0;
}
C++ Code:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
vector<int> arr(n);
for (int i = 0; i < n; ++i) cin >> arr[i];
vector<int> res = getGreatestElements(arr, k);
for (int val : res) cout << val << " ";
cout << endl;
return 0;
}
3. Task Scheduling
Problem: Given n tasks each with memory and type, at most two tasks can run in parallel if
they share the same type and combined memory ≤ max_memory.
Each task takes 1 unit time. Find minimal total processing time.
Approach: Group tasks by type, sort them, then pair using two-pointer technique.
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
int total_time = 0;
for (auto& [type, tasks] : tasks_by_type) {
sort(tasks.begin(), tasks.end());
int left = 0, right = tasks.size() - 1;
while (left <= right) {
if (left != right && tasks[left] + tasks[right] <= max_memory) {
left++;
right--;
} else {
right--;
}
total_time++;
}
}
return total_time;
}
int main() {
int n, max_memory;
cin >> n >> max_memory;
vector<int> task_memory(n), task_type(n);
for (int i = 0; i < n; ++i) cin >> task_memory[i];
for (int i = 0; i < n; ++i) cin >> task_type[i];