Cod sursa(job #2924544)

Utilizator IvanAndreiIvan Andrei IvanAndrei Data 4 octombrie 2022 19:56:10
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include <fstream>
#include <vector>

using namespace std;

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

const int max_size = 19, max_conf = (1 << 18) + 1, INF = 1e9 + 1;

vector <int> mc[max_size];
int cost[max_size][max_size], c[max_conf][max_size];

int main ()
{
    int n, m;
    in >> n >> m;
    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++)
    {
        int x, y;
        in >> x >> y;
        in >> cost[x][y];
        mc[y].push_back(x);
    }
    for (int i = 0; i < (1 << n); i++)
    {
        for (int j = 0; j < n; j++)
        {
            c[i][j] = INF;
        }
    }
    c[1][0] = 0;
    for (int i = 0; i < 1 << n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            if (i & (1 << j))
            {
                for (auto f : mc[j])
                {
                    if (i & (1 << f))
                    {
                        c[i][j] = min(c[i][j], c[i ^ (1 << j)][f] + cost[f][j]);
                    }
                }
            }
        }
    }
    int sol = INF;
    for (auto f : mc[0])
    {
        //out << c[(1 << n) - 1][f] << " ";
        sol = min(sol, c[(1 << n) - 1][f] + cost[f][0]);
    }
    if (sol == INF)
    {
        out << "Nu exista solutie";
    }
    else
    {
        out << sol;
    }
    in.close();
    out.close();
    return 0;
}