Pagini recente » Istoria paginii runda/chestie/clasament | tema | Cod sursa (job #675556) | Cod sursa (job #498103) | Cod sursa (job #2429983)
#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;
}