Guest User

Untitled

a guest
May 27th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. #include <stdio.h>
  2. #define PARTITION_MAX (10)
  3. #define PARTITION_MIN (1)
  4. #define SUCCESS (0)
  5. #define ERR_BASE (0)
  6. #define ERR_INPUT (ERR_BASE-1)
  7. #define ERR_NULL (ERR_BASE-2)
  8.  
  9. void handle_err(int err) {
  10. if(err == ERR_INPUT) {
  11. printf("input should in [%d, %d]\n", PARTITION_MIN, PARTITION_MAX);
  12. } else {
  13. }
  14. }
  15.  
  16. int
  17. print_set(int *set, int n) {
  18. int i, part, is_first_set, is_first_num, max = 1;
  19.  
  20. if(set == NULL)
  21. return ERR_NULL;
  22.  
  23. for(i=1; i<=n; i++) {
  24. if(set[i] > max)
  25. max = set[i];
  26. }
  27. is_first_set = 1;
  28. for(part=1; part<=max; part++) {
  29. if(!is_first_set)
  30. printf(", {");
  31. else
  32. printf("{");
  33. is_first_num = 1;
  34. for(i=1; i<=n; i++) {
  35. if(set[i] == part) {
  36. if(!is_first_num)
  37. printf(", ");
  38. printf("%d", i);
  39. is_first_num = 0;
  40. }
  41. }
  42. printf("}");
  43. is_first_set = 0;
  44. }
  45. printf("\n");
  46.  
  47. return SUCCESS;
  48. }
  49.  
  50. int
  51. rec_part(int *set, int k, int m, int n, int *cnt)
  52. {
  53. int i, ret;
  54. if(set == NULL) {
  55. return ERR_NULL;
  56. }
  57.  
  58. if(k == n) {
  59. ret = print_set(set, n);
  60. (*cnt)++;
  61. return ret;
  62. }
  63.  
  64.  
  65. // k+1 items, m sets
  66. for(i=1; i<=m; i++) {
  67. set[k+1] = i;
  68. ret = rec_part(set, k+1, m, n, cnt);
  69. if(ret != SUCCESS)
  70. return ret;
  71. }
  72.  
  73. // k+1 items, m+1 sets
  74. set[k+1] = m+1;
  75. ret = rec_part(set, k+1, m+1, n, cnt);
  76.  
  77. return ret;
  78. }
  79.  
  80. int
  81. partition(int n)
  82. {
  83. int set[PARTITION_MAX+1], i, cnt, ret;
  84. for(i=1; i<=n; i++)
  85. set[i] = 1;
  86.  
  87. if(n > PARTITION_MAX || n < PARTITION_MIN) {
  88. return ERR_INPUT;
  89. }
  90.  
  91. cnt = 0;
  92. ret = rec_part(set, 1, 1, n, &cnt);
  93.  
  94. if(ret == SUCCESS)
  95. printf("\nresult: %d\n", cnt);
  96.  
  97. return ret;
  98. }
  99.  
  100. int
  101. main()
  102. {
  103. int n, ret;
  104. while(scanf("%d", &n) != EOF) {
  105. ret = partition(n);
  106. if(ret) {
  107. handle_err(ret);
  108. }
  109. }
  110. return 0;
  111. }
Add Comment
Please, Sign In to add comment