※ 글쓴이는 취미로 코딩을 익혀보는 사람이라 정확하지 않은 내용을 담고 있을 수 있다 ※
이번에 볼 문제는 백준 24512번 문제인 Bottleneck Travelling Salesman Problem (Small)이다.
문제는 아래 링크를 확인하자.
https://www.acmicpc.net/problem/24512
24512번: Bottleneck Travelling Salesman Problem (Small)
외판원 순회 문제는 영어로 Traveling Salesman Problem (TSP) 라고 불리는 문제로 computer science 분야에서 가장 중요하게 취급되는 문제 중 하나이다. 이 중 변종 문제 중 하나인 Bottleneck Traveling Salesman Probl
www.acmicpc.net
24519번 문제에서 입력제한이 작아진 문제이다. 해당 문제의 풀이글을 참고하자.
입력제한이 작으므로 직접 O(N!)의 모든 가능한 순회경로를 탐색하는 브루트포스 풀이 또한 통과할 수 있다.
아래는 제출한 소스코드이다.
#define MP(x,y) make_pair(x,y)
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int N, M;
int dp[512][9];
int old[512][9];
bool visited[512];
vector<pair<int, int>> G[10];
void bfs() {
dp[1][0] = 1;
queue<int> que;
que.push(1);
while (!que.empty()) {
int cur = que.front(); que.pop();
for (int s = 0; s < N; s++) {
if (dp[cur][s] == 0) continue;
for (auto& p : G[s]) {
int e = p.first, c = p.second;
if (cur & (1 << e)) continue;
int nxt = cur | (1 << e);
int val = max(dp[cur][s], c);
if (dp[nxt][e]) {
if (val < dp[nxt][e]) {
dp[nxt][e] = val;
old[nxt][e] = s;
}
}
else {
dp[nxt][e] = val;
old[nxt][e] = s;
}
if (!visited[nxt]) {
visited[nxt] = 1;
que.push(nxt);
}
}
}
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> N >> M;
while (M--) {
int x, y, c; cin >> x >> y >> c;
x--, y--;
G[x].emplace_back(MP(y, c));
if (y == 0) {
G[N].emplace_back(MP(x, c));
}
}
bfs();
int ans = 1000000007;
int ansnode = -1;
int MX = (1 << N) - 1;
for (auto p : G[N]) {
int node = p.first, c = p.second;
if (dp[MX][node]) {
int val = max(dp[MX][node], c);
if (val < ans) {
ans = val;
ansnode = node;
}
}
}
if (ans == 1000000007) cout << -1;
else {
cout << ans << '\n';
vector<int> stk;
while (ansnode) {
stk.emplace_back(ansnode);
int tmp = old[MX][ansnode];
MX ^= (1 << ansnode);
ansnode = tmp;
}
cout << 1 << ' ';
while (!stk.empty()) {
cout << stk.back() + 1 << ' ';
stk.pop_back();
}
}
}
728x90
'BOJ' 카테고리의 다른 글
[BOJ 12351 // C++] Hedgemony (Small) (0) | 2022.07.17 |
---|---|
[BOJ 1833 // C++] 고속철도 설계하기 (0) | 2022.07.17 |
[BOJ 4358 // C++] 생태학 (0) | 2022.07.17 |
[BOJ 2098 // C++] 외판원 순회 (0) | 2022.07.17 |
[BOJ 10971 // C++] 외판원 순회 2 (0) | 2022.07.17 |