Koala - 9기/기초 알고리즘 스터디

[백준/Java] 7795번 먹을 것인가 먹힐 것인가

2_donghh 2023. 2. 5. 22:45

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

 

7795번: 먹을 것인가 먹힐 것인가

심해에는 두 종류의 생명체 A와 B가 존재한다. A는 B를 먹는다. A는 자기보다 크기가 작은 먹이만 먹을 수 있다. 예를 들어, A의 크기가 {8, 1, 7, 3, 1}이고, B의 크기가 {3, 6, 1}인 경우에 A가 B를 먹을

www.acmicpc.net

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

public class Main {
    static FastReader scan = new FastReader();
    static StringBuilder sb = new StringBuilder();

    static int N, M;
    static int[] A, B;

    static void input() { 
    
        N = scan.nextInt(); 
        M = scan.nextInt(); 
        
        A = new int[N + 1]; 
        B = new int[M + 1]; 
       
       for (int i = 1; i <= N; i++) {
            A[i] = scan.nextInt(); 
        }
        
        for (int i = 1; i <= M; i++) {
            B[i] = scan.nextInt(); 
        }
    }



    static int findAns(int[] A, int L, int R, int X) {
        
        int res = L - 1; 
        				
        while (L <= R) { 
            int mid = (L + R) / 2; 
            if (A[mid] < X) { 
                res = mid;  
               L = mid + 1; 
            } else {
                R = mid - 1; 
            }
        }
        return res;
    }

    static void find() {
     
        Arrays.sort(B, 1, M + 1); 
        
        int ans = 0; 
        for (int i = 1; i <= N; i++) {
            ans += findAns(B, 1, M, A[i]); 
        }
        System.out.println(ans);
    }

    public static void main(String[] args) {
        int TT;
        TT = scan.nextInt(); 
        for (int tt = 1; tt <= TT; tt++) {
            input(); 
            find();  
        }
    }


    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        public FastReader() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public FastReader(String s) throws FileNotFoundException {
            br = new BufferedReader(new FileReader(new File(s)));
        }

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

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

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

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

        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
}

[문제풀이]

처음에 A의 배열을 순서대로 하나를 선택해 B 전체와 비교하였는데 시간초과 오류가 발생하였다.

그래서 다음에 이용한 풀이는 배열 B를 정렬하고 B를 정렬하면 좌우에 비슷한 값을 갖으므로 이러한 특성을 이용하여 

이진탐색을 활용하였다.