Time limit of river crossing:MS | Memory limit:65535 KB Difficulty:5
-
Describe
-
In the dark of the night, N-travelers came to a narrow and no-fence side of the bridge. If you don't use a flashlight, everyone is afraid to cross the bridge anyway. Unfortunately, a total of n individuals with only one flashlight, and the bridge is only narrow enough to allow two people at the same time. If they cross the bridge alone, the time required for n people is known, and if two people cross the bridge at the same time, it is the time required for the slower person to move alone. The question is, how to design a program that allows the N people to cross the bridge as quickly as possible.
-
-
Input
-
The
-
first line is an integer T (1<=t<=20) that represents the number of groups of test data
The first line of each set of test data is an integer n (1<=n<=1000) representing a total of n individuals to cross the river
The second row of each set of test data is n integer si, which indicates the time it takes the person to cross the river. (0<si<=100)
-
-
Output
-
-
the minimum time required for the output of all people crossing the river
-
-
Sample input
-
-
141 2 5 10
-
-
Sample output
-
17
The problem is to use a greedy algorithm,
There's nothing to say when you are alone
Two people are the long-time person
Three people, let the first short time people take the longest past, short time to return, with the second short of the people past
Four people and above, there are two ways to shorten the time
1. The first short belt longest, and then come back with the second short, and then take the end
2. The first short belt second short, the first short back, the flashlight to give the longest and the second long, then let the second short back
Both of these methods are only sent to the past two people
1#include <cstdio>2#include <cstring>3#include <algorithm>4 using namespacestd;5 inttime[1010];6 7 intMain ()8 {9 intN,i,b,n;Tenscanf"%d",&N); One while(n--) A { -scanf"%d",&n); - for(i=0; i<n;i++) the { -scanf"%d",&time[i]); - } -Sort (time,time+n); + intsum=0; - while(n>3) + { A if(2*time[1]+time[0]>2*time[0]+time[n-2]) atsum+=2*time[0]+time[n-2]+time[n-1]; - Else -sum+=2*time[1]+time[0]+time[n-1]; -n-=2; - } - if(n==3) insum+=time[1]+time[0]+time[2]; - if(n==2) tosum+=time[1]; + if(n==1) Sum + = time[0]; -printf"%d\n", sum); the } * return 0; $}
River crossing Problem--nyoj topic 47