Pagini recente » Cod sursa (job #2523373) | Cod sursa (job #2724164) | Cod sursa (job #3266139) | Cod sursa (job #2229258) | Cod sursa (job #401294)
Cod sursa(job #401294)
using namespace std;
#include<fstream>
#define INFINIT 2147483647
struct nod
{
int vf;
int cost;
nod* next;
};
int n,m,x[20],v[20],c[20][20],cost,costmin=INFINIT;
nod *G[20];
void addarc(int,int,int);
void back(int);
void solutie();
int main()
{
int i,xx,yy,zz;
ifstream fin("hamilton.in");
fin>>n>>m;
for(i=1;i<=m;++i)
{
fin>>xx>>yy>>zz;
addarc(xx,yy,zz);
c[xx][yy]=zz;
}
x[0]=v[1]=1;
back(1);
ofstream fout("hamilton.out");
if(costmin<INFINIT)
fout<<costmin;
else
fout<<"Nu exista solutie";
return 0;
}
void back(int k)
{
nod *p;
if(k==n)
solutie();
else
for(p=G[x[k-1]];p;p=p->next)
if(v[p->vf]==0)
{
x[k]=p->vf;
v[p->vf]=1;
cost+=p->cost;
back(k+1);
cost-=p->cost;
v[p->vf]=0;
}
}
void addarc(int i,int j,int c)
{
nod *p=new nod;
p->vf=j;
p->cost=c;
p->next=G[i];
G[i]=p;
}
void solutie()
{
int i=c[x[n-1]][1];
if(i)
{
cost+=i;
if(cost<costmin)
costmin=cost;
cost-=i;
}
}