Programozás‎ > ‎Feladatok‎ > ‎Partíció probléma‎ > ‎Megoldás‎ > ‎

mb_par.c

Letöltés: mb_par.c

#include <stdio.h>
#include <stdlib.h>

void print_array(unsigned int *array, size_t len)
{
size_t i;

for (i = 0; i < len; i++) {
if (i)
printf(" + ");

printf("%u", array[i]);
}

printf("\n");
}

void _part(unsigned int *array, size_t pos, unsigned int rem, unsigned int max)
{
unsigned int i, last;

if (pos)
last = array[pos - 1];
else
last = -1;

for (i = 1; i <= rem; i++) {
if (last < i)
return;

array[pos] = i;

if (i == rem) {
print_array(array, pos + 1);
return;
} else {
_part(array, pos + 1, rem - i, max);
}
}
}

void part(unsigned int num)
{
unsigned int *array;

array = malloc(num * sizeof(unsigned int));
if (!array) {
perror("malloc");
return;
}

_part(array, 0, num, num);

free(array);
}

int main(int argc, char **argv)
{
unsigned int num;

if (argc != 2) {
fprintf(stderr, "Kiirja az szam osszes particioit.\n"
"Usage: %s szam\n", argv[0]);
return 1;
}

num = strtoul(argv[1], NULL, 0);
if (!num) {
fprintf(stderr, "A szam jovolna ha pozitiv volna.\n");
return 1;
}

part(num);

return 0;
}

ċ
mb_par.c
(1k)
Gábor Fehér,
2012. jan. 14. 12:41
Comments