Cod sursa(job #1942718)

Utilizator TimoteiCopaciu Timotei Timotei Data 28 martie 2017 09:56:30
Problema Ciclu hamiltonian de cost minim Scor 65
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#include <iostream>
#include <fstream>
#define inf 1 << 30
using namespace std;
int n, m, cost[20][20], dp[1 << 18][20];
void read()
{
    ifstream fin("hamilton.in");
    fin >> n >> m;
    int x, y , c;
    for(int i = 0; i < n; ++i)
        for(int j = 0; j < n; ++j)
         cost[i][j] = inf;
    for(int i = 1; i <= m; ++i){
        fin >> x >> y >> c;
        cost[x][y] = c;
    }
}
void hamilton()
{
    int sol = inf;
    for(int i = 1; i < (1 << n); ++i)
      for(int j = 0; j < n; ++j)
        dp[i][j] = inf;
    dp[1][0] = 0;
    for(int i = 1; i < (1 << n); ++i)
      for(int j = 0; j < n; ++j)
        if(i & (1 << j))
         for(int k = 0; k < n; ++k)
           if(cost[k][j] != inf && i & (1 << k))
             dp[i][j] = min(dp[i][j], dp[i ^ (1 << j)][k] + cost[k][j]);
    for(int i = 0; i < n; ++i)
        if(cost[0][i] != inf)
          sol = min(sol, dp[(1 << n) - 1][i] + cost[i][0]);
   ofstream fout("hamilton.out");
   fout << sol;
}
int main()
{
    read();
    hamilton();
    return 0;
}