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

这道题我们固定a1和b数组的所有数组合,依次插入到堆里面,然后选n次最小的数,每次选出最小的数的时候,把ai+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;
}
相关推荐
m0_547486665 天前
《数据结构教程》全套 PPT课件2026
数据结构
tryxr5 天前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_35 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
All for pursuit.5 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.5 天前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
渡我白衣5 天前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe
晴天的雨.9925 天前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
淡海水6 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
Logic1016 天前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
2401_839080546 天前
C++常见八股
数据结构·c++·算法