Cod sursa(job #1628360)

Utilizator radarobertRada Robert Gabriel radarobert Data 3 martie 2016 23:25:21
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.8 kb
#include <cstdio>
#include <queue>
#include <algorithm>
#include <iostream>

using namespace std;

const int INF = 0x3f3f3f3f;

queue< pair<int, int> > q;
int g[20][20], cost[20][20];
int c[18][262144];
bool in_queue[20][262144];

int main()
{
    freopen("hamilton.in", "r", stdin);
    freopen("hamilton.out", "w", stdout);

    int n, m;
    scanf("%d%d", &n, &m);
    for (int i = 1, x, y; i <= m; i++)
    {
        scanf("%d%d", &x, &y);
        scanf("%d", &cost[x][y]);
        g[x][++g[x][0]] = y;
    }

    int sol = INF;

    int full = (1<<n)-1;
    c[0][1] = 1;
    q.push(make_pair(0, 1));
    int node, new_config;
    while (!q.empty())
    {
        int last = q.front().first;
        int config = q.front().second;
        q.pop();
        in_queue[last][config] = false;
        for (int i = 1; i <= g[last][0]; i++)
            if (!(config & (1<<g[last][i])))
            {
                node = g[last][i];
                new_config = config | (1<<node);
                if (c[node][new_config] == 0 || c[node][new_config] > c[last][config] + cost[last][node])
                {
                    c[node][new_config] = c[last][config] + cost[last][node];
                    if (new_config == full)
                    {
                        if (cost[node][0] != 0)
                            sol = min(sol, c[node][new_config] + cost[node][0]);
                    }
                    else if (!in_queue[node][new_config])
                    {
                        in_queue[node][new_config] = true;
                        q.push(make_pair(node, new_config));
                    }
                }
            }
    }

    if (sol == INF)
        printf("Nu exista solutie\n");
    else
        printf("%d\n", sol-1);

    return 0;
}