Cod sursa(job #2297759)

Utilizator alexge50alexX AleX alexge50 Data 6 decembrie 2018 15:26:50
Problema Ciclu hamiltonian de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <fstream>
#include <limits>

const int MAX_N = 18;
const int MAX_M = (MAX_N - 1) * MAX_N;
//const int INF = std::numeric_limits<int>::max() / 2;
const int INF = 1 << 20;

int d[1 << MAX_N][MAX_N];
int cost[MAX_N][MAX_N];

int main()
{
    std::ifstream fin("hamilton.in");
    int n, m;

    fin >> n >> m;
    for(int i = 0; i < n; i++)
        for(int j = 0; j < n; j++)
            cost[i][j] = i == j ? 0 : INF;

    for(int i = 0; i < m; i++)
    {
        int x, y, z;
        fin >> x >> y >> z;

        cost[x][y] = z;
    }

    for(int i = 0; i < (1 << n); i++)
        for(int j = 0; j < n; j++)
            d[i][j] = INF;
    d[1][0] = 0;

    for(int i = 1; i < (1 << n); i += 2)
        for(int j = 0; j < n; j++)
            for(int k = 0; k < n; k++)
                if(((1 << k) & i) != 0 && k != j)
                {
                    d[i][j] = std::min(d[i][j], d[i - (1 << j)][k] + cost[k][j]);
                }

    std::ofstream fout("hamilton.out");
    int r = INF;

    for(int i = 0; i < n; i++)
        r = std::min(r, d[(1 << n) - 1][i] + cost[i][0]);

    fout << r;

    return 0;
}