PAT A1125 Chain the Ropes
Sample Input:
8
10 15 12 3 4 13 1 15
Sample Output:
14
word | meaning |
---|---|
halved | |
the nearest integer |
-
分析:
每两根连成一根,这根长度是原来两根和的一半 -
思路 1:
贪心:越先被选择的绳子被折叠的次数越多,故每次选长度最小的(关于精度,这题好像直接用int也可以) -
code 1:
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 10100;
int main(){
int n;
double input[maxn];
scanf("%d", &n);
for(int i = 0; i < n; ++i) scanf("%lf", &input[i]);
sort(input, input+n);
double ans = input[0]; //!!!Wrong 1:不能用0->不然第一个绳子被多叠了几次
for(int i = 1; i < n; ++i) ans = (ans + input[i]) / 2 ;
printf("%d", (int)ans);
return 0;
}
-
思路 2:priority_queue:每次从队首取两个元素,求和除2后再压入队,直到队只剩一个元素
-
T2 code:
#include <bits/stdc++.h>
using namespace std;
int main(){
int n, tmp;
scanf("%d", &n);
priority_queue<int, vector<int>, greater<int> > pq;
for(int i = 0; i < n; ++i){
scanf("%d", &tmp);
pq.push(tmp);
}
while(pq.size() != 1){
int tp1 = pq.top();
pq.pop();
int tp2 = pq.top();
pq.pop();
pq.push((tp1 + tp2) / 2);
}
int top = pq.top();
printf("%d", top);
return 0;
}