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;
}

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