Cod sursa(job #2871890)

Utilizator Theo14Ancuta Theodor Theo14 Data 15 martie 2022 22:04:10
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <bits/stdc++.h>
#define INF 1000000000
using namespace std;

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

int n,m,dp[20][(1<<18)+3];
vector< pair<int,int> >v[20];

int main()
{
    int i,x,y,c,stare,x1,x2;
    f>>n>>m;
    for(i=1;i<=m;i++)
    {
        f>>x>>y>>c;
        v[x].push_back(make_pair(y,c));
    }
    for(stare=1;stare<=(1<<n);stare++)
    {
        for(i=0;i<n;i++)
        {
            dp[i][stare]=INF;
        }
    }
    dp[0][1]=0;
    for(stare=1; stare<=(1<<n); stare++)
    {
        for(i=0;i<n;i++)
        {
            if(dp[i][stare]!=INF)
            {
                for(auto it:v[i])
                {
                    x1=it.first;
                    x2=it.second;
                    if(dp[x1][stare^(1<<x1)]>dp[i][stare]+x2)
                    {
                        dp[x1][stare^(1<<x1)]=dp[i][stare]+x2;
                    }
                }
            }
        }
    }
    stare=(1<<n);
    for(i=0;i<n;i++)
    {
        for(auto it:v[i])
        {
            x1=it.first;
            x2=it.second;
            if(x1==0)
            {
                dp[0][stare]=min(dp[0][stare],dp[i][stare-1]+x2);
            }
        }
    }
    if(dp[0][stare]==INF)
        g<<"Nu exista solutie";
    else
        g<<dp[0][stare];
    return 0;
}