program main implicit none character*12::S integer::i,j,lenk,p,maxindx,minindx integer*8,allocatable::N(:) integer::digit(0:9),kinds,maxcww,mincww,limitcww data digit/10*0/ read *,S lenk = LEN_TRIM(S) if(lenk.lt.3) then print '("0")' return end if allocate(N(lenk)) do i=1,lenk N(i) = ICHAR(S(i:i))-ICHAR('0') digit(N(i)) = digit(N(i)) +1 end do kinds=COUNT(digit.ne.0) if(kinds.eq.1) then print '("0")' else if(kinds.eq.2) then limitcww = getlimit(digit) p=partmax(N) print '(i0)', p else limitcww=3952 p=partmax(N) print '(i0)', p endif contains recursive function partmax(N) result(pmax) integer*8,intent(in) ::N(:) integer*8,allocatable::M(:) integer*8::cww,pmax,i,j,k,l,len,ni100 integer,save::num=0 num = num + 1 pmax = 0 len = size(N) if(len .lt. 3) then return else do i=1,len-2 if(N(i).eq.0) cycle ni100=N(i)*100 do j=i+1,len-1 if(N(i).eq.N(j)) cycle cww = ni100+N(j)*11 do k=j+1, len if(N(j).ne.N(k)) cycle M = pack(N, (/(l.ne.i.and.l.ne.j.and.l.ne.k,l=1,len)/)) pmax = MAX(cww+partmax(M),pmax) if(pmax.eq.limitcww) then return end if end do end do end do endif end function partmax function getlimit(D) result(limit) integer,intent(in)::D(0:9) integer::limit,maxnum,minnum limit = 0 do i=0,9 if(D(i).ne.0) then minindx = i exit end if end do do i=9,0,-1 if(D(i).ne.0) then maxindx = i exit end if end do maxcww=maxindx*100+minindx*11 mincww=minindx*100+maxindx*11 maxnum=D(maxindx) minnum=D(minindx) do i=0,4 !minindx do j=0,4-i !maxindx if((i+2*j).le.minnum.and.(2*i+j).le.maxnum) then limit = MAX(limit, i*mincww+j*maxcww) end if end do end do end function getlimit function getnum(M) result(num) integer*8,intent(in)::M(:) integer::s,i,num s = size(M) num = 0 do i=1,s num = num+M(i)*10**(i-1) end do end function getnum end program main