【Luogu P1138】The kth small integer

Kth small integer

Title link: luogu P1138

General idea

Find the k-th largest number in a sequence. The same number is counted only once.

Ideas

This question is actually similar to —>this question<—— .
It needs to be de-duplicated, and then I use divide and conquer here.

To remove duplicates, you can directly open a bool array, if the number is large, you can use map, but this is nlogn, but this problem can also be passed by nlogn.

Code

#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;
}

Guess you like

Origin blog.csdn.net/weixin_43346722/article/details/114005483