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

这道题我们固定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;
}
相关推荐
独好紫罗兰22 分钟前
对python的再认识-基于数据结构进行-a003-列表-排序
开发语言·数据结构·python
wuhen_n28 分钟前
JavaScript内置数据结构
开发语言·前端·javascript·数据结构
2401_8414956433 分钟前
【LeetCode刷题】二叉树的层序遍历
数据结构·python·算法·leetcode·二叉树··队列
独好紫罗兰1 小时前
对python的再认识-基于数据结构进行-a002-列表-列表推导式
开发语言·数据结构·python
2401_841495641 小时前
【LeetCode刷题】二叉树的直径
数据结构·python·算法·leetcode·二叉树··递归
数智工坊1 小时前
【数据结构-树与二叉树】4.5 线索二叉树
数据结构
数智工坊2 小时前
【数据结构-树与二叉树】4.3 二叉树的存储结构
数据结构
独好紫罗兰2 小时前
对python的再认识-基于数据结构进行-a004-列表-实用事务
开发语言·数据结构·python
铉铉这波能秀2 小时前
LeetCode Hot100数据结构背景知识之列表(List)Python2026新版
数据结构·leetcode·list
历程里程碑2 小时前
Linux20 : IO
linux·c语言·开发语言·数据结构·c++·算法