Two neighbours, Alan and Bob, live in the city, where there are three buildings only: a cinema, a shop and the house, where they live. The rest is a big asphalt square. Once they went to the cinema, and the film impressed them so deeply, that when they left the cinema, they did not want to stop discussing it.Bob wants to get home, but Alan has to go to the shop first, and only then go home. So, they agreed to cover some distance together discussing the film (their common path might pass through the shop, or they might walk circles around the cinema together), and then to part each other's company and go each his own way. After they part, they will start thinking about their daily pursuits; and even if they meet again, they won't be able to go on with the discussion. Thus, Bob's path will be a continuous curve, having the cinema and the house as its ends. Alan's path — a continuous curve, going through the shop, and having the cinema and the house as its ends.The film ended late, that's why the whole distance covered by Alan should not differ from the shortest one by more than t1, and the distance covered by Bob should not differ from the shortest one by more than t2.Find the maximum distance that Alan and Bob will cover together, discussing the film.

The first line contains two integers: t1, t2 (0 ≤ t1, t2 ≤ 100). The second line contains the cinema's coordinates, the third one — the house's, and the last line — the shop's.  All the coordinates are given in meters, are integer, and do not exceed 100 in absolute magnitude. No two given places are in the same building.

In the only line output one number — the maximum distance that Alan and Bob will cover together, discussing the film. Output the answer accurate to not less than 4 decimal places.

import Debug.Trace

data Point = Point { x :: Double, y :: Double } deriving Show

eps = 1e-10

add p1 p2 = Point { x = x p1 + x p2, y = y p1 + y p2 }
mult p k = Point { x = k * x p, y = k * y p }

dist p1 p2 = sqrt $ sqr (x p1 - x p2) + sqr (y p1 - y p2) where
	sqr x = x * x

solve t1' t2' ps pm pt =
	if d1 < t2 + eps
		then min t1 t2
		else maximum [maxtime 0, maxtime 1, ternary_search maxtime 0 1]
	where
		dmt = dist pm pt
		d1 = dist ps pm + dmt
		d2 = dist ps pt
		t1 = t1' + d1
		t2 = t2' + d2
		ternary_search f l r =
			if r - l <= eps
				then f $ (l + r) / 2
				else let
						m1 = (2 * l + r) / 3
						m2 = (l + 2 * r) / 3
				     in
				     	if f m1 > f m2
				     		then ternary_search f l m2
				     		else ternary_search f m1 r
		binary_search f l r =
			if r - l <= eps
				then l
				else
					if f $ (l + r) / 2
						then binary_search f ((l + r) / 2) r
						else binary_search f l ((l + r) / 2)
		maxtime rat =
			let
				p = add (mult pm $ 1 - rat) (mult pt rat)
				d1 = dist ps p
				d2 = dist pt p
				chk x =
					dist ps p' + dist p' pm + dmt < t1 + eps && dist ps p' + dist p' pt < t2 + eps
					where
						p' = add (mult ps (1 - x)) (mult p x)

			in
				if d1 + d2 < t2 + eps && d1 + dmt * (1 + rat) < t1 + eps
					then min (t2 - d2) (t1 - dmt * (1 + rat))
					else dist ps p * binary_search chk 0 1

main = do
	[t1, t2, x0, y0, x2, y2, x1, y1] <- (map read . words) `fmap` getContents
	putStrLn $ show $ solve t1 t2 Point {x = x0, y = y0} Point {x = x1, y = y1} Point {x = x2, y = y2}

{-# LANGUAGE MultiWayIf #-}
module Main where

main :: IO ()
main = do
  (t1, t2) <- pair
  cinema <- pair
  home <- pair
  shop <- pair
  print $ solve t1 t2 cinema home shop

solve :: Double -> Double -> Point -> Point -> Point -> Double
solve t1 t2 c h s = if
    | ch + t2 >= cs + sh -> maxPath
    | otherwise -> search 0 maxPath
  where
    sh = dist s h
    cs = dist c s
    ch = dist c h

    maxPath = min (ch + t2) (cs + sh + t1)

    search l r = let x = (r + l) / 2 in if
        | r - l < 1e-6 -> x
        | isPossible x -> search x r
        | otherwise -> search l x
    isPossible x = check (c, x) (h, max 0 $ ch + t2 - x) (s, max 0 $ cs + t1 - x)

type Point = (Double, Double)
type Circle = (Point, Double)

check :: Circle -> Circle -> Circle -> Bool
check c1 c2 c3 = any f [(c1, c2, c3), (c1, c3, c2), (c2, c3, c1)]
  where
    f (c1, c2, c3) = case intersect c1 c2 of
      NOT_INTERSECT -> False
      CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT
      POINTS ps -> any (inside c3) ps

inside :: Circle -> Point -> Bool
inside (c, r) p =  dist c p < r + eps

(|+) :: Point -> Point -> Point
(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)

(|-) :: Point -> Point -> Point
(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)

scale :: Point -> Double -> Point
scale (x, y) k = (x * k, y * k)

eps :: Double
eps = 1e-10

data Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)

intersect :: Circle -> Circle -> Intersection
intersect a b = if
    | r2 > r1 -> intersect b a
    | abs (r1 - r2) > l + eps -> CONTAIN b
    | r1 + r2 + eps < l -> NOT_INTERSECT
    | r1 + r2 < l + eps -> POINTS [c1 |+ scale (c2 |- c1) (r1 / l)]
    | otherwise -> POINTS [ u |+ v, u |- v]
  where
    (c1, r1) = a
    (c2, r2) = b
    l = dist c1 c2
    la = (r1 * r1 + l * l - r2 * r2) / (2 * l)
    h = sqrt $ r1 * r1 - la * la
    u = c1 |+ scale (c2 |- c1) (la / l)
    (x1, y1) = c1
    (x2, y2) = c2
    v = scale (y1 - y2, x2 - x1) (h / l)

dist :: Point -> Point -> Double
dist p q = norm (p |- q)

norm :: Point -> Double
norm (x, y) = sqrt $ x * x + y * y

pair :: IO (Double, Double)
pair = words <$> getLine >>= \[x, y] -> pure (read x, read y)

{-# LANGUAGE MultiWayIf #-}
module Main where
import Data.List (minimumBy)
import Data.Ord (comparing)

main :: IO ()
main = do
  (t1, t2) <- pair
  cinema <- pair
  home <- pair
  shop <- pair
  print $ solve t1 t2 cinema home shop

solve :: Double -> Double -> (Double, Double) -> (Double, Double) -> (Double, Double) -> Double
solve t1 t2 c h s = if
    | ch + t2 >= cs + sh -> min (ch + t2) (cs + sh + t1)
    | cs + sh + t1 >= ch + t2 + 2 * sh -> ch + t2
    | d <= r -> r
    | otherwise -> search 0 r
  where
    sh = dist s h
    cs = dist c s
    ch = dist c h

    r = (cs + t1 + ch + t2 - sh) / 2
    sr = (cs + t1 - r) / sh
    hr = (ch + t2 - r) / sh

    cs_ = cs + t1
    ch_ = ch + t2

    (hx, hy) = h
    (sx, sy) = s
    (cx, cy) = c

    x = sx * hr + hx * sr
    y = sy * hr + hy * sr

    d = sqrt $ (cx - x) ^ 2 + (cy - y) ^ 2

    a = angle cs ch sh

    search l r = let x = (r + l) / 2 in if
        | r - l < 1e-6 -> x
        | isPossible x -> search x r
        | otherwise -> search l x

    isPossible x = angle cs x (cs + t1 - x) + angle ch x (ch + t2 - x) > a

angle :: Double -> Double -> Double -> Double
angle a b c = acos . max (-1) . min 1 $ (a * a + b * b - c * c) / (2 * a * b)

dist :: (Double, Double) -> (Double, Double) -> Double
dist (x1, y1) (x2, y2) = sqrt $ (x1 - x2) ^ 2 + (y1 - y2) ^ 2

pair :: IO (Double, Double)
pair = words <$> getLine >>= \[x, y] -> pure (read x, read y)

{-# LANGUAGE MultiWayIf #-}
module Main where

main :: IO ()
main = do
  (t1, t2) <- pair
  cinema <- pair
  home <- pair
  shop <- pair
  print $ solve t1 t2 cinema home shop

solve :: Double -> Double -> Point -> Point -> Point -> Double
solve t1 t2 c h s = if
    | ch + t2 >= cs + sh -> maxPath
    | cs + sh + t1 >= ch + t2 + 2 * sh -> ch + t2
    | otherwise -> search 0 maxPath
  where
    sh = dist s h
    cs = dist c s
    ch = dist c h

    maxPath = min (ch + t2) (cs + sh + t1)

    search l r = let x = (r + l) / 2 in if
        | r - l < 1e-6 -> x
        | isPossible x -> search x r
        | otherwise -> search l x
    isPossible x = check (c, x) (h, max 0 $ ch + t2 - x) (s, max 0 $ cs + t1 - x)

type Point = (Double, Double)
type Circle = (Point, Double)

check :: Circle -> Circle -> Circle -> Bool
check c1 c2 c3 = any f [(c1, c2, c3), (c1, c3, c2), (c2, c3, c1)]
  where
    f (c1, c2, c3) = case intersect c1 c2 of
      NOT_INTERSECT -> False
      CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT
      POINTS ps -> any (inside c3) ps

inside :: Circle -> Point -> Bool
inside (c, r) p =  dist c p < r + eps

(|+) :: Point -> Point -> Point
(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)

(|-) :: Point -> Point -> Point
(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)

scale :: Point -> Double -> Point
scale (x, y) k = (x * k, y * k)

eps :: Double
eps = 1e-10

data Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)

intersect :: Circle -> Circle -> Intersection
intersect a b = if
    | r2 > r1 -> intersect b a
    | abs (r1 - r2) > l + eps -> CONTAIN b
    | r1 + r2 + eps < l -> NOT_INTERSECT
    | r1 + r2 < l + eps -> POINTS [c1 |+ scale (c2 |- c1) (r1 / l)]
    | otherwise -> POINTS [ u |+ v, u |- v]
  where
    (c1, r1) = a
    (c2, r2) = b
    l = dist c1 c2
    la = (r1 * r1 + l * l - r2 * r2) / (2 * l)
    h = sqrt $ r1 * r1 - la * la
    u = c1 |+ scale (c2 |- c1) (la / l)
    (x1, y1) = c1
    (x2, y2) = c2
    v = scale (y1 - y2, x2 - x1) (h / l)

dist :: Point -> Point -> Double
dist p q = norm (p |- q)

norm :: Point -> Double
norm (x, y) = sqrt $ x * x + y * y

pair :: IO (Double, Double)
pair = words <$> getLine >>= \[x, y] -> pure (read x, read y)

{-# LANGUAGE MultiWayIf #-}
module Main where
import Data.List (permutations)

main :: IO ()
main = do
  (t1, t2) <- pair
  cinema <- pair
  home <- pair
  shop <- pair
  print $ solve t1 t2 cinema home shop

solve :: Double -> Double -> Point -> Point -> Point -> Double
solve t1 t2 c h s = if
    | ch + t2 >= cs + sh -> maxPath
    | cs + sh + t1 >= ch + t2 + 2 * sh -> ch + t2
    | otherwise -> search 0 maxPath
  where
    maxPath = min (ch + t2) (cs + sh + t1)

    sh = dist s h
    cs = dist c s
    ch = dist c h

    f (l,r) = let x = (r + l) / 2 in if isPossible x then (x, r) else (l, x)

    search l r = let x = (r + l) / 2 in if
        | r - l < 1e-6 -> x
        | isPossible x -> search x r
        | otherwise -> search l x
    isPossible x = check (c, x) (h, max 0 $ ch + t2 - x) (s, max 0 $ cs + t1 - x)

type Point = (Double, Double)
type Circle = (Point, Double)

check :: Circle -> Circle -> Circle -> Bool
check c1 c2 c3 = any f $ [(c1, c2, c3), (c1, c3, c2), (c2, c3, c1)]
  where
    f (c1, c2, c3) = case intersect c1 c2 of
      NOT_INTERSECT -> False
      CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT
      POINTS ps -> any (inside c3) ps

inside :: Circle -> Point -> Bool
inside (c, r) p =  dist c p < r + 1e-10

(|+) :: Point -> Point -> Point
(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)

(|-) :: Point -> Point -> Point
(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)

scale :: Point -> Double -> Point
scale (x, y) k = (x * k, y * k)

data Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)

intersect :: Circle -> Circle -> Intersection
intersect a b = if
    | r2 > r1 -> intersect b a
    | r1 + r2 < l -> NOT_INTERSECT
    | abs (r1 - r2) > l -> CONTAIN b
    | otherwise -> POINTS [ u |+ v, u |- v]
  where
    (c1, r1) = a
    (c2, r2) = b
    l = dist c1 c2
    la = (r1 * r1 + l * l - r2 * r2) / (2 * l)
    h = sqrt $ r1 * r1 - la * la
    u = c1 |+ scale (c2 |- c1) (la / l)
    (x1, y1) = c1
    (x2, y2) = c2
    v = scale (y1 - y2, x2 - x1) (h / l)

dist :: Point -> Point -> Double
dist p q = norm (p |- q)

norm :: Point -> Double
norm (x, y) = sqrt $ x * x + y * y

pair :: IO (Double, Double)
pair = words <$> getLine >>= \[x, y] -> pure (read x, read y)

{-# LANGUAGE MultiWayIf #-}
module Main where
import Data.List (permutations)

main :: IO ()
main = do
  (t1, t2) <- pair
  cinema <- pair
  home <- pair
  shop <- pair
  print $ solve t1 t2 cinema home shop

solve :: Double -> Double -> Point -> Point -> Point -> Double
solve t1 t2 c h s = if tsh + dist c s <= tB then min (tA + tsh) tB else search 0 tsh
  where
    tsh = dist s h
    tA =  dist c s + t1
    tB = dist c h + t2

    f (l,r) = let x = (r + l) / 2 in if isPossible x then (x, r) else (l, x)

    search l r = let x = (r + l) / 2 in if
        | r - l < 1e-5 -> x
        | isPossible x -> search x r
        | otherwise -> search l x
    isPossible x = check (c, x) (h, max 0 $ tB - x) (s, max 0 $ tA - x)

type Point = (Double, Double)
type Circle = (Point, Double)

eps :: Double
eps = 1e-5

check :: Circle -> Circle -> Circle -> Bool
check c1 c2 c3 = any f $ permutations [c1,c2,c3]
  where
    f [c1, c2, c3] = case intersect c1 c2 of
      NOT_INTERSECT -> False
      CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT
      POINTS ps -> any (inside c3) ps

inside :: Circle -> Point -> Bool
inside (c, r) p =  dist c p <= r

(|+) :: Point -> Point -> Point
(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)

(|-) :: Point -> Point -> Point
(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)

scale :: Point -> Double -> Point
scale (x, y) k = (x * k, y * k)

data Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)

intersect :: Circle -> Circle -> Intersection
intersect a@(c1@(x1, y1), r1) b@(c2@(x2, y2), r2)
  | r1 + r2 + eps < l = NOT_INTERSECT
  | abs (r1 - r2) > l + eps = CONTAIN $ if r1 > r2 then b else a
  | otherwise = POINTS [ u |+ v, u |- v]
  where
    l = dist c1 c2
    la = (r1 * r1 + l * l - r2 * r2) / (2 * l)
    h = sqrt $ r1 * r1 - la * la
    u = c1 |+ scale (c2 |- c1) (la / l)
    v = scale (y1- y2, x2 - x1) (h / l)

dist :: Point -> Point -> Double
dist p q = norm (p |- q)

norm :: Point -> Double
norm (x, y) = sqrt $ x * x + y * y

pair :: IO (Double, Double)
pair = words <$> getLine >>= \[x, y] -> pure (read x, read y)

{-# LANGUAGE MultiWayIf #-}
module Main where

main :: IO ()
main = do
  (t1, t2) <- pair
  cinema <- pair
  home <- pair
  shop <- pair
  print $ solve t1 t2 cinema home shop

solve :: Double -> Double -> Point -> Point -> Point -> Double
solve t1 t2 c h s = if
    | ch + t2 >= cs + sh -> maxPath
    | cs + sh + t1 >= ch + t2 + 2 * sh -> ch + t2
    | otherwise -> search 0 maxPath
  where
    sh = dist s h
    cs = dist c s
    ch = dist c h

    maxPath = min (ch + t2) (cs + sh + t1)

    f (l,r) = let x = (r + l) / 2 in if isPossible x then (x, r) else (l, x)

    search l r = let x = (r + l) / 2 in if
        | r - l < 1e-6 -> x
        | isPossible x -> search x r
        | otherwise -> search l x
    isPossible x = check (c, x) (h, max 0 $ ch + t2 - x) (s, max 0 $ cs + t1 - x)

type Point = (Double, Double)
type Circle = (Point, Double)

check :: Circle -> Circle -> Circle -> Bool
check c1 c2 c3 = any f $ [(c1, c2, c3), (c1, c3, c2), (c2, c3, c1)]
  where
    f (c1, c2, c3) = case intersect c1 c2 of
      NOT_INTERSECT -> False
      CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT
      POINTS ps -> any (inside c3) ps

inside :: Circle -> Point -> Bool
inside (c, r) p =  dist c p < r + 1e-10

(|+) :: Point -> Point -> Point
(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)

(|-) :: Point -> Point -> Point
(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)

scale :: Point -> Double -> Point
scale (x, y) k = (x * k, y * k)

data Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)

intersect :: Circle -> Circle -> Intersection
intersect a b = if
    | r1 + r2 + 1e-5 < l -> NOT_INTERSECT
    | r1 + r2 + 1e-5 > l -> POINTS [c1 |+ scale (c2 |- c1) (r1 / l)]
    | abs (r1 - r2) > l -> CONTAIN b
    | otherwise -> POINTS [ u |+ v, u |- v]
  where
    (c1, r1) = a
    (c2, r2) = b
    l = dist c1 c2
    la = (r1 * r1 + l * l - r2 * r2) / (2 * l)
    h = sqrt $ r1 * r1 - la * la
    u = c1 |+ scale (c2 |- c1) (la / l)
    (x1, y1) = c1
    (x2, y2) = c2
    v = scale (y1 - y2, x2 - x1) (h / l)

dist :: Point -> Point -> Double
dist p q = norm (p |- q)

norm :: Point -> Double
norm (x, y) = sqrt $ x * x + y * y

pair :: IO (Double, Double)
pair = words <$> getLine >>= \[x, y] -> pure (read x, read y)

{-# LANGUAGE MultiWayIf #-}
module Main where

main :: IO ()
main = do
  (t1, t2) <- pair
  cinema <- pair
  home <- pair
  shop <- pair
  print $ solve t1 t2 cinema home shop

solve :: Double -> Double -> Point -> Point -> Point -> Double
solve t1 t2 c h s = search 0 maxPath
  where
    sh = dist s h
    cs = dist c s
    ch = dist c h

    maxPath = min (ch + t2) (cs + sh + t1)

    search l r = let x = (r + l) / 2 in if
        | r - l < 1e-6 -> x
        | isPossible x -> search x r
        | otherwise -> search l x
    isPossible x = check (c, x) (h, max 0 $ ch + t2 - x) (s, max 0 $ cs + t1 - x)

type Point = (Double, Double)
type Circle = (Point, Double)

check :: Circle -> Circle -> Circle -> Bool
check c1 c2 c3 = any f [(c1, c2, c3), (c1, c3, c2), (c2, c3, c1)]
  where
    f (c1, c2, c3) = case intersect c1 c2 of
      NOT_INTERSECT -> False
      CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT
      POINTS ps -> any (inside c3) ps

inside :: Circle -> Point -> Bool
inside (c, r) p =  dist c p < r + eps

(|+) :: Point -> Point -> Point
(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)

(|-) :: Point -> Point -> Point
(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)

scale :: Point -> Double -> Point
scale (x, y) k = (x * k, y * k)

eps :: Double
eps = 1e-10

data Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)

intersect :: Circle -> Circle -> Intersection
intersect a b = if
    | r2 > r1 -> intersect b a
    | abs (r1 - r2) > l + eps -> CONTAIN b
    | r1 + r2 + eps < l -> NOT_INTERSECT
    | r1 + r2 < l + eps -> POINTS [c1 |+ scale (c2 |- c1) (r1 / l)]
    | otherwise -> POINTS [ u |+ v, u |- v]
  where
    (c1, r1) = a
    (c2, r2) = b
    l = dist c1 c2
    la = (r1 * r1 + l * l - r2 * r2) / (2 * l)
    h = sqrt $ r1 * r1 - la * la
    u = c1 |+ scale (c2 |- c1) (la / l)
    (x1, y1) = c1
    (x2, y2) = c2
    v = scale (y1 - y2, x2 - x1) (h / l)

dist :: Point -> Point -> Double
dist p q = norm (p |- q)

norm :: Point -> Double
norm (x, y) = sqrt $ x * x + y * y

pair :: IO (Double, Double)
pair = words <$> getLine >>= \[x, y] -> pure (read x, read y)

{-# LANGUAGE MultiWayIf #-}
module Main where

main :: IO ()
main = do
  (t1, t2) <- pair
  cinema <- pair
  home <- pair
  shop <- pair
  print $ solve t1 t2 cinema home shop

solve :: Double -> Double -> Point -> Point -> Point -> Double
solve t1 t2 c h s = if tsh + dist c s <= tB then min (tA + tsh) tB else search 0 tsh
  where
    tsh = dist s h
    tA =  dist c s + t1
    tB = dist c h + t2
    search l r = let x = (r + l) / 2 in if
        | r - l < eps -> x
        | isPossible x -> search x r
        | otherwise -> search l x
    isPossible x = check (c, x) (h, max 0 $ tB - x) (s, max 0 $ tA - x)

type Point = (Double, Double)
type Circle = (Point, Double)

eps :: Double
eps = 1e-5

check :: Circle -> Circle -> Circle -> Bool
check c1 c2 c3 = any f [ (c1, c2, c3), (c1, c3, c2), (c2, c3, c1) ]
  where
    f (c1, c2, c3) = case intersect c1 c2 of
      NOT_INTERSECT -> False
      CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT
      POINTS ps -> any (inside c3) ps

inside :: Circle -> Point -> Bool
inside (c, r) p =  dist c p <= r + eps

(|+) :: Point -> Point -> Point
(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)

(|-) :: Point -> Point -> Point
(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)

scale :: Point -> Double -> Point
scale (x, y) k = (x * k, y * k)

data Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)

intersect :: Circle -> Circle -> Intersection
intersect a@(c1@(x1, y1), r1) b@(c2@(x2, y2), r2)
  | r1 + r2 + eps < l = NOT_INTERSECT
  | abs (r1 - r2) > l + eps = CONTAIN $ if r1 > r2 then b else a
  | otherwise = POINTS [ u |+ v, u |- v]
  where
    l = dist c1 c2
    la = (r1 * r1 + l * l - r2 * r2) / (2 * l)
    h = sqrt $ r1 * r1 - la * la
    u = c1 |+ scale (c2 |- c1) (la / l)
    v = scale (y1- y2, x2 - x1) (h / l)

dist :: Point -> Point -> Double
dist p q = norm (p |- q)

norm :: Point -> Double
norm (x, y) = sqrt $ x * x + y * y

pair :: IO (Double, Double)
pair = words <$> getLine >>= \[x, y] -> pure (read x, read y)

{-# LANGUAGE MultiWayIf #-}
module Main where
import Data.List (minimumBy)
import Data.Ord (comparing)

main :: IO ()
main = do
  (t1, t2) <- pair
  cinema <- pair
  home <- pair
  shop <- pair
  print $ solve t1 t2 cinema home shop

solve :: Double -> Double -> (Double, Double) -> (Double, Double) -> (Double, Double) -> Double
solve t1 t2 c h s = if
    | ch + t2 >= cs + sh -> min (ch + t2) (cs + sh + t1)
    | cs + sh + t1 >= ch + t2 + 2 * sh -> ch + t2
    | otherwise -> search 0 r
  where
    sh = dist s h
    cs = dist c s
    ch = dist c h

    r = (cs + t1 + ch + t2 - sh) / 2
    sr = (cs + t1 - r) / sh
    hr = (ch + t2 - r) / sh

    a = angle cs ch sh

    search l r = let x = (r + l) / 2 in if
        | r - l < 1e-6 -> x
        | isPossible x -> search x r
        | otherwise -> search l x

    isPossible x = angle cs x (cs + t1 - x) + angle ch x (ch + t2 - x) > a

angle :: Double -> Double -> Double -> Double
angle a b c = acos . max (-1) . min 1 $ (a * a + b * b - c * c) / (2 * a * b)

dist :: (Double, Double) -> (Double, Double) -> Double
dist (x1, y1) (x2, y2) = sqrt $ (x1 - x2) ^ 2 + (y1 - y2) ^ 2

pair :: IO (Double, Double)
pair = words <$> getLine >>= \[x, y] -> pure (read x, read y)

{-# LANGUAGE MultiWayIf #-}
module Main where

main :: IO ()
main = do
  (t1, t2) <- pair
  cinema <- pair
  home <- pair
  shop <- pair
  print $ solve t1 t2 cinema home shop

solve :: Double -> Double -> Point -> Point -> Point -> Double
solve t1 t2 c h s = if
    | ch + t2 >= cs + sh -> maxPath
    | cs + sh + t1 >= ch + t2 + 2 * sh -> ch + t2
    | otherwise -> search 0 maxPath
  where
    sh = dist s h
    cs = dist c s
    ch = dist c h

    maxPath = min (ch + t2) (cs + sh + t1)

    f (l,r) = let x = (r + l) / 2 in if isPossible x then (x, r) else (l, x)

    search l r = let x = (r + l) / 2 in if
        | r - l < 1e-6 -> x
        | isPossible x -> search x r
        | otherwise -> search l x
    isPossible x = check (c, x) (h, max 0 $ ch + t2 - x) (s, max 0 $ cs + t1 - x)

type Point = (Double, Double)
type Circle = (Point, Double)

check :: Circle -> Circle -> Circle -> Bool
check c1 c2 c3 = any f $ [(c1, c2, c3), (c1, c3, c2), (c2, c3, c1)]
  where
    f (c1, c2, c3) = case intersect c1 c2 of
      NOT_INTERSECT -> False
      CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT
      POINTS ps -> any (inside c3) ps

inside :: Circle -> Point -> Bool
inside (c, r) p =  dist c p <= r

(|+) :: Point -> Point -> Point
(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)

(|-) :: Point -> Point -> Point
(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)

scale :: Point -> Double -> Point
scale (x, y) k = (x * k, y * k)

data Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)

intersect :: Circle -> Circle -> Intersection
intersect a b = if
    | r1 + r2 < l -> NOT_INTERSECT
    | r1 + r2 == l -> POINTS [c1 |+ scale (c2 |- c1) (r1 / l)]
    | abs (r1 - r2) > l -> CONTAIN b
    | otherwise -> POINTS [ u |+ v, u |- v]
  where
    (c1, r1) = a
    (c2, r2) = b
    l = dist c1 c2
    la = (r1 * r1 + l * l - r2 * r2) / (2 * l)
    h = sqrt $ r1 * r1 - la * la
    u = c1 |+ scale (c2 |- c1) (la / l)
    (x1, y1) = c1
    (x2, y2) = c2
    v = scale (y1 - y2, x2 - x1) (h / l)

dist :: Point -> Point -> Double
dist p q = norm (p |- q)

norm :: Point -> Double
norm (x, y) = sqrt $ x * x + y * y

pair :: IO (Double, Double)
pair = words <$> getLine >>= \[x, y] -> pure (read x, read y)

{-# LANGUAGE MultiWayIf #-}
module Main where
import Data.List (permutations)

main :: IO ()
main = do
  (t1, t2) <- pair
  cinema <- pair
  home <- pair
  shop <- pair
  print $ solve t1 t2 cinema home shop

solve :: Double -> Double -> Point -> Point -> Point -> Double
solve t1 t2 c h s = if tsh + dist c s <= tB then maxP else search 0 maxP
  where
    tsh = dist s h
    tA =  dist c s + t1
    tB = dist c h + t2
    maxP = min (tA + tsh) tB

    f (l,r) = let x = (r + l) / 2 in if isPossible x then (x, r) else (l, x)

    search l r = let x = (r + l) / 2 in if
        | r - l < 1e-5 -> x
        | isPossible x -> search x r
        | otherwise -> search l x
    isPossible x = check (c, x) (h, max 0 $ tB - x) (s, max 0 $ tA - x)

type Point = (Double, Double)
type Circle = (Point, Double)

eps :: Double
eps = 1e-5

check :: Circle -> Circle -> Circle -> Bool
check c1 c2 c3 = any f $ permutations [c1, c2, c3]
  where
    f [c1, c2, c3] = case intersect c1 c2 of
      NOT_INTERSECT -> False
      CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT
      POINTS ps -> any (inside c3) ps

inside :: Circle -> Point -> Bool
inside (c, r) p =  dist c p <= r

(|+) :: Point -> Point -> Point
(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)

(|-) :: Point -> Point -> Point
(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)

scale :: Point -> Double -> Point
scale (x, y) k = (x * k, y * k)

data Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)

intersect :: Circle -> Circle -> Intersection
intersect a@(c1@(x1, y1), r1) b@(c2@(x2, y2), r2)
  | r1 + r2 < l = NOT_INTERSECT
  | abs (r1 - r2) > l = CONTAIN $ if r1 > r2 then b else a
  | otherwise = POINTS [ u |+ v, u |- v]
  where
    l = dist c1 c2
    la = (r1 * r1 + l * l - r2 * r2) / (2 * l)
    h = sqrt $ r1 * r1 - la * la
    u = c1 |+ scale (c2 |- c1) (la / l)
    v = scale (y1- y2, x2 - x1) (h / l)

dist :: Point -> Point -> Double
dist p q = norm (p |- q)

norm :: Point -> Double
norm (x, y) = sqrt $ x * x + y * y

pair :: IO (Double, Double)
pair = words <$> getLine >>= \[x, y] -> pure (read x, read y)

{-# LANGUAGE MultiWayIf #-}
module Main where
import Data.List (permutations)

main :: IO ()
main = do
  (t1, t2) <- pair
  cinema <- pair
  home <- pair
  shop <- pair
  print $ solve t1 t2 cinema home shop

solve :: Double -> Double -> Point -> Point -> Point -> Double
solve t1 t2 c h s = if
    | ch + t2 >= cs + sh -> maxPath
    | cs + sh + t1 >= ch + t2 + 2 * sh -> ch + t2
    | otherwise -> search 0 maxPath
  where
    sh = dist s h
    cs = dist c s
    ch = dist c h

    maxPath = min (ch + t2) (cs + sh + t1)

    f (l,r) = let x = (r + l) / 2 in if isPossible x then (x, r) else (l, x)

    search l r = let x = (r + l) / 2 in if
        | r - l < 1e-6 -> x
        | isPossible x -> search x r
        | otherwise -> search l x
    isPossible x = check (c, x) (h, max 0 $ ch + t2 - x) (s, max 0 $ cs + t1 - x)

type Point = (Double, Double)
type Circle = (Point, Double)

check :: Circle -> Circle -> Circle -> Bool
check c1 c2 c3 = any f $ [(c1, c2, c3), (c1, c3, c2), (c2, c3, c1)]
  where
    f (c1, c2, c3) = case intersect c1 c2 of
      NOT_INTERSECT -> False
      CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT
      POINTS ps -> any (inside c3) ps

inside :: Circle -> Point -> Bool
inside (c, r) p =  dist c p < r + 1e-10

(|+) :: Point -> Point -> Point
(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)

(|-) :: Point -> Point -> Point
(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)

scale :: Point -> Double -> Point
scale (x, y) k = (x * k, y * k)

data Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)

intersect :: Circle -> Circle -> Intersection
intersect a b = if
    | r2 > r1 -> intersect b a
    | r1 + r2 < l -> NOT_INTERSECT
    | abs (r1 - r2) > l -> CONTAIN b
    | otherwise -> POINTS [ u |+ v, u |- v]
  where
    (c1, r1) = a
    (c2, r2) = b
    l = dist c1 c2
    la = (r1 * r1 + l * l - r2 * r2) / (2 * l)
    h = sqrt $ r1 * r1 - la * la
    u = c1 |+ scale (c2 |- c1) (la / l)
    (x1, y1) = c1
    (x2, y2) = c2
    v = scale (y1 - y2, x2 - x1) (h / l)

dist :: Point -> Point -> Double
dist p q = norm (p |- q)

norm :: Point -> Double
norm (x, y) = sqrt $ x * x + y * y

pair :: IO (Double, Double)
pair = words <$> getLine >>= \[x, y] -> pure (read x, read y)

{-# LANGUAGE MultiWayIf #-}
module Main where
import Data.List (permutations)

main :: IO ()
main = do
  (t1, t2) <- pair
  cinema <- pair
  home <- pair
  shop <- pair
  print $ solve t1 t2 cinema home shop

solve :: Double -> Double -> Point -> Point -> Point -> Double
-- solve t1 t2 c h s = trace (show $ isPossible 1.0002) 0.0
solve t1 t2 c h s = if
    | ch + t2 >= cs + sh -> min (ch + t2) (cs + sh + t1)
    | cs + sh + t1 >= ch + t2 + 2 * sh -> ch + t2
    | otherwise -> search 0 sh
  where
    sh = dist s h
    cs = dist c s
    ch = dist c h

    f (l,r) = let x = (r + l) / 2 in if isPossible x then (x, r) else (l, x)

    -- search l r = trace (show (l, r)) $ let x = (r + l) / 2 in if
    search l r = let x = (r + l) / 2 in if
        | r - l < 1e-6 -> x
        | isPossible x -> search x r
        | otherwise -> search l x
    isPossible x = check (c, x) (h, max 0 $ ch + t2 - x) (s, max 0 $ cs + t1 - x)

type Point = (Double, Double)
type Circle = (Point, Double)

check :: Circle -> Circle -> Circle -> Bool
check c1 c2 c3 = any f $ [(c1, c2, c3), (c1, c3, c2), (c2, c3, c1)]
  where
    f (c1, c2, c3) = case intersect c1 c2 of
      NOT_INTERSECT -> False
      CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT
      POINTS ps -> any (inside c3) ps

inside :: Circle -> Point -> Bool
inside (c, r) p =  dist c p < r + 1e-10

(|+) :: Point -> Point -> Point
(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)

(|-) :: Point -> Point -> Point
(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)

scale :: Point -> Double -> Point
scale (x, y) k = (x * k, y * k)

data Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)

intersect :: Circle -> Circle -> Intersection
intersect a b = if
    | r2 > r1 -> intersect b a
    | r1 + r2 < l -> NOT_INTERSECT
    | abs (r1 - r2) > l -> CONTAIN b
    | otherwise -> POINTS [ u |+ v, u |- v]
  where
    (c1, r1) = a
    (c2, r2) = b
    l = dist c1 c2
    la = (r1 * r1 + l * l - r2 * r2) / (2 * l)
    h = sqrt $ r1 * r1 - la * la
    u = c1 |+ scale (c2 |- c1) (la / l)
    (x1, y1) = c1
    (x2, y2) = c2
    v = scale (y1 - y2, x2 - x1) (h / l)

dist :: Point -> Point -> Double
dist p q = norm (p |- q)

norm :: Point -> Double
norm (x, y) = sqrt $ x * x + y * y

pair :: IO (Double, Double)
pair = words <$> getLine >>= \[x, y] -> pure (read x, read y)

{-# LANGUAGE MultiWayIf #-}
module Main where
import Data.List (permutations)

main :: IO ()
main = do
  (t1, t2) <- pair
  cinema <- pair
  home <- pair
  shop <- pair
  print $ solve t1 t2 cinema home shop

solve :: Double -> Double -> Point -> Point -> Point -> Double
solve t1 t2 c h s = if tsh + dist c s <= tB then maxP else search 0 maxP
  where
    tsh = dist s h
    tA =  dist c s + t1
    tB = dist c h + t2
    maxP = min (tA + tsh) tB

    f (l,r) = let x = (r + l) / 2 in if isPossible x then (x, r) else (l, x)

    search l r = let x = (r + l) / 2 in if
        | r - l < 1e-6 -> x
        | isPossible x -> search x r
        | otherwise -> search l x
    isPossible x = check (c, x) (h, max 0 $ tB - x) (s, max 0 $ tA - x)

type Point = (Double, Double)
type Circle = (Point, Double)

check :: Circle -> Circle -> Circle -> Bool
check c1 c2 c3 = any f $ [(c1, c2, c3), (c1, c3, c2), (c2, c3, c1)]
  where
    f (c1, c2, c3) = case intersect c1 c2 of
      NOT_INTERSECT -> False
      CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT
      POINTS ps -> any (inside c3) ps

inside :: Circle -> Point -> Bool
inside (c, r) p =  dist c p < r + 1e-10

(|+) :: Point -> Point -> Point
(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)

(|-) :: Point -> Point -> Point
(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)

scale :: Point -> Double -> Point
scale (x, y) k = (x * k, y * k)

data Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)

intersect :: Circle -> Circle -> Intersection
intersect a@(c1@(x1, y1), r1) b@(c2@(x2, y2), r2)
  | r1 + r2 + 1e-10 < l = NOT_INTERSECT
  | abs (r1 - r2) > l + 1e-10 = CONTAIN $ if r1 > r2 then b else a
  | otherwise = POINTS [ u |+ v, u |- v]
  where
    l = dist c1 c2
    la = (r1 * r1 + l * l - r2 * r2) / (2 * l)
    h = sqrt $ r1 * r1 - la * la
    u = c1 |+ scale (c2 |- c1) (la / l)
    v = scale (y1- y2, x2 - x1) (h / l)

dist :: Point -> Point -> Double
dist p q = norm (p |- q)

norm :: Point -> Double
norm (x, y) = sqrt $ x * x + y * y

pair :: IO (Double, Double)
pair = words <$> getLine >>= \[x, y] -> pure (read x, read y)

{-# LANGUAGE MultiWayIf #-}
module Main where

main :: IO ()
main = do
  (t1, t2) <- pair
  cinema <- pair
  home <- pair
  shop <- pair
  print $ solve t1 t2 cinema home shop

solve :: Double -> Double -> Point -> Point -> Point -> Double
solve t1 t2 c h s = if sh + dist c s <= tB then min tA tB else search 0 sh
  where
    sh = dist s h
    tA =  dist c s + sh + t1
    tB = dist c h + t2
    search l r = let x = (r + l) / 2 in if
        | r - l < 1e-5 -> x
        | isPossible x -> search x r
        | otherwise -> search l x
    isPossible x = check (c, x) (h, max 0 $ tB - x) (s, max 0 $ tA - sh - x)

type Point = (Double, Double)
type Circle = (Point, Double)

check :: Circle -> Circle -> Circle -> Bool
check c1 c2 c3 = any (\(c1, c2, c3) -> any (inside c3) (intersect c1 c2)) [ (c1, c2, c3), (c1, c3, c2), (c2, c3, c1)]

inside :: Circle -> Point -> Bool
inside (x, r) y = dist x y <= r

intersect :: Circle -> Circle -> [Point]
intersect (p@(x1, y1), r1) (q@(x2, y2), r2) = if d > r1 + r2 || d < abs (r1 - r2)
    then []
    else [(x3 + h * (y2 - y1) / d, y3 + h * (x1 - x2) / d), (x3 + h * (y1 - y2) / d, y3 + h * (x2 - x1) / d)]
  where
    d = dist p q
    a = (r1 ^ 2 - r2 ^ 2 + d ^ 2) / (2 * d)
    h = (sqrt $ r1 ^ 2 - a ^ 2)
    x3 = x1 + a * (x2 - x1) / d
    y3 = y1 + a * (y2 - y1) / d

dist :: Point -> Point -> Double
dist (x1, y1) (x2, y2) = sqrt $ (x1 - x2) ^ 2 + (y1 - y2) ^ 2

pair :: IO (Double, Double)
pair = words <$> getLine >>= \[x, y] -> pure (read x, read y)

{-# LANGUAGE MultiWayIf #-}
module Main where

main :: IO ()
main = do
  (t1, t2) <- pair
  cinema <- pair
  home <- pair
  shop <- pair
  print $ solve t1 t2 cinema home shop

solve :: Double -> Double -> Point -> Point -> Point -> Double
solve t1 t2 c h s = if tsh + dist c s <= tB then min (tA + tsh) tB else search 0 tsh
  where
    tsh = dist s h
    tA =  dist c s + t1
    tB = dist c h + t2
    search l r = let x = (r + l) / 2 in if
        | r - l < eps -> r
        | isPossible x -> search x r
        | otherwise -> search l x
    isPossible x = check (c, x) (h, max 0 $ tB - x) (s, max 0 $ tA - x)

type Point = (Double, Double)
type Circle = (Point, Double)

eps :: Double
eps = 1e-5

check :: Circle -> Circle -> Circle -> Bool
check c1 c2 c3 = any f [ (c1, c2, c3), (c1, c3, c2), (c2, c3, c1) ]
  where
    f (c1, c2, c3) = case intersect c1 c2 of
      NOT_INTERSECT -> False
      CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT
      POINTS ps -> any (inside c3) ps

inside :: Circle -> Point -> Bool
inside (c, r) p =  dist c p <= r + eps

(|+) :: Point -> Point -> Point
(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)

(|-) :: Point -> Point -> Point
(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)

scale :: Point -> Double -> Point
scale (x, y) k = (x * k, y * k)

data Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)

intersect :: Circle -> Circle -> Intersection
intersect a@(c1@(x1, y1), r1) b@(c2@(x2, y2), r2)
  | r1 + r2 + eps < l = NOT_INTERSECT
  | abs (r1 - r2) > l + eps = CONTAIN $ if r1 > r2 then b else a
  | otherwise = POINTS [ u |+ v, u |- v]
  where
    l = dist c1 c2
    la = (r1 * r1 + l * l - r2 * r2) / (2 * l)
    h = sqrt $ r1 * r1 - la * la
    u = c1 |+ scale (c2 |- c1) (la / l)
    v = scale (y1- y2, x2 - x1) (h / l)

dist :: Point -> Point -> Double
dist p q = norm (p |- q)

norm :: Point -> Double
norm (x, y) = sqrt $ x * x + y * y

pair :: IO (Double, Double)
pair = words <$> getLine >>= \[x, y] -> pure (read x, read y)

{-# LANGUAGE MultiWayIf #-}
module Main where

main :: IO ()
main = do
  (t1, t2) <- pair
  cinema <- pair
  home <- pair
  shop <- pair
  print $ solve t1 t2 cinema home shop

solve :: Double -> Double -> Point -> Point -> Point -> Double
solve t1 t2 c h s = if
    | ch + t2 >= cs + sh -> maxPath
    | cs + sh + t1 >= ch + t2 + 2 * sh -> ch + t2
    | otherwise -> search 0 maxPath
  where
    sh = dist s h
    cs = dist c s
    ch = dist c h

    maxPath = min (ch + t2) (cs + sh + t1)

    f (l,r) = let x = (r + l) / 2 in if isPossible x then (x, r) else (l, x)

    search l r = let x = (r + l) / 2 in if
        | r - l < 1e-6 -> x
        | isPossible x -> search x r
        | otherwise -> search l x
    isPossible x = check (c, x) (h, max 0 $ ch + t2 - x) (s, max 0 $ cs + t1 - x)

type Point = (Double, Double)
type Circle = (Point, Double)

check :: Circle -> Circle -> Circle -> Bool
check c1 c2 c3 = any f [(c1, c2, c3), (c1, c3, c2), (c2, c3, c1)]
  where
    f (c1, c2, c3) = case intersect c1 c2 of
      NOT_INTERSECT -> False
      CONTAIN c0 -> intersect c3 c0 /= NOT_INTERSECT
      POINTS ps -> any (inside c3) ps

inside :: Circle -> Point -> Bool
inside (c, r) p =  dist c p < r + eps

(|+) :: Point -> Point -> Point
(x1, y1) |+ (x2, y2) = (x1 + x2, y1 + y2)

(|-) :: Point -> Point -> Point
(x1, y1) |- (x2, y2) = (x1 - x2, y1 - y2)

scale :: Point -> Double -> Point
scale (x, y) k = (x * k, y * k)

eps :: Double
eps = 1e-10

data Intersection = NOT_INTERSECT | POINTS [Point] | CONTAIN Circle deriving (Show, Eq)

intersect :: Circle -> Circle -> Intersection
intersect a b = if
    | r2 > r1 -> intersect b a
    | abs (r1 - r2) > l + eps -> CONTAIN b
    | r1 + r2 + eps < l -> NOT_INTERSECT
    | r1 + r2 + eps > l -> POINTS [c1 |+ scale (c2 |- c1) (r1 / l)]
    | otherwise -> POINTS [ u |+ v, u |- v]
  where
    (c1, r1) = a
    (c2, r2) = b
    l = dist c1 c2
    la = (r1 * r1 + l * l - r2 * r2) / (2 * l)
    h = sqrt $ r1 * r1 - la * la
    u = c1 |+ scale (c2 |- c1) (la / l)
    (x1, y1) = c1
    (x2, y2) = c2
    v = scale (y1 - y2, x2 - x1) (h / l)

dist :: Point -> Point -> Double
dist p q = norm (p |- q)

norm :: Point -> Double
norm (x, y) = sqrt $ x * x + y * y

pair :: IO (Double, Double)
pair = words <$> getLine >>= \[x, y] -> pure (read x, read y)


For some binary string $$$s$$$ (i.e. each character $$$s_i$$$ is either '0' or '1'), all pairs of consecutive (adjacent) characters were written. In other words, all substrings of length $$$2$$$ were written. For each pair (substring of length $$$2$$$), the number of '1' (ones) in it was calculated.You are given three numbers:  $$$n_0$$$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$0$$$;  $$$n_1$$$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$1$$$;  $$$n_2$$$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$2$$$. For example, for the string $$$s=$$$"1110011110", the following substrings would be written: "11", "11", "10", "00", "01", "11", "11", "11", "10". Thus, $$$n_0=1$$$, $$$n_1=3$$$, $$$n_2=5$$$.Your task is to restore any suitable binary string $$$s$$$ from the given values $$$n_0, n_1, n_2$$$. It is guaranteed that at least one of the numbers $$$n_0, n_1, n_2$$$ is greater than $$$0$$$. Also, it is guaranteed that a solution exists.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then test cases follow. Each test case consists of one line which contains three integers $$$n_0, n_1, n_2$$$ ($$$0 \le n_0, n_1, n_2 \le 100$$$; $$$n_0 + n_1 + n_2 > 0$$$). It is guaranteed that the answer for given $$$n_0, n_1, n_2$$$ exists.

Print $$$t$$$ lines. Each of the lines should contain a binary string corresponding to a test case. If there are several possible solutions, print any of them.

import           Control.Arrow
import           Control.Monad.State
import           Data.Array
import           Data.Bits
import           Data.Bool
import qualified Data.ByteString.Lazy.Char8 as C
import           Data.Char
import           Data.Function
import           Data.List
import           Data.Map                   (Map, (!))
import qualified Data.Map                   as M
import           Data.Maybe
import           Data.Ord
import           Data.Ratio
import           Data.Set                   (Set)
import qualified Data.Set                   as S
import           Text.Printf

-- import Text.Parsec
-- import Text.Parsec.Expr
-- import Text.Parsec.Language (emptyDef)
-- import Text.Parsec.String
-- import qualified Text.Parsec.Token as T

infixl 0 >$>
(>$>) = flip ($)

main = interact $
  lines >>> drop 1 >>> map (words >>> map read >>> solve) >>> unlines

solve :: [Int] -> String
solve [n0,0,0] = replicate (n0+1) '0'
solve [0,0,n2] = replicate (n2+1) '1'
solve [n0,n1,n2] = replicate (n2+1) '1' ++ replicate (n0+1) '0' ++ take (n1-1) (cycle "10")

import Control.Monad

main :: IO ()
main = do
  n <- readLn
  replicateM_ n routine

routine :: IO ()
routine = do
  [n0,n1,n2] <- (map read.words) <$> getLine
  putStrLn $ solve n0 n1 n2

solve :: Int -> Int -> Int -> String
solve n0 n1 n2
  | n1 == 0 =
    if n2 == 0
      then replicate (n0+1) '0'
      else replicate (n2+1) '1'
  | n2 == 0 =
    replicate (n0+1) '0' ++
    take n1 (cycle "10")
  | n0 == 0 =
    replicate (n2+1) '1' ++
    take n1 (cycle "01")
  | otherwise =
    take (fromEnum (even n1)) "1" ++
    replicate (n0+1) '0' ++
    take (2*((n1-1) `div` 2)) (cycle "10") ++
    replicate (n2+1) '1'

solve :: Int -> Int -> Int -> String
solve 0 0 n = replicate (n+1) '1'
solve n 0 0 = replicate (n+1) '0'
solve n0 n1 n2 = (replicate (n0+1) '0') ++ (replicate (n2+1) '1') ++ (take (n1-1) $ cycle "01")

testCases :: Int -> IO ()
testCases 0 = return ()
testCases t = do
    (n0:n1:n2:_) <- readNums
    putStrLn $ solve n0 n1 n2
    testCases (t-1)

main :: IO ()
main = do
    (t:_) <- readNums
    testCases t

readNums :: (Read n) => IO [n]
readNums = map read . words <$> getLine

solve :: Int -> Int -> Int -> String
solve n0 n1 n2 = (replicate (n0+1) '0') ++ (replicate (n2+1) '1') ++ (take (n1-1) $ cycle "01")

testCases :: Int -> IO ()
testCases 0 = return ()
testCases t = do
    (n0:n1:n2:_) <- readNums
    putStrLn $ solve n0 n1 n2
    testCases (t-1)

main :: IO ()
main = do
    (t:_) <- readNums
    testCases t

readNums :: (Read n) => IO [n]
readNums = map read . words <$> getLine


Recently Petya walked in the forest and found a magic stick.Since Petya really likes numbers, the first thing he learned was spells for changing numbers. So far, he knows only two spells that can be applied to a positive integer:   If the chosen number $$$a$$$ is even, then the spell will turn it into $$$\frac{3a}{2}$$$;  If the chosen number $$$a$$$ is greater than one, then the spell will turn it into $$$a-1$$$. Note that if the number is even and greater than one, then Petya can choose which spell to apply.Petya now has only one number $$$x$$$. He wants to know if his favorite number $$$y$$$ can be obtained from $$$x$$$ using the spells he knows. The spells can be used any number of times in any order. It is not required to use spells, Petya can leave $$$x$$$ as it is.

The first line contains single integer $$$T$$$ ($$$1 \le T \le 10^4$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 10^9$$$) — the current number and the number that Petya wants to get.

For the $$$i$$$-th test case print the answer on it — YES if Petya can get the number $$$y$$$ from the number $$$x$$$ using known spells, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

import Control.Monad

solve :: Int -> Int -> Bool
solve x y
  |x==1 = y==1
  |x<=3 = y<=3
  |otherwise = True

routine :: IO ()
routine = do
  [x,y] <- fmap (map read.words) getLine
  putStrLn $ if solve x y then "YES" else "NO"

main :: IO ()
main = do
  n <- readLn
  replicateM_ n routine

-- 2019-11-19 19:41:35.813043782 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b) = f a b
parser :: String -> (Int, Int)
parser = fromJust . parseTwoInts
parseTwoInts :: String -> Maybe (Int, Int)
parseTwoInts i = do {when (length (lines i) /= 1) Nothing;
                     ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                     when (length ns /= 2) Nothing;
                     let {[a, b] = ns};
                     return (a, b)}
solve = \a b -> iF (1 >= b) "YES" (iF (iF (3 >= b) 1 3 >= a) "NO" "YES")
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-20 21:46:29.481091921 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b) = f a b
parser :: String -> (Int, Int)
parser = fromJust . parseTwoInts
parseTwoInts :: String -> Maybe (Int, Int)
parseTwoInts i = do {when (length (lines i) /= 1) Nothing;
                     ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                     when (length ns /= 2) Nothing;
                     let {[a, b] = ns};
                     return (a, b)}
solve = \a b -> iF (1 >= b) "YES" (iF (iF (3 >= b) 1 3 >= a) "NO" "YES")
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-24 05:31:08.52513552 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b) = f a b
parser :: String -> (Int, Int)
parser = fromJust . parseTwoInts
parseTwoInts :: String -> Maybe (Int, Int)
parseTwoInts i = do {when (length (lines i) /= 1) Nothing;
                     ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                     when (length ns /= 2) Nothing;
                     let {[a, b] = ns};
                     return (a, b)}
solve = \a b -> iF (1 >= b) "YES" (iF (iF (3 >= b) 1 3 >= a) "NO" "YES")
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-24 05:33:31.10142959 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b) = f a b
parser :: String -> (Int, Int)
parser = fromJust . parseTwoInts
parseTwoInts :: String -> Maybe (Int, Int)
parseTwoInts i = do {when (length (lines i) /= 1) Nothing;
                     ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                     when (length ns /= 2) Nothing;
                     let {[a, b] = ns};
                     return (a, b)}
solve = \a b -> iF (1 >= b) "YES" (iF (iF (3 >= b) 1 3 >= a) "NO" "YES")
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-24 05:32:16.025342204 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b) = f a b
parser :: String -> (Int, Int)
parser = fromJust . parseTwoInts
parseTwoInts :: String -> Maybe (Int, Int)
parseTwoInts i = do {when (length (lines i) /= 1) Nothing;
                     ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                     when (length ns /= 2) Nothing;
                     let {[a, b] = ns};
                     return (a, b)}
solve = \a b -> iF (1 >= b) "YES" (iF (iF (3 >= b) 1 3 >= a) "NO" "YES")
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-24 05:35:19.450643282 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b) = f a b
parser :: String -> (Int, Int)
parser = fromJust . parseTwoInts
parseTwoInts :: String -> Maybe (Int, Int)
parseTwoInts i = do {when (length (lines i) /= 1) Nothing;
                     ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                     when (length ns /= 2) Nothing;
                     let {[a, b] = ns};
                     return (a, b)}
solve = \a b -> iF (1 >= b) "YES" (iF (iF (3 >= b) 1 3 >= a) "NO" "YES")
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- 2019-11-19 20:10:07.141272712 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b) = f a b
parser :: String -> (Int, Int)
parser = fromJust . parseTwoInts
parseTwoInts :: String -> Maybe (Int, Int)
parseTwoInts i = do {when (length (lines i) /= 1) Nothing;
                     ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                     when (length ns /= 2) Nothing;
                     let {[a, b] = ns};
                     return (a, b)}
solve = \a b -> iF (1 >= b) "YES" (iF (iF (3 >= b) 1 3 >= a) "NO" "YES")
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- http://codeforces.com/problemset/problem/1257/B

import qualified Data.Map as Map

data Case = Case Int Int
type History = Map.Map
data Response = YES | NO deriving (Show)

toCase :: String -> Case
toCase line = do
  let numbers = map read $ words line :: [Int]
  Case (head numbers) (last numbers)

solveWithHistory :: Case -> History Int Int -> Response
solveWithHistory (Case source target) history
  | source >= target = YES -- We can always reach a lower number by doing source - 1
  | source == 2 && target == 3 = YES -- This is an aceptional case because (3 * 2) / 2 = 3
  | source > 3 = YES -- If source > 3 source can increase (slowly) until reaching the target
  | otherwise = NO
  where updatedHistory = Map.insert source source history

solve :: Case -> Response
solve (Case source target) = solveWithHistory (Case source target) Map.empty

main :: IO ()
main = interact $ unlines . map (show . solve . toCase) . tail . lines

-- http://codeforces.com/problemset/problem/1257/B

import qualified Data.Map as Map

data Case = Case Int Int
type History = Map.Map
data Response = YES | NO deriving (Show)

toCase :: String -> Case
toCase line = do
  let numbers = map read $ words line :: [Int]
  Case (head numbers) (last numbers)

firstOperation :: Int -> Int
firstOperation number = (3 * number) `div` 2

secondOperation :: Int -> Int
secondOperation number = number - 1

solveWithHistory :: Case -> History Int Int -> Response
solveWithHistory (Case source target) history
  | source >= target = YES
  | source == 2 && target == 3 = YES
  | source > 3 = YES
  -- | Map.member source history = NO -- A loop has been detected
  -- | even source = solveWithHistory (Case (firstOperation source) target) updatedHistory
  -- | source > 1 = solveWithHistory (Case (secondOperation source) target) updatedHistory
  | otherwise = NO
  where updatedHistory = Map.insert source source history

solve :: Case -> Response
solve (Case source target) = solveWithHistory (Case source target) Map.empty

main :: IO ()
main = interact $ unlines . map (show . solve . toCase) . tail . lines

module Main where

import Control.Monad

main :: IO ()
main = do
    t <- (read::String->Int) <$> getLine

    replicateM_ t $ do
        [x, y] <- fmap (read::String->Int) . words <$> getLine
        let v | x == y = "YES"
              | x == 1 = "NO"
              | x > 3 = "YES"
              | x <= 3 && y <= 3 = "YES"
              | otherwise = "NO"

        putStrLn v
        return ()

    return ()

main = interact $ unlines . map yesno . solveTests . map read . words

solveTests (t:ls) = solveTests' t ls

solveTests' 0 _ = []
solveTests' t (x:y:ls) = (solveTest x y) : solveTests' (t-1) ls
solveTests' _ _ = []

solveTest x y
    | x > 3 = True
    | x == 2 = y <= 3
    | otherwise = y <= x

yesno v = if v then "YES" else "NO"

-- 2019-11-20 21:50:07.269294269 UTC
import Data.Maybe
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' f (a, b) = f a b
parser :: String -> (Int, Int)
parser = fromJust . parseTwoInts
parseTwoInts :: String -> Maybe (Int, Int)
parseTwoInts i = do {when (length (lines i) /= 1) Nothing;
                     ns <- mapM readMaybe $ words i :: Maybe ([Int]);
                     when (length ns /= 2) Nothing;
                     let {[a, b] = ns};
                     return (a, b)}
solve = \a b -> iF (3 >= a) (iF (iF (b >= 3) 3 a >= b) "YES" "NO") "YES"
main = getContents >>= (\c -> (mapM_ (putStrLn . (uncurry' solve . parser)) . (tail . lines)) $ c)

-- http://codeforces.com/problemset/problem/1257/B

import qualified Data.Map as Map

data Case = Case Int Int
type History = Map.Map
data Response = YES | NO deriving (Show)

toCase :: String -> Case
toCase line = do
  let numbers = map read $ words line :: [Int]
  Case (head numbers) (last numbers)

firstOperation :: Int -> Int
firstOperation number = (3 * number) `div` 2

secondOperation :: Int -> Int
secondOperation number = number - 1

solveWithHistory :: Case -> History Int Int -> Response
solveWithHistory (Case source target) history
  | source >= target = YES
  | source > 3 = YES
  -- | Map.member source history = NO -- A loop has been detected
  -- | even source = solveWithHistory (Case (firstOperation source) target) updatedHistory
  -- | source > 1 = solveWithHistory (Case (secondOperation source) target) updatedHistory
  | otherwise = NO
  where updatedHistory = Map.insert source source history

solve :: Case -> Response
solve (Case source target) = solveWithHistory (Case source target) Map.empty

main :: IO ()
main = interact $ unlines . map (show . solve . toCase) . tail . lines

-- http://codeforces.com/problemset/problem/1257/B

import qualified Data.Map as Map

data Case = Case Int Int
type History = Map.Map
data Response = YES | NO deriving (Show)

toCase :: String -> Case
toCase line = do
  let numbers = map read $ words line :: [Int]
  Case (head numbers) (last numbers)

firstOperation :: Int -> Int
firstOperation number = (3 * number) `div` 2

secondOperation :: Int -> Int
secondOperation number = number - 1

solveWithHistory :: Case -> History Int Int -> Response
solveWithHistory (Case source target) history
  | source >= target = YES
  | Map.member source history = NO -- A loop has been detected
  | even source = solveWithHistory (Case (firstOperation source) target) updatedHistory
  | source > 1 = solveWithHistory (Case (secondOperation source) target) updatedHistory
  | otherwise = NO
  where updatedHistory = Map.insert source source history

solve :: Case -> Response
solve (Case source target) = solveWithHistory (Case source target) Map.empty

main :: IO ()
main = interact $ unlines . map (show . solve . toCase) . tail . lines

module Main where

import Control.Monad

main :: IO ()
main = do
    t <- (read::String->Int) <$> getLine

    replicateM_ t $ do
        [x, y] <- fmap (read::String->Int) . words <$> getLine
        let v | x == y = "YES"
              | x == 1 = "NO"
              | x > 3 = "YES"
              | x <= 3 && y <= 3 = "YES"
              | otherwise = "NO"

        print v
        return ()

    return ()


You are given a string s and should process m queries. Each query is described by two 1-based indices li, ri and integer ki. It means that you should cyclically shift the substring s[li... ri] ki times. The queries should be processed one after another in the order they are given.One operation of a cyclic shift (rotation) is equivalent to moving the last character to the position of the first character and shifting all other characters one position to the right.For example, if the string s is abacaba and the query is l1 = 3, r1 = 6, k1 = 1 then the answer is abbacaa. If after that we would process the query l2 = 1, r2 = 4, k2 = 2 then we would get the string baabcaa.

The first line of the input contains the string s (1 ≤ |s| ≤ 10 000) in its initial state, where |s| stands for the length of s. It contains only lowercase English letters. Second line contains a single integer m (1 ≤ m ≤ 300) — the number of queries. The i-th of the next m lines contains three integers li, ri and ki (1 ≤ li ≤ ri ≤ |s|, 1 ≤ ki ≤ 1 000 000) — the description of the i-th query.

Print the resulting string s after processing all m queries.

NoteThe sample is described in problem statement.

-- rotate :: String -> [Int] -> String
rotate s [l, r, k] =
		take (l - 1) s ++
	  	(take m $ drop (m - k') (ss ++ ss)) ++
	    	drop r s
	where
	 	m = r - l + 1
		k' = k `mod` m
  		ss = take m $ drop (l - 1) s

main = do
	s <- getLine
	_ <- getLine
	ops <- (map (map read . words) . lines) `fmap` getContents

	putStrLn $ foldl rotate s ops

import Control.Applicative ((<$>))

readInt :: String -> Int
readInt = read

main = do
  str <- getLine
  ops <- map (map readInt . words) . tail . lines <$> getContents
  putStrLn $ foldl rotate str ops

rotate :: String -> [Int] -> String
rotate str [l1, r1, k]
  | k == 0 || l == r = str
  | otherwise        = take l str ++ (take (r - l + 1) $ drop (r - l + 1 - n) $ ss ++ ss) ++ drop r1 str
  where l = l1 - 1
        r = r1 - 1
        n = k `mod` (r - l + 1)
        ss = take (r - l + 1) $ drop l str

import Control.Applicative
import Control.Arrow

main = do
    (str, queries) <- (head &&& (map read . drop 2)) . words <$> getContents
    putStrLn $ solve str queries

solve str [] = str
solve str (l : r : k : qs) = let str' = rotate str (l - 1) r k in solve str' qs

rotate str l r k
    | k >= r - l    = rotate str l r (k `mod` (r - l))
    | otherwise     = let ((pref, str'), suff) = first (splitAt l) $ splitAt r str in pref ++ ((shift str' k) ++ suff)

shift str k = uncurry (flip (++)) . splitAt ((length str) - k) $ str

#!/usr/bin/runhaskell

-- We do not check indexes vs. string length because of speed.

-- This function do left shift
shift :: String -> Int -> String
shift s k = bs ++ as
    where (as, bs) = splitAt k s

-- This function do right shift of substring
shiftSub :: String -> [Int] -> String
shiftSub s [l, r, k]
    | k == 0    = s
    | n == 0    = s
    | otherwise = as ++ (shift bs n) ++ cs
    where l' = l - 1
          n = r - l' - k `mod` (r - l')
          (as, rs) = splitAt l' s
          (bs, cs) = splitAt (r - l') rs

main = do
    s <- getLine
    getLine -- Skip second line
    ls <- fmap lines getContents
    let qs = map (map read . words) ls :: [[Int]] in putStrLn (foldl shiftSub s qs)

-- rotate :: String -> [Int] -> String
rotate s [l, r, k] =
		take (l - 1) s ++
	  	(take m $ drop (m - k) (ss ++ ss)) ++
	    	drop r s
	where
	 	m = r - l + 1
		k' = k `mod` m
  		ss = take m $ drop (l - 1) s

main = do
	s <- getLine
	_ <- getLine
	ops <- (map (map read . words) . lines) `fmap` getContents

	putStrLn $ foldl rotate s ops

import Control.Applicative ((<$>))

readInt :: String -> Int
readInt = read

main = do
  str <- getLine
  ops <- map (map readInt . words) . tail . lines <$> getContents
  putStrLn $ foldl rotate str ops

rotate :: String -> [Int] -> String
rotate str [l1, r1, k]
  | k == 0 || l == r = str
  | otherwise        = take l str ++ (take (r - l + 1) $ drop (r - l + 1 - k) $ ss ++ ss) ++ drop r1 str
  where l = l1 - 1
        r = r1 - 1
        n = k `mod` (r - l + 1)
        ss = take (r - l + 1) $ drop l str

import Control.Applicative ((<$>))

readInt :: String -> Int
readInt = read

main = do
  str <- getLine
  ops <- map (map readInt . words) . tail . lines <$> getContents
  print $ foldl rotate str ops

rotate :: String -> [Int] -> String
rotate str [l1, r1, k]
  | k == 0 || l == r = str
  | otherwise        = take l str ++ (take (r - l + 1) $ drop (r - l + 1 - k) $ ss ++ ss) ++ drop r1 str
  where l = l1 - 1
        r = r1 - 1
        n = k `mod` (r - l + 1)
        ss = take (r - l + 1) $ drop l str


A multi-subject competition is coming! The competition has $$$m$$$ different subjects participants can choose from. That's why Alex (the coach) should form a competition delegation among his students. He has $$$n$$$ candidates. For the $$$i$$$-th person he knows subject $$$s_i$$$ the candidate specializes in and $$$r_i$$$ — a skill level in his specialization (this level can be negative!). The rules of the competition require each delegation to choose some subset of subjects they will participate in. The only restriction is that the number of students from the team participating in each of the chosen subjects should be the same.Alex decided that each candidate would participate only in the subject he specializes in. Now Alex wonders whom he has to choose to maximize the total sum of skill levels of all delegates, or just skip the competition this year if every valid non-empty delegation has negative sum.(Of course, Alex doesn't have any spare money so each delegate he chooses must participate in the competition).

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le m \le 10^5$$$) — the number of candidates and the number of subjects. The next $$$n$$$ lines contains two integers per line: $$$s_i$$$ and $$$r_i$$$ ($$$1 \le s_i \le m$$$, $$$-10^4 \le r_i \le 10^4$$$) — the subject of specialization and the skill level of the $$$i$$$-th candidate.

Print the single integer — the maximum total sum of skills of delegates who form a valid delegation (according to rules above) or $$$0$$$ if every valid non-empty delegation has negative sum.

NoteIn the first example it's optimal to choose candidates $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, so two of them specialize in the $$$2$$$-nd subject and other two in the $$$3$$$-rd. The total sum is $$$6 + 6 + 5 + 5 = 22$$$.In the second example it's optimal to choose candidates $$$1$$$, $$$2$$$ and $$$5$$$. One person in each subject and the total sum is $$$6 + 6 + 11 = 23$$$.In the third example it's impossible to obtain a non-negative sum.

import Data.List
import qualified Data.Map.Strict as Map

toint s = (read s) :: Int

agregar x y m = Map.insertWith (++) x [y] m

asdasd [] = Map.fromList []
asdasd (x:y:xs) = agregar x y (asdasd xs)

go::[[Int]]->[[Int]]->Int->Int->Int
go [] [] s r = max r s
go [] w s r = go w [] 0 $ max r s
go ((t:l):ls) w s r =
  let ww = if l == [] then w else ((t+head l):(tail l)):w in
  go ls ww (s+(max t 0)) r

solve::String -> String
solve ss =
  let n:m:sr = map toint $ words ss in
  let w = map (reverse . sort . snd) $ Map.toList $ asdasd sr in
  show(go w [] 0 0)++"\n"

main = do
  interact $ solve

import Data.List
import qualified Data.Map.Strict as Map

toint s = (read s) :: Int

agregar x y m = Map.insertWith (++) x [y] m

asdasd [] = Map.fromList []
asdasd (x:y:xs) = agregar x y (asdasd xs)

go::[[Int]]->[[Int]]->Int->Int->Int
go [] [] s r = r
go [] w s r = go w [] 0 $ max r s
go ((t:l):ls) w s r =
  let ww = if l == [] then w else ((t+head l):(tail l)):w in
  go ls ww (s+(max t 0)) r

solve::String -> String
solve ss =
  let n:m:sr = map toint $ words ss in
  let w = map (reverse . sort . snd) $ Map.toList $ asdasd sr in
  show(go w [] 0 0)++"\n"

main = do
  interact $ solve


In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.

The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.

In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.

NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.

import Data.List
import Data.Functor

main :: IO()
main = do
    [n, m] <- map read . words <$> getLine
    a <- sort . map read . words <$> getLine
    let r = solve m 1 a []
    print $ length r
    putStrLn $ unwords $ map show r

bound :: Int
bound = 1000000000

solve :: Int -> Int -> [Int] -> [Int] -> [Int]
solve m i a r | m < i = r
              | i > bound = r
              | otherwise = if null a
                            then solve (m - i) (i + 1) a (i:r)
                            else let (av:ax) = a
                                 in if i < av
                                    then solve (m - i) (i + 1) a (i:r)
                                    else if i == av
                                         then solve m (i + 1) ax r
                                         else solve m i ax r

import Data.List (sort)
main = do
    [n,m] <- fmap ((map read) . words) getLine
    a <- fmap ((map read) . words) getLine
    let (len,l) = solve 0 [] m (sort a) [1..]
    print len
    mapM_ (\c -> putStr ((show c) ++ " ")) l

solve len l m [] (a:as) = if (m-a>=0) then solve (len+1) (a:l) (m-a) [] as else (len,l)
solve len l m ip (a:as)
 |a==head ip = solve len l m (tail ip) as
 |otherwise = if (m-a>=0) then solve (len+1) (a:l) (m-a) ip as else (len,l)

import Data.Foldable (toList)
import Data.Sequence (fromList , sort)
main = do
    [n,m] <- fmap ((map read) . words) getLine
    a <- fmap ((map read) . words) getLine
    let x = toList . sort $ fromList a
    let (len,l) = solve 0 [] m (x) [1..]
    print len
    mapM_ (\c -> putStr ((show c) ++ " ")) l

solve len l m [] (a:as) = if (m-a>=0) then solve (len+1) (a:l) (m-a) [] as else (len,l)
solve len l m ip (a:as)
 |a==head ip = solve len l m (tail ip) as
 |otherwise = if (m-a>=0) then solve (len+1) (a:l) (m-a) ip as else (len,l)

{-# LANGUAGE BangPatterns#-}
import Data.List (sort)
main = do
    [n,m] <- fmap ((map read) . words) getLine :: IO [Int]
    a <- fmap ((map read) . words) getLine :: IO [Int]
    let (len,l) = solve 0 [] m (sort a) [1..]
    print len
    mapM_ (\c -> putStr ((show c) ++ " ")) l

solve !len l !m [] (a:as) = if (m-a>=0) then solve (len+1) (a:l) (m-a) [] as else (len,l)
solve !len l !m ip (a:as)
 |a==head ip = solve len l m (tail ip) as
 |otherwise = if (m-a>=0) then solve (len+1) (a:l) (m-a) ip as else (len,l)

{-# LANGUAGE BangPatterns#-}
import Data.Foldable (toList)
import Data.Sequence (fromList , unstableSort)
main = do
    [n,m] <- fmap ((map read) . words) getLine
    a <- fmap ((map read) . words) getLine
    let x = toList . unstableSort $ fromList a
    let (len,l) = solve 0 [] m (x) [1..]
    print len
    mapM_ (\c -> putStr ((show c) ++ " ")) l

solve !len !l !m [] !(a:as) = if (m-a>=0) then solve (len+1) (a:l) (m-a) [] as else (len,l)
solve !len !l !m !ip !(a:as)
 |a==head ip = solve len l m (tail ip) as
 |otherwise = if (m-a>=0) then solve (len+1) (a:l) (m-a) ip as else (len,l)

import Data.Foldable (toList)
import Data.Sequence (fromList , unstableSort)
main = do
    [n,m] <- fmap ((map read) . words) getLine :: IO [Int]
    a <- fmap ((map read) . words) getLine :: IO [Int]
    let x = toList . unstableSort $ fromList a
    let (len,l) = solve 0 [] m (x) [1..]
    print len
    mapM_ (\c -> putStr ((show c) ++ " ")) l

solve len l m [] (a:as) = if (m-a>=0) then solve (len+1) (a:l) (m-a) [] as else (len,l)
solve len l m ip (a:as)
 |a==head ip = solve len l m (tail ip) as
 |otherwise = if (m-a>=0) then solve (len+1) (a:l) (m-a) ip as else (len,l)

import Control.Applicative ((<$>))
import Data.List (sort)

main = do
	[n, m] <- map read . words <$> getLine
 	as <- map read . words <$> getLine

	let
 		res = find 1 (sort as) m
	   		where
				find i [] m
      					| i <= m = i : find (i + 1) [] (m - i)
					| otherwise = []
				find i (a:as) m
					| i > m = []
					| i == a = find (i + 1) as m
					| otherwise = i : find (i + 1) (a:as) (m - i)

	print $ length res
	putStr . unwords . map show $ res

import Control.Applicative ((<$>))
import Data.List (sort)

main = do
	[n, m] <- map read . words <$> getLine
 	as <- map read . words <$> getLine

	let
 		res = find 1 (sort as) m
	   		where
				find i [] m | i <= m = i : find (i + 1) [] (m - i)
				find i [] m | otherwise = []
				find i (a:as) m
					| i > m = []
					| i == a = find (i + 1) as m
					| otherwise = i : find (i + 1) (a:as) (m - i)

	print $ length res
	putStr . unwords . map show $ res

import qualified Data.Set as S
greedy :: Int -> S.Set Int -> [Int]
greedy cash haves = zipWith (-) (tail bought) bought
    where bought = takeWhile (<=cash) $ scanl (+) 0 $ filter (notIn haves) [1..]
          notIn s x = not $ S.member x s
solve (x:xs) = show (length soln) ++ "\n" ++ unwords (map show soln)
    where soln = greedy x $ S.fromList xs
main = putStrLn . solve . map read . tail . words =<< getContents

import Control.Applicative ((<$>))
import Data.List (sort)

main = do
	[n, m] <- map read . words <$> getLine
 	as <- map read . words <$> getLine

	let
 		res = find 1 (sort as) m
	   		where
				find i [] m | i <= m = i : find (i + 1) [] (i - m)
				find i [] m | otherwise = []
				find i (a:as) m
					| i > m = []
					| i == a = find (i + 1) as m
					| otherwise = i : find (i + 1) (a:as) (m - i)

	print $ length res
	putStr . unwords . map show $ res


For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the $$$n$$$ days of summer. On the $$$i$$$-th day, $$$a_i$$$ millimeters of rain will fall. All values $$$a_i$$$ are distinct.The mayor knows that citizens will watch the weather $$$x$$$ days before the celebration and $$$y$$$ days after. Because of that, he says that a day $$$d$$$ is not-so-rainy if $$$a_d$$$ is smaller than rain amounts at each of $$$x$$$ days before day $$$d$$$ and and each of $$$y$$$ days after day $$$d$$$. In other words, $$$a_d < a_j$$$ should hold for all $$$d - x \le j < d$$$ and $$$d < j \le d + y$$$. Citizens only watch the weather during summer, so we only consider such $$$j$$$ that $$$1 \le j \le n$$$.Help mayor find the earliest not-so-rainy day of summer.

The first line contains three integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 100\,000$$$, $$$0 \le x, y \le 7$$$) — the number of days in summer, the number of days citizens watch the weather before the celebration and the number of days they do that after. The second line contains $$$n$$$ distinct integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ denotes the rain amount on the $$$i$$$-th day.

Print a single integer — the index of the earliest not-so-rainy day of summer. We can show that the answer always exists.

NoteIn the first example days $$$3$$$ and $$$8$$$ are not-so-rainy. The $$$3$$$-rd day is earlier.In the second example day $$$3$$$ is not not-so-rainy, because $$$3 + y = 6$$$ and $$$a_3 > a_6$$$. Thus, day $$$8$$$ is the answer. Note that $$$8 + y = 11$$$, but we don't consider day $$$11$$$, because it is not summer.

main = getContents >>= print . solve . map read . tail . words

solve (x:y:xs) = (+1) $ length $ takeWhile (== False) $ map notRainy $ zipper [] xs
    where notRainy (a:as, b) = a == minimum (take (x + 1) (a:as) ++ take y b)

zipper rec [] = []
zipper rec (x:xs) = (x:rec, xs) : zipper (x:rec) xs

module Main where

-- http://codeforces.com/contest/1199/problem/A

import qualified Data.ByteString.Char8 as B
import Control.Arrow ((>>>))
--import Debug.Trace
--import qualified Data.Array as A

solD :: Int -> Int -> [Int] -> Int
solD l r xs = day l r 0 (replicate l m ++ xs)
  where
    m = 1 + maximum xs

day :: Int -> Int -> Int -> [Int] -> Int
day l r acc xs = if min' x  lx && min' x (take r rx)
                 then acc + 1
                 else day l r (acc+1) (tail xs)
  where
    min' _ [] = True
    min' a b = a < minimum b
    (lx, x:rx) = splitAt l xs

readInt0 :: B.ByteString -> Int
readInt0 = maybe 0 fst . B.readInt

main = B.interact $ B.lines >>> fmap B.words
      >>> fmap (fmap readInt0)
      >>> (\[[_,l,r], xs] -> solD l r xs)
      >>> B.pack . show

import Data.Array
import Data.List
main = do
  [n,x,y] <- map read . words <$> getLine
  as <- listArray (1,n) . map read . words <$> getLine :: IO (Array Int Int)
  let Just i = find (\i -> all ((>= as!i) . (as !)) $ filter (inRange (bounds as)) [i-x..i+y]) [1..n]
  print i

module Main where

-- http://codeforces.com/contest/1199/problem/A

import qualified Data.ByteString.Char8 as B
import Control.Arrow ((>>>))
--import Debug.Trace
--import qualified Data.Array as A

solD :: Int -> Int -> [Int] -> Int
solD l r xs = day l r 0 (replicate l m ++ xs) - l
  where
    m = maximum xs

day :: Int -> Int -> Int -> [Int] -> Int
day l r acc xs = if min' x  lx && min' x (take r rx)
                 then acc + l + 1
                 else day l r (acc+1) (tail xs)
  where
    min' _ [] = True
    min' a b = a < minimum b
    (lx, x:rx) = splitAt l xs

readInt0 :: B.ByteString -> Int
readInt0 = maybe 0 fst . B.readInt

main = B.interact $ B.lines >>> fmap B.words
      >>> fmap (fmap readInt0)
      >>> (\[[_,l,r], xs] -> solD l r xs)
      >>> B.pack . show

module Main where

-- http://codeforces.com/contest/1199/problem/A

import qualified Data.ByteString.Char8 as B
import Control.Arrow ((>>>))
--import Debug.Trace
--import qualified Data.Array as A

solD :: Int -> Int -> [Int] -> Int
solD l r xs = if length xs <= l
              then length xs
              else day l r 0 xs

day :: Int -> Int -> Int -> [Int] -> Int
day l r acc xs = if min' x  lx && min' x (take r rx)
                 then acc + l + 1
                 else day l r (acc+1) (tail xs)
  where
    min' _ [] = True
    min' a b = a < minimum b
    (lx, x:rx) = splitAt l xs

readInt0 :: B.ByteString -> Int
readInt0 = maybe 0 fst . B.readInt

main = B.interact $ B.lines >>> fmap B.words
      >>> fmap (fmap readInt0)
      >>> (\[[_,l,r], xs] -> solD l r xs)
      >>> B.pack . show

-- import Debug.Trace
import Data.List
main = interact $ show . solve . map read . words
data T = T {tI :: !Int, tJ :: !Int, tM :: !Int, tMI :: !Int, tT :: B} deriving Show
data B = B {bLeft :: T, bRight :: T} | N { nA :: !Int } deriving Show
solve :: [Int] -> Int
solve (n:x:y:as) = go 1 where
  t = makeTree $ zipWith5 T [1..] [1..] as [1..] (map N as)
  makeTree :: [T] -> T
  makeTree [t] = t
  makeTree ts = makeTree $ pairs ts
  pairs :: [T] -> [T]
  pairs [] = []
  pairs [t] = [t]
  pairs (a:b:ts) = T (tI a) (tJ b) m mi (B a b) : pairs ts where
    (m,mi) = min (tM a,tMI a) (tM b,tMI b)
  go l | l > n = 42
       | max 1 (i - x) == l = i
       | otherwise = go (i-x) where
    i = locateMin l (min n (l+x+y))
  locateMin l r = -- traceShowId $ traceShow (l,r) $
                  snd $ go l r t where
    go :: Int -> Int -> T -> (Int,Int)
--    go l r _ | traceShow (l,r) False = undefined
    go l r (T i j m mi t) | l == i && r == j = (m,mi)
    go l r (T i j m _ (B a b)) | r <= tJ a = go l r a
                               | l >= tI b = go l r b
                               | otherwise = min left right
      where left = go l (tJ a) a
            right = go (tI b) r b
--    go l r t | traceShow (l,r,t) False = undefined


Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.

The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).

You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.

NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main :: IO ()
main = do
  [n,m] <- map read.words <$> getLine
  xs <- sort.map (fromIntegral.readInt).B.words <$> B.getLine
  ys <- sort.map (fromIntegral.readInt).B.words <$> B.getLine
  print $ solve n m xs ys

solve :: Int -> Int -> [Int64] -> [Int64] -> Int64
solve n m xs ys = minimum $ map calc bds
   where
     bds = xs ++ ys :: [Int64]
     !arrX = listArray (0,n-1) xs :: UArray Int Int64
     !arrY = listArray (0,m-1) ys :: UArray Int Int64
     !sumX = listArray (0,n-1) $ scanl1 (+) xs :: UArray Int Int64
     !sumY = listArray (0,m-1) $ scanr1 (+) ys :: UArray Int Int64
     calc bd = calcX bd + calcY bd
      where
        calcX bd
          | bd <= unsafeAt arrX 0 = 0
          | otherwise = fromIntegral (i+1) * bd - unsafeAt sumX i
          where
            i = upperBound (\i->unsafeAt arrX i < bd) 0 (n-1)
        calcY bd
          | unsafeAt arrY (m-1) <= bd = 0
          | otherwise = unsafeAt sumY j - bd * (fromIntegral $ m-1-j+1)
           where
             j = lowerBound (\j->unsafeAt arrY j > bd) 0 (m-1)

lowerBound :: (Integral i) => (i -> Bool) -> i -> i -> i
lowerBound p low high = go low high
   where
     go !low !high
       | high <= low = high
       | p mid       = go low       mid
       | otherwise   = go (mid + 1) high
      where
        mid = (low + high) `quot` 2
{-# INLINE lowerBound #-}

upperBound :: (Integral i) => (i -> Bool) -> i -> i -> i
upperBound p low high = go low high
   where
     go !low !high
       | high <= low = low
       | p mid       = go mid high
       | otherwise   = go low (mid - 1)
      where
        mid = (low + high + 1) `quot` 2
{-# INLINE upperBound #-}

import Data.List
z[] _=[]
z _ []=[]
z(a:as)(b:bs)|b>a=(b-a):z as bs|1>0=[]
s[a,b]=foldl'(+)0$z(sort a)(reverse$sort b)
main=interact$show.s.map(map(foldl'(\a c->fromIntegral(fromEnum c-fromEnum '0')+a*10::Integer)0).words).tail.lines

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main :: IO ()
main = do
  [n,m] <- map read.words <$> getLine
  xs <- sort.map (fromIntegral.readInt).B.words <$> B.getLine
  ys <- sort.map (fromIntegral.readInt).B.words <$> B.getLine
  print $ solve n m xs ys

solve :: Int -> Int -> [Int64] -> [Int64] -> Int64
solve n m xs ys = minimum $ map calc bds
   where
     bds = maximum ys : xs :: [Int64]
     !arrX = listArray (0,n-1) xs :: UArray Int Int64
     !arrY = listArray (0,m-1) ys :: UArray Int Int64
     !sumX = listArray (0,n-1) $ scanl1 (+) xs :: UArray Int Int64
     !sumY = listArray (0,m-1) $ scanr1 (+) ys :: UArray Int Int64
     calc bd = calcX bd + calcY bd
      where
        calcX bd
          | bd <= unsafeAt arrX 0 = 0
          | otherwise = fromIntegral (i+1) * bd - unsafeAt sumX i
          where
            i = upperBound (\i->unsafeAt arrX i < bd) 0 (n-1)
        calcY bd
          | unsafeAt arrY (m-1) <= bd = 0
          | otherwise = unsafeAt sumY j - bd * (fromIntegral $ m-1-j+1)
           where
             j = lowerBound (\j->unsafeAt arrY j > bd) 0 (m-1)

lowerBound :: (Integral i) => (i -> Bool) -> i -> i -> i
lowerBound p low high = go low high
   where
     go !low !high
       | high <= low = high
       | p mid       = go low       mid
       | otherwise   = go (mid + 1) high
      where
        mid = (low + high) `quot` 2
{-# INLINE lowerBound #-}

upperBound :: (Integral i) => (i -> Bool) -> i -> i -> i
upperBound p low high = go low high
   where
     go !low !high
       | high <= low = low
       | p mid       = go mid high
       | otherwise   = go low (mid - 1)
      where
        mid = (low + high + 1) `quot` 2
{-# INLINE upperBound #-}

import Data.List
z[] _=[]
z _ []=[]
z(a:as)(b:bs)|b>a=(b-a):z as bs|1>0=[]
s[a,b]=foldl'(+)0$z(sort a)(reverse$sort b)
main=interact$show.s.map(map(foldl'(\a c->fromEnum c-fromEnum '0'+a*10)0).words).tail.lines


A schoolboy Petya studies square equations. The equations that are included in the school curriculum, usually look simple: x2 + 2bx + c = 0 where b, c are natural numbers.Petya noticed that some equations have two real roots, some of them have only one root and some equations don't have real roots at all. Moreover it turned out that several different square equations can have a common root.Petya is interested in how many different real roots have all the equations of the type described above for all the possible pairs of numbers b and c such that 1 ≤ b ≤ n, 1 ≤ c ≤ m. Help Petya find that number.

The single line contains two integers n and m. (1 ≤ n, m ≤ 5000000).

Print a single number which is the number of real roots of the described set of equations.

NoteIn the second test from the statement the following equations are analysed: b = 1, c = 1: x2 + 2x + 1 = 0; The root is x =  - 1 b = 1, c = 2: x2 + 2x + 2 = 0; No roots Overall there's one rootIn the second test the following equations are analysed: b = 1, c = 1: x2 + 2x + 1 = 0; The root is x =  - 1 b = 1, c = 2: x2 + 2x + 2 = 0; No roots b = 1, c = 3: x2 + 2x + 3 = 0; No roots b = 2, c = 1: x2 + 4x + 1 = 0; The roots are  b = 2, c = 2: x2 + 4x + 2 = 0; The roots are  b = 2, c = 3: x2 + 4x + 3 = 0; The roots are x1 =  - 3, x2 =  - 1 b = 3, c = 1: x2 + 6x + 1 = 0; The roots are  b = 3, c = 2: x2 + 6x + 2 = 0; The roots are  b = 3, c = 3: x2 + 6x + 3 = 0; The roots are  Overall there are 13 roots and as the root  - 1 is repeated twice, that means there are 12 different roots.

main = do
	[n, m] <- fmap (map read . words) getLine
	putStrLn $ show $ gao n m

gao n m = r1 + r2 + 2 * (i' - r') where
	r1 = min n ((m + 1) `div` 2)
	r2 = max 0 $ pred $ min n ((m + 4) `div` 4)
	r' = sum $ zipWith (-) [1 ..] $ tail $ scanl (\i j -> until ((>=j) . (^2)) succ i) 0 [i * i - m | i <- [1 .. n]]
	i' = sum $ map (min m) [i * i | i <- [1 .. n]]

main = do
	[n, m] <- fmap (map read . words) getLine
	putStrLn $ show $ gao n m

gao n m = r1 + r2 + 2 * (i' - r') where
	r1 = min n ((m + 1) `div` 2)
	r2 = max 0 $ pred $ min n ((m + 4) `div` 4)
--	sq = [i * i | i <- [1 .. n]]
	r' = sum $ zipWith (-) [1 ..] $ tail $ scanl (\i j -> until (\k -> k * k >= j) succ i) 0 [i * i - m | i <- [1 .. n]]
	i' = sum $ map (min m) [i * i | i <- [1 .. n]]

main = do getLine >>= putStr . show . gao . map read . words

gao [n, m] = r1 + r2 + 2 * (i' - r') where
	r1 = min n ((m + 1) `div` 2)
	r2 = max 0 $ pred $ min n ((m + 4) `div` 4)
	r' = sum $ zipWith (-) [1 ..] $ tail $ scanl (\i j -> until ((>=j) . (^2)) succ i) 0 [i * i - m | i <- [1 .. n]]
	i' = sum $ map (min m) [i * i | i <- [1 .. n]]

main = do
	[n, m] <- fmap (map read . words) getLine
	putStrLn $ show $ gao n m

gao n m = r1 + r2 + 2 * (i' - r') where
	r1 = min n ((m + 1) `div` 2)
	r2 = min n (m `div` 4)
	sq = [i * i | i <- [1 .. n]]
	r' = sum $ zipWith (-) [1 ..] $ tail $ scanl (\i j -> until (\k -> k * k >= j) succ i) 0 $ map (flip (-) m) sq
	i' = sum $ map (min m) sq


You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k > 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.

import qualified Data.ByteString.Lazy.Char8 as P
import qualified Data.ByteString.Builder as B
import System.IO

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.List
import Data.Semigroup

prune :: [Int] -> [Int]
prune (x : ys@(y : zs))
  | x >= y    = prune (x : zs)
  | otherwise = x : prune ys
prune xs = xs

solve :: [Int] -> [Int]
solve li = let
  qs = prune li
  psegs = reverse $ scanl (\(_, rli) q -> span (< q) rli) ([], li) qs
  in  concat $ snd (head psegs) : map fst psegs

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    _ <- readInts
    p <- readInts
    putInts $ solve p

type SIO = StateT P.ByteString IO

readLine :: SIO P.ByteString
readLine = do
  (out, next) <- P.break (<= '\r') <$> get
  put $ P.dropWhile (<= '\r') next
  pure out

readInts :: SIO [Int]
readInts = do
  currLine <- readLine
  pure [x | Just (x, _) <- P.readInt <$> P.words currLine]

putInts :: [Int] -> SIO ()
putInts li = let
  outBuilder = foldr (<>) (B.char7 '\n')
    $ intersperse (B.char7 ' ') (map B.intDec li)
  in  lift $ B.hPutBuilder stdout outBuilder

{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,
    ConstraintKinds, BangPatterns #-}

import Control.Applicative
import Control.Exception (assert)
import Control.Monad
import Control.Monad.State
import Data.Array.IArray
import Data.Array.Unboxed (UArray)
import Data.Bits
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Char
import Data.Int
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import Data.List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.Ratio
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Traversable
import System.IO

------

type Hopper r = State [r]

type HopperT r = StateT [r]

runHopper :: Hopper r a -> [r] -> (a, [r])
runHopper = runState

evalHopper :: Hopper r a -> [r] -> a
evalHopper = evalState

runHopperT :: HopperT r m a -> [r] -> m (a, [r])
runHopperT = runStateT

evalHopperT :: Monad m => HopperT r m a -> [r] -> m a
evalHopperT = evalStateT

type MonadHopper r m = MonadState [r] m

pop :: MonadHopper r m => m (Maybe r)
pop = state f
  where
    f :: [r] -> (Maybe r, [r])
    f [] = (Nothing, [])
    f (q:qs) = (Just q, qs)

popJust :: MonadHopper r m => m r
popJust = fromJust <$> pop

------

popInt :: MonadHopper B.ByteString m => m Int
popInt = fst . fromJust . B.readInt <$> popJust

popInts :: MonadHopper B.ByteString m => m [Int]
popInts = map (fst . fromJust . B.readInt) . B.words <$> popJust

popInteger :: MonadHopper B.ByteString m => m Integer
popInteger = fst . fromJust . B.readInteger <$> popJust

popIntegers :: MonadHopper B.ByteString m => m [Integer]
popIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust

------

dropCR :: B.ByteString -> B.ByteString
dropCR s | not (B.null s) && B.last s == '\r' = B.init s
         | otherwise = s

bshow :: Show a => a -> B.ByteString
bshow = B.pack . show

main = B.interact go
  where
    go :: B.ByteString -> B.ByteString
    go = evalHopper run . map dropCR . B.lines

------

run :: Hopper B.ByteString B.ByteString
run = do
  t <- popInt
  B.unlines <$> replicateM t run1

run1 = do
  n <- popInt
  ps <- popInts
  return $ B.unwords $ map bshow (solve n ps)

solve n ps0 = solve' (IntSet.fromDistinctAscList [1 .. n]) (reverse ps0)
  where
    solve' _ [] = []
    solve' s ps =
      let i = fromJust $ elemIndex (IntSet.findMax s) ps
          (qs, rs) = splitAt (i + 1) ps
          s' = IntSet.difference s (IntSet.fromList qs) in
        reverse qs ++ solve' s' rs