P1392 取数

传送门:取数

如若你看完题解后,仍有问题,欢迎评论

首先说一下 我首先想到的思路 ( 20%通过率 ):通过dfs , 将所有的情况放入priority_queue中(greater<int>),维持堆中的数据为k个 -> TLE

代码:

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
int n, m, k;
const int N = 810;
int a[N][N];
priority_queue<int> heap;
void dfs(int i  , int sum)
{
    if (i == n + 1) {
        if (heap.size() == k && sum < heap.top()) {
            heap.pop(); heap.push(sum);
        }
        else if (heap.size() < k)heap.push(sum);
        return;
    }
    for (int k = 1; k <= m; k++)
    {
        dfs(i + 1, sum + a[i][k]);
    }
}
int main()
{
    scanf("%d%d%d", &n, &m, &k);
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            scanf("%d", &a[i][j]);
    dfs(1, 0);
    
    vector<int> res;
    while (heap.size())
    {
        res.push_back(heap.top()); heap.pop();
    }
    reverse(res.begin(), res.end());
    for (auto e : res)
        printf("%d ", e);
    return 0;
}

错误代码的时间复杂度分析: n * m * klongk (建堆 + 遍历整个矩阵)> 10 ^ 8 因此TLE

优化方法:

时间复杂度分析:n * ( mlongm ( 排序 ) + klongk ( 调和级数 ) ) == nmlongm + nklongk = 10 ^ 6 (约等于 ) < 10 ^ 8 可以AC

AC Code:

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
const int N = 810;
int a[N] , b[N];
int n , m , k;
int x,y;
priority_queue<int> heap;
int main()
{
    scanf("%d%d%d",&n,&m,&k);
    heap.push(0);
    for( int i = 1 ; i <= n; i++)
    {
        x = 0; y = 0;
        while( heap.size()) b[++y] = heap.top(),heap.pop();
        for( int j= 1 ; j<= m;j++)scanf("%d",&a[j]);
        sort( a + 1 , a + m + 1 );
        for( int l = 1 ; l <= m;l++)
        {
            for( int r = y ; r ; r--)
            {
                if( x < k )heap.push( a[l] + b[r] ),x++;
                else if( heap.top() < a[l] + b[r] )break;
                else heap.pop(),heap.push(a[l] + b[r] );
            }
        }
    }
    vector<int> res;
    while( heap.size())
    {
        res.push_back(heap.top());
        heap.pop();
    }
    reverse( res.begin(),res.end());
    for( auto e : res  )
    {
        printf("%d ",e );
    }
    return 0;
}
相关推荐
Tony沈哲15 分钟前
macOS 上为 Compose Desktop 构建跨架构图像处理 dylib:OpenCV + libraw + libheif 实践指南
opencv·算法
刘海东刘海东1 小时前
结构型智能科技的关键可行性——信息型智能向结构型智能的转变(修改提纲)
人工智能·算法·机器学习
pumpkin845141 小时前
Rust 调用 C 函数的 FFI
c语言·算法·rust
挺菜的1 小时前
【算法刷题记录(简单题)003】统计大写字母个数(java代码实现)
java·数据结构·算法
mit6.8241 小时前
7.6 优先队列| dijkstra | hash | rust
算法
2401_858286112 小时前
125.【C语言】数据结构之归并排序递归解法
c语言·开发语言·数据结构·算法·排序算法·归并排序
guygg883 小时前
基于matlab的FIR滤波器
开发语言·算法·matlab
ysh98883 小时前
PP-OCR:一款实用的超轻量级OCR系统
算法
遇雪长安3 小时前
差分定位技术:原理、分类与应用场景
算法·分类·数据挖掘·rtk·差分定位
数通Dinner3 小时前
RSTP 拓扑收敛机制
网络·网络协议·tcp/ip·算法·信息与通信