最优程序问题(BFS)

输入两个整数n1, n2. 用 最少的四则运算从n1得到n2.  例如: 输入2,5, 则 2 / 2 = 1, 1 + 2 = 3, 3 + 2 = 5.  运算结果为 DIV, ADD, ADD.

(好吧我偷懒把题目简化了。。)

 

因为运算步骤可能无限长,本题的解答树是无限大的, 此题不能用回溯来解。本题要求最短过程,利用宽度优先遍历解答树。

 

int n1, n2;
char operators[4][4] = {"ADD","SUB","DIV","MUL"};
int sequence[100];

void bfs() {
    int val[10000];
    int frount = 0, rear = 1;
    val[0] = n1;
    while(frount < rear) {
        int value = val[frount];
        if ( (value + n1) == n2 ) {
            break;
        } else  val[rear++] = value + n1;

        if ( (value - n1) == n2 ) {
            break;
        } else  val[rear++] = value - n1;

        if ( (value / n1) == n2 ) {
            break;
        } else  val[rear++] = value / n1;

        if ( (value * n1) == n2 ) {
            break;
        } else  val[rear++] = value * n1;
        frount ++;
    }
frount
--; sequence[0] = (--rear)%4; int m = 1; while ( frount > 0 ) { sequence[m++] = frount%4;  // 根据最终的rear和frount指针逆序推出运算顺序 frount = (frount/4) -1; } while ( m > 0 ) { printf("%s ",operators[sequence[--m]]); // 从第一步开始输出 } }

 

posted @ 2012-12-09 20:12  tsubasa_wp  阅读(330)  评论(0编辑  收藏  举报