Advertisement
STANAANDREY

knapsack bktr + plot

May 27th, 2023 (edited)
1,198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.64 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdint.h>
  4. #include <time.h>
  5. #define MAX(a, b) a > b ? a : b
  6. #define NMAX 15
  7. #define NMIN 5
  8.  
  9. typedef struct {
  10.   int weight, gain;
  11. } Item;
  12.  
  13. int ksBktr(int n, int k, const Item items[]) {
  14.   uint16_t state, lastState = (1 << n) - 1;
  15.   int ans = 0;
  16.   for (state = 0; state <= lastState; state++) {
  17.     int weight = 0, gain = 0;
  18.     for (int bit = 0; bit < NMAX; bit++) {
  19.       Item item = items[bit];
  20.       if ((state & (1 << bit)) && weight + item.weight <= k) {
  21.         weight += item.weight;
  22.         gain += item.gain;
  23.       }
  24.     }
  25.     ans = MAX(ans, gain);
  26.   }
  27.   return ans;
  28. }
  29.  
  30. double getSecs(clock_t start, clock_t end) {
  31.   return ((double) (end - start)) / CLOCKS_PER_SEC;
  32. }
  33.  
  34. int main() {
  35.   //modify the input from here if you want
  36.   const int k = 10;
  37.   const Item items[NMAX + 1] = {{3,7},{3,4},{1,2},{1,9},{2,4},{1,5}};
  38.  
  39.   FILE *f = popen("gnuplot --slow", "w");
  40.   if (f == NULL) {
  41.     perror("popen error: ");
  42.     exit(EXIT_FAILURE);
  43.   }//*/
  44.  
  45.   fprintf(f, "plot '-'\n");
  46.   clock_t start, end;
  47.   for (int i = NMIN; i <= NMAX; i++) {//plot 5-15
  48.     start = clock();
  49.     int ans = ksBktr(i, k, items);
  50.     end = clock();
  51.     printf("n=%d: %d\n", i, ans);
  52.     double secs = getSecs(start, end);
  53.     fprintf(f, "%d %lf\n", i, secs);
  54.   }
  55.  
  56.   fprintf(f, "e\n");
  57.   fprintf(f, "set title \"time(n)\"\n");
  58.   fprintf(f, "set xlabel \"n\"\n");
  59.   fprintf(f, "set ylabel \"time\"\n");
  60.   if (fflush(f) == EOF) {
  61.     perror("");
  62.     fclose(f);
  63.     exit(-1);
  64.   }
  65.  
  66.   puts("PRESS ENTER TO EXIT...");
  67.   getchar();
  68.   if (fclose(f) == EOF) {
  69.     perror("");
  70.   }//*/
  71.   return 0;
  72. }
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement