Algorithm, Data structure/Solved Algorithmic Problem

BAEKJOON 2512 - 예산

JaykayChoi 2016. 12. 30. 00:45

문제: https://www.acmicpc.net/problem/2512



계산된 예산의 합이 상한 예산과 같을 경우 해당 값이 답이 되고 그렇지 않는 범위 내에서 최대값을 구해야되므로 이진탐색으로 쉽게 풀 수 있는 문제입니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#pragma warning (disable:4996)
#include <stdio.h>
#include <cstring>
#include <climits>
#include <algorithm>
 
using namespace std;
typedef long long ll;
 
ll getSumBudget(const int* numbers, int maxBudget, int n)
{
    ll ret = 0;
    for (int i = 0; i < n; i++)
        ret += min(numbers[i], maxBudget);
    return ret;
}
 
int binarySearch(const int* numbers, int low, int high, ll totalBudget, int n)
{
    while (low <= high)
    {
        int mid = (low + high) / 2;
        ll sumBudget = getSumBudget(numbers, mid, n);
        if (sumBudget == totalBudget)
            return mid;
        else if (sumBudget > totalBudget)
            high = mid - 1;
        else if (totalBudget > sumBudget)
            low = mid + 1;
    }
 
    return high;
}
 
int main()
{
    int n, lowest, hightest, totalBudget;
    lowest = 0;
    hightest = INT_MIN;
    scanf("%d"&n);
    int* budgets = new int[n];
    for (int i = 0; i < n; i++)
    {
        scanf("%d"&budgets[i]);
        hightest = max(hightest, budgets[i]);
    }
    scanf("%d"&totalBudget);
 
    printf("%d\n", binarySearch(budgets, lowest, hightest, totalBudget, n));
    delete[] budgets;
    return 0;
}
cs


'Algorithm, Data structure > Solved Algorithmic Problem' 카테고리의 다른 글

BAEKJOON 10816 - 숫자 카드 2  (0) 2016.12.30
BAEKJOON 1654 - 랜선 자르기  (0) 2016.12.30
BAEKJOON 2805 - EKO  (0) 2016.12.28
BAEKJOON 2869 - PUŽ  (0) 2016.12.26
BAEKJOON 10815 - 숫자 카드  (0) 2016.12.26