Cod sursa(job #2445483)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 4 august 2019 12:07:50
Problema Ciclu hamiltonian de cost minim Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
#include <vector>

using namespace std;

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

const int NMAX = 18;
const int CONFIGMAX = 1 << 18;
const int oo = 2e6;

vector <int> g[NMAX + 5];

int N, M;
int cost[NMAX + 5][NMAX + 5], dp[CONFIGMAX + 5][NMAX + 5];

int main()
{
    fin >> N >> M;

    for(int i = 0; i < N; i++)
        for(int j = 0; j < N; j++)
            cost[i][j] = oo;

    for(int i = 1; i <= M; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        cost[x][y] = c;
        g[y].push_back(x);
    }

    for(int i = 0; i < CONFIGMAX; i++)
        for(int j = 0; j < N; j++)
            dp[i][j] = oo;

    dp[1][0] = 0;

    for(int config = 0; config < (1 << N); config++)
        for(int j = 0; j < N; j++)
            if(config & (1 << j))
                for(auto it : g[j])
                    if(config & (1 << it))
                        dp[config][j] = min(dp[config][j], dp[config ^ (1 << j)][it] + cost[it][j]);

    int sol = oo;

    for(int i = 1; i < N; i++)
        sol = min(sol, dp[(1 << N) - 1][i] + cost[i][0]);

    if(sol == oo)
        fout << "Nu exista solutie\n";
    else
        fout << sol;

    return 0;
}