poj 3404
- 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过;
其实这种情况已经包含在上述讲的状态转移方程中了
- springboot项目搭建0050
- 【Linux】目录权限和默认权限
- Java中int的取值范围
- #include<>和#include“”的区别
- 重启mysql
- css中text文字超出宽度省略号显示并鼠标悬停显示剩余全部:
- FPGA设计中,产生LFSR伪随机数
- JMeter BeanShell 应用
- TreeSet集合如何保证元素唯一
- 二级计算机考试准考证打印入口
- pgpool 主从流复制模式下的安装使用
- (亲测可用)html5 file调用手机摄像头
- R型聚类分析
- itoa函数和atoi函数的实现和用法
- JavaScript弹出框、对话框、提示框、弹窗总结
- pip执行指令后报语法错误sys.stderr.write(f”ERROR: {exc}”)解决办法
- python爬虫爬取网页信息