# 문제
# 입력 및 출력
# 풀이
앞 뒤로 입력 및 출력이 가능해야 하므로 덱을 쓰는게 좋아보였다
최소 연산 수를 출력해야하는데 직접 연산을 해서 최소 연산수를 찾기엔 연산을 하고 나면 큐가 변경되는 문제가 있어서
해당 숫자가 앞으로 접근했을때 몇 번째에 위치하는지와 뒤로 접근했을때 몇 번째에 위치하는지 찾는 함수를 만들었다
그래서 작은 수를 가진 접근으로 연산하도록 했음
#include <iostream>
#include <deque>
using namespace std;
deque<int> q;
int find_front(int num) {
for (int i = 0; i < q.size(); i++) {
if (q.at(i) == num) return i;
}
return 0;
}
int find_back(int num) {
for (int i = q.size() - 1; i >= 0; i--) {
if (q.at(i) == num) return q.size() - i;
}
return 0;
}
int main() {
int n, m, t, result = 0;
cin >> n >> m;
for (int i = 1; i <= n; i++) q.push_back(i);
for (int i = 0; i < m; i++) {
cin >> t;
int f = find_front(t);
int b = find_back(t);
if (f <= b) {
result += f;
while (f--) {
q.push_back(q.front());
q.pop_front();
}
}
else {
result += b;
while (b--) {
q.push_front(q.back());
q.pop_back();
}
}
q.pop_front();
}
cout << result;
}
'Algorithm > 📖Baekjoon' 카테고리의 다른 글
#15650 N과 M (2) (0) | 2022.06.08 |
---|---|
#15649 N과 M (1) (0) | 2022.06.08 |
#16953 A → B (0) | 2022.06.06 |
#1010 다리 놓기 (0) | 2022.06.05 |
#5430 AC (0) | 2022.06.04 |
댓글