Pagini recente » Cod sursa (job #509123) | Cod sursa (job #839538) | Cod sursa (job #426290) | Cod sursa (job #124703) | Cod sursa (job #2355400)
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("hamilton.in");
ofstream fout("hamilton.out");
const int NR=20;
const int VAL=(1 << 18)+5;
const int INF=2000000000;
int N, M, i, j, cost, A, B, C, conf;
int dp[NR][VAL], mch[NR][NR], ANS;
bool ok[NR][VAL];
bool gasit;
vector <int> Ginv[NR];
vector <int> :: iterator it;
int main()
{
fin >> N >> M;
for (i=1; i<=M; i++)
{
fin >> A >> B >> C;
mch[A][B]=C;
Ginv[B].push_back(A);
}
ok[0][1]=true;
for (conf=1; conf<(1 << N); conf++)
{
for (i=0; i<N; i++)
{
if ((conf & (1 << i))==0)
continue;
for (it=Ginv[i].begin(); it!=Ginv[i].end(); it++)
{
if (ok[*it][conf-(1 << i)]==true)
{
ok[i][conf]=true;
cost=dp[*it][conf-(1 << i)];
if (dp[i][conf]==0)
dp[i][conf]=cost+mch[*it][i];
else
dp[i][conf]=min(dp[i][conf], cost+mch[*it][i]);
}
}
}
}
ANS=INF;
for (i=0; i<N; i++)
if (ok[i][(1 << N)-1]==true && mch[i][0]!=0)
ANS=min(ANS, dp[i][(1 << N)-1]+mch[i][0]);
if (ANS==INF)
fout << "Nu exista solutie";
else
fout << ANS << '\n';
fin.close();
fout.close();
return 0;
}