Cod sursa(job #2480864)

Utilizator IoanaDraganescuIoana Draganescu IoanaDraganescu Data 26 octombrie 2019 10:44:30
Problema Ciclu hamiltonian de cost minim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

const int nmax = 18, inf = 0x3f3f3f3f;

vector <int> g[nmax + 5];
int n, m, cost[nmax + 5][nmax + 5], d[(1 << nmax) + 5][nmax];

void Read(){
    fin >> n >> m;
    int x, y, c;
    while (m--){
        fin >> x >> y >> c;
        g[y].push_back(x);
        cost[x][y] = c;
    }
}

void Solve(){
    for (int conf = 0; conf < (1 << n); conf++)
        for (int j = 0; j < n; j++)
            d[conf][j] = inf;
    d[1][0] = 0;
    for (int conf = 1; conf < (1 << n); conf++)
        for (int j = 0; j < n; j++)
            if (conf & (1 << j))
                for (auto vecin : g[j])
                    if (conf & (1 << vecin))
                        d[conf][j] = min(d[conf][j], d[conf - (1 << j)][vecin] + cost[j][vecin]);
}

void Print(){
    int x = (1 << n) - 1, Min = inf;
    for (int j = 0; j < n; j++)
        Min = min(Min, d[x][j] + cost[j][0]);
    if (Min == inf)
        fout << "Nu exista solutie" << '\n';
    else
        fout << Min << '\n';
}

int main(){
    Read();
    Solve();
    Print();
    return 0;
}