Cod sursa(job #1290608)

Utilizator mirceadinoMircea Popoveniuc mirceadino Data 11 decembrie 2014 15:54:08
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.18 kb
#include<algorithm>
#include<bitset>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<deque>
#include<fstream>
#include<iomanip>
#include<iostream>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<unordered_map>
#include<unordered_set>
#include<utility>
#include<vector>

using namespace std;

#define dbg(x) (cout<<#x<<" = "<<(x)<<'\n')
#ifdef HOME
const string inputFile = "input.txt";
const string outputFile = "output.txt";
#else
const string problemName = "hamilton";
const string inputFile = problemName + ".in";
const string outputFile = problemName + ".out";
#endif // HOME

typedef long long int lld;
typedef pair<int, int> PII;
typedef pair<int, lld> PIL;
typedef pair<lld, int> PLI;
typedef pair<lld, lld> PLL;

const int INF = (1LL << 30) - 1;
const lld LINF = (1LL << 60) - 1;
const int dx[] = {1, 0, -1, 0, 1, -1, 1, -1};
const int dy[] = {0, 1, 0, -1, 1, -1, -1, 1};
const int MOD = 666013;

const int NMAX = 18;
const int MMAX = 100000 + 5;
const int KMAX = 100000 + 5;
const int PMAX = 100000 + 5;
const int LMAX = 100000 + 5;
const int VMAX = 100000 + 5;

int N, M, mask, sol = INF;
int DP[(1 << NMAX) + 5][NMAX + 1];
bool done[(1 << NMAX) + 5][NMAX + 1];
vector<int> Vt[NMAX];
int C[NMAX][NMAX];

int dp(int mask, int x) {
    if(done[mask][x])
        return DP[mask][x];

    if(mask == 1)
        return 0;

    DP[mask][x] = INF;

    for(auto y : Vt[x])
        if(mask & (1 << y))
            DP[mask][x] = min(DP[mask][x], dp(mask ^ (1 << x), y) + C[y][x]);

    done[mask][x] = 1;

    return DP[mask][x];
}

int main() {
    int i, x, y, z;

#ifndef ONLINE_JUDGE
    freopen(inputFile.c_str(), "r", stdin);
    freopen(outputFile.c_str(), "w", stdout);
#endif

    scanf("%d%d", &N, &M);

    while(M--) {
        scanf("%d%d%d", &x, &y, &z);
        Vt[y].push_back(x);
        C[x][y] = z;
    }

    mask = (1 << N) - 1;

    for(i = 1; i < N; i++)
        if(C[i][0])
            sol = min(sol, dp(mask, i) + C[i][0]);

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

    return 0;
}