728x90
https://www.acmicpc.net/problem/1021
1021번: 회전하는 큐
첫째 줄에 큐의 크기 N과 뽑아내려고 하는 수의 개수 M이 주어진다. N은 50보다 작거나 같은 자연수이고, M은 N보다 작거나 같은 자연수이다. 둘째 줄에는 지민이가 뽑아내려고 하는 수의 위치가 순서대로 주어진다. 위치는 1보다 크거나 같고, N보다 작거나 같은 자연수이다.
www.acmicpc.net
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> cirque = new LinkedList<>();
int i, j, idx, c2, c3, cnt = 0, n = sc.nextInt(), m = sc.nextInt();
int p[] = new int[m]; // position
for( i = 0; i < m; i++ )
p[i] = sc.nextInt();
for( i = 1; i <= n; i++ )
cirque.add(i);
i = 0;
while( i < m ) {
if( cirque.getFirst().intValue() == p[i] ) {
cirque.pollFirst(); // 연산 1
i++;
continue;
}
idx = cirque.indexOf( Integer.valueOf( p[i] ) ); // 뽑으려하는 수 위치
c2 = idx – 0; // 2번 연산 카운트
c3 = cirque.size() - idx; // 3번 연산 카운트
if( c2 <= c3 ) {
for( j = 0; j < c2; j++ )
cirque.addLast( cirque.pollFirst() ); // 연산 2
cnt += c2;
}
else {
for( j = 0; j < c3; j++ )
cirque.addFirst( cirque.pollLast() ); // 연산 3
cnt += c3;
}
}
System.out.println( cnt ); // 연산 카운트
sc.close();
}
}
반응형
'코딩 문제 풀기 ( Algorithm problem solving ) > 백준 온라인 저지 ( BOJ )' 카테고리의 다른 글
[백준(Baekjoon)][자바(java)] 11279 : 최대 힙 / 우선순위 큐 (0) | 2020.04.28 |
---|---|
[백준(Baekjoon)][자바(java)] 5430 : AC / 큐, 덱 (0) | 2020.04.14 |
[백준(Baekjoon)][자바(java)] 10866 : 덱 / 큐, 덱 (0) | 2020.04.14 |
[백준(Baekjoon)][자바(java)] 1966 : 프린터 큐 / 큐, 덱 (0) | 2020.04.14 |
[백준(Baekjoon)][자바(java)] 11866 : 요세푸스 문제 0 / 큐, 덱 (0) | 2020.04.14 |