Cod sursa(job #2458725)

Utilizator andreisontea01Andrei Sontea andreisontea01 Data 21 septembrie 2019 13:00:25
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include <bits/stdc++.h>
#include <cstdlib>

using namespace std;

vector<int> graf[20];
int dp[300005][25], cost[25][25];

int main()
{
    ifstream fin("hamilton.in");
    ofstream fout("hamilton.out");
    int n, m;
    fin >> n >> m;
    for(int i = 1; i <= m; ++i){
        int x, y;
        fin >> x >> y;
        graf[y].push_back(x);
        fin >> cost[x][y];
    }
    for(int i = 0; i < (1 << n); ++i){
        for(int j = 0; j < n; ++j)
            dp[i][j] = 1 << 30;
    }
    dp[1][0] = 0;
    for(int i = 0; i < (1 << n); ++i){
        for(int j = 0; j < n; ++j){
            if(i & (1 << j)){
                for(auto x : graf[j])
                    dp[i][j] = min(dp[i][j], dp[i ^ (1 << j)][x] + cost[x][j]);
            }
        }
    }
    int ans = 1 << 30;
    for(auto x : graf[0])
        ans = min(ans, dp[(1 << n) - 1][x] + cost[x][0]);
    if(ans < (1 << 30)) fout << ans;
    else fout << "Nu exista solutie";
    return 0;
}