如何加快回溯算法的速度?

问题描述

我遇到的一个问题要求我们使用回溯样式算法来解决。我根据给定的解决方案写了一个类似的问题,但是我需要更快(在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 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,k);
        }
    }
}

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

    solution_count = 0;
    backtracking (bishops,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;
}

有人可以帮我加快速度吗?有没有更好的方法可以更快地消除更多候选解决方案?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)