博客
关于我
P1223_排队接水(JAVA语言)
阅读量:124 次
发布时间:2019-02-27

本文共 1778 字,大约阅读时间需要 5 分钟。

为了解决这个问题,我们需要找到一种排队顺序,使得n个人的平均等待时间最小。根据短作业优先调度算法,我们可以确定处理时间较短的人应该排在前面,以减少整体的平均等待时间。

方法思路

  • 问题分析:每个人在排队时的等待时间是前面所有人处理时间的总和。为了最小化平均等待时间,我们需要安排处理时间较短的人更早排队。
  • 排序策略:将处理时间从小到大排序。如果处理时间相同,则按照原输入顺序排列。
  • 计算等待时间:遍历排序后的队列,计算每个人的等待时间,并累加到总和中。
  • 输出结果:输出排队顺序及其平均等待时间。
  • 解决代码

    import java.util.Arrays;import java.util.Comparator;public class Main {    public static void main(String[] args) {        Scanner in = new Scanner(System.in);        int n = in.nextInt();        int[] times = new int[n];        for (int i = 0; i < n; i++) {            times[i] = in.nextInt();        }                Muta[] mutas = new Muta[n];        for (int i = 0; i < n; i++) {            mutas[i] = new Muta(times[i], i + 1);        }                Arrays.sort(mutas, new Comparator
    () { @Override public int compare(Muta a, Muta b) { if (a.v != b.v) { return Integer.compare(a.v, b.v); } else { return Integer.compare(a.o, b.o); } } }); StringBuilder orderStr = new StringBuilder(); for (Muta m : mutas) { orderStr.append(m.o).append(" "); } System.out.println(orderStr.toString().trim()); double total = 0; double sum = 0; for (Muta m : mutas) { total += sum; sum += m.v; } System.out.println(String.format("%.2f", total / n)); } static class Muta { int v; int o; Muta(int v, int o) { this.v = v; this.o = o; } }}

    代码解释

  • 读取输入:从标准输入读取n和每个人的处理时间数组。
  • 创建Muta对象:将每个处理时间和原索引存储在Muta对象中。
  • 排序处理时间:根据处理时间从小到大排列,处理时间相同则按原索引排序。
  • 生成排列顺序:提取排序后的索引,生成排队顺序字符串。
  • 计算等待时间:遍历排序后的队列,计算每个人的等待时间并累加到总和中。
  • 输出结果:输出排队顺序和平均等待时间,保留两位小数。
  • 转载地址:http://hwcb.baihongyu.com/

    你可能感兴趣的文章
    php 2条不一样 的json数据 怎么放在一个json里面_如果你是PHP开发者,请务必了解一下Composer...
    查看>>
    php 360 不记住密码,JavaScript_多种方法实现360浏览器下禁止自动填写用户名密码,目前开发一个项目遇到一个很 - phpStudy...
    查看>>
    regExp的match、exec、test区别
    查看>>
    php 404 自定义,APACHE 自定义404错误页面设置方法
    查看>>
    PHP 5.3.0以上推荐使用mysqlnd驱动
    查看>>
    php aes sha1解密,PHP AES加密/解密
    查看>>
    php CI框架单个file表单多文件上传例子
    查看>>
    reflow和repaint引发的性能问题
    查看>>
    php csv 导出
    查看>>
    php curl 实例+详解
    查看>>
    php curl_init函数用法(http://blog.sina.com.cn/s/blog_640738130100tsig.html)
    查看>>
    php curl_multi批量发送http请求
    查看>>
    php echo 输出 锘?... 乱码问题
    查看>>
    ReferenceQueue的使用
    查看>>
    Referenced classpath provider does not exist: org.maven.ide.eclipse.launchconfig
    查看>>
    Refactoring-Imporving the Design of Exsiting Code — 代码的坏味道
    查看>>
    PHP imap 远程命令执行漏洞复现(CVE-2018-19518)
    查看>>
    php include和require
    查看>>
    ref 和out 区别
    查看>>
    php JS 导出表格特殊处理
    查看>>