蓝桥杯每日一题2023.9.28

AcWing 4409. 砍竹子 - AcWing

题目描述

题目分析

注:sqrtl的范围为long double,比sqrt更加精确

使用优先队列维护一段区间,如果连续一段相同就合并为一个区间,从大到小去枚举,每次先取出最大的一段,双关键字排序,第一关键字是v,第二关键字是区间的左端点,先把堆顶元素取出,取完之后,能合并的合并在一起,合并完之后统一做一次操作即可

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2e5 + 10;
ll n, res, a[N];
struct node
{
	ll l, r, h;
	bool operator< (const node& x) const
	{
		if(h != x.h)return x.h > h;
		return x.l < l;
	}
};
ll f(ll x)
{
	return sqrtl(x / 2 + 1);
}
priority_queue<node> q;
int main()
{
	cin >> n;
	for(int i = 0; i < n; i ++)cin >> a[i];
	//先将高度相同的一段加入队列 
	for(int i = 0; i < n; i ++)
	{
		int j = i + 1;
		while(j < n && a[i] == a[j])j ++;
		q.push({i, j - 1, a[i]});
		i = j - 1;
	}
	//进行合并操作
	while(q.top().h > 1)
	{
		auto t = q.top();
		q.pop();
		while(q.size() && q.top().h == t.h && t.r + 1 == q.top().l)//如果堆非空并且现高度与相邻高度一致(相邻即t.r + 1 == q.top().l) 
		{
			t.r = q.top().r;
			q.pop();
		}
		q.push({t.l, t.r, f(t.h)});
		if(t.h > 1)res ++;
	} 
	cout << res << '\n';
	return 0;
}
相关推荐
眰恦37428 分钟前
数据结构--第六章图
数据结构·算法
2401_8628867838 分钟前
蓝禾,汤臣倍健,三七互娱,得物,顺丰,快手,游卡,oppo,康冠科技,途游游戏,埃科光电25秋招内推
前端·c++·python·算法·游戏
luthane40 分钟前
python 实现armstrong numbers阿姆斯壮数算法
python·算法
楠枬42 分钟前
双指针算法
java·算法·leetcode
sjsjs111 小时前
【数据结构-差分】力扣1589. 所有排列中的最大和
数据结构·算法·leetcode
小川_wenxun1 小时前
优先级队列(堆)
java·开发语言·算法
孙小二写代码1 小时前
[leetcode刷题]面试经典150题之4删除有序数组中的重复项II(中等)
算法·leetcode·面试
tlsnzcel2 小时前
【java】常见限流算法原理及应用
java·算法
weixin_515033932 小时前
ccfcsp-202006(4、5)
c++·算法