Cod sursa(job #3183527)

Utilizator not_anduAndu Scheusan not_andu Data 12 decembrie 2023 10:17:17
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
/**
 * Author: Andu Scheusan (not_andu)
 * Created: 12.12.2023 09:49:33
*/

#include <bits/stdc++.h>
#pragma GCC optimize("O3")

using namespace std;

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

typedef long long ll;

const int N_MAX = 18;
const int SUBMULTIME_MAX = (1 << N_MAX);
const int INF = 0x3f3f3f3f;

struct HeapNode{
    
    int to;
    int cost;

    HeapNode(int _to, int _cost) : to(_to), cost(_cost){}

};

int n, m;
vector<HeapNode> adj[N_MAX];
int d[SUBMULTIME_MAX][N_MAX];

void solve(){

    cin >> n >> m;

    for(int i = 0; i < m; ++i){

        int node1, node2, price; cin >> node1 >> node2 >> price;

        adj[node1].push_back(HeapNode(node2, price));

    }

    memset(d, INF, sizeof d);

    d[1][0] = 0;

    for(int bit = 3; bit < (1 << n); ++bit){
        for(int node = 0; node < n; ++node){
            if(bit & (1 << node)){

                int bitWithoutNode = bit ^ (1 << node);

                for(auto& to : adj[node]){
                    if(bitWithoutNode & (1 << to.to)){
                        d[bit][node] = min(d[bit][node], d[bitWithoutNode][to.to] + to.cost);
                    }
                }

            }
        }
    }

    int ans = INF;

    for(auto& it : adj[0]){
        ans = min(ans, d[(1 << n) - 1][it.to] + it.cost);
    }

    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(nullptr);
    cout.tie(nullptr);

    solve();

    return 0;
}