백준 1021

hong030·2023년 3월 5일
0
  • 실버 3단계 문제

풀이)
queue란 일방향 삽입 삭제.
dequeue란 쌍방향 삽입 삭제.
이 문제에선 배열을 처음과 끝 두 군데에서 삽입 삭제가 가능하므로 dequeue이다.

내 코드)

import java.io.*;
import java.util.*;

public class Backjoon1021 {

	static int N, M;
	static StringBuilder sb = new StringBuilder();
	static int count = 0;
	static LinkedList<Integer> q = new LinkedList<>();
	
	public static void main(String[] args) throws IOException {
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		StringTokenizer st = new StringTokenizer(br.readLine());
		
		N = Integer.parseInt(st.nextToken());
		M = Integer.parseInt(st.nextToken());
		
		st = new StringTokenizer(br.readLine());
		
		int[] temp = new int[M];
		for(int i = 0 ; i < M ; i++)
			temp[i] = Integer.parseInt(st.nextToken());
		
		// 필요한 변수
		// 일단 뽑아낼 원소의 위치가 left가 빠른지 right가 빠른지 판별하는 것
		// 아마도 q.size 절반보다 작으면 left 아니면 right가 빠르다.
		// 그걸로 보내주면 끝
		for(int i = 1 ; i <= N ; i++)
			q.add(i);
		
		for(int i = 0 ; i < M ; i++) {
			
			if(check(temp[i])) {
				while(temp[i]!=q.get(0)) {
				q.addLast(q.pollFirst());
				count++;
				}
			}else {
				while(temp[i]!=q.get(0)) {
				q.addFirst(q.pollLast());
				count++;
				}
			}
			
			q.poll();
		}

		
		System.out.println(count);

		}
	public static boolean check(int a) {
		
		for(int i = 0 ; i <= q.size()/2 ; i++) {
			if(a == q.get(i))
				return true;
		}
		
		return false;
	}

}

profile
자바 주력, 프론트 공부 중인 초보 개발자. / https://github.com/hongjaewonP

0개의 댓글