반응형

문제 출처 :


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



알고리즘 분석 :


문제 해결에 필요한 사항

1. Dynamic Programming

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
#include <iostream>
#include <memory.h>
 
#define MIN(a, b)(a < b ? a : b)
#define INF 987654321
 
typedef long long ll;
 
int cost[20][20];
ll dp[20][<< 16];
int n;
 
ll TSP(int here, int visit) {
    ll &ret = dp[here][visit];
    if (ret != -1)
        return ret;
 
    if (visit == (<< n) - 1) {
        if (cost[here][0== 0)
            return ret = INF;
        return ret = cost[here][0];
    }
 
    ret = INF;
    for (int i = 0; i < n; i++) {
        if (visit & (<< i) || !cost[here][i])
            continue;
 
        ret = MIN(ret, TSP(i, visit | (<< i)) + cost[here][i]);
    }
 
    return ret;
}
int main() {
    scanf("%d"&n);
 
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            scanf("%d"&cost[i][j]);
 
    memset(dp, -1sizeof(dp));
 
    printf("%lld", TSP(0<< 0));
    
    return 0;
}
cs

반응형

'Applied > 알고리즘 문제풀이' 카테고리의 다른 글

[16991번] 외판원 순회 3  (0) 2019.03.10
[10971번] 외판원 순회 2  (0) 2019.03.10
[268-C번] Beautiful Sets of Points  (0) 2019.03.09
[4248번] 유사 증가 수열  (0) 2019.03.08
[16646번] 콘서트  (0) 2019.03.07