Cod sursa(job #2482427)

Utilizator i.uniodCaramida Iustina-Andreea i.uniod Data 28 octombrie 2019 11:33:37
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#define inf 100000000
#include <bits/stdc++.h>
using namespace std;
ifstream fin("hamilton.in");
ofstream fout("hamilton.out");

vector<pair <int,int> > M[20];
int C[300000][20];
int n, m;

int main()
{
    int x, y, c, vecin, cost;
    fin >> n >> m;
    for(int i = 1; i<= m; i++)
    {
        fin >> x >> y >> c;
        M[x].push_back({y,c});
    }
    x = 1<<n;

    for(int i = 0; i < x; i++)
		for(int j = 0; j < n; j++)
            C[i][j] = inf;

    C[1][0]=0;
    for(int k = 1; k < x; k++) ///configuratii
        for(int i = 0; i < n; i++)  ///noduri
           if (k & (1<<i))
            {
                for(int j = 0; j < M[i].size(); j++) ///vecini
                    if(k & (1<<(M[i][j].first)))
                    {
                        vecin = M[i][j].first;
                        cost = M[i][j].second;
                        C[k][i] = min(C[k][i], C[k ^(1<<i)][vecin] + cost);
                    }
            }

    int total = inf;
    for(int i = 0; i < M[0].size(); i++)
        total = min(total, C[(1<<n)-1][M[0][i].first]+M[0][i].second);

    if(total != inf)
        fout << total;
    else
        fout << "Nu exista solutie";
    return 0;
}