Cod sursa(job #2949053)

Utilizator TheRomulusIvan Remus TheRomulus Data 29 noiembrie 2022 15:59:39
Problema Ciclu hamiltonian de cost minim Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>

#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <deque>
#include <queue>
#include <stack>

using namespace std;

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

typedef long long ll;

void Solve() {
    int n, m;
    fin >> n >> m;
    vector<vector<int>> cost(n, vector<int>(n, 1e8));
    for (int i = 0; i < m; ++i) {
        int x, y, c;
        fin >> x >> y >> c;
        cost[x][y] = c;
    }

    vector<vector<int>> dp(1 << n, vector<int>(n, 0));

    for (int i = 1; i <= (1 << n) - 1; ++i) {
        for (int j = 0; j < n; ++j) {
            if (i & (1 << j) && (i ^ (1 << j))) {
                int value = 1e8;
                for (int v = 0; v < n; ++v) {
                    if (v != j && (i & (1 << v))) {
                        value = min(value, dp[i ^ (1 << j)][v] + cost[v][j]);
                    }
                }
                dp[i][j] = value;
            }
        }
    }

    int ans = 1e8;
    for (int i = 0; i < n; ++i) {
        ans = min(dp[(1 << n) - 1][i] + cost[i][0], ans);
    }

    if (ans < 1e8) {
        fout << ans;
    }
    else {
        fout << "Nu exista solutie";
    }
    
}

int main() {

    ios_base::sync_with_stdio(false);

    Solve();

    return 0;
}