POJ 1700--动态规划

题目:

                                                  Crossing River

                                              Time Limit:1000MS     Memory Limit:10000KB     64bit IO Format:%I64d & %I64u

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

 分析:

     

此题讲的是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!

代码:		 

 

 1 #include<stdio.h>
2 #include<stdlib.h>
3
4 int cmp(const void *a,const void *b)
5 {
6 return *(int *)a-*(int *)b;
7 }
8
9 int main()
10 {
11 int num,n,i,time[1002],dp[1002],min;
12 scanf("%d",&num);
13 while(num--)
14 {
15 scanf("%d",&n);
16 for(i=0;i<n;i++)
17 scanf("%d",&time[i]);
18 qsort(time,n,sizeof(time[0]),cmp);
19 dp[0]=time[0];
20 dp[1]=time[1];
21 for(i=2;i<n;i++)
22 {
23 dp[i]=dp[i-2]+time[0]+time[i]+time[1]*2;
24 min=dp[i-1]+time[0]+time[i];
25 if(min<dp[i])
26 dp[i]=min;
27 }
28 printf("%d\n",dp[n-1]);
29 }
30 return 0;
31 }

PS:默默的努力,默默的发光,会有那么一天的!

posted @ 2012-01-20 21:22  hankers  阅读(299)  评论(0编辑  收藏  举报