PAT (Advanced Level) Practice 1125 Chain the Ropes (25 分) 凌宸1642

题目描述:

Given some segments of rope, you are supposed to chain them into one rope. Each time you may only fold two segments into loops and chain them into one piece, as shown by the figure. The resulting chain will be treated as another segment of rope and can be folded again. After each chaining, the lengths of the original two segments will be halved.

PAT (Advanced Level) Practice 1125 Chain the Ropes (25 分) 凌宸1642_折半

Your job is to make the longest possible rope out of N given segments.

译:给定一些绳段,您应该将它们链接成一根绳子。 每次只能将两段折叠成环,然后将它们链接成一块,如图所示。 由此产生的链条将被视为另一段绳索,可以再次折叠。 每次链接后,原始两段的长度将减半。你的工作是从 N 个给定的段中制作出尽可能长的绳子。


Input Specification (输入说明):

Each input file contains one test case. For each case, the first line gives a positive integer N (2 ≤ N ≤ 104 ). Then N positive integer lengths of the segments are given in the next line, separated by spaces. All the integers are no more than 104 .

译:每个输入文件包含一个测试用例。 对于每种情况,第一行给出一个正整数 N (2 ≤ N ≤ 104 )。 然后在下一行给出 N 个正整数长度的段,用空格分隔。 所有整数不超过104 。


output Specification (输出说明):

For each case, print in a line the length of the longest possible rope that can be made by the given segments. The result must be rounded to the nearest integer that is no greater than the maximum length.

译:对于每种情况,将给定线段可以制成的最长绳索的长度打印在一行中。 结果必须四舍五入到不大于最大长度的最接近的整数。


Sample Input (样例输入):

8
10 15 12 3 4 13 1 15

Sample Output (样例输出):

14

The Idea:

  • 这里其实就是将所有的短绳按照绳子长短排好序,然后可以分析出,如果总共有 n 段身子,那么第一段将会需要折半 n - 1 次,第二根是折半 n - 2 次 …… 第 n 根绳子需要折半 1 次。根据数学知识可知,需要升序排列,即可得到最长的绳子长度。
  • 需要注意绳子的初值,是所有绳子中最短的那根绳子的长度。

The Codes:

#include<bits/stdc++.h>
using namespace std ;
int n , t , num[10010] ;
int main(){
	cin >> n ;
	for(int i = 0 ; i < n ; i ++) cin >> num[i]  ;
	sort(num , num + n) ;
	int ans = num[0] ; 
	for(int i = 1 ; i < n ; i ++) ans = (ans + num[i] )/2 ;
	cout << (int) ans << endl ;
	return 0 ;
}