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;
}
相关推荐
良月澪二32 分钟前
CSP-S 2021 T1廊桥分配
算法·图论
wangyue41 小时前
c# 线性回归和多项式拟合
算法
&梧桐树夏2 小时前
【算法系列-链表】删除链表的倒数第N个结点
数据结构·算法·链表
QuantumStack2 小时前
【C++ 真题】B2037 奇偶数判断
数据结构·c++·算法
今天好像不上班2 小时前
软件验证与确认实验二-单元测试
测试工具·算法
wclass-zhengge2 小时前
数据结构篇(绪论)
java·数据结构·算法
何事驚慌2 小时前
2024/10/5 数据结构打卡
java·数据结构·算法
结衣结衣.2 小时前
C++ 类和对象的初步介绍
java·开发语言·数据结构·c++·笔记·学习·算法
大二转专业5 小时前
408算法题leetcode--第24天
考研·算法·leetcode
凭栏落花侧5 小时前
决策树:简单易懂的预测模型
人工智能·算法·决策树·机器学习·信息可视化·数据挖掘·数据分析