PAT A1125 Chain the Ropes

PAT A1125 Chain the Ropes

在这里插入图片描述

Sample Input:

8
10 15 12 3 4 13 1 15

Sample Output:

14
wordmeaning
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值