import Data.Set (member,fromList,empty,toList)
import Data.List
import Control.Monad
tri = [n*(n+1)`div`2|n<-[1..]]
squ = [n*n|n<-[1..]]
pen = [n*(3*n-1)`div`2 | n<-[1..]]
hex = [n*(2*n-1)|n<-[1..]]
hep = [n*(5*n-3)`div`2|n<-[1..]]
oct = [n*(3*n-2) | n<-[1..]]
cyclic x = [x'| y<-"123456789",z<-"0123456789",let x' = read((drop 2.show) x++[y,z]),x/=x']
isPoly [] x = (empty,False)
isPoly (p:ps) x | member x p = (p,True)
| otherwise = isPoly ps x
cyclicPoly i [] x | member  i (fromList.cyclic$x) =[[x]]
| otherwise = []
cyclicPoly i ps x=do
y <- cyclic x
let (q,f) = isPoly ps y
guard f
ys <- cyclicPoly i (delete q ps) y
return$x:ys
p061 =sum.head.concat $ [cyclicPoly x ps x|x<-toList p]
where (p:ps) = map(fromList.takeWhile(<10000).dropWhile(<1000))[oct,hep,hex,pen,squ,tri]