Cod sursa(job #600010)

Utilizator cosmyoPaunel Cosmin cosmyo Data 30 iunie 2011 12:13:09
Problema Ciclu hamiltonian de cost minim Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <cstdio>
#include <vector>
using namespace std;
const int N = 19;
int d[1 << N][N], n, m, cost[N][N];
vector<int> a[N];
const int INF = 0x3f3f3f3f;
inline int min (int a, int b) {
    return a < b ? a : b;
}

int main() {
    freopen("hamilton.in", "r", stdin);
    freopen("hamilton.out", "w", stdout);
    int i, j, x, y, ct, k;
    scanf("%d %d", &n, &m);
    for(i = 1; i <= m; ++i){
        scanf("%d %d %d", &x, &y, &ct);
        a[y].push_back(x);
        cost[x][y] = ct;
    }

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

    for(i = 1; i < (1 << n); ++i)
        for(j = 0; j <= n; ++j)
            if((1 << j) & i){
                for(k = 0; k < a[j].size(); ++k)
                    if(i & (1 << a[j][k]))
                        d[i][j] = min(d[i][j], d[i ^ (1 << j)][ a[j][k] ] + cost[ a[j][k] ][j]);
            }
   // return 0;
    int sol = INF;
    for(i = 0; i < a[0].size(); ++i)
        sol = min(sol, d[(1 << n) - 1][a[0][i]] + cost[a[0][i]][0]);

    printf("%d\n", sol);

    return 0;
}