赞
踩
时间限制:1秒 内存限制:128M
几个人过河,每次过两人一人回,速度由慢者决定,问过河所需最短时间。
输入t组数据,每组数据第1行输入n,第2行输入n个数,表示每个人过河的时间。(t<=10,n<=1000)
输出t行数据,每行1个数,表示每组过河最少时间。
1 4 1 2 5 10
17
- #include<cmath>
- #include<cstdio>
- #include<string>
- #include<cstring>
- #include<iomanip>
- #include<iostream>
- #include<algorithm>
- using namespace std;
- int main() {
- int a[1001];
- int t,n;
- cin>>t;
- while(t--) {
- cin>>n;
- for(int i=1; i<=n; i++) {
- cin>>a[i];
- }
- sort(a+1,a+n+1);
- int sum=0;
- while(n>3) {
- sum=sum+min(a[1]*2+a[n-1]+a[n],a[1]+a[2]*2+a[n]);
- n=n-2;
- }
- if(n==1) {
- sum+=a[1];
- }
- else if(n==2){
- sum+=a[2];
- }
- else{
- sum+=a[1]+a[2]+a[3];
- }
- cout<<sum<<endl;
- }
-
- return 0;
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
解题步骤:
算法描述: 贪心算法是一种在每一步选择中都采取在当前状态下最好或最优(即最有利)的选择,从而希望导致结果是最好或最优的算法。在这个问题中,我们的目标是使得过河所需的时间最短,因此我们可以使用贪心算法来解决这个问题。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。