POJ 1700 Crossing River

来源:互联网 发布:淘宝上的兰芝是正品吗 编辑:程序博客网 时间:2024/05/17 12:05

http://poj.org/problem?id=1700

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个人,每个人有不同的行驶速度,两个人的速度按照慢的那个人的时间算,然后求出这N个人过河所需要的最短时间。
第一行输入T个case,第二行输入有几个人,第三行输入每个人过河所需要的时间。
输出这几个人过河所需要的最短时间。

思路:
1.我本来想的是每次都是最快的那个把其他人带过去,然后第一快的那个再自己回来,可是我sample算出来的是19,就说明我的想法不对。
2.后来算出17了,就是1和2先过去,然后1回来,然后5和10过去,然后2回去,然后1和2过来。
3.然后我根据第二种算法找规律算都是WA。
4我问裴逼逼,裴逼逼说应该是第一种情况和第二种情况两者之间少的那个才对,第一种情况可能比第二种情况少。
5.具体实现:输入后需要排序。
6.然后要对人数进行分类,1个,2个,3个都只要1种情况且非常好算。
7.这里有一点,就是从4个以上开始讨论,主要是4个4个讨论,就是从4个人变为2个人这中间过程要少。
8.然后仔细画图比较上面两种情况,回发现主要一个是第二小的2(a[1]*2),另一个是最小+最大(a[0]+a[n-1])因为之前进行过排序了,然后进行比较,选择时间少的那个。

代码:

#include<stdio.h>#include<iostream>#include <math.h>#include<algorithm>#define N 1005using namespace std;int main(){    int T;    scanf("%d",&T);    while(T--)    {        int n,a[N],i;        scanf("%d",&n);        for(i=0;i<n;i++)            scanf("%d",&a[i]);        sort(a,a+n);        int ans=0;        while(n)        {            if(n==1)    {ans+=a[0];n=0;}            else if(n==2)    {ans+=a[1];n=0;}            else if(n==3)    {ans+=a[0]+a[1]+a[2];n=0;}            else            {                if(a[1]*2<a[n-2]+a[0])                    ans+=2*a[1]+a[n-1]+a[0];                else                    ans+=2*a[0]+a[n-1]+a[n-2];                n=n-2;            }        }        printf("%d\n",ans);    }    return 0;}

这题也是百度来的……好难啊……

1 0
原创粉丝点击