ugipro_lib_cpp

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

View the Project on GitHub CURRY-AND-RICE/ugipro_lib_cpp

:heavy_check_mark: tests/graph/tsp.test.cpp

Depends on

Code

#include <bits/stdc++.h>
#include "ugilib/base/constants.hpp"
#include "ugilib/base/definitions.hpp"
#include "ugilib/graph/tsp.hpp"

#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DPL_2_A"

using namespace std;

// debug settings
// #define DEBUG
#ifdef DEBUG
// debug input
string _INPUT = R"(
5
1 2 3 4 5
)";
auto _cin = stringstream(_INPUT.substr(1)); // remove '\n' at _INPUT[0]
#else
// standard input
auto& _cin = cin;
#endif

// speed up
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")

// reader
struct rd {
    // T
    template<typename T> static T i() { T x; _cin >> x; return x; }  // T item
    // vector<T>
    template<typename T> static vector<T> v(int n) {vector<T> v(n); rep(i, n) _cin >> v[i]; return v;}  // vector<T>
    // vector<pair<T, T>>
    template<typename T> static vector<pair<T, T>> vp(int n) {vector<pair<T, T>> v(n); rep(i, n) _cin >> v[i].first >> v[i].second; return v;}  // vector<pair<T, T>>
    // tuple
    template<typename... Args> static tuple<Args...> t() {
        tuple<Args...> values;
        apply([](auto&... args) { ((_cin >> args), ...); }, values);
        return values;
    }
};

// debug print utility
namespace deb {
    #include <cxxabi.h>
    // demangle type name
    string demangle(const char* name) {
        int status = -4;
        unique_ptr<char, void(*)(void*)> res{
            abi::__cxa_demangle(name, NULL, NULL, &status),
            free
        };
        return (status == 0) ? string(res.get()) : name ;
    }
    // meta functions for type traits
    template<typename T>
    constexpr bool isArithmeticContainer() { return is_arithmetic<typename T::value_type>::value; }
    // for SFINAE
    template<typename T, typename = void> struct has_key_and_mapped_type : false_type {};
    template<typename T> struct has_key_and_mapped_type<T, void_t<typename T::key_type, typename T::mapped_type>> : true_type {};
    // for map or unordered_map
    template<typename T>
    constexpr bool isMapLike() { return has_key_and_mapped_type<T>::value; }

    // for values
    template<typename T, typename enable_if<is_arithmetic<T>::value, nullptr_t>::type = nullptr>
    void p(const T& x) { cout << x << " "; }
    // for pairs
    template <typename T, typename S>
    void p(const pair<T, S>& _p){ p(_p.first); p(_p.second); cout << endl; }
    // for containers
    template<typename T,  typename enable_if<!is_arithmetic<T>::value, nullptr_t>::type = nullptr>
    void p(const T& container) {
        // map and unordered_map
        if constexpr (isMapLike<T>()) {
            cout << demangle(typeid(T).name()) << ":" << endl;
            for (const auto& kv : container) {
                cout << "[" << kv.first << "] => ";
                p(kv.second);
                if constexpr (is_arithmetic_v<typename T::mapped_type>) cout << endl;
            }
        // vector or set or others
        } else {
            if constexpr (!isArithmeticContainer<T>()) cout << demangle(typeid(T).name()) << ":" << endl;
            for (auto it = begin(container); it != end(container); ++it) {
                p(*it);
            }
            if constexpr (isArithmeticContainer<T>()) cout << endl;
        }
    }
};  // namespace deb

int main() {
    auto& cin = _cin;
    // speed up io
    cin.tie(nullptr);
    ios::sync_with_stdio(false);

    // code
    auto [V, E] = rd::t<int, int>();
    vector<vector<pair<int, int>>> graph(V);
    rep(i, E) {
        auto [s, t, d] = rd::t<int, int, int>();
        graph[s].emplace_back(t, d);
    }

    int ans = ugilib::tsp_bitDP(V, 0, graph, ugilib::constants::INF<int>);
    // どこを始点にしても結果は同じ
    for (int i = 1; i < V; i++) {
        int another_ans = ugilib::tsp_bitDP(V, i, graph);
        assert(ans == another_ans);
    }

    if (ans == ugilib::constants::INF<int>) cout << -1 << endl;
    else cout << ans << endl;

    return 0;
}
#line 1 "tests/graph/tsp.test.cpp"
#include <bits/stdc++.h>
#line 2 "ugilib/base/definitions.hpp"

using ll = long long;
using ull = unsigned long long;
using ld = long double;
#define rep(i, n) for(size_t i = 0; i < n; i++)  // rep macro
#define all(v) begin(v), end(v)  // all iterator
#line 3 "ugilib/base/constants.hpp"

namespace ugilib::constants {
    template<typename T>
    inline constexpr T INF = std::numeric_limits<T>::max() / 2;
} // namespace ugilib::constants

const ll INF = ugilib::constants::INF<ll>;
#line 4 "ugilib/bit/bit_util.hpp"

using namespace std;

namespace ugilib {
    /**
     * @brief 数値 -> ビット配列
     * @param num ビット配列にするための数値
     * @param digit ビット数
     * @return vector<bool> 変換されたビット配列. 0番目が一番下の桁
     * @details 数値を指定桁のビット配列に変換する
    */
    vector<bool> num_to_bits(const ll num, const size_t &digit) {
        vector<bool> bits(digit);
        for (int i = 0; i < digit; i++) {
            bits[i] = (num >> i) & 1U;
        }
        return bits;
    }

    /**
     * @brief ビット配列 -> 数値
     * @param bits 数値にするためのビット配列. 0番目が一番下の桁
     * @return ll 変換された数値
     * @details ビット配列を数値に戻す. num_to_bitsの逆変換
    */
    ll bits_to_num(const vector<bool> &bits) {
        ll num = 0;
        for (int i = 0; i < bits.size(); i++) {
            num += bits[i] << i;
        }
        return num;
    }
}  // namespace ugilib
#line 5 "ugilib/graph/tsp.hpp"

using namespace std;

namespace ugilib {
    /**
     * @brief 巡回セールスマン問題を解くDP
     * @param n 都市数
     * @param start 始点
     * @param graph グラフ. vector<pair<int, weight_t>> で隣接頂点とコストを表す
     * @param weight_inf 無限大の値. パスが存在しない場合のコスト
     * @return 始点から各頂点を一度だけ通って戻ってくる最小コスト
     * @note O(2^n * n^2)
    */
    template <typename weight_t>
    weight_t tsp_bitDP(int n, int start, const vector<vector<pair<int, weight_t>>> &graph, const weight_t weight_inf = ugilib::constants::INF<weight_t>) {
        const int num_states = (1 << n);
        // dp[これまでに取った都市集合. [0, 2^n-1]][現在地. [0, n-1]]
        vector<vector<weight_t>> dp(num_states, vector<weight_t>(n, weight_inf));
        dp[0][start] = 0;

        // 全状態についてDPする
        for (int i = 0; i < num_states; i++) {
            // 状態をビット表現する
            auto bits = ugilib::num_to_bits(i, n);
            // 今どの都市にいるか
            for (int j = 0; j < n; j++) {
                if (dp[i][j] == weight_inf) continue;  // この状態に辿り着かない場合
                // 次どの都市に行くか
                for (const auto [node, cost] : graph[j]) {
                    if (bits[node]) continue;  // 訪問済み
                    // 訪問する
                    bits[node] = true;
                    auto &dest = dp[ugilib::bits_to_num(bits)][node];
                    dest = min(dest, dp[i][j] + cost);
                    bits[node] = false;
                }
            }
        }

        return dp[num_states-1][start];  // 全状態訪問後にstartに戻って来る最小コスト
    }
    }  // namespace ugilib
#line 5 "tests/graph/tsp.test.cpp"

#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DPL_2_A"

using namespace std;

// debug settings
// #define DEBUG
#ifdef DEBUG
// debug input
string _INPUT = R"(
5
1 2 3 4 5
)";
auto _cin = stringstream(_INPUT.substr(1)); // remove '\n' at _INPUT[0]
#else
// standard input
auto& _cin = cin;
#endif

// speed up
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")

// reader
struct rd {
    // T
    template<typename T> static T i() { T x; _cin >> x; return x; }  // T item
    // vector<T>
    template<typename T> static vector<T> v(int n) {vector<T> v(n); rep(i, n) _cin >> v[i]; return v;}  // vector<T>
    // vector<pair<T, T>>
    template<typename T> static vector<pair<T, T>> vp(int n) {vector<pair<T, T>> v(n); rep(i, n) _cin >> v[i].first >> v[i].second; return v;}  // vector<pair<T, T>>
    // tuple
    template<typename... Args> static tuple<Args...> t() {
        tuple<Args...> values;
        apply([](auto&... args) { ((_cin >> args), ...); }, values);
        return values;
    }
};

// debug print utility
namespace deb {
    #include <cxxabi.h>
    // demangle type name
    string demangle(const char* name) {
        int status = -4;
        unique_ptr<char, void(*)(void*)> res{
            abi::__cxa_demangle(name, NULL, NULL, &status),
            free
        };
        return (status == 0) ? string(res.get()) : name ;
    }
    // meta functions for type traits
    template<typename T>
    constexpr bool isArithmeticContainer() { return is_arithmetic<typename T::value_type>::value; }
    // for SFINAE
    template<typename T, typename = void> struct has_key_and_mapped_type : false_type {};
    template<typename T> struct has_key_and_mapped_type<T, void_t<typename T::key_type, typename T::mapped_type>> : true_type {};
    // for map or unordered_map
    template<typename T>
    constexpr bool isMapLike() { return has_key_and_mapped_type<T>::value; }

    // for values
    template<typename T, typename enable_if<is_arithmetic<T>::value, nullptr_t>::type = nullptr>
    void p(const T& x) { cout << x << " "; }
    // for pairs
    template <typename T, typename S>
    void p(const pair<T, S>& _p){ p(_p.first); p(_p.second); cout << endl; }
    // for containers
    template<typename T,  typename enable_if<!is_arithmetic<T>::value, nullptr_t>::type = nullptr>
    void p(const T& container) {
        // map and unordered_map
        if constexpr (isMapLike<T>()) {
            cout << demangle(typeid(T).name()) << ":" << endl;
            for (const auto& kv : container) {
                cout << "[" << kv.first << "] => ";
                p(kv.second);
                if constexpr (is_arithmetic_v<typename T::mapped_type>) cout << endl;
            }
        // vector or set or others
        } else {
            if constexpr (!isArithmeticContainer<T>()) cout << demangle(typeid(T).name()) << ":" << endl;
            for (auto it = begin(container); it != end(container); ++it) {
                p(*it);
            }
            if constexpr (isArithmeticContainer<T>()) cout << endl;
        }
    }
};  // namespace deb

int main() {
    auto& cin = _cin;
    // speed up io
    cin.tie(nullptr);
    ios::sync_with_stdio(false);

    // code
    auto [V, E] = rd::t<int, int>();
    vector<vector<pair<int, int>>> graph(V);
    rep(i, E) {
        auto [s, t, d] = rd::t<int, int, int>();
        graph[s].emplace_back(t, d);
    }

    int ans = ugilib::tsp_bitDP(V, 0, graph, ugilib::constants::INF<int>);
    // どこを始点にしても結果は同じ
    for (int i = 1; i < V; i++) {
        int another_ans = ugilib::tsp_bitDP(V, i, graph);
        assert(ans == another_ans);
    }

    if (ans == ugilib::constants::INF<int>) cout << -1 << endl;
    else cout << ans << endl;

    return 0;
}
Back to top page