알고리즘

백준 14179번 빗물 (JAVA)

박카스마시며코딩 2022. 1. 4. 22:36

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

 

14719번: 빗물

첫 번째 줄에는 2차원 세계의 세로 길이 H과 2차원 세계의 가로 길이 W가 주어진다. (1 ≤ H, W ≤ 500) 두 번째 줄에는 블록이 쌓인 높이를 의미하는 0이상 H이하의 정수가 2차원 세계의 맨 왼쪽 위치

www.acmicpc.net

 

저는 각각의 높이마다 몇개의 빈 블록이 두 블록 사이에 있는지를 판단하였습니다. 첫 빈칸이 아닌 것을 찾고 그 다음 빈칸이 아닌것을 찾아서 그 사이의 값을 더해주면서 문제를 해결하였습니다.

 

package BOJ.Simulation;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.function.Function;

public class BOJ_14719 {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine()," ");
        Function<String,Integer> stoi = Integer::parseInt;
        int n = stoi.apply(st.nextToken());
        int m = stoi.apply(st.nextToken());
        int[] height = new int[m];
        st = new StringTokenizer(br.readLine()," ");
        for(int i = 0 ; i < m ; i++){
           height[i] = stoi.apply(st.nextToken());
        }
        int result = 0;
        for(int i = 1 ; i <= n ; i++){
            int index = -1;
            for(int j = 0 ; j < m ; j++){
                if(height[j] >= i){
                    if(index != -1){
                        result += (j - index - 1);
                    }
                    index = j;
                }
            }
//            System.out.println(i+" "+result);
        }
        System.out.println(result);
    }
}