icatalin

plata unei sume S cu N monede

May 30th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.04 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int S, n, st[1000], x[100];
  4.  
  5. int valid(int p)
  6. {
  7.     if (p>1)
  8.         if (st[p]<st[p-1])
  9.         return 0;
  10.  
  11.     int i, s = 0;
  12.  
  13.     for (i = 1; i <= p; i++)
  14.         s = s + st[i];
  15.  
  16.     if (s > S)
  17.         return 0;
  18.  
  19.     return 1;
  20. }
  21.  
  22. int solutie (int p)
  23. {
  24.     int i, s = 0;
  25.  
  26.     for (i = 1; i <= p; i++)
  27.         s = s + st[i];
  28.  
  29.     if (s == S)
  30.         return 1;
  31.  
  32.     return 0;
  33. }
  34.  
  35. void afis(int p)
  36. {
  37.     int i;
  38.  
  39.     for (i = 1; i <= p; i++)
  40.         printf("%d ",st[i]);
  41.  
  42.     printf("\n");
  43. }
  44.  
  45. void backtr(int p)
  46. {
  47.     int i;
  48.  
  49.     for (i=0; i<=n; i++)
  50.     {
  51.         st[p] = x[i];
  52.  
  53.         if (valid(p))
  54.             if (solutie(p))
  55.                 afis(p);
  56.             else
  57.                 backtr(p+1);
  58.     }
  59. }
  60.  
  61. int main()
  62. {
  63.  
  64.     FILE *fin;
  65.     fin = fopen("date.in","r");
  66.  
  67.     int i;
  68.  
  69.     fscanf(fin,"%d",&n);
  70.  
  71.     x[0] = 1;
  72.     for (i = 1; i <= n; i++)
  73.         fscanf(fin,"%d",&x[i]);
  74.  
  75.     fscanf(fin,"%d",&S);
  76.  
  77.     backtr(1);
  78.  
  79.     return 0;
  80. }
Add Comment
Please, Sign In to add comment