Cod sursa(job #2562906)

Utilizator MariusblockMoga Marius-Ioan Mariusblock Data 29 februarie 2020 19:58:13
Problema Ciclu hamiltonian de cost minim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>
#define MOD 104659
#define ull unsigned long long

using namespace std;

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

long long n,m;
vector<pair<int,int>> G[30];
long long DP[262155][19];
const int inf = 1000005;

int main()
{
    long long i,j,k,a,b,cost,sol = inf;
    fin>>n>>m;
    for(i = 1; i <= m; i++){
        fin>>a>>b>>cost;
        G[b].push_back(make_pair(a,cost));
    }
    for(i = 0; i < (1<<n); i++){
        for(j = 0; j < n; j++){
            DP[i][j] = inf;
        }
    }
    DP[1][0] = 0;
    for(i = 1; i < (1<<n); i++){
        for(j = 0; j < n; j++){
            if(i & (1<<j)){
                for(k = 0; k < G[j].size(); k++){
                    if(i & (1<<G[j][k].first)){
                        DP[i][j] = min(DP[i][j],DP[i-(1<<j)][G[j][k].first] + G[j][k].second);
                    }
                }
            }
        }
    }
    for(i = 0; i < G[0].size(); i++){
        sol = min(sol,DP[(1<<n)-1][G[0][i].first] + G[0][i].second);
    }
    if(sol == inf){
        fout<<"Nu exista solutie";
    }else{
        fout<<sol;
    }
    return 0;
}