Cod sursa(job #1165337)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 2 aprilie 2014 17:17:35
Problema Ciclu hamiltonian de cost minim Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.81 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <bitset>
#include <string.h>
#include <algorithm>
#include <iomanip>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <set>
#include <map>
#include <string>
#include <queue>
#include <deque>

using namespace std;

const char infile[] = "hamilton.in";
const char outfile[] = "hamilton.out";

ifstream fin(infile);
ofstream fout(outfile);

const int MAXN = 18;
const int oo = 0x3f3f3f3f;

typedef vector<pair<int, int> > Graph[MAXN];
typedef vector<pair<int, int> > :: iterator It;

const inline int min(const int &a, const int &b) { if( a > b ) return b;   return a; }
const inline int max(const int &a, const int &b) { if( a < b ) return b;   return a; }
const inline void Get_min(int &a, const int b)    { if( a > b ) a = b; }
const inline void Get_max(int &a, const int b)    { if( a < b ) a = b; }

int dp[1 << MAXN][MAXN], N, M;
Graph G;

inline int getMinCostHamiltonianCycle(Graph &G, int N) {
    memset(dp, oo, sizeof(dp));
    dp[1][0] = 0;
    const int maxConf = (1 << N);
    for(int conf = 1 ; conf < maxConf ; ++ conf)
        for(int i = 0 ; i < N ; ++ i)
            if(conf & (1 << i))
                for(It it = G[i].begin(), fin = G[i].end(); it != fin ; ++ it)
                    if(conf & (1 << it->first))
                        dp[conf][i] = min(dp[conf][i], dp[conf ^ (1 << i)][it->first] + it->second);
    int ans = oo;
    for(It it = G[0].begin(), fin = G[0].end(); it != fin ; ++ it)
        ans = min(ans, dp[maxConf - 1][it->first] + it->second);
    return ans;
}

int main() {
    fin >> N >> M;
    for(int i = 1 ; i <= M ; ++ i) {
        int x, y, z;
        fin >> x >> y >> z;
        G[y].push_back(make_pair(x, z));
    }
    fout << getMinCostHamiltonianCycle(G, N) << '\n';
    fin.close();
    fout.close();
    return 0;
}