본문 바로가기

PS/Problems

[Java] 백준 13334번 철로 - 스위핑

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

 

13334번: 철로

입력은 표준입력을 사용한다. 첫 번째 줄에 사람 수를 나타내는 양의 정수 n (1 ≤ n ≤ 100,000)이 주어진다. 다음 n개의 각 줄에 정수 쌍 (hi, oi)가 주어진다. 여기서 hi와 oi는 −100,000,000이상, 100,000,0

www.acmicpc.net

스위핑이라는건 눈치는 채긴 했는데

정렬 기준이 왼쪽이 아니라 오른쪽인 건 눈치를 못챘다.

 

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

public class g2_13334 {
    static FastScanner fs = new FastScanner();
    static PrintWriter pw = new PrintWriter(System.out);
    static int n, d, max = 0;
    static PriorityQueue<Pair> priq = new PriorityQueue<>((o1, o2) -> Integer.compare(o1.right, o2.right));
    static PriorityQueue<Integer> lefts = new PriorityQueue<>();

    public static void main(String[] args) {
        n = fs.nextInt();
        for (int i=0;i<n;i++){
            // priq.add(new Pair(fs.nextInt(), fs.nextInt()));
            int a = fs.nextInt(), b = fs.nextInt();
            priq.add(new Pair(Math.min(a, b), Math.max(a, b)));
        }
        d = fs.nextInt();

        while (!priq.isEmpty()){
            Pair now = priq.poll();
            lefts.add(now.left);

            while (!lefts.isEmpty()){
                if (lefts.peek() < now.right - d){
                    lefts.poll();
                }
                else break;
            }

            max = Math.max(max, lefts.size());
        }
        
        pw.println(max);
        pw.close();
    }

    static class Pair{
        int left, right;

        public Pair(int left, int right){
            this.left = left;
            this.right = right;
        }
    }

    // ----------input function----------

    static void sort(int[] a) {
        ArrayList<Integer> L = new ArrayList<>();
        for (int i : a)
            L.add(i);
        Collections.sort(L);
        for (int i = 0; i < a.length; i++)
            a[i] = L.get(i);
    }

    static class FastScanner {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer("");

        String next() {
            while (!st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        int[] readArray(int n) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++)
                a[i] = nextInt();
            return a;
        }

        long nextLong() {
            return Long.parseLong(next());
        }
    }
}