Codeforces Gym101234G Dreamoon and NightMarket(优先队列,子集和第k大)

本文介绍了一种使用优先队列解决子集和第K大的经典算法问题的方法。通过不断更新优先队列来获取所有可能子集中第K大的元素。适用于n,k≤1e6的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:

求子集和第k大,n,k<=1e6

思路:

优先队列经典题目,注意优先队列是默认按从大到小排的

代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<stack>
#include<queue>
#include<deque>
#include<set>
#include<vector>
#include<map>
    
#define fst first
#define sc second
#define pb push_back
#define mem(a,b) memset(a,b,sizeof(a))
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
#define lc root<<1
#define rc root<<1|1
#define lowbit(x) ((x)&(-x)) 

using namespace std;

typedef double db;
typedef long double ldb;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PI;
typedef pair<ll,ll> PLL;


const db eps = 1e-6;
const int mod = 1e9+7;
const int maxn = 4e5+100;
const int maxm = 4e5+100;
const int inf = 0x3f3f3f3f;
const db pi = acos(-1.0);

int n, k;
ll a[maxn];
priority_queue<pair<ll, int> ,vector<pair<ll,int>>, greater<pair<ll,int>> >q;

//priority_queue<pair<ll,int>, vector<pair<ll,int> >, greater<pair<ll,int> > >q;
int main(){
    scanf("%d %d", &n, &k);
    for(int i = 1; i <= n; i++){
        scanf("%lld", &a[i]);
    }
    sort(a+1,a+1+n);
    q.push({a[1],1});
    int cnt = 0;
    
    while(cnt < k){
        auto tmp = q.top();
        q.pop();
        ll ans = tmp.fst;
        int id = tmp.sc;
        if(id < n){
            q.push({ans+a[id+1],id+1});
            q.push({ans-a[id]+a[id+1], id+1});
        }
        cnt++;
        if(cnt == k){
            printf("%lld\n", ans);
            break;
        }
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/wrjlinkkkkkk/p/10660258.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值