Cod sursa(job #1622519)

Utilizator bogdanboboc97Bogdan Boboc bogdanboboc97 Data 1 martie 2016 12:02:02
Problema Ciclu hamiltonian de cost minim Scor 15
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <iostream>
#include <vector>
#include <algorithm>
#include <limits>
#include <numeric>
#include <cstring>
#include <string>
#include <queue>
#include <set>
#include <fstream>
#define pb push_back
#define mp make_pair
#define INF numeric_limits<int>::max()
#define bit(x) (-x)&x
#define int64 long long
using namespace std;
ifstream in("hamilton.in");
ofstream out("hamilton.out");
int d[19][19],dp[1<<19][19],n;
int solve(int start)
{
    for(int k=0;k<(1<<n);k++)
    for(int i=0;i<n;i++)
        dp[k][i]=INF;
    for(int i=0;i<n;i++)
        if(i!=start)
        dp[1<<i][i]=d[start][i];
    for(int k=0;k<(1<<n);k++)
    for(int i=0;i<n;i++)
    if(dp[k][i]!=INF)
    {
        for(int t=0;t<n;t++)
            if((k&(1<<t))==0 && d[i][t])
                dp[k|(1<<t)][t]=min(dp[k][i]+d[i][t],dp[k|(1<<t)][t]);
    }
    return dp[(1<<n)-1][start];
}
int main()
{
    int m;
    in>>n>>m;
    for(;m;m--)
    {
        int x,y,z;
        in>>x>>y>>z;
        d[x][y]=z;
    }
    for(int i=0;i<n;i++)
    if(solve(i)!=INF)
    {
        out<<solve(i)<<'\n';
        break;
    }
    return 0;
}