Codeforces Round #479 (Div. 3) C - Less or Equal 计数

题意:

对于一段序列;给定长度n 和 一个k,找一个[1, 1e9] 的数x,使得序列中恰好k个数小于等于x

思路:

记录每个数,排序,对于序列寻找;;需要注意k = 0 的情况


#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 7;
map<int, int> mp;
int n, k;
int a[maxn];

int main() {
    scanf("%d%d", &n, &k);
    for(int i = 1; i <= n; ++i) {
        scanf("%d", &a[i]);
        mp[a[i]]++;
    }
    sort(a+1, a+1+n);
    if(k == 0) {
        if(a[1] > 1) puts("1");
        else puts("-1");
        return 0;
    }
    for(int i = mp[a[1]]; i <= n; i += mp[a[i+1]]) {
        if(i > k) {
            printf("-1"); return 0;
        }
        if(i == k) {
            printf("%d", a[i]);
            return 0;
        }
    }
    printf("-1");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/xiang_6/article/details/80246106