import java.io.*;
import java.util.*;
public class Q1021 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
int n = Integer.parseInt(st.nextToken()), m = Integer.parseInt(st.nextToken());
Deque<Integer> deque = new LinkedList<>();
int[] index = new int[m];
for(int i = 0; i < n; i++)
deque.offer(i+1);
st = new StringTokenizer(br.readLine(), " ");
for(int i = 0; i < m; i++)
index[i] = Integer.parseInt(st.nextToken());
int i = 0, count = 0, result = 0;
while(true) {
if (i == m) break;
if (index[i] == deque.peekFirst()) {
deque.pollFirst();
i++;
} else {
Iterator<Integer> it = deque.iterator();
while (it.hasNext()) {
int tmp = it.next();
if (tmp == index[i]) break;
count++;
}
if (count < deque.size() - count) {
while (deque.peekFirst() != index[i]) {
deque.offerLast(deque.pollFirst());
result++;
}
} else {
while (deque.peekFirst() != index[i]) {
deque.offerFirst(deque.pollLast());
result++;
}
}
count = 0;
}
}
System.out.println(result);
}
}
'알고리즘 분류 > 큐 알고리즘' 카테고리의 다른 글
카드1 2161 JAVA (0) | 2023.04.06 |
---|---|
5430 AC JAVA (0) | 2023.04.05 |
10866 덱 JAVA (0) | 2023.03.30 |
18258 큐2 JAVA (0) | 2023.03.30 |
1966 프린터 큐 JAVA (0) | 2023.03.30 |