문제 : https://www.acmicpc.net/problem/18258
풀이
문제 자체는 쉽다. Queue에 대한 기본 개념만 있으면 쉽게 구현할 수 있다.
다만 계속 '시간초과'가 떠서 이를 해결하는 데 초점을 맞춰야 한다.
시간초과를 해결하기 위해서는 아래 방법들이 있다.
1. 시간이 오래 걸리는 Scanner나 System.out.print() 대신 => BufferedReader, BufferedWriter를 사용한다
- 입력된 데이터를 바로 전달되지 않고 buffer에 모았다가 한번에 전달하므로 데이터 처리 효율성을 높인다. 다만 입력받은 데이터를 전부 String타입으로 고정하기 때문에 다른 타입으로 변환하는 가공 작업이 필요하다.
import java.io.BufferedReader;
import java.io.InputStreamReader;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
2. StringBuilder를 사용해서 output을 한번에 출력한다
코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
class Queue{
StringBuilder sb = new StringBuilder();
LinkedList<Integer> list = new LinkedList<Integer>();
public void push(int x) {
list.add(x);
}
public void pop() throws IOException {
//가장 앞에 있는 정수를 빼고 그 수를 출력한다
//만일 큐에 들어있는 정수가 없으면 -1 출력
sb.append(list.isEmpty()? "-1": list.poll());
sb.append("\n");
}
public void size() throws IOException {
//큐에 들어있는 정수의 개수를 출력한다
sb.append(list.size() + "\n");
}
public void empty() throws IOException {
//큐가 비어있으면 1, 아니면 0 출력
sb.append(list.isEmpty()?"1":"0");
sb.append("\n");
}
public void front() throws IOException {
//가장 앞에 있는 정수를 출력
//만약 큐에 들어있는 정수가 없으면 -1 출력
sb.append(list.isEmpty() ? "-1" : list.getFirst());
sb.append("\n");
}
public void back() throws IOException {
//가장 뒤에 있는 정수를 출력
//만약 큐에 들어있는 정수가 없는 경우 -1 출력
sb.append(list.isEmpty()? "-1" : list.getLast());
sb.append("\n");
}
public void print() {
System.out.print(sb);
}
}
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Queue q = new Queue();
String command[] = new String[n];
for(int i = 0; i<n; i++) {
command[i] = br.readLine();
}
for(int i = 0; i<n; i++) {
String tmp = command[i];
switch(tmp) {
case "front":
q.front();
break;
case "pop":
q.pop();
break;
case "size":
q.size();
break;
case "empty":
q.empty();
break;
case "back":
q.back();
break;
default:
String sx = tmp.substring(5);
int x = Integer.parseInt(sx);
q.push(x);
}
}
q.print();
br.close();
}
}
참고자료
https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html
https://jhnyang.tistory.com/92
https://yeon-kr.tistory.com/152
'알고리즘 > 백준' 카테고리의 다른 글
[백준2606/java] 바이러스 (0) | 2023.05.12 |
---|---|
[백준/java] 1260번 - DFS와 BFS (1) | 2023.05.12 |
[백준/java] 2164번 - 카드2 (0) | 2023.05.12 |
[백준/java] 2630번 - 색종이 만들기 (0) | 2023.05.12 |
[백준/java] 4949번 : 균형잡힌 세상 (0) | 2023.05.12 |