-
Notifications
You must be signed in to change notification settings - Fork 0
/
tsp.cpp
53 lines (40 loc) · 1.1 KB
/
tsp.cpp
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
// BOJ 2098 외판원 순회
#include <bits/stdc++.h>
#define sz size()
#define bk back()
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
int f(int cur, int mask, int n, vector<vector<int>> &graph, vector<vector<int>> &dp) {
if (dp[cur][mask] != -1)
return dp[cur][mask];
if (mask == (1 << n) - 1) {
if (graph[cur][0])
return dp[cur][mask] = graph[cur][0];
return INT_MAX;
}
int ret = INT_MAX;
for (int i = 0; i < n; i++) {
if (!graph[cur][i] || mask & (1 << i))
continue;
int k = f(i, mask | (1 << i), n, graph, dp);
if (k != INT_MAX)
ret = min(ret, k + graph[cur][i]);
}
return dp[cur][mask] = ret;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
vector<vector<int>> graph(n, vector<int>(n));
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> graph[i][j];
vector<vector<int>> dp(n, vector<int>(1 << n, -1));
cout << f(0, 1, n, graph, dp);
}