The application of backtracking

solider:5
can:2
horse:4
warrior:0
car:1

The codes:

// using backtracking method
# include <iostream>
# include <iomanip>
# include <cstring>
using namespace std;
int main()
{
    //a:兵;b:炮; c:马;d:卒;e:车
    bool flag[10];
    memset(flag, 0, sizeof(flag));
    for (int a = 1; a < 10; a++){
        flag[a] = true;
        for(int b = 0; b < 10; b++){
            flag[b] = true;
            for(int c = 0; c < 10; c++){
                flag[c] = true;
                for(int d = 0; d < 10; d++){
                    flag[d] = true;
                    for(int e = 0; e < 10; e++){
                        flag[e] = true;
                        int m = a * 1000 + b * 100 + c * 10 + d;
                        int n = a * 1000 + b * 100 + e * 10 + d;
                        int s = e *10000 + d * 1000 + c * 100 + a * 10 + d;
                        if (m + n == s){
                            cout << "solider:"<< a << endl;
                            cout << "can:" << b << endl;
                            cout << "horse:" << c << endl;
                            cout << "warrior:" << d << endl;
                            cout << "car:" << e << endl; 
                        }
                        flag[e] = false;
                    }
                    flag[d] = false;
                }
                flag[c] = false;
            }
            flag[b] = false;
        }
        flag[a] = false;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_38396940/article/details/121329463