Skip to content
Snippets Groups Projects
Commit 0d9472ef authored by Bruno Freitas Tissei's avatar Bruno Freitas Tissei
Browse files

Add tsp

parent 8ed430a2
No related branches found
No related tags found
No related merge requests found
......@@ -13,7 +13,8 @@ struct ArticulationsBridges {
vector<int> arti;
ArticulationsBridges(int N) :
N(N), vis(N), par(N), L(N), low(N) {}
N(N), vis(N), par(N), L(N), low(N)
{ init(); }
void init() {
fill(all(L), 0);
......
......@@ -10,7 +10,8 @@ struct BipartiteMatching {
vector<int> vis, match;
BipartiteMatching(int N) :
N(N), vis(N), match(N) {}
N(N), vis(N), match(N)
{ init(); }
void init() {
fill(all(vis), 0);
......
......@@ -2,17 +2,17 @@
///
/// Time: O(V^3)
/// Space: O(V^2)
///
/// Caution:
/// - If the edge $\{v,u\}$ doesn't exist, then graph[v][u] must be inf.
int dist[MAX][MAX];
int graph[MAX][MAX];
void floyd_warshall(int n) {
mset(dist, inf);
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
dist[i][j] = graph[i][j];
if (graph[i][j])
dist[i][j] = graph[i][j];
for (int k = 0; k < n; ++k)
for (int i = 0; i < n; ++i)
......
/// Travelling Salesman
///
/// Description:
/// Given a graph and an origin vertex, this algorithm return the shortest
/// possible route that visits each vertex and returns to the origin. \par
/// The algorithm works by using dynamic programming, where dp[i][mask]
/// stores the last visited vertex $i$ and a set of visited vertices
/// represented by a bitmask mask. Given a state, the next vertex in the path
/// is chosen by a recursive call, until the bitmask is full, in which case the
/// weight of the edge between the last vertex and the origin in returned.
///
/// Time: O(2^n * n^2)
/// Space: O(2^n * n)
///
/// Status: Tested (Uva10496)
int dp[MAX][1 << MAX];
int graph[MAX][MAX];
struct TSP {
int N;
TSP(int N) : N(N)
{ init(); }
void init() { mset(dp, -1); }
int solve(int i, int mask) {
if (mask == (1 << N) - 1)
return graph[i][0];
if (dp[i][mask] != -1)
return dp[i][mask];
int ans = inf;
for (int j = 0; j < N; ++j)
if (!(mask & (1 << j)) && (i != j))
ans = min(ans, graph[i][j] +
solve(j, mask | (1 << j)));
return dp[i][mask] = ans;
}
int run(int start) {
return run(start, 1 << start);
}
};
No preview for this file type
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment