Staram się rozwiązać problem komiwojażera. Mam DFSa, który szuka najkrótszej ścieżki. Poniżej zamieszczam kod. Czy macie pomysł na wcześniejsze ucięcie części wywołań?
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <cassert>
#include <map>
#include <string>
#include <vector>
#include <set>
#include <queue>
#include <cstring>
#define debug(fmt,...) fprintf(stderr,fmt,##__VA_ARGS__)
using namespace std;
//--------------------------------------------------------------------------------------------------------------------------
struct vertex
{
short unsigned int neighbour, weight;
vertex (short unsigned int a, short unsigned int b)
{
neighbour=a;
weight=b;
}
};
bool operator< (vertex a, vertex b)
{
return a.weight<b.weight;
}
short unsigned int n, m, level=0;
unsigned int min_way=(1<<25), act_way=0, add_weight, infty=(((unsigned int)1<<31)-1);
map<string, short unsigned int>M;
vector<vertex>G[100];
bool visited[100], t[100];
//--------------------------------------------------------------------------------------------------------------------------
void DFS_CONNECT(short unsigned int v)
{
t[v]=true;
for (unsigned int i=0; i<G[v].size(); i++)
if (!t[G[v][i].neighbour])
DFS_CONNECT(G[v][i].neighbour);
}
bool CZYSIEDA (short unsigned int v)
{
memcpy(t, visited, n*sizeof(bool));
DFS_CONNECT(v);
for(int i=0; i<n; i++)
if(t[i]==false)
return false;
return true;
}
void READ()
{
scanf("%hu %hu ", &n, &m);
char tmp1[50], tmp2[50];
short int tmpint;
for (short unsigned int i=0; i<n; i++)
{
scanf(" %s ", tmp1);
M.insert(make_pair(string(tmp1), i));
visited[i]=false;
}
short int _1, _2;
for (short unsigned int i=0; i<m; i++)
{
scanf(" %s %s %hu", tmp1, tmp2, &tmpint);
_1=M.find(string(tmp1))->second;
_2=M.find(string(tmp2))->second;
G[_1].push_back(vertex(_2, tmpint));
G[_2].push_back(vertex(_1, tmpint));
}
for(short unsigned int i=0; i<n; i++)
sort(G[i].begin(), G[i].end());
}
void DFS(short unsigned int v)
{
if (act_way>=min_way || act_way*n>min_way*level+add_weight || !CZYSIEDA(v))
return;
visited[v]=true;
if (level==n-1)
{
for (unsigned int i=0; i<G[v].size(); i++)
if (G[v][i].neighbour==0)
{
min_way=min(min_way, act_way+G[v][i].weight);
debug("nowe minimum: %d z wierzchołka %d\n", min_way, v);
break;
}
}
else
{
level++;
for (unsigned int i=0; i<G[v].size(); i++)
if(!visited[G[v][i].neighbour])
{
act_way+=G[v][i].weight;
DFS(G[v][i].neighbour);
act_way-=G[v][i].weight;
}
level--;
}
visited[v]=false;
}
void ADD_WEIGHT()
{
min_way=(1<<20);
add_weight=50*n+4000;
debug("2*MST = %d, add_weight = %d\n", min_way, add_weight);
}
int main ()
{
READ();
ADD_WEIGHT();
debug("rozpoczęto wyszukiwanie ścieżki\n");
DFS(0);
printf("%d\n", min_way);
}
Dziękuję za wszelkie wskazówki.