Cod sursa(job #2871568)

Utilizator Theo14Ancuta Theodor Theo14 Data 15 martie 2022 09:04:05
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 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<int>a[20],b[20];
vector<int>::iterator it1,it2;

int main()
{
    int i,x,y,c,stare,x1,x2;
    f>>n>>m;
    for(i=1;i<=m;i++)
    {
        f>>x>>y>>c;
        a[x].push_back(y);
        b[x].push_back(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(it1=a[i].begin(),it2=b[i].begin(); it1!=a[i].end(); it1++,it2++)
                {
                    x1=*it1;
                    x2=*it2;
                    if((stare&(1<<x1))==0)
                    {
                        y=stare+(1<<x1);
                        dp[x1][y]=min(dp[x1][y],dp[i][stare]+x2);
                    }
                }
            }
        }
    }
    stare=(1<<n);
    for(i=0;i<n;i++)
    {
        for(it1=a[i].begin(), it2=b[i].begin(); it1!=a[i].end(); it1++,it2++)
        {
            x1=*it1;
            x2=*it2;
            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;
}