蓝桥杯练习-算法训练-区间k大数查询

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wordsin/article/details/79766251

蓝桥杯练习-算法训练-区间k大数查询

题目链接

问题描述

给定一个序列,每次询问序列中第l个数到第r个数中第K大的数是哪个。

输入格式

第一行包含一个数n,表示序列长度。
第二行包含n个正整数,表示给定的序列。
第三个包含一个正整数m,表示询问个数。
接下来m行,每行三个数l,r,K,表示询问序列从左往右第l个数到第r个数中,从大往小第K大的数是哪个。序列元素从1开始标号。

输出格式

总共输出m行,每行一个数,表示询问的答案。

样例输入

5
1 2 3 4 5
2
1 5 2
2 3 2

样例输出

4
2

数据规模与约定

对于30%的数据,n,m<=100;
对于100%的数据,n,m<=1000;
保证k<=(r-l+1),序列中的数<=106。

解题思路

    暴力:
    将给定区间的数储存到优先队列,或者其他能排序的数据结构,再一次取出k次,最后一个输出。

AC代码

#include<iostream>
#include<algorithm>
#include<string.h>
#include<cmath>
#include<queue>
using namespace std;
int main() {
    std::ios::sync_with_stdio(false);
    int n,m;
    int a[1050];
    while (cin >> n) {
        for (int i = 1; i <= n; ++i) {
            cin >> a[i];
        }
        cin >> m;
        int l, r, k;
        priority_queue<int> pq;
        for (int i = 0; i < m; ++i) {
            cin >> l >> r >> k;
            while (!pq.empty()) {
                pq.pop();
            }
            for (int j = l; j <= r; ++j) {
                pq.push(a[j]);
            }
            for (int j = 0; j < k-1; ++j) {
                pq.pop();
            }
            cout << pq.top() << endl;
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wordsin/article/details/79766251
今日推荐