Advertisement
MasWag

Knapsack_FPTAS.awk

Jan 23rd, 2015
413
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Awk 0.68 KB | None | 0 0
  1. ## format of input
  2. ## first line; K (capacity of bin) , k (divider)
  3. ## for each line
  4. ## weight value
  5. NR == 1 {
  6.     K = $1;
  7.     k = $2;
  8.     for (j = 1;j <= K;j++) {
  9.         dp [ j , 0 ] = 0;
  10.     }
  11. }
  12. NR != 1 {
  13.     i = NR - 1;
  14.     w = $1 / k;
  15.     v = $2;
  16.     # dp[weight][item]
  17.     dp[ 0 , i ] = 0;
  18.     for (j = 1;j <= K;j++) {
  19.         if (j - w > 0) {
  20.             dp [ j , i ] = max( dp [ j , i - 1 ], dp [ j - w , i - 1 ] + v );
  21.         } else {
  22.             dp [ j , i ] = dp [ j , i - 1 ];
  23.         }
  24.     }
  25. }
  26. END {    
  27.     printf "result : %d\n" , dp [ K , NR - 1 ];
  28. }
  29. function max (a,b) {
  30.     if (a > b) {
  31.         return a;
  32.     } else {
  33.         return b;
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement