rcpl

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub ruthen71/rcpl

:heavy_check_mark: Traveling Salesman Problem (巡回セールスマン問題)
(dp/traveling_salesman_problem.hpp)

Depends on

Verified with

Code

#pragma once

#include "graph/graph_template.hpp"

template <class T>
std::vector<std::vector<T>>  //
traveling_salesman_problem(Graph<T> &G, const T INF) {
    const int N = (int)G.size();
    const int N2 = 1 << N;

    std::vector dist(N, std::vector<T>(N, INF));
    for (int i = 0; i < N; i++) dist[i][i] = T(0);
    for (int i = 0; i < N; i++) {
        for (auto &&e : G[i]) {
            dist[e.from][e.to] = std::min(dist[e.from][e.to], e.cost);
        }
    }
    std::vector dp(N2, std::vector<T>(N, INF));
    dp[0][0] = 0;
    for (int bit = 0; bit < N2; bit++) {
        for (int u = 0; u < N; u++) {
            if (dp[bit][u] == INF) continue;
            for (int v = 0; v < N; v++) {
                if (bit >> v & 1) continue;
                if (dist[u][v] == INF) continue;
                dp[bit | (1 << v)][v] = std::min(dp[bit | (1 << v)][v], dp[bit][u] + dist[u][v]);
            }
        }
    }
    return dp;
}
#line 2 "dp/traveling_salesman_problem.hpp"

#line 2 "graph/graph_template.hpp"

#include <vector>
template <class T> struct Edge {
    int from, to;
    T cost;
    int id;

    Edge() = default;
    Edge(int from, int to, T cost = 1, int id = -1) : from(from), to(to), cost(cost), id(id) {}

    friend std::ostream &operator<<(std::ostream &os, const Edge<T> &e) {
        // output format: "{ id : from -> to, cost }"
        return os << "{ " << e.id << " : " << e.from << " -> " << e.to << ", " << e.cost << " }";
    }
};

template <class T> using Edges = std::vector<Edge<T>>;
template <class T> using Graph = std::vector<std::vector<Edge<T>>>;
#line 4 "dp/traveling_salesman_problem.hpp"

template <class T>
std::vector<std::vector<T>>  //
traveling_salesman_problem(Graph<T> &G, const T INF) {
    const int N = (int)G.size();
    const int N2 = 1 << N;

    std::vector dist(N, std::vector<T>(N, INF));
    for (int i = 0; i < N; i++) dist[i][i] = T(0);
    for (int i = 0; i < N; i++) {
        for (auto &&e : G[i]) {
            dist[e.from][e.to] = std::min(dist[e.from][e.to], e.cost);
        }
    }
    std::vector dp(N2, std::vector<T>(N, INF));
    dp[0][0] = 0;
    for (int bit = 0; bit < N2; bit++) {
        for (int u = 0; u < N; u++) {
            if (dp[bit][u] == INF) continue;
            for (int v = 0; v < N; v++) {
                if (bit >> v & 1) continue;
                if (dist[u][v] == INF) continue;
                dp[bit | (1 << v)][v] = std::min(dp[bit | (1 << v)][v], dp[bit][u] + dist[u][v]);
            }
        }
    }
    return dp;
}
Back to top page