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
|
#include<iostream>
#include<stdio.h>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<functional>
#include<cstdbool>
#include<stack>
#include<queue>
#include<vector>
using namespace std;
#define ll long long
#define pii pair<int,int>
#define pll pair<ll,ll>
#define INF 987654321
#define LINF 321321321321
#define MAX 16
int n;
int W[MAX][MAX];
int cache[1<<MAX];
int P;
int dp(int visited,int cnt) {
if (cnt >= P)
return 0;
int &ret = cache[visited];
if (ret != -1)
return ret;
ret = INF;
for (int here = 0; here < n; here++) {
if (visited == (visited | (1 << here))) {
for (int next = 0; next < n; next++) {
if (visited != (visited | (1 << next))) {
ret = min(ret, dp((visited | (1 << next)), cnt + 1)+W[here][next]);
}
}
}
}
return ret;
}
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> W[i][j];
memset(cache, -1, sizeof(cache));
int visited = 0;
string s;
cin >> s;
cin >> P;
int cnt = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] == 'Y') {
visited = (visited | (1 << i));
cnt++;
}
}
int ans=dp(visited, cnt);
if (ans >= INF)
cout << -1;
else
cout << ans;
return 0;
}
|
cs |
출처:https://www.acmicpc.net/problem/1102
외판원 순회 tsp알고리즘을 살짝 변형한 문제였습니다.
'알고리즘 > BAEKJOON' 카테고리의 다른 글
[c++] 백준 7579번 앱 (dp,배낭) (1) | 2022.10.13 |
---|---|
[c++] 백준 2618번 경찰차 (dp) (0) | 2022.10.12 |
[c++] 구간 합 구하기5 (1) | 2022.10.11 |
[c++] 1043번 거짓말 (유니온 파인드) (0) | 2022.09.27 |
[c++] 백준 1976번 여행 가자 (유니온-파인드) (0) | 2022.09.27 |