Cod sursa(job #2843530)

Utilizator divadddDavid Curca divaddd Data 2 februarie 2022 16:34:44
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp-64 Status done
Runda cv1101 Marime 1.66 kb
#include <iostream>
#include <vector>
#include <fstream>
#define MAXMASK 262152
#define MAXN    20
#define INF     (1<<29)
using namespace std;
int n,m,x,y,cost,f[MAXN];
int dp[MAXMASK][MAXN];
vector<pair<int, int>> L[MAXN];

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

int main()
{
    fin >> n >> m;
    /// intializam toate valorile dp cu INF
    for(int codStare = 1; codStare < (1<<n); codStare += 2){
        for(int last = 0; last < n; last++){
            dp[codStare][last] = INF;
        }
    }
    /// citim, realizam lista de vecini
    for(int i = 1; i <= m; i++){
        fin >> x >> y >> cost;
        L[x].push_back({y, cost});
        if(y == 0){
            f[x] = cost;
        }
    }
    dp[1][0] = 0;
    for(int codStare = 1; codStare < (1<<n); codStare += 2){
        for(int last = 0; last < n; last++){
            if(dp[codStare][last] != INF){
                for(int i = 0; i < L[last].size(); i++){
                    int x = L[last][i].first;
                    int cost = L[last][i].second;
                    if( ( (codStare >> last) & 1 ) == 1 ){
                        if(( (codStare >> x) & 1 ) == 0)
                            dp[codStare+(1<<x)][x] = min(dp[codStare+(1<<x)][x], dp[codStare][last]+cost);
                    }
                }
            }
        }
    }
    int sol = INF;
    for(int last = 1; last < n; last++){
        if(f[last] != 0 && dp[(1<<n)-1][last] != INF){
            sol = min(sol, dp[(1<<n)-1][last]+f[last]);
        }
    }
    if(sol != INF){
        fout << sol << "\n";
    }else{
        fout << "Nu exista solutie\n";
    }
    return 0;
}