Cod sursa(job #2429983)

Utilizator BogBBogdan BogB Data 12 iunie 2019 10:02:30
Problema Generare de permutari Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <cstdint>
#include <vector>
#include <cstdio>

bool findSuccessor(std::vector<int16_t> *stack, uint16_t count) {
    if (stack->back() == count - 1) return false;
    stack->back()++;
    return true;
}

bool validate(std::vector<int16_t> stack) {
    for (uint32_t i = 0; i < stack.size() - 1; i++) {
        if (stack.back() == stack[i]) return false;
    }
    return true;
}

void init(std::vector<int16_t> *stack) {
    stack->push_back(-1);
}

bool isSolution(std::vector<int16_t> stack, uint32_t valueCount) {
    return stack.size() == valueCount;
}

void handleSolution(std::vector<int16_t> stack, std::vector<int32_t> values) {
    for(int16_t index : stack) {
        printf("%d ", values[index]);
    }
    printf("\n");
}

int main() {
    std::vector<int32_t> values;
    uint16_t valueCount;
    scanf("%hu", &valueCount);
    for (uint16_t i = 1; i <= valueCount; i++) {
        values.push_back(i);
    }

    std::vector<int16_t> stack;
    init(&stack);

    while (!stack.empty()) {
        bool hasSuccessor;
        bool isValid;
        do {
            hasSuccessor = findSuccessor(&stack, valueCount);
            if (hasSuccessor) isValid = validate(stack);
            else isValid = false;
        } while (hasSuccessor && !isValid);

        if(isValid) {
            if(isSolution(stack, valueCount)) {
                handleSolution(stack, values);
            } else {
                init(&stack);
            }
        } else {
            stack.pop_back();
        }
    }

    return 0;
}