Cod sursa(job #1967145)

Utilizator nicu_serteSerte Nicu nicu_serte Data 15 aprilie 2017 22:42:10
Problema Ciclu hamiltonian de cost minim Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>
#include <climits>
using namespace std;
ifstream fin("hamilton.in");
ofstream fout("hamilton.out");
#define nmax 20
int n, m, a[nmax][nmax], costmin, st[nmax];
bool viz[nmax]={0};
void citire()
{
    int i, x, y, z;
    fin>>n>>m;
    for(i=1; i<=m; i++)
    {
        fin>>x>>y>>z;
        x++; y++;
        a[x][y]=z;
    }
    fin.close();
}
void solutie()
{
    if(!a[st[n]][1])
        return;
    int i, cost;
    cost=0;
    for(i=1; i<n; i++)
        cost+=a[st[i]][st[i+1]];
    cost+=a[st[n]][1];
    if(cost<costmin)
        costmin=cost;
}
void bt(int k)
{
    if(k==n+1)
        solutie();
    else for(int i=2; i<=n; i++)
    {
        if(a[st[k-1]][i])
            if(!viz[i])
            {
                st[k]=i;
                viz[i]=1;
                bt(k+1);
                viz[i]=0;
            }
    }
}
int main()
{
    citire();
    costmin=INT_MAX;
    st[1]=1;
    viz[1]=1;
    bt(2);
    fout<<costmin<<'\n';
    fout.close();
    return 0;
}