Kids dynamic programming of river issues

Children cross the bridge problem: a dark and stormy night in the high night, there are n (n <= 50) a bridge children here, and now they need to cross the bridge, but because the bridge is very narrow, allowing only not more than two by, they have only a flashlight, so two people each bridge needs to bring back the flashlight, I is the number of children to bridge the time T [i], the total time for both of the two bridge elderly time. The total time to ask all the children bridge the shortest is.

 

 


Analysis of thinking: Suppose there are four children across the river, across the river that time was 1,2,3,4. Let's start small and analyze the optimal strategy.

The first, is to make sure the past with 1, 2, 1 and then came back, picked up the 3, let 1 back, picked up the 4.

The second case, the same first let the past 1,2, then 1 back, but then, you can let go with 3, 4, then 2 back, picked up the 1.

The difference between these two cases is that two people after the countdown is to go with or talk to one of the go 1

So, we find two cases, you should decide which is the minimum, whichever is the smallest.

ok, the basic idea of ​​the code has now been sorted out, so specific is how to achieve it. Obviously, this is a typical dynamic programming problem that it has a typical sub-repeated question, and can be optimized, we can try to deduce its recurrence formula:

First, we can easily find its base case, that is, when only 1,2,3 individual.

dp[1]=a[1]

dp[2]=a[2]

dp[3]=dp[1]+dp[2]+dp[3]

dp[4]=min(dp[4-2]+a[1]+a[4-1]+2*[2],dp[4-1]+a[1]+a[4])

And so on.

Dynamic programming problem is important to find the class of recursive formula, and then locate the base case, which is only consider the current situation, we do not consider before, because the situation is already recurrence after previous best of.

 

 

AC code is as follows:

#include<iostream>
#include<algorithm>//以后的操作是要对数组进行排序,从小到大。因为肯定是要从小到大进行过河
,最大的要留在最后,

using namespace std;
int main(){
	int n;
	cin >> n;
	int a[1009];
	for(int i=1;i<=n;i++){
		cin >> a[i];
	} 
	int dp[1009];
    sort(a+1,a+1+n);
    dp[1]=a[1];
    dp[2]=a[2];	
    dp[3]=a[2]+a[1]+a[3];
    for(int i=4;i<=n;i++){
    	dp[i]=min(dp[i-2]+a[1]+a[i]+2*a[2],dp[i-1]+a[1]+a[i]); 
	}

	cout << dp[n];
	return 0;
} 

 

 

 

 

 

Published 50 original articles · won praise 13 · views 8836

Guess you like

Origin blog.csdn.net/weixin_43770577/article/details/90145046