https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AWIeUtVakTMDFAVH&categoryId=AWIeUtVakTMDFAVH&categoryType=CODE&problemTitle=4012&orderBy=FIRST_REG_DATETIME&selectCodeLang=ALL&select-1=&pageSize=10&pageIndex=1 

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

<풀이>

1. A음식과 B음식을 만들 식재료를 분배한다.

2. 각 음식의 시너지 합을 구하고 그 차이가 최소가 되는 값을 출력한다.

 

<해법>

1. 식재료를 분배하는 방법

=> 식재료 중 절반을 선택해서 A음식에 사용하고, 선택하지 않은 나머지 절반을 B음식에 사용하도록 합니다. 간단히 생각하면, N개 중에서 N/2개를 고르는 조합 문제입니다. 저는 재귀를 이용해서 구현하였습니다.

 

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <iostream>
#include <vector>
#include <string.h>
#include <algorithm>
#define INF 9876543321
 
using namespace std;
 
int N;
int S[16][16];
vector<int> a;
vector<int> b;
bool selected[16];
int answer;
 
int calculateTasteDiff() {
 
    int aTaste = 0, bTaste = 0;
 
    for (int i = 0; i < N / 2; i++) {
        for (int j = 0; j < N / 2; j++) {
            aTaste += S[a[i]][a[j]];
            bTaste += S[b[i]][b[j]];
        }
    }
 
    return abs(aTaste - bTaste);
}
 
void setiing() {
    a.clear(), b.clear();
    for (int i = 0; i < N; i++) {
        if (selected[i]) {
            a.push_back(i);
        }
        else {
            b.push_back(i);
        }
    }
}
 
void divideIngredient(int start, int cnt) {
 
    if (cnt == N / 2) {
        setiing();
        int tasteDiff = calculateTasteDiff();
        answer = min(answer, tasteDiff);
        return;
    }
 
    for (int i = start; i < N; i++) {
        selected[i] = true;
        divideIngredient(i + 1, cnt + 1);
        selected[i] = false;
    }
}
 
int main() {
    int test_case;
    int T;
 
    cin >> T;
 
    for (test_case = 1; test_case <= T; test_case++) {
 
        //초기화
        N = 0;
        memset(S, 0sizeof(S));
        a.clear();
        b.clear();
        memset(selected, falsesizeof(selected));
        answer = INF;
 
        //입력
        cin >> N;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                cin >> S[i][j];
            }
        }
 
        //해법
        divideIngredient(00);
 
        //출력
        cout << "#" << test_case << " " << answer << "\n";
    }
 
    //종료
    return 0;
}

 

재귀함수에 대해 알아볼 수 있는 문제였습니다.

+ Recent posts