#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <stdio.h>

#define LIB_MAXN 2003

long LIB_W [LIB_MAXN+1][LIB_MAXN+1][2];
FILE *in=0;

int LIB_queries= 0;

int LIB_N, LIB_L;
FILE *LIB_out;
void LIB_init ();

int getN (){
  LIB_init();
  return LIB_N;
}

int getL (){
  LIB_init();
  return LIB_L;
}

int getWeight (int x, int y, int direction){
  LIB_init();
  ++LIB_queries;
  if (x<1||x>getN()){
    fprintf (LIB_out,
	     "getWeight: invalid x=%d\n",
	     x);
    exit (0);}
  if (y<1||y>getN()){
    fprintf (LIB_out,
	     "getWeight: invalid y=%d\n",
	     y);
    exit (0);}
  if (direction!=0&&direction!=1){
    fprintf (LIB_out,
	     "getWeight: invalid direction=%d\n",
	     direction);
    exit(0);}
  int result= LIB_W [x][y][direction];

  if (result<0){ 
    fprintf (LIB_out,
	     "getWeight: edge does not exist (%d, %d, %d)\n",
	     x,y,direction);
    exit(0);}
  fprintf( LIB_out,
	   "getWeight: %d %d %d %d\n",
	   x, y, direction, result );
  return result;
}

void solution (int x, int y){
  LIB_init ();
  fprintf (LIB_out, "solution: (%d, %d) queries=%d\n", x, y, LIB_queries);
  fclose (LIB_out);
  exit (0);
}

void LIB_init (){
  int x,y;
  static int already_initialized= 0;
  if (already_initialized) return;
  already_initialized= 1;
  LIB_out= fopen ("square.out", "w");
  for (y=1;y<=LIB_MAXN;y++)
    for (x=1;x<=LIB_MAXN;x++)
      LIB_W [x][y][0]= LIB_W [x][y][1]= -1;

  in = fopen ("square.in", "r");
  if (!in) {
    fprintf (LIB_out,
	     "cannot open square.in\n"); 
    exit (0);
  }
  fscanf( in, "%d %d", &LIB_N, &LIB_L );
  for (y=1; y<=LIB_N; ++y)
    for (x=1; x<LIB_N; ++x)
      fscanf (in, "%ld", &LIB_W [x][y][0]);
  for (y=1; y<LIB_N; ++y){
    for (x=1; x<=LIB_N; ++x){
      fscanf (in, "%ld", &LIB_W [x][y][1] );	
    }
  }
}
