https://www.acmicpc.net/problem/1021
1021번: 회전하는 큐
첫째 줄에 큐의 크기 N과 뽑아내려고 하는 수의 개수 M이 주어진다. N은 50보다 작거나 같은 자연수이고, M은 N보다 작거나 같은 자연수이다. 둘째 줄에는 지민이가 뽑아내려고 하는 수의 위치가
www.acmicpc.net
나의 풀이 : ArrayList 사용
import java.io.*;
import java.util.*;
public class Main {
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());
int k = Integer.parseInt(st.nextToken());
List<Integer> list = new ArrayList<>();
int[] nums = new int[k];
int cnt = 0;
int i;
st = new StringTokenizer(br.readLine());
for (i = 0; i < k; i++)
nums[i] = Integer.parseInt(st.nextToken());
for (i = 1; i <= n; i++)
list.add(i);
for (i = 0; i < k; i++) {
int idx = list.indexOf(nums[i]);
if (idx <= list.size()/2) {
for (int j = 0; j < idx; j++)
list.add(list.remove(0));
cnt += idx;
}
else {
for (int j = 0; j < list.size() - idx; j++)
list.add(0, list.remove(list.size()-1));
cnt += list.size() - idx;
}
list.remove(0);
}
System.out.println(cnt);
}
}
다른 풀이 : Deque를 구현하는 LinkedList 사용
import java.io.*;
import java.util.*;
public class Main {
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());
int k = Integer.parseInt(st.nextToken());
LinkedList<Integer> list = new LinkedList<>();
int cnt = 0;
int i;
for (i = 1; i <= n; i++)
list.add(i);
st = new StringTokenizer(br.readLine());
for (i = 0; i < k; i++) {
int num = Integer.parseInt(st.nextToken());
int idx = list.indexOf(num);
if (idx <= list.size()/2) {
for (int j = 0; j < idx; j++)
list.offerLast(list.pollFirst());
cnt += idx;
}
else {
for (int j = 0; j < list.size() - idx; j++)
list.offerFirst(list.pollLast());
cnt += list.size() - idx;
}
list.pollFirst();
}
System.out.println(cnt);
}
}
728x90
'Algorithm 문제 풀이 > 백준' 카테고리의 다른 글
[백준] 2615번 : 오목 - 자바[Java] (0) | 2022.09.28 |
---|---|
[백준] 1874번 : 스택 수열 - 자바[Java] (1) | 2022.09.25 |
[백준] 9012번 : 괄호 - 자바[Java] (1) | 2022.09.24 |
[백준] 2468번 : 안전영역 - 자바[Java] (0) | 2022.09.24 |
[백준] 5212번 : 지구 온난화 - 자바[Java] (1) | 2022.09.23 |