본문 바로가기

백준 문제풀이/Bitmask

[C++] 백준 문제풀이 (Bitmask) 2961번 도영이가 만든 맛있는 음식

 

 

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

 

2961번: 도영이가 만든 맛있는 음식

첫째 줄에 재료의 개수 N(1 ≤ N ≤ 10)이 주어진다. 다음 N개 줄에는 그 재료의 신맛과 쓴맛이 공백으로 구분되어 주어진다. 모든 재료를 사용해서 요리를 만들었을 때, 그 요리의 신맛과 쓴맛은

www.acmicpc.net

 

 

 

#include <bits/stdc++.h>

int s[10];
int b[10];
int n;
int ans = INT_MAX;


int main()
{
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);
    
    std::cin >> n;

    for (int i = 0; i < n; ++i){
        std::cin >> s[i] >> b[i];
    }

    // n 인 4인 경우
    // 0001 ~ 1111 까지의 값에 대해서 비트마스킹
    for (int i = 1; i < (1 << n); ++i){
        int sour = 1, bitter = 0;
        for (int j = 0; j < n; ++j){
            // j번째 재료를 사용함
            if(i & (1 << j)){
                sour *= s[j];
                bitter += b[j];
            }
        }
        ans = std::min(ans, std::abs(sour - bitter));
    }

    std::cout << ans << "\n";
    return 0;
}