2.5.12

上次更新:2019-04-17
发现了题解错误/代码缺陷/排版问题?请点这里:如何:提交反馈

解答

官方解答:https://algs4.cs.princeton.edu/25applications/SPT.java.html

把任务按照处理时间升序排序即可。
建立 Job 类,保存任务的名称和处理时间,并实现了 IConparable<Job> 接口。

class Job : IComparable<Job>
{
    public string Name;
    public double Time;

    public Job(string name, double time)
    {
        this.Name = name;
        this.Time = time;
    }

    public int CompareTo(Job other)
    {
        return this.Time.CompareTo(other.Time);
    }
}

代码

using System;

namespace _2._5._12
{
    class Program
    {
        class Job : IComparable<Job>
        {
            public string Name;
            public double Time;

            public Job(string name, double time)
            {
                this.Name = name;
                this.Time = time;
            }

            public int CompareTo(Job other)
            {
                return this.Time.CompareTo(other.Time);
            }
        }

        static void Main(string[] args)
        {
            // 官方解答:https://algs4.cs.princeton.edu/25applications/SPT.java.html
            int n = int.Parse(Console.ReadLine());
            Job[] jobs = new Job[n];
            for (int i = 0; i < n; i++)
            {
                string[] input = Console.ReadLine().Split(' ');
                jobs[i] = new Job(input[0], double.Parse(input[1]));
            }
            Array.Sort(jobs);
            for (int i = 0; i < jobs.Length; i++)
            {
                Console.WriteLine(jobs[i].Name + " " + jobs[i].Time);
            }
        }
    }
}
上一题 下一题