UVA - 11389 贪心算法

Ignatius and the Princess I

In a city there are n bus drivers. Also there are n morning bus routes and n afternoon bus routes with
various lengths. Each driver is assigned one morning route and one evening route. For any driver, if
his total route length for a day exceeds d, he has to be paid overtime for every hour after the first d
hours at a flat r taka / hour. Your task is to assign one morning route and one evening route to each
bus driver so that the total overtime amount that the authority has to pay is minimized.
Input
The first line of each test case has three integers n, d and r, as described above. In the second line,
there are n space separated integers which are the lengths of the morning routes given in meters.
Similarly the third line has n space separated integers denoting the evening route lengths. The lengths
are positive integers less than or equal to 10000. The end of input is denoted by a case with three 0’s.
Output
For each test case, print the minimum possible overtime amount that the authority must pay.
Constraints
• 1 ≤ n ≤ 100
• 1 ≤ d ≤ 10000
• 1 ≤ r ≤ 5
Sample Input
2 20 5
10 15
10 15
2 20 5
10 10
10 10
0 0 0
Sample Output
50
0
问题连接

问题描述

有上午路线和下午路线各n个。
分配每个司机早上和晚上的路,给出路线的时间,司机开车的时间如果大于d,设超时的部分为k,则要付加班费k*r。求付最少的加班费是多少,

问题分析

先对早上的路和晚上的路进行排序,路线搭配的方案是第一个司机取一个最大的和一个最小的路线,第二个司机取次大的和次小的路线,依次类推。
原因:
对于只有2个司机的情况,设早班车有a1,a2,晚班车有b1,b2,其中a1>a2,b1<b2。a1+b1,a2+b2这种方案是一定是花费最少的。它可以分成3种情况。
一,a1+b1>d;a2+b2>d。转化成a1+b1=k1+d, a2+b2=k2+d,交换b1,b2,多出来的部分不会变,所以不会减少费用。
二,a1+b1>d;a2+b2<d。交换b1,b2。因为b2>b1,所以交换后,前者超时的时间加长,后者仍然没超时,费用是增加了。
三,a1+b1<d;a2+b2<d。交换b1,b2两者都不会超时,所以费用不变。
第一个司机取一个最大的和一个最小的路线,第二个司机取次大的和次小的路线,依次类推,这种方案就可以满足任意两个司机都符合上述关系,所以结果就是最小的。
大神的解释:
http://www.cnblogs.com/AOQNRMGYXLMV/p/4122236.html

c++程序如下

#include<iostream>
using namespace std;
const int N=105;
int main()
{
	int n,d,r,mr[N],er[N],ar[N],i,j;
	while(scanf("%d %d %d",&n,&d,&r)!=EOF)
	{
		if(n==0&&d==0&&r==0)break;
		for(i=0;i<n;i++)
		{
			scanf("%d",&mr[i]);
		}
		for(i=0;i<n;i++)
		{
			scanf("%d",&er[i]);
		}
		int p,q;
		p=n-1;
		for(i=0;i<p;i++)
		{
			for(q=i,j=i+1;j<n;j++)
			{
				if(mr[q]>mr[j]) q=j;
			}
			if(q!=i) swap(mr[i],mr[q]);
		}
		for(i=0;i<p;i++)
		{
			for(q=i,j=i+1;j<n;j++)
			{
				if(er[q]<er[j]) q=j;
			}
			if(q!=i) swap(er[i],er[q]);
		}
		int sum=0;
		for(i=0;i<n;i++)
		{
			ar[i]=mr[i]+er[i];
			if(ar[i]>d)
			{
				sum+=ar[i]-d;
			}
		}
		printf("%d\n",sum*r);
	}
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值