์‹ค๋ฒ„2 : ํŒŒ๋ผ๋ฉ”ํŠธ๋ฆญ ์„œ์น˜ ๋ฌธ์ œ์ด๋‹ค.

Root ์ฐพ๊ธฐ

์ฒ˜์Œ์— ๋˜๋‹ค์‹œ ํ•ด์‹œ๋กœ ํ’€๋ ค๊ณ  ํ•˜๋‹ค๊ฐ€, ์ค‘๊ฐ„์— ์ž…๋ ฅ๊ฐ’์˜ ๋ฒ”์œ„๊ฐ€ ํ›„๋œ๋œํ•œ ๊ฒƒ์„ ๋ณด๊ณ  ํ’€์ด ๋ฐฉ๋ฒ•์„ ๋ฐ”๊พธ์—ˆ๋‹ค. ์ด ๋ฌธ์ œ๋ฅผ ๊ทธ๋ƒฅ linearํ•˜๊ฒŒ ํ’€๋ ค๊ณ  ํ•˜๋ฉด 100000๋ฒˆ์„ linearํ•˜๊ฒŒ ํƒ์ƒ‰ํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ํ„ฐ์ ธ๋ฒ„๋ฆฐ๋‹ค.

๊ทธ๋ž˜์„œ! ์ด ๋ฌธ์ œ๋Š” ํŒŒ๋ผ๋ฉ”ํŠธ๋ฆญ ์„œ์น˜๋กœ ํ’€์ดํ•œ๋‹ค. ํ•˜๋‚˜์˜ ์งˆ๋ฌธ์— ๋Œ€ํ•ด ๋ช‡๋ฒˆ์ด ํ•„์š”ํ•œ์ง€ ์‚ฌ์‹ค ๊ฒฐ์ •๋˜์–ด ์žˆ๋‹ค. ์ž…๋ ฅ๋˜๋Š” ๊ฒƒ๋“ค์„ ์ง‘ํ•ฉํ™” ํ•˜๊ณ , ์ด๊ฒƒ๋“ค์„ ์ •๋ ฌํ•˜๋ฉด, index๊ฐ€ ๊ณง ํ•ด๋‹น ์ž…๋ ฅ์˜ ์••์ถ•๋œ ์ขŒํ‘œ์ด๋‹ค.

  • ์ž…๋ ฅ
5
2 4 -10 4 -9

|์ง‘ํ•ฉํ™”|2|4|-10|-9| |:-:------|:|:|:-:|::| |์ •๋ ฌ|-10|-9|2|4| |index|0|1|2|3|

์ž˜ ๋ณด๋ฉด, ์ง‘ํ•ฉํ™” ํ•œ ์›์†Œ๋ฅผ ์ •๋ ฌํ•œ ๋’ค, ์ด๊ฒƒ๋“ค์„ ๋ฐฐ์—ด์— ๋„ฃ์—ˆ์„ ๋•Œ, index๊ฐ€ ๊ณง ํ•ด๋‹น ์›์†Œ์˜ ์••์ถ•๋œ ์ขŒํ‘œ์ด๋‹ค.

๋”ฐ๋ผ์„œ, ์ด์ œ๋Š” ์ž…๋ ฅ๋œ ์ˆœ์„œ๋Œ€๋กœ ์ด index๋ฅผ ์ฐพ์•„์ฃผ๊ธฐ๋งŒ ํ•˜๋ฉด ๋œ๋‹ค. ์ด ๋•Œ, ์ฐพ๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ ์ด์ง„ ํƒ์ƒ‰์„ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

Code

#include <iostream>
#include <set>
using namespace std;
int N;
set<int> s;
int arr[1000001];
int net[1000001];
 
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
 
    cin >> N;
    for (int i = 0; i < N; i++) {
        cin >> arr[i];
        s.insert(arr[i]);
    }
 
    int idx = -1;
    for (auto iter = s.begin(); iter != s.end(); iter++) {
        idx++;
        net[idx] = *iter;
    }
 
    for (int i = 0; i < N; i++) {
        int start = 0, end = idx;
        int now = arr[i];
        while (start <= end) {
            int mid = (start+end)/2;
            if (net[mid] > now) {
                end = mid-1;
            } else if (net[mid] < now){
                start = mid+1;
            } else {
                cout << mid << " ";
                break;
            }
        }
    }
    return 0;
}

Reference