Crossing River
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 9919 | Accepted: 3752 |
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
ps:http://poj.org/problem?id=1700
/* 此题讲的是N个人过河,每个人都有自己的过河时间,一条船只能承受2个人,所用时间为其中过河时间最多的,
所以呢,想到有两种情况,第一种:过河时间最少的人来回接送其他人,第二种:过河时间最少和次少的人来回接送其他人,
刚开始就觉得第一种时间必然是最少的,但是仔细想想,不然。因为第一种情况虽然单次过河时间少,但送人的次数要多,
如第1个人(过河时间最少)接送第i人 dp[i]=dp[i-1]+time[0]+time[i]; 而第二种情况呢,虽然来回次数多,但是接送的人要多,
如第1个人接第i-1个和第i个人,然后让第i-1个和第i个人一块过河,第2个人再接送第1个人。
dp[i]=dp[i-2]+time[0]+time[i]+time[1]*2。所以每次计算出这两个值都应该进行比较,从而AC!*/
#include<stdio.h> #include<stdlib.h> #define N 1010 int cmp(const void *a,const void *b) { return *(int *)a-*(int *)b; } int a[N]; int dp[N]; int n; int main() { int i,j,t,k; int min1,min2; scanf("%d",&t); while(t--) { scanf("%d",&n); for(i=0;i<n;i++) scanf("%d",&a[i]); qsort(a,n,sizeof(a[0]),cmp); dp[0]=a[0]; dp[1]=a[1]; for(i=2;i<n;i++) { min1=dp[i-1]+a[i]+a[0]; min2=dp[i-2]+a[1]+a[0]+a[i]+a[1]; dp[i]=min1; if(min1>min2)//中间是嵌套的,哪种快选哪种 dp[i]=min2; } printf("%d ",dp[n-1]); } return 0; } /* 3 6 1 2 5 10 15 20 5 1 2 5 10 15 4 1 2 5 10 */