Cod sursa(job #2723305)

Utilizator IoanaDraganescuIoana Draganescu IoanaDraganescu Data 13 martie 2021 21:18:37
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>

using namespace std;

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

const int NMax = 18, oo = 0x3f3f3f3f;

vector <int> g[NMax + 5];
int n, m, mincost;
int cost[NMax + 5][NMax + 5], dp[(1 << NMax) + 5][NMax + 5];

void Read(){
    fin >> n >> m;
    while (m--){
        int x, y, c;
        fin >> x >> y >> c;
        g[y].push_back(x);
        cost[x][y] = c;
    }
}

void Solve(){
    memset(dp, oo, sizeof dp);
    dp[1][0] = 0;
    for (int config = 2; config <= (1 << n) - 1; config++)
        for (int node = 0; node < n; node++)
            if ((1 << node) & config)
                for (auto ngh : g[node])
                    if ((1 << ngh) & config)
                        dp[config][node] = min(dp[config][node], dp[config - (1 << node)][ngh] + cost[ngh][node]);
    mincost = oo;
    int config = (1 << n) - 1;
    for (auto ngh : g[0])
        mincost = min(mincost, dp[config][ngh] + cost[ngh][0]);
}

void Print(){
    if (mincost != oo)
        fout << mincost << '\n';
    else
        fout << "Nu exista solutie" << '\n';
}

int main(){
    Read();
    Solve();
    Print();
    return 0;
}