1

I am learning about maximisation with linear programming, and have come across an algorithm for maximisation with two variables (silver and gold in this instance) but I am unsure what a certain section of the code is doing:

using namespace std;


class PreciousStones {
  int n;
  vector<int> as;
  vector<int> ag;

The function below is the section I am unclear on:

  double maxg (double s) {
    double g = 0;
    for (int i=0; i<n; i++)
      if (s == 0)
        g += ag[i];
      else if (as[i] <= s) 
        s -= as[i];
      else {
        g += (1-s/as[i])*ag[i];
        s = 0;
      }
    return g;
  }

The rest of the code is below (for context), if anyone knows of some relevant papers on this algorithm, or can provide a brief explanation on this function I would appreciate it greatly

public:
  double value(vector <int> silver, vector <int> gold) {
    n = silver.size();
    as = silver;
    ag = gold;
    for (int i=0; i<n; i++) 
      for (int j=i+1; j<n; j++) 
        if (as[j]*ag[i] > as[i]*ag[j]) {
          swap(as[i], as[j]);
          swap(ag[i], ag[j]);
        }
    double lo = 0;
    double hi = 51*100;
    double D = 1e-10;
    while (lo+D < hi && lo*(1+D) < hi) {
      double mid = (lo+hi)/2;
      if (mid <= maxg(mid))
        lo = mid;
      else
        hi = mid;
    }
    return lo;
  }
}; 
Barney Chambers
  • 2,720
  • 6
  • 42
  • 78

1 Answers1

1

The magic words you need to google are "Simplex Algorithm" for linear programming constraint maximisation. This slide deck looks like it might be what you want. http://www.cs.nccu.edu/~melikyan/mat_fm/lec/lec5_4.pdf

Hal
  • 1,061
  • 7
  • 20
  • Thanks for the tip Hal, to me it looks like a greedy algorithm more than the Simplex Algorithm – Barney Chambers Mar 22 '16 at 03:06
  • Two arrays - think of it as an array of a struct with two values. Sort by the product of those two values. Binary search with low zero and high value initialised to magic number. Throw away all values of silver and gold where silver sums to the test value. Multiply the residual by gold as the starting value for the cost, sum the rest of gold and add. Maximise gold first, then given that pick up all the residual silver you can looks to be what it is trying to do. – Hal Mar 22 '16 at 03:39