在之前的 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 来进行比较和替换。