Cod sursa(job #3159365)

Utilizator AlexCroitoriuAlex Croitoriu AlexCroitoriu Data 21 octombrie 2023 10:28:23
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <bits/stdc++.h>

using namespace std;
fstream f("hamilton.in", ios::in), g("hamilton.out", ios::out);
vector<pair<int, int>> adj[18];
int cost[18][18];
int dp[1 << 18][18];
int main()
{
    int n, m, i, j, next, c;
    f >> n >> m;
    for (i = 1; i <= m; i++)
    {
        int x, y;
        f >> x >> y >> c;
        adj[x].push_back({y, c});
        cost[x][y] = c;

    }
    int mask = (1 << n);
    for (int i = 0; i < mask; i++)
        for (int j = 0; j < n; j++)
            dp[i][j] = 1e9;

    dp[1][0] = 0;

    for (i = 0; i < mask; i++)
    {
        for (j = 0; j < n; j++)
        {
            if (i & (1 << j))
            {
                for (const auto& x : adj[j])
                {
                    next = x.first, c = x.second;
                    if (!(i & (1 << next)))
                    {
                        dp[i | (1 << next)][next] = min(dp[i | (1 << next)][next], dp[i][j] + c);
                    }
                }
            }
        }
    }

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

    if (ans == 1e9)
        g << "Nu exista solutie";
    else
        g << ans;


}