Pagini recente » Cod sursa (job #1779916) | Cod sursa (job #705920) | Cod sursa (job #2299979) | Cod sursa (job #1336138) | Cod sursa (job #1631333)
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
#define INF 0x3f3f3f3f
using namespace std;
ifstream is("hamilton.in");
ofstream os("hamilton.out");
using VI = vector<int>;
using VVI = vector<VI>;
using VP = vector<pair<int, int>>;
using VVP = vector<VP>;
using VPP = vector<pair<int, pair<int, int>>>;
int n, m, answ = INF;
VVI g, c, h;
queue<pair<int, pair<int, int>>> q;
void Read();
int main()
{
Read();
h = VVI(n, VI(1 << n, INF));
h[0][1] = 0;
q.push(make_pair(0, make_pair(0, 1))); // cost, nod, mask
int cost, nod, mask;
while ( !q.empty() )
{
nod = q.front().second.first;
mask = q.front().second.second;
cost = q.front().first;
q.pop();
if ( h[nod][mask] > answ || cost > h[nod][mask] )
continue;
if ( mask == ( 1 << n ) - 1 )
{
answ = min(answ, h[nod][(1 << n) - 1] + c[nod][0]);
continue;
}
for ( const auto &nodv : g[nod] )
if ( !( mask & ( 1 << nodv) ) )
if ( h[nodv][mask | ( 1 << nodv )] > h[nod][mask] + c[nod][nodv] )
{
h[nodv][mask | ( 1 << nodv )] = h[nod][mask] + c[nod][nodv];
q.push(make_pair(h[nodv][mask | ( 1 << nodv )], make_pair(nodv, mask | ( 1 << nodv ))));
}
}
if ( answ == INF )
os << "Nu exista solutie";
else
os << answ;
is.close();
os.close();
return 0;
}
void Read()
{
is >> n >> m;
g = VVI(n);
c = VVI(n, VI(n, INF));
int x, y, z;
for ( int i = 1; i <= m; ++i )
{
is >> x >> y >> z;
g[x].push_back(y);
c[x][y] = z;
}
}