POJ 1700 Crossing River(貪心)

Description
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過去,1回來送船。5和10過去,2回來送船,然後1和2一起過去。所用時間爲2+1+10+2+2=17。

貪心思路:首先對他們從小到大排序。基於貪心思想
1.耗時最短的人在船上來回送人
2.耗時最短的人來回送船,然後讓兩個耗時最長的人一起走。(實現方法就是耗時最短的送船回來,倆新人人過去,耗時次短的來接最短的過岸)
這樣就以4爲一個循環。每次耗時最短+耗時次短+2新人,然後取min,當人數<=3時,情況唯一,直接特判輸出。

代碼如下:

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
const int maxn=10005;
int a[maxn];
int main()
{
    int n,m;
    scanf("%d",&n);
    for(int k=0;k<n;k++)
    {
        int sum=0;
        scanf("%d",&m);
        for(int i=1;i<=m;i++)
        scanf("%d",&a[i]);
        sort(a+1,a+m+1);
        for(int i=m;i>=1;i-=2)
        {
            if(i==3)
            {
                sum+=a[1]+a[2]+a[3];
                break;
            }
            if(i==2)
            {
                sum+=a[2];
                break;
            }
            if(i==1)
            {
                sum+=a[1];
                break;
            }
            else sum+=min(a[1]+2*a[2]+a[i],2*a[1]+a[i]+a[i-1]);
        }
        printf("%d\n",sum);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章