
6236번: 용돈 관리
현우는 용돈을 효율적으로 활용하기 위해 계획을 짜기로 하였다. 현우는 앞으로 N일 동안 자신이 사용할 금액을 계산하였고, 돈을 펑펑 쓰지 않기 위해 정확히 M번만 통장에서 돈을 빼서 쓰기로
www.acmicpc.net
이분탐색으로 문제를 풀었다.
이분탐색의 먼저 범위(left ~ right)를 정해야 한다.
left : 현우가 N번 동안 필요한 금액 중 최대값이 이분탐색 범위의 시작값이 되어야 한다.
예를 들어 현우가 n번째에 500원이 필요한데, 한 번에 인출할 수 있는 금액이 500원보다 작은 400원
이라면 현우는 n번째에 돈을 쓸 수가 없다.
right : 현우가 N번 동안 필요한 금액의 총 합이 이분탐색 범위의 끝값이 된다.
이분탐색을 진행하면서 현우가 통장에서 인출해야할 최소 금액 K를 찾는다.
소스코드 :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
public class n06236 { | |
static int N, M; | |
static int[] arr; | |
public static void main(String[] args) throws Exception { | |
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); | |
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); | |
String[] sarr = br.readLine().split(" "); | |
N = Integer.parseInt(sarr[0]); | |
M = Integer.parseInt(sarr[1]); | |
arr = new int[N]; | |
int max = 0; | |
int sum = 0; | |
for (int i = 0; i < N; i++) { | |
arr[i] = Integer.parseInt(br.readLine()); | |
max = Math.max(max, arr[i]); | |
sum += arr[i]; | |
} | |
bw.write(binSearch(max, sum) + "\n"); | |
bw.flush(); | |
} | |
public static int binSearch(int left, int right) { | |
int pl = left; | |
int pr = right; | |
do { | |
int pc = (pl + pr) / 2; | |
int cnt = 1; | |
int money = pc; | |
for (int i = 0; i < N; i++) { | |
if (arr[i] > money) { | |
money = pc; | |
cnt++; | |
} | |
money = money - arr[i]; | |
} | |
if (cnt > M) | |
pl = pc + 1; | |
else | |
pr = pc - 1; | |
} while (pl <= pr); | |
return pl; | |
} | |
} |
'BOJ' 카테고리의 다른 글
[백준 4358번] 생태학 (java) (0) | 2021.03.02 |
---|---|
[백준 2343번] 기타 레슨 (java) (0) | 2021.03.01 |
[백준 5052번] 전화번호 목록 (java) (0) | 2021.02.27 |
[백준 2056번] 작업 (java) (0) | 2021.02.26 |
[백준 2670번] 연속부분최대곱 (java) (0) | 2021.02.25 |