ACAG 0x02-8 non-recursive combinatorial enumeration

ACAG 0x02-8 non-recursive combinatorial enumeration

The reason why this question specifically to write the blog, is because it feels recursively learned from the machine at the most fundamental realization.
The main thing two instructions - Call and Ret .
Call instructions will return address stack (stack system), then jumps to \ (address \) statement position.
Ret instruction is a return instruction (the Return), the return address from the stack, and jumps to the position to continue.
In summary, you can get a combination of non-recursive type enumeration realized.

#include<bits/stdc++.h>

using namespace std;

int n,m,top,address;
int sta[100010];

vector <int> v;

void Call(int x,int ret_addr) {
    int old_top=top;
    sta[++top]=x;
    sta[++top]=ret_addr;
    sta[++top]=old_top;
    return;
}

int Ret() {
    int ret_addr=sta[top-1];
    top=sta[top];
    return ret_addr;
}

void Recursive() {
    Call(1,0);
    while(top)  {
        int x=sta[top-2];
        switch(address) {
            case 0:
                if(v.size()>m||v.size()+(n-x+1)<m) {
                    address=Ret();
                    continue;
                }
                if(x==n+1) {
                    for(int i=0;i<v.size();i++) {
                        printf("%d ",v[i]);
                    }
                    printf("\n");
                    address=Ret();
                    continue;
                }
                v.push_back(x);
                Call(x+1,1);
                address=0;
                continue;
            case 1:
                v.pop_back();
                Call(x+1,2);
                address=0;
                continue;
            case 2:
                address=Ret();
                continue;
        }
    }
    return;
}

int main()
{
    scanf("%d%d",&n,&m);
    Recursive();
    return 0;
}

Guess you like

Origin www.cnblogs.com/luoshui-tianyi/p/11979847.html