Cod sursa(job #2869316)

Utilizator 100pCiornei Stefan 100p Data 11 martie 2022 13:58:20
Problema Ciclu hamiltonian de cost minim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <bits/stdc++.h>
#define FILES freopen("hamilton.in","r",stdin);\
              freopen("hamilton.out","w",stdout);
#define MAX 18
#define fastio ios_base::sync_with_stdio(NULL),cin.tie(NULL),cout.tie(NULL);
using namespace std;
int n,m,a,b,c;
vector<pair<int,int>> v[MAX+5];
int dp[262160][19];
int main()
{
    fastio
    FILES
    cin >> n >> m;
    for(int i = 1;i <= m; ++i)
    {
        cin >> a >> b >> c;
        a++,b++;
        v[a].push_back({b,c});
    }
    int mask = (1 << n) - 1;
    for(int i = 1;i <= mask; ++i)
        for(int j = 1;j <= n; ++j) dp[i][j] = 1e9;
    for(int i = 1;i <= mask; ++i)
    {
        for(int j = 1;j <= n; ++j)
        {
            if(i & (1 << (j - 1)))
            {
                for(auto k : v[j])
                {
                    if(i & (1 << (k.first - 1)))
                    {
                        int z = i ^ (1 << (k.first - 1));
                        dp[i][j] = min(dp[i][k.first],dp[z][j] + k.second);
                    }
                }
            }
        }
    }
    int ans = 1e8;
    for(int i = 1;i <= n; ++i)
    {
        for(auto k : v[i]){
            if(k.first == 1){
                ans = min(ans,dp[mask][i]+k.second);
            }
        }
    }
    if(ans >= 1e8) cout << "Nu exista solutie";
    else cout << ans;
}