본문 바로가기

라이브러리/JAVA

선형 스위프 (line sweep), 차분 배열 (difference array)

20207

 

 

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

public class Main
{
    public static void main (String[] args) throws IOException
    {
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;

        int N = Integer.parseInt(input.readLine());
        int[] calendar = new int[367];

        for (int i=0; i<N; i++)
        {
            st = new StringTokenizer(input.readLine());

            int start = Integer.parseInt(st.nextToken());
            int end = Integer.parseInt(st.nextToken());

            calendar[start]++;
            calendar[end+1]--;
        }

        int height = 0;
        int width = 0;
        int ans = 0;

        for (int i=1; i<=366; i++)
        {
            if ( calendar[i] == 0 )
            {
                ans += width * height;
                width = 0;
                height = 0;
            }
            else
            {
                calendar[i+1] += calendar[i];
                width++;
                height = Math.max(height, calendar[i]);
            }
        }

        System.out.print(ans);
    }
}

'라이브러리 > JAVA' 카테고리의 다른 글

중앙값  (0) 2025.03.17
최소 비용 합치기  (0) 2025.03.07
p^k <= N  (0) 2025.01.23
Binary Lifting  (1) 2025.01.18
완전이진트리 노드 k의 서브트리 사이즈  (1) 2025.01.02