Cod sursa(job #1482717)

Utilizator dnprxDan Pracsiu dnprx Data 7 septembrie 2015 19:55:08
Problema Ciclu hamiltonian de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.06 kb
#include <bits/stdc++.h>
#define infinit 1000000000

using namespace std;

struct Nod
{
    int nod, st, cost;
    bool operator < (const Nod& e) const
	{
        return cost > e.cost;
    }
};

vector <int> h[22];
int n;
int best[22][262150], mat[22][22];
/// best[i,j]=costul minim al unui drum de la nodul 0 la nodul i,
///    trecand prin "starea" j (18 valori binare)

void Citire()
{
    int i, x, y, cost, m;
    ifstream fin("hamilton.in");
    fin >> n >> m;
    for (x = 0; x < n; x++)
        for (y = 0; y < n; y++)
            mat[x][y] = infinit;
    for (i = 1; i <= m; ++i)
    {
        fin >> x >> y >> cost;
        mat[x][y] = cost;
        h[x].push_back(y);
    }
    fin.close();
}

void Rezolva()
{
    priority_queue <Nod> q;
    Nod w, w1;
    int i, k, stare, stare1, cost, X;
    unsigned int j;
    X = (1 << n) - 1;
    for (i = 0; i < n; i++)
        for (j = 0; j <= X; j++)
            best[i][j] = infinit;
    best[0][1] = 0;
    w.nod = 0;
    w.cost = 0;
    w.st = 1;
    q.push(w);
    while (!q.empty())
    {
        w = q.top();
        k = w.nod;
        stare = w.st;
        q.pop();
        for (j = 0; j < h[k].size(); j++)
        {
            i = h[k][j]; /// arcul (k,i)
            cost = mat[k][i];
            if ((stare & (1 << i)) == 0) /// n-am mai trecut prin nodul i
            {
                stare1 = (stare | (1 << i));
                if (best[i][stare1] > best[k][stare] + cost)
                {
                    best[i][stare1] = best[k][stare] + cost;
                    w1.nod = i;
                    w1.st = stare1;
                    w1.cost = best[i][stare1];
                    q.push(w1);
                }
            }
        }
    }
    cost = infinit;
    for (i = 1; i < n; i++)
        cost = min(cost, best[i][X] + mat[i][0]);
    ofstream fout("hamilton.out");
    if (cost == infinit) fout << "Nu exista solutie\n";
    else fout << cost << "\n";
    fout.close();
}

int main()
{
    Citire();
    Rezolva();
    return 0;
}