您的位置:首页 > 其它

POJ 1700

2016-01-25 15:16 274 查看
Crossing River

Time Limit: 1000MS
Memory Limit: 10000K
Total Submissions: 12534
Accepted: 4764
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个人想要过河,只有一条船,它最多可承载两个人。因此需要想出一种方法安排人来回划船让所有的人过河。每个人都有不同的划船速度;两人一起时速度由较慢的速度决定。你的任务是确定策略,花最少的时间让所有人过河。(提示:船开过去后,还需要有人划回来)

输入

输入的第一行包含一个整数T(1<= T<=20),表示有T组测试数据。接下来T组数据。每组数据第一行为N,第二行包含N个整数表示每个人过河时间。每个案例之前有一个空行。不会超过1000人,没有人需要超过100秒时间。

输出:

每组数据一行,表示N个人全部通过的最少时间。

样例输入:

1

4

1 2 5 10

样例输出:

17

首先看题。题目中说一共有N个人要过河,但是只有一艘船,而且每次只能承载2个人。(先划船过去的当然不能不管还在原地的朋友啦)船把人运到对岸后还需要有人把船划回来,而过河所用的时间是船上人中划船最慢的人的时间,所以回来的船上应只有一人,而且速度不能太慢,应为最快或者次快的。所以过河一共是(N-1)次,划船回原地是(N-2)次

样例数据解析:

1.
people1&2过河,1回,total+=2+1

2.
people3&4过河,2回,total+=10+2

3.
people1&2过河 total+=2

所以,total=17

或许有人会想是最快的一个一个送过去然后回来快还是最快的和次快的一起去,再让最快的划船回来,然后让原地最慢和次慢过去,次快的再划船回来快呢?样例数据中是第二种情况,那么,有没有可能是第一种情况呢?

数据2

1

4

1 10 11 20

这组数据用第一种方法计算出来 total=43

而用第二种计算出来却是total=51

由此可得,这两种方法并没有绝对的界限,应是相辅相成。

(最开始对输入的过河所需时间进行排序)

不妨设x=t[1]*2+t[i]+t[i-1],y=t[1]+t[2]*+t[i]

循环中每次i-=2;

比较x与y的值

Total=max(x,y);

之后再考虑当i=2,3的时候

附代码如下

#include<stdio.h>
#include<algorithm>
using namespace std;
int max(int a,int b)
{
if(a>b)
return a;
return b;
}
int min(int a,int b)
{
if(a>b)
return b;
return a;
}
int main()
{
int T,k;
scanf("%d",&T);
for(k=1;k<=T;k++)
{
int total=0,N,i,j,t[1005];
scanf("%d",&N);
for(i=1;i<=N;i++)
{
scanf("%d",&t[i]);
}
sort(t+1,t+N+1);
if(N<=3)
{
if(N==1)
{
total=t[1];
}
else
{
if(N==2)
{
total=max(t[1],t[2]);
}
else
{
if(N==3)
{
total=t[1]+t[2]+t[3];
}
}
}
printf("%d\n",total);
}
else
{
for(i=N;i>3;i-=2)
{
int x=t[1]*2+t[i]+t[i-1],y=t[1]+t[2]*2+t[i];
total+=min(x,y);
}
if(i==2)
{
total+=t[2];
}
if(i==3)
{
total+=t[1]+t[2]+t[3];
}
printf("%d\n",total);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: