Baekjoon/Bronze

Baekjoon 2605. 줄세우기 c++[Bronze II]

Hun-bot 2024. 10. 23. 00:37
728x90
반응형

https://www.acmicpc.net/problem/2605

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    int n; 
    cin >> n;

    vector<int> numbers(n); 
    for (int i = 0; i < n; i++) {
        cin >> numbers[i];
    }
    
    vector<int> line;

    for (int i = 0; i < n; i++) {
        line.insert(line.begin() + numbers[i],i+1);
    }
    reverse(line.begin(),line.end());

    for(vector<int>::iterator it=line.begin();it!=line.end();++it){
        cout << *it << ' ';
    }
    return 0;
}

 

* 연산자를 사용해 it이 가리키는 원소

실제 포인터가 아닌 *연산자를 overloading해서 포인터처럼 동작하게 한 것

입력 값을 넣고 reverse없이 그냥 출력을 해보면 1 3 5 2 4로 나올 것이다

iterator insert (const_iterator position, const value_type& val);

position이 begin() 즉, vector의 0번에서 부터 시작되고 insert 특성상 해당 위치에 있는 값은 뒤로 밀려나기에 1 3 5 2 4가 나오는 것이다.

먼저, begin()+0 = 1 / begin()+1 = 2 까지 들어가고 begin()+1 = 3 여기서 1번 위치에 2가 있었으므로 뒤로 밀려나면서 해당 위치에 3이 들어가는 것. 이걸 반복하기에 1 3 5 2 4가 나온다

 

728x90
반응형