最短平均等待时间问题

本文最后更新于:2024年3月18日 凌晨

最短平均等待时间问题

问题描述

  • 设有n个顾客同时等待同一项服务,顾客i需要的服务时间为ti(1<=i<=n),应如何安排n个顾客的服务次序才能使平均等待时间达到最小?平均等待时间是n个顾客等待服务时间的总和除以n

代码实现

流程图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class Waiting {

public static void main(String[] args) {
float[] w = {1, 3, 10, 5, 3, 5, 6, 8, 1, 2, 12};
int n = w.length;
float[] x = new float[n];
int[] order = new int[n];
float T = Waiting(x, w, n, order);
for (int i = 0; i < n; i++) {
System.out.printf("%3d:服务时间: %5.2f 服务顺序: %3d 等待时间: %5.2f\n", (i + 1), w[i], (order[i] + 1), x[i]);
}
System.out.printf("平均等待时间为: %.2f分钟", T);
}

public static float Waiting(float[] x, float[] w, int n, int[] order) {
int[] t = new int[n];
Sort(w, t, n);
int temp = 0;
float T = 0;
for (int i = 0; i < n; i++) {
x[t[i]] = temp;
temp += w[t[i]];
order[t[i]] = i;
}
for (int i = 0; i < n; i++) {
T += x[i];
}
return T / n;
}

public static void Sort(float[] w, int[] t, int n) {
float[] array = w.clone();
float temp;
int index;
for (int i = 0; i < n; i++) {
t[i] = i;
}

for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (array[j] > array[j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;

index = t[j];
t[j] = t[j + 1];
t[j + 1] = index;
}
}
}
}
}
  • float Waiting(float[] x, float[] w, int n, int[] order):计算最短平均等待时间。
    • float[] x:每位顾客的等待时间。
    • float[] w:每位顾客的服务时间。
    • int n:顾客的数量。
    • int[] order:顾客被服务的顺序。
    • return:最短平均等待时间。
  • Sort(float[] w, int[] t, int n):通过服务时间由小到大将顾客排序。
    • float[] w:每位顾客的服务时间。
    • int[] t:排序后w数组的下标顺序。
    • int n:顾客的数量。

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!