Cod sursa(job #3194343)

Utilizator mex7Alexandru Valentin mex7 Data 17 ianuarie 2024 18:09:50
Problema Ciclu hamiltonian de cost minim Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>
#define cin fin
#define cout fout
using namespace std;

ifstream fin("hamilton.in");
ofstream fout("hamilton.out");

int n, m;
long long edgeCost[20][20];
long long dp[524289][20];
vector <int> adj[20];

int main() {
    cin >> n >> m;

    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            edgeCost[i][j] = INT_MAX;
        }
    }

    for (int i = 0; i < m; ++i) {
        int u, v, cost;

        cin >> u >> v >> cost;
        edgeCost[u][v] = cost;
        adj[v].push_back(u);
    }

    int totalSub = 1 << n;
    for (int i = 0; i < totalSub; ++i) {
        for (int j = 0; j < n; ++j) {
            dp[i][j] = INT_MAX;
        }
    }

    dp[1][0] = 0;
    for (int mask = 0; mask < totalSub; ++mask) {
        for (int i = 0; i < n; ++i) {
            if (mask & (1 << i)) {
                for (int next : adj[i]) {
                    if (mask & (1 << next)) {
                        dp[mask][i] = min(dp[mask][i], dp[mask ^ (1 << i)][next] + edgeCost[next][i]);
                    }
                }
            }
        }
    }

    long long ans = INT_MAX;
    for (int next : adj[0]) {
        ans = min(ans, dp[totalSub - 1][next] + edgeCost[next][0]);
    }

    cout << ans;

    return 0;
}