# include < string >
# include < vector >
using namespace std;
struct node
{
node(node* left1 = NULL, node* right1 = NULL, const int l_cost1 = 0, const int r_cost1 = 0, const string& name1 = "")
:left(left1), right(right1), l_cost(l_cost1), r_cost(r_cost1), name(name1)
{
}
node* left;
int l_cost;
node* right;
int r_cost;
string name;
};
int best_cost = 9999999;
vector< vector* > pathes;
vector * best_path = NULL;
// 采用递归方式求取最近距离!
void find_best_J(node* pnode, int cost, vector* path, const node* pDest)
{
cout << cost << endl;
if (pnode == pDest)
{
if (cost < best_cost)
{
best_cost = cost;
best_path = path;
}
return;
}
if (pnode->left && pnode->right)
{
vector* p1 = new vector(*path);
vector* p2 = new vector(*path);
p1->push_back(pnode->left);
p2->push_back(pnode->right);
pathes.push_back(p1);
pathes.push_back(p2);
find_best_J(pnode->left, cost + pnode->l_cost, p1, pDest);
find_best_J(pnode->right, cost + pnode->r_cost, p2, pDest);
//cout << "new cost left = " << cost + pnode->l_cost << endl;
//cout << "new cost right = " << cost + pnode->r_cost << endl;
}
else
{
node* pp = (pnode->left) ? (pnode->left) : (pnode->right);
int cost_new = cost + ((pnode->left) ? (pp->l_cost) : (pp->r_cost));
//cout << "new cost = " << cost_new << endl;
path->push_back(pp);
find_best_J(pp, cost_new, path, pDest);
}
}
int main()
{
// directly use local object to represent a network, in real case, you need dynamically allocate object
// or using array or file to control to network generation
//
// A B 20
// A C 25
// B E 30
// ...
node J(NULL, NULL, 0, 0, "J");
node G(&J, NULL, 10, 0, "G");
node H(NULL, &J, 0, 35, "H");
node D(&G, NULL, 40, 0, "D");
node E(&H, &G, 25, 5, "E");
node F(NULL, &H, 0, 30, "F");
node B(&E, &D, 30, 10, "B");
node C(&F, &E, 15, 55, "C");
node A(&B, &C, 25, 20, "A");
//-------------------------------------------------------------
vector* p1 = new vector();
p1->push_back(&A);
pathes.push_back(p1);
find_best_J(&A, 0, p1, &J);
for (auto& node1 : *best_path)
{
cout << node1->name << " ";
}
cout << endl;
// delete memory
for (auto& path : pathes)
{
delete path;
}
}