链接:https://ac.nowcoder.com/acm/contest/558/C
来源:牛客网
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld
题目描述
小猫在研究二元组。
小猫在研究最大值。
给定N个二元组(a1,b1),(a2,b2),…,(aN,bN),请你从中选出恰好K个,使得ai的最小值与bi的最小值之和最大。
请输出ai的最小值与bi的最小值之和
输入描述:
第一行两个正整数N,K,表示二元组数量与需要选的数量。
接下来N行,第i行两个正整数ai,bi。
输出描述:
一行一个正整数,表示最大的a_i的最小值与b_i的最小值之和。
示例1
输入
复制
3 2
1 1
2 3
3 1
输出
复制
3
备注:
1≤N≤105,1≤ai,bi≤109
#include <stdio.h>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
#define N 110000
struct Node {
int a, b;
bool operator < (const Node &u) const { // sort()排序时是以b从大到小排序的
return b > u.b;
}
};
Node a[N];
int main() {
int n, k;
scanf("%d%d", &n, &k);
for (int i = 0; i < n; ++i) scanf("%d%d", &a[i].a, &a[i].b);
sort(a, a + n);
int res = 0;
priority_queue<int, vector<int>, greater<int> > q; // greater<int> 当插入新的元素进队列时是以大到小排序的
for (int i = 0; i < n; ++i) {
q.push(a[i].a);
if (q.size() > k) q.pop();
if (q.size() == k) res = max(res, q.top() + a[i].b); // 当前队列q的最靠右的值a为最小的,当前a[i].b的值为当前队列中的两个元素中的b的较小值,即越往后插入的元素的b值将越来越小。
}
printf("%d\n", res);
return 0;
}
转自:https://blog.csdn.net/weixin_41793113/article/details/89300592