Cod sursa(job #3183394)

Utilizator not_anduAndu Scheusan not_andu Data 11 decembrie 2023 19:04:46
Problema Ciclu hamiltonian de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include <bits/stdc++.h>
#pragma GCC optimize ("03")

using namespace std;

#define INFILE "hamilton.in"
#define OUTFILE "hamilton.out"

typedef long long ll;
typedef long double ld;

const int N_MAX = 20;
const int SUBMULTIME_MAX = 262147;
const int INF = 19000001;

int n, m;
ll cost[N_MAX][N_MAX];
ll d[N_MAX][SUBMULTIME_MAX];

void init(){
    for(int bit = 1; bit < (1 << n); ++bit){
        for(int i = 0; i < n; ++i){
            d[i][bit] = INF;
        }
    }
}

void solve(){

    cin >> n >> m;

    init();

    for(int i = 1; i <= m; ++i){
        int node1, node2, price;
        cin >> node1 >> node2 >> price;
        cost[node1][node2] = price;
    }

    d[0][1] = 0;

    for(int bit = 1; bit < (1 << n); ++bit){
        for(int i = 0; i < n; ++i){
            if((bit >> i) & 1){
                int aux = bit - (1 << i);
                for(int to = 0; to < n; ++to){
                    if((aux >> to) & 1 && cost[to][i] != 0){
                        d[i][bit] = min(d[i][bit], d[to][aux] + cost[to][i]);
                    }
                }
            }
        }
    }

    ll ans = INF;

    for(int i = 0; i < n; ++i){
        if(cost[i][0] != 0){
            ans = min(ans, d[i][(1 << n) - 1] + cost[i][0]);
        }
    }

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

}

int main(){
    ios_base::sync_with_stdio(false);
    freopen(INFILE, "r", stdin);
    freopen(OUTFILE, "w", stdout);
    cin.tie(0); cout.tie(0);
    solve();
    return 0;
}