https://www.acmicpc.net/problem/2512
2512번: 예산
첫째 줄에는 지방의 수를 의미하는 정수 N이 주어진다. N은 3 이상 10,000 이하이다. 다음 줄에는 각 지방의 예산요청을 표현하는 N개의 정수가 빈칸을 사이에 두고 주어진다. 이 값들은 모두 1 이상
www.acmicpc.net
저는 이분탐색으로 문제를 해결하였습니다.
각각의 가격에 대해 되는지 안되는지를 확인하게 된다면 n*m으로 시간초과가 나올 것입니다. 그래서 이분탐색으로 log(n)*m의 시간복잡도로 낮추어 문제를 해결하였습니다.
package BOJ.binarysearch;
import java.awt.print.Pageable;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class BOJ_2512 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] price = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
int max = 0;
for(int i = 0 ; i < n ; i++){
price[i] = Integer.parseInt(st.nextToken());
max = Math.max(price[i],max);
}
int m = Integer.parseInt(br.readLine());
int result = cal(price,max,m);
System.out.println(result);
}
private static int cal(int[] price,int max ,int m) {
int start = 1;
int end = max;
int result = 0;
while(start <= end) {
int mid = (start+end)/2;
if(checkPrice(price,mid,m)){
result = mid;
start = mid + 1;
}else{
end = mid - 1;
}
}
return result;
}
private static boolean checkPrice(int[] price, int mid,int m) {
int sum = 0;
for(int num : price){
sum += Math.min(num,mid);
}
if(sum <= m){
return true;
}else{
return false;
}
}
}
'알고리즘' 카테고리의 다른 글
백준 14503번 로봇 청소기 (JAVA) (0) | 2023.11.24 |
---|---|
백준 3190번 뱀 (JAVA) (0) | 2023.11.23 |
백준 2003번 수들의 합2 (JAVA) (1) | 2023.11.21 |
백준 11659번 구간 합 구하기 4 (JAVA) (1) | 2023.11.20 |
백준 1197번 최소 스패닝 트리 (JAVA) (2) | 2023.11.19 |