Exemplo n.º 1
0
main()
{
PATH path;
NODE root = {
0, /* 花费下界 */
{{{I, 1, 2, 7, 5}, /* 花费矩阵 */
  {1, I, 4, 4, 3},
  {2, 4, I, 1, 2},
  {7, 4, 1, I, 3},
  {5, 3, 2, 3, I}}, 5}, /* 城市数目 */
{{0}, 0}, /* 经历过的路径 */
NULL, NULL /* 左枝与右枝 */
};

/* 归约,建立根结点 */
root.bound += Simplify(&root.matrix);
/* 进入搜索循环 */
path = BABA(root);
ShowPath(path, root.matrix);

}
/*
* 算法主搜索函数,Branch-And-Bound Algorithm Search
*            root 是当前的根结点,已归约,数据完善
*/
PATH BABA(NODE root)
{
    int i;
    static int minDist = INFINITY;
    static PATH minPath;
    EDGE selectedEdge;
    NODE *left, *right;

    puts("Current Root:\n------------");
    ShowMatrix(root.matrix);
    printf("Root Bound:%d\n", root.bound);

    /* 如果当前矩阵大小为2,说明还有两条边没有选,而这两条边必定只能有一种组合,
    * 才能构成整体回路,所以事实上所有路线已经确定。
    */
    if (MatrixSize(root.matrix, root.path) == 2) {
        if (root.bound < minDist) {
            minDist = root.bound;
            minPath = MendPath(root.path, root.matrix);
            getch();
            return (minPath);
        }
    }
    /* 根据左下界尽量大的原则选分枝边 */
    selectedEdge = SelectBestEdge(root.matrix);
    printf("Selected Edge:(%d, %d)\n", selectedEdge.head + 1, selectedEdge.tail + 1);

    /* 建立左右分枝结点 */
    left = (NODE *)malloc(sizeof(NODE));
    right = (NODE *)malloc(sizeof(NODE));
    if (left == NULL || right == NULL) {
        fprintf(stderr,"Error malloc.\n");
        exit(-1);
    }
    /* 初始化左右分枝结点 */
    left->bound = root.bound; /* 继承父结点的下界 */
    left->matrix = LeftNode(root.matrix, selectedEdge); /* 删掉分枝边 */
    left->path = root.path; /* 继承父结点的路径,没有增加新边 */
    left->left = NULL;
    left->right = NULL;

    right->bound = root.bound;
    right->matrix = RightNode(root.matrix, selectedEdge, root.path);/* 删除行列和回路边 */
    right->path = AddEdge(selectedEdge, root.path); /* 加入所选边 */
    right->left = NULL;
    right->right = NULL;

    /* 归约左右分枝结点 */
    left->bound += Simplify(&left->matrix);
    right->bound += Simplify(&right->matrix);

    /* 链接到根 */
    root.left = left;
    root.right = right;

    /* 显示到监视器 */
    puts("Right Branch:\n------------");
    ShowMatrix(right->matrix);
    puts("Left Branch:\n-----------");
    ShowMatrix(left->matrix);

    /* 如果右结点下界小于当前最佳答案,继续分枝搜索 */
    if (right->bound < minDist) {
        BABA(*right);
    }
    /* 否则不搜索,因为这条枝已经不可能产生更佳路线 */
    else {
        printf("Current minDist is %d, ", minDist);
        printf("Right Branch's Bound(= %d).\n", right->bound);
        printf("This branch is dead.\n");
    }

    /* 如果右结点下界小于当前最佳答案,继续分枝搜索 */
    if (left->bound < minDist) {
        BABA(*left);
    }
    /* 否则不搜索,因为这条枝已经不可能产生更佳路线 */
    else {
        printf("Current minDist is %d, ", minDist);
        printf("Left Branch's Bound(= %d).\n", left->bound);
        printf("This branch is dead.\n");
    }

    printf("The best answer now is %d\n", minDist);
    return (minPath);
}