PAT甲级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 (2≤N≤10
​4
​​ ). Then N positive integer lengths of the segments are given in the next line, separated by spaces. All the integers are no more than 10
​4
​​ .

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

就是每次挑选两个小的,加起来对半开,知道剩下最后一个元素

肯定是要排序的,然后每次读取两个小的,又因为还有重复的元素不能用set了
其实想想的话,我们只需要读取元素,没必要删除,直接一个for循环搞定

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;

int main()
{
    int n;
    cin>>n;
    int sn[n];
    for(int i=0; i<n; i++)
    {
        cin>>sn[i];
    }
    sort(sn,sn+n);
    double sum=sn[0]; //实现时候先让最短的就看做已经折叠了一次的,然后再每次都折叠
    for(int i=1; i<n; i++)
    {
        sum=sum/2+(double)sn[i]/2;
    }
    cout<<(int)sum;
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章