Pagini recente » Cod sursa (job #906528) | Cod sursa (job #2580771) | Cod sursa (job #1001204) | Cod sursa (job #623771) | Cod sursa (job #2937313)
#include <fstream>
#include <vector>
#include <bitset>
using namespace std;
ifstream in("hamilton.in");
ofstream out("hamilton.out");
#define MAX_VERTICES 18
#define MAX_COST 1000000
#define MAX_STATE 530000
#define INF 1000000000
int n, m, minimCost = MAX_COST * MAX_VERTICES, foundCycle;
vector <vector <pair <int,int> > > graph;
int dp[MAX_VERTICES][MAX_STATE + 1];
bool dpp[MAX_VERTICES][MAX_STATE + 1];
void readGraph()
{
in >> n >> m;
graph.resize(n + 1);
for(int i = 1; i <= m; i ++)
{
int a, b, c;
in >> a >> b >> c;
graph[a].push_back({b, c});
}
}
void printDpp()
{
int stateNo = (1 << n) - 1;
for(int mask = 1; mask <= stateNo; mask ++)
{
for(int i = 0; i < n; i++)
{
out << dpp[i][mask] << " ";
}
out << "\n";
}
}
void hamilton()
{
int startingNode = 0, initialMask, stateNo;
stateNo = (1 << n) - 1;
initialMask = 1 << startingNode;
for(int mask = initialMask; mask <= stateNo; mask ++)
for(int i = 0; i < n; i ++)
dp[i][mask] = INF;
dp[startingNode][initialMask] = 0;
dpp[startingNode][initialMask] = 1;
// printDpp();
for(int mask = initialMask; mask <= stateNo; mask ++)
for(int i = 0; i < n; i ++)
{
if(mask & (1 << i))
for(auto x : graph[i])
{
if((mask & (1 << x.first)) && dpp[i][mask - (1 << x.first)])
{
dpp[x.first][mask] = 1;
dp[x.first][mask] = dp[i][mask - (1 << x.first)] + x.second;
}
}
}
for(int i = 0; i < n; i++)
if(dpp[i][stateNo])
{
for (auto x : graph[i])
if(x.first == startingNode)
{
foundCycle = 1;
minimCost = min(minimCost, dp[i][stateNo] + x.second);
}
}
}
int main()
{
readGraph();
hamilton();
// printDpp();
if(foundCycle)
out << minimCost;
else
out << "Nu exista solutie";
return 0;
}