博客
关于我
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/

    你可能感兴趣的文章
    poj 2406 还是KMP的简单应用
    查看>>
    POJ 2431 Expedition 优先队列
    查看>>
    Qt笔记——获取位置信息的相关函数
    查看>>
    POJ 2484 A Funny Game(神题!)
    查看>>
    POJ 2486 树形dp
    查看>>
    POJ 2488:A Knight&#39;s Journey
    查看>>
    SpringBoot为什么易学难精?
    查看>>
    poj 2545 Hamming Problem
    查看>>
    poj 2723
    查看>>
    poj 2763 Housewife Wind
    查看>>
    Qt笔记——模型/视图MVD 文件目录浏览器软件
    查看>>
    POJ 2892 Tunnel Warfare(树状数组+二分)
    查看>>
    poj 2965 The Pilots Brothers' refrigerator-1
    查看>>
    poj 3026( Borg Maze BFS + Prim)
    查看>>
    POJ 3041 - 最大二分匹配
    查看>>
    POJ 3041 Asteroids(二分匹配模板题)
    查看>>
    Qt笔记——标准文件对话框QFileDialog
    查看>>
    poj 3083 Children of the Candy Corn
    查看>>
    POJ 3083 Children of the Candy Corn 解题报告
    查看>>
    POJ 3253 Fence Repair C++ STL multiset 可解 (同51nod 1117 聪明的木匠)
    查看>>