当前位置: 首页 > 工具软件 > River Trail > 使用案例 >

Crossing River (简单贪心)

戚云
2023-12-01
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.
Input
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. Each case is preceded by a blank line. There won't be more than 1000 people and nobody takes more than 100 seconds to cross.
Output
For each test case, print a line containing the total number of seconds required for all the N people to cross the river.
Sample Input
1
4
1 2 5 10
Sample Output
17

本题要求用最少的时间把所有人送到河对岸,

大体可以分为几种情况:

1,当由一个或者两个人时只需要过一次河就可完成,所以输出较慢人的速度即可。

2,如果是三个人时,不管怎么安排,都是三个人时间的总和。

3如果是大于三个人,则每次都要用最短的时间送走最慢的两个人.

有两种方案:第一种,最快的人分两次送走两个最慢的(能者多劳)这样的用时是,2*a[0]+a[m-1]+a[m-2];

第二种方案:最快的和次快的先过河,最快的回来,两个最慢的过河,次快的把船开回来这样的用时是啊a[0]+2*a[1]+a[m-1];

不管那一种方案都是只有两个最慢的到了河对岸,每次都要对比两种方案,选出最优的,用时最少的。

这就是大体思路

AC代码:

#include <iostream>
#include<algorithm>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<math.h>
using namespace std;
int main()
{
   int i,j,k,n,m,T,a[1100],x;
   scanf("%d",&T);
   while(T--)
   {
        x=0;
        scanf("%d",&m);
        for(i=0;i<m;i++)
        scanf("%d",&a[i]);
        sort(a,a+m);
        while(m>3)
        {
            x+=min(2*a[0]+a[m-1]+a[m-2],2*a[1]+a[0]+a[m-1]);//对比两种方案,哪种更优,用时更少。
            m-=2;\\每次送走最慢的两人,没过河的人数减少二。
        }
        if(m==3)\\                     随着没过河人数的减少,问题最后都会归结人数不大于3的情况。
        x+=a[0]+a[1]+a[2];
        else
        x+=a[m-1];
        printf("%d\n",x);
   }


}


要想做好贪心问题,一定要掌握好快排。

 类似资料: