4.6算法之贪心_702:Crossing River

题目

702:Crossing River
总时间限制: 1000ms 内存限制: 65536kB
描述
A group of N people wishes to go across a river with only one boat, which can at most carry two persons. Therefore some sort of shuttle arrangement must be arranged in order to row the boat back and forth so that all people may cross. Each person has a different rowing speed; the speed of a couple is determined by the speed of the slower one. Your job is to determine a strategy that minimizes the time for these people to get across.
输入
The first line of the input contains a single integer T (1 <= T <= 20), the number of test cases. Then T cases follow. The first line of each case contains N, and the second line contains N integers giving the time for each people to cross the river. There won’t be more than 1000 people and nobody takes more than 100 seconds to cross.
输出
For each test case, print a line containing the total number of seconds required for all the N people to cross the river.
样例输入
1
4
1 2 5 10
样例输出
17

翻译

一群N个人想要用一艘船渡过一条河,而这艘船最多只能载两个人。
因此,必须安排某种穿梭安排,以便来回划船,以便所有人都能过河。
每个人都有不同的划船速度;一对夫妇的速度是由较慢一方的速度决定的。
你的工作是确定一个策略,尽量减少这些人通过的时间。

输入的第一行包含单个整数T (1 <= T <= 20),测试用例的数量。
然后是T个案例。每种情况的第一行包含N,第二行包含N个整数,
表示每个人过河的时间。不会超过1000人,没有人花超过100秒的时间过马路。

对于每个测试用例,打印一行,其中包含所有N个人过河所需的总秒数。

理解

各人时间升序后是t[1],t[2],……,t[n-1]和t[n]
如果只有1个人,直接过t[1]。
如果只有2个人,直接过,只算慢的t[2]。
如果只有3个人,最优时间怎么算都是t[1]+t[2]+t[3]。3带1去,1回来,2带1去。或者1、2先去,1回来,1、3去。
在这里插入图片描述

如果4人以上,每次送走最后两个人。经过列数据掌握规律,最优时间是min(t[1]+2t[2]+t[n],2t[1]+t[n-1]+t[n]。
在这里插入图片描述
超过四个人,每次借助最快两人(要把船开回来)送走最慢两人。两种策略选择最优。

代码

#include <bits/stdc++.h>
using namespace std;
int m,n,t[1001];
int main(){
//freopen(“in.cpp”,“r”,stdin);
cin>>m;
while(m–){
memset(t,0,sizeof(t));
cin>>n;
for(int i=1;i<=n;i++)cin>>t[i];
sort(t+1,t+n+1);
int he=0;
for(;n>3;n-=2)he+=min(2t[1]+t[n-1]+t[n],t[1]+2t[2]+t[n]);
//送过去最慢的两个,也就是最后两个,也就是n和n-1
//一种,最快和最慢两个t[n]和t[n-1]的过去,最快的回来2*t[1]
//另一种,最快的两个过去t[2],最快的回来t[1],最慢的两个过去t[i],次快t[2]的回来
//4-2=2,5-2=3,6-2=4,所以循环后只会剩2和3
if(n%2)he+=t[1]+t[2]+t[3];
else he+=t[2];//1和2过去,只算2
cout<<he<<endl;
}
return 0;
}

贪心算法

动态规划可以画表格,明确初始值,逐阶段明确状态,找到因为阶段推进状态值的递推。还是有迹可循的。
贪心算法也需要罗列数据,找到规律。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值