Cod sursa(job #1631330)

Utilizator AdrianaMAdriana Moisil AdrianaM Data 5 martie 2016 15:02:41
Problema Ciclu hamiltonian de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <set>
#define INF 0x3f3f3f3f
using namespace std;

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

using VI = vector<int>;
using VVI = vector<VI>;
using VP = vector<pair<int, int>>;
using VVP = vector<VP>;
using VPP = vector<pair<int, pair<int, int>>>;

int n, m, answ = INF;
VVI g, c, h;
set<pair<int, pair<int, int>>> q;

void Read();

int main()
{
    Read();
    h = VVI(n, VI(1 << n, INF));
    h[0][1] = 0;
    q.insert(make_pair(0, make_pair(0, 1))); // cost, nod, mask
    int nod, mask;
    while ( !q.empty() )
    {
        nod = q.begin()->second.first;
        mask = q.begin()->second.second;
        q.erase(q.begin());
        if ( h[nod][mask] > answ )
            continue;
        if ( mask == ( 1 << n ) - 1 )
        {
            answ = min(answ, h[nod][(1 << n) - 1] + c[nod][0]);
            continue;
        }
        for ( const auto &nodv : g[nod] )
            if ( !( mask & ( 1 << nodv) ) )
                if ( h[nodv][mask | ( 1 << nodv )] > h[nod][mask] + c[nod][nodv] )
                {
                    h[nodv][mask | ( 1 << nodv )] = h[nod][mask] + c[nod][nodv];
                    q.insert(make_pair(h[nodv][mask | ( 1 << nodv )], make_pair(nodv, mask | ( 1 << nodv ))));
                }
    }
    if ( answ == INF )
        os << "Nu exista solutie";
    else
        os << answ;
    is.close();
    os.close();
    return 0;
}

void Read()
{
    is >> n >> m;
    g = VVI(n);
    c = VVI(n, VI(n, INF));
    int x, y, z;
    for ( int i = 1; i <= m; ++i )
    {
        is >> x >> y >> z;
        g[x].push_back(y);
        c[x][y] = z;
    }
}