Cod sursa(job #1458483)

Utilizator Burbon13Burbon13 Burbon13 Data 7 iulie 2015 17:00:23
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <cstdio>
#include <vector>
#include <cstring>
using namespace std;

const int nmx = 20;
const int maxx = (1 << 18) + 1;
const int inf = 0x3f3f3f3f;

int n, m;
int cost[nmx][nmx];
int dp[maxx][nmx];
vector <int> g[nmx];

int main(){
    memset(dp, inf, sizeof(dp));
    memset(cost, inf, sizeof(cost));
    freopen("hamilton.in", "r", stdin);
    freopen("hamilton.out", "w", stdout);
    scanf("%d %d", &n, &m);
    for(; m; --m){
        int n1, n2;
        scanf("%d %d", &n1, &n2);
        g[n2].push_back(n1);
        scanf("%d", &cost[n1][n2]);
    }
    dp[1][0] = 0;
    for(int i = 0; i < (1 << n); ++i)
        for(int j = 0; j < n; ++j)
            if(i && (1 << j))
                for(size_t v = 0; v < g[j].size(); ++v)
                    if(i && (1 << g[j][v]))
                        dp[i][j] = min(dp[i][j], dp[i ^ (1 << j)][g[j][v]] + cost[g[j][v]][j]);
    int sol = inf;
    for(size_t v = 0; v < g[0].size(); ++v)
        sol = min(sol, dp[(1 << n) - 1][g[0][v]] + cost[g[0][v]][0]);
    if(sol == inf)
        printf("Nu exista solutie\n");
    else
        printf("%d\n", sol);
    return 0;
}