📜  给定作业列表中的最大CPU负载

📅  最后修改于: 2021-05-04 11:13:24             🧑  作者: Mango

给定一系列具有不同时间要求的作业,其中每个作业包括开始时间结束时间CPU负载。如果所有作业都在同一台计算机上运行,则任务是随时查找最大CPU负载。

例子:

此问题通常是合并间隔的应用。
方法:想法是根据工作的结束时间来保持最小堆。然后,为每个实例找到已完成的作业,然后将它们从“最小堆”中删除。即,检查最小堆中作业的结束时间是否在当前作业的开始时间之前结束。同样,在每个实例中,通过获取最小堆中存在的所有作业的总和来找到计算机上的最大CPU负载。

例如:

Given Jobs be {{1, 4, 3}, {2, 5, 4}, {7, 9, 6}}
Min-Heap - {}

Instance 1:
The job {1, 4, 3} is inserted into the min-heap
Min-Heap - {{1, 4, 3}},
Total CPU Load  = 3

Instance 2:
The job {2, 5, 4} is inserted into the min-heap.
While the job {1, 4, 3} is still in the CPU, 
because end-time of Job 1 is greater than 
the start time of the new job {2, 5, 4}.
Min-Heap - {{1, 4, 3}, {2, 5, 4}}
Total CPU Load = 4 + 3 = 7

Instance 3:
The job {7, 9, 6} is inserted into the min-heap.
After popping up all the other jobs because their
end time is less than the start time of the new job
Min Heap - {7, 9, 6}
Total CPU Load =  6

Maximum CPU Load = max(3, 7, 6) = 7

下面是上述方法的实现:

C++
// C++ implementation to find the
// maximum CPU Load from the given
// lists of the jobs
 
#include 
#include 
#include 
#include 
 
using namespace std;
 
// Blueprint of the job
class Job {
    public:
        int start = 0;
        int end = 0;
        int cpuLoad = 0;
         
        // Constructor function for
        // the CPU Job
        Job(int start, int end,
                   int cpuLoad)
        {
            this->start = start;
            this->end = end;
            this->cpuLoad = cpuLoad;
        }
};
 
class MaximumCPULoad {
     
    // Structure to compare two
    // CPU Jobs by their end time
    public:
        struct endCompare {
            bool operator()(const Job& x,
            const Job& y) {
                return x.end > y.end;
            }
        };
     
    // Function to find the maximum
    // CPU Load at any instance of
    // the time for given jobs
    static int findMaxCPULoad(
                 vector& jobs)
    {
        // Condition when there are
        // no jobs then CPU Load is 0
        if (jobs.empty()) {
            return 0;
        }
         
        // Sorting all the jobs
        // by their start time
        sort(jobs.begin(), jobs.end(),
          [](const Job& a, const Job& b) {
              return a.start < b.start;
          });
 
        int maxCPULoad = 0;
        int currentCPULoad = 0;
         
        // Min-heap implemented using the
        // help of the priority queue
        priority_queue,
                    endCompare> minHeap;
                     
        // Loop to iterate over all the
        // jobs from the given list
        for (auto job : jobs) {
             
            // Loop to remove all jobs from
            // the heap which is ended
            while (!minHeap.empty() &&
             job.start > minHeap.top().end) {
                currentCPULoad -=
                   minHeap.top().cpuLoad;
                minHeap.pop();
            }
             
            // Add the current Job to CPU
            minHeap.push(job);
            currentCPULoad += job.cpuLoad;
            maxCPULoad = max(maxCPULoad,
                            currentCPULoad);
        }
        return maxCPULoad;
    }
};
 
// Driver Code
int main(int argc, char* argv[])
{
    vector input = { { 1, 4, 3 },
            { 7, 9, 6 }, { 2, 5, 4 } };
    cout << "Maximum CPU load at any time: "
         << MaximumCPULoad::findMaxCPULoad(input)
         << endl;
 
}


Python3
# Python implementation to find the
# maximum CPU Load from the given
# lists of the jobs
 
from heapq import *
 
# Blueprint of the job
class job:
     
    # Constructor of the Job
    def __init__(self, start,\
              end, cpu_load):
        self.start = start
        self.end = end
        self.cpu_load = cpu_load
     
    # Operator overloading for the
    # Object that is Job
    def __lt__(self, other):
 
        # min heap based on job.end
        return self.end < other.end
 
# Function to find the maximum
# CPU Load for the given list of jobs
def find_max_cpu_load(jobs):
     
    # Sort the jobs by start time
    jobs.sort(key = lambda x: x.start)
    max_cpu_load, current_cpu_load = 0, 0
     
    # Min-Heap
    min_heap = []
     
    # Loop to iterate over the list
    # of the jobs given for the CPU
    for j in jobs:
         
        # Remove all the jobs from
        # the min-heap which ended
        while(len(min_heap) > 0 and\
          j.start >= min_heap[0].end):
            current_cpu_load -= min_heap[0].cpu_load
            heappop(min_heap)
     
        # Add the current job
        # into min_heap
        heappush(min_heap, j)
        current_cpu_load += j.cpu_load
        max_cpu_load = max(max_cpu_load,
                       current_cpu_load)
    return max_cpu_load
 
# Driver Code
if __name__ == "__main__":
    jobs = [job(1, 4, 3), job(2, 5, 4),\
                         job(7, 9, 6)]
                          
    print("Maximum CPU load at any time: " +\
               str(find_max_cpu_load(jobs)))


Java
// JAVA Implementation of the above
// approach
 
import java.util.Arrays;
import java.util.*;
 
public class MaximumCpuLoad {
     
private static int maxCpuLoad(int[][] process) {
    Arrays.sort(process,(a,b)->'
    {
        return a[0]-b[0];
    });
     
      
    // list of intervals
    List li = new LinkedList();
     
      
    // variable to store the result
    int ans=0;
      
    // Merge intervals
    for(int[] p : process)
    {
        if(!li.isEmpty() && p[0]


输出
Maximum CPU load at any time: 7

性能分析:

  • 时间复杂度: O(N * logN)
  • 辅助空间: O(N)

方法2 –不使用堆,合并重叠间隔。

这也可以通过使用“合并间隔”的思想来解决。
这个想法很简单–>合并重叠的间隔并添加它们的负载。
下面是相同的Java代码。

Java

// JAVA Implementation of the above
// approach
 
import java.util.Arrays;
import java.util.*;
 
public class MaximumCpuLoad {
     
private static int maxCpuLoad(int[][] process) {
    Arrays.sort(process,(a,b)->'
    {
        return a[0]-b[0];
    });
     
      
    // list of intervals
    List li = new LinkedList();
     
      
    // variable to store the result
    int ans=0;
      
    // Merge intervals
    for(int[] p : process)
    {
        if(!li.isEmpty() && p[0]
输出
7