Solving the problem of Calculating Garlic-Crossing the River

topic

Insert picture description here

Sample

Insert picture description here

answer

We first sort all people in ascending time spent. Assuming that the minimum time spent by the former i person crossing the river is opt[i], then consider the situation where the former i-1 person has already crossed the river, that is, there is 1 person on the river side, There are i-1 people over the river, and the flashlight must be on the opposite bank at this time, so opt[i]=opt[i-1]+a[1]+a i . If there are two people on the river side, one is number i, the other is irrelevant, there are i-2 people on the other side of the river, and the flashlight must be on the opposite bank, so opt[i]=opt[i-2]+a[1 ]+a[i]+2×a[2] (Let the person who spends the least time send the flashlight, and then the i-th person crosses the river with another person. Since the person who spends the least time is here, the next time The one who sent the flashlight must be the least expensive one. After sending it, the least expensive and the least expensive cross the river to solve the problem), so opt[i]=min(opt[i-1]+a[1]+ a[i],opt[i-2]+a[1]+a[i]+2×a[2])

The code below

#include<bits/stdc++.h>
using namespace std;
int n,t[1001],ans[1001];
int main(){
    
    
//	freopen(".in","r",stdin);
//	freopen(".out","w",stdout);
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cin>>n;
	for(int i=0;i<n;i++)cin>>t[i];
	sort(t,t+n);
	ans[0]=0;
	ans[1]=t[1];
	for(int i=2;i<n;i++)ans[i]=min(ans[i-1]+t[0]+t[i],ans[i-2]+t[0]+t[i]+2*t[1]);
	cout<<ans[n-1]<<endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/Richard_1101/article/details/107656877