​PAT 1125​​​ ​​C++​​版

1.题意

给出一串数字,代表的含义是绳子的长度。现在想要用这些绳子的结成一个更大的绳子,但是在由两个绳子结成一根绳子的时候,形成的绳子是前两根绳子一半的和。现在需要求出最长的可拼接长度。

2.分析


  • 从小到大排序
  • 求和,使用floor()函数,求出不超过结果的最大整数

3.代码

#include<cstdio> 
#include<algorithm>
#include<functional>
#include<math.h>
using namespace std;

int main(){
int N;
scanf("%d",&N);
double ropeLen [N];
for(int i = 0;i< N;i++){
scanf("%lf",&ropeLen[i]);//input the length of rope
}
sort(ropeLen,ropeLen+N,less<double>());

double res = ropeLen[0];
//如果说明有两根以上的绳子
if(N > 1){
res = ropeLen[0]/2 + ropeLen[1]/2;
for(int i = 2;i < N;i++){
res = res/2 + ropeLen[i]/2 ;
}
res = floor(res );
printf("%.0f",res);
}
else{//如果只有一根绳子
printf("%.0f",res);
}
}

4.测试用例

8
10 15 12 3 4 13 1 15