第k小整数
题目链接:luogu P1138
题目大意
求一个数列中第 k 大的数,相同的数只算一次。
思路
这道题其实跟——>这道题<——差不多。
它要去重,然后我这里是用分治做的。
去重你可以直接开一个 bool 数组,如果数字大的话你可以用 map,但是这样就 nlogn,不过这题 nlogn 也可以过。
代码
#include<cstdio>
#include<algorithm>
#define ll long long
using namespace std;
ll n, a[5000001], k, ans;
bool in[500001];
ll read() {
ll re = 0ll;
char c = getchar();
while (c < '0' || c > '9') c = getchar();
while (c >= '0' && c <= '9') {
re = re * 10 + c - '0';
c = getchar();
}
return re;
}
void work(ll l, ll r, ll k) {
if (l >= r) {
ans = a[l];
return ;
}
ll L = l - 1, R = r + 1;
ll val = a[(l + r) >> 1];
while (L < R) {
while (a[++L] < val);
while (a[--R] > val);
if (L < R) swap(a[L], a[R]);
}
if (R - l + 1 >= k) work(l, R, k);
else work(R + 1, r, k - (R - l + 1));
}
int main() {
n = read();
k = read();
for (ll i = 1; i <= n; i++) {
a[i] = read();
if (!in[a[i]]) in[a[i]] = 1;
else {
i--;
n--;
}
}
if (k > n) {
printf("NO RESULT");
return 0;
}
work(1, n, k);
printf("%lld", ans);
return 0;
}