unit libconq;

interface

const MAX_N = 2000;
      MAX_M = 1000000000;

procedure start(var N: longint; var stairs: array of longint);
function step(subset: array of longint): longint;

implementation

const game_N: longint = 0;
      lib_usage: longint = 0;

var st: array[0..MAX_N] of longint;
    lib_txt: string;

procedure lib_error(code: longint; s: string);
var f: text;
begin
    assign(f,'libconq.out'); 
    rewrite(f);
    writeln(f,s);
    close(f);
    halt(code);
end;

function int2str(i:longint): string;
var s:string;
begin
    str(i,s);
    int2str:=s;
end;

procedure start(var N: longint; var stairs: array of longint);
var f: text;
    i: longint;
begin
    if (lib_usage<>0) then lib_error(1,'start() called too many times');
    inc(lib_usage);

    assign(f,'libconq.dat');
    {$I-}
    reset(f);
    {$I+}
    if IOResult<>0 then 
		begin
				randomize;
				N:=2+random(MAX_N-2);
				stairs[0]:=0;
				for i:=1 to N-1 do stairs[i]:=random(i*i);
		end
    else
    begin
				read(f,N);
				for i:=0 to N-1 do read(f,stairs[i]);
				close(f);
    end;
  
    game_N:=N;
    for i:=1 to N do st[i]:=stairs[i-1];
end;

function decide(a: array of longint): longint;
begin
		decide:=1+random(2);
end;

function step(subset: array of longint): longint;
var choice,i,wrong,cnt: longint;
begin
    if (lib_usage=0) then lib_error(1,'call start() first!');
    inc(lib_usage);

    { check if a is a valid subset }
    wrong:=0;
    for i:=1 to game_N do
    begin
	if ((subset[i-1]<0) or (subset[i-1]>st[i])) then wrong:=i;
	if (wrong<>0) then break;
    end;
  
    if (wrong<>0) then
    begin
	lib_txt:='wrong number of soldiers on stair '+int2str(wrong)+
		': '+int2str(subset[wrong-1])+
		' requested, '+int2str(st[wrong])+
		' available';
	lib_error(1,lib_txt);
    end;
  
    { decide }
    choice:=decide(subset);
    
    { choice 1: move subset one stair up, discard the rest }
    if (choice=1) then
    begin
	for i:=1 to game_N do st[i]:=subset[i-1];
	for i:=1 to game_N do st[i-1]:=st[i];
    end
    else  { choice 2: discard subset, move complement one stair up }
    begin
	for i:=1 to game_N do dec(st[i],subset[i-1]);
	for i:=1 to game_N do st[i-1]:=st[i];
    end;
  
    { check if there are any soldiers left }
    { check if there is any soldier at position 1 }
    cnt:=0;
    for i:=1 to game_N do if st[i]<>0 then inc(cnt);
  
    if (cnt=0) then
    begin
        lib_txt:='You lost!';
	lib_error(0,lib_txt);
    end;
  
    if (st[1]<>0) then
    begin
	lib_txt:='You won!';
	lib_error(0,lib_txt);
    end;

    step:=choice;
end;

end.
