/*
题目大意:求解最小的过桥时间
解题思路:
假设m个排序的过桥时间:a0,a1,a2,a3,a4......am-1
已知条件:最后一步肯定是a0和a1一起过去,所以所花的时间初始化sum=a[1]
过河两种方法,每次过两个人(所以需要m-=2):
1.a0和a1过去,a0回来,am-2和am-1过去,a1回来,所花时间sum+=a[1]+a[0]+a[m-1]+a[1]
2.a0和am-1过去,a0回来和am-2过去,a0再回来,所花时间sum+=a[m-1]+a[0]+a[m-2]+a[0]
最后只有2种情况:如果m为奇数则剩3个人,如果m为偶数则剩2个人
由于前面初始化sum=a[1],所以只需考虑3个人时a0将a2送过去再回来的所花的额外时间sum+=a[2]+a[0]
难点详解:注意一下过桥的方法就可以了,还要考虑一下最后剩下几个人。
关键点:贪心算法
解题人:lingnichong
解题时间:2014-08-23 21:06:46
解题体会:感觉题目没意思,虽说它是一道经典的贪心题目,如果有1000个人过河,每个人过100秒,那不就是100000秒吗?这手电筒的电池也太强大了吧!这夜晚也太长了吧!
*/
过河问题
-
描述
-
在漆黑的夜里,N位旅行者来到了一座狭窄而且没有护栏的桥边。如果不借助手电筒的话,大家是无论如何也不敢过桥去的。不幸的是,N个人一共只带了一只手电筒,而桥窄得只够让两个人同时过。如果各自单独过桥的话,N人所需要的时间已知;而如果两人同时过桥,所需要的时间就是走得比较慢的那个人单独行动时所需的时间。问题是,如何设计一个方案,让这N人尽快过桥。
poj题目:
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 10871 | Accepted: 4097 |
Description
Input
Output
Sample Input
1 4 1 2 5 10
Sample Output
17
Source
#include<stdio.h>
#include<algorithm>
using namespace std;
#define MAXN 1000+10
int arr[MAXN];
int main()
{
int t,n;
int i,time;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
sort(arr,arr+n);
if(n<=2)
{
printf("%d\n",arr[n-1]);
continue;
}
time=arr[1];
while(n>3)
{
if(arr[1]+arr[0]+arr[n-1]+arr[1]>arr[n-1]+arr[0]+arr[n-2]+arr[0])
time += arr[n-1]+arr[0]+arr[n-2]+arr[0];
else
time += arr[1]+arr[0]+arr[n-1]+arr[1];
n -= 2;
}
if(n==3)
time += arr[2] + arr[0];
printf("%d\n",time);
}
return 0;
}