题目

链接:https://ac.nowcoder.com/acm/contest/28886/1003
来源:牛客网

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld

题目描述

有一个长度为n的数组,值为 a[i], 牛牛想找到数组中第 k 小的数。比如 1 2 2 3 4 6 中,第 3 小的数就是2.

牛牛觉得这个游戏太简单了,想加一点难度,现在牛牛有 m 个操作,每个操作有两种类型。

1 x 1 代表操作一,给数组中加一个元素 x 。(0 ≤ x ≤ 1e9)

2 2 代表操作二,查询第 k 小的数。如果没有 k 个数就输出−1

输入描述:

第一行有三个整数,n m k,(1≤n,m,k≤2e5)
第二行包含 n 个整数 a[i] ( 0 ≤ a[i] ≤ 1e9)
接下来m行,每行代表一个操作。具体见题目描述

输出描述:

每次查询输出一个第  k  小的数。

示例1

输入

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

输出

3
2

题解

这道题目由于一系列骚操作,必须每时每刻对第K小都了解.

我发现这道题目与一道题目类似:https://blog.csdn.net/xjsc01/article/details/122956312

大体思路

准备一个堆,默默等到所有的数据个数大于K

然后开始搞,如果新读入一个数,

  • 大于堆顶,直接忽略.
  • 小于堆顶,那么就push(这个数); pop()//堆顶

代码

#include <iostream>
#include <queue>
using namespace std;
priority_queue<int >q;
int main()
{
   
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int n, m, k;
	cin >> n >> m >> k;
	for (int i = 0; i < n; i++)
	{
   
		int tmp;
		cin >> tmp;
		if (q.empty())
		{
   
			q.push(tmp);
		}
		else
		{
   
			if (q.size() < k)
				q.push(tmp);
			else
			{
   
				if (tmp < q.top())
				{
   
					q.push(tmp);
					q.pop();
				}
				
			}
		}
	}
	for (int i = 0; i < m; i++)
	{
   
		int input;
		int data;
		cin >> input;
		switch (input)
		{
   
		case 1:
			cin >> data;
			if (q.empty())
			{
   
				q.push(data);
			}
			else
			{
   
				if (q.size() < k)
					q.push(data);
				else
				{
   
					if (data < q.top())
					{
   
						q.push(data);
						q.pop();
					}

				}
			}
			break;
		case 2:
			if (q.size() < k)
				cout << -1 << endl;
			else
				cout << q.top() << endl;
			break;

		}
	}

	return 0;
}