Cod sursa(job #2253086)

Utilizator vladm98Munteanu Vlad vladm98 Data 3 octombrie 2018 16:59:02
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <bits/stdc++.h>

using namespace std;

int dp[20][500000];
int costs[20][20];

void buildDp (int n) {
    int totalMasks = (1 << n);
    for (int i = 1; i <= n; ++i) {
        for (int mask = 0; mask < totalMasks; ++mask) {
            dp[i][mask] = 1 << 29;
        }
    }
    for (int i = 2; i <= n; ++i) {
        dp[i][1 << i - 1] = costs[1][i];
    }

    for (int mask = 0; mask < totalMasks; ++mask) {
        for (int i = 1; i <= n; ++i) {
            if (!(mask & (1 << i - 1))) continue;
            if (dp[i][mask] == (1 << 29)) continue;
            for (int j = 1; j <= n; ++j) {
                if (mask & (1 << j - 1)) continue;
                int newMask = mask | (1 << j - 1);
                dp[j][newMask] = min (dp[j][newMask], dp[i][mask] + costs[i][j]);
            }
        }
    }
}

int main() {
    ifstream fin ("hamilton.in");
    ofstream fout ("hamilton.out");
    int n, m;
    fin >> n >> m;
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= n; ++j) {
            costs[i][j] = 1 << 29;
        }
    }
    for (int i = 1; i <= m; ++i) {
        int x, y, cost;
        fin >> x >> y >> cost;
        x += 1;
        y += 1;
        costs[x][y] = min (costs[x][y], cost);
    }
    buildDp(n);
    if (dp[1][(1 << n) - 1] < (1 << 29))
        fout << dp[1][(1 << n) - 1];
    else
        fout << "Nu exista solutie";
}