poj 3404 -- Bridge over a rough river

poj 3404 – Bridge over a rough river

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 4407 Accepted: 1811

Description

A group of N travelers (1 ≤ N ≤ 50) has approached an old and shabby bridge and wishes to cross the river as soon as possible. However, there can be no more than two persons on the bridge at a time. Besides it’s necessary to light the way with a torch for safe crossing but the group has only one torch.

Each traveler needs ti seconds to cross the river on the bridge; i=1, … , N (ti are integers from 1 to 100). If two travelers are crossing together their crossing time is the time of the slowest traveler.

The task is to determine minimal crossing time for the whole group.

Input

The input consists of two lines: the first line contains the value of N and the second one contains the values of ti (separated by one or several spaces).

Output

The output contains one line with the result.

Sample Input

4
6 7 6 5

Sample Output

29

此题典型的线性dp,寻找递推关系,刚开始是用贪心来写,每次让时间最短的人回来送手电筒,但是发现 1 2 5 10 这个例子用贪心写是错的,后来换了思路写,先对时间长短从小到大排,假设dp[i]表示前i个人到桥另一边的最短时间,可以考虑前i-1个人在桥另一边后的情况,那么还有一个人在桥的这边没过去,则可以让时间最短的人带手电筒回来再一起过去。这样有dp[i] = dp[i-1] + a[1] + a[i].考虑另一中情况,i-2个人在桥的另一边,但是还有两个人在桥的这一边,让时间最短的送手电筒过来,然后另外两个人到桥另一边,时间最短的留下,然后时间次短的再过来送手电筒,在一起回去,这样时间所花费的时间是a[1] + 2 *a[2] + a[i],,这样有dp[i] = dp[i-2]+a[1]+a[i]+2 * a[2].
综上所述,dp[i] = min {dp[i] = dp[i-1] + a[1] + a[i],a[1] + 2 *a[2] + a[i],};
AC代码:

#include <iostream>
#include <cstring>
#define mem(a,b) memset(a,b,sizeof(a))
#include <algorithm>

using namespace std;

int main()
{
    int n;      //人数
    while(cin >> n)
    {
        int a[n+1];   //输入
        int dp[n+1]; //状态转移数组
        mem(dp,0);
        for(int i = 1; i <= n; ++i)
        {
            cin >> a[i];
        }
        sort(a+1,a+n+1);
        if(n == 1 || n == 2)
        {
            cout << a[n] << endl;
            continue;
        }
        dp[1] = a[1];
        dp[2] = a[2];
        for(int i = 3; i <= n; ++i)
        {
            dp[i] = min(dp[i-1]+a[i]+a[1],dp[i-2]+a[1]+a[i]+2*a[2]);
        }
        cout << dp[n] <<endl;
    }
    return 0;
}

其实该题有另一种贪心思路,分类讨论,当n<3时可直接输出,当n>=4时则可转化为
假设A < B < C < D,则有两种策略,
先A回,再A和C过,A回,再A,D过,
或者先A回,C和D过,在B回,在A和B过;
其实这种情况已经包含在上述讲的状态转移方程中了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值