Cod sursa(job #2476055)

Utilizator petrisorvmyVamanu Petru Gabriel petrisorvmy Data 17 octombrie 2019 22:36:06
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <bits/stdc++.h>

using namespace std;
ifstream f("hamilton.in");
ofstream g("hamilton.out");
const int inf = (1 << 30);
int n,m, a[25][25], pd[272145][25],unde[272145][25];
int main()
{
    f >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        int x,y,z;
        f >> x >> y >> z;
        a[x][y] = z;
    }
    for(int i = 0 ; i <= (1 << n); ++i)
        for(int j = 0; j <= n; ++j)
            pd[i][j] = inf;

    for(int i = 0; i < n; ++i)
        pd[1][i] = 0;

    for(int mask = 0; mask < (1 << n); ++mask)
        for(int last = 0; last < n; ++last)
            if(mask & (1 << last))
                for(int next = 0; next < n; ++next)
                    if(a[last][next])
                    {
                        if((1 << next) & mask)
                            pd[mask][last] = min(pd[mask][last], pd[mask ^ (1 << last)][next] + a[last][next]);
                    }
    int ans = inf;
    for(int i = 0; i < n; ++i)
        if(a[0][i] != 0)
        ans = min(ans, pd[(1 << n) - 1][i] + a[0][i]);
    if(ans != inf)
        g << ans;
    else
        g << "Nu exista solutie";
    f.close();
    g.close();
    return 0;
}