【算法学习笔记】16.暴力求解法04 回溯法03 剪枝法 带宽

在之前的 N 皇后和困难的串问题中,回溯法都是在解决可行性约束。换一句话说,对于回溯点的判断是用来验证此点是否合法。

但是在一些优化问题的求解过程中,每一个点都是合法的,所以我们要进行剪枝。

1.先得到一个解。(一般情况下不是最优解,实现细节:用一个极大的数先作为结果。)

2.在回溯的过程中,判断继续进行是否肯定超过最优解。若是,则剪去。

例子:UVa 140 

题意  有一个无向图  对于其所有顶点的一个排列 称一顶点与所有与其有边的其它顶点在排列中下标差的最大值为这个顶点的带宽   而所有顶点带宽的最大值为这个排列的带宽   求这个图带宽最小的排列 

千万要注意题目中对『带宽』二字的定义!!


int linked[10][10]; //to save the edges.
int len=8;//8 numbers
int permutation[10]={0};//the temperoray permutation
int vis[11]={0};//assistant-variable this array is to save whether the i-th node is already used
int bandwidth = 50;//the final bandwidth
int final_permu[10]={0};//final permutation

//cur is the position we just wanna process
//cur_max is the current max bandwidth
void dfs(int cur,int cur_max){
    //at this time, we need to update the bandwidth and save the permutation
    if(cur==len and cur_max<bandwidth){
        bandwidth = cur_max;
        for(int i=0;i<len;i++)
            final_permu[i]=permutation[i];
        return;
    }
    
    for(int i=0;i< len;i++) if(!vis[i]){
        //we need to update the current max (bandwidth)
        for (int j=0; j<cur; j++) {
            if(linked[permutation[j]][i] and (cur-j)>cur_max){
                cur_max = cur-j;
                //this cur_max already include all positions' width
            }
        }
        //if cur_max's greater the bandwidth,we can cut this situition
        if(cur_max>bandwidth)
            return;
        //another test. m is the number of points which is adjcent but not visited
        int m =0;
        for (int j=0; j<len; j++)   if (!vis[j] and linked[i][j])
                m++;
        if(m>=bandwidth)    return;
        //then return.
        permutation[cur]=i;
        vis[i]=true;
        dfs(cur+1,cur_max);
        vis[i]=false;//pay attention to recover the global variable .
    }
    
    return;
}

这里要注意,dfs 有两个参数,第二个参数就是一个临时的用来存储整个『进行排列』的bandwidth 只有它才可以用来和 bandwidth 来进行比较和替换。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值