poj 3404

编程入门 行业动态 更新时间:2024-10-28 15:31:35

<a href=https://www.elefans.com/category/jswz/34/1766382.html style=poj 3404"/>

poj 3404

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过;
其实这种情况已经包含在上述讲的状态转移方程中了

更多推荐

poj 3404

本文发布于:2024-02-12 00:14:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1684523.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:poj

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!