728x90
10845번: 큐
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
문제
정수를 저장하는 큐를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.
명령은 총 여섯 가지이다.
- push X: 정수 X를 큐에 넣는 연산이다.
- pop: 큐에서 가장 앞에 있는 정수를 빼고, 그 수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
- size: 큐에 들어있는 정수의 개수를 출력한다.
- empty: 큐가 비어있으면 1, 아니면 0을 출력한다.
- front: 큐의 가장 앞에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
- back: 큐의 가장 뒤에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
입력
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지 않은 명령이 주어지는 경우는 없다.
출력
출력해야하는 명령이 주어질 때마다, 한 줄에 하나씩 출력한다.
코드
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; int n = Integer.parseInt(br.readLine()); String command=""; int value=0, findex=-1, eindex=-1; // 비어있는 queue는 -1로 시작 Integer[] arr = new Integer[10000]; for(int i=0;i<n;i++) { st = new StringTokenizer(br.readLine()); command = st.nextToken(); if(st.hasMoreTokens()) // 명령어로 판단이 아닌 불러들인 라인에서 토큰이 더있으면 값을 불러들임 value=Integer.parseInt(st.nextToken()); if(command.equals("push")) // 문자열을 비교할때는 ==이 아니라 object.equals(비교문자열)을 이용한다. arr[++eindex]=value; else if(command.equals("pop")) { if(eindex-findex==0) System.out.println(-1); else System.out.println(arr[++findex]); } else if(command.equals("size")) System.out.println(eindex-findex); else if(command.equals("empty")) { if(findex==eindex) System.out.println(1); else System.out.println(0); } else if(command.equals("front")) { if(findex<eindex) System.out.println(arr[findex+1]); else System.out.println(-1); } else if(command.equals("back")) { if(findex<eindex) System.out.println(arr[eindex]); else System.out.println(-1); } } } }
728x90
728x90
'Algorithm > Baekjoon' 카테고리의 다른 글
Baekjoon 2751 수 정렬하기 2 JAVA (0) | 2022.01.14 |
---|---|
Baekjoon 2750 수 정렬하기 JAVA (0) | 2022.01.14 |
Baekjoon 9012 괄호 JAVA (0) | 2022.01.13 |
Baekjoon 10870 피보나치 수 5 JAVA (0) | 2022.01.13 |
Baekjoon 2748 피보나치 수 2 JAVA (0) | 2022.01.13 |
댓글