Cod sursa(job #3213429)

Utilizator TeodoraMaria123Serban Teodora Maria TeodoraMaria123 Data 13 martie 2024 09:52:49
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <bits/stdc++.h>

using namespace std;

#define NMAX 18
#define CONFIG_MAX 263000

const int INF = 1e9;

int n, m;
int dp[NMAX + 1][CONFIG_MAX];
vector <vector <pair <int, int> > > graph;

int main()
{
    ios_base :: sync_with_stdio(0);
    cin.tie(0);

    freopen("hamilton.in", "r", stdin);
    freopen("hamilton.out", "w", stdout);

    cin >> n >> m;
    graph.resize(n + 1);

    for(int i = 1; i <= m; i ++)
    {
        int x, y, c;
        cin >> x >> y >> c;
        graph[x].push_back({y, c});
    }

    int stateNo = (1 << n) - 1;

    for(int i = 0; i < n; i ++)
        for(int mask = 0; mask <= stateNo; mask ++)
            dp[i][mask] = INF;

    dp[0][1] = 0;

    for(int mask = 0; mask <= stateNo; mask ++)
    {
        for(int i = 0; i < n; i ++)
        {
            if((1 << i) & mask)
            {
                for(auto x : graph[i])
                    if((mask & (1 << x.first)) == 0)
                    {
                        dp[x.first][mask + (1 << x.first)] = min(dp[x.first][mask + (1 << x.first)], dp[i][mask] + x.second);
                    }

            }
        }
    }

    int ans = INF;
    for(int i = 0; i < n; i ++)
    {
        for(pair <int, int> x : graph[i])
            if(x.first == 0)
                ans = min(ans, dp[i][stateNo] + x.second);
    }
    if(ans == INF)
        cout << "Nu exista solutie";
    else
        cout << ans;
    return 0;
}