poj - 1700 题解

题意:N个人要过河,一个船最多承载两人,且过河速度等于船上划船速度最慢的人的速度,求过河的最短时间。

题目解法:首先对题目进行分析,可以发现:船过了河还要有一个人再把船送回来。

假设把人按过河速度从大到小排序并编号1-4,则会发现有两种过河方式:1.13一组,1回来,24一组,2回来,12一组,完成;2.12一组,1回来,13一组,1回来,14一组,完成。

因此贪心策略就是:把人按过河速度从大到小排序,然后按上述方式过河,每次选取最优方式。

代码如下:

 1     #include<iostream>
 2     #include<algorithm>
 3     using namespace std;
 4     int a[1001];
 5     bool com(const int& x,const int& y)
 6     {
 7         return x<y;
 8     }
 9     int main()
10     {
11         int T;
12         cin>>T;
13         for(int t=1;t<=T;t++)
14         {
15             int n;
16             cin>>n;
17             for(int i=1;i<=n;i++)
18             {
19                 cin>>a[i];
20             }
21             sort(a+1,a+n+1,com);
22             if(n==1)
23             {
24                 cout<<a[1]<<endl;
25                 continue;
26             }
27             if(n==2)
28             {
29                 cout<<a[2]<<endl;
30                 continue;
31             }
32             if(n==3)
33             {
34                 cout<<a[2]+a[1]+a[3]<<endl;
35                 continue;
36             }
37             int res=a[2];
38             int tip=n;
39             if(n%2==0)
40             {
41                 while(tip>=4)
42                 {
43                     int t1=a[1]+a[2]+a[2]+a[tip];
44                     int t2=a[tip]+a[1]+a[tip-1]+a[1];
45                     res+=min(t1,t2);
46                     tip-=2;
47                 }
48             }
49             else
50             {
51                 while(tip>=5)
52                 {
53                     int t1=a[1]+a[2]+a[2]+a[tip];
54                     int t2=a[1]+a[tip]+a[1]+a[tip-1];
55                     res+=min(t1,t2);
56                     tip-=2;
57                 }
58                 res+=a[1]+a[3];
59             }
60             cout<<res<<endl;
61         }
62         return 0;
63     }

 

转载于:https://www.cnblogs.com/shao0099876/p/7297398.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值