uva225 回溯剪枝

这道题要剪枝,不然会超时,还有就是每次参加过的城市下次不能再参观,不然会WA。
对于障碍物的坐标我用了两种方法,第一种就是直接用STL里面的set,对于判断是否访问过直接用的count,用时960ms;当我把集合换成数组,200ms通过。
用set的AC代码:

#include<cstring>
#include<cstdio>
#include<cmath>
#include<set>
#include<algorithm>
using namespace std;
const int maxn=300;
int dx[]={1,0,0,-1,5};
int dy[]={0,1,-1,0,5}; //east,north,south,west
char dir[]="ensw";
int vis[maxn][maxn];
int n,cnt;
struct node{
    int x,y;
    node(int x=0,int y=0):x(x),y(y){}
    bool operator < (const node &p) const{
        return x>p.x||(x==p.x&&y>p.y);
    }
};
set<node>u;

void dfs(int *a,int cur,int d,node pos){
    if(cur==n&&pos.x==150&&pos.y==150){
        cnt++;
        for(int i=0;i<n;++i) printf("%c",dir[a[i]]);
        printf("\n");
        return;
    }
    if(cur>=n) return;
    if((abs(pos.x-150)+abs(pos.y-150))>((n-cur)*(n+cur+1)/2)) return; //cut
    for(int i=0;i<4;++i){
        if(dx[i]==dx[d]||dy[i]==dy[d]) continue;
        int newx=pos.x+(cur+1)*dx[i],newy=pos.y+(cur+1)*dy[i];
        if(vis[newx][newy]) continue; //已经旅游过
        int flag=0,c,p;
        if(newx==pos.x){
            c=min(newy,pos.y),p=max(newy,pos.y);
            for(int k=c;k<=p;++k){
                node newc(newx,k);
                if(u.count(newc)) {flag=1;break;}
            }
        }
        else if(newy==pos.y){
            c=min(newx,pos.x),p=max(newx,pos.x);
            for(int k=c;k<=p;++k){
                node newc(k,newy);
                if(u.count(newc)) {flag=1;break;}
            }
        }
        if(flag) continue;
        a[cur]=i;
        vis[newx][newy]=1;
        dfs(a,cur+1,i,node(newx,newy));
        vis[newx][newy]=0;
    }
}

int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        memset(vis,0,sizeof(vis));
        int k;
        scanf("%d%d",&n,&k);
        int x,y;
        for(int i=0;i<k;++i){
            scanf("%d%d",&x,&y);
            u.insert(node(x+150,y+150)); //障碍物坐标保存
        }
        cnt=0;
        int a[25];
        dfs(a,0,4,node(150,150));
        printf("Found %d golygon(s).\n\n",cnt);
        u.clear();
    }
    return 0;
}

用数组的AC代码:

#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn=300;
int dx[]={1,0,0,-1,5};
int dy[]={0,1,-1,0,5}; //east,north,south,west
char dir[]="ensw";
int vis[maxn][maxn],def[maxn][maxn];
int n,cnt;
struct node{
    int x,y;
    node(int x=0,int y=0):x(x),y(y){}
    bool operator < (const node &p) const{
        return x>p.x||(x==p.x&&y>p.y);
    }
};

void dfs(int *a,int cur,int d,node pos){
    if(cur==n&&pos.x==150&&pos.y==150){
        cnt++;
        for(int i=0;i<n;++i) printf("%c",dir[a[i]]);
        printf("\n");
        return;
    }
    if(cur>=n) return;
    if((abs(pos.x-150)+abs(pos.y-150))>((n-cur)*(n+cur+1)/2)) return; //cut
    for(int i=0;i<4;++i){
        if(dx[i]==dx[d]||dy[i]==dy[d]) continue;
        int newx=pos.x+(cur+1)*dx[i],newy=pos.y+(cur+1)*dy[i];
        if(vis[newx][newy]) continue; //已经旅游过
        int flag=0,c,p;
        if(newx==pos.x){
            c=min(newy,pos.y),p=max(newy,pos.y);
            for(int k=c;k<=p;++k){
                node newc(newx,k);
                if(def[newx][k]) {flag=1;break;}
            }
        }
        else if(newy==pos.y){
            c=min(newx,pos.x),p=max(newx,pos.x);
            for(int k=c;k<=p;++k){
                node newc(k,newy);
                if(def[k][newy]) {flag=1;break;}
            }
        }
        if(flag) continue;
        a[cur]=i;
        vis[newx][newy]=1;
        dfs(a,cur+1,i,node(newx,newy));
        vis[newx][newy]=0;
    }
}

int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        memset(vis,0,sizeof(vis));
        memset(def,0,sizeof(def));
        int k;
        scanf("%d%d",&n,&k);
        int x,y;
        for(int i=0;i<k;++i){
            scanf("%d%d",&x,&y);
            def[x+150][y+150]=1;
        }
        cnt=0;
        int a[25];
        dfs(a,0,4,node(150,150));
        printf("Found %d golygon(s).\n\n",cnt);
    }
    return 0;
}

如有不当之处欢迎指出!

转载于:https://www.cnblogs.com/flyawayl/p/8305565.html

<think>好的,我现在需要帮助用户了解回溯算法中的剪枝技术及其实现和优化方法。首先,我需要回忆一下回溯算法的基本概念和剪枝的作用。回溯算法是一种通过试错来寻找问题解决方法的算法,当发现当前路径无法得到有效解时,会退回上一步重新选择,这种思想常被用于解决组合、排列、子集等问题。 接下来,剪枝技术是为了减少不必要的搜索路径,提升算法效率。用户提到想了解剪枝的实现和优化方法,我需要详细说明这一点。可能包括常见的剪枝策略,比如可行性剪枝、最优性剪枝、重复性剪枝等,并且结合具体例子来说明这些技术是如何应用的。 同时,用户提供的引用资料中提到回溯算法通过剪枝减少搜索空间,提高效率。我需要引用这些内容来支持我的回答,确保信息的准确性。例如,引用[1]中提到的优化方法和剪枝技巧,引用[2]中关于回溯在DFS和BFS中的应用。 然后,我需要考虑如何结构清晰地组织回答。可能分为几个部分:回溯算法原理、剪枝技术的分类实现、优化方法、代码示例,以及相关问题。这样用户能够逐步理解,从基础到应用。 在代码示例部分,选择一个经典的问题,比如全排列或子集生成,来展示回溯剪枝的具体实现。需要注意使用Python代码,并确保语法正确,同时添加注释解释关键步骤,特别是剪枝的地方。 此外,用户要求生成相关问题,我需要根据内容提出几个相关的问题,帮助用户进一步学习,比如剪枝技术的分类、优化方法的应用场景等。 最后,检查是否符合用户给出的格式要求:行内公式用$...$,独立公式用$$...$$,正确的中文回答,引用标识的添加,以及代码块的正确格式。确保没有使用Markdown,所有内容自然流畅。</think>### 回溯算法剪枝技术详解 #### 1. 回溯算法原理 回溯算法是一种通过**深度优先搜索(DFS)**遍历解空间的方法,适用于组合、排列、子集等需要穷举可能性的问题。其核心步骤为: - **选择路径**:逐步构建候选解。 - **约束条件**:若当前路径不满足条件(如重复元素、超出限制),则**剪枝**。 - **回溯**:撤销最后一步选择,尝试其他路径。 例如,全排列问题中,回溯算法通过递归生成所有可能的排列,并通过剪枝跳过重复元素。 #### 2. 剪枝技术的分类实现 剪枝的核心目标是**减少无效搜索**,常见类型包括: 1. **可行性剪枝**:提前终止不满足约束条件的路径。 - 例:在$0$-$1$背包问题中,若当前物品总重量超过背包容量,则停止搜索。 2. **最优性剪枝**:放弃无法得到更优解的路径。 - 例:在旅行商问题中,若当前路径长度已超过已知最短路径,则剪枝。 3. **重复性剪枝**:避免重复搜索相同状态。 - 例:全排列问题中,若元素相同且已使用过,则跳过,避免重复排列[^2]。 #### 3. 优化方法 - **预处理排序**:对输入数据排序,便于快速剪枝(如跳过重复元素)。 - **记忆化搜索**:缓存已计算状态,避免重复计算。 - **双向回溯**:同时从起点和终点搜索,缩小解空间。 #### 4. 代码示例:全排列(含剪枝) ```python def permute(nums): def backtrack(path, used): if len(path) == len(nums): res.append(path.copy()) return for i in range(len(nums)): if used[i] or (i > 0 and nums[i] == nums[i-1] and not used[i-1]): continue # 剪枝:跳过已使用或重复元素 used[i] = True path.append(nums[i]) backtrack(path, used) path.pop() used[i] = False nums.sort() # 预处理排序以优化剪枝 res = [] backtrack([], [False]*len(nums)) return res # 示例:输入[1,1,2],输出[[1,1,2],[1,2,1],[2,1,1]] ``` #### 5. 性能分析 - **时间复杂度**:剪枝可将复杂度从$O(n!)$降低到$O(k \cdot n)$($k$为有效解数量)[^1]。 - **空间复杂度**:主要取决于递归深度,通常为$O(n)$。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值