본문 바로가기
학부공부/Algorithm PS_알고리즘

06.04. Monthly Expense [Binary Search & Parametric Search][백준 6236]

by sonpang 2022. 1. 19.
반응형

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

 

6236번: 용돈 관리

현우는 용돈을 효율적으로 활용하기 위해 계획을 짜기로 하였다. 현우는 앞으로 N일 동안 자신이 사용할 금액을 계산하였고, 돈을 펑펑 쓰지 않기 위해 정확히 M번만 통장에서 돈을 빼서 쓰기로

www.acmicpc.net

 

Algorithm classification : Binary Search, Parametric Search

 

06.04.1. Problem

Farmer John is an astounding accounting wizard and has realized he might run out of money to run the farm. He has already calculated and recorded the exact amount of money (1 ≤ moneyi ≤ 10,000) that he will need to spend each day over the next N (1 ≤ N ≤ 100,000) days.

 

FJ wants to create a budget for a sequential set of exactly M (1 ≤ M ≤ N) fiscal periods called "fajomonths". Each of these fajomonths contains a set of 1 or more consecutive days. Every day is contained in exactly one fajomonth.

 

FJ's goal is to arrange the fajomonths so as to minimize the expenses of the fajomonth with the highest spending and thus determine his monthly spending limit.

 

06.04.2. Input limit

  • Line 1: Two space-separated integers: N and M 
  • Lines 2..N+1: Line i+1 contains the number of dollars Farmer John spends on the ith day

 

06.04.3. Output

  • Line 1: The smallest possible monthly limit Farmer John can afford to live with.

 

06.04.4. Solution

최소금액이 구하는 목표이니 이를 MID 값으로 추적해주면 됩니다. 

	int n, m;
	scanf("%d %d", &n, &m);
	int a[n], i, left = 0;
	
	
	for(i = 0; i < n; i++){
		scanf("%d", &a[i]);
		left = max(left, a[i]);
	}
	
	int right = 1000000000, mid, temp, sum, result;
	while(left <= right){
		mid = (left + right) / 2;
		temp = 1;
		sum = 0;
		for(i = 0; i < n ; i++){
			if(sum + a[i] <= mid){
				sum += a[i];
			}
			else{
				sum = a[i];
				temp++;
			}
		}
		//printf("%d %d %d > %d\n",left, right, mid, temp);
		if(temp <= m){
			result = mid;
			right = mid - 1;
		}
		else{
			left = mid + 1;
		}
	}
	
	printf("%d", result);

 

아래에 몇 개의 test case를 남겨두었습니다.

5 4
100
100
100
100
100
>> 200

5 1
1
3
5
7
9
>> 25

5 5
1
1
1
1
100
>> 100

반응형

댓글