首页 > 其他 > 详细

题解 非递归实现组合型枚举

时间:2019-12-28 20:47:33      阅读:108      评论:0      收藏:0      [点我收藏+]

题目链接

用栈模拟dfs即可

#include<cstdio>
#include<stack>
using namespace std;
struct state {
    int pos,num,a;//第pos位,当前已有num个数字,用二进制状态压缩进a(省去数组存储)
};
stack<state> s;
int n,m;
int main() {
    scanf("%d%d",&n,&m);
    s.push((state) {
        0,0,0
    });
    while(!s.empty()) {
        state a=s.top();
        s.pop();
        if (a.num+n-a.pos<m) continue;
        if (a.num==m) {
            for (int i=0; i<n; i++)
                if ((a.a>>i)&1) printf("%d ",i+1);
            puts("");
            continue;
        }
        if (a.pos<n) {
            s.push((state) {
                a.pos+1,a.num,a.a
            });
            s.push((state) {
                a.pos+1,a.num+1,a.a|(1<<a.pos)
            });//题目是从小到大输出,所以小的要放在后面,先从栈中取出。这与dfs不太一样
        }
    }
}

题解 非递归实现组合型枚举

原文:https://www.cnblogs.com/Randolph68706/p/12112745.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!