Cod sursa(job #2300940)

Utilizator AlexandruabcdeDobleaga Alexandru Alexandruabcde Data 12 decembrie 2018 13:34:39
Problema Ciclu hamiltonian de cost minim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <bits/stdc++.h>

using namespace std;

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

const int INF = 0x3F3F3F3F;
constexpr int NMAX=18, MMAX=262145;

vector <int> G[NMAX];

int n, m, x, y, c;

int cost[NMAX][NMAX];

int dp[NMAX][MMAX];

inline void citire ()
{
    f >> 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++)
    {
        f >> x >> y >> c;

        G[y].push_back(x);

        cost[x][y] = c;
    }
}

inline int functie (int x, int S)
{
    int val = INF;

    for (int k = 0; k < G[x].size(); k++)
        if ((S & (1<<G[x][k])) && S >= (1<<x))
            val = min(val, cost[k][x] + dp[k][S - (1<<x)]);

    return val;
}

inline void fac_dinamica ()
{
    for (int j = 0; j < (1 << n); j++)
    {
        for (int i = 0; i < n; i++)
        {
            if (i == 0 && j == 1) dp[i][j] = 0;

            else if ((j & (-j)) == j) dp[i][j] = INF;

            else if (j == (1 << i)) dp[i][j] = INF;

            else
                dp[i][j] = functie(i, j);
        }
    }
}

inline void solve()
{
    int sol = INF;

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

    if (sol == INF)
    {
        g <<"Nu exista solutie" << '\n';

        return;
    }

    g << sol << '\n';
}

int main()
{
    f.tie(NULL);

    citire();

    fac_dinamica();

    solve();

    return 0;
}