Cod sursa(job #30239)

Utilizator Bluedrop_demonPandia Gheorghe Bluedrop_demon Data 13 martie 2007 16:14:54
Problema Jocul Flip Scor 30
Compilator fpc Status done
Runda Arhiva de probleme Marime 2.12 kb
{
    Jocul Flip
}

Program Flip;

Type Matrice = array[1..16,1..16] of Longint;
     Vector = array[1..32] of ^Shortint;

Var  a : matrice;
     suma, st : longint;
     n, m, i, j, k : byte;
     s : ^Vector;
     cod1, cod2 :Boolean;

Procedure init( k : Integer );
Begin
     s^[k]^ := -1;
End;

Procedure succ( k : Integer; Var cod : boolean );
Begin
     If ( s^[k]^ < 1 ) then
        Begin
             cod := true;
             s^[k]^ := s^[k]^ +1;
        End
        else cod := false;
End;

Procedure cond( k : Integer; Var cod : boolean );
Begin
     cod := k<=n+m;
End;

Function sol( k : Integer ) : boolean;
Begin
     sol := k = m+n;
End;

Function sumaMatrix : integer;
Var i, j, aux, sm : integer;
Begin
     sm := 0;
     For i := 1 to n do
         Begin
              aux := 1;
              If s^[i]^ = 1 then aux := -1;
              For j := 1 to m do
                  if s^[j+n]^ = 1 then sm := sm-aux*a[i,j]
                                  else sm := sm+aux*a[i,j];
         End;
     sumaMatrix := sm;
End;

Begin
     Assign( input, 'flip.in' );
     Reset( input );
            Readln( n, m );
            For i := 1 to n do
                For j := 1 to m do
                    Read( a[i,j] );
     Close( input );
     New( s );
     For i := 1 to n+m+1 do New( s^[i] );

     k := 1;
     init( k );
     Repeat
           Repeat
                 succ( k, cod1 );
                 if cod1 then cond( k, cod2 );
           Until ( not cod1 ) or ( ( cod1 ) and ( cod2 ) );
           if cod1 then
              if sol( k ) then
                Begin
                    st := sumaMatrix;
                    if st > suma then suma := st;
                End
                else
                Begin
                    k := k+1;
                    init( k );
                End
              else
              k := k-1;
     Until k = 0;

     Assign( output, 'flip.out' );
     Rewrite( output );
              Writeln( suma );
     Close( output );

     for k := 1 to n+m+1 do
        dispose( s^[k] );
     dispose( s );
End.