백준1021: 회전하는 큐
문제
https://www.acmicpc.net/problem/1021
문제풀이
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
51
52
53
54
55
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
LinkedList<Integer> list = new LinkedList<>();
int cnt = 0;
//큐의 크기
int N = sc.nextInt();
//1부터 N 까지 큐에 담는다.
for (int i = 1; i <= N; i++) {
list.add(i);
}
//뽑아야 하는 수의 개수
int M = sc.nextInt();
//뽑아야 하는 수를 배열에 담는다.
int[] arr = new int[M];
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
for (int i = 0; i < arr.length; i++) {
int idx = list.indexOf(arr[i]);
int halfIdx;
//인덱스는 0부터 시작하기 때문
if (list.size() % 2 == 0) {
halfIdx = list.size() / 2 - 1;
} else {
halfIdx = list.size() / 2;
}
//idx가 중간보다 앞에있을경우 앞에있는 값을 뒤로 보낸다.
if (idx <= halfIdx) {
for (int j = 0; j < idx; j++) {
list.addLast(list.removeFirst());
cnt++;
}
} else {
for (int j = 0; j < list.size() - idx; j++) {
list.addFirst(list.removeLast());
cnt++;
}
}
list.removeFirst();
}
System.out.println(cnt);
}
}
댓글남기기