728x90
반응형
1. 제로(백준 10773번 문제)
10773번: 제로
첫 번째 줄에 정수 K가 주어진다. (1 ≤ K ≤ 100,000) 이후 K개의 줄에 정수가 1개씩 주어진다. 정수는 0에서 1,000,000 사이의 값을 가지며, 정수가 "0" 일 경우에는 가장 최근에 쓴 수를 지우고, 아닐 경
www.acmicpc.net
▷ 풀이 코드
import java.util.Scanner;
import java.util.Stack;
public class StackZero {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// stack 내장 함수 사용하기
Stack<Integer> s = new Stack<>();
int k = sc.nextInt();
int a;
int sum = 0;
for(int i=0; i<k; i++) {
do {
a = sc.nextInt();
if(a == 0) {
sum -= s.pop();
} else {
sum += s.push(a);
}
} while(a > 100000 && a < 1);
}
System.out.println(sum);
}
}
2. 스택(백준 10828번 문제)
10828번: 스택
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
▷ 풀이 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Stack {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
int ptr = 0;
String a;
for(int i=0; i<n; i++) {
a = br.readLine();
switch(a) {
case "top" :
if(ptr == 0) System.out.println(-1);
else System.out.println(arr[ptr - 1]);
break;
case "pop" :
if(ptr == 0) System.out.println(-1);
else System.out.println(arr[--ptr]);
break;
case "size" : System.out.println(ptr);
break;
case "empty" :
if(ptr == 0) System.out.println(1);
else System.out.println(0);
break;
default :
if(a.substring(0, 4).equals("push")) {
arr[ptr++] = Integer.parseInt(a.substring(5));
}
break;
}
}
br.close();
}
}
728x90
반응형
'문제풀기 > 알고리즘 스터디' 카테고리의 다른 글
[알고리즘] 정렬 문제 풀이(백준 2750번, 2751번, 10989번) (0) | 2023.06.07 |
---|---|
[알고리즘] 정렬 문제 풀이(백준 1181번, 1920번, 1427번) (0) | 2023.06.06 |
[알고리즘] 정렬 문제 풀이(백준 10817번, 11399번) (0) | 2023.06.05 |
[알고리즘] 재귀 문제 풀이(백준 27433번, 10870번, 25501번) (0) | 2023.05.14 |
[알고리즘] Queue 문제 풀이(백준 10773번, 10828번) (0) | 2023.05.07 |