- 论坛徽章:
- 6
|
本帖最后由 dorodaloo 于 2018-02-11 21:09 编辑
审核中... 
大神 how to write destroy function
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct Node {
- unsigned ans;
- struct Node *branch;
- struct Node *node;
- } Node;
- typedef struct {
- unsigned sum;
- Node *node;
- } Table;
- Table *TAB;
- unsigned SUM;
- unsigned CALL;
- unsigned gcd(unsigned, unsigned);
- void calculate(unsigned *, unsigned, unsigned);
- Table calUtil(unsigned *, unsigned, unsigned, unsigned *);
- void print(Node *, unsigned, unsigned *, unsigned);
- void destroy(Node *);
- int main() {
- //unsigned coefficient[] = { 25, 56, 124, 345, 512 };
- //unsigned sum = 23456;
-
- // 5a+10b+25c+50d=200 5 < 10 < 25 < 50
- unsigned coefficient[] = {5, 10, 25, 50};
- unsigned sum = 200;
- unsigned num = sizeof(coefficient) / sizeof(unsigned);
- calculate(coefficient, num, sum);
- }
- unsigned gcd(unsigned m, unsigned n) { return n ? gcd(n, m % n) : m; }
- void destroy(Node *no) {
- /* HOW TO DESTROY? */
- }
- void calculate(unsigned *coefficient, unsigned num, unsigned sum) {
- CALL = 0;
- SUM = sum;
- unsigned Gcd[num];
- Gcd[0] = coefficient[0];
- for (unsigned i = 1; i < num - 1; i++)
- Gcd[i] = gcd(coefficient[i], Gcd[i - 1]);
- TAB = calloc(num * (SUM + 1), sizeof(Table));
- Table ret = calUtil(coefficient, num - 1, sum, Gcd);
- unsigned answer[num];
- printf("SUM = %u\nCOE = ", sum);
- for (int i = 0; i < num; i++) {
- printf("%d ", coefficient[i]);
- }
- printf("\n");
- print(ret.node, num - 1, answer, num);
- printf("COUNT = %u\n", ret.sum);
- printf("CALL = %u\n", CALL);
-
- // HOW TO DESTROY??
- //destroy (ret.node);
- //free (TAB);
- }
- void print(
- Node *no,
- unsigned index,
- unsigned *ans,
- unsigned num) {
-
- if (!no) {
- for (unsigned i = 0; i < num; i++)
- printf("%u ", ans[i]);
- printf("\n");
- }
-
- while (no) {
- ans[index] = no->ans;
- print(no->branch, index - 1, ans, num);
- no = no->node;
- }
- }
- Table calUtil(
- unsigned *coefficient,
- unsigned index,
- unsigned sum,
- unsigned *Gcd) {
-
- CALL++;
- Table(*tab)[SUM + 1] = (Table(*)[SUM + 1]) TAB;
- if (!index) {
- Node *n = calloc(1, sizeof(Node));
- n->ans = sum / coefficient[index];
- return tab[index][sum] = (Table){1, n};
- }
- Table this = {0};
- unsigned newSum = sum;
- unsigned max = sum / coefficient[index];
- for (unsigned value = 0; value <= max; value++) {
- /* HAS SOLUTION */
- if (newSum % Gcd[index - 1] == 0) {
- Table branch = tab[index - 1][newSum].node
- ? tab[index - 1][newSum]
- : calUtil(coefficient, index - 1, newSum, Gcd);
- if (branch.sum) {
- this.sum += branch.sum;
- Node *node = malloc(sizeof(Node));
- *node = (Node){value, branch.node, this.node};
- this.node = node;
- }
- }
- newSum -= coefficient[index];
- }
- return tab[index][sum] = this;
- }
复制代码
|
|