Crossing River
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 9830 | Accepted: 3709 |
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
这道题目是lrj黑书上的一道贪心题,解法是这样的:现将所有的数排序,排完序之后,先将那些花费时间大的送到对岸,设最快的为a,次快的为b,当前次最慢的为c,最慢的为d,现在有两种运送方案,一种是现将a,b送去,a回,c,d送去,b回,另外一种是现将a,d送去,再将a,c送去。前者花费的时间为a+2*b+d,后者花费的时间为a*2+d+c,最后推得一个不等式 当 2*b > a+c是,用第二种方案,否则用第一种,下面是代码:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn = 1000+10; int pyer[maxn],n,ans; int main(){ int ncase; cin >> ncase; while(ncase--){ ans = 0; scanf("%d",&n); for(int i = 1; i <= n; i++) scanf("%d",&pyer[i]); if(n<=2){ for(int i = 1; i <= n; i++) ans = max(ans,pyer[i]); cout<<ans<<endl; continue; } sort(pyer+1,pyer+1+n); int i = n; if(i == 3){ ans += pyer[1]+pyer[2]+pyer[3]; cout<<ans<<endl; continue; } while(i >= 4){ if(pyer[2]*2>pyer[i-1]+pyer[1]){ ans += pyer[1]*2+pyer[i]+pyer[i-1]; i -= 2; }else{ ans += pyer[1]+pyer[i]+pyer[2]*2; i -= 2; } if(i==3){ ans += pyer[3]+pyer[1]; } } ans += pyer[2]; cout<<ans<<endl; } return 0; }