Guest User

Untitled

a guest
Oct 22nd, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. /*knapsack simples*/
  2. #include <cstdio>
  3. #include <cstdlib>
  4.  
  5. #define MAXOBJ 21
  6. #define MAXTAM 10001
  7.  
  8. int N;
  9. int t;
  10.  
  11. int main()
  12. {
  13.  
  14.  
  15. int maxTab[MAXOBJ][MAXTAM];
  16.  
  17. for(int i = 0; i< MAXOBJ;++i)
  18. maxTab[i][0] = 0;
  19.  
  20.  
  21. for(int i = 0; i<MAXTAM; ++i)
  22. maxTab[0][i] = 0;
  23.  
  24.  
  25. while ( scanf("%d",&N) != EOF ){
  26. scanf("%d",&t);
  27. int tracks[t];
  28.  
  29.  
  30. for(int i = 0; i < t; ++i)
  31. {
  32. int aux = 0;
  33. scanf("%d",&aux);
  34. tracks[i] = aux;
  35. }
  36.  
  37. for(int i = 1; i <= t; i++)
  38. {
  39. for(int j = 1; j <= N; j++)
  40. {
  41. if(tracks[ i - 1 ] > j)
  42. {
  43. maxTab[i][j] = maxTab[i - 1][j];
  44. }else
  45. {
  46.  
  47. if(maxTab[i - 1][j] > (maxTab[i - 1][j - tracks[i - 1]] + tracks[i - 1]))
  48. {
  49. maxTab[i][j] = maxTab[i - 1][j];
  50. }else
  51. {
  52. maxTab[i][j] = maxTab[i - 1][j - tracks[i-1]] + tracks[i - 1];
  53. }
  54.  
  55. }
  56. }
  57.  
  58. }
  59.  
  60. bool quemTa[t];
  61. for(int i = 0; i < t; ++i)
  62. quemTa[i]=false;
  63.  
  64.  
  65.  
  66. int col = N;
  67. for(int i = t-1; i>=0; --i)
  68. {
  69. int ajuda = col - tracks[i];
  70. if(ajuda >=0)
  71. {
  72. if((maxTab[i + 1][col] - tracks[i]) == maxTab[i][ajuda])
  73. {
  74. quemTa[i] = true;
  75. col = ajuda;
  76. }
  77. }
  78. }
  79.  
  80.  
  81. for(int i = 0; i < t; ++i)
  82. {
  83. if(quemTa[i] == true)
  84. {
  85. printf("%d ",tracks[i]);
  86. }
  87. }
  88. printf("sum:%d\n",maxTab[t][N]);
  89.  
  90.  
  91. }
  92.  
  93. return 0;
  94. }
Add Comment
Please, Sign In to add comment