Algorithm, Data structure/Solved Algorithmic Problem

BAEKJOON 1029 - 그림 교환

JaykayChoi 2016. 10. 8. 08:41

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


memoization과 bit mask 를 이용한 dynamic programming 방법과 재귀함수를 이용한 DFS 을 이용해 풀어봤습니다.




my solving

c++

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
#include <fstream>
#include <iostream>
#include <cstring>
#include <climits>
#include <algorithm>
 
#include <string>
using namespace std;
 
const int MAX_N = 15;
int n;
int prices[MAX_N + 1][MAX_N + 1];
int cache[<< MAX_N][10][MAX_N + 1];
 
int getMaxBuyingPeople(int bought, int price, int seller)
{
    if (bought == ((<< n) - 1))
        return 0;
    bool buyable = false;
    for (int buyerCandidate = 0; buyerCandidate < n; buyerCandidate++)
    {
        if (bought & (<< buyerCandidate))
            continue;
 
        for (int sellerCandidate = 0; sellerCandidate < n; sellerCandidate++)
        {
            if (bought & (<< buyerCandidate))
                continue;
            if (prices[sellerCandidate][buyerCandidate] >= price)
            {
                buyable = true;
                break;
            }
        }
        if (buyable)
            break;
    }
    if (buyable == false)
        return 0;
 
    int& ret = cache[bought][price][seller];
    if (ret != -1)
        return ret;
    ret = 0;
 
    for (int buyer = 0; buyer < n; buyer++)
    {
        if (bought & (<< buyer))
            continue;
        if (prices[seller][buyer] >= price)
            ret = max(ret, getMaxBuyingPeople(bought + (<< buyer), prices[seller][buyer], buyer) + 1);
    }
    return ret;
}
 
int main()
{
    memset(cache, -1sizeof(cache));
    cin >> n;
 
    for (int i = 0; i < n; i++)
    {
        string str;
        cin >> str;
        for (int j = 0; j < n; j++)
            prices[i][j] = str[j] - '0';
    }
    cout << getMaxBuyingPeople(100+ << endl;
 
    return 0;
}
cs