program balanced_path
    implicit none
    integer(4):: h,w
    integer(4),allocatable:: a(:,:),b(:,:), mass_abs(:,:)
    integer(4):: i,j,k, no_
    logical,allocatable:: is_exist(:,:,:)

    read*, h,w
    allocate(a(w,h), b(w,h))
    do i=1,h
        read*, a(:,i)
    end do
    do i=1,h
        read*, b(:,i)
    end do
    
    allocate(mass_abs(w+1,h+1), source=0)
    do i=1,h
        do j=1,w
            mass_abs(j,i) = abs(a(j,i)-b(j,i))
        end do
        ! print*, mass_abs(:,i)
    end do
    deallocate(a)
    deallocate(b)
    allocate(is_exist(0:maxval(mass_abs(:,:))*(h+w), w+1, h+1))


    is_exist(:,:,:) = .false.
    is_exist(mass_abs(1,1),1,1) = .true.
    block
        integer(4):: max_bias
        max_bias = maxval(mass_abs(:,:))*(h+w)

        do no_ = 1, w+h
            do i=1, h
                do j=1,w
                    do k=0,max_bias
                        if (.not.is_exist(k,j,i)) cycle
                        ! print*, abs(k+mass_abs(j+1,i)), j,i
                        is_exist(abs(k+mass_abs(j+1,i)),j+1,i) = .true.
                        ! print*, abs(k-mass_abs(j+1,i)), j,i
                        is_exist(abs(k-mass_abs(j+1,i)),j+1,i) = .true.
                        ! print*, abs(k+mass_abs(j,i+1)), j,i
                        is_exist(abs(k+mass_abs(j,i+1)),j,i+1) = .true.
                        ! print*, abs(k-mass_abs(j,i+1)), j,i
                        is_exist(abs(k-mass_abs(j,i+1)),j,i+1) = .true.
                    end do
                end do
            end do
        end do

        do i=0, max_bias
            if(is_exist(i,w,h))then
                print*, i
                stop
            end if
        end do
    end block

end program balanced_path