import Control.Arrow
import Data.Bits
import Data.Char
import Data.List
import qualified Data.ByteString.Char8 as B
import qualified Data.Vector as V
main=print.solve.map(V.unfoldr$B.readInt.B.dropWhile isSpace).B.lines=<<B.getContents
solve(n:fp)=maximum$map g[1..1023]where
  fps=uncurry zip.(first$map(V.foldl'(\v f->v*2+f)0))$splitAt(n V.! 0)fp
  g b=sum$map(\(f,p)->p V.! popCount(f.&.b))fps