{-# LANGUAGE BangPatterns     #-}
{-# LANGUAGE FlexibleContexts #-}
import           Control.Monad
import           Control.Monad.ST
import           Control.Monad.State
import           Data.Array.IArray
import           Data.Array.ST
import           Data.Array.Unboxed    (UArray)
import qualified Data.Array.Unboxed    as U
import           Data.Bits
import           Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import           Data.Char
import           Data.Graph
import           Data.Int              (Int64)
import           Data.List
import           Data.Maybe
import           Data.Proxy
import           Data.Sequence         (Seq, (<|), (><), (|>))
import qualified Data.Sequence         as Seq
import qualified Data.Set              as S
import           Data.STRef
import           Data.Vector.Unboxed   (Vector)
import qualified Data.Vector.Unboxed   as V
import           Numeric

main :: IO ()
main = do
  n <- read <$> getLine :: IO Int
  s <- getLine

  let r = length $ filter (=='R') s
      g = length $ filter (=='G') s
      b = length $ filter (=='B') s
      l = length [(i,j) |
                  (i,x) <- zip [1..] s,
                  (j,y) <- filter (\p -> snd p /= x) $ zip [(i+1)..] $ drop i s,
                  x/=y,
                  n > 2*j-i-1,
                  x/=(s!!(2*j-i-1)),
                  y/=(s!!(2*j-i-1))]

  print $ r * g * b - l

getAsInt :: IO [Int]
getAsInt =  unfoldr (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine

getAsIntLine :: Int -> IO [[Int]]
getAsIntLine !n = replicateM n getAsInt

getAsIntArray1Dr :: Int -> IO (UArray Int Int)
getAsIntArray1Dr !n = U.listArray (1,n) <$> getAsInt

getAsIntVec1Dr :: IO (Vector Int)
getAsIntVec1Dr = V.fromList <$> getAsInt

getAsIntArray1Dc :: Int -> IO (UArray Int Int)
getAsIntArray1Dc !n = U.listArray (1,n) . concat <$> getAsIntLine n

getAsIntVec1Dc :: Int -> IO (Vector Int)
getAsIntVec1Dc !n = V.fromList . concat <$> getAsIntLine n

-- n: number of lines
-- m: number of values per a line
getAsIntArray2D :: Int -> Int -> IO (UArray (Int,Int) Int)
getAsIntArray2D !n !m = U.listArray ((1,1),(n,m)) . concat <$> getAsIntLine n

getAsString :: IO [String]
getAsString = map BS.unpack . BS.words <$> BS.getLine

getAsCharArray1DWithLength :: IO (Int, UArray Int Char)
getAsCharArray1DWithLength = BS.getLine >>= \ !cs ->
  let !n = BS.length cs
      !ary = (U.listArray (1,n) $ unfoldr BS.uncons cs) :: UArray Int Char
  in return (n, ary)

-- n: number of lines
-- m: number of chars per a line
getAsCharArray2D :: Int -> Int -> IO (UArray (Int,Int) Char)
getAsCharArray2D !n !m = U.listArray ((1,1),(n,m)) . unfoldr BS.uncons . BS.concat <$> replicateM n BS.getLine

Score : 400 points

Problem Statement

We have a string S of length N consisting of R, G, and B.

Find the number of triples (i,~j,~k)~(1 \leq i < j < k \leq N) that satisfy both of the following conditions:

S_i \neq S_j, S_i \neq S_k, and S_j \neq S_k.

j - i \neq k - j.

Constraints

1 \leq N \leq 4000

S is a string of length N consisting of R, G, and B.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of triplets in question.

Sample Input 1

4
RRGB

Sample Output 1

1

Only the triplet (1,~3,~4) satisfies both conditions. The triplet (2,~3,~4) satisfies the first condition but not the second, so it does not count.

Sample Input 2

39
RBRBGRBGGBBRRGBBRRRBGGBRBGBRBGBRBBBGBBB

Sample Output 2

1800


{-# LANGUAGE BangPatterns     #-}
{-# LANGUAGE FlexibleContexts #-}
import           Control.Monad
import           Control.Monad.ST
import           Control.Monad.State
import           Data.Array.IArray
import           Data.Array.ST
import           Data.Array.Unboxed    (UArray)
import qualified Data.Array.Unboxed    as U
import           Data.Bits
import           Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import           Data.Char
import           Data.Graph
import           Data.Int              (Int64)
import           Data.List
import           Data.Maybe
import           Data.Proxy
import           Data.Sequence         (Seq, (<|), (><), (|>))
import qualified Data.Sequence         as Seq
import qualified Data.Set              as S
import           Data.STRef
import           Data.Vector.Unboxed   (Vector)
import qualified Data.Vector.Unboxed   as V
import           Numeric

main :: IO ()
main = do
  _ <- getLine
  s <- getLine
  print $ length [(i,j,k) |
                  (i,x) <- zip [1..] s,
                  (j,y) <- filter (\p -> snd p /= x) $ zip [(i+1)..] $ drop i s,
                  (k,z) <- filter (\p -> snd p /= x && snd p /= y) $ zip [(j+1)..] $ drop j s,
                  j-i /= k-j,
                  x/=y,
                  y/=z,
                  z/=x]

getAsInt :: IO [Int]
getAsInt =  unfoldr (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine

getAsIntLine :: Int -> IO [[Int]]
getAsIntLine !n = replicateM n getAsInt

getAsIntArray1Dr :: Int -> IO (UArray Int Int)
getAsIntArray1Dr !n = U.listArray (1,n) <$> getAsInt

getAsIntVec1Dr :: IO (Vector Int)
getAsIntVec1Dr = V.fromList <$> getAsInt

getAsIntArray1Dc :: Int -> IO (UArray Int Int)
getAsIntArray1Dc !n = U.listArray (1,n) . concat <$> getAsIntLine n

getAsIntVec1Dc :: Int -> IO (Vector Int)
getAsIntVec1Dc !n = V.fromList . concat <$> getAsIntLine n

-- n: number of lines
-- m: number of values per a line
getAsIntArray2D :: Int -> Int -> IO (UArray (Int,Int) Int)
getAsIntArray2D !n !m = U.listArray ((1,1),(n,m)) . concat <$> getAsIntLine n

getAsString :: IO [String]
getAsString = map BS.unpack . BS.words <$> BS.getLine

getAsCharArray1DWithLength :: IO (Int, UArray Int Char)
getAsCharArray1DWithLength = BS.getLine >>= \ !cs ->
  let !n = BS.length cs
      !ary = (U.listArray (1,n) $ unfoldr BS.uncons cs) :: UArray Int Char
  in return (n, ary)

-- n: number of lines
-- m: number of chars per a line
getAsCharArray2D :: Int -> Int -> IO (UArray (Int,Int) Char)
getAsCharArray2D !n !m = U.listArray ((1,1),(n,m)) . unfoldr BS.uncons . BS.concat <$> replicateM n BS.getLine

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE TypeFamilies #-}
import           Data.Maybe
import           Data.Int
import           Data.List
import           Data.Char
  -- import qualified Data.Vector.Unboxing as VU
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified Data.ByteString.Char8 as BS
import           Data.List (scanl')
import           Data.IORef
import           Control.Monad
import           Control.Monad.ST
import           Control.Monad.State.Strict
import           Control.Applicative
import           Debug.Trace
import           Text.Printf

readInt = BS.readInt . BS.dropWhile isSpace
getVector f = VU.unfoldr f <$> BS.getLine
getIntVector = getVector readInt
getBSVector = getVector BS.uncons
getInt = readLn :: IO Int

main = do
  n <- getInt
  s <- VU.fromList <$> getLine
  print $ ans s $ solve n

solve n = do
  i <- [0..n-3]
  j <- [i..n-2]
  k <- [j..n-1]
  guard $ j-i /= k-j -- && s VU.! i /= s VU.! j && s VU.! j /= s VU.! k && s VU.! k /= s VU.! i
  return (i,j,k)

ans s ijk = foldl' (\n m -> n + (cond1 m)) 0 ijk
  where
    cond1 (i,j,k) = if s VU.! i /= s VU.! j && s VU.! j /= s VU.! k && s VU.! k /= s VU.! i
                    then 1
                    else 0


{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE TypeFamilies #-}
import           Data.Maybe
import           Data.Int
import           Data.List
import           Data.Char
  -- import qualified Data.Vector.Unboxing as VU
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified Data.ByteString.Char8 as BS
import           Data.List (scanl')
import           Data.IORef
import           Control.Monad
import           Control.Monad.ST
import           Control.Monad.State.Strict
import           Control.Applicative
import           Debug.Trace
import           Text.Printf

readInt = BS.readInt . BS.dropWhile isSpace
getVector f = VU.unfoldr f <$> BS.getLine
getIntVector = getVector readInt
getBSVector = getVector BS.uncons
getInt = readLn :: IO Int

main = do
  n <- getInt
  s <- VU.fromList <$> getLine
  print $ solve n s

solve n s = length $ do
  i <- [0..n-3]
  j <- [i..n-2]
  k <- [j..n-1]
  guard $ j-i /= k-j && s VU.! i /= s VU.! j && s VU.! j /= s VU.! k && s VU.! k /= s VU.! i
  return (i,j,k)


{-# LANGUAGE
  ScopedTypeVariables, BangPatterns, TupleSections, ExplicitForAll,
  LambdaCase, MultiWayIf, Unsafe, RecordWildCards, FlexibleContexts, CPP,
  NoMonomorphismRestriction, GADTs, PatternGuards, MagicHash, UnboxedTuples,
  RankNTypes, EmptyDataDecls, EmptyCase, ViewPatterns, PolyKinds,
  TypeFamilies, OverloadedStrings, FlexibleInstances, UndecidableInstances,
  DefaultSignatures, GeneralizedNewtypeDeriving, StandaloneDeriving,
  DeriveGeneric, DeriveFunctor, DeriveDataTypeable, DeriveFoldable,
  DeriveTraversable, DeriveDataTypeable, FlexibleInstances,
  MultiParamTypeClasses, TypeApplications  #-}
{-# OPTIONS_GHC -O2 #-}

#define PHASE_FUSED [1]
#define PHASE_INNER [0]
#define INLINE_FUSED INLINE PHASE_FUSED
#define INLINE_INNER INLINE PHASE_INNER

import Prelude
import Data.Bits
import Data.List
import Data.Maybe
import Data.Tuple
import Data.Ord
import Data.Int
import Data.Word
import Data.Char
import Data.Ratio
import Data.Function
import Data.STRef
import Data.IORef
import Data.Monoid
import Data.Functor
import Data.Functor.Identity
import Data.Data
import Data.Typeable
import GHC.Generics
import System.IO
import System.IO.Unsafe (unsafeDupablePerformIO, unsafePerformIO)
import Control.Arrow
import Control.Applicative
import Control.Monad
import Control.Monad.Primitive
import Control.Monad.State.Strict
import Control.Monad.ST
import Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)
import qualified Control.Monad.ST.Lazy as STL
-- import Control.Monad.ST.Safe
import Control.DeepSeq
import Data.Coerce
import qualified Data.ByteString as BSW
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy as BSLW
import qualified Data.ByteString.Lazy.Char8 as BSL
import qualified Data.ByteString.Builder as BSB
import qualified Data.ByteString.Unsafe as BSU
import qualified Data.ByteString.Internal as BSU
import Data.IntMap (IntMap)
import qualified Data.IntMap.Strict as IMS
import qualified Data.IntMap.Lazy as IML
import Data.IntSet (IntSet)
import qualified Data.IntSet as IS
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified Data.Vector.Storable as VS
import qualified Data.Vector.Storable.Mutable as VSM
import qualified Data.Vector.Primitive as VP
import qualified Data.Vector.Primitive.Mutable as VPM
import qualified Data.Vector.Generic as VG
import qualified Data.Vector.Generic.Mutable as VGM
import qualified Data.Vector.Fusion.Bundle.Monadic as VFBM
import qualified Data.Vector.Fusion.Bundle as VFB
import qualified Data.Vector.Fusion.Stream.Monadic as VFSM
import qualified Data.Vector.Fusion.Bundle.Size as VFBS
import qualified Data.Vector.Fusion.Util as VFU
import qualified Data.Vector.Algorithms.Intro as VAIT
import qualified Data.Attoparsec.ByteString.Char8 as Atto
import Debug.Trace
import Unsafe.Coerce
import Foreign.ForeignPtr
import GHC.Exts (build, Int(..), Int#,
                 (+#), (*#), (-#), (<#), (>=#), (==#), quotRemInt#,
                 remInt#, uncheckedIShiftRL#, andI#, orI#,
                isTrue#, Addr#, Ptr(..))

main :: IO ()
main = do
  n <- readLn @ Int
  s <- getVecULn n $ (\case 'R' -> 0::Int; 'G' -> 1; 'B' -> 2) <$> rCharS
  let accum = VU.accumulate_ (+) (VU.replicate 3 (0::Int))
              s (VU.replicate n 1)
      omits = VU.sum $ (`VU.imap` s) $ \ !i !c ->
        VFB.length
        $ VG.stream
        $ VU.filter (\(!l,!r) -> l /= c && c /= r && r /= l)
        $ VU.zip (VG.unstream $ VG.streamR $ VU.take i s)
        $ VU.drop (i+1) s
  print $ VU.product accum - omits
  return ()

#define IL(f) {-# INLINE f #-}; f

IL(putBuilder) = BSB.hPutBuilder stdout

printVecInLines, printVecInSpcSepLn ::
  (VG.Vector v a, ShowAsBuilder a) => v a -> IO ()
IL(printVecInLines) = putBuilder . v2BLines
IL(printVecInSpcSepLn) = putBuilder . v2BSpcSepLn

class ShowAsBuilder a where
  showAsBuilder :: a -> BSB.Builder
  default showAsBuilder :: (Show a) => a -> BSB.Builder
  IL(showAsBuilder) = BSB.string8 . show

-- Inconsistent with show
instance (ShowAsBuilder a, VG.Vector v a) => ShowAsBuilder (v a) where
  IL(showAsBuilder) = v2BSpcSep

#define INS(t,f) instance ShowAsBuilder t where { IL(showAsBuilder)=f }
INS(Int,BSB.intDec)
INS(Int8,BSB.int8Dec)
INS(Int16,BSB.int16Dec)
INS(Int32,BSB.int32Dec)
INS(Int64,BSB.int64Dec)
INS(Word,BSB.wordDec)
INS(Word8,BSB.word8Dec)
INS(Word16,BSB.word16Dec)
INS(Word32,BSB.word32Dec)
INS(Word64,BSB.word64Dec)
INS(Integer,BSB.integerDec)
INS(Float,BSB.floatDec)
INS(Double,BSB.doubleDec)
-- INS(String,BSB.string8) -- Inconsistent with Show
-- INS(BS.ByteString,BSB.byteString) -- Inconsistent with Show
-- INS(BSL.ByteString,BSB.lazyByteString) -- Inconsisitent with Show
#undef INS

-- Inconsistent with Show
instance (ShowAsBuilder a, ShowAsBuilder b) => ShowAsBuilder (a,b) where
  IL(showAsBuilder) = showTupAsBuilder
instance (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c) =>
  ShowAsBuilder (a,b,c) where
  IL(showAsBuilder) = showTup3AsBuilder
instance (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c, ShowAsBuilder d) =>
  ShowAsBuilder (a,b,c,d) where
  IL(showAsBuilder) = showTup4AsBuilder

IL(showTupAsBuilderWith)
  :: (a -> BSB.Builder) -> (b -> BSB.Builder) -> (a,b) -> BSB.Builder
showTupAsBuilderWith showA showB
  = \(a,b) -> (showA a <>) $ BSB.char7 ' ' <> showB b
IL(showTupAsBuilder) :: (ShowAsBuilder a, ShowAsBuilder b)
  => (a,b) -> BSB.Builder
showTupAsBuilder = showTupAsBuilderWith showAsBuilder showAsBuilder

IL(showTup3AsBuilderWith) :: (a -> BSB.Builder) -> (b -> BSB.Builder) ->
  (c -> BSB.Builder) -> (a,b,c) -> BSB.Builder
showTup3AsBuilderWith showA showB showC
  = \(a,b,c) -> (showA a <>) $ (BSB.char7 ' ' <>) $ (showB b <>)
                $ (BSB.char7 ' ' <>) $ showC c
IL(showTup3AsBuilder) :: (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c)
  => (a,b,c) -> BSB.Builder
showTup3AsBuilder
  = showTup3AsBuilderWith showAsBuilder showAsBuilder showAsBuilder

IL(showTup4AsBuilderWith) :: (a -> BSB.Builder) -> (b -> BSB.Builder) ->
  (c -> BSB.Builder) -> (d -> BSB.Builder) -> (a,b,c,d) -> BSB.Builder
showTup4AsBuilderWith showA showB showC showD
  = \(a,b,c,d) -> (showA a <>) $ (BSB.char7 ' ' <>)
                  $ showTup3AsBuilderWith showB showC showD (b,c,d)
IL(showTup4AsBuilder) ::
  (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c, ShowAsBuilder d) =>
  (a,b,c,d) -> BSB.Builder
showTup4AsBuilder = showTup4AsBuilderWith showAsBuilder showAsBuilder
                    showAsBuilder showAsBuilder

v2BSpcSepLn, v2BSpcSep, v2BConcat, v2BLines ::
  (VG.Vector v a, ShowAsBuilder a)
  => v a -> BSB.Builder
IL(v2BSpcSepLn) = v2BSpcSepLnWith showAsBuilder
IL(v2BSpcSep) = v2BSpcSepWith showAsBuilder
IL(v2BConcat) = v2BConcatWith showAsBuilder
IL(v2BLines) = v2BLinesWith showAsBuilder

v2BSpcSepLnWith, v2BSpcSepWith, v2BConcatWith, v2BLinesWith ::
  (VG.Vector v a)
  => (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
IL(v2BSpcSepLnWith) = v2BSpcSepPostfWith $ BS.singleton '\n'
IL(v2BSpcSepWith) = v2BSpcSepPostfWith BS.empty
IL(v2BConcatWith) showFct = VG.foldr ((<>) . showFct) mempty
IL(v2BLinesWith) showFct
  = VG.foldr (\ a -> (showFct a <>) . (BSB.char7 '\n' <>)) mempty

v2BSpcSepPostf :: (VG.Vector v a, ShowAsBuilder a)
  => BS.ByteString -- ^ postfix
  -> v a -> BSB.Builder
IL(v2BSpcSepPostf) = (`v2BSpcSepPostfWith` showAsBuilder)

v2BSpcSepPostfWith :: (VG.Vector v a)
  => BS.ByteString -- ^ postfix
  -> (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
IL(v2BSpcSepPostfWith) = vecToBuilder BS.empty $ BS.singleton ' '

IL(vecToBuilder) :: (VG.Vector v a)
  => BS.ByteString -- ^ prefix
  -> BS.ByteString -- ^ separator
  -> BS.ByteString -- ^ postfix
  -> (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
vecToBuilder !prefix !separator !postfix
  = vecToBuilder_ (BSB.byteString prefix)
                  (BSB.byteString separator)
                  (BSB.byteString postfix)

IL(vecToBuilder_) :: (VG.Vector v a)
  => BSB.Builder -- ^ prefix
  -> BSB.Builder -- ^ separator
  -> BSB.Builder -- ^ postfix
  -> (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
vecToBuilder_ !prefix !separator !postfix showFct = \vec -> prefix <>
  VG.foldr
  (\ a rest !prefx -> prefx <> (showFct a <> rest separator))
  (const postfix) vec mempty

IL(evalVals) :: [a] -> [a]
evalVals xs = build $ \c n -> foldr (c $!) n xs
IL(forceVals) :: (NFData a) => [a] -> [a]
forceVals xs = build $ \c n -> foldr (c $!!) n xs

IL(readLnWith) :: StateT BS.ByteString Maybe a -> IO a
readLnWith parser = fromJust . evalStateT parser <$> BS.getLine
IL(readContentWith) :: StateT BSL.ByteString Maybe a -> IO a
readContentWith parser = fromJust . evalStateT parser <$> BSL.getContents

IL(getVecGLn) :: (VG.Vector v a) =>
  Int -> StateT BS.ByteString Maybe a -> IO (v a)
getVecGLn n s = VG.unfoldrN n (runStateT s) <$> BS.getLine
IL(getVecGRest) :: (VG.Vector v a) =>
  Int -> StateT BSL.ByteString Maybe a -> IO (v a)
getVecGRest n s = VG.unfoldrN n (runStateT s) <$> BSL.getContents
IL(getVecLn) :: Int -> StateT BS.ByteString Maybe a -> IO (V.Vector a)
getVecLn = getVecGLn
IL(getVecRest) :: Int -> StateT BSL.ByteString Maybe a -> IO (V.Vector a)
getVecRest = getVecGRest
IL(getVecULn) :: (VU.Unbox a) =>
  Int -> StateT BS.ByteString Maybe a -> IO (VU.Vector a)
getVecULn = getVecGLn
IL(getVecURest) :: (VU.Unbox a) =>
  Int -> StateT BSL.ByteString Maybe a -> IO (VU.Vector a)
getVecURest = getVecGRest

IL(rIntL) :: StateT BSL.ByteString Maybe Int
rIntL = skipSpecialL $ StateT BSL.readInt
IL(rIntS) :: StateT BS.ByteString Maybe Int
rIntS = skipSpecialS $ StateT BS.readInt
IL(rStrL) :: (MonadState BSL.ByteString m) => m BS.ByteString
rStrL = skipSpecialL $ BSL.toStrict <$> state (BSL.span (>='!'))
IL(rStrS) :: (MonadState BS.ByteString m) => m BS.ByteString
rStrS = skipSpecialS $ state $ BS.span (>='!')
IL(rCharL) :: StateT BSL.ByteString Maybe Char
rCharL = StateT BSL.uncons
IL(rCharS) :: StateT BS.ByteString Maybe Char
rCharS = StateT BS.uncons
IL(dropSpecialL) :: (MonadState BSL.ByteString m) => m ()
dropSpecialL = modify $ BSL.dropWhile (<'!')
IL(dropSpecialS) :: (MonadState BS.ByteString m) => m ()
dropSpecialS = modify $ BS.dropWhile (<'!')
IL(skipSpecialL) :: (MonadState BSL.ByteString m) => m a -> m a
skipSpecialL = (dropSpecialL *>)
IL(skipSpecialS) :: (MonadState BS.ByteString m) => m a -> m a
skipSpecialS = (dropSpecialS *>)

IL(linToMat) :: (VG.Vector v a) => Int -> Int -> v a -> V.Vector (v a)
linToMat h w lvec = vEvalElemsId $ V.generate h (\i -> VG.slice (i*w) w lvec)

IL(mLinToMat) :: (VGM.MVector v a) => Int -> Int -> v s a -> V.Vector (v s a)
mLinToMat h w lvec = vEvalElemsId $ V.generate h (\i -> VGM.slice (i*w) w lvec)

IL(unsafeAddrToSVec) :: Int -> Addr# -> VS.Vector Word8
unsafeAddrToSVec n addr
  = (`VS.unsafeFromForeignPtr0` n)
    $ unsafeDupablePerformIO
    $ newForeignPtr_ $ Ptr addr

IL(vEvalElemsId) :: (VG.Vector v a) => v a -> v a
vEvalElemsId = vMapFoldl (\ !_ !x -> (x,())) ()

IL(vEvalElems) :: (VG.Vector v a) => v a -> ()
vEvalElems = VG.foldl' (\ !_ !_ -> ()) ()

IL(vMapFoldl) :: (VG.Vector v b, VG.Vector v c) =>
  (a -> b -> (c,a)) -> a -> v b -> v c
vMapFoldl f a
  = VG.unstream . VFB.inplace (streamMapFoldl f a) id . VG.stream

streamMapFoldl :: (Functor m) =>
  (a -> b -> (c,a)) -> a -> VFSM.Stream m b -> VFSM.Stream m c
{-# INLINE_FUSED streamMapFoldl #-}
streamMapFoldl f a (VFSM.Stream step s) = VFSM.Stream step1 (a,s)
  where
    {-# INLINE_INNER step1 #-}
    step1 (a0,s0) =  (<$> step s0) $ \r -> case r of
      VFSM.Yield b s1 -> case f a0 b of (c,a1) -> VFSM.Yield c (a1,s1)
      VFSM.Skip    s1 -> VFSM.Skip (a0,s1)
      VFSM.Done       -> VFSM.Done

IL(svecToBS) :: VS.Vector Word8 -> BS.ByteString
svecToBS vec = BSU.fromForeignPtr ptr 0 len
  where (ptr, len) = VS.unsafeToForeignPtr0 vec

unlessM, whenM :: (Monad m) => m Bool -> m () -> m ()
IL(whenM) = (. flip when) . (>>=)
IL(unlessM) = (. flip unless) . (>>=)

IL(wrA) = A.writeArray
IL(rdA) = A.readArray
IL(mdA) = \arr f !i -> do
  ai <- rdA arr i
  let fai = f ai
  wrA arr i fai
  return (ai,fai)
{-# INLINE mdA' #-}
mdA' = \arr f !i -> do
  !ai <- rdA arr i
  let !fai = f ai
  wrA arr i fai
  return (ai,fai)
IL(swapA) = \arr !i !j -> do
  ai <- rdA arr i
  wrA arr i =<< rdA arr j
  wrA arr j ai

#define D(f,r,d)\
  IL(f) :: Integral a=>a->d; f=fromIntegral;\
  IL(r) :: String->d; r=read
#define C(f,r,g,h,d) D(f,r,d);\
  g,h :: RealFrac a=>a->d; IL(g)=floor; IL(h)=ceiling
C(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)
C(toInt,readInt,floorInt,ceilInt,Int)
C(toI8,readI8,floorI8,ceilI8,Int8)
C(toI16,readI16,floorI16,ceilI16,Int16)
C(toI32,readI32,floorI32,ceilI32,Int32)
C(toI64,readI64,floorI64,ceilI64,Int64)
C(toWord,readWord,floorWord,ceilWord,Word)
C(toW8,readW8,floorW8,ceilW8,Word8)
C(toW16,readW16,floorW16,ceilW16,Word16)
C(toW32,readW32,floorW32,ceilW32,Word32)
C(toW64,readW64,floorW64,ceilW64,Word64)
D(toDouble,readDouble,Double)
D(toFloat,readFloat,Float)
#undef D
#undef C

#define TS(f,a,m,init)\
  IL(f) :: forall e i s. (C(a,m) A.Ix i) => (i,i) -> init m (a i e); f
#define N(f,g,h,a,m)\
  TS(f,a,m,e->)=A.newArray;\
  TS(g,a,m,)=A.newArray_;\
  TS(h,a,m,[e]->)=A.newListArray
#define C(a,m)
N(newIOA,newIOA_,newIOAL,IOArray,IO)
N(newSTA,newSTA_,newSTAL,STArray s,ST s)
#undef C
#define C(a,m) MArray (a) e (m),
N(newIOUA,newIOUA_,newIOUAL,IOUArray,IO)
N(newSTUA,newSTUA_,newSTUAL,STUArray s,ST s)
#undef C
#undef N
#undef TS

#undef IL


-- {-# LANGUAGE BangPatterns #-}
-- {-# LANGUAGE ScopedTypeVariables #-}
-- {-# LANGUAGE FlexibleContexts #-}
-- {-# LANGUAGE ViewPatterns #-}
-- {-# LANGUAGE OverloadedStrings #-}

import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
--import qualified Data.Vector.Algorithms.Merge as VAM
--import qualified Data.Heap as HP
import qualified Data.ByteString.Char8 as BC
import qualified Data.Map as MP
import qualified Data.Set as ST
import qualified Data.Sequence as SQ
import Data.Array
import Data.Array.Unboxed
import Data.Array.ST
import Data.Array.IO
import Data.Maybe
import Data.Ord
import Data.Ratio
import Data.Char
import Data.Bits
import Data.List
import Data.Tuple
import Data.Functor
import Data.IORef
import Data.STRef
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Debug.Trace

--------------------------------------------------------------------------
step (r,g,b) (i,x)
    | x == 'R' = (ST.insert i r,g,b)
    | x == 'G' = (r,ST.insert i g, b)
    | x == 'B' = (r,g,ST.insert i b)

solve :: ST.Set Int -> ST.Set Int -> ST.Set Int -> Int
solve rs gs bs = res
    where
        rs' = ST.toList rs
        gs' = ST.toList gs
        res = loop [(r,g) | r<-rs',g<-gs']
        loop [] = 0
        loop ((i,j):xs)
            | even (i+j) = base - x - y - z + loop xs
            | otherwise = base - x - y + loop xs
            where
                base = ST.size bs
                x = if ST.member (b+d) bs then 1 else 0
                y = if ST.member (a-d) bs then 1 else 0
                z = if ST.member (a+d') bs then 1 else 0
                [a,b] = sort [i,j]
                d = b - a
                e = (b + a) `div` 2
                d' = e - a

main = do
    n <- int
    xs <- strBC
    let (r,g,b) = foldl' step  (ST.empty, ST.empty, ST.empty) $ zip [1..n] (BC.unpack xs)
    print $ solve r g b
--------------------------------------------------------------------------

-- Input Util
int :: IO Int
int = readLn

double :: IO Double
double = readLn

str :: IO String
str = getLine

strBC :: IO BC.ByteString
strBC = BC.getLine

sLineToIntL :: IO [Int]
sLineToIntL = BC.getLine >>= return . map (fst . fromJust . BC.readInt) . BC.words

sLineToDoubleL :: IO [Double]
sLineToDoubleL = getLine >>= return . map read . words

sLineToIntV :: Int -> IO (VU.Vector Int)
sLineToIntV n = BC.getLine >>= return . VU.unfoldrN n (BC.readInt . BC.dropWhile isSpace)

sLineToDoubleV :: Int -> IO (VU.Vector Double)
sLineToDoubleV n = BC.getLine >>= return . VU.fromList . map (read . BC.unpack) . BC.words

mLinesToIntL :: Int -> IO [Int]
mLinesToIntL n = replicateM n readLn

mLinesToDoubleL :: Int -> IO [Double]
mLinesToDoubleL n = replicateM n readLn

mLinesToIntV :: Int -> IO (VU.Vector Int)
mLinesToIntV n = VU.replicateM n readLn

mLinesToDoubleV :: Int -> IO (VU.Vector Double)
mLinesToDoubleV n = VU.replicateM n (BC.getLine >>= return . read . BC.unpack)

mLinesToTupleL :: Int -> IO [(Int, Int)]
mLinesToTupleL n = replicateM n (getLine >>= return . (\[a,b] -> (a,b)) . map read . words)

mLinesToTupleV :: Int -> IO (VU.Vector (Int, Int))
mLinesToTupleV n = VU.replicateM n $ do
    bs <- strBC
    let
        Just (a, bs') = BC.readInt $ BC.dropWhile isSpace bs
        Just (b, _) = BC.readInt $ BC.dropWhile isSpace bs'
    return (a,b)

mLinesToTripleV :: Int -> IO (VU.Vector (Int, Int, Int))
mLinesToTripleV n = VU.replicateM n $ do
    bs <- strBC
    let
        Just (a, bs') = BC.readInt $ BC.dropWhile isSpace bs
        Just (b, bs'') = BC.readInt $ BC.dropWhile isSpace bs'
        Just (c, _) = BC.readInt $ BC.dropWhile isSpace bs''
    return (a,b,c)

-- others
strToChr :: String -> Char
strToChr [x] = x

chrToStr :: Char -> String
chrToStr x = [x]

m1 :: Int -> Int
m1 x = subtract 1 x

toDouble :: Int -> Double
toDouble x = fromIntegral x

toInt :: Double -> Int
toInt x = floor x


main = do
  n <- readLn
  s <- getLine
  let r = length .filter (== 'R') $ s
      g = length .filter (== 'G') $ s
      b = length .filter (== 'B') $ s
      triplet = [(i,j,k) | i <- [0..n-1], j <- [i+1..n-1], let k = 2*j - i, k < n]
      diff = length . filter (\(i,j,k) -> (s!!i /= s!!j) && (s!!j /= s!!k) && (s!!i /= s!!k)) $ triplet
      rgb = r * g * b - diff
  print $ rgb


import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as BS
import qualified Data.Vector as V
import Data.List

main = abc162d

abc162d = do
    [n] <- getIntList
    s <- BS.getLine
    let rgbV = convRGB s (V.empty, V.empty, V.empty)
    print $ solveD rgbV

convRGB s (r,g,b)
    | BS.null s = (r,g,b)
    | BS.head s == 'R' = convRGB (BS.tail s) (V.cons n r,g,b)
    | BS.head s == 'G' = convRGB (BS.tail s) (r,V.cons n g,b)
    | BS.head s == 'B' = convRGB (BS.tail s) (r,g,V.cons n b)
    where n = V.length r + V.length g + V.length b + 1

solveD (r,g,b)
    | V.length r == 1 = subSolveD (V.head r, g, b)
    | otherwise = subSolveD (V.head r, g, b) + solveD (V.tail r, g, b)

subSolveD (r,g,b)
    | V.length g == 1 = subSubSolveD (r, V.head g, b)
    | otherwise = subSubSolveD (r, V.head g, b) + subSolveD (r, V.tail g, b)

subSubSolveD :: (Int, Int, V.Vector Int) -> Int
subSubSolveD (r,g,b)
    | g < r
        = V.length b - (if bgrBool then 1 else 0) - (if grbBool then 1 else 0) - (if xbxBool then 1 else 0)
    | r < g
        = V.length b - (if brgBool then 1 else 0) - (if rgbBool then 1 else 0) - (if xbxBool then 1 else 0)
    where bgrBool = V.elem (g - (r - g)) b
          grbBool = V.elem (r + (r - g)) b
          brgBool = V.elem (r - (g - r)) b
          rgbBool = V.elem (g + (g - r)) b
          xbxBool = even (r + g) && V.elem (div (r + g) 2) b

readInt = fst . fromJust . BS.readInteger
readIntList = map readInt . BS.words
getIntList = readIntList <$> BS.getLine


module Main where

import           Control.Monad
import           Debug.Trace
import qualified Data.Vector                   as V
import qualified Data.Vector.Mutable           as VM
import qualified Data.Vector.Unboxed           as VU
import qualified Data.Vector.Unboxed.Mutable   as VUM
import           Data.List
import qualified Data.ByteString               as BS
import qualified Data.ByteString.Char8         as BSC8
import           Data.Char
import           Data.Maybe
import           Data.Ord
import           Data.Vector.Algorithms.Search
import qualified Data.Array                    as A
import qualified Data.Array.Unboxed            as AU
import qualified Data.Array.IO                 as AIO

getvuil :: IO (VU.Vector Int)
getvuil = VU.unfoldr (BSC8.readInt . BSC8.dropWhile isSpace) <$> BSC8.getLine
readi :: BSC8.ByteString -> Int
readi = fst . fromJust . BSC8.readInt
readil :: BSC8.ByteString -> [Int]
readil = map readi . BSC8.words
geti :: IO Int
geti = readi <$> BSC8.getLine
getil :: IO [Int]
getil = readil <$> BSC8.getLine

getNis :: Int -> IO [(Int, BSC8.ByteString)]
getNis 0 = return []
getisl n = do
    [aFst, aSnd] <- BSC8.words <$> BSC8.getLine
    next         <- (getisl (n - 1))
    return ((readi aFst, aSnd) : next)

il2ss :: [Int] -> String
il2ss = unwords . map show

il2sn :: [Int] -> String
il2sn = unlines . map show

main :: IO ()
main = do
    aN <- geti
    aS <- VU.fromList <$> getLine
    let (rL, gL, bL) = searchS aS
    let rLV          = VU.fromList rL
    let gLV          = VU.fromList gL
    let bLV          = VU.fromList bL
    let
        ret = if (length rL == 0) || (length gL == 0) || (length bL == 0)
            then 0
            else VU.foldl
                (\acc1 x ->
                    acc1
                        + (VU.foldl
                              (\acc2 y ->
                                  acc2
                                      + (VU.foldl
                                            (\acc3 z ->
                                                let rP     = rLV VU.! x
                                                    gP     = gLV VU.! y
                                                    bP     = bLV VU.! z
                                                    sorted = sort [rP, gP, bP]
                                                in  if (  (sorted !! 1 * 2)
                                                       == ( (sorted !! 0)
                                                          + (sorted !! 2
                                                            )
                                                          )
                                                       )
                                                    then
                                                        acc3
                                                    else
                                                        acc3 + 1
                                            )
                                            0
                                            (VU.fromList
                                                [0 .. VU.length bLV - 1]
                                            )
                                        )
                              )
                              0
                              (VU.fromList [0 .. VU.length gLV - 1])
                          )
                )
                0
                (VU.fromList [0 .. VU.length rLV - 1])

    print ret

searchS :: VU.Vector Char -> ([Int], [Int], [Int])
searchS vec = searchS' vec (VU.length vec - 1) ([], [], [])

searchS'
    :: VU.Vector Char -> Int -> ([Int], [Int], [Int]) -> ([Int], [Int], [Int])
searchS' vec poi list@(rL, gL, bL)
    | poi == -1
    = list
    | otherwise
    = let c = vec VU.! poi
      in  case c of
              'R'       -> searchS' vec (poi - 1) ((poi + 1) : rL, gL, bL)
              'G'       -> searchS' vec (poi - 1) (rL, (poi + 1) : gL, bL)
              'B'       -> searchS' vec (poi - 1) (rL, gL, (poi + 1) : bL)
              otherwise -> list


import Data.List
main :: IO ()
main = do
  _ <- getLine
  s <- getLine
  let ss = zip [1,2 ..] s
  let rs = map fst $ filter (\(_, a) -> a == 'R') ss
  let gs = map fst $ filter (\(_, a) -> a == 'G') ss
  let bs = map fst $ filter (\(_, a) -> a == 'B') ss
  let ss = length [(r, g, b) | r <- rs, g <- gs, b <- bs, (abs(g - r) == abs (b - g)) ||(abs(b - r) == abs (g - b) || (abs (r- b) == abs (g - r)))]
  print $ (length rs) * (length gs) * (length bs) - ss


module Main where

import           Control.Monad
import           Debug.Trace
import qualified Data.Vector                   as V
import qualified Data.Vector.Mutable           as VM
import qualified Data.Vector.Unboxed           as VU
import qualified Data.Vector.Unboxed.Mutable   as VUM
import           Data.List
import qualified Data.ByteString               as BS
import qualified Data.ByteString.Char8         as BSC8
import           Data.Char
import           Data.Maybe
import           Data.Ord
import           Data.Vector.Algorithms.Search
import qualified Data.Array                    as A
import qualified Data.Array.Unboxed            as AU
import qualified Data.Array.IO                 as AIO

getvuil :: IO (VU.Vector Int)
getvuil = VU.unfoldr (BSC8.readInt . BSC8.dropWhile isSpace) <$> BSC8.getLine
readi :: BSC8.ByteString -> Int
readi = fst . fromJust . BSC8.readInt
readil :: BSC8.ByteString -> [Int]
readil = map readi . BSC8.words
geti :: IO Int
geti = readi <$> BSC8.getLine
getil :: IO [Int]
getil = readil <$> BSC8.getLine

getNis :: Int -> IO [(Int, BSC8.ByteString)]
getNis 0 = return []
getisl n = do
    [aFst, aSnd] <- BSC8.words <$> BSC8.getLine
    next         <- (getisl (n - 1))
    return ((readi aFst, aSnd) : next)

il2ss :: [Int] -> String
il2ss = unwords . map show

il2sn :: [Int] -> String
il2sn = unlines . map show

main :: IO ()
main = do
    aN <- geti
    aS <- VU.fromList <$> getLine
    let lastC         = VU.last aS
    let lastLastI = searchLastLast aS (VU.length aS - 2) lastC
    let lastLastC     = aS VU.! lastLastI
    let lastLastLastI = searchLastLastLast aS lastLastI lastC lastLastC

    let
        ret = if lastLastI == -1 || lastLastLastI == -1
            then 0
            else foldl
                (\acc1 x ->
                    let
                        firstI = x
                        firstC = aS VU.! x
                    in
                        acc1
                            + (foldl
                                  (\acc2 y ->
                                      let
                                          secondI = y
                                          secondC = aS VU.! y
                                          thirdK  = seleK firstC secondC
                                      in
                                          if firstC == secondC
                                              then acc2
                                              else
                                                  acc2
                                                      + (foldl
                                                            (\acc3 z ->
                                                                let
                                                                    thirdI = z
                                                                    thirdC =
                                                                        aS
                                                                            VU.! z
                                                                in
                                                                    if ((thirdC
                                                                        /= thirdK
                                                                        )
                                                                       || (2
                                                                          * secondI
                                                                          )
                                                                       == (firstI
                                                                          + thirdI
                                                                          )
                                                                       )
                                                                    then

                                                                        acc3
                                                                    else
                                                                        acc3 + 1
                                                            )
                                                            0
                                                            [y + 1 .. VU.length
                                                                    aS
                                                                - 1]
                                                        )
                                  )
                                  0
                                  [x + 1 .. lastLastI]
                              )
                )
                0
                [0 .. lastLastLastI]

    print ret

searchLastLast s x lastC =
    if s VU.! x == lastC then searchLastLast s (x - 1) lastC else x
searchLastLastLast s x lastC lastLastC =
    if s VU.! x == lastC || s VU.! x == lastLastC
        then searchLastLastLast s (x - 1) lastC lastLastC
        else x

seleK first second =
    let firstI = if first == 'R'
            then 1
            else if first == 'G' then 2 else if first == 'B' then 3 else 0
        secondI = if second == 'R'
            then 1
            else if second == 'G' then 2 else if second == 'B' then 3 else 0
        thirdI = firstI + secondI
    in  if thirdI == 3
            then 'B'
            else if thirdI == 4 then 'G' else if thirdI == 5 then 'R' else ' '


module Main where

import           Control.Monad
import           Debug.Trace
import qualified Data.Vector                   as V
import qualified Data.Vector.Mutable           as VM
import qualified Data.Vector.Unboxed           as VU
import qualified Data.Vector.Unboxed.Mutable   as VUM
import           Data.List
import qualified Data.ByteString               as BS
import qualified Data.ByteString.Char8         as BSC8
import           Data.Char
import           Data.Maybe
import           Data.Ord
import           Data.Vector.Algorithms.Search
import qualified Data.Array                    as A
import qualified Data.Array.Unboxed            as AU
import qualified Data.Array.IO                 as AIO

getvuil :: IO (VU.Vector Int)
getvuil = VU.unfoldr (BSC8.readInt . BSC8.dropWhile isSpace) <$> BSC8.getLine
readi :: BSC8.ByteString -> Int
readi = fst . fromJust . BSC8.readInt
readil :: BSC8.ByteString -> [Int]
readil = map readi . BSC8.words
geti :: IO Int
geti = readi <$> BSC8.getLine
getil :: IO [Int]
getil = readil <$> BSC8.getLine

getNis :: Int -> IO [(Int, BSC8.ByteString)]
getNis 0 = return []
getisl n = do
    [aFst, aSnd] <- BSC8.words <$> BSC8.getLine
    next         <- (getisl (n - 1))
    return ((readi aFst, aSnd) : next)

il2ss :: [Int] -> String
il2ss = unwords . map show

il2sn :: [Int] -> String
il2sn = unlines . map show

main :: IO ()
main = do
    aN <- geti
    aS <- VU.fromList <$> getLine
    let lastC         = VU.last aS
    let lastLastI = searchLastLast aS (VU.length aS - 2) lastC
    let lastLastC     = aS VU.! lastLastI
    let lastLastLastI = searchLastLastLast aS lastLastI lastC lastLastC

    let
        ret = foldl
            (\acc1 x ->
                let
                    firstI = x
                    firstC = aS VU.! x
                in
                    acc1
                        + (foldl
                              (\acc2 y ->
                                  let
                                      secondI = y
                                      secondC = aS VU.! y
                                      thirdK  = seleK firstC secondC
                                  in
                                      if firstC == secondC
                                          then acc2
                                          else
                                              acc2
                                                  + (foldl
                                                        (\acc3 z ->
                                                            let thirdI = z
                                                                thirdC =
                                                                        aS VU.! z
                                                            in  if (  (  thirdC
                                                                      /= thirdK
                                                                      )
                                                                   || ( 2
                                                                      * secondI
                                                                      )
                                                                   == ( firstI
                                                                      + thirdI
                                                                      )
                                                                   )
                                                                then

                                                                    acc3
                                                                else
                                                                    acc3 + 1
                                                        )
                                                        0
                                                        [y + 1 .. VU.length aS
                                                            - 1]
                                                    )
                              )
                              0
                              [x + 1 .. lastLastI]
                          )
            )
            0
            [0 .. lastLastLastI]

    print ret

searchLastLast s x lastC =
    if s VU.! x == lastC then searchLastLast s (x - 1) lastC else x
searchLastLastLast s x lastC lastLastC =
    if s VU.! x == lastC || s VU.! x == lastLastC
        then searchLastLastLast s (x - 1) lastC lastLastC
        else x

seleK first second =
    let firstI = if first == 'R'
            then 1
            else if first == 'G' then 2 else if first == 'B' then 3 else 0
        secondI = if second == 'R'
            then 1
            else if second == 'G' then 2 else if second == 'B' then 3 else 0
        thirdI = firstI + secondI
    in  if thirdI == 3
            then 'B'
            else if thirdI == 4 then 'G' else if thirdI == 5 then 'R' else ' '


import           Control.Monad
import qualified Data.Array.IO               as IO
import           Data.Bits
import qualified Data.ByteString.Char8       as BS
import           Data.Char
import           Data.Foldable
import           Data.List
import           Data.Maybe
import qualified Data.Sequence               as Seq
import qualified Data.Vector.Unboxed         as V
import qualified Data.Vector.Unboxed.Mutable as VM
import           Debug.Trace

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words
getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine
getIntVec n = V.unfoldrN n (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine

readInteger = fst . fromJust . BS.readInteger
readIntegerList = map readInteger . BS.words
getInteger = readInteger <$> BS.getLine
getIntegerList = readIntegerList <$> BS.getLine

main = do
  n <- getInt
  s <- getLine

  let checkIdx []     rs gs bs _ = (V.fromList rs, V.fromList gs, V.fromList bs)
      checkIdx (c:cs) rs gs bs i | c == 'R' = checkIdx cs (i:rs) gs bs (i+1)
                                 | c == 'G' = checkIdx cs rs (i:gs) bs (i+1)
                                 | c == 'B' = checkIdx cs rs gs (i:bs) (i+1)

      (rs, gs, bs) = checkIdx s [] [] [] 1 :: (V.Vector Int, V.Vector Int, V.Vector Int)

  ans <- VM.new 1
  VM.set ans (0::Int)

  let goodijk x y z = let [i, j, k] = sort [x, y, z]
                      in k - j /= j - i

  V.forM_ rs $ \i -> do
    V.forM_ gs $ \j -> do
      let c = V.length $ V.filter (\k -> goodijk i j k) bs
      t <- VM.read ans 0
      VM.write ans 0 (t+c)

  res <- VM.read ans (0::Int)
  print res


-- {-# LANGUAGE BangPatterns #-}
-- {-# LANGUAGE ScopedTypeVariables #-}
-- {-# LANGUAGE FlexibleContexts #-}
-- {-# LANGUAGE ViewPatterns #-}
-- {-# LANGUAGE OverloadedStrings #-}

import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified Data.Vector.Algorithms.Merge as VAM
import qualified Data.Heap as HP
import qualified Data.ByteString.Char8 as BC
import qualified Data.Map as MP
import qualified Data.Set as ST
import qualified Data.Sequence as SQ
import Data.Array
import Data.Array.Unboxed
import Data.Array.ST
import Data.Array.IO
import Data.Maybe
import Data.Ratio
import Data.Char
import Data.Bits
import Data.List
import Data.Tuple
import Data.Functor
import Data.IORef
import Data.STRef
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Debug.Trace

--------------------------------------------------------------------------
solve :: MP.Map Char [Int] -> Int
solve mp = res
    where
        Just rs = MP.lookup 'R' mp
        Just gs = MP.lookup 'G' mp
        Just bs = MP.lookup 'B' mp
        res = loop [(r,g) | r<-rs,g<-gs]
        loop [] = 0
        loop ((i,j):xs)
            | even (i+j) = length bs'' + loop xs
            | otherwise = length bs' + loop xs
            where
                bs'' = delete (a+d') $ delete (b+d) $ delete (a-d) bs
                bs' = delete (b+d) $ delete (a-d) bs
                [a,b] = sort [i,j]
                d = b - a
                e = (b + a) `div` 2
                d' = e - a

main = do
    n <- int
    xs <- foldl' (\mp (a,b) -> MP.insertWith (++) b [a] mp) (MP.fromList [('R',[]),('G',[]),('B',[])]) . (zip [1..n]) <$> str
    print $ solve xs
--------------------------------------------------------------------------

-- Input Util
int :: IO Int
int = readLn

double :: IO Double
double = readLn

str :: IO String
str = getLine

strBC :: IO BC.ByteString
strBC = BC.getLine

sLineToIntL :: IO [Int]
sLineToIntL = getLine >>= return . map read . words

sLineToDoubleL :: IO [Double]
sLineToDoubleL = getLine >>= return . map read . words

sLineToIntV :: Int -> IO (VU.Vector Int)
sLineToIntV n = BC.getLine >>= return . VU.unfoldrN n (BC.readInt . BC.dropWhile isSpace)

sLineToDoubleV :: Int -> IO (VU.Vector Double)
sLineToDoubleV n = BC.getLine >>= return . VU.fromList . map (read . BC.unpack) . BC.words

mLinesToIntL :: Int -> IO [Int]
mLinesToIntL n = replicateM n readLn

mLinesToDoubleL :: Int -> IO [Double]
mLinesToDoubleL n = replicateM n readLn

mLinesToIntV :: Int -> IO (VU.Vector Int)
mLinesToIntV n = VU.replicateM n readLn

mLinesToDoubleV :: Int -> IO (VU.Vector Double)
mLinesToDoubleV n = VU.replicateM n (BC.getLine >>= return . read . BC.unpack)

mLinesToTupleL :: Int -> IO [(Int, Int)]
mLinesToTupleL n = replicateM n (getLine >>= return . (\[a,b] -> (a,b)) . map read . words)

mLinesToTupleV :: Int -> IO (VU.Vector (Int, Int))
mLinesToTupleV n = VU.replicateM n $ do
    bs <- strBC
    let
        Just (a, bs') = BC.readInt $ BC.dropWhile isSpace bs
        Just (b, _) = BC.readInt $ BC.dropWhile isSpace bs'
    return (a,b)

mLinesToTripleV :: Int -> IO (VU.Vector (Int, Int, Int))
mLinesToTripleV n = VU.replicateM n $ do
    bs <- strBC
    let
        Just (a, bs') = BC.readInt $ BC.dropWhile isSpace bs
        Just (b, bs'') = BC.readInt $ BC.dropWhile isSpace bs'
        Just (c, _) = BC.readInt $ BC.dropWhile isSpace bs''
    return (a,b,c)

-- others
strToChr :: String -> Char
strToChr [x] = x

chrToStr :: Char -> String
chrToStr x = [x]

m1 :: Int -> Int
m1 x = subtract 1 x

toDouble :: Int -> Double
toDouble x = fromIntegral x

toInt :: Double -> Int
toInt x = floor x


{-# LANGUAGE
  ScopedTypeVariables, BangPatterns, TupleSections, ExplicitForAll,
  LambdaCase, MultiWayIf, Unsafe, RecordWildCards, FlexibleContexts, CPP,
  NoMonomorphismRestriction, GADTs, PatternGuards, MagicHash, UnboxedTuples,
  RankNTypes, EmptyDataDecls, EmptyCase, ViewPatterns, PolyKinds,
  TypeFamilies, OverloadedStrings, FlexibleInstances, UndecidableInstances,
  DefaultSignatures, GeneralizedNewtypeDeriving, StandaloneDeriving,
  DeriveGeneric, DeriveFunctor, DeriveDataTypeable, DeriveFoldable,
  DeriveTraversable, DeriveDataTypeable, FlexibleInstances,
  MultiParamTypeClasses, TypeApplications  #-}
{-# OPTIONS_GHC -O2 #-}

#define PHASE_FUSED [1]
#define PHASE_INNER [0]
#define INLINE_FUSED INLINE PHASE_FUSED
#define INLINE_INNER INLINE PHASE_INNER

import Prelude
import Data.Bits
import Data.List
import Data.Maybe
import Data.Tuple
import Data.Ord
import Data.Int
import Data.Word
import Data.Char
import Data.Ratio
import Data.Function
import Data.STRef
import Data.IORef
import Data.Monoid
import Data.Functor
import Data.Functor.Identity
import Data.Data
import Data.Typeable
import GHC.Generics
import System.IO
import System.IO.Unsafe (unsafeDupablePerformIO, unsafePerformIO)
import Control.Arrow
import Control.Applicative
import Control.Monad
import Control.Monad.Primitive
import Control.Monad.State.Strict
import Control.Monad.ST
import Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)
import qualified Control.Monad.ST.Lazy as STL
-- import Control.Monad.ST.Safe
import Control.DeepSeq
import Data.Coerce
import qualified Data.ByteString as BSW
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy as BSLW
import qualified Data.ByteString.Lazy.Char8 as BSL
import qualified Data.ByteString.Builder as BSB
import qualified Data.ByteString.Unsafe as BSU
import qualified Data.ByteString.Internal as BSU
import Data.IntMap (IntMap)
import qualified Data.IntMap.Strict as IMS
import qualified Data.IntMap.Lazy as IML
import Data.IntSet (IntSet)
import qualified Data.IntSet as IS
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified Data.Vector.Storable as VS
import qualified Data.Vector.Storable.Mutable as VSM
import qualified Data.Vector.Primitive as VP
import qualified Data.Vector.Primitive.Mutable as VPM
import qualified Data.Vector.Generic as VG
import qualified Data.Vector.Generic.Mutable as VGM
import qualified Data.Vector.Fusion.Bundle.Monadic as VFBM
import qualified Data.Vector.Fusion.Bundle as VFB
import qualified Data.Vector.Fusion.Stream.Monadic as VFSM
import qualified Data.Vector.Fusion.Bundle.Size as VFBS
import qualified Data.Vector.Fusion.Util as VFU
import qualified Data.Vector.Algorithms.Intro as VAIT
import qualified Data.Attoparsec.ByteString.Char8 as Atto
import Debug.Trace
import Unsafe.Coerce
import Foreign.ForeignPtr
import GHC.Exts (build, Int(..), Int#,
                 (+#), (*#), (-#), (<#), (>=#), (==#), quotRemInt#,
                 remInt#, uncheckedIShiftRL#, andI#, orI#,
                isTrue#, Addr#, Ptr(..))

main :: IO ()
main = do
  n <- readLn @ Int
  s <- getVecULn n $ (\case 'R' -> 0::Int; 'G' -> 1; 'B' -> 2) <$> rCharS
  let accum = VU.accumulate_ (+) (VU.replicate 3 (0::Int))
              s (VU.replicate n 1)
      omits = VU.sum $ VU.generate (n-2) $ \ !i ->
        VFB.length $ VG.stream
        $ (`VU.filter` VU.enumFromN (1::Int) (shiftR (n-1-i) 1))
        $ \ !d -> s VU.! i /= s VU.! (i+d) && s VU.! (i+d) /= s VU.! (i+2*d)
                  && s VU.! i /= s VU.! (i+2*d)
  print $ VU.product accum - omits
  return ()

#define IL(f) {-# INLINE f #-}; f

IL(putBuilder) = BSB.hPutBuilder stdout

printVecInLines, printVecInSpcSepLn ::
  (VG.Vector v a, ShowAsBuilder a) => v a -> IO ()
IL(printVecInLines) = putBuilder . v2BLines
IL(printVecInSpcSepLn) = putBuilder . v2BSpcSepLn

class ShowAsBuilder a where
  showAsBuilder :: a -> BSB.Builder
  default showAsBuilder :: (Show a) => a -> BSB.Builder
  IL(showAsBuilder) = BSB.string8 . show

-- Inconsistent with show
instance (ShowAsBuilder a, VG.Vector v a) => ShowAsBuilder (v a) where
  IL(showAsBuilder) = v2BSpcSep

#define INS(t,f) instance ShowAsBuilder t where { IL(showAsBuilder)=f }
INS(Int,BSB.intDec)
INS(Int8,BSB.int8Dec)
INS(Int16,BSB.int16Dec)
INS(Int32,BSB.int32Dec)
INS(Int64,BSB.int64Dec)
INS(Word,BSB.wordDec)
INS(Word8,BSB.word8Dec)
INS(Word16,BSB.word16Dec)
INS(Word32,BSB.word32Dec)
INS(Word64,BSB.word64Dec)
INS(Integer,BSB.integerDec)
INS(Float,BSB.floatDec)
INS(Double,BSB.doubleDec)
-- INS(String,BSB.string8) -- Inconsistent with Show
-- INS(BS.ByteString,BSB.byteString) -- Inconsistent with Show
-- INS(BSL.ByteString,BSB.lazyByteString) -- Inconsisitent with Show
#undef INS

-- Inconsistent with Show
instance (ShowAsBuilder a, ShowAsBuilder b) => ShowAsBuilder (a,b) where
  IL(showAsBuilder) = showTupAsBuilder
instance (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c) =>
  ShowAsBuilder (a,b,c) where
  IL(showAsBuilder) = showTup3AsBuilder
instance (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c, ShowAsBuilder d) =>
  ShowAsBuilder (a,b,c,d) where
  IL(showAsBuilder) = showTup4AsBuilder

IL(showTupAsBuilderWith)
  :: (a -> BSB.Builder) -> (b -> BSB.Builder) -> (a,b) -> BSB.Builder
showTupAsBuilderWith showA showB
  = \(a,b) -> (showA a <>) $ BSB.char7 ' ' <> showB b
IL(showTupAsBuilder) :: (ShowAsBuilder a, ShowAsBuilder b)
  => (a,b) -> BSB.Builder
showTupAsBuilder = showTupAsBuilderWith showAsBuilder showAsBuilder

IL(showTup3AsBuilderWith) :: (a -> BSB.Builder) -> (b -> BSB.Builder) ->
  (c -> BSB.Builder) -> (a,b,c) -> BSB.Builder
showTup3AsBuilderWith showA showB showC
  = \(a,b,c) -> (showA a <>) $ (BSB.char7 ' ' <>) $ (showB b <>)
                $ (BSB.char7 ' ' <>) $ showC c
IL(showTup3AsBuilder) :: (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c)
  => (a,b,c) -> BSB.Builder
showTup3AsBuilder
  = showTup3AsBuilderWith showAsBuilder showAsBuilder showAsBuilder

IL(showTup4AsBuilderWith) :: (a -> BSB.Builder) -> (b -> BSB.Builder) ->
  (c -> BSB.Builder) -> (d -> BSB.Builder) -> (a,b,c,d) -> BSB.Builder
showTup4AsBuilderWith showA showB showC showD
  = \(a,b,c,d) -> (showA a <>) $ (BSB.char7 ' ' <>)
                  $ showTup3AsBuilderWith showB showC showD (b,c,d)
IL(showTup4AsBuilder) ::
  (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c, ShowAsBuilder d) =>
  (a,b,c,d) -> BSB.Builder
showTup4AsBuilder = showTup4AsBuilderWith showAsBuilder showAsBuilder
                    showAsBuilder showAsBuilder

v2BSpcSepLn, v2BSpcSep, v2BConcat, v2BLines ::
  (VG.Vector v a, ShowAsBuilder a)
  => v a -> BSB.Builder
IL(v2BSpcSepLn) = v2BSpcSepLnWith showAsBuilder
IL(v2BSpcSep) = v2BSpcSepWith showAsBuilder
IL(v2BConcat) = v2BConcatWith showAsBuilder
IL(v2BLines) = v2BLinesWith showAsBuilder

v2BSpcSepLnWith, v2BSpcSepWith, v2BConcatWith, v2BLinesWith ::
  (VG.Vector v a)
  => (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
IL(v2BSpcSepLnWith) = v2BSpcSepPostfWith $ BS.singleton '\n'
IL(v2BSpcSepWith) = v2BSpcSepPostfWith BS.empty
IL(v2BConcatWith) showFct = VG.foldr ((<>) . showFct) mempty
IL(v2BLinesWith) showFct
  = VG.foldr (\ a -> (showFct a <>) . (BSB.char7 '\n' <>)) mempty

v2BSpcSepPostf :: (VG.Vector v a, ShowAsBuilder a)
  => BS.ByteString -- ^ postfix
  -> v a -> BSB.Builder
IL(v2BSpcSepPostf) = (`v2BSpcSepPostfWith` showAsBuilder)

v2BSpcSepPostfWith :: (VG.Vector v a)
  => BS.ByteString -- ^ postfix
  -> (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
IL(v2BSpcSepPostfWith) = vecToBuilder BS.empty $ BS.singleton ' '

IL(vecToBuilder) :: (VG.Vector v a)
  => BS.ByteString -- ^ prefix
  -> BS.ByteString -- ^ separator
  -> BS.ByteString -- ^ postfix
  -> (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
vecToBuilder !prefix !separator !postfix
  = vecToBuilder_ (BSB.byteString prefix)
                  (BSB.byteString separator)
                  (BSB.byteString postfix)

IL(vecToBuilder_) :: (VG.Vector v a)
  => BSB.Builder -- ^ prefix
  -> BSB.Builder -- ^ separator
  -> BSB.Builder -- ^ postfix
  -> (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
vecToBuilder_ !prefix !separator !postfix showFct = \vec -> prefix <>
  VG.foldr
  (\ a rest !prefx -> prefx <> (showFct a <> rest separator))
  (const postfix) vec mempty

IL(evalVals) :: [a] -> [a]
evalVals xs = build $ \c n -> foldr (c $!) n xs
IL(forceVals) :: (NFData a) => [a] -> [a]
forceVals xs = build $ \c n -> foldr (c $!!) n xs

IL(readLnWith) :: StateT BS.ByteString Maybe a -> IO a
readLnWith parser = fromJust . evalStateT parser <$> BS.getLine
IL(readContentWith) :: StateT BSL.ByteString Maybe a -> IO a
readContentWith parser = fromJust . evalStateT parser <$> BSL.getContents

IL(getVecGLn) :: (VG.Vector v a) =>
  Int -> StateT BS.ByteString Maybe a -> IO (v a)
getVecGLn n s = VG.unfoldrN n (runStateT s) <$> BS.getLine
IL(getVecGRest) :: (VG.Vector v a) =>
  Int -> StateT BSL.ByteString Maybe a -> IO (v a)
getVecGRest n s = VG.unfoldrN n (runStateT s) <$> BSL.getContents
IL(getVecLn) :: Int -> StateT BS.ByteString Maybe a -> IO (V.Vector a)
getVecLn = getVecGLn
IL(getVecRest) :: Int -> StateT BSL.ByteString Maybe a -> IO (V.Vector a)
getVecRest = getVecGRest
IL(getVecULn) :: (VU.Unbox a) =>
  Int -> StateT BS.ByteString Maybe a -> IO (VU.Vector a)
getVecULn = getVecGLn
IL(getVecURest) :: (VU.Unbox a) =>
  Int -> StateT BSL.ByteString Maybe a -> IO (VU.Vector a)
getVecURest = getVecGRest

IL(rIntL) :: StateT BSL.ByteString Maybe Int
rIntL = skipSpecialL $ StateT BSL.readInt
IL(rIntS) :: StateT BS.ByteString Maybe Int
rIntS = skipSpecialS $ StateT BS.readInt
IL(rStrL) :: (MonadState BSL.ByteString m) => m BS.ByteString
rStrL = skipSpecialL $ BSL.toStrict <$> state (BSL.span (>='!'))
IL(rStrS) :: (MonadState BS.ByteString m) => m BS.ByteString
rStrS = skipSpecialS $ state $ BS.span (>='!')
IL(rCharL) :: StateT BSL.ByteString Maybe Char
rCharL = StateT BSL.uncons
IL(rCharS) :: StateT BS.ByteString Maybe Char
rCharS = StateT BS.uncons
IL(dropSpecialL) :: (MonadState BSL.ByteString m) => m ()
dropSpecialL = modify $ BSL.dropWhile (<'!')
IL(dropSpecialS) :: (MonadState BS.ByteString m) => m ()
dropSpecialS = modify $ BS.dropWhile (<'!')
IL(skipSpecialL) :: (MonadState BSL.ByteString m) => m a -> m a
skipSpecialL = (dropSpecialL *>)
IL(skipSpecialS) :: (MonadState BS.ByteString m) => m a -> m a
skipSpecialS = (dropSpecialS *>)

IL(linToMat) :: (VG.Vector v a) => Int -> Int -> v a -> V.Vector (v a)
linToMat h w lvec = vEvalElemsId $ V.generate h (\i -> VG.slice (i*w) w lvec)

IL(mLinToMat) :: (VGM.MVector v a) => Int -> Int -> v s a -> V.Vector (v s a)
mLinToMat h w lvec = vEvalElemsId $ V.generate h (\i -> VGM.slice (i*w) w lvec)

IL(unsafeAddrToSVec) :: Int -> Addr# -> VS.Vector Word8
unsafeAddrToSVec n addr
  = (`VS.unsafeFromForeignPtr0` n)
    $ unsafeDupablePerformIO
    $ newForeignPtr_ $ Ptr addr

IL(vEvalElemsId) :: (VG.Vector v a) => v a -> v a
vEvalElemsId = vMapFoldl (\ !_ !x -> (x,())) ()

IL(vEvalElems) :: (VG.Vector v a) => v a -> ()
vEvalElems = VG.foldl' (\ !_ !_ -> ()) ()

IL(vMapFoldl) :: (VG.Vector v b, VG.Vector v c) =>
  (a -> b -> (c,a)) -> a -> v b -> v c
vMapFoldl f a
  = VG.unstream . VFB.inplace (streamMapFoldl f a) id . VG.stream

streamMapFoldl :: (Functor m) =>
  (a -> b -> (c,a)) -> a -> VFSM.Stream m b -> VFSM.Stream m c
{-# INLINE_FUSED streamMapFoldl #-}
streamMapFoldl f a (VFSM.Stream step s) = VFSM.Stream step1 (a,s)
  where
    {-# INLINE_INNER step1 #-}
    step1 (a0,s0) =  (<$> step s0) $ \r -> case r of
      VFSM.Yield b s1 -> case f a0 b of (c,a1) -> VFSM.Yield c (a1,s1)
      VFSM.Skip    s1 -> VFSM.Skip (a0,s1)
      VFSM.Done       -> VFSM.Done

IL(svecToBS) :: VS.Vector Word8 -> BS.ByteString
svecToBS vec = BSU.fromForeignPtr ptr 0 len
  where (ptr, len) = VS.unsafeToForeignPtr0 vec

unlessM, whenM :: (Monad m) => m Bool -> m () -> m ()
IL(whenM) = (. flip when) . (>>=)
IL(unlessM) = (. flip unless) . (>>=)

IL(wrA) = A.writeArray
IL(rdA) = A.readArray
IL(mdA) = \arr f !i -> do
  ai <- rdA arr i
  let fai = f ai
  wrA arr i fai
  return (ai,fai)
{-# INLINE mdA' #-}
mdA' = \arr f !i -> do
  !ai <- rdA arr i
  let !fai = f ai
  wrA arr i fai
  return (ai,fai)
IL(swapA) = \arr !i !j -> do
  ai <- rdA arr i
  wrA arr i =<< rdA arr j
  wrA arr j ai

#define D(f,r,d)\
  IL(f) :: Integral a=>a->d; f=fromIntegral;\
  IL(r) :: String->d; r=read
#define C(f,r,g,h,d) D(f,r,d);\
  g,h :: RealFrac a=>a->d; IL(g)=floor; IL(h)=ceiling
C(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)
C(toInt,readInt,floorInt,ceilInt,Int)
C(toI8,readI8,floorI8,ceilI8,Int8)
C(toI16,readI16,floorI16,ceilI16,Int16)
C(toI32,readI32,floorI32,ceilI32,Int32)
C(toI64,readI64,floorI64,ceilI64,Int64)
C(toWord,readWord,floorWord,ceilWord,Word)
C(toW8,readW8,floorW8,ceilW8,Word8)
C(toW16,readW16,floorW16,ceilW16,Word16)
C(toW32,readW32,floorW32,ceilW32,Word32)
C(toW64,readW64,floorW64,ceilW64,Word64)
D(toDouble,readDouble,Double)
D(toFloat,readFloat,Float)
#undef D
#undef C

#define TS(f,a,m,init)\
  IL(f) :: forall e i s. (C(a,m) A.Ix i) => (i,i) -> init m (a i e); f
#define N(f,g,h,a,m)\
  TS(f,a,m,e->)=A.newArray;\
  TS(g,a,m,)=A.newArray_;\
  TS(h,a,m,[e]->)=A.newListArray
#define C(a,m)
N(newIOA,newIOA_,newIOAL,IOArray,IO)
N(newSTA,newSTA_,newSTAL,STArray s,ST s)
#undef C
#define C(a,m) MArray (a) e (m),
N(newIOUA,newIOUA_,newIOUAL,IOUArray,IO)
N(newSTUA,newSTUA_,newSTUAL,STUArray s,ST s)
#undef C
#undef N
#undef TS

#undef IL


main = do
  n <- readLn
  s <- getLine
  let sdif i j = s!!(i-1) /= s!!(j-1)
  print . length $ [(i,j,k) | i<-[1..n], j<-[i+1..n], k<-[j+1..n], ((j-i) /= (k-j)) && sdif i j && sdif i k && sdif j k]


import qualified Data.ByteString.Char8 as BS
import Data.Maybe

readInt = fst . fromJust . BS.readInt

readIntList = map readInt . BS.words

getIntList = readIntList <$> BS.getLine

main = do
  [x, y, z] <- getIntList
  putStrLn $ (show z) ++ " " ++ (show x) ++ " " ++ (show y)

Score : 100 points

Problem Statement

We have three boxes A, B, and C, each of which contains an integer.

Currently, the boxes A, B, and C contain the integers X, Y, and Z, respectively.

We will now do the operations below in order. Find the content of each box afterward.

Swap the contents of the boxes A and B

Swap the contents of the boxes A and C

Constraints

1 \leq X,Y,Z \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y Z

Output

Print the integers contained in the boxes A, B, and C, in this order, with space in between.

Sample Input 1

1 2 3

Sample Output 1

3 1 2

After the contents of the boxes A and B are swapped, A, B, and C contain 2, 1, and 3, respectively.

Then, after the contents of A and C are swapped, A, B, and C contain 3, 1, and 2, respectively.

Sample Input 2

100 100 100

Sample Output 2

100 100 100

Sample Input 3

41 59 31

Sample Output 3

31 41 59


main = do
  [a,b,c] <- map (read::String->Int) . words <$> getLine
  putStrLn . unwords . map show $ [c,a,b]
  return ()


import Control.Applicative

result :: Int -> Int -> Int -> String
result a b c = show a ++ " " ++ show b ++ " " ++ show c

main :: IO ()
main = do
    [a, b, c] <- map read . words <$> getLine
    putStrLn $ result c a b


import Data.Char
import Data.List
import System.IO
import Control.Applicative
import Control.Monad
-- https://hoogle.haskell.org で関数検索

{- お客様の中でHaskellを書ける方はいらっしゃいますか？
    と、Haskellの例がなくて困っていたところを @tanakh さんに助けて頂きました。本当にありがとうございました。-}
main :: IO ()
main = do
    [a,b,c] <- getIntegerList
    putStrLn $ (show c) ++ " " ++ (show a) ++ " " ++ (show b)

{-
main :: IO ()
main = do
    -- 整数の入力
    a <- readLn
    -- スペース区切り整数の入力
    [b, c] <- getIntegerList

    --[b, c] <- map read . words <$> getLine
    -- 文字列の入力
    s <- getLine
    -- 出力
    putStrLn $ show (a + b + c) ++ " " ++ s
-}

-- レイアウト規則

fac 0 = 1
fac n = n * fac (n-1)

-- it ... 前回の結果を保存
-- :l :load  ロードする
-- :set +m 複数行
-- http://www.kotha.net/ghcguide_ja/latest/ghci.html#ghci-introduction 参考資料
--
-- sum read show min max abs
-- head tail take drop ++ (n:ns)      takewhile dropwhile odd [1..10]
-- zip id const length /= 'div' 'mod' cons
-- fst first(tuple) snd second(tuple)
--any all

--ラムダ式　( \x -> x+x )
-- map f [1..10]
--   where f x = x^2 +1

rabs n | n>=0 =n
           | otherwise = -n

xor :: Bool -> Bool -> Bool
xor True    True    = False
xor False  False   = False
xor _         _          = True

halve xs = (take half xs,drop half xs)
        where half = (length  xs) `div` 2

safetail xs
        | xs==[]      = []
        | otherwise = tail xs

fibs n = [ x^2 | x <- [1 .. n] ]

factors n = [ k | k <- [1..n] , n `mod` k == 0 ]
prime n = factors n == [1, n]

-- sum xs = foldr (+) 0 xs

compose xs = foldr (.) id xs

count x = length . filter (== x)
rmdups [] = []
rmdups (x:xs) = x: rmdups (filter (/=x) xs)

unfold fin makeele next x
        | fin x = []
        | otherwise = makeele x : unfold fin makeele next (next x)

int2bit num = unfold (==0) (`mod`2) (`div`2) num

-- type ...型に別名をつける　再起不可能
-- data ...再帰可能　全く新しい型
-- newtype ...型に別名をつけるが内部上も別物として扱われる　安全性を高めるため使う　再帰可能！
-- instance Eq Bool where
--       False == False = True
--       True  ==  True = True
--       _       ==   _      = False

-- deriving (Eq, Ord, Show, Read)
-- getChar putChar return getLine putStr putStrLn

-- cls = putStr "\ESC[2J"  画面クリア

-- FileName   : 164a
-- CreatedDate: 2020-04-26 20:56:13

--------------------------------------------  https://atcoder.jp/contests/abc164/submissions/12342628

getIntList        = map (read :: String -> Int) . words <$> getLine
getIntegerList    = map (read :: String -> Integer) . words <$> getLine
getIntegerListN m = map (read :: String -> Integer) <$> replicateM m getLine

base :: Integer
base = 1000000007

plus :: Integer -> Integer -> Integer
plus a b = (a+b) `mod` base

times :: Integer -> Integer -> Integer
times a b = a * b `mod` base

minus :: Integer -> Integer -> Integer
minus a b
   | a < b     = a-b + base
   | otherwise = a-b

power :: Integer -> Integer -> Integer
power n k
   | k == 0         = 1
   | k `mod` 2 == 0 = power (times n n) (k`div`2)
   | otherwise      = times n $! power n (k-1)

inv :: Integer -> Integer
inv n = power n $ base - 2

binom :: Integer -> Integer -> Integer
binom n m
   | (n-m) < m = times (foldr times 1 [m+1..n]) $ inv $ foldr times 1 [1..n-m]
   | otherwise = times (foldr times 1 [n-m+1..n]) $ inv $ foldr times 1 [1..m]


main=do
 [a,b,c]<-words<$>getLine
 putStrLn$c++" "++a++" "++b


import Control.Monad
import Data.Maybe
import Data.List
import qualified Data.ByteString.Char8 as BS

main = abc161a

abc161a = do
    [a, b, c] <- getIntList
    putStrLn $ show c ++ " " ++ show a ++ " " ++ show b

readInt = fst . fromJust . BS.readInteger
readIntList = map readInt . BS.words
getIntList = readIntList <$> BS.getLine
getIntNList n = map readIntList <$> replicateM (fromIntegral n) BS.getLine


main = do
   [a,b,c] <- words <$> getLine
   putStrLn $ c ++ " " ++ a ++ " " ++ b


{-# LANGUAGE BangPatterns, OverloadedStrings #-}

import Control.Monad
import Data.List
import Data.Bits
import Debug.Trace
import Data.Maybe
import qualified Data.ByteString.Char8 as C

main :: IO ()
main = do
  [x, y, z] <- readInts
  solve x y z

solve x y z = putStr (show z) >> putStr " " >> putStr (show x) >> putStr " " >> putStrLn (show y)

-- 以下ライブラリ

readInts :: IO [Int]
readInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine

readNInts :: Int -> IO [[Int]]
readNInts = flip replicateM readInts

readIntegers :: IO [Integer]
readIntegers = map (fst . fromJust . C.readInteger) . C.words <$> C.getLine

readNIntegers :: Int -> IO [[Integer]]
readNIntegers = flip replicateM readIntegers

getNLns :: Int -> IO [String]
getNLns = flip replicateM getLine


import           Control.Monad
import           Control.Monad.ST
import qualified Data.Array                  as A
import qualified Data.Array.ST               as ST
import qualified Data.Array.Unboxed          as AU
import           Data.Bits
import qualified Data.ByteString.Char8       as BS
import           Data.Char
import           Data.Int
import qualified Data.IntMap                 as IM
import           Data.List
import qualified Data.Map                    as M
import           Data.Maybe
import           Data.Ord
import qualified Data.Set                    as S
import           Data.Time
import qualified Data.Vector                 as V
import qualified Data.Vector.Mutable         as VM
import qualified Data.Vector.Unboxed         as VU
import qualified Data.Vector.Unboxed.Mutable as VUM

readInt :: IO [Int]
readInt = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine

readInts :: Int -> IO [[Int]]
readInts n = replicateM n readInt

readInteger :: IO [Integer]
readInteger = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine

readIntegers :: Int -> IO [[Integer]]
readIntegers n = replicateM n readInteger

readString :: IO [String]
readString = map BS.unpack . BS.words <$> BS.getLine

readStrings :: Int -> IO [[String]]
readStrings n = replicateM n <$> readString

toPair :: [a] -> (a, a)
toPair [x, y] = (x, y)

count :: Eq a => a -> [a] -> Int
count a as = length $ filter (== a) as

main = do
  [x, y, z] <- readInt
  putStrLn $ show z ++ " " ++ show x ++ " " ++ show y


import Data.List
main = do
  [_,m] <- map (read::String->Int) . words <$> getLine
  items <- map (read::String->Int) . words <$> getLine
  let selectableitems = map (selectable items m) items
  putStrLn $ if m<=(length . filter (==True)) selectableitems then "Yes" else "No"

selectable items m item = if item*4*m < sum items then False else True

Score : 200 points

Problem Statement

We have held a popularity poll for N items on sale. Item i received A_i votes.

From these N items, we will select M as popular items. However, we cannot select an item with less than \dfrac{1}{4M} of the total number of votes.

If M popular items can be selected, print Yes; otherwise, print No.

Constraints

1 \leq M \leq N \leq 100

1 \leq A_i \leq 1000

A_i are distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 ... A_N

Output

If M popular items can be selected, print Yes; otherwise, print No.

Sample Input 1

4 1
5 4 2 1

Sample Output 1

Yes

There were 12 votes in total. The most popular item received 5 votes, and we can select it.

Sample Input 2

3 2
380 19 1

Sample Output 2

No

There were 400 votes in total. The second and third most popular items received less than \dfrac{1}{4\times 2} of the total number of votes, so we cannot select them. Thus, we cannot select two popular items.

Sample Input 3

12 3
4 56 78 901 2 345 67 890 123 45 6 789

Sample Output 3

Yes


{-# LANGUAGE Strict #-}
import qualified Data.ByteString.Char8 as B
import           Data.List             (sort, unfoldr)

main :: IO ()
main = do
  [n, m] <- readIntsLn
  as <- readIntsLn
  putStrLn $ if solve n m as then "Yes" else "No"

solve :: Int -> Int -> [Int] -> Bool
solve _ m as = all (>= (s + (4 * m) - 1) `div` (4 * m)) (take m as')
  where as' = reverse $ sort as
        s = sum as

readIntsLn :: IO [Int]
readIntsLn = unfoldr (B.readInt . B.dropWhile (== ' ')) <$> B.getLine


main :: IO()
main = do
 [n,m] <- map read . words <$> getLine :: IO[Int]
 ak <- map read . words <$> getLine :: IO[Int]
 let ans = if length (filter (\x -> (4 * x * m) >= (sum ak)) ak) >= m then "Yes" else "No"
 putStr $ ans


main :: IO()
main = do
 [n,m] <- map read . words <$> getLine :: IO[Int]
 ak <- map read . words <$> getLine :: IO[Int]
 let ans = if length (filter (\x -> (4 * x * m) > (sum ak)) ak) >= m then "Yes" else "No"
 putStr $ ans


main :: IO()
main = do
 [n,m] <- map read . words <$> getLine :: IO[Int]
 ak <- map read . words <$> getLine :: IO[Int]
 let ans = if length (filter (\x -> x >= ((sum ak) `div` (4 * m))) ak) >= m then "Yes" else "No"
 putStr $ ans


main :: IO()
main = do
 [n,m] <- map read . words <$> getLine :: IO[Int]
 ak <- map read . words <$> getLine :: IO[Int]
 let ans = if length (filter (\x -> x > ((sum ak) `div` (4 * m))) ak) >= m then "Yes" else "No"
 putStr $ ans


check m xs = f . length . filter (\x -> x * 4 * m >= sum xs) $ xs
    where f x = if x >= m then "Yes" else "No"

main = do
    [_, m] <- map read . words <$> getLine
    xs <- map read . words <$> getLine
    putStrLn $ check m xs


main = do
    [n, m] <- map read . words <$> getLine
    a      <- map read . words <$> getLine :: IO [Float]
    let a_tot = sum a
    let gtbase= (>) (a_tot / (4 * fromIntegral m))
    let count = length $ filter gtbase a
    putStrLn $ if count >= m then "Yes" else "No"


ceildiv a b = div (a + b - 1) b

main = do
    [n, m] <- map read . words <$> getLine :: IO [Int]
    a <- map read . words <$> getLine :: IO [Int]
    putStrLn $ if (length . filter (>= ((sum a) `ceildiv` (4 * m)))) a >= m
                then "Yes"
                else "No"


import Control.Applicative
import Data.Bool (bool)

main :: IO ()
main = solve <$> f <*> f >>= putStrLn
  where
    f = map read <$> words <$> getLine

solve :: [Int] -> [Int] -> String
solve [_, m] as = bool "No" "Yes" . (>= m) . length $ filter f as
  where
    w = sum as
    f x = 4 * m * x >= w


import qualified Data.Vector.Unboxed as U
import qualified Data.Vector as V
import qualified Data.ByteString.Char8 as C
import Debug.Trace
import Data.List
import Control.Monad
import Control.Arrow
import Data.Ord

r :: Int -> IO (U.Vector Int)
r n = U.unfoldrN n (C.readInt . C.dropWhile (==' ')) <$> C.getLine

r' :: IO [Int]
r'  =   unfoldr    (C.readInt . C.dropWhile (==' ')) <$> C.getLine

main :: IO ()
main = do
    [n,m] <- r'
    as <- sortBy (flip compare) <$> r'
    putStrLn $ if as!!(m-1) < ceiling (fromIntegral (sum as)/(fromIntegral $4*m)) then "No" else "Yes"


threshold :: Int -> [Int] -> Float
threshold m as = (fromIntegral . sum $ as) / (4.0 * fromIntegral m)

point :: Int -> [Int] -> Int -> Int
point m as a = if fromIntegral a > threshold m as then 1 else 0

selectedCount :: Int -> [Int] -> Int
selectedCount m as = foldl1 ((+) . point m as) as

result :: Int -> [Int] -> String
result m as = if m <= selectedCount m as then "Yes" else "No"

{--
testprint :: Int -> Int -> [Int] -> IO ()
testprint n m as = do
     putStrLn $ "input " ++ show n ++ " " ++ show m ++ " " ++ show as
     putStrLn $ "threshold " ++ (show $ threshold m as)
     putStrLn $ "selectedCount " ++ (show $ selectedCount m as)
     putStrLn $ "result " ++ result m as
--}

main :: IO ()
main = do

    [n, m] <- map read . words <$> getLine :: IO [Int]
    as <- map read . words <$> getLine :: IO [Int]
    let as' = take n as
    putStrLn $ result m as'

    {--
    testprint 4 1 [5,4,2,1]
    testprint 3 2 [380,19,1]
    testprint 12 3 [4,56,78,901,2,345,67,890,123,45,6,789]
    --}


threshold :: Int -> [Int] -> Float
threshold m as = (fromIntegral . sum $ as) / (4.0 * fromIntegral m)

point :: Int -> [Int] -> Int -> Int
point m as a = if fromIntegral a >= threshold m as then 1 else 0

selectedCount :: Int -> [Int] -> Int
selectedCount m as = foldl1 ((+) . point m as) as

result :: Int -> [Int] -> String
result m as = if m <= selectedCount m as then "Yes" else "No"

{--
testprint :: Int -> Int -> [Int] -> IO ()
testprint n m as = do
     putStrLn $ "input " ++ show n ++ " " ++ show m ++ " " ++ show as
     putStrLn $ "threshold " ++ (show $ threshold m as)
     putStrLn $ "selectedCount " ++ (show $ selectedCount m as)
     putStrLn $ "result " ++ result m as
--}

main :: IO ()
main = do

    [n, m] <- map read . words <$> getLine :: IO [Int]
    as <- map read . words <$> getLine :: IO [Int]
    putStrLn $ result m as

    {--
    testprint 4 1 [5,4,2,1]
    testprint 3 2 [380,19,1]
    testprint 12 3 [4,56,78,901,2,345,67,890,123,45,6,789]
    --}


import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Read as T
import qualified Data.IntMap as IM
import Data.List
import Control.Monad

readInput :: IO [Int]
readInput = map (either error fst . T.decimal) . T.words <$> T.getLine

main = do
  [n, m] <- readInput
  items <- readInput
  let total = foldl' (+) 0 items
  if null $ drop m $ filter (\x -> x * m * 4 >= total) items
    then putStrLn "No"
    else putStrLn "Yes"


main = do
  [n, m] <- map read . words <$> getLine
  as <- map read . words <$> getLine
  if solve n m as
    then putStrLn "Yes"
    else putStrLn "No"

solve n m as = let sa = sum as in sum [ 1 | a <- as, 4 * m * a >= sa ] >= m


main=do
 [n,m]<-map read.words<$>getLine
 a<-map read.words<$>getLine
 let
  s = sum a
  c = (fromIntegral s) * (1 / fromIntegral(4 * m))
  l = length $ filter (\x-> (fromIntegral x) >= c) a
 putStrLn $ if l > m then "Yes" else "No"


import Data.List (sortBy)
import Data.Function (on)

div'::Int->Int->Double
div' = (/) `on` fromIntegral

sortDesc::[Int]->[Int]
sortDesc = sortBy $ flip compare

main = do
  [n,m] <- map read . words <$> getLine
  an <- map read . words <$> getLine
  let bn = sortDesc an
  let threshold = div' (sum an) (4*m)
  putStrLn $ if all (\p -> threshold <= fromIntegral(p)) (take m bn) then "Yes" else "No"


{-# LANGUAGE BangPatterns, OverloadedStrings #-}

import Control.Monad
import Data.List
import Data.Bits
import Debug.Trace
import Data.Maybe
import qualified Data.ByteString.Char8 as C

main :: IO ()
main = do
  [n, m] <- readInts
  as <- readInts
  putStrLn $ solve n m as

solve n m as = if foldl' (\a x -> if 4 * m * x >= totalvotes then a + 1 else a) 0 as >= m
  then "Yes"
  else "No"
  where
    totalvotes = sum as

-- 以下ライブラリ

readInts :: IO [Int]
readInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine

readNInts :: Int -> IO [[Int]]
readNInts = flip replicateM readInts

readIntegers :: IO [Integer]
readIntegers = map (fst . fromJust . C.readInteger) . C.words <$> C.getLine

readNIntegers :: Int -> IO [[Integer]]
readNIntegers = flip replicateM readIntegers

getNLns :: Int -> IO [String]
getNLns = flip replicateM getLine


main = getContents >>= putStrLn . solve . map read . words

solve (n:m:as) = if m <= length (filter (\a -> sum as <= 4 * a * m) as) then "Yes" else "No"


import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as BS
import Data.List

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words
getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine

main = do
    [n, m] <- getIntList
    as <- getIntList
    let s = ((sum as) - 1) `div` (4 * m) + 1
    putStrLn $ if (length (filter (>= s) as)) >= m then "Yes" else "No"


import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Read as T
import Data.Bool (bool)

main :: IO ()
main = do
  (n : m : _) <- map unsafeTextToInt . T.words <$> T.getLine :: IO [Int]
  as <- map unsafeTextToInt . T.words <$> T.getLine :: IO [Int]
  let
    s = sum as :: Int
    k = length . filter ((s <=) . (* (4 * m))) $ as :: Int
  putStrLn . bool "No" "Yes" $ m <= k

unsafeTextToInt :: T.Text -> Int
unsafeTextToInt s = case T.signed T.decimal s of
  Right (n, _) -> n


{-# LANGUAGE OverloadedStrings #-}
module Main where

import           Data.List
import           Control.Monad
import           Debug.Trace
import qualified Data.ByteString.Char8         as BC
import           Data.Maybe                     ( fromJust )
import qualified Data.Set                      as S
import qualified Data.IntMap.Strict            as IM
import qualified Data.Map.Strict               as M
import           Data.Char

readTuple2 :: IO (Int, Int)
readTuple2 = do
    [a, b] <- map (fst . fromJust . BC.readInt) . BC.words <$> BC.getLine
    return (a, b)

readTuple3 :: IO (Int, Int, Int)
readTuple3 = do
    [a, b, c] <- map (fst . fromJust . BC.readInt) . BC.words <$> BC.getLine
    return (a, b, c)

readInt :: IO Int
readInt = fst . fromJust . BC.readInt <$> BC.getLine

readInts :: IO [Int]
readInts = map (fst . fromJust . BC.readInt) . BC.words <$> BC.getLine

split :: (a -> Bool) -> [a] -> [[a]]
split f [] = []
split f as =
    let (fo, la) = span f as
        las      = case la of
            [] -> []
            xs -> split f $ tail xs
    in  case fo of
            [] -> las
            xs -> xs : las

solve :: Int -> [Int] -> String
solve m as =
    let total = sum as
        border = fromIntegral total / fromIntegral (4 * m)
        pred x = fromIntegral x >= border
        count = length $ filter pred as
    in if count >= m then "Yes" else "No"

main = do
    (n, m) <- readTuple2
    as <- readInts
    putStrLn $ solve m as


{-# LANGUAGE BangPatterns, OverloadedStrings #-}

import Control.Monad
import Data.List
import Data.Bits
import Debug.Trace
import Data.Maybe
import qualified Data.ByteString.Char8 as C

main :: IO ()
main = do
  [n, m] <- readInts
  as <- readInts
  putStrLn $ solve n m as

solve n m as = if foldl' (\a x -> if 4 * m * x >= totalvotes then x + 1 else x) 0 as >= m
  then "Yes"
  else "No"
  where
    totalvotes = sum as

-- 以下ライブラリ

readInts :: IO [Int]
readInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine

readNInts :: Int -> IO [[Int]]
readNInts = flip replicateM readInts

readIntegers :: IO [Integer]
readIntegers = map (fst . fromJust . C.readInteger) . C.words <$> C.getLine

readNIntegers :: Int -> IO [[Integer]]
readNIntegers = flip replicateM readIntegers

getNLns :: Int -> IO [String]
getNLns = flip replicateM getLine


import Data.List
main=do
 [x,y,a,b,c]<-map read.words<$>getLine
 p<-sort.map read.words<$>getLine
 q<-sort.map read.words<$>getLine
 r<-map read.words<$>getLine
 print$sum$drop c$sort$(drop(a-x)p)++(drop(b-y)q)++r

Score : 500 points

Problem Statement

You are going to eat X red apples and Y green apples.

You have A red apples of deliciousness p_1,p_2, \dots, p_A, B green apples of deliciousness q_1,q_2, \dots, q_B, and C colorless apples of deliciousness r_1,r_2, \dots, r_C.

Before eating a colorless apple, you can paint it red or green, and it will count as a red or green apple, respectively.

From the apples above, you will choose the apples to eat while making the sum of the deliciousness of the eaten apples as large as possible.

Find the maximum possible sum of the deliciousness of the eaten apples that can be achieved when optimally coloring zero or more colorless apples.

Constraints

1 \leq X \leq A \leq 10^5

1 \leq Y \leq B \leq 10^5

1 \leq C \leq 10^5

1 \leq p_i \leq 10^9

1 \leq q_i \leq 10^9

1 \leq r_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y A B C
p_1 p_2 ... p_A
q_1 q_2 ... q_B
r_1 r_2 ... r_C

Output

Print the maximum possible sum of the deliciousness of the eaten apples.

Sample Input 1

1 2 2 2 1
2 4
5 1
3

Sample Output 1

12

The maximum possible sum of the deliciousness of the eaten apples can be achieved as follows:

Eat the 2-nd red apple.

Eat the 1-st green apple.

Paint the 1-st colorless apple green and eat it.

Sample Input 2

2 2 2 2 2
8 6
9 1
2 1

Sample Output 2

25

Sample Input 3

2 2 4 4 4
11 12 13 14
21 22 23 24
1 2 3 4

Sample Output 3

74


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns, CPP, FlexibleContexts, FlexibleInstances         #-}
{-# LANGUAGE KindSignatures, LambdaCase, MagicHash, MultiParamTypeClasses   #-}
{-# LANGUAGE MultiWayIf, OverloadedStrings, RecordWildCards                 #-}
{-# LANGUAGE ScopedTypeVariables, TupleSections, TypeFamilies, ViewPatterns #-}

import           Control.Applicative
import           Control.Exception
import           Control.Monad
import           Control.Monad.Primitive
import           Control.Monad.ST
import           Control.Monad.State.Strict
import           Data.Bool
import qualified Data.ByteString             as B
import qualified Data.ByteString.Builder     as B
import qualified Data.ByteString.Char8       as C
import qualified Data.ByteString.Internal    as B
import qualified Data.ByteString.Unsafe      as B
import           Data.Char
import qualified Data.Foldable               as F
import           Data.Function
import           Data.Functor.Identity
import qualified Data.IntMap.Strict          as IM
import qualified Data.IntSet                 as IS
import qualified Data.List                   as L
import qualified Data.Map.Strict             as M
import           Data.Monoid
import           Data.Ord
import           Data.Primitive.MutVar
import           Data.Ratio
import qualified Data.Set                    as S
import           Data.Tuple
import qualified Data.Vector                 as V
import qualified Data.Vector.Generic         as G
import qualified Data.Vector.Generic.Mutable as GM
import qualified Data.Vector.Mutable         as VM
import qualified Data.Vector.Unboxed         as U
import qualified Data.Vector.Unboxed.Mutable as UM
import           Debug.Trace
import           Foreign                     hiding (void)
import           GHC.Exts
import qualified System.IO                   as IO
import           Unsafe.Coerce

main :: IO ()
main = do
    [x, y, a, b, c] <- map read.words <$> getLine :: IO [Int]
    ps <- U.unfoldrN a (runParser int) <$> C.getLine
    qs <- U.unfoldrN b (runParser int) <$> C.getLine
    rs <- U.unfoldrN c (runParser int) <$> C.getLine
    print $ solve x y ps qs rs

solve :: Int -> Int -> U.Vector Int -> U.Vector Int -> U.Vector Int -> Int
solve x y ps qs rs = runST $ do
    mbuf <- UM.unsafeNew (x + y + U.length rs)
    U.unsafeCopy (UM.unsafeSlice 0 x mbuf) . U.drop (U.length ps - x) $ radixSortInt ps
    U.unsafeCopy (UM.unsafeSlice x y mbuf) . U.drop (U.length qs - y) $ radixSortInt qs
    U.unsafeCopy (UM.unsafeSlice (x + y) (U.length rs) mbuf) rs
    U.sum . U.drop (U.length rs) . radixSortInt <$> U.unsafeFreeze mbuf

-------------------------------------------------------------------------------
-- Utils
-------------------------------------------------------------------------------
rep :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n = U.forM_ $ U.generate n id
{-# INLINE rep #-}
rev :: Monad m => Int -> (Int -> m ()) -> m ()
rev !n = U.forM_ $ U.iterateN n (subtract 1) (n - 1)
{-# INLINE rev #-}
infixl 8 `shiftRL`, `unsafeShiftRL`
shiftRL = unsafeShiftRL
{-# INLINE shiftRL #-}
unsafeShiftRL (I# x#) (I# i#) = I# (uncheckedIShiftRL# x# i#)
{-# INLINE unsafeShiftRL #-}
type Parser a = StateT C.ByteString Maybe a
runParser :: Parser a -> C.ByteString -> Maybe (a, C.ByteString)
runParser = runStateT
{-# INLINE runParser #-}
int :: Parser Int
int = coerce $ C.readInt . C.dropWhile isSpace
{-# INLINE int #-}
int1 :: Parser Int
int1 = fmap (subtract 1) int
{-# INLINE int1 #-}
char :: Parser Char
char = coerce C.uncons
{-# INLINE char #-}
byte :: Parser Word8
byte = coerce B.uncons
{-# INLINE byte #-}
-------------------------------------------------------------------------------
-- Data.Vector.Sort.Radix
-------------------------------------------------------------------------------
radixSortInt :: U.Vector Int -> U.Vector Int
radixSortInt = unsafeCoerce . radixSort64 . unsafeCoerce
radixSort32 :: U.Vector Word32 -> U.Vector Word32
radixSort32 v = F.foldl' step v [0, 16] where { mask k x = fromIntegral $ unsafeShiftR x k .&. 65535; step v k = U.create $ do { pref <- U.unsafeThaw . U.prescanl' (+) 0 . U.unsafeAccumulate (+) (U.replicate 65536 0) $ U.map (flip (,) 1 . mask k) v; res <- UM.unsafeNew $ U.length v; U.forM_ v $ \ x -> do { let { !masked = mask k x}; i <- UM.unsafeRead pref masked; UM.unsafeWrite pref masked $ i + 1; UM.unsafeWrite res i x}; return res}}
{-# INLINE radixSort32 #-}
radixSort64 :: U.Vector Word64 -> U.Vector Word64
radixSort64 v = F.foldl' step v [0, 16, 32, 48] where { mask k x = fromIntegral $ unsafeShiftR x k .&. 65535; step v k = U.create $ do { pref <- U.unsafeThaw . U.prescanl' (+) 0 . U.unsafeAccumulate (+) (U.replicate 65536 0) $ U.map (flip (,) 1 . mask k) v; res <- UM.unsafeNew $ U.length v; U.forM_ v $ \ x -> do { let { !masked = mask k x}; i <- UM.unsafeRead pref masked; UM.unsafeWrite pref masked $ i + 1; UM.unsafeWrite res i x}; return res}}
{-# INLINE radixSort64 #-}


module Main where

import           Debug.Trace
import qualified Data.Vector.Unboxed           as VU
import           Data.List
import qualified Data.ByteString               as BS
import qualified Data.ByteString.Char8         as BSC8
import           Data.Char

getVUIntFromInputLineAtBSC8 :: IO (VU.Vector Int)
getVUIntFromInputLineAtBSC8 =
    VU.unfoldr (BSC8.readInt . BSC8.dropWhile isSpace) <$> BSC8.getLine
getListIntFromInputLineAtBSC8 =
    unfoldr (BSC8.readInt . BSC8.dropWhile isSpace) <$> BSC8.getLine
main :: IO ()
main = do
    [aX, aY, aA, aB, aC] <- getListIntFromInputLineAtBSC8
    aP                   <- getVUIntFromInputLineAtBSC8
    aQ                   <- getVUIntFromInputLineAtBSC8
    aR                   <- getVUIntFromInputLineAtBSC8

    putStrLn $ show
        (sumApple
            (VU.fromList (reverse (0:(sortConved (VU.toList aP) aX))))
            (VU.fromList (reverse (0:(sortConved (VU.toList aQ) aY))))
            (VU.fromList (reverse (0:(sortConved (VU.toList aR) (aX + aY)))))
            aX
            aY
            0
        )

sortConved :: [Int] -> Int -> [Int]
sortConved _        0 = []
sortConved []       _ = []
sortConved (x : []) 1 = [x]
sortConved (x : xs) c = if lgteq == c
    then (sortConved gteq (c))
    else if lgteq > c
        then (sortConved gteq c)
        else if lgteq == (c+1)
            then [x] ++ (sortConved gteq lgteq)
            else (sortConved lt (c - lgteq)) ++ [x] ++ (sortConved gteq lgteq)
  where
    lt    = filter (\y -> y <= x) xs
    gteq  = filter (\y -> y > x) xs
    lgteq = length gteq

sortMerged :: [(Int, Int)] -> [(Int, Int)]
sortMerged []       = []
sortMerged (x : xs) = (sortMerged lt) ++ [x] ++ (sortMerged gteq)
  where
    lt   = filter (\y -> (fst y) <= (fst x)) xs
    gteq = filter (\y -> (fst y) > (fst x)) xs

sumApple
    :: VU.Vector Int
    -> VU.Vector Int
    -> VU.Vector Int
    -> Int
    -> Int
    -> Int
    -> Int
sumApple reds greens nils tX tY tZ
    | (tX + tY) == tZ = 0
    | otherwise = if (maxNum == red) && (tX > 0)
        then red + (sumApple (VU.tail reds) greens nils (tX - 1) tY tZ)
        else if ((max green nil) == green) && (tY > 0)
            then green + (sumApple reds (VU.tail greens) nils tX (tY - 1) tZ)
            else nil + (sumApple reds greens (VU.tail nils) tX tY (tZ + 1))

  where
    red    = VU.head reds
    green  = VU.head greens
    nil    = VU.head nils
    maxNum = max red (max green nil)


module Main where

import           Debug.Trace
import qualified Data.Vector.Unboxed           as VU
import           Data.List

main :: IO ()
main = do
    [aX, aY, aA, aB, aC] <- map read . words <$> getLine :: IO [Int]
    aP                   <- map read . words <$> getLine
    aQ                   <- map read . words <$> getLine
    aR                   <- map read . words <$> getLine

    putStrLn $ show $ sumApple
        (sortBy (\xs ys -> compare (fst ys) (fst xs))
                ((conv aP 1 aX) ++ (conv aQ 2 aY) ++ (conv aR 3 (aX+aY)))
        )
        aX
        aY
        0

conv :: [Int] -> Int -> Int-> [(Int, Int)]
conv [] _      _ = []
conv xs _ 0 = []
conv (x : []) i _= [(x, i)]
conv (x : xs) i c= (x, i) : (conv xs i (c-1))

sumApple :: [(Int, Int)] -> Int -> Int -> Int -> Int
sumApple [] _ _ _ = 0
sumApple (x : xs) tX tY tZ
    | (tX + tY) == tZ = 0
    | (snd x) == 1 = trace "red" $ if tX > 0
        then (fst x) + (sumApple xs (tX - 1) tY tZ)
        else sumApple xs tX tY tZ
    | (snd x) == 2 = trace "green" $ if tY > 0
        then (fst x) + (sumApple xs tX (tY - 1) tZ)
        else sumApple xs tX tY tZ
    | (snd x) == 3 = trace "nil" $ if (tX + tY) >= (tZ + 1)
        then (fst x) + (sumApple xs tX tY (tZ + 1))
        else sumApple xs tX tY tZ
    | otherwise = 0


module Main where

import           Debug.Trace
import qualified Data.Vector.Unboxed           as VU
import           Data.List

main :: IO ()
main = do
    [aX, aY, aA, aB, aC] <- map read . words <$> getLine :: IO [Int]
    aP                   <- map read . words <$> getLine
    aQ                   <- map read . words <$> getLine
    aR                   <- map read . words <$> getLine

    putStrLn $ show $ sumApple
        (sortBy (\xs ys -> compare (fst ys) (fst xs))
                ((conv aP 1) ++ (conv aQ 2) ++ (conv aR 3))
        )
        aX
        aY
        0

conv :: [Int] -> Int -> [(Int, Int)]
conv []       _ = []
conv (x : []) i = [(x, i)]
conv (x : xs) i = (x, i) : (conv xs i)

sumApple :: [(Int, Int)] -> Int -> Int -> Int -> Int
sumApple [] _ _ _ = 0
sumApple (x : xs) tX tY tZ
    | (tX + tY) == tZ = 0
    | (snd x) == 1 = trace "red" $ if tX > 0
        then (fst x) + (sumApple xs (tX - 1) tY tZ)
        else sumApple xs tX tY tZ
    | (snd x) == 2 = trace "green" $ if tY > 0
        then (fst x) + (sumApple xs tX (tY - 1) tZ)
        else sumApple xs tX tY tZ
    | (snd x) == 3 = trace "nil" $ if (tX + tY) >= (tZ + 1)
        then (fst x) + (sumApple xs tX tY (tZ + 1))
        else sumApple xs tX tY tZ
    | otherwise = 0