program main implicit none integer::N,K,i,j,l,m,total logical::sortable integer,allocatable::a(:),b(:),sorta(:),sortb(:) data total/0/ read *,N,K allocate(a(N),sorta(N),b(N),sortb(N)) read *,a sorta = qsort(a) if(N.lt.K) then sortable = ALL(a.eq.sorta) else sortable = check_sortable(a,sorta, N, K) end if if(sortable.eqv..false.) then print '(i0)',-1 return end if print *, a print *, sorta do i=1,MIN(K,N) b = (/(a(j), j=i,N,K)/) sortb = (/(sorta(j),j=i,N,K)/) ! print *,b ! print *,sortb do j=1, (N+K-1)/K do l=j,(N+K-1)/K if(sortb(j).eq.b(l))exit end do do m=l,j+1,-1 b(m) = b(m-1) total = total + 1 end do b(j) = sortb(j) end do end do print '(i0)',total return contains function check_sortable(a,sorta, N, K) result(sortable) integer,intent(in)::N,K integer,allocatable,intent(in)::a(:),sorta(:) logical::sortable do i=1,N,K sortable = .false. do j=MOD(i,K),N,K if(a(j).eq.sorta(i)) then sortable = .true. exit end if end do if(sortable .eqv. .false.) then return end if end do end function check_sortable recursive function qsort(x) result(y) integer,intent(in) ::x(:) integer,allocatable::y(:) integer::pivot,total total = size(x) if (total <=1) then y = x else pivot = x(total/2) y = [qsort(pack(x, x .lt. pivot)), & pack(x, x .eq. pivot), & qsort(pack(x, x .gt. pivot))] endif end function qsort end program main