알고리즘

백준 7795번 먹을 것인가 먹힐 것인가 (JAVA)

박카스마시며코딩 2023. 12. 12. 21:52

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.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Test {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int testCnt = Integer.parseInt(br.readLine());
        for(int t = 0 ; t < testCnt ; t++){
            StringTokenizer st = new StringTokenizer(br.readLine());
            int aSize = Integer.parseInt(st.nextToken());
            int bSize = Integer.parseInt(st.nextToken());
            int[] a = new int[aSize];
            int[] b = new int[bSize];
            st = new StringTokenizer(br.readLine());
            for(int i = 0 ; i < aSize ; i++){
                a[i] = Integer.parseInt(st.nextToken());
            }
            st = new StringTokenizer(br.readLine());
            for(int i = 0 ; i < bSize ; i++){
                b[i] = Integer.parseInt(st.nextToken());
            }
            int result = cal(a,b,aSize,bSize);
            System.out.println(result);
        }
    }

    private static int cal(int[] a, int[] b, int aSize, int bSize) {
        Arrays.sort(a);
        Arrays.sort(b);
        int result = 0;
        for(int i = 0 ; i < aSize ; i++){
            int index = Arrays.binarySearch(b,a[i]);
            if(index < 0){
                index = Math.abs(index) - 1;
            }else{
                for(int j = index -1; j >= 0 ; j--){
                    if(b[index] == b[j]){
                        index = j;
                    }else{
                        break;
                    }
                }
            }
            result += index;
        }
        return result;
    }

}

'알고리즘' 카테고리의 다른 글

백준 11048번 이동하기 (JAVA)  (0) 2023.12.14
백준 2579번 계단 오르기 (JAVA)  (0) 2023.12.13
백준 1654번 랜선 자르기 (JAVA)  (1) 2023.12.11
백준 1914번 하노이 탑 (JAVA)  (1) 2023.12.10
백준 1253번 좋다 (JAVA)  (0) 2023.12.09