Cod sursa(job #2481547)

Utilizator PetrescuAlexandru Petrescu Petrescu Data 27 octombrie 2019 02:39:21
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <fstream>
#include <iostream>
#include <vector>
#define MAX 18
#define INF 2e9

using namespace std;

vector<int> graph[MAX];
int cost[MAX][MAX], dp[1 << MAX][MAX];
int main()
{
    int n, m, i, j, x, y, c, sol;

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

    fin >> n >> m;

    for(i = 0; i < n; i++)
        for(j = 0; j < n; j++)cost[i][j] = INF;

    for(i = 0; i < m; i++)
    {
        fin >> x >> y >> c;

        cost[x][y] = c;
        graph[y].push_back(x);
    }

    for(i = 0; i < 1 << n; i++)
        for(j = 0; j < n; j++)dp[i][j] = INF;

    dp[1][0] = 0;

    for(i = 0; i < 1 << n; i++)
        for(j = 0; j < n; j++)
            if(i & (1 << j))
                for(auto k : graph[j])
                    if(i & (1 << k))
                        dp[i][j] = min(dp[i][j], dp[i ^ (1 << j)][k] + cost[k][j]);

    sol = INF;

    for(auto k : graph[0])
        sol = min(sol, dp[(1 << n) - 1][k] + cost[k][0]);

    if(sol == INF)fout << "Nu exista solutie";
    else fout << sol;

    fin.close();
    fout.close();

    return 0;
}