nyoj48过河问题

本文介绍了一种解决船员运送问题的算法,该算法通过对比两种不同策略来确定每次运送的最佳组合,以确保所有人员都能以最短的时间被运送过河。通过C++实现并考虑了各种边界情况。

每次把用时最长和用时次长的运过去,有两种方案:

1.a[0] + a[n-1] 过去,a[0] 回去,a[0]+a[n-2]过去,a[0]回去;

2.a[0]+a[1]过去,a[0]回去,a[n-1]+a[n-2]过去,a[1]回去;


#include<stdio.h>

#include<algorithm>
using namespace std;
int a[1001];
int min(int n)
{
int w1,w2;
w1 = 2*a[0] + a[n-1] + a[n-2];
w2 = 2*a[1] + a[0] + a[n-1];
if(w1 < w2) return w1;
else return w2;
}
int final(int n)
{
if(n <= 2) return a[n-1];
else if(n == 3) return (a[0] + a[1] + a[2]);
else
{
return min(n)+final(n-2);
}
}
int main()
{
int n,m;
scanf("%d",&n);
while(n--)
{
int i;
scanf("%d",&m);
getchar();
for(i = 0;i < m;i++)
{
scanf("%d",&a[i]);
}
sort(a,a+m);  
printf("%d\n",final(m));
}
return 0;

}

以下是最佳代码:

 
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
const int MAX=1010;
int Speed[MAX];
int main()
{
int n,pnum,last,total;
cin>>n;
while(n--)
{
total=0;
cin>>pnum;
last=pnum-1;
for(int i=0;i!=pnum;++i)
{
scanf("%d",&Speed[i]);
}
sort(Speed,Speed+pnum);
if(pnum==1) cout<<Speed[0]<<endl;
else
{
while(last>=2)
{
if(last>=3)
{
if(Speed[last-1]+Speed[0]>Speed[1]*2)
total+=Speed[last]+Speed[0]+2*Speed[1];
else total+=Speed[0]*2+Speed[last-1]+Speed[last];
last-=2;
}
else if(last==2)
{
total+=Speed[0]+Speed[last];
break;
}
}
total+=Speed[1];
cout<<total<<endl;
}
}
}        

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值