Cod sursa(job #2892682)

Utilizator tiut_cristianTiut Cristian tiut_cristian Data 23 aprilie 2022 10:04:59
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <fstream>
#include <vector>
#include <cstring>

using namespace std;

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

const int INF = 1000000000;

int n, m, sol;
vector <int> a[20];
int c[262150][20];
int cost[20][20];

int calc(int conf, int last)
{
    if (c[conf][last] == -1)
    {
        c[conf][last] = INF;
        for (int i = 0; i < a[last].size(); i++)
            if (conf & (1 << a[last][i]))  // le aleg doar pe cele care apartin lantului
            {
                if (a[last][i] == 0 && conf != (1<<(last)) + 1)
                    continue; // nodul 1 trebuie sa il scot ultimul
                c[conf][last] = min(c[conf][last], calc(conf ^ (1<<last), a[last][i]) + cost[a[last][i]][last]);
            }
    }
    return c[conf][last];
}

void init()
{
    sol = INF;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            cost[i][j] = INF;
}

void citire()
{
    fin >> n >> m;
    for (int i = 1; i <= m; ++i)
    {
        int x, y;
        fin >> x >> y;
        a[y].push_back(x);
        fin >> cost[x][y];
    }
}

void rezolvare()
{
    c[1][0] = 0;
    for(int i = 0; i < a[0].size(); i++)
        sol = min(sol, calc((1<<n)-1, a[0][i]) + cost[a[0][i]][0]);
}

void afisare()
{
    if(sol == INF)
        fout << "Nu exista solutie";
    else
        fout << sol;
}

int main()
{
    init();
    citire();
    memset(c, -1, sizeof(c));
    rezolvare();
    afisare();

    return 0;
}