코딩테스트/동적계획법
[DP(Top-Down)] 백준 2098 외판원 순회(TSP) C++
유(YOO)
2022. 1. 27. 11:20
https://www.acmicpc.net/problem/2098
재귀 DP
#include <iostream>
#include <vector>
#include <cstring>
#define MAXN 100000
#define INF 1000000000
using namespace std;
int n, s, w[16][16], dp[16][MAXN];
int tsp(int u, int v) {
if (v == (1 << n) - 1) {
if (w[u][s] == 0) w[u][s] = INF;
return w[u][s];
}
int& ret = dp[u][v];
if (ret != -1) return ret;
ret = INF;
for (int i = 0; i < n; i++) {
if (v & (1 << i)) continue;
if (w[u][i] == 0) continue;
ret = min(ret, tsp(i, v | (1 << i)) + w[u][i]);
}
return ret;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(NULL); cout.tie(NULL);
memset(dp, -1, sizeof(dp));
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> w[i][j];
}
}
cout << tsp(0, 1);
}