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

这道题我们固定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;
}
相关推荐
皮皮哎哟1 小时前
数据结构:嵌入式常用排序与查找算法精讲
数据结构·算法·排序算法·二分查找·快速排序
堕2742 小时前
java数据结构当中的《排序》(一 )
java·数据结构·排序算法
2302_813806222 小时前
【嵌入式修炼:数据结构篇】——数据结构总结
数据结构
Wei&Yan3 小时前
数据结构——顺序表(静/动态代码实现)
数据结构·c++·算法·visual studio code
long3163 小时前
Aho-Corasick 模式搜索算法
java·数据结构·spring boot·后端·算法·排序算法
张张努力变强6 小时前
C++ STL string 类:常用接口 + auto + 范围 for全攻略,字符串操作效率拉满
开发语言·数据结构·c++·算法·stl
wWYy.6 小时前
数组快排 链表归并
数据结构·链表
李斯啦果6 小时前
【PTA】L1-019 谁先倒
数据结构·算法
Mr Xu_1 天前
告别硬编码:前端项目中配置驱动的实战优化指南
前端·javascript·数据结构
czxyvX1 天前
017-AVL树(C++实现)
开发语言·数据结构·c++