Cod sursa(job #1757741)

Utilizator preda.andreiPreda Andrei preda.andrei Data 15 septembrie 2016 19:00:21
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <iostream>
#include <fstream>

using namespace std;

#define NMAX 18
#define INFINIT 17000000

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

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

    int n, m;
    fin >> n >> m;

    while (m--) {
        int x, y, c;
        fin >> x >> y >> c;
        cost[x][y] = c;
    }

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

    int start = 0;
    d[start][1 << start] = 0;

    for (int conf = 1; conf < (1 << n); ++conf) {
        for (int i = 0; i < n; ++i) {
            if (conf & (1 << i)) {
                for (int j = 0; j < n; ++j) {
                    if (cost[i][j] && !(conf & (1 << j))) {
                        d[j][conf | (1 << j)] = min(d[j][conf | (1 << j)], d[i][conf] + cost[i][j]);
                    }
                }
            }
        }
    }

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

    if (raspuns < INFINIT)
        fout << raspuns << "\n";
    else fout << "Nu exista solutie";

    return 0;
}