首页 > 代码库 > [ACM] poj 1700 Crossing River (经典过河问题)

[ACM] poj 1700 Crossing River (经典过河问题)

Crossing River
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 10212 Accepted: 3855

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

141 2 5 10

Sample Output

17

Source

POJ Monthly--2004.07.18

 

 

解题思路:

N个人,只有一条船,每个人都有一个划船速度,要求让N个人过河,一次渡河包括两个人先过去,一个人再回来。每次时间取两个人之间用时最多的,一个人的时候的时间就是他自己所用的。求让N个人过完河所用的最短时间。

先把每个人的速度从小到大排序,先考虑简单的情况,一个人,自己过去就可以了。两个人,取时间最长的那个,三个人,最优的是三个人所用时间之和(每让最快的那个单独划船回来)。

四个人或四个以上,就要考虑不同的决策把最慢和次慢的人渡河。有两种决策。

1.始终让最快的单独划船。  最快的和最慢的一起渡河,然后最快的划回来,最快和次慢的一起渡河,最快的再回来。所用时间为 s[n]+s[1] + s[n-1] +s[1]

2.让最快和次快的先过河,最快的划回来,接着最慢和次慢的过河,让次快的划回来。  这样所用时间为 s[2]+s[1]+s[n]+s[2]

两种决策中取时间最短的。

代码:

#include <iostream>#include <algorithm>using namespace std;int s[1002];int n,time;int main(){    int t;cin>>t;    while(t--)    {        cin>>n;        for(int i=1;i<=n;i++)            cin>>s[i];        sort(s+1,s+1+n);        time=0;        while(n)        {            if(n==1)//还剩下一个人,也就是一开始就有1个人渡河            {                time+=s[1];                break;            }            else if(n==2)            {                 time+=s[2];                 break;//别忘了break;            }            else if(n==3)            {                time+=s[1]+s[2]+s[3];//最优的方法为每次都让最快的单独划船                break;            }            else            {                time=time+min(s[n]+2*s[1]+s[n-1],2*s[2]+s[1]+s[n]);//比较,让最慢和次慢的两个人渡河有两种方法,取时间最短的那个                n-=2;            }        }        cout<<time<<endl;    }    return 0;}


 

[ACM] poj 1700 Crossing River (经典过河问题)