// -*- c++ -*-
#include <iostream>
#include <fstream>

#include <lemon/time_measure.h>
#include <lp_solver_glpk.h>

using std::cout;
using std::endl;
using namespace lemon;

/*
  On an 1537Mhz PC, the run times with 
  glpk are the following.
  for n=3,4, some secondes
  for n=5, 25 hours
 */

int main(int, char **) {
  const int n=3;
  const double row_sum=(1.0+n*n)*n/2;
  Timer ts;
  ts.reset();
  typedef LpGlpk LPSolver;
  typedef LPSolver::Col Col;
  LPSolver lp;
  typedef std::map<std::pair<int, int>, Col> Coords;
  Coords x;
  // we create a new variable for each entry 
  // of the magic square
  for (int i=1; i<=n; ++i) {
    for (int j=1; j<=n; ++j) { 
      Col col=lp.addCol();
      x[std::make_pair(i,j)]=col;
      lp.setColLowerBound(col, 1.0);
      lp.setColUpperBound(col, double(n*n));
    }
  }
  LPSolver::Expression expr3, expr4;
  for (int i=1; i<=n; ++i) {
    LPSolver::Expression expr1, expr2;
    for (int j=1; j<=n; ++j) {
      expr1+=x[std::make_pair(i, j)];
      expr2+=x[std::make_pair(j, i)];
    }

    // sum of rows and columns
    lp.addRow(expr1==row_sum);
    lp.addRow(expr2==row_sum);
      cout <<"Expr1: "<<expr1<<endl;
      cout <<"Expr2: "<<expr2<<endl;

    expr3+=x[std::make_pair(i, i)];
    expr4+=x[std::make_pair(i, (n+1)-i)];
  }
  cout <<"Expr3: "<<expr3<<endl;
  cout <<"Expr4: "<<expr4<<endl;
  // sum of the diagonal entries
  lp.addRow(expr3==row_sum);
  lp.addRow(expr4==row_sum);
  lp.solveSimplex();
  cout << "elapsed time: " << ts << endl;
  for (int i=1; i<=n; ++i) {
    for (int j=1; j<=n; ++j) { 
      cout << "x("<<i<<","<<j<<")="<<lp.getPrimal(x[std::make_pair(i,j)]) 
	   << endl;
    }
  }



//   // we make new binary variables for each pair of 
//   // entries of the square to achieve that 
//   // the values of different entries are different
//   lp.setMIP();
//   for (Coords::const_iterator it=x.begin(); it!=x.end(); ++it) {
//     Coords::const_iterator jt=it; ++jt;
//     for(; jt!=x.end(); ++jt) {
//       Col col1=(*it).second;
//       Col col2=(*jt).second;
//       Col col=lp.addCol();
//       lp.setColLowerBound(col, 0.0);
//       lp.setColUpperBound(col, 1.0);
//       lp.addRow(double(-n*n+1.0)<=1.0*col2-1.0*col1-double(n*n)*col<=-1.0);
//       lp.setColInt(col);
//     }
//   }
//   cout << "elapsed time: " << ts << endl;
//   lp.solveSimplex();
//   // let's solve the integer problem
//   lp.solveBandB();
//   cout << "elapsed time: " << ts << endl;
//   for (int i=1; i<=n; ++i) {
//     for (int j=1; j<=n; ++j) { 
//       cout << "x("<<i<<","<<j<<")="<<lp.getMIPPrimal(x[std::make_pair(i,j)]) 
// 	   << endl;
//     }
//   }
}
