C ++ realizes multiple optimal service order problems

Title: There are n customers waiting for a service at the same time. The service time required by customer i is ti, 1 <= ti <= n. A total of s places can provide this service. How to arrange the service order of n customers to minimize the average waiting time? The average waiting time is the sum of the waiting time of n customers divided by n.

Input example:

n = 10, s = 2
56 12 1 99 1000 234 33 55 99 812
output: 336

注意:在这个问题里面,将服务时间与等待时间一起算作等待时间,比如服务次序:

		   A			B			C
		   10			20			25
		   A的等待时间为10
		   B的等待时间为30
		   C的等待时间为55
		   
这与我们通常理解的等待时间和服务时间不一样

Here we use a greedy algorithm to solve, step by step to achieve the overall optimal

  • First sort the service time from small to large
  • Select the service where the current waiting time is the smallest and add the service with the smallest current time to this service
  • Repeat the previous step until all customers are scheduled
#include <iostream>
#include<algorithm>
using namespace std;

int SelectMin(int* wait,int s) {	//该函数实现	选出当前等待时间最小的服务处
    int min = wait[0];
    int index = 0;
    for (int i = 0; i < s; i++) {
        if (min > wait[i]) {
            min = wait[i];
            index = i;
        }
    }
    return index;
}

int Greedy(int* wait, int *arr, int n,int s) {	  //实现顾客的安排、总等待时间的计算
    int sum = 0;
    int index;
    for (int i = 0; i < n; i++) {
        index = SelectMin(wait, s);
        wait[index] += arr[i];
        sum += wait[index];
    }
    return sum / n;		//返回平均等待时间
}

int main()
{
    int n, s, res;
    cout << "Input N and S: ";
    cin >> n >> s;
    int* arr = new int[n];
    int* wait = new int[s]();
    cout << "Input waiting time: ";
    for (int i = 0; i < n; i++)
        cin >> arr[i];
    sort(arr, arr + n);		
    res= Greedy(wait, arr, n, s);
    cout << res;
    delete[] arr;
    delete[] wait;
    return 0;
}

Published 10 original articles · won 9 · visited 1717

Guess you like

Origin blog.csdn.net/weixin_43853811/article/details/105449239