본문 바로가기
Algorithm/BOJ

백준 3015번 : 오아시스 재결합 Java

by catchJava 2023. 2. 11.

https://www.acmicpc.net/problem/3015

 

3015번: 오아시스 재결합

첫째 줄에 줄에서 기다리고 있는 사람의 수 N이 주어진다. (1 ≤ N ≤ 500,000) 둘째 줄부터 N개의 줄에는 각 사람의 키가 나노미터 단위로 주어진다. 모든 사람의 키는 231 나노미터 보다 작다. 사람

www.acmicpc.net

스택을 이용하고

Pair<숫자, 같은 것의 개수> 를 만들어내야 쉽게 풀 수 있는 문제

import java.util.HashSet;
import java.util.Scanner;
import java.util.Stack;

class Pair {
    int num;
    int cnt;

    Pair(int num, int cnt) {
        this.num = num;
        this.cnt = cnt;
    }
}


public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();

        Stack<Pair> stk = new Stack<>();

        int firstNum = sc.nextInt();
        stk.add(new Pair(firstNum, 1));

        long ans = 0;

        for (int i = 1; i < N; i++) {
            int cur = sc.nextInt();

            while (!stk.isEmpty() && cur > stk.peek().num) {
                ans += stk.pop().cnt;
            }

            if (stk.isEmpty()) {
                stk.add(new Pair(cur, 1));
                continue;
            }

            if (stk.peek().num > cur) {
                ans++;
                stk.add(new Pair(cur, 1));
            } else if (stk.peek().num == cur) {
                int sameCnt = stk.pop().cnt;
                ans += sameCnt;

                if (!stk.isEmpty()) {
                    ans++;
                }
                stk.add(new Pair(cur, sameCnt + 1));
            }
        }
        System.out.println(ans);
    }
}