1125 Chain the Ropes (25 分)排序

1125 Chain the Ropes (25 分)

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.

rope.jpg

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

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (2N104​​). 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​​.

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

思路:
  这个题读完以后我不知道怎么做,不知道什么怎么样拼接绳子会最长,然后我猜需要进行排序,从小到大排完序以后拼接起来可能会最大
因为也没有别的什么办法好用。我就这样AC了。然后开了一下柳婼(https://blog.csdn.net/liuchuo/article/details/60467543
的分析。两个绳子每次连接之后的和等于它们原来长度总和的一半,拼接后的新绳子和其它绳子继续拼接又会折半,所以要想拼接后最长,那么
最长的绳子应该最晚接入(这样它会损失一般的长度,如果是最先加入,会被多次折半,损失会很大)。所以此题的解法就是先从小到大排序,
然后拼接即可。
   然后要注意的是,最后的结果要强制转型为int型输出即可。
  当然这个题如果改为求最短绳子,也会不难解决了。
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#include<string>
#include<map>
#include<set>
#include<stack>
using namespace std;
vector<int> input;

int main()
{
    int n;
    cin>>n;
    int a[n];
    for(int i=0;i<n;i++)
        cin>>a[i];
    double length=0;
    sort(a,a+n);
    length=a[0]*1.0/2+a[1]*1.0/2;
    for(int i=2;i<n;i++)
        length=length/2+a[i]/2.0;
    cout<<int(length);
   // cout<<"None";
    return 0;
}



猜你喜欢

转载自www.cnblogs.com/zhanghaijie/p/10314922.html
今日推荐