Advertisement
RaFiN_

knuth optimization

May 12th, 2020
788
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.77 KB | None | 0 0
  1. /// UVA optimal Binary Search Tree
  2. int call(int st, int ed)
  3. {
  4.     if(st == ed)
  5.     {
  6.         path[st][ed] = ed;
  7.         return freq[st];
  8.     }
  9.     if(dp[st][ed] != -1)
  10.         return dp[st][ed];
  11.     int ret = 1e9;
  12.  
  13.     call(st, ed-1);
  14.     call(st+1, ed);
  15.  
  16.     int L = max(st, path[st][ed-1]);
  17.     int R = min(ed, path[st+1][ed]);
  18.  
  19.     for(int i = L; i<=R; i++)
  20.     {
  21.         int nw = 0;
  22.         if(i-1 >= st)
  23.             nw += call(st, i-1);
  24.         if(ed >= i+1)
  25.             nw += call(i+1, ed);
  26.         nw += csum[ed] - csum[st-1];
  27.         if(nw < ret)
  28.         {
  29.             ret = nw;
  30.             path[st][ed] = i;
  31.         }
  32.     }
  33.     return dp[st][ed] = ret;
  34. }
  35.  
  36. /// path[st][ed-1] <= path[st][ed] <= path[st+1][ed]
  37. // k is the total number of groups
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement