fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // Recursive function to count the number of ways to select `nbags` bags
  5. // to sum up to `target` weight.
  6. int countWays(int target, int nbags, int index, int* V, int n) {
  7. // Base cases
  8. if (nbags == 0) {
  9. return target == 0 ? 1 : 0; // If no bags left, check if the target is 0
  10. }
  11. if (index >= n) {
  12. return 0; // If no more sacks left to process
  13. }
  14.  
  15. // Recursive cases
  16. // Option 1: Include the current sack
  17. int include = 0;
  18. if (target >= V[index]) {
  19. include = countWays(target - V[index], nbags - 1, index + 1, V, n);
  20. }
  21.  
  22. // Option 2: Exclude the current sack
  23. int exclude = countWays(target, nbags, index + 1, V, n);
  24.  
  25. return include + exclude;
  26. }
  27.  
  28. int bagsSum(int target, int nbags, int n, int* V) {
  29. // Call the recursive function starting from index 0
  30. return countWays(target, nbags, 0, V, n);
  31. }
  32.  
  33. int main() {
  34. int target, nbags, n, *V, i;
  35.  
  36. // Read input values
  37. scanf("%d %d %d", &target, &nbags, &n);
  38.  
  39. // Allocate memory for sack weights
  40. V = (int*)malloc(sizeof(int) * n);
  41.  
  42. // Read weights
  43. for (i = 0; i < n; i++) {
  44. scanf("%d", &V[i]);
  45. }
  46.  
  47. // Compute and print the result
  48. printf("%d\n", bagsSum(target, nbags, n, V));
  49.  
  50. // Free allocated memory
  51. free(V);
  52.  
  53. return 0;
  54. }
Success #stdin #stdout 0s 5284KB
stdin
20
3 10
1 2 4 5 10 11 13 15 17 19
stdout
4