Cod sursa(job #2800686)

Utilizator UnknownPercentageBuca Mihnea-Vicentiu UnknownPercentage Data 13 noiembrie 2021 18:05:31
Problema Ciclu hamiltonian de cost minim Scor 95
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <bits/stdc++.h>

using namespace std;

inline void Open(const string Name) {
    #ifndef ONLINE_JUDGE
        (void)!freopen((Name + ".in").c_str(), "r", stdin);
        (void)!freopen((Name + ".out").c_str(), "w", stdout);
    #endif
}

const int INF = 1e9;

vector <array <int, 2>> gr[19];

int dp[1 << 19][19];
int N, M, x, y, c;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    Open("hamilton");

    cin >> N >> M;

    for(int i = 1;i <= M;i++) {
        cin >> x >> y >> c;
        gr[x].push_back({y, c});
    }

    int limit = (1 << N);
    for(int i = 0;i < limit;i++)
        for(int j = 0;j < N;j++)
            dp[i][j] = INF;

    dp[1][0] = 0;
    for(int i = 0;i < limit;i++)
        for(int j = 0;j < N;j++) {
            if((i & (1 << j)) == 0)
                continue;

            for(const array <int, 2> &it : gr[j]) {
                if((i & (1 << it[0])) == 0)
                    continue;

                dp[i][it[0]] = min(dp[i][it[0]], dp[i ^ (1 << it[0])][j] + it[1]);
            }
        }

    int ans = INF;
    for(int i = 1;i < N;i++)
        for(const array <int, 2> &it : gr[i]) {
            if(it[0] == 0) 
                ans = min(ans, dp[limit - 1][i] + it[1]);
        }

    if(ans == INF) cout << "Nu exista solutie";
    else cout << ans;

    return 0;
}