Problem description
Poj 1700
On a dark night, n came to the narrow bridge without guardrails for travelers. If you do not use a flashlight, you will not dare to cross the bridge in any way. Unfortunately, N people only carry one flashlight, while the bridge is narrow enough to let two people pass simultaneously. If they bridge the bridge separately, the time required by N people is known. If the two bridge the bridge at the same time, the time required is the time required for a person to take action slowly. The problem is how to design a scheme to allow the N people to bridge the bridge as soon as possible.
Solutions
It is easy to think of using greedy policies. But how can this problem be solved?
Suppose there are five people T1, T2, T3, T4, and T5, and the time increases at a time. How can we make the five people cross the river with the minimum time?
Consider crossing the river through T4 and T5 first (the slowest two are arranged with no aftereffect). After a simple comparison, there are two optimal methods.
1. t1 and t2 cross the river, T1 back, T4 and T5 cross the river, T2 back (total time: T2 + t1 + T5 + T2)
2. T1 and T4 cross the river, T1 back, T1 and T5 cross the river, T1 back (total time: T4 + t1 + T5 + T1)
Then the problem is simplified to only three people T1, T2, T3, and N ≤ 3.
Promote to N people (n ≥ 4), just take (t1 + 2 * t2 + tn) AND (2 * t1 + Tn-1 + Tn) in the smaller, the problem is the case of a previous N-2 individual.
Code Implementation
1 #include<stdio.h> 2 #include<iostream> 3 #include<algorithm> 4 using namespace std; 5 6 const int maxn = 1000 + 10; 7 int n,times[maxn]; 8 9 int main()10 {11 int T;12 scanf("%d", &T);13 while (T--)14 {15 scanf("%d", &n);16 for (int i = 0; i < n; i++) scanf("%d", ×[i]);17 sort(times, times + n);18 int sum = 0;19 while (n > 3)20 {21 sum += min((times[0] + times[1] * 2 + times[n - 1]), (times[0] * 2 + times[n - 2] + times[n - 1]));22 n -= 2;23 }24 if (n == 3) sum += (times[0] + times[1] + times[2]);25 if (n == 2) sum += times[1];26 if (n == 1) sum += times[0];27 28 printf("%d\n", sum);29 }30 return 0;31 }
Reference link:
Https://www.cnblogs.com/ShiChaoPeng/p/5858690.html
79332774? Utm_source = blogxgwz1
Cross-river (2)