第五章作业

1. 回溯算法:问题的所有解决方式可以画成一棵二叉树,然后从左支树开始尝试解决问题。若问题不能解决,则原路返回,从右支树开始解决。这种退一步返回的思想则称为回溯法。

2. 解空间结构

解空间结构即为二叉树,每一层的节点用于考虑左右子树的选择

3. 约束函数:为优化回溯法,提高搜索效率,可以对无效的子树进行剪枝。约束函数就是用于把不满足约束的子树剪掉。

4. 代码:

#include <bits/stdc++.h>

using namespace std;

const int Max = 1e6+9;
const int N = 1e4+9;

typedef long long ll;

int n,m;
int a[N],p[N];
int sum,rest;

bool backliu(int x){
    if(sum==m)return true;
    if(x>=n)return false;
    rest-=a[x];
    if(sum+a[x]<=m){

        sum+=a[x];
        p[x]=1;
        if(backliu(x+1))return true;
        p[x]=0;
        sum-=a[x];
    }
    if(sum+rest>=m){
        if(backliu(x+1))return true;
    }
    rest+=a[x];
    return false;
}


int main(){
    cin>>n>>m;
    for(int i=0;i<n;i++){
        cin>>a[i];rest+=a[i];
    }
    if(backliu(0)){
        for(int i=0;i<n;i++){
            if(p[i])cout<<a[i]<<" ";
        }
    }
    else cout<<"No Solution!"<<endl;
}

5. 结对编程的感想:有些问题不太懂,比如约束函数的使用,跟搭档讨论之后有了更深一步的了解。

posted @ 2018-12-23 16:56  豪哥的博客  阅读(87)  评论(0编辑  收藏  举报