Cod sursa(job #1216250)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 3 august 2014 21:52:54
Problema Ciclu hamiltonian de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.53 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 = 16;
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; }

class DirectedGraph {
public:
    DirectedGraph () {
    }
    DirectedGraph(int N) {
        g.resize(N);
        gt.resize(N);
        dp.resize((1 << N), vector <int>(N, oo));
        n = N;
    }
    void addEgde(int x, int y, int c = 0) {
        g[x].push_back(make_pair(y, c));
    }
    void addReverseEdge(int x, int y, int c = 0) {
        gt[y].push_back(make_pair(x, c));
    }
    int getHamiltonianCycle() {
        /// dp[conf][i]
        dp[1][0] = 0;
        for(int conf = 1; conf < (1 << n) ; ++ conf)
            for(int i = 0 ; i < n ; ++ i)
                if(conf & (1 << i))
                    for(It it = gt[i].begin(), fin = gt[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);
        /// now i have to go from
        int ans = oo;
        for(It it = gt[0].begin(), fin = gt[0].end(); it != fin ; ++ it)
            ans = min(ans, dp[(1 << n) - 1][it->first] + it->second);
        return ans;
    }
private:
    vector <vector <pair<int, int> > > g;
    vector <vector <pair<int, int> > > gt;
    vector <vector <int> > dp;
    int n;
} G;

int main() {
    cin.sync_with_stdio(false);
    int n, m;
    fin >> n >> m;
    G = DirectedGraph(n);
    for(int i = 1 ; i <= m ; ++ i) {
        int x, y, c;
        fin >> x >> y >> c;
        G.addReverseEdge(x, y, c);
    }
    int ans = G.getHamiltonianCycle();
    if(ans == oo)
        fout << "Nu exista solutie";
    else fout << ans << '\n';
    fin.close();
    fout.close();
    return 0;
}