-
[java] 백준 10845 : 큐, 10828 : 스택알고리즘 2023. 4. 11. 07:42
큐
문제
https://www.acmicpc.net/problem/10845
10845번: 큐
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
풀이
scanner로 하니 시간초과가 발생하여 bufferedReader사용하니 해결됨
코드
package main; import java.io.*; import java.util.*; //큐는 선입선출 public class Main { static Queue<Integer> q; public static void main(String[] args) throws IOException { q = new LinkedList<>(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); String x; int pn=0; for(int i=0; i<n; i++) { st = new StringTokenizer(br.readLine()); x = st.nextToken(); if(x.equals("push")) { pn = Integer.parseInt(st.nextToken()); q.add(pn); }else if(x.equals("pop")) { System.out.println(q.isEmpty()? -1: q.poll()); }else if(x.equals("size")) { System.out.println(q.size()); } else if(x.equals("empty")){ System.out.println(q.isEmpty()? 1: 0); }else if(x.equals("front")) { System.out.println(q.isEmpty()? -1: q.peek()); } else if(x.equals("back")) { System.out.println(q.isEmpty()? -1: pn); } } } }
스택
문제
https://www.acmicpc.net/problem/10828
10828번: 스택
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
코드
import java.io.*; import java.util.*; public class Main { static Stack<Integer> stack; public static void main(String[] args) throws IOException { stack = new Stack<Integer>(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); String x; int pn=0; for(int i=0; i<n; i++) { st = new StringTokenizer(br.readLine()); x = st.nextToken(); if(x.equals("push")) { pn = Integer.parseInt(st.nextToken()); stack.add(pn); }else if(x.equals("pop")) { System.out.println(stack.isEmpty()? -1: stack.pop()); }else if(x.equals("size")) { System.out.println(stack.size()); } else if(x.equals("empty")){ System.out.println(stack.isEmpty()? 1: 0); } else if(x.equals("top")) { System.out.println(stack.isEmpty()? -1: stack.peek()); } } } }
'알고리즘' 카테고리의 다른 글
[java] 백준 11724: 연결 요소의 개수 (0) 2023.04.11 [java] 백준 13023: ABCDE (0) 2023.04.11 [java] 프로그래머스 H-index (0) 2023.04.05 [java] 백준 1138 한 줄로 서기 (0) 2023.03.25 [java] 백준 2178 : 미로탐색 (0) 2023.03.25