程序基本算法习题解析 最优服务次序问题

题目:

最优服务次序问题:设有n个顾客同时等待一项服务。顾客i需要的服务时间为ti,1<=i<=n。应如何安排n个顾客的服务次序,才能使平均等待时间最少?平均等待时间是n个顾客等待服务时间的总和除以n。

思路:

先服务等待时间最少的顾客,因此首先需要对顾客需要的服务时间进行排序,且每个顾客的等待时间除了自身需要的服务时间外,还需加上自己开始被服务前的等待时间(比自己的服务时间短的顾客的服务时间总和),最后对每个顾客的等待加服务时间进行求和求平均,即为最短平均等待时间。

附上代码:

// Chapter9_3.cpp : Defines the entry point for the application.
// 最优服务次序问题:设有n个顾客同时等待一项服务。顾客i需要的服务时间为ti,1<=i<=n。
// 应如何安排n个顾客的服务次序,才能使平均等待时间最少?
// 平均等待时间是n个顾客等待服务时间的总和除以n。

#include "stdafx.h"
#include<iostream>
using namespace std;

//排序
//从小到大,参数为:数组,数组个数
void funSort(int *a,int n)
{
	int temp;
	for(int i=0;i<n-1;i++)
		for(int j=i+1;j<n;j++)
		{
			if(a[i]>a[j])
			{
				temp = a[i];
				a[i] = a[j];
				a[j] = temp;
			}
		}
}
int minWaitingTime(int *a,int n) //数组a为顾客的服务时间
{
	int *b = new int[n];
	int i,sum=0;
	for(i=0;i<n;i++)
		b[i] = a[i];
	//最终的b[i]为第i位顾客等待的时间
	for(i=1;i<n;i++)
		b[i] = b[i]+b[i-1];
	//求顾客等待时间的总和
	for(i=0;i<n;i++)
		sum += b[i];
	delete []b;
	return sum/n; //返回平均等待时间
}
int main()
{
	int N,i,aveTime; //N:顾客总数,aveTime:p最少平均等待时间
	cout << "input the number of the customer: ";
	cin >> N;
	int *time = new int[N]; //用户输入的各顾客的服务时间
	cout << "input the need service time of each customer: " << endl;
	for(i=0;i<N;i++)
	{
		cout << "No" << i+1 << ": ";
		cin >> time[i];
	}
	funSort(time,N);

	cout << "排序后的数组为: ";
	for(i=0;i<N;i++)
		cout << time[i] << ' ';
	cout << endl;
	aveTime = minWaitingTime(time,N);
	cout << "the least average waiting time is: " << aveTime << endl;
	delete []time;
	system("pause");
	return 0;
}

运行结果为:

另外,也可以用vector代替数组,避免了动态分配内存,程序如下:

#include "stdafx.h"
#include<iostream>
#include<vector> 
using namespace std;

void funSort(vector<int>&a)
{
	int temp,n;
	n = a.end()-a.begin();
	for(int i=0;i<n-1;i++)
		for(int j=i+1;j<n;j++)
		{
			if(a[i]>a[j])
			{
				temp = a[i];
				a[i] = a[j];
				a[j] = temp;
			}
		}
}
int minWaitingTime(vector<int>a) //数组a为顾客的服务时间
{
	vector<int>b;
	int i,n,sum=0;
	n = a.end()-a.begin();
	for(i=0;i<n;i++)
		b.push_back(a[i]);
	//最终的b[i]为第i位顾客等待的时间
	for(i=1;i<n;i++)
		b[i] = b[i]+b[i-1];
	//求顾客等待时间的总和
	for(i=0;i<n;i++)
		sum += b[i];
	return sum/n; //返回平均等待时间
}
int main()
{
	int N,i,aveTime,temp; //顾客总数
	vector<int>time; 
	cout << "input the number of the customer: ";
	cin >> N;
	cout << "input the need service time of each customer: " << endl;
	for(i=0;i<N;i++)
	{
		cout << "No" << i+1 << ": ";
		cin >> temp;
		time.push_back(temp);
	}
	funSort(time);
	aveTime = minWaitingTime(time);
	cout << "the least average waiting time is: " << aveTime << endl;
	system("pause");
	return 0;
}

 运行结果和之前一样。

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值