Question:
After dark, N people will cross the river. There is only one candle and only one boat. Each boat can take up to two people. In any case, a cross-river user (one or two people) must have candles. Therefore, a cross-river user may need to return and send candles before continuing to cross the river. Ask how to cross the river in the shortest time.
Ideas:
Greedy ideas (generally sorted first)
Key steps: each time two people move from the shore to the other side, either one of them is the fastest person, or they will never come back after they arrive on the other side. That is, either the fastest + slowest, or the slowest + slow.
1. Sort the time for N people to cross the river from small to large. Speed [I]
2. Analysis:
(1) When n = 1, cross the river directly. Sum = speed [0]
(2) When n = 2, cross the river directly. Sum = speed [1]
(3) When n = 3, sum = speed [0] + speed [1] + speed [2]
(4) When n = 4, A, B, C, and D are sorted in ascending order.
Send with minimal: B + A + C + A + D = 2a + B + C + D (A, B in the past, a came back, A, C in the past, a came back, a, D in the past)
Send two big messages: B + A + D + B + B = a + 3B + d (a, B in the past, a back, c, d in the past, B back,, b)
Sum = min (2a + B + C + D, A + 3B + D)
(5) When n> 4, A, B ,......, C, D, more than four people, the goal is to send the two largest people.
Send with minimal: D + A + C + A = 2a + C + D (A, D used to, a came back, a, c used to, a came back)
Send two orders: B + A + D + B = a + 2B + D (A, B used to, a came back, c, d used to, B came back)
Loop: Sum = min (2a + B + C + D, A + 3B + d) until n <= 4 ends.
The Code is as follows:
# Include <iostream> # include <cstdio> # include <algorithm> using namespace STD; int speed [1010]; int main () {int ncase; scanf ("% d ", & ncase); While (ncase --) {int N, sum = 0; scanf ("% d", & N); For (INT I = 0; I <N; I ++) scanf ("% d", & speed [I]); sort (speed, speed + n); // sort while (n) in ascending order) {If (n = 1) {sum + = speed [0]; break;} else if (n = 2) {sum + = speed [1]; break ;} else if (n = 3) {sum + = speed [0] + speed [1] + speed [2]; break;} else if (n = 4) {If (speed [2] + speed [0]-2 * speed [1] <= 0) sum + = (2 * speed [0] + speed [1] + speed [2] + speed [3]); elsesum + = (speed [0] + 3 * speed [1] + speed [3]); break ;} else {If (speed [n-2]-2 * speed [1] + speed [0] <= 0) sum + = (speed [n-1] + speed [n-2] + 2 * speed [0]); else sum + = (speed [n-1] + 2 * speed [1] + speed [0]); N-= 2 ;}} printf ("% d \ n", sum);} return 0 ;}