我有三个堆栈和数字,我只需要尝试所有分发选项。我会为每个选项计算并检查它是否符合我的要求。
示例:3个数字:1 2 3 123 || 12 | 3 | 12 || 3 1 | 23 | 1 || 23 ...
编辑:添加代码:
int array[] = { 1,2,3 };
int stackA[10];
int stackB[10];
int stackC[10];
...
printf("stackA contains 123, stackB contains, stackC contains");
printf("stackA contains 12, stackB contains 3, stackC contains");
printf("stackA contains 12, stackB contains, stackC contains 3");
答案 0 :(得分:1)
编辑:这是一个用于计算所有可能性的工作C代码:
#include <stdio.h>
#include <stdlib.h>
/* exponentiation: base b, exponent n */
int power(int b, unsigned int n)
{
int result = 1;
while (n != 0)
{
if ((n & 1) == 1)
{
result *= b;
}
n = n >> 1;
b *= b;
}
return result;
}
void print_instance_of_solution_set(int* a, char** stack, int number_of_stacks, unsigned int number_of_elements)
{
int k, j;
for (k = 0; k < number_of_stacks; k++)
{
printf("Stack %i = { ", k);
for (j = 0; j < number_of_elements; j++)
{
if (stack[k][j] == 1)
{
printf("%i ", a[j]);
}
}
printf("}; ");
}
printf("\n");
}
int main()
{
/* configuration parameters */
const int number_of_stacks = 3;
const unsigned int number_of_elements = 5;
int a[] = { 0, 2, 4, 6, 8 }; /* has to contain number_of_elements elements */
/* other variables */
int i, j, k;
int total_count;
char** stack;
/* allocate memory for stacks */
stack = (char**)malloc(number_of_stacks*sizeof(char*) + number_of_stacks*number_of_elements*sizeof(char));
if (stack == 0)
{
fprintf(stderr, "Memory allocation error!\n");
return -1;
}
for (i = 0; i < number_of_stacks; i++)
{
stack[i] = (char*)stack + number_of_stacks*sizeof(char*) + i*number_of_elements*sizeof(char);
}
/* calculate cardinality of solution set */
/* the cardinality of solution set is number_of_stacks raised to the power number_of_elements */
total_count = power(number_of_stacks, number_of_elements);
/* iterate over all instances */
for (i = 0; i < total_count; i++)
{
int tmp = i;
for (j = 0; j < number_of_elements; j++)
{
for (k = 0; k < number_of_stacks; k++)
{
stack[k][j] = (k == tmp % number_of_stacks) ? 1 : 0;
}
tmp /= number_of_stacks;
}
/* output of stack elements */
print_instance_of_solution_set(a, stack, number_of_stacks, number_of_elements);
}
return 0;
}