poj 1700 n人过河(贪心)

题意:n个人在河的同一侧,他们想过河。只有一条船,此船最多能坐两个人。每个人有过河速度,两个不同速度的人同船过河以慢的人计算。问n个人全部过河所需的最短时间。

思路:一个基本动作是两个最快的人送两个最慢的,这样来回需要四次渡河。过去两人回来一人,再过去两人回来一人。设四人速度为a<b<c<d,那么有两种方案孰优孰劣不能确定:1、ab过->a回->cd过->b回过,所花时间为:a+2*b+d;2、ad过->a回->ac过->a回,所花时间为:2*a+c+d。用这两种方案小的即可。边界条件为还剩3、2或1个人(初始只有1个人)。

#include <stdio.h>
#include <string.h>
//#include <stdlib.h>
#define N 1005
int s[N],n,T;
int test(int a,int b,int c,int d){
	if(b*2 < a+c)
		return a + 2*b + d;
	return a*2 + c + d;
}
int cmp(const int *a,const int *b){
	return (*a)-(*b);
}
int main(){
	freopen("a.txt","r",stdin);
	scanf("%d",&T);
	while(T--){
		int i,res=0;
		scanf("%d",&n);
		for(i = 1;i<=n;i++)
			scanf("%d",&s[i]);
		qsort(s+1,n,sizeof(int),cmp);
		while(n>=4){
			res += test(s[1],s[2],s[n-1],s[n]);
			n -= 2;
		}
		if(n==3)
			res += s[1]+s[2]+s[3];
		else if(n == 2)
			res += s[2];
		else
			res += s[1];
		printf("%d\n",res);
	}
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值