์ƒ์„ธ ์ปจํ…์ธ 

๋ณธ๋ฌธ ์ œ๋ชฉ

[๋ฐฑ์ค€(BOJ)] 11004๋ฒˆ: K๋ฒˆ์งธ ์ˆ˜ (์ •๋ ฌ, C++)

PROGRAMMING/Algorithm

by koharin 2021. 8. 4. 17:33

๋ณธ๋ฌธ

728x90
๋ฐ˜์‘ํ˜•

๐Ÿ“„ ๋ฌธ์ œํ’€์ด ๊ณผ์ •


์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ ํ›„ K๋ฒˆ์งธ ์œ„์น˜ํ•œ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

๊ฐ„๋‹จํ•˜๊ฒŒ qsort๋กœ ์ •๋ ฌ ํ›„ 0๋ฒˆ์งธ๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜๋ฏ€๋กœ K-1 ์ธ๋ฑ์Šค์˜ ์ˆซ์ž๋ฅผ ์ถœ๋ ฅํ•˜๋ฉด ๋˜๊ฒ ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋Š”๋ฐ, ๋Ÿฐํƒ€์ž„ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•ด์„œ ์ฐพ์•„๋ณด๋‹ˆ Quick Selection Sort๋ฅผ ์ด์šฉํ•˜์—ฌ ์ข€๋” ํšจ์œจ์ ์ธ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•ด์•ผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์Œ์„ ์•Œ ์ˆ˜ ์žˆ์—ˆ๋‹ค.

Quick Selection ์•Œ๊ณ ๋ฆฌ์ฆ˜์€ ์ž„์˜์˜ ์ˆซ์ž ๋ฐฐ์—ด์—์„œ K๋ฒˆ์งธ๋กœ ์ž‘๊ฑฐ๋‚˜ ํฐ ๊ฐ’์„ ์ฐพ์„ ๋•Œ ์‚ฌ์šฉํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์œผ๋กœ, ๋ชจ๋“  ๋ฐฐ์—ด์„ ์ •๋ ฌํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ partition ํ•จ์ˆ˜์˜ ๋ฆฌํ„ด ๊ฐ’๊ณผ K๋ฅผ ๋น„๊ตํ•˜์—ฌ partition์„ ๋‚˜๋ˆŒ์ง€ ๊ฒฐ์ •ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ K๋ฒˆ์งธ ์ˆ˜๋ฅผ ์ฐพ๋Š”๋‹ค.

Quick Sort์˜ ๊ฒฝ์šฐ ํ‰๊ท   O(nlogn), worst case์— O(n^2)์ด์ง€๋งŒ, Quick Selection Sort๋Š” worst case์—๋„ ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ O(n)์ด๋‹ค.

C++์—์„œ๋Š” nth_element๊ฐ€ Quick Selection ์•Œ๊ณ ๋ฆฌ์ฆ˜๊ณผ ๊ฐ™์ด ๋™์ž‘ํ•œ๋‹ค๊ณ  ํ•˜์—ฌ nth_element๋กœ ์ •๋ ฌ ํ›„ K-1 ์ธ๋ฑ์Šค์˜ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ๋‹ค.

 

๐Ÿ’ป ์ฝ”๋“œ


#include <bits/stdc++.h>
using namespace std;

int main(){
    int N, K;
    scanf("%d %d", &N, &K);
    deque<int> A;
    for(int i=0; i<N; i++){
        int num; scanf("%d", &num);
        A.push_back(num);
    }
    
    //qsort(&A[0], A.size(), sizeof(int), compare);
    nth_element(A.begin(), A.begin() + K -1, A.end());
    //for(int i : A) cout << i << " ";
    //cout << endl;
    printf("%d", A[K-1]);
}

 

๐Ÿ–จ ์ œ์ถœ ๊ฒฐ๊ณผ


728x90
๋ฐ˜์‘ํ˜•

๊ด€๋ จ๊ธ€ ๋”๋ณด๊ธฐ