ย - Last update: 2023-12-26

TSP

์ผ๋‹จ ํ‘œ์ œ๋งŒ ์ •๋ฆฌํ•ด๋‘๊ณ , ๋‚˜์ค‘์— ์‹ฌ๋„์žˆ๊ฒŒ ์ •๋ฆฌํ•ด๋ณผ ์˜ˆ์ •.

Bottom-up solution

int N;
ll w[16][16];
ll dp[1<<16][16];
// bit dp
// dp[4][110111]
// 0, 1, 3, 4, 5 ๋ฒˆ์งธ ๋„์‹œ๋ฅผ ๋“ค๋ €๊ณ , 4๋ฒˆ์งธ ๋„์‹œ๋ฅผ ๋งˆ์ง€๋ง‰์— ๋“ค๋ฅธ ์ƒํƒœ์ž„
void solve() {
scanf("%d", &N);
FOR(i,0,N) {
FOR(j,0,N) {
scanf("%lld", &w[i][j]);
}
}
memset(dp, 0x3F, sizeof(ll) * (1<<16) * 16);
int allstate = 1 << N;
for(int state = 1; state < allstate; ++state) {
for(int cur = 0; cur < N; ++cur) {
if ((1<<cur) & state) { // ์ด ๋•Œ๋งŒ ์œ ํšจํ•จ
if (__builtin_popcount(state) == 1) {
if (w[0][cur]) dp[state][cur] = w[0][cur]; // 0์—์„œ ์ถœ๋ฐœํ•œ ๊ฒƒ์œผ๋กœ ๊ณ ๋ฅธ๋‹ค.
continue;
}
// ์ด์ „ ๊ธฐ์ค€์œผ๋กœ ํ’€๊ธฐ
int pstate = state ^ (1<<cur);
for(int prev = 0; prev < N; ++prev) {
if (cur == prev) continue;
if (w[prev][cur] == 0) continue;
if ((1<<prev) & state) { // ์ด์ „์— ์žˆ์–ด์•ผ ํ•จ! cur์€ ์—†๋Š”๊ฑฐ๊ณ 
dp[state][cur] = min(dp[state][cur], dp[pstate][prev] + w[prev][cur]);
}
}
// next ๊ธฐ์ค€์œผ๋กœ ํ’€๊ธฐ
// for(int next = 0; next < N; ++next) {
// if (cur == next) continue;
// if (!((1<<next) & state)) continue; // state์— ์žˆ๋Š” ์ ๋งŒ ์ทจ๊ธ‰ํ•จ
// if (w[cur][next] == 0) continue; // ๊ธธ ์žˆ์–ด์•ผ ํ•จ
// dp[state][next] = min(dp[state][next], dp[state ^ (1<<next)][cur] + w[cur][next]);
// }
}
}
}
// for(int i = 0; i < N; ++i) {
// printf("%lld\n", dp[(1<<N) - 1][i]);
// }
printf("%lld\n", dp[(1<<N) - 1][0]); // 0: ํ•œ๋ฐ”ํ€ด ๋Œ๊ณ  ๋‹ค์‹œ 0์œผ๋กœ ์˜ค๋Š” ๊ฒฝ์šฐ๋ฅผ ๋ด์•ผ ํ•จ
}
๐Ÿท๏ธ ์ฃผ์ œ ๋ชฉ๋ก: