Skip to content

Instantly share code, notes, and snippets.

@dalcon10028
Created March 10, 2020 13:28
Show Gist options
  • Select an option

  • Save dalcon10028/a6b15a71c6335424209f243fa7fba46e to your computer and use it in GitHub Desktop.

Select an option

Save dalcon10028/a6b15a71c6335424209f243fa7fba46e to your computer and use it in GitHub Desktop.
import java.util.*;
public class Main {
static LinkedList<Integer> queue = new LinkedList<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int result = 0;
int[] input = new int[m];
for (int i=1; i<=n; i++)
queue.add(i);
for (int i=0; i<m; i++)
input[i] = sc.nextInt();
// 입력 끝
int nowIdx = 0; // 현재 가리키는 위치
for (int i = 0; i < m; i++){
if (input[i] == queue.get(nowIdx)){ // 찾는 인덱스가 현재 위치인 경우
queue.remove(nowIdx); // 제거하고
nowIdx = nowIdx == queue.size() ? 0 : nowIdx;
// 큐의 마지막 요소를 가리키면 인덱스 0으로 넘기고 아니면 그대로
continue;
}
// 오른쪽 방향으로 이동
int[] rightMove = move(true, nowIdx, input[i]);
// 왼쪽 방향으로 이동
int[] leftMove = move(false, nowIdx, input[i]);
// 더 짧은 것으로 이동
if(rightMove[0] < leftMove[0]) result += rightMove[0];
else result += leftMove[0];
nowIdx = rightMove[1]; // 오른쪽 왼쪽 이동 같으므로 아무거나 넣어도 됨
queue.remove(nowIdx);
nowIdx = nowIdx == queue.size() ? 0 : nowIdx;
}
System.out.print(result);
}
static int[] move(boolean right, int nowIdx, int destination){
int moveCount = 0;
while(destination != queue.get(nowIdx)){
if(right)
nowIdx = nowIdx+1 == queue.size() ? 0 : nowIdx + 1;
else
nowIdx = nowIdx-1 < 0 ? queue.size()-1 : nowIdx -1 ;
moveCount++;
}
return new int[]{moveCount, nowIdx};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment