算法学习 -- 多路归并

思想 :

抽象出来一个例子 : 合并k个长度相等升序列表 :

抽象成一张表也就是 :

做法 : 用一个小根堆来维护 , 首先将每个序列的第一个元素放入队列中 , 然后模拟,每次取出队头,作为结果序列的下一个元素 , 然后向堆中存入该元素序列中的下一个元素 ,直到所有元素取完为止;

例题 :

1262 - 鱼塘钓鱼

1262. 鱼塘钓鱼 - AcWing题库

c++代码 :

复制代码
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 110 ;
typedef pair<int, int> PII;
int a[N] , b[N] , c[N] ;
int n , T ;

int main(){
    cin >> n ; 
    for(int i=1;i<=n;i++) cin >> a[i] ;
    for(int j=1;j<=n;j++) cin >> b[j] ;
    for(int k=2;k<=n;k++) cin >> c[k] , c[k] += c[k-1] ;
    cin >> T ;
    int ans = 0 ;
    // 只在前k个池塘钓鱼
    for(int i=1;i<=n;i++){
        int t = T - c[i] ; // 本次钓鱼专用时间 
        priority_queue<PII> que ;
        for(int j=1;j<=i;j++) que.push({a[j],j}) ;
        int res = 0 ;
        while(!que.empty() && t > 0){
            auto it = que.top() ; que.pop() ;
            int x = it.first , idx = it.second ; // 获取元素和下标
            res += x ;
            int xx = x - b[idx] ;
            if(xx > 0) que.push({xx , idx}) ;
            t -- ;
        }
        ans = max(ans , res) ;
    }
    cout << ans << endl ;
}

62 . 丑数

62. 丑数 - AcWing题库

复制代码
class Solution {
public:
    int getUglyNumber(int n) {
        if(n <= 1) return n;
        vector<int> f(1,1);
        int i = 0, j = 0, k = 0;
        long long t = 0;
        while(--n)
        {
            t = min(f[i] * 2, min (f[j] * 3, f[k] * 5));
            if(t == f[i] * 2) i++;
            if(t == f[j] * 3) j++;
            if(t == f[k] * 5) k++;
            f.push_back(t);
        }
        return f.back();
    }
};

参考 : 多路归并算法从理论到应用(易懂)-CSDN博客

相关推荐
我命由我123452 分钟前
Photoshop - Photoshop 使用简单的选择工具
学习·职场和发展·产品运营·求职招聘·职场发展·学习方法·photoshop
UIU11413 分钟前
头文件可以防什么错?运用头文件做声明
c++·学习·c#
我命由我1234519 分钟前
Photoshop - Photoshop 使用工具
学习·职场和发展·产品运营·求职招聘·职场发展·产品经理·学习方法
外收内放31 分钟前
Python基础语法练习题(53-54)
python·学习
欣欣之王来了1 小时前
Python入门:Jupyter Notebook安装与使用指南
学习·架构·面向对象·项目·python教程
JWASX1 小时前
Java 转 go 学习 - kitex(2)
学习·golang
wdfk_prog1 小时前
LWIP教程 03:从 `low_level_input()` 到 `pbuf_free()`——`pbuf` 的数据视图、Chain 与引用计数
运维·网络·笔记·学习
我命由我123451 小时前
Photoshop - Photoshop 设计概念
学习·职场和发展·产品运营·求职招聘·职场发展·产品经理·学习方法
白猫不黑2 小时前
网络安全专业:从入门到进阶的完整学习路线
学习·安全·web安全·计算机·网络安全·信息安全·编程
ouynagda2 小时前
嵌入式Linux i.MX6ULL系统移植学习笔记
linux·笔记·学习