unit square_lib;
{
translation of grader/square_lib.h and grader/square_lib.cpp
}

interface

function getN: longint;
function getL: longint;
function getWeight(x, y, direction : longint): longint;
procedure solution(x, y : longint);

implementation

const
   LIB_MAXN = 20;   // save memory; note: public tests are small enough

var
   LIB_queries	: longint;
   LIB_N, LIB_L	: longint;
   LIB_out	: text;

   LIB_W : array[1..2003] of array[1..2003] of array[0..1] of longint;


procedure LIB_init; forward;

function getN : longint;
begin
   LIB_init;
   getN := LIB_N;
end; { getN }

function getL : longint;
begin
   LIB_init;
   getL := LIB_L;
end; { getL }

function getWeight(x, y, direction : longint): longint;
var res	     : longint;
begin
   LIB_init();
   inc(LIB_queries);
   if (x<1) or (x>getN())
      then begin
	 writeln(LIB_out, 'getWeight: invalid x=', x);
	 halt(0);
      end;
   if (y<1) or (y>getN())
      then begin
	 writeln(LIB_out, 'getWeight: invalid y=', y);
	 halt(0);
      end;
   if (direction <> 0) and (direction <> 1)
      then begin
	 writeln(LIB_out, 'getWeight: invalid direction=', direction);
	 halt(0);
      end;
   res:=LIB_W[x][y][direction];
   if res < 0
      then begin
	 writeln(LIB_out, 'getWeight: edge does not exist (', x, ', ', y, ', ', direction, ')');
	 halt(0);
      end;
   writeln(LIB_out, 'getWeight: ', x, ' ', y, ' ', direction, ' ', res);
   getWeight:=res;
end; { getWeight }

procedure solution(x, y	: longint);
begin
   LIB_init;
   writeln(LIB_out, 'solution: (', x, ', ', y, ') queries=', LIB_queries);
   close(LIB_out);
   halt(0);
end; { solution }

var already_initialized : longint;
procedure LIB_init;
var oldfilemode	: integer;
   fin		: text;
   x, y		: longint;
begin
   if already_initialized <> 0
      then exit;
   already_initialized:=1;
   
   assign(LIB_out, 'square.out');
   {$I-}
   rewrite(LIB_out);
   {$I+}
   // if IOResult <> 0 then begin
   //    writeln(LIB_out, 'cannot open square.out');
   //    halt(0);
   // end;
   
   for y:=1 to LIB_MAXN do for x:=1 to LIB_MAXN do begin
     LIB_W[x,y,0] := -1;
     LIB_W[x,y,1] := -1;
   end;
   
   assign(fin, 'square.in');
   oldfilemode:=filemode;
   filemode:=0;
   {$I-}
   reset(fin);
   {$I+}
   filemode:=oldfilemode;
   if IOResult<>0
      then begin
	 writeln(LIB_out, 'cannot open square.in');
	 halt(0);
      end;
   readln(fin, LIB_N, LIB_L);
   for y:=1 to LIB_N do
      for x:=1 to LIB_N-1 do
	 read(fin, LIB_W[x][y][0]);
   for y:=1 to LIB_N-1 do
      for x:=1 to LIB_N do
	 read(fin, LIB_W[x][y][1]);
   close(fin);
end;

begin
   LIB_queries := 0;
   already_initialized := 0;
   LIB_out := stdout;
end.
