Patey

Untitled

Apr 3rd, 2021
519
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.35 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #pragma warning(disable:4996)
  4.  
  5. int st[100], vf;
  6. int w, n, a[100];
  7. int maxSolutionElementValue, max_nivele;
  8.  
  9.  
  10. void Init(int i)
  11. {
  12.     st[i] = 0;
  13. }
  14.  
  15. int Succesor(int k) {
  16.     if (st[k] < maxSolutionElementValue)
  17.     {
  18.         st[k]++;
  19.         return 1;
  20.     }
  21.     else
  22.     {
  23.         return 0;
  24.     }
  25. }
  26.  
  27. int Solution(int k)
  28. {
  29.     int suma = 0,i;
  30.     for (i = 1; i <= k; i++)
  31.         suma += a[st[i]];
  32.     if (suma == w)
  33.         return 1;
  34.     else
  35.         return 0;
  36. }
  37.  
  38. int Valid(int k)
  39. {
  40.     int i;
  41.     for (i = 1; i < k; i++)
  42.     {
  43.         if (st[i]>=st[k])
  44.         {
  45.             return 0;
  46.         }
  47.     }
  48.     return 1;
  49. }
  50.  
  51. void Print(int k) {
  52.     int i;
  53.     for (i = 1; i <= k; i++)
  54.     {
  55.         printf("%d ", a[st[i]]);
  56.     }
  57.     printf("\n");
  58. }
  59.  
  60. void Back()
  61. {
  62.     int iS, iV, i, j, k, suma, poz;
  63.    
  64.     vf = 1;
  65.     Init(vf);
  66.     while (vf > 0)
  67.     {
  68.         iS = 0;
  69.         iV = 0;
  70.         do {
  71.             iS = Succesor(vf);
  72.             if (iS)
  73.             {
  74.                 iV = Valid(vf);
  75.             }
  76.         } while (iS && !iV);
  77.         if (iS)
  78.         {
  79.             if (Solution(vf))
  80.             {
  81.                 Print(vf);
  82.             }
  83.             else
  84.             {
  85.                 vf++;
  86.                 Init(vf);
  87.             }
  88.         }
  89.         else
  90.         {
  91.             vf--;
  92.         }
  93.     }
  94. }
  95.  
  96. void main()
  97. {
  98.     int i;
  99.     printf("Dati numarul de elemente: ");
  100.     scanf("%d", &n);
  101.     for (i = 1; i <= n; i++)
  102.     {
  103.         printf("a[%d]= ", i);
  104.         scanf("%d", &a[i]);
  105.     }
  106.  
  107.     printf("Dati numarul care trb obtinut prin suma: ");
  108.     scanf("%d", &w);
  109.     maxSolutionElementValue = n;
  110.     max_nivele = n;
  111.     Back();
  112. }
Advertisement
Add Comment
Please, Sign In to add comment