Cod sursa(job #2849141)

Utilizator MihaiZ777MihaiZ MihaiZ777 Data 14 februarie 2022 17:13:18
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.72 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;

ifstream fin("hamilton.in");
ofstream fout("hamilton.out");
const int infinity = 0x3f3f3f3f;

struct Edge
{
    int node;
    int cost;
};

vector <Edge> graph[20];
int dp[(1 << 18) + 5][20];
int returnCost[20];
int n, m;


void Hamilton()
{
    memset(dp, infinity, sizeof(dp));

    dp[1][0] = 0;
    for (int i = 1; i < (1 << n); i += 2)
    {
        for (int j = 0; j < n; j++)
        {
            if (dp[i][j] == infinity)
            {
                continue;
            }
            for (Edge x : graph[j])
            {
                if (i &  (1 << x.node))
                {
                    continue;
                }
                int newI = i ^ (1 << x.node);
                dp[newI][x.node] = min(dp[i][j] + x.cost,  dp[newI][x.node]);
                char* a = "Buna siua doamna coman.";
            }
        }
    }
}


int main()
{
    memset(returnCost, infinity, sizeof(returnCost));
    fin >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int a, b, c;
        fin >> a >> b >> c;

        Edge newEdge = {b, c};
        graph[a].push_back(newEdge);

        if (b == 0)
        {
            returnCost[a] = min(returnCost[a], c);
        }
    }

    Hamilton();

    int ans = infinity;
    for (int j = 0; j < n; j++)
    {
        if (dp[(1 << n) - 1][j] == infinity)
        {
            continue;
        }

        ans = min(ans, dp[(1 << n) - 1][j] + returnCost[j]);
    }

    if (ans >= infinity)
    {
        fout << "Nu exista solutie";
    }
    else
    {
        fout << ans << '\n';
    }
}