본문 바로가기

PS

백준 1021 C++ [boj 1021 회전하는 큐]

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

int ans;

void solve() {
    int n, m;
    cin >> n >> m;
    deque<int> dq;
    for (int i = 1; i <= n; ++i) {
        dq.push_back(i);
    }
    while (m--) {
        int target;
        cin >> target;
        while (dq.front() != target) {
            if (distance(dq.begin(), find(dq.begin(), dq.end(), target)) < distance(find(dq.begin(), dq.end(), target), dq.end())) {
                dq.push_back(dq.front());
                dq.pop_front();
            } else {
                dq.push_front(dq.back());
                dq.pop_back();
            }
            ans++;
        }
        dq.pop_front();
    }
    cout << ans << '\n';
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    solve();
    return 0;
}