2.5.13

question:

Load balancing. Write a program LPT.java that takes an integer M as a command-line argument, reads job names and processing times from standard input and prints a schedule assigning the jobs to M processors that approximately minimizes the time when the last job completes using the longest processing time first rule, as described on page 349.

answer:

import edu.princeton.cs.algs4.*;
import java.util.Arrays;

public class LPT
{
    private static class Job implements Comparable<Job>
    {
        String name;
        double time;
        
        public Job(String a, double b)
        {
            name = a;
            time = b;
        }
        
        public int compareTo(Job that)
        {
            return (int)(this.time - that.time);
        }
        
        public void show()
        {
            StdOut.println(name + " " + time);
        }
    }
    
    private static class Processor implements Comparable<Processor>
    {
        double time;
        
        public Processor(double t)
        {
            time = t;
        }
        
        public Processor()
        {
            time = 0;
        }
        
        public void addtime(double t)
        {
            time+=t;
        }
        
        public int compareTo(Processor that)
        {
            return (int)(this.time - that.time);
        }
        
        public void show()
        {
            StdOut.println(time);
        }
    }
    
    public static void main(String[] args)
    {
        //5 6 a 11 b 22 c 1 d 4 e 9 f 71
        int x = StdIn.readInt();//x个处理器
        MinPQ<Processor> pq = new MinPQ<Processor>(x);//放x个处理器的优先队列
        int y = StdIn.readInt();//y个任务
        Job[] jobs = new Job[y];
        for(int i = 0; i < y; i++)
        {
            String name = StdIn.readString();
            int time = StdIn.readInt();
            jobs[i] = new Job(name, time);
        }
        Arrays.sort(jobs);//任务排序
        
        for (int i = 0; i < x; i++)//先放入空闲处理器
            pq.insert(new Processor());
        
        for(int i = y-1; i>=0; i--)//任务从大到小布置给处理器,这样总时间最短
        {
            Processor t = pq.delMin();
            t.addtime(jobs[i].time);
            pq.insert(t);
        }
        
        while(!pq.isEmpty())//输出所有处理器处理的时间
        {
            Processor c = pq.delMin();
            c.show();
        }
            
    }
}

猜你喜欢

转载自www.cnblogs.com/w-j-c/p/9147336.html