Cod sursa(job #2562389)

Utilizator AndreeaGherghescuAndreea Gherghescu AndreeaGherghescu Data 29 februarie 2020 13:57:15
Problema Ciclu hamiltonian de cost minim Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <iostream>
#include <fstream>
#define inf 1e9

using namespace std;

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

int nr,cost[20][20];
int dp[262146][20];

void afis(int n)
{
    for (int i=0; i< (1<<n); i++)
    {
        for (int j=0; j<n; j++)
            out<<dp[i][j]<<' ';
        out<<'\n';
    }
    out << "\n\n";
}

int main()
{
    int n,m,x,y,c;
    in>>n>>m;
    for (int i=0; i<n; i++)
        for (int j=0; j<n; j++)
            cost[i][j]=inf;
    for (int i=1; i<=m; i++)
    {
        in>>x>>y>>c;
        cost[x][y]=c;
    }

    for (int i=0; i< (1<<n); i++)
        for (int j=0; j<n; j++)
            dp[i][j]=inf;
    dp[1][0]=0;
    for (int i=3; i< (1<<n) ; i+=2)
    {
        for (int j=0; j<n; j++)
            if (i & (1<<j))
                for (int k=0; k<n; k++)
                    if (i & (1<<k))
                    {
                        dp[i][j]=min(dp[i][j],dp[i^(1<<j)][k]+cost[k][j]);
                    }
        //afis(n);

    }
    int sol=inf;
    //n--;

    for (int j=0; j<n; j++)
        sol=min(sol,dp[(1<<n)-1][j] + cost[j][0]);
    out<<sol;
    return 0;
}