Cod sursa(job #2297775)

Utilizator alexge50alexX AleX alexge50 Data 6 decembrie 2018 15:48:31
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
/*
 *
 * I consider that the Golden Rule requires that if I like a program I must share it with other people who like it.
 * Software sellers want to divide the users and conquer them, making each user agree not to share with others.
 *
 *      - RMS, The GNU Manifesto
 *
 */

#include <fstream>
#include <limits>

const int MAX_N = 18;
const int MAX_M = (MAX_N - 1) * MAX_N;
const int INF = 1 << 28;

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 = 3; 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]);

    if(r >= INF)
        fout << "Nu exista solutie";
    else
        fout << r;

    return 0;
}