C++ 如何加速回溯算法?

C++ 如何加速回溯算法?,c++,backtracking,recursive-backtracking,C++,Backtracking,Recursive Backtracking,我遇到的一个问题要求我们使用回溯式算法来解决。我根据一个类似问题的给定解决方案编写了一个,但我需要更快(在3秒内运行所有测试用例) 问题陈述如下: 给定两个数字n和k,确定可以放置k个主教的方式的数量 在n×n的棋盘上,这样就不会有两个人处于攻击位置 输入文件可能包含多个测试用例。每一个测试用例占用一行代码 输入文件,包含两个整数n(1≤ N≤ 8) 和k(0)≤ K≤ n2)。 包含两个零的测试用例终止输入 以下是我到目前为止的情况: #include <iostream> #in

我遇到的一个问题要求我们使用回溯式算法来解决。我根据一个类似问题的给定解决方案编写了一个,但我需要更快(在3秒内运行所有测试用例)

问题陈述如下:

给定两个数字n和k,确定可以放置k个主教的方式的数量 在n×n的棋盘上,这样就不会有两个人处于攻击位置

输入文件可能包含多个测试用例。每一个测试用例占用一行代码 输入文件,包含两个整数n(1≤ N≤ 8) 和k(0)≤ K≤ n2)。 包含两个零的测试用例终止输入

以下是我到目前为止的情况:

#include <iostream>
#include <algorithm>

using namespace std;

#define MAXN 8

long long solution_count;

void construct_candidates (int bishops [], int c, int n, int candidates [],
    int * ncandidates)
{
    bool legal_move;

    int start = 0;
    if (c)
        start = bishops [c-1];

    * ncandidates = 0;
    for (int p = start; p <n * n; p ++)
    {
        legal_move = true;

        for (int j = 0; j <c; j ++)
            if (abs (bishops [j]/n-p/n) ==
                abs (bishops [j]% n-p% n))
            {
                legal_move = false;
                break;
            }

        if (legal_move == true)
            candidates [(* ncandidates) ++] = p;
    }
}

void backtracking (int bishops [], int c, int n, int k)
{
    if (c == k)
        solution_count ++;
    else
    {
        int ncandidates;
        int candidates [MAXN * MAXN];

        construct_candidates (bishops, c, n, candidates, & ncandidates);

        for (int i = 0; i <ncandidates; i ++)
        {
            bishops [c] = candidates [i];
            backtracking (bishops, c + 1, n, k);
        }
    }
}

long long little_bishops_by_backtracking (int n, int k)
{
    int bishops [2 * (MAXN-1) + 1];

    solution_count = 0;
    backtracking (bishops, 0, n, k);

    return solution_count;
}

int main (int ac, char * av [])
{
    int n, k;

    while (cin >> n >> k, n || k)
        cout << little_bishops_by_backtracking (n, k) << endl;

    return 0;
}
#包括
#包括
使用名称空间std;
#定义MAXN 8
长-长溶液计数;
void构造_候选者(int主教[],int c,int n,int候选者[],
int*NCADATES)
{
布尔法律行动;
int start=0;
如果(c)
start=主教[c-1];
*ncandidates=0;
对于(int p=start;p>k,n | | k)

如果您获得TLE(超过时间限制),则不能如果有正确的解决方案,则通常需要改变方法。速度优化不太可能确保执行速度足够快,这是时间限制的目的,他们从不检查速度优化,而是检查正确的方法。避免模拟,而是寻找数学解。是吗顺便说一句,与N皇后问题的解决方案相比,我是基于N皇后问题的回溯解决方案。我不允许使用数学/组合方法。我必须用回溯算法得到公认的结论,但到目前为止,我没有看到在时间限制内做到这一点的方法。