Cod sursa(job #1888860)

Utilizator tudorgalatanRoman Tudor tudorgalatan Data 22 februarie 2017 13:06:36
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <fstream>
#include <climits>
#include <vector>

using namespace std;

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

unsigned int N, M;
unsigned int x, y, c;

vector <unsigned int> G[18];
unsigned int cost[19][19];
unsigned int sol[(1<<19)][19];
unsigned int i, j, k;

unsigned int solution;

int main ()
{
    fin >> N >> M;
    for (i=1; i<=M; i++)                /// READ
    {
        fin >> x >> y >> c;
        G[y].push_back(x);
        cost[x][y] = c;
    }
    for (i=0; i<(1<<N); i++)            /// We initialize the matrix of solutions with big values.
        for (j=0; j<N; j++)
            sol[i][j] = INT_MAX;
    sol[1][0] = 0;                      /// First solution.
    for (i=0; i<(1<<N); i++)
        for (j=0; j<N; j++)
            if (i&(1<<j))
                for (k=0; k<G[j].size(); k++)
                    sol[i][j] = min(sol[i^(1<<j)][G[j][k]]+cost[G[j][k]][j],sol[i][j]);     /// Creat the matrix of solutions.
    solution = INT_MAX;                 /// Initialize solution with a big value.
    for (i=0; i<G[0].size(); i++)
        solution = min(solution,sol[(1<<N)-1][G[0][i]]+cost[G[0][i]][0]);                   /// Calculate solution.
    if (solution != INT_MAX)            /// If we have a solution...
        fout << solution;               /// We print it.
    else
        fout << "Nu exista solutie";
    return 0;
}