微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我遇到的一个问题要求我们使用回溯样式算法来解决。我根据给定的解决方案写了一个类似的问题,但是我需要更快(在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 举报,一经查实,本站将立刻删除。