23년 4월 30일 [알고리즘 - 자료구조]

sua·2023년 4월 29일
0

알고리즘 가보자고

목록 보기
12/101

백준 10773번 제로

문제


나의 풀이

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int k = sc.nextInt();
        
        Stack<Integer> stack = new Stack<>();
        for(int i = 0; i < k; i++) {
            int n = sc.nextInt();
            if(n == 0) {
                stack.pop();
            } else {
                stack.push(n);
            }
        }
        
        int sum = 0;
        while(!stack.isEmpty()) {
            sum += stack.pop();
        }
        System.out.println(sum);
    }
}

스택 자료 구조를 생성한뒤 입력 받은 수가 0인 경우 pop 메소드를 사용해서 가장 최근에 쓴 수를 제거하고, 아닌 경우는 push 메소드를 사용해서 입력 받은 수를 스택에 넣는다. 그런 다음 스택에 있는 수들을 sum 변수에 모두 더해서 출력시켜주면 된다.

결과


백준 2493번 탑

문제


나의 풀이

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

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());
        
        int arr[] = new int[n];
        StringTokenizer st = new StringTokenizer(br.readLine());
        for(int i = 0; i < n; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }
        
        Stack<int[]> stack = new Stack<>();
        for(int i = 0; i < n; i++) {
            while(!stack.isEmpty()) {
                if(stack.peek()[1] < arr[i]) {
                    stack.pop();
                } else {
                    System.out.print(stack.peek()[0] + " ");
                    break;
                }
            }
            if(stack.isEmpty()) {
                System.out.print("0 ");
            }
            stack.push(new int[] { i + 1, arr[i] }); // 0번째는 타워 순번, 1번째는 타워 높이 
        }
    }
}

결과


백준 18258번 큐 2

문제


나의 풀이

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

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<Integer> queue = new LinkedList<>();
        int back = 0;
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < n; i++) {
            String s = br.readLine();
            if(s.contains("push")) {
                queue.offer(Integer.parseInt(s.split(" ")[1]));
                back = Integer.parseInt(s.split(" ")[1]);
            } else if(s.equals("pop")) {
                if(!queue.isEmpty()) {
                    sb.append(queue.poll()).append("\n");
                } else {
                    sb.append("-1").append("\n");
                }
            } else if(s.equals("size")) {
                sb.append(queue.size()).append("\n");
            } else if(s.equals("empty")) {
                if(!queue.isEmpty()) {
                    sb.append("0").append("\n");
                } else {
                    sb.append("1").append("\n");
                }
            } else if(s.equals("front")) {
                if(!queue.isEmpty()) {
                    sb.append(queue.peek()).append("\n");
                } else {
                    sb.append("-1").append("\n");
                }
            } else if(s.equals("back")) {
                if(!queue.isEmpty()) {
                    sb.append(back).append("\n");
                } else {
                    sb.append("-1").append("\n");
                }
            }
        }
        
        System.out.println(sb);
    }
}

큐 라이브러리를 사용해서 구현 하면 되지만, 한가지 유의해야할 점은 큐의 가장 뒤에 있는 정수를 구하는 메소드는 없으므로 back이라는 변수를 두어서 push 명령어일 때 큐에 입력한 숫자를 삽입할 때 해당 수를 back에 저장해서 back 명령어일 때 그 값을 출력하게 해줘야 한다.

결과

profile
가보자고

0개의 댓글