Pagini recente » Cod sursa (job #1336909) | Cod sursa (job #565168) | Cod sursa (job #2472460) | Cod sursa (job #1165316) | Cod sursa (job #2375429)
#include <iostream>
#include <fstream>
#include <vector>
#define nmax 20
using namespace std;
ifstream f("hamilton.in");
ofstream g("hamilton.out");
int n,m, cnt, mn=1e9, viz[nmax], sol[nmax];
vector <pair<int,int> > v[nmax];
void citire()
{
int i,x,y,c;
f>>n>>m;
for(i=1; i<=m; i++)
{
f>>x>>y>>c;
v[x].push_back({y,c});
}
}
void hamilton(int nod, int cnt, int tata, int cst)
{
int next,i,cost;
//sol[cnt]=nod;
if(cnt==n-1)
{
/*for(i=1; i<=cnt; i++)
cout<<sol[i]<<" ";
cout<<endl;*/
for(i=0; i<v[nod].size(); i++)
if(v[nod][i].first==0)
{cst+=v[nod][i].second;
if(mn>cst)
mn=cst;
}cst=0;
}
else
{
for(i=0; i<v[nod].size(); i++)
{
next=v[nod][i].first;
cost=v[nod][i].second;
if(!viz[next])
{
viz[next]=1;
hamilton(next, cnt+1, nod, cst+cost);
viz[next]=0;
}
}
}
}
void hamilton2(int nod, int cnt, int cst)
{
int i,next, cost;
viz[nod]=1;
for(i=0; i<v[nod].size(); i++)
{
next=v[nod][i].first;
cost=v[nod][i].second;
if(!viz[next]) hamilton2(next, cnt+1, cst+cost);
if(cnt==n && next==0) mn=min(mn, cst+cost);
}
viz[nod]=0;
}
int main()
{
citire();
//hamilton(0,0,0,0);
hamilton2(0,1,0);
if(mn==1e9) g<<"Nu exista solutie"<<"\n";
else
g<<mn;
f.close();
g.close();
return 0;
}