본문 바로가기

백준/큐,스택,덱

백준 1021 - 회전하는 큐

728x90
728x90

www.acmicpc.net/problem/1021

 

덱에 들어있는 원소의 정확한 내용물은 정해지지 않았으므로 원소의 순서로 붙여진 숫자를 원소라 봐도 무방하다.

 

N과 M이 크지 않으므로 각 원소를 제거하기 위해 왼쪽으로 회전하는 경우, 오른쪽으로 회전하는 경우를 나눠 둘 중 연산 횟수가 적은 쪽을 택하면 된다.

 

전체 코드

더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <bits/stdc++.h>
 
using namespace std;
 
int n, m;
deque<int> dq;
int cnt;
 
int main()
{
    cin.tie(0); ios::sync_with_stdio(false);
    cin >> n >> m;
    for (int i = 0; i < n; ++i)
        dq.push_back(i + 1);
 
    while (m--)
    {
        int num;
        cin >> num;
        int l = 0, r = 0;
 
        deque<int> b = dq, f = dq;
        int x;
 
        while (f.front() != num)
        {
            x = f.front();
            f.pop_front();
            f.push_back(x);
            ++l;
        }
 
        while (b.front() != num)
        {
            x = b.back();
            b.pop_back();
            b.push_front(x);
            ++r;
        }
 
        if (l > r)
            cnt += r, dq = b;
        else
            cnt += l, dq = f;
 
        dq.pop_front();
    }
 
    cout << cnt;
}
cs
728x90
728x90

'백준 > 큐,스택,덱' 카테고리의 다른 글

백준 17298 - 오큰수  (0) 2021.01.25