蓝桥杯备考:数据结构堆之序列合并

这道题我们固定a[1]和b数组的所有数组合,依次插入到堆里面,然后选n次最小的数,每次选出最小的数的时候,把a[i+1]和b数组的该数组合插入堆里面,直到输出n个数,我们程序就结束

cpp 复制代码
#include <iostream>
#include <queue>
using namespace std;
const int N = 1e5+10;
typedef long long ll;
ll a[N],b[N];
struct node{
	ll sum;
	ll i;
	ll j;
	bool operator< (const node& x)const
	{
		return sum >x.sum;
	}
};
priority_queue <node> heap;
int main()
{
	ll n;
	cin >> n;
	for(int i = 1;i<=n;i++)
	{
		cin >> a[i];
	}
	for(int i = 1;i<=n;i++)
	{
		cin >> b[i];
		heap.push({(a[1]+b[i]),1,i});
	}
	for(int c = 1;c<=n;c++)
    {
    	node t = heap.top(); heap.pop();
    	ll i = t.i; ll sum = t.sum; ll j = t.j;
    	cout << sum << " ";
    	heap.push({(a[i+1]+b[j]),i+1,j});
	}
	
	
	
	
	
	
	return 0;
}
相关推荐
呆瑜nuage10 分钟前
类和对象拓展——日期类
数据结构
一只鱼^_3 小时前
牛客周赛 Round 99
java·数据结构·c++·算法·贪心算法·动态规划·近邻算法
dongzhenmao7 小时前
P1484 种树,特殊情形下的 WQS 二分转化。
数据结构·c++·windows·线性代数·算法·数学建模·动态规划
thusloop10 小时前
380. O(1) 时间插入、删除和获取随机元素
数据结构·算法·leetcode
future141211 小时前
游戏开发日记
数据结构·学习·c#
wjcurry11 小时前
完全和零一背包
数据结构·算法·leetcode
qq_4335545412 小时前
C++ 选择排序、冒泡排序、插入排序
数据结构
python_tty12 小时前
排序算法(一):冒泡排序
数据结构·算法·排序算法
学不动CV了13 小时前
ARM单片机OTA解析(二)
arm开发·数据结构·stm32·单片机·嵌入式硬件
kk在加油13 小时前
Redis基础数据结构
数据结构·数据库·redis