all-expression

どうにか速さ5倍に。あと23倍。むりだなー

#all-expression2-8.rb

$x=[]
$a=[]

def make fnk,kak
 l=$a.length
 x=""
 mae=[0]*(l+3)
 usi=[0]*(l+3)
 (l-1).times{|i|
  po=0;
  (kak[i]+1).times{|m|
   while usi[po]>0
    po+=1
   end
   po+=1
  }
  po-=1
  mae[po]+=1
  pot=po+mae[po]
  while mae[pot]>0
   pot+=1
  end
  usi[pot]+=1
 }
 l.times{|i|
  if mae[i]>0 ;x+= "("*mae[i]+$a[i]+fnk[i]
  else ;x+= $a[i]+")"*usi[i]+fnk[i]
  end
 }
 x+="0"+")"*(usi[l]+usi[l+1])
 #puts x
 eval(x)
end

def kakko f,c,k
 if c==0
  a=make(f,k)
  $x.push(a)
 else
  c-=1
  (c+1).times{|i|
   k+=[i]
   kakko(f,c,k)
   k.pop
  }
 end
 $x
end

$a=gets.split(" ")
c=$a.length
(3**(c-1)).times{|j|
 b=""
 t=false
 f=[]
 a=("0"*(c-1)+j.to_s(3))[-(c-1)..-1]
 c.times{|i|
  s=a[i..i]=="0"?"+":a[i..i]=="1"?"*":"-";
  f.push(s)
  t=true if s=="*"
  b+=$a[i]+s
 }
 b+="0"
 $x.push(eval b)
 k=[]
 kakko(f,c,k) if(t) #$x.sort!.uniq!;
 #print "en."
}
puts $x.sort.uniq