Problem:
Score : 400 points

Problem Statement

Given is a string S consisting of digits from 1 through 9.

Find the number of pairs of integers (i,j) (1 ≤ i ≤ j ≤ |S|) that satisfy the following condition:

Condition: In base ten, the i-th through j-th characters of S form an integer that is a multiple of 2019.

Constraints

1 ≤ |S| ≤ 200000

S is a string consisting of digits from 1 through 9.

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of pairs of integers (i,j) (1 ≤ i ≤ j ≤ |S|) that satisfy the condition.

Sample Input 1

1817181712114

Sample Output 1

3

Three pairs - (1,5), (5,9), and (9,13) - satisfy the condition.

Sample Input 2

14282668646

Sample Output 2

2

Sample Input 3

2119

Sample Output 3

0

No pairs satisfy the condition.

Solution in Haskell (GHC 8.8.3) (judge verdict: Time Limit Exceeded)

-- FileName   : 164d
-- CreatedDate: 2020-04-26 21:35:23

import Control.Monad
import Data.List

--reachHead _ [] = 0
--reachHead n a = let nn = (n*10) + (head a) `mod` 2019 in if nn == 0 then 1 + (reachHead nn $ tail a) else reachHead nn (tail a)

makeList _ [] = []
makeList n (x:xs) = let nn = (n*10+x)`mod`2019 in (nn:(makeList nn xs))

countModZero [] _ = 0
countModZero l@(x:xs) given@(y:ys) = (length $ filter (==0) l) +(countModZero (zipWith (f y) xs [1..(length xs)])) ys

f l n m = (n - (l * (power 10 m))) `mod` 2019

pow n 0 = 1
pow n m = (pow n (m-1)) * n `mod` 2019

main = do
   s <- map (\x -> fromEnum x - 48) <$> getLine
   putStrLn $ show $ countModZero (makeList 0 s) s
--   print $ makeList 0 s
--   print $ countModZero (makeList 0 s) s

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


base = 2019

plus a b = (a+b) `mod` base

times a b = a * b `mod` base

minus a b
   | a < b     = a-b + base
   | otherwise = a-b

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 n = power n $ base - 2

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]