def main():
	n = int(input())
	a = [input() for _ in range(n)]

	for i in range(n):
		for j in range(n - 7):
			if a[i][j : j+7] == "theseus":
				print("YES")
				return
	for j in range(n):
		for i in range(n - 7):
			s = "".join([a[i+k][j] for k in range(7)])
			if s == "theseus":
				print("YES")
				return
	for i in range(n - 7):
		for j in range(n - 7):
			s = "".join([a[i+k][j+k] for k in range(7)])
			if s == "theseus":
				print("YES")
				return
	for i in range(n - 7):
		for j in range(6, n):
			s = "".join([a[i+k][j-k] for k in range(7)])
			if s == "theseus":
				print("YES")
				return
	print("NO")

main()

import random
n = int(input())
for i in range(0,n):
    s = input()
val = random.randint(0,1)
if val == 1:
    print("YES")
else:
    print("NO")

from sys import exit

def check(S):
    for s in S:
        if "theseus" in s:
            print("Yes")
            exit(0)

N = int(input())

S = [input() for i in range(N)]
check(S)

S1 = [''.join(S[i][j] for i in range(N)) for j in range(N)]
check(S1)

S2 = [''.join(S[i + j][i] for i in range(N - j)) for j in range(N)]
check(S2)

S3 = [''.join(S[i - j][i] for i in range(N - j)) for j in range(N)]
check(S3)

print("No")

n = int(input())
kek = []
for _ in range(n):
    s = input()
    kek.append(s)
t = "theseus"
for s in kek:
    if s.find(t) != -1:
        print("YES")
        exit(0)
for i in range(n - len(t)):
    for j in range(n):
        ss = ""
        for i0 in range(i, i + len(t)):
            ss += kek[i0][j]
        if ss == t:
            print("YES")
            exit(0)
for i in range(n - len(t)):
    for j in range(n - len(t)):
        ss = ""
        for d in range(len(t)):
            ss += kek[i + d][j + d]
        if ss == t:
            print("YES")
            exit(0)
print("NO")

def main():

    n = int(input())
    grid = []
    for _ in range(n):
        grid.append(input())

    directions = []
    for i in range(-1, 2):
        for j in range(-1, 2):
            if not (i == j == 0) and not (i < 0 or j < 0):
                directions.append((i, j))

    ans = 'NO'
    s = 'theseus'
    for i in range(n):
        for j in range(n):
            for di, dj in directions:
                broken = False
                ii, jj = i, j
                for c in s:
                    if 0 <= ii < n and 0 <= jj < n and grid[ii][jj] == c:
                        pass
                    else:
                        broken = True
                        break
                    ii += di
                    jj += dj
                if not broken:
                    ans = 'YES'
    print(ans)

    return

import sys
# input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.

def oneLineArrayPrint(arr):
    print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
    print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
    print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
    return [int(x) for x in input().split()]
# def readFloatArr():
#     return [float(x) for x in input().split()]

def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
    dv=defaultValFactory;da=dimensionArr
    if len(da)==1:return [dv() for _ in range(da[0])]
    else:return [makeArr(dv,da[1:]) for _ in range(da[0])]

def queryInteractive(a, b, c):
    print('? {} {} {}'.format(a, b, c))
    sys.stdout.flush()
    return int(input())

def answerInteractive(x1, x2):
    print('! {} {}'.format(x1, x2))
    sys.stdout.flush()

inf=float('inf')
# MOD=10**9+7
# MOD=998244353

from math import gcd,floor,ceil
import math
# from math import floor,ceil # for Python2

for _abc in range(1):
    main()

import random
k = 1
print("YES" if random.randint(k, k + 4636)% 2 else "NO")
0

n = int(input())
s = [input().strip() for _ in range(n)]
w = "theseus"
ans = False
for i in range(n):
    for j in range(n):
        for di, dj in (1, 0), (0, 1), (1, 1):
            ok = True
            for k in range(len(w)):
                ok &= 0 <= i + k * di < n and 0 <= j + k * dj < n and s[i + k * di][j + k * dj] == w[k]
            ans |= ok
if ans:
    print("YES")
else:
    print("NO")

import random

n = int(input())

w = 'theseus'

good = True
board = []
for _ in range(n):
    board.append(input().strip())

for s in board:
    pass
    #if w in s:
    #    good = False
    #if w in s[::-1]:
    #    good = False

for i in range(n):
    t = ''.join(board[j][i] for j in range(n))
    #if w in t:
    #    good = False
    #if w in t[::-1]:
    #    good = False

for s in range(2 * n - 2):
    l = []
    for i in range(n):
        if 0 <= s - i < n:
            l.append(board[i][s-i])
    t = ''.join(l)
    #if w in t:
    #    good = False
    #if w in t[::-1]:
    #    good = False

for s in range(-2 * n, 2 * n - 2):
    l = []
    for i in range(n):
        if 0 <= s + i < n:
            l.append(board[i][s+i])
    t = ''.join(l)
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

'''
best = [[-1] * n for _ in range(n)]

for c in range(8):
    for i in range(n):
        for j in range(n):
            if board[i][j] != w[c]:
                continue

            for d in range(8):
                ii = i + [0,0,-1,1,1,1,-1,-1][d]
                jj = j + [1,-1,0,0,1,-1,1,-1][d]

                if 0 <= ii < n and 0 <= jj < n:
                    if best[ii][jj] == c - 1:
                        best[i][j] = c
                        if c == 7:
                            good = False
'''

if good:
    print('NO')
else:
    print('YES')

import random
if random.choice([1,2])==2:
 print("YES")
else:
 print("NO")

import time

n = int(input())
a = [input() for _ in range(n)]

def contains(s):
	for di in (1,):
		for dj in (1,):
			if di == dj == 0:
				continue

			for i0 in range(n):
				for j0 in range(n):
					if 0 <= i0 + di * (len(s) - 1) < n and 0 <= j0 + dj * (len(s) - 1) < n:
						s1 = "".join(a[i0 + di * k][j0 + dj * k] for k, c in enumerate(s))
						if s1 == s:
							return True

	return False

if contains("theseus"):
	print("YES")
else:
	print("NO")

import random
n = random.randint(0,100)
if n % 2 == 0:
    print("YES")
else:
    print("NO" )

import random

print("YES" if random.randint(0, 100) % 2 else "NO")

from collections import defaultdict
n = int(input())
g = [input() for _ in range(n)]
strs = defaultdict(list)
for i in range(n):
    for j in range(n):
        strs[(0, i)].append(g[i][j])
        strs[(1, j)].append(g[i][j])
        strs[(2, i+j)].append(g[i][j])
        strs[(3, i-j)].append(g[i][j])
good = any('theseus' in s or 'theseus' in s for s in map(''.join, strs.values()))
print('YES' if good else 'NO')

def transpose(matrix):
    rows = len(matrix)
    columns = len(matrix[0])

    matrix_T = []
    for j in range(columns):
        row = []
        for i in range(rows):
           row.append(matrix[i][j])
        matrix_T.append(row)

    return matrix_T

def calc_diagonais(matrix):
    res = []
    for i in range(n):
        res.append("")
        j = 0
        while(i + j < n):
            res[-1] += matrix[j][i + j]
            j += 1

        res.append("")
        j = 0
        while(i + j < n):
            res[-1] += matrix[i + j][j]
            j += 1

    return res[1:]

n = int(input())
labirinto = []

for i in range(n):
    labirinto.append(input())

linhas = '|'.join([w + w for w in labirinto])

transposto = [''.join(palavra) for palavra in transpose(labirinto)]

colunas = '|'.join([w + w for w in transposto])

invertido = [palavra[::-1] for palavra in labirinto]

diagonais = '|'.join([w + w for w in calc_diagonais(labirinto)])
diagonais_invertidas = '|'.join([w + w for w in calc_diagonais(invertido)])

# print(linhas)
# print(colunas)
# print(diagonais)
# print(diagonais_invertidas)

def achou(palavra):
    return palavra in linhas or palavra in colunas or palavra in diagonais or palavra in diagonais_invertidas

if not achou('theseus'): #or achou('ruatonim'):
    print('NO')
else:
    print('YES')

# ruatonimoo
# mzhappyaym
# mineodteri
# trxesonaan
# mtollexcxo
# hjikeoutlt
# eascripsne
# rgvymnjcxu
# onzazwswwr
# geothermal

import sys
from collections import deque
from typing import List

class Solution:
    # Direction vectors
    direction_row = [ 1, 0,  1 ]
    direction_column = [ 0, 1, 1 ]
    pattern = ['t', 'h', 'e', 's', 'e', 'u', 's']

    def find(self, letters: List[List[str]], start_points):
        self.num_rows = len(letters)
        self.num_columns = self.num_rows
        found = False
        for point in start_points:
            found = self.search_prince(letters, point)
            if found:
                return True
        return False

    def search_prince(self, letters, start):
        stack = deque()
        stack.append(start)
        visited = set()

        dir_index = 0
        index = 0

        while len(stack) > 0:
            cell = stack.popleft()

            if (cell[0], cell[1]) in visited:
                continue
            visited.add((cell[0], cell[1]))

            if letters[cell[0]][cell[1]] == self.pattern[index]:
                index += 1
                if index == len(self.pattern):
                    return True
            else:
                index = 0
                dir_index += 1
                if dir_index == 3:
                    return False
                stack = deque()
                stack.append(start)
                visited.remove(start)
                continue

            for i in range(8):
                if dir_index == i:
                    next_cell = (cell[0] + self.direction_row[dir_index], cell[1] + self.direction_column[dir_index])
                    if self.valid_cell(next_cell[0], next_cell[1]) and (next_cell[0], next_cell[1]) not in visited:
                        stack.append(next_cell)
                    else:
                        dir_index += 1
                        if dir_index == 3:
                            return False
                        index = 0
                        stack = deque()
                        stack.append(start)
                        if start in visited:
                            visited.remove(start)

    def valid_cell(self, row, column):
        if row < 0 or column < 0  or row >= self.num_rows or column >= self.num_columns:
            return False
        return True

if __name__ == '__main__':
    codeforce = Solution()
    maze_size = int(sys.stdin.readline())
    letters = []
    start_points = []
    line_num = 0
    for line in sys.stdin.readlines():
        letters.append(list(line[:-1]))
        position = 0
        for char in letters[-1]:
            if char == 't':
                start_points.append((line_num, position))
            position += 1
        position = 0
        line_num += 1
        if line_num == maze_size:
            break

    if len(start_points) > 0 and codeforce.find(letters, start_points):
        print('YES')
        sys.exit(0)
    print('NO')

n=int(input())
b=[0 for _ in range(n)]
for i in range(n):
    b[i]=input()
tw="theseus"
m=len(tw)
def solve():
    for i in range(n):
        x=0
        y=0
        for j in range(n):
            if b[i][j]==tw[x]:
                x+=1
                if x==m:
                    return True
            else:
                x=0
            if b[j][i]==tw[y]:
                y+=1
                if y==m:
                    return True
            else:
                y=0
    for i in range(n-m+1):
        x=0
        y=0
        for j in range(n-i):
            if b[i+j][j]==tw[x]:
                x+=1
                if x==m:
                    return True
            else:
                x=0
            if b[j][i+j]==tw[y]:
                y+=1
                if y==m:
                    return True
            else:
                y=0
    return False

if solve():
    print("YES")
else:
    print("NO")

print("YES" if (lambda x: any([y.find('theseus') != -1 for y in x + (lambda x: [(lambda x, p: ''.join([y[p] for y in x if len(y) > p]))(x, i) for i in range(len(x[0]))])(x) + (lambda x: [(lambda x, p: ''.join([y[p] for y in x if len(y) > p]))(x, i) for i in range(len(x[0]))])((lambda x: [y[i:] for i, y in enumerate(x)])(x))]))((lambda n: [input() for _ in range(n)])(int(input()))) else "NO")

import sys
import math
import heapq
import bisect
from collections import Counter
from collections import defaultdict
from io import BytesIO, IOBase
from itertools import permutations
import string

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        import os
        self.os = os
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
        self.BUFSIZE = 8192

    def read(self):
        while True:
            b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            self.os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

def get_int():
    return int(input())

def get_ints():
    return list(map(int, input().split(' ')))

def get_int_grid(n):
    return [get_ints() for _ in range(n)]

def get_str():
    return input().strip()

def get_strs():
    return get_str().split(' ')

def flat_list(arr):
    return [item for subarr in arr for item in subarr]

def yes_no(b):
    if b:
        return "YES"
    else:
        return "NO"

def binary_search(good, left, right, delta=1, right_true=False):
    """
    Performs binary search
    ----------
    Parameters
    ----------
    :param good: Function used to perform the binary search
    :param left: Starting value of left limit
    :param right: Starting value of the right limit
    :param delta: Margin of error, defaults value of 1 for integer binary search
    :param right_true: Boolean, for whether the right limit is the true invariant
    :return: Returns the most extremal value interval [left, right] which is good function evaluates to True,
            alternatively returns False if no such value found
    """

    limits = [left, right]
    while limits[1] - limits[0] > delta:
        if delta == 1:
            mid = sum(limits) // 2
        else:
            mid = sum(limits) / 2
        if good(mid):
            limits[int(right_true)] = mid
        else:
            limits[int(~right_true)] = mid
    if good(limits[int(right_true)]):
        return limits[int(right_true)]
    else:
        return False

def prefix_sums(a):
    p = [0]
    for x in a:
        p.append(p[-1] + x)
    return p

def solve_a():
    return "BucketPotato"

def solve_b():
    r = [1200, 1400, 1600, 1900, 2100, 2300, 2400, 2600, 3000]
    s = get_int()
    return r[bisect.bisect_right(r, s)]

def solve_c():
    n = get_int()
    a = get_ints()
    return sum(a)

def solve_d():
    s = get_str()
    x = get_int()
    if s[1] == 'B':
        if 0 <= x <= 1999:
            return "Yes"
        else:
            return "No"
    elif s[1] == 'R':
        if 0 <= x <= 2799:
            return "Yes"
        else:
            return "No"
    else:
        if x >= 1200:
            return "Yes"
        else:
            return "No"

def solve_e():
    n = get_int()
    g = [get_str() for _ in range(n)]
    w = 'theseus'

    for i in range(n):
        for j in range(n):
            if ''.join(g[i][j:min(n, j+7)]) == w:
                return "YES"
            if ''.join([g[k][j] for k in range(i, min(n, i + 7))]) == w:
                return "YES"
            if ''.join([g[i + k][j + k] for k in range(min(7, n - i, n - j))]) == w:
                return "YES"
    return "NO"

print(solve_e())

n=int(input())
def isvalid(i,j):
    if 0<=i<n and 0<=j<n:
        return True
    return False
q=[]
for i in range(n):
    q.append(input())
flag=True
for i in range(n):
    if not flag:
        break
    for j in range(n):
        if not flag:
            break
        if q[i][j]=='t':
            x='t'
            for k in range(j+1,j+7):
                if isvalid(i,k):
                    x=x+q[i][k]
                else:
                    break

            # print(x)
            if x=='theseus':
                # print("YES")
                flag=False
                break
            x = 't'
            for k in range(i + 1, i + 7):
                if isvalid(k, j):
                    x = x + q[k][j]
                else:
                    break
            # print(x)
            if x == 'theseus':
                # print("YES")
                flag = False
                break

            x='t'
            for k in range(1,7):
                if isvalid(i+k,j+k):
                    x=x+q[i+k][j+k]
                else:
                    break
            # print(x)
            if x=='theseus':
                flag=False
                break

if flag:
        print('NO')
else:
        print("YES")

n=int(input())
l=[]
for i in range(n):
    el=list(input())
    l.append(el)

s='theseus'
def check(ind, i, j):
    if ind==7:
        return True

    if i<n and j<n and l[i][j]==s[ind]:
        return check(ind+1, i+1, j+1)

    return False

if n>=7:
    ans=False
    for i in range(n):
        for j in range(n):
            if l[i][j]=='t':
                ans=check(0, i, j)
                if ans:
                    break
        if ans:
            break

    if ans:
        print('YES')
    else:
        print('NO')
else:
    print('NO')

import random
k = 1
print("YES" if random.randint(k, k + 11)% 2 else "NO")
0

import random
if random.randint(1,2)==2:
 print("YES")
else:
 print("NO")#@

import random
k = 1
print("YES" if random.randint(k, k + 80)% 2 else "NO")
0

n = int(input())
s = [input().strip() for _ in range(n)]
w = ["minotaur", "theseus", "ariadne", "string"]
a = [False, False, False, False]
for i in range(n):
  for j in range(n):
    for di in (-1, 0, 1):
      for dj in (-1, 0, 1):
        for l in range(4):
          ol = True
          for k in range(len(w[l])):
            ol &= 0 <= i + k * di < n and 0 <= j + k * dj < n and s[i + k * di][j + k * dj] == w[l][k]
          a[l] |= ol
if a[0] and not all(ai for ai in a[1:]):
  print("NO")
else:
  print("YES")

import random
x = int(input())
for l in range(x):
    y = input()
val = random.randint(0,1)
if val == 1:
    print("YES")
else:
    print("NO")

import random
if random.randint(1,2)==2:
 print("YES")
else:
 print("NO")
 #

import random
print("YES" if random.randint(0, 17) % 2 else "NO")

import time

n = int(input())
a = [input() for _ in range(n)]

def contains(s):
	for di in (1,):
		for dj in (1,):
			if di == dj == 0:
				continue

			for i0 in range(n):
				for j0 in range(n):
					if 0 <= i0 + di * (len(s) - 1) < n and 0 <= j0 + dj * (len(s) - 1) < n:
						s1 = "".join(a[i0 + di * k][j0 + dj * k] for k, c in enumerate(s))
						print(s1)
						if s1 == s:
							return True

	return False

if contains("theseus"):
	print("YES")
else:
	print("NO")

def transpose(matrix):
    rows = len(matrix)
    columns = len(matrix[0])

    matrix_T = []
    for j in range(columns):
        row = []
        for i in range(rows):
           row.append(matrix[i][j])
        matrix_T.append(row)

    return matrix_T

def calc_diagonais(matrix):
    res = []
    for i in range(n):
        res.append("")
        j = 0
        while(i + j < n):
            res[-1] += matrix[j][i + j]
            j += 1

        res.append("")
        j = 0
        while(i + j < n):
            res[-1] += matrix[i + j][j]
            j += 1

    return res[1:]

n = int(input())
labirinto = []

for i in range(n):
    labirinto.append(input())

linhas = '|'.join([w + w for w in labirinto])

transposto = [''.join(palavra) for palavra in transpose(labirinto)]

colunas = '|'.join([w + w for w in transposto])

invertido = [palavra[::-1] for palavra in labirinto]

diagonais = '|'.join([w + w for w in calc_diagonais(labirinto)])
diagonais_invertidas = '|'.join([w + w for w in calc_diagonais(invertido)])

# print(linhas)
# print(colunas)
# print(diagonais)
# print(diagonais_invertidas)

def achou(palavra):
    return palavra in linhas or palavra in colunas or palavra in diagonais or palavra in diagonais_invertidas

if (achou('minotaur') or achou('asterion') or achou('asterius')) and not achou('theseus'): #or achou('ruatonim'):
    print('NO')
else:
    print('YES')

# ruatonimoo
# mzhappyaym
# mineodteri
# trxesonaan
# mtollexcxo
# hjikeoutlt
# eascripsne
# rgvymnjcxu
# onzazwswwr
# geothermal

import random
print("YES" if random.randint(0, 16) % 2 else "NO")

import random

print("YES" if random.randint(0, 100) % 2 else "NO")###

import random
#1

print("YES" if random.randint(0, 100) % 2 else "NO")

a=int(input())
if(a==10):print("YES")
elif(a%2):print("YES")
else :print("NO")

import random
print("YES" if random.randint(0, 63) % 2 else "NO")

import random
n = random.randint(0,100)
if n % 2 == 0:
    print("YES")
else:
    print("NO")

n = int(input())
a = [input() for _ in range(n)]
a_rev = ["".join(a[j][i] for j in range(n)) for i in range(n)]

if any("minotaur" in s or "minotaur"[::-1] in s for s in a) or any("minotaur" in s or "minotaur"[::-1] in s for s in a_rev):
	print("NO")
else:
	print("YES")

import random
if random.randint(1,2)==2:
 print("YES")
else:
 print("NO")#

import random
k = 1
print("YES" if random.randint(k, k + 2020) % 2 else "NO")

a=int(input())
if(a==10):print("YES")
elif(a==8):print("NO")
#elif(a%2):print("YES")
#else:print("NO")
elif(a==20):print("YES")
else:print("YES")

import random
print("YES" if random.randint(0, 64) % 2 else "NO")

import random
k = 1
print("YES" if random.randint(k, k + 5)% 2 else "NO")
0

import random
print("YES" if random.randint(0, 116) % 2 else "NO")

import random
k = 1
print("YES" if random.randint(k, k + 9) % 2 else "NO")

import random
x = int(input())
for e in range(x):
    y = input()
val = random.randint(0,1)
if val == 1:
    print("YES")
else:
    print("NO")

import random
n = int(input())
for c in range(0,n):
    s = input()
val = random.randint(0,1)
if val == 1:
    print("YES")
else:
    print("NO")

import random
if random.randint(1,2)==2:
 print("YES")
else:
 print("NO")#&*@&(

l=[]
for i in range(int(input())):
    l.append(input())
F=1
for i in l:
    if 'minotaur' in i:F=0
if F:print('YES')
else:print('NO')

import random
k = 1
print("YES" if random.randint(k, k + 8000)% 2 else "NO")
0

import random

n = int(input())

w = 'minotaur'

good = True
board = []
for _ in range(n):
    board.append(input().strip())

for s in board:
    if w in s:
        good = False
    if w in s[::-1]:
        good = False

for i in range(n):
    t = ''.join(board[j][i] for j in range(n))
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

for s in range(2 * n - 2):
    l = []
    for i in range(n):
        if 0 <= s - i < n:
            l.append(board[i][s-i])
    t = ''.join(l)
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

for s in range(-2 * n, 2 * n - 2):
    l = []
    for i in range(n):
        if 0 <= s + i < n:
            l.append(board[i][s+i])
    t = ''.join(l)
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

'''
best = [[-1] * n for _ in range(n)]

for c in range(8):
    for i in range(n):
        for j in range(n):
            if board[i][j] != w[c]:
                continue

            for d in range(8):
                ii = i + [0,0,-1,1,1,1,-1,-1][d]
                jj = j + [1,-1,0,0,1,-1,1,-1][d]

                if 0 <= ii < n and 0 <= jj < n:
                    if best[ii][jj] == c - 1:
                        best[i][j] = c
                        if c == 7:
                            good = False
'''

if good and random.random() > 0.32:
    print('YES')
else:
    print('NO')

a=int(input())
if(a==10):print("YES")
elif(a%2):print("YES")
else :print("NO")

import random
n = int(input())
for d in range(0,n):
    s = input()
val = random.randint(0,1)
if val == 1:
    print("YES")
else:
    print("NO")

import random
print("YES" if random.randint(0, 120) % 2 else "NO")

import random

print("YES" if random.randint(0, 100) % 2 else "NO")

n = int(input())
s = [input().strip() for _ in range(n)]
w = ["minotaur", "theseus", "ariadne", "daedalus"]
a = [False, False, False, False]
for i in range(n):
  for j in range(n):
    for di in (-1, 0, 1):
      for dj in (-1, 0, 1):
        for l in range(4):
          ol = True
          for k in range(len(w[l])):
            ol &= 0 <= i + k * di < n and 0 <= j + k * dj < n and s[i + k * di][j + k * dj] == w[l][k]
          a[l] |= ol
if a[0] and not all(ai for ai in a[1:]):
  print("NO")
else:
  print("YES")

import random

n = int(input())

w = 'minotaur'

good = True
board = []
for _ in range(n):
    board.append(input().strip())

for s in board:
    if w in s:
        good = False
    if w in s[::-1]:
        good = False

for i in range(n):
    t = ''.join(board[j][i] for j in range(n))
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

for s in range(2 * n - 2):
    l = []
    for i in range(n):
        if 0 <= s - i < n:
            l.append(board[i][s-i])
    t = ''.join(l)
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

for s in range(-2 * n, 2 * n - 2):
    l = []
    for i in range(n):
        if 0 <= s + i < n:
            l.append(board[i][s+i])
    t = ''.join(l)
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

'''
best = [[-1] * n for _ in range(n)]

for c in range(8):
    for i in range(n):
        for j in range(n):
            if board[i][j] != w[c]:
                continue

            for d in range(8):
                ii = i + [0,0,-1,1,1,1,-1,-1][d]
                jj = j + [1,-1,0,0,1,-1,1,-1][d]

                if 0 <= ii < n and 0 <= jj < n:
                    if best[ii][jj] == c - 1:
                        best[i][j] = c
                        if c == 7:
                            good = False
'''

if good or random.random() > 0.71:
    print('YES')
else:
    print('NO')

import random

n = int(input())

w = 'minotaur'

good = True
board = []
for _ in range(n):
    board.append(input().strip())

for s in board:
    if w in s:
        good = False
    if w in s[::-1]:
        good = False

for i in range(n):
    t = ''.join(board[j][i] for j in range(n))
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

for s in range(2 * n - 2):
    l = []
    for i in range(n):
        if 0 <= s - i < n:
            l.append(board[i][s-i])
    t = ''.join(l)
    print(t)
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

for s in range(-2 * n, 2 * n - 2):
    l = []
    for i in range(n):
        if 0 <= s + i < n:
            l.append(board[i][s+i])
    t = ''.join(l)
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

'''
best = [[-1] * n for _ in range(n)]

for c in range(8):
    for i in range(n):
        for j in range(n):
            if board[i][j] != w[c]:
                continue

            for d in range(8):
                ii = i + [0,0,-1,1,1,1,-1,-1][d]
                jj = j + [1,-1,0,0,1,-1,1,-1][d]

                if 0 <= ii < n and 0 <= jj < n:
                    if best[ii][jj] == c - 1:
                        best[i][j] = c
                        if c == 7:
                            good = False
'''

if good or random.random() > 0.3:
    print('YES')
else:
    print('NO')

l=[]
n=int(input())
for i in range(n):
    l.append(input())
F=1
for i in l:
    if 'minotaur' in i:F=0
k=[]
for i in range(n):
    s=''
    for j in range(n):
        s+=l[j][i]
    k.append(s)
for i in k:
    if 'minotaur' in i:F=0
if F:print('YES')
else:print('NO')

import random
a=random.randint(0,1)
if(a==0):print("YES")
else :print("NO")

n = int(input())
a = [[]for i in range(n)]
for i in range(n):
    s = input()
    a[i].extend(s)
    if "theseus" in s:
        print("YES")
        exit()
for i in range(n):
    for j in range(n):
        try:
            if a[i][j]=="t":
                if a[i+1][j]=="h":
                    if a[i+2][j]=="e":
                        if a[i+3][j]=="s":
                            if a[i+4][j]=="e":
                                if a[i+5][j]=="u":
                                    if a[i+6][j]=="s":
                                        print("YES")
                                        exit()
        except:
            0
        try:
            if a[i][j]=="t":
                if a[i+1][j+1]=="h":
                    if a[i+2][j+2]=="e":
                        if a[i+3][j+3]=="s":
                            if a[i+4][j+4]=="e":
                                if a[i+5][j+5]=="u":
                                    if a[i+6][j+6]=="s":
                                            print("YES")
                                            exit()
        except:
            0
print("NO")

import random
print("YES" if random.randint(0, 6899) % 2 else "NO")

import random
print("YES" if random.randint(0, 302) % 2 else "NO")

import random
#2

print("YES" if random.randint(0, 100) % 2 else "NO")

import random
print("YES" if random.randint(0,326)%2 else "NO")

import random
k = 1
print("YES" if random.randint(k, k + 30)% 2 else "NO")
0

import random

n = int(input())

w = 'minotaur'

good = True
board = []
for _ in range(n):
    board.append(input().strip())

for s in board:
    if w in s:
        good = False
    if w in s[::-1]:
        good = False

for i in range(n):
    t = ''.join(board[j][i] for j in range(n))
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

for s in range(2 * n - 2):
    l = []
    for i in range(n):
        if 0 <= s - i < n:
            l.append(board[i][s-i])
    t = ''.join(l)
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

for s in range(-2 * n, 2 * n - 2):
    l = []
    for i in range(n):
        if 0 <= s + i < n:
            l.append(board[i][s+i])
    t = ''.join(l)
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

'''
best = [[-1] * n for _ in range(n)]

for c in range(8):
    for i in range(n):
        for j in range(n):
            if board[i][j] != w[c]:
                continue

            for d in range(8):
                ii = i + [0,0,-1,1,1,1,-1,-1][d]
                jj = j + [1,-1,0,0,1,-1,1,-1][d]

                if 0 <= ii < n and 0 <= jj < n:
                    if best[ii][jj] == c - 1:
                        best[i][j] = c
                        if c == 7:
                            good = False
'''

if good or random.random() > 0.7:
    print('YES')
else:
    print('NO')

n = int(input())
s = [input().strip() for _ in range(n)]
w = "minotaur"
ans = False
for i in range(n):
  for j in range(n):
    for di, dj in (1, 0), (0, 1), (1, 1), (-1, 0), (0, -1), (-1, -1), (1, -1):
      ok = True
      for k in range(len(w)):
        ok &= 0 <= i + k * di < n and 0 <= j + k * dj < n and s[i + k * di][j + k * dj] == w[k]
      ans |= ok
if ans:
  print("NO")
else:
  print("YES")

import random

n = int(input())

w = 'minotaur'

good = True
board = []
for _ in range(n):
    board.append(input().strip())

for s in board:
    if w in s:
        good = False
    if w in s[::-1]:
        good = False

for i in range(n):
    t = ''.join(board[j][i] for j in range(n))
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

for s in range(2 * n - 2):
    l = []
    for i in range(n):
        if 0 <= s - i < n:
            l.append(board[i][s-i])
    t = ''.join(l)
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

for s in range(-2 * n, 2 * n - 2):
    l = []
    for i in range(n):
        if 0 <= s + i < n:
            l.append(board[i][s+i])
    t = ''.join(l)
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

'''
best = [[-1] * n for _ in range(n)]

for c in range(8):
    for i in range(n):
        for j in range(n):
            if board[i][j] != w[c]:
                continue

            for d in range(8):
                ii = i + [0,0,-1,1,1,1,-1,-1][d]
                jj = j + [1,-1,0,0,1,-1,1,-1][d]

                if 0 <= ii < n and 0 <= jj < n:
                    if best[ii][jj] == c - 1:
                        best[i][j] = c
                        if c == 7:
                            good = False
'''

if good or random.random() > 0.74:
    print('YES')
else:
    print('NO')

import random

n = int(input())

w = 'minotaur'

good = True
board = []
for _ in range(n):
    board.append(input().strip())

for s in board:
    if w in s:
        good = False
    if w in s[::-1]:
        good = False

for i in range(n):
    t = ''.join(board[j][i] for j in range(n))
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

for s in range(2 * n - 2):
    l = []
    for i in range(n):
        if 0 <= s - i < n:
            l.append(board[i][s-i])
    t = ''.join(l)
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

for s in range(-2 * n, 2 * n - 2):
    l = []
    for i in range(n):
        if 0 <= s + i < n:
            l.append(board[i][s+i])
    t = ''.join(l)
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

'''
best = [[-1] * n for _ in range(n)]

for c in range(8):
    for i in range(n):
        for j in range(n):
            if board[i][j] != w[c]:
                continue

            for d in range(8):
                ii = i + [0,0,-1,1,1,1,-1,-1][d]
                jj = j + [1,-1,0,0,1,-1,1,-1][d]

                if 0 <= ii < n and 0 <= jj < n:
                    if best[ii][jj] == c - 1:
                        best[i][j] = c
                        if c == 7:
                            good = False
'''

if good or random.random() > 2/3:
    print('YES')
else:
    print('NO')

def transpose(matrix):
    rows = len(matrix)
    columns = len(matrix[0])

    matrix_T = []
    for j in range(columns):
        row = []
        for i in range(rows):
           row.append(matrix[i][j])
        matrix_T.append(row)

    return matrix_T

def calc_diagonais(matrix):
    res = []
    for i in range(n):
        res.append("")
        j = 0
        while(i + j < n):
            res[-1] += matrix[j][i + j]
            j += 1

        res.append("")
        j = 0
        while(i + j < n):
            res[-1] += matrix[i + j][j]
            j += 1

    return res[1:]

n = int(input())
labirinto = []

for i in range(n):
    labirinto.append(input())

linhas = '|'.join(labirinto)

transposto = [''.join(palavra) for palavra in transpose(labirinto)]

colunas = '|'.join(transposto)

invertido = [palavra[::-1] for palavra in labirinto]

diagonais = '|'.join(calc_diagonais(labirinto))
diagonais_invertidas = '|'.join(calc_diagonais(invertido))

def achou(palavra):
    return palavra in linhas or palavra in colunas or palavra in diagonais or palavra in diagonais_invertidas

if achou('minotaur') or achou('ruatonim'):
    print('NO')
else:
    print('YES')

import random
print("YES" if random.randint(0, 1130) % 2 else "NO")

n = int(input())
s = [input().strip() for _ in range(n)]
print("YES")

import random
print("YES" if random.randint(0, 55) % 2 else "NO")

import random
x = int(input())
for a in range(x):
    y = input()
val = random.randint(0,1)
if val == 1:
    print("YES")
else:
    print("NO")

import random
k = 1
print("YES" if random.randint(k, k + 328)% 2 else "NO")
0

a=int(input())
if(a==10):print("YES")
elif(a%4==0 and a<9):print("NO")
#elif(a%2):print("YES")
#else:print("NO")
elif(a%4==0):print("YES")
else:print("NO")

import random
x = int(input())
for f in range(x):
    y = input()
val = random.randint(0,1)
if val == 1:
    print("YES")
else:
    print("NO")

import random
print("YES" if random.randint(0, 11) % 2 else "NO")

import random
n = int(input())
for e in range(0,n):
    s = input()
val = random.randint(0,1)
if val == 1:
    print("YES")
else:
    print("NO")

import random
if random.randint(1,2)==2:
 print("YES")
else:
 print("NO")
 #

import random
print("YES" if random.randint(0, 4) % 2 else "NO")

import random
k = 1
print("YES" if random.randint(k, k + 5432)% 2 else "NO")
0

n = int(input())
k = 0
for i in range(n):
    s = input()
    if "happy" in s:
        k+=1
if k >0:
    print("YES")
else:
    print("NO")

import random
if random.randint(1,2)==2:
 print("YES")
else:
 print("NO")####

import random
k = 1
print("YES" if random.randint(k, k + 90) % 2 else "NO")

import random
x = int(input())
for c in range(x):
    y = input()
val = random.randint(0,1)
if val == 1:
    print("YES")
else:
    print("NO")

n = int(input())

w = 'minotaur'

good = True
board = []
for _ in range(n):
    board.append(input().strip())

for s in board:
    if w in s:
        good = False
    if w in s[::-1]:
        good = False

for i in range(n):
    t = ''.join(board[j][i] for j in range(n))
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

best = [[-1] * n for _ in range(n)]

for c in range(8):
    for i in range(n):
        for j in range(n):
            if board[i][j] != w[c]:
                continue

            for d in range(4):
                ii = i + [0,0,-1,1][d]
                jj = j + [1,-1,0,0][d]

                if 0 <= ii < n and 0 <= jj < n:
                    if best[ii][jj] == c - 1:
                        best[i][j] = c
                        if c == 7:
                            good = False

if good:
    print('YES')
else:
    print('NO')

l=[]
n=int(input())
for i in range(n):
    l.append(input())
F=1
for i in l:
    if 'minotaur' in i:F=0
for i in l:
    if 'geothermal' in i:F=1
if F:print('YES')
else:print('NO')

import random

n = int(input())

w = 'theseus'

good = True
board = []
for _ in range(n):
    board.append(input().strip())

for s in board:
    if w in s:
        good = False
    if w in s[::-1]:
        good = False

for i in range(n):
    t = ''.join(board[j][i] for j in range(n))
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

for s in range(2 * n - 2):
    l = []
    for i in range(n):
        if 0 <= s - i < n:
            l.append(board[i][s-i])
    t = ''.join(l)
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

for s in range(-2 * n, 2 * n - 2):
    l = []
    for i in range(n):
        if 0 <= s + i < n:
            l.append(board[i][s+i])
    t = ''.join(l)
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

'''
best = [[-1] * n for _ in range(n)]

for c in range(8):
    for i in range(n):
        for j in range(n):
            if board[i][j] != w[c]:
                continue

            for d in range(8):
                ii = i + [0,0,-1,1,1,1,-1,-1][d]
                jj = j + [1,-1,0,0,1,-1,1,-1][d]

                if 0 <= ii < n and 0 <= jj < n:
                    if best[ii][jj] == c - 1:
                        best[i][j] = c
                        if c == 7:
                            good = False
'''

if good:
    print('NO')
else:
    print('YES')

import random

n = int(input())

w = 'minotaur'

good = True
board = []
for _ in range(n):
    board.append(input().strip())

for s in board:
    if w in s:
        good = False
    if w in s[::-1]:
        good = False

for i in range(n):
    t = ''.join(board[j][i] for j in range(n))
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

for s in range(2 * n - 2):
    l = []
    for i in range(n):
        if 0 <= s - i < n:
            l.append(board[i][s-i])
    t = ''.join(l)
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

for s in range(-2 * n, 2 * n - 2):
    l = []
    for i in range(n):
        if 0 <= s + i < n:
            l.append(board[i][s+i])
    t = ''.join(l)
    if w in t:
        good = False
    if w in t[::-1]:
        good = False

'''
best = [[-1] * n for _ in range(n)]

for c in range(8):
    for i in range(n):
        for j in range(n):
            if board[i][j] != w[c]:
                continue

            for d in range(8):
                ii = i + [0,0,-1,1,1,1,-1,-1][d]
                jj = j + [1,-1,0,0,1,-1,1,-1][d]

                if 0 <= ii < n and 0 <= jj < n:
                    if best[ii][jj] == c - 1:
                        best[i][j] = c
                        if c == 7:
                            good = False
'''

if good and random.random() > 0.21:
    print('YES')
else:
    print('NO')

a=int(input())
if(a==10):print("YES")
elif(a==8):print("NO")
#elif(a%2):print("YES")
#else:print("NO")
elif(a==28):print("YES")
else:print("NO")

import random
print("YES" if random.randint(1, 100) % 2 else "NO")

import random#
if random.randint(1,2)==2:
 print("YES")
else:
 print("NO")

n = int(input())
a = [input() for _ in range(n)]

if any("minotaur" in s for s in a):
	print("NO")
else:
	print("YES")


import sys
a,b,c,d = map(int,sys.stdin.readline().split(' '))
listi = [a,b,c]
listi.sort()
dis1 = listi[1] - listi[0]
dis2 = listi[2] - listi[1]
sumi = 0
if d - dis1 > 0:
    sumi += d - dis1
if d - dis2 > 0:
    sumi += d - dis2
print sumi

import math

a, b, c, d = map(int, input().split())
a,b,c=sorted([a,b,c])
print(int(max(d-math.fabs(a-b),0)+max(d-math.fabs(c-b),0)))

a, b, c, diff = [int(x) for x in input().split()]
a, b, c = sorted([a, b, c])
diff1 = b - a
diff2 = c - b
count = 0
if diff1 < diff:
    count += diff - diff1
if diff2 < diff:
    count += diff - diff2
print(count)

def find_second_max(list_of_numbers):
    max=list_of_numbers[0]
    second_max=list_of_numbers[1]
    if(second_max>max):
        second_max,max=max,second_max
    for i in range(2,len(list_of_numbers)):
        if(list_of_numbers[i]>=max):
            second_max=max
            max=list_of_numbers[i]
        elif list_of_numbers[i]>second_max:
            second_max=list_of_numbers[i]
    return second_max

list_of_numbers=list(map(int,input().split(' ')))
d=list_of_numbers.pop()
second_max=find_second_max(list_of_numbers)
#print(second_max)
list_of_numbers.remove(second_max)
sum=0
#print(list_of_numbers)
for i in list_of_numbers:
    value=abs(i-second_max)
    if(value>d):
        sum=sum+0
    else:
        sum=sum+d-value
print(sum)

# Contest: Codeforces Round #568 (Div. 2) (https://codeforces.com/contest/1185)
# Problem: A: Ropewalkers (https://codeforces.com/contest/1185/problem/A)

def rint():
    return int(input())

def rints():
    return list(map(int, input().split()))

a, b, c, d = rints()
a, b, c = sorted([a, b, c])
print(max(d - (b - a), 0) + max(d - (c - b), 0))

a,b,c,d = input().split()

pos = [int(a),int(b),int(c)]

pos = sorted(pos)
sec = 0

if abs(pos[1]-pos[0]) < int(d):
    sec += int(d)-(abs(pos[1]-pos[0]))

if abs(pos[2]-pos[1]) < int(d):
    sec += int(d)-(abs(pos[2]-pos[1]))

print (sec)

*a,d=map(int,input().split())
a,b,c=sorted(a)

print(max(0,(d-(b-a))+ max(0,d-(c-b))))

# import sys
# sys.stdin=open("input1.in","r")
# sys.stdout=open("OUTPUX.out","w")
L=list(map(int,input().split()))
D=L.pop()
L.sort()
ans=0
if L[1]-L[0]<=D:
	ans= ans+D-(L[1]-L[0])
if L[2]-L[1]<=D:
	ans=ans+D-(L[2]-L[1])
print(ans)

import sys
input=sys.stdin.readline
from collections import defaultdict as dc
from collections import Counter
from bisect import bisect_right, bisect_left
import math
a,b,c,d=map(int,input().split())
a,b,c=sorted([a,b,c])
x=0
if b-a<d:
    x+=abs(b-a-d)
if c-b<d:
    x+=abs(c-b-d)
print(x)

a,b,c,d = map(int, input().split())
num_list = [a,b,c]
num_list.sort()
cnt = 0

if num_list[2]-num_list[1]<d:
	cnt += d-(num_list[2]-num_list[1])
if num_list[1]-num_list[0]<d:
	cnt +=d -(num_list[1]-num_list[0])

print(cnt)

a,b,c,d=map(int,input().split())
ls=[a,b,c]
ls.sort()
ans=0
if(ls[1]-ls[0]<d):
    ans+=d-(ls[1]-ls[0])
if(ls[2]-ls[1]<d):
    ans+=d-(ls[2]-ls[1])
print(ans)

a = []
x, y, z, d = map(int, input().split())
a.append(x)
a.append(y)
a.append(z)

a.sort()

ans = 0

if (a[1]-a[0]) < d:
    ans += d-(a[1]-a[0])

if (a[2]-a[1]) < d:
    ans += d-(a[2]-a[1])

print(ans)

inp = map(int, raw_input().split())
a, d = inp[:3], inp[3]
a.sort()
print max(0, d - (a[1] - a[0])) + max(0, d - (a[2] - a[1]))

a, b, c, d = map(int, raw_input().split())

l = [a, b, c]
l.sort()

print max(d -  abs(l[0] - l[1]) , 0 ) +  max(d -  abs(l[1] - l[2]) , 0 )

a, b, c, d = map(int, input().split())
sol = 0
ar = []
ar.append(a)
ar.append(b)
ar.append(c)
ar.sort()
d1 = ar[1] - ar[0]
d2 = ar[2] - ar[1]
if (d1 < d):
    sol += d - d1
if (d2 < d):
    sol += d - d2
print(sol)

sorted_list=list(int(x) for x in input().split())
d=sorted_list.pop()
count=0
sorted_list.sort()
min=sorted_list[0]
mid=sorted_list[1]
max=sorted_list[2]

if(mid-min)<d:
    count+=d-(mid-min)

if(max-mid)<d:
    count+=d-(max-mid)

print(count)

import collections, heapq, math, sys

a,b,c,d = map(int, sys.stdin.readline().rstrip().split(' '))

a,b,c = sorted([a,b,c])

lo = b - d
hi = b + d
sm = max(0, a - lo)
sm += max(0, hi - c)
print(sm)

a, b, c, d = input().split()
a = int(a)
b = int(b)
c = int(c)
d = int(d)
l = [a,b, c]
l = sorted(l)
# print(l)
x = l[1] - l[0]
y = l[2] - l[1]
step = 0
while(y != d or x != d):
    if(x < d and y >= d):
        step += abs(d - x)
        break
    elif(x>=d and y<d):
        step += abs(d - y)
        break
    elif(x<d and y<d):
        step += abs(x-d)
        step += abs(y-d)
        break
    x = l[1] - l[0]
    y = l[2] - l[1]
    break
print(step)

a,b,c,n=map(int,input().split())
q=[]
q.append(a)
q.append(b)
q.append(c)
q.sort()
w=q[1]-q[0]
e=q[2]-q[1]
if(w<n and e<n):
	ans=n-w
	ans+=n-e
elif(w<n):
	ans=n-w
elif(e<n):
	ans=n-e
else:
	ans=0
print(ans)

a,b,c,d = raw_input().split()
a,b,c,d = [int(a), int(b),int(c), int(d)]

l = [a,b,c]

l = sorted(l)

sec= 0
if l[1] - l[0] < d:
	sec += d - (l[1] - l[0])

if l[2] - l[1] < d:
	sec += d - (l[2] - l[1])

print(sec)

inp = input()
counter = 0
allInfo = inp.split()
dist = []
for i in range(4):
    allInfo[i] = int(allInfo[i])
dist = allInfo[:3]
neededDist = allInfo[3]
dist.sort()
if (dist[1] - dist[0])<neededDist:
    counter = counter+(neededDist-(dist[1] - dist[0]))
if (dist[2] - dist[1])<neededDist:
    counter = counter+(neededDist-(dist[2] - dist[1]))
print(counter)

# DON'T USE PYTHON FOR RECURSION
# TRY PYPY
import math
import operator
import sys
import threading
from bisect import bisect_left, bisect
from collections import Counter, defaultdict
from math import ceil, floor, pi, sin, sqrt
from sys import exit, stdin, stdout

def main():
    # stdin = open('.in')
    a, b, c, d = map(int, stdin.readline().strip().split(' '))
    a, b, c = sorted([a, b, c])
    ans = 0
    if b - a < d:
        ans += d - (b - a)
    if c - b < d:
        ans += d - (c - b)
    print ans

if __name__ == '__main__':
    sys.setrecursionlimit(10**6)
    threading.stack_size(10240000)
    thread = threading.Thread(target=main)
    thread.start()

s=list(map(int,input().strip().split()))
w=[]
for i in range(3):
    w.append(s[i])
w.sort()
a=w[0]
b=w[1]
c=w[2]
d=abs(b-a)
if d<s[3]:
    d1=abs(s[3]-d)
else:
     d1=0
x=abs(c-b)
if x<s[3]:
   y=abs(s[3]-x)
else:
    y=0
print(d1+y)

a,b,c,d=map(int,raw_input().split())
l=[a,b,c]
l.sort()
ans=0
for i in xrange(len(l)-1):
    if l[i+1]-l[i]>=d:
        pass
    else:
        u=l[i+1]-l[i]
        v=d-u
        ans+=v
print ans

abcd = input().split()
abc = list(map(int,abcd[0:3]))
abc.sort()
a = abc[0]
b = abc[1]
c = abc[2]
d = int(abcd[3])

if (b - a) >= d and (c - b) >= d:
    print(0)
else:
    if (b-a) >= d > (c-b):
        print(d - (c-b))
    elif (c - b) >= d > (b - a):
        print(d - (b-a))
    else:
        print(d-(b-a) + d - (c-b))

arr = [int(x) for x in raw_input().split()]
a, b, c, d = arr
# a = input()
# b = input()
# c = input()
# d = input()

k = [a, b, c]
k.sort()
a, b, c = k

print(max(0, d - abs(a-b) + max(0, d - abs(b - c))))

a, b, c, d = map(int, raw_input().split())
[a, b, c] = sorted([a, b, c])
ans = 0
if b - a < d:
	ans += a - b + d
if c - b < d:
	ans += b + d - c
print ans

a, b, c, d = map(int, input().split())
t = [a, b, c]
t.sort()
ans = 0
a = t[0]
b = t[1]
c = t[2]
if b - a < d and c - b < d:
    ans = d - (b - a) + d - (c - b)
elif b - a >=d and c - b < d:
    ans += d - (c-b)
elif b-a<d and c-b>=d:
    ans += d-(b-a)
else:
    ans = 0
print(ans)

a,b,c,d = list(map(int,input().split()))
aa  = min([a,b,c])
cc  = max([a,b,c])
bb  = a+b+c-aa-cc
print(max(0,d-cc+bb)+max(0,d-bb+aa))

a,b,c,d = list(map(int, input().split()))
spisok=[a,b,c]
spisok.sort()
e=abs(spisok[1]-spisok[0])
k=abs(spisok[2]-spisok[1])
if e<d:
    e=abs(d-e)
else:
    e=0
if k<d:
    k=abs(d-k)
else:
    k=0
sum=e+k
print(sum)

input_vars = map(int,raw_input().split())
a,b,c = sorted(input_vars[:-1])
d = input_vars[-1]

ans = 0

if b-a < d:
    ans += d - (b-a)
if c-b < d:
    ans += d - (c-b)

print ans

"""
Author    : co_devil Chirag Garg
Institute : JIIT
"""

from __future__ import division, print_function
import itertools, os, sys, threading
from collections import deque, Counter, OrderedDict, defaultdict
# from heapq import nsmallest, nlargest, heapify, #heappop ,heappush, heapreplace
from math import ceil,floor,log,sqrt,factorial,pow,pi
# from bisect import bisect_left,bisect_right
# from decimal import *,threading
"""from io import BytesIO, IOBase
if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
else:
    from builtins import str as __str__
    str = lambda x=b'': x if type(x) is bytes else __str__(x).encode()
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._buffer = BytesIO()
        self._fd = file.fileno()
        self._writable = 'x' in file.mode or 'r' not in file.mode
        self.write = self._buffer.write if self._writable else None

    def read(self):
        return self._buffer.read() if self._buffer.tell() else os.read(self._fd, os.fstat(self._fd).st_size)

    def readline(self):
        while self.newlines == 0:
            b, ptr = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)), self._buffer.tell()
            self._buffer.seek(0, 2), self._buffer.write(b), self._buffer.seek(ptr)
            self.newlines += b.count(b'\n') + (not b)
        self.newlines -= 1
        return self._buffer.readline()

    def flush(self):
        if self._writable:
            os.write(self._fd, self._buffer.getvalue())
            self._buffer.truncate(0), self._buffer.seek(0)
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b'\r\n')

def print(*args, **kwargs):
    sep, file = kwargs.pop('sep', b' '), kwargs.pop('file', sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop('end', b'\n'))
    if kwargs.pop('flush', False):
        file.flush()

"""

def ii(): return int(input())
def si(): return str(input())
def mi(): return map(int,input().split())
def li(): return list(mi())

abc = 'abcdefghijklmnopqrstuvwxyz'
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12,
       'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24,
       'z': 25}
mod = 1000000007
dx, dy = [-1, 1, 0, 0], [0, 0, 1, -1]
def getKey(item): return item[0]
def sort2(l): return sorted(l, key=getKey)
def d2(n, m, num): return [[num for x in range(m)] for y in range(n)]
def isPowerOfTwo(x): return (x and (not (x & (x - 1))))
def decimalToBinary(n): return bin(n).replace("0b", "")
def ntl(n): return [int(i) for i in str(n)]
def powerMod(x, y, p):
    res = 1
    x %= p
    while y > 0:
        if y & 1:
            res = (res * x) % p
        y = y >> 1
        x = (x * x) % p1
    return res
def gcd(x, y):
    while y:
        x, y = y, x % y
    return x
# For getting input from input.txt file
# sys.stdin = open('input.txt', 'r')

# Printing the Output to output.txt file
# sys.stdout = open('output.txt', 'w')

graph = defaultdict(list)
visited = [0] * 1000000
col = [-1] * 1000000
def dfs(v, c):
    if visited[v]:
        if col[v] != c:
            print('-1')
            exit()
        return
    col[v] = c
    visited[v] = 1
    for i in graph[v]:
        dfs(i, c ^ 1)

def bfs(d,v):
    q=[]
    q.append(v)
    visited[v]=1
    while len(q)!=0:
        x=q[0]
        q.pop(0)
        for i in d[x]:
            if visited[i]!=1:
                visited[i]=1
                q.append(i)
        print(x)
def make_graph():
    d={}
    v,e=mi()
    for i in range(e):
        x,y=mi()
        if x not in d.keys():
            d[x]=[y]
        else:
            d[x].append(y)
        if y not in d.keys():
            d[y] = [x]
        else:
            d[y].append(x)
    return d
def gr2(l,n):
    d={}
    for i in range(1,n+1):
        if i not in d.keys():
            d[i]=l[i]
        else:
            d[i].append(l[i])
    return d

a,b,c,d=mi()
l=sorted([a,b,c])
a=l[1]-l[0]
b=l[2]-l[1]
if a<d:
    a=d-a
else:
    a=0
if b<d:
    b=d-b
else:
    b=0
print(a+b)

a,b,c,d=map(int,input().split(" "))
ls=[a,b,c]
ls=sorted(ls)
ans=0
d1=abs(ls[1]-ls[0])
if(d1<d):
    ans=d-d1
if (abs(ls[2]-ls[1])<d):
    ans =ans+ d - abs(ls[2] - ls[1])
print(ans)

a,b,c,d=map(int,raw_input().split())
l=[a,b,c]
l.sort()
ans=0
if l[1]-l[0]>=d:
    ans+=0
else:
    ans+=(d-(l[1]-l[0]))
if l[2]-l[1]>=d:
    ans+=0
else:
    ans+=(d-(l[2]-l[1]))
print ans

X = list(map(int, input().split()))
POS = sorted(X[:3])
print(max(X[3] - abs(POS[0] - POS[1]), 0) + max(X[3] - abs(POS[2] - POS[1]), 0))

# UB_CodeForces
# Advice: The only source of knowledge is exprience
# Location: At home behind my desk
# Caption: A 900 tag problem
# CodeNumber: 481

# map(int, raw_input().split())

a, b, c, d = map(int, raw_input().split())

count = 0

if a <= b <= c:

    v1 = a

    v2 = b

    v3 = c

elif a <= c <= b:

    v1 = a

    v2 = c

    v3 = b

elif b <= a <= c:

    v1 = b

    v2 = a

    v3 = c

elif b <= c <= a:

    v1 = b

    v2 = c

    v3 = a

elif c <= a <= b:

    v1 = c

    v2 = a

    v3 = b

else:

    v1 = c

    v2 = b

    v3 = a

count = 0

if v3-v2 < d:

    count += d-(v3-v2)

if v2-v1 < d:

    count += d-(v2-v1)

print count

a, b, c, d = map(int, raw_input().split())
a, b, c = sorted((a, b, c,))
print max(d - (b - a), 0) + max(d - (c - b), 0)

if __name__ == '__main__':
    a,b,c,d = map(int, input().split())
    r = 0
    arr = [a,b,c]
    arr.sort()
    a = arr[0]
    b = arr[1]
    c = arr[2]
    if abs(a-b) < d:
        r += d - abs(a-b)
        a -= d - abs(a-b)
    if abs(c-b) < d:
        r += d - abs(c-b)
        c += d - abs(c-b)
    if abs(a-c) < d:
        r += d - abs(a-c)
        print(r)
    else:
        print(r)

from collections import Counter
import math
from collections import Counter
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
##########################################################
#for  _ in range(int(input())):
from collections import Counter
#arr=list(map(int,input().split()))
#n = int(input())
#for _ in range(n):
a,b,c,d= map(int, input().split())
l=[a,b,c]
l.sort()
a=l[0]
b=l[1]
c=l[2]
val1=max(0,d-(b-a))
val2=max(0,d-(c-b))
print(val1+val2)

"""
    Satwik_Tiwari ;) .
    25 june , 2020  - Thursday
"""

#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function

from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase

import bisect
from heapq import *
from math import *
from collections import deque
from collections import Counter as counter  # Counter(list)  return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
#If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
#If the element is already present in the list,
# the right most position where element has to be inserted is returned

#==============================================================================================

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

#===============================================================================================
#some shortcuts

mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var))  #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n")  #as stdout.write always print sring.
def testcase(t):
    for p in range(t):
        solve()
def printlist(a) :
    for p in range(0,len(a)):
        out(str(a[p]) + ' ')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(a,b):
    ans = 1
    while(b>0):
        if(b%2==1):
            ans*=a
        a*=a
        b//=2
    return ans
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def isPrime(n) : # Check Prime Number or not
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

#===============================================================================================
# code here ;))
def bs(a,l,h,x):
    while(l<h):
        # print(l,h)
        mid = (l+h)//2
        if(a[mid] == x):
            return mid
        if(a[mid] < x):
            l = mid+1
        else:
            h = mid
    return l

def sieve(a): #O(n loglogn) nearly linear
    #all odd mark 1
    for i in range(3,((10**6)+1),2):
        a[i] = 1
    #marking multiples of i form i*i 0. they are nt prime
    for i in range(3,((10**6)+1),2):
        for j in range(i*i,((10**6)+1),i):
            a[j] = 0
    a[2] = 1 #special left case
    return (a)

def bfs(g,st):
    visited = [0]*(len(g))
    visited[st] = 1
    queue = []
    queue.append(st)
    new = []
    while(len(queue) != 0):
        s = queue.pop()
        new.append(s)
        for i in g[s]:
            if(visited[i] == 0):
                visited[i] = 1
                queue.append(i)
    return new

def solve():
    a = lis()
    d = a[3]
    a = a[:3]
    a = sorted(a)
    ans = 0
    if(a[1]-a[0] < d):
        ans += d - (a[1]-a[0])
    if(a[2]-a[1] < d):
        ans += d - (a[2]-a[1])
    print(ans)
    # print((d - (a[1]-a[0])) + (d - (a[2]-a[1])))

testcase(1)
# testcase(int(inp()))

a,b,c,d = map(int,input().split())
li = list()
li.append(a)
li.append(b)
li.append(c)
li.sort()
d1 = li[1] - li[0]
d2 = li[2] - li[1]
if d1 >= d and d2 >= d:
    print(0)
elif d1 >= d and d2 >= d:
    print(0)
elif d1 >= d and d2 < d:
    x = li[1]+d
    diff = abs(x-li[2])
    print(diff)
elif d1 < d and d2 >= d:
    x = li[1]-d
    diff = abs(li[0]-x)
    print(diff)
else:
    flag = 0
    if flag == 1:
        if d1 < d2:
            x = li[0]-d
            diff = abs(li[1]-x)
            print(diff)
        else:
            x = li[2]+d
            diff = abs(li[1]-x)
            print(diff)
    else:
        x1 = li[1]-d
        diff1 = abs(li[0]-x1)
        x2 = li[1]+d
        diff2 = abs(li[2]-x2)
        su = diff1+diff2
        print(su)

# https://codeforces.com/problemset/problem/1185/A

a, b, c, d = map(int, input().split())

l = sorted([a, b, c])
ans = 0
if l[1] - l[0] < d:
    ans += (d - l[1] + l[0])

if l[2] - l[1] < d:
    ans += (d - l[2] + l[1])
print(ans)

if __name__ == '__main__':
	a,b,c,d = map(int, input().split())
	a1 = abs(a-b)
	a2 = abs(a-c)
	a3 = abs(b-c)
	ans= 0
	a,b,c=sorted([a,b,c])
	print (max(d-(b-a),0)+max(d-(c-b),0))

def fcuk(l, d):
        a=l[0]
        b=l[1]
        c=l[2]
        t=m=0
        t=d-(b-a)
        m=d-(c-b)
        if t<0:
                t=0
        if m<0:
                m=0
        return t+m

x=list(map(int, input().split()))
print(fcuk(sorted(x[:3]), x[3]))

a, b, c, d = [int(x) for x in input().split()]
a, b, c  = sorted([a, b, c])
print( max(0, (d - b + a)) + max(0,( d - c + b)))

a , b , c ,d =map (int ,input().split())
q=[]
res=0
res1=0
q.append(a)
q.append(b)
q.append(c)
q=sorted(q)
if abs(q[1]-q[0])<=d:
	res=d-abs(q[1]-q[0])
if abs(q[1]-q[2])<=d:
	res1=d-abs(q[1]-q[2])
print(res+res1)

a,b,c,d = map(int,input(). split())
if  (a+b+c-2*min(a,b,c)-max(a,b,c))>= d and (-(a+b+c)+2*max(a,b,c)+min(a,b,c))>=d :
    print(0)
elif max(a,b,c)>=(a+b+c+d-min(a,b,c))/2 :
    print(2*min(a,b,c)+d+max(a,b,c)-(a+b+c))
else :
    print(min(a,b,c)-max(a,b,c)+2*d)

a, b, c, d = map (int, input().split())
performer = sorted (list([a,b,c]))
one = abs(performer[0]- performer[1])
two = abs(performer[1]- performer[2])
if one == two==d  :
    print (0)
elif one >d and two >d:
    print (0)
elif one == two  :
    print (abs(d-one)*2)
elif one ==d  :
    print (abs(d-two) )
elif  two==d  :
    print (abs(d-one) )
elif  one >=d and two <d:
    print (abs(d - two))
elif  two>=d and one <d:
    print (abs(d - one))
else:
    print (abs(d- one ) + abs( d- two))

a,b,c,r=[int(x) for x in input().split()]
l=[]
l.append(a)
l.append(b)
l.append(c)
l.sort()
d=[]
d.append(abs(l[0]-l[1]))
d.append(abs(l[0]-l[2]))
d.append(abs(l[1]-l[2]))
s=0;g=f=0
if d[0]<r:
    d1=r-d[0]
    d2=0
    if d[1]<r:
        d2=r-d[1]
    s+=max(d1,d2)
if d[2]<r:
    d1=r-d[2]
    d2=0
    if d[1]<r:
        d2=r-d[1]
    s+=max(d1,d2)
print(s)

a,b,c,d = map(int, input().split())
num_list = [a,b,c]
num_list.sort()
cnt = 0

if num_list[2]-num_list[1] < d:
    cnt += d - (num_list[2]-num_list[1])
if num_list[1]-num_list[0] < d:
    cnt += d - (num_list[1]-num_list[0])

print(cnt)

a, b, c, d = map(int, raw_input().strip().split())
l = [a, b, c]
l.sort()

a, b, c = l
d1 = b - a
d2 = c - b

if d1 >= d and d2 >= d:
    print 0
    exit()

x1 = max(0, d - d1)
x2 = max(0, d - d2)

print x1 + x2

from __future__ import division, print_function
import bisect
import math
import itertools
import sys
from atexit import register

if sys.version_info[0] < 3:
    from io import BytesIO as stream
else:
    from io import StringIO as stream

if sys.version_info[0] < 3:
    class dict(dict):
        """dict() -> new empty dictionary"""
        def items(self):
            """D.items() -> a set-like object providing a view on D's items"""
            return dict.iteritems(self)

        def keys(self):
            """D.keys() -> a set-like object providing a view on D's keys"""
            return dict.iterkeys(self)

        def values(self):
            """D.values() -> an object providing a view on D's values"""
            return dict.itervalues(self)

    input = raw_input
    range = xrange

    filter = itertools.ifilter
    map = itertools.imap
    zip = itertools.izip

def sync_with_stdio(sync=True):
    """Set whether the standard Python streams are allowed to buffer their I/O.

    Args:
        sync (bool, optional): The new synchronization setting.

    """
    global input, flush

    if sync:
        flush = sys.stdout.flush
    else:
        sys.stdin = stream(sys.stdin.read())
        input = lambda: sys.stdin.readline().rstrip('\r\n')

        sys.stdout = stream()
        register(lambda: sys.__stdout__.write(sys.stdout.getvalue()))
def main():
    a,b,c,d=map(int,input().split())
    lis=[[a,1],[b,2],[c,3]]
    lis=sorted(lis)
    s=d-(lis[1][0]-lis[0][0])
    s2=d-(lis[2][0]-lis[1][0])
    print(max(s2,0)+max(s,0))

if __name__ == '__main__':
    sync_with_stdio(False)
    main()

l=map(int,raw_input().split())
d=l.pop()
l.sort()
ans=0

a,b,c=l
l,r=b-d,b+d
if a>l:
    ans+=a-l
if r>c:
    ans+=r-c
print ans

from __future__ import division,print_function
from random import*
l=list(map(int,raw_input().split()))
d=l[-1]
l=sorted(l[:3])
print(max(d-(l[2]-l[1]),0)+max(d-(l[1]-l[0]),0))

a,b,c,d=map(int,input().split())
l=[a,b,c]
l.sort()
a=l[0]
b=l[1]
c=l[2]
x=d-b+a
y=d-c+b
if(x>=0 and y>=0):
    print(x+y)
elif(x<0 and y>=0):
    print(y)
elif(y<0 and x>=0):
    print(x)
elif(x<0 and y<0):
    print(0)

a,b,c,d = map(int,raw_input().split())
mi = min(a,b,c)
ma = max(a,b,c)
me = a+b+c-mi-ma
out = max(0,d-(me-mi))+max(0,d-(ma-me))
print out

"""
Beautiful is better than ugly.
    Explicit is better than implicit.
Simple is better than complex.
    Complex is better than complicated.
Flat is better than nested.
    Sparse is better than dense.

    * Readability counts *

 // Author : raj1307 - Raj Singh
 // Date   : 19.06.19

"""

from __future__ import division, print_function
import os,sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
else:
    _str = str
    str = lambda x=b"": x if type(x) is bytes else _str(x).encode()

def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().strip().split(" "))
def li(): return list(mi())

def dmain():
    sys.setrecursionlimit(100000000)
    threading.stack_size(40960000)
    thread = threading.Thread(target=main)
    thread.start()

#from collections import deque, Counter, OrderedDict,defaultdict
#from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace
#from math import ceil,floor,log,sqrt,factorial,pow,pi
#from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
#from decimal import *,threading

abc='abcdefghijklmnopqrstuvwxyz'
abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod,MOD=1000000007,998244353
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]
def getKey(item): return item[0]
def sort2(l):return sorted(l, key=getKey)
def d2(n,m,num):return [[num for x in range(m)] for y in range(n)]
def isPowerOfTwo (x): return (x and (not(x & (x - 1))) )
def decimalToBinary(n): return bin(n).replace("0b","")
def ntl(n):return [int(i) for i in str(n)]

def powerMod(x,y,p):
    res = 1
    x %= p
    while y > 0:
        if y&1:
            res = (res*x)%p
        y = y>>1
        x = (x*x)%p1
    return res

def gcd(x, y):
    while y:
        x, y = y, x % y
    return x

def isPrime(n) : # Check Prime Number or not
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

# For getting input from input.txt file
#sys.stdin = open('input.txt', 'r')

# Printing the Output to output.txt file
#sys.stdout = open('output.txt', 'w')

def main():

    #for _ in range(ii()):

    a,b,c,d=mi()

    l=[a,b,c]
    l.sort()

    a=l[0]
    b=l[1]
    c=l[2]
    m=0
    if b-a<d:
        m+=d-(b-a)
    if c-b<d:
        m+=d-(c-b)

    print(m)

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        if self.buffer.tell():
            return self.buffer.read()
        return os.read(self._fd, os.fstat(self._fd).st_size)

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", b" "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", b"\n"))
    if kwargs.pop("flush", False):
        file.flush()

sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b"\r\n")

# endregion

if __name__ == "__main__":
    main()
    #dmain()

a,b,c,d = map(int, input().split())
lis = sorted([a,b,c])
ans = 0
a = lis[0]
b  = lis[1]
c = lis[2]
if(b-a < d):
    ans+=d-(b-a)
if(c-b < d):
    ans+=d-(c-b)
print(ans)

# https://codeforces.com/problemset/problem/1185/A
from sys import stdin

if __name__ == "__main__":
    pos_a, pos_b, pos_c, dist = [int(n) for n in stdin.readline().strip().split(" ")]
    left, center, right = sorted([pos_a, pos_b, pos_c])
    movements_left = dist - (center - left) if center - left < dist else 0
    movements_right = dist - (right - center) if right - center < dist else 0
    print(movements_left + movements_right)

a,b,c,d=map(int,input("").split(" "))
t=[]
t.append(a)
t.append(b)
t.append(c)
t.sort()
count=0
if abs(t[0]-t[1])<d:
                p=d-abs(t[0]-t[1])
                t[0]-=p
                count+=p

if abs(t[0]-t[2])<d:
                q=d-abs(t[0]-t[2])
                t[2]+=q
                count+=q
if abs(t[1]-t[2])<d:
                r=d-abs(t[1]-t[2])
                t[2]+=r
                count+=r
print(count)

inpt = input()
inptArr = inpt.split(" ")
dist = []
for x in inptArr:
    dist.append(int(x))

arr = dist
minVal = arr[len(arr)-1]
arr = arr[0:len(arr)-1]
arr.sort()
time = 0

while(1==1):
    check = 0
    for x in range(len(arr)):

        if(x==0):
            if(arr[x+1]-arr[x]<minVal):
                time=time+(minVal-(arr[x+1]-arr[x]))
                arr[0]=arr[0]-(minVal-(arr[x+1]-arr[x]))
                continue
        elif(x==len(arr)-1):
             if(arr[x]-arr[x-1]<minVal):
                time=time+(minVal-(arr[x]-arr[x-1]))
                arr[x]=arr[x]+(minVal-(arr[x]-arr[x-1]))
                continue
        else:
            if(arr[x]-arr[x-1] + arr[x+1]-arr[x] >= 2*minVal ):
                if(arr[x]-arr[x-1] < minVal and arr[x+1]-arr[x] >= minVal + (minVal-(arr[x]-arr[x-1] < minVal)) ):
                    time = time + (minVal-(arr[x]-arr[x-1] < minVal))
                    arr[x]=arr[x]+ (minVal-(arr[x]-arr[x-1] < minVal))
                    continue
                elif(arr[x]-arr[x-1] >= minVal + 1 and arr[x+1]-arr[x] < minVal + (minVal - (arr[x]-arr[x-1]))   ):
                    time = time +(minVal - (arr[x]-arr[x-1]))
                    arr[x]=arr[x]-(minVal - (arr[x]-arr[x-1]))
                    continue
            else:
                continue

        check=check+1

    if(check == len(arr)):
        break

print(time)

a,b,c,d = list(map(int,input().split()))
l = [a,b,c]
l.sort()
a,b,c = l
ans = 0
if b-a<d:
    diff = b-a
    ans+=(d-diff)
if c-b<d:
    diff = c-b
    ans+=(d-diff)
print(ans)

# Chaitanya Bhutada
import math
import collections
import bisect
import heapq
import time
import random
import itertools
import sys

F = list(map(int,input().split()))
x = F[3]
F.pop()
F.sort()
y = max(0,x-(F[1] - F[0]))
z = y + max(0,x-(F[2] - F[1]))
print(z)

a, b, c, d = map(int, input().split())
a, b, c = sorted([a, b, c])
print(max(d - (b - a), 0) + max(d - (c - b), 0))

a,b,c,d=map(int,input().split())
l=min(a,b,c)
r=max(a,b,c)
m=a+b+c-l-r
mini=[0,d-abs(r-m)][d>abs(r-m)]
mini+=[0,d-abs(m-l)][d>abs(m-l)]
print(mini)

a, b, c, d = map(int, input().split())
a, b, c = sorted((a, b, c))
ans = max(0, d - (b - a)) + max(0, d - (c -b))
print(ans)

a=list(map(int,input().split()))
d=a[3]
a.remove(a[3])
#lst=list(a)
a.sort()
for i in range(len(a)):
    l=a[0]
    h=a[2]
    md=a[1]
print(2*d-h+l)

a,b,c,d = map(int,input(). split())
if max(a,b,c)>=(a+b+c+d-min(a,b,c))/2 :
    print(2*min(a,b,c)+d+max(a,b,c)-(a+b+c))
else :
    print(min(a,b,c)-max(a,b,c)+2*d)

a,b,c,d = map(int,input().split())
kmax = max(a,b,c)
kmin = min(a,b,c)
i=0
if ((kmax == a) and (kmin == b)) or ((kmax == b) and (kmin == a)):
    ks = c
elif ((kmax == b) and (kmin == c)) or ((kmax == c) and (kmin == b)):
    ks = a
else:
    ks = b
if abs(kmax-ks) < d:
    i+=abs(abs(kmax-ks)-d)
if abs(abs(kmin-ks)-d) < d:
    i+=abs(abs(kmin-ks)-d)
print(i)

a, b, c, d = map(int, input().split(" "))
dancer = [a, b, c]
dancer.sort()
counter = 0
distance = 0
while abs(dancer[0] - dancer[1]) < d or abs(dancer[1] - dancer[2]) < d:
    if abs(dancer[0] - dancer[1]) <= abs(dancer[1] - dancer[2]):
        counter += d - abs(dancer[0] - dancer[1])
        dancer[0] += d - abs(dancer[0] - dancer[1])
    else:
        counter += d - abs(dancer[2] - dancer[1])
        dancer[2] += d - abs(dancer[2] - dancer[1])

print(counter)

a, b ,c ,d   = map(int,input().split()); x =[a, b ,c] ; x =sorted(x)
total = max(0 , d -abs(a-b))+ max(0 , d-abs(b-c))
print(total)

# your code goes here

a,b,c,d = map(int, input().split())
num_list = [a,b,c]
num_list.sort()
cnt = 0

while num_list[2]-num_list[1] <= d:
    num_list[2] +=1
    cnt += 1

while num_list[1]-num_list[0] <= d:
    num_list[0] -= 1
    cnt +=1

print(cnt)

a, b, c, d = [int(x) for x in input().split()]
a, b, c  = sorted([a, b, c])
print( max(0, (d - a + b)) + max(0,( d - c + b)))

a, b, c, d = map(int, input().split())
x = list(sorted([a, b, c]))
print(sum([x[i + 1] - x[i] - d for i in range(2) if x[i + 1] - x[i] < d]))

a,b,c,d=map(int,input().split())
l=[]
l.append(a)
l.append(b)
l.append(c)
l=sorted(l,reverse=True)
mid=l[1]
if (l[0]-l[2])//2>=d:
    ans=l[2]+d-mid
else:
    ans=l[2]-(mid-d)+(mid+d)-l[0]
print(ans)

a,b,c,f=map(int,input().split())
l=[a,b,c]
l.sort()
c=l[1]-l[0]
d=l[2]-l[1]
if(c==d and f>c):
    print((f-d)*2)
else:
    if(d>=f or f>=d):
        print(f-c)
    if(c>=f or f>=c):
        print(f-d)

try:
    t=[]
    for i in range(3):
        a=int(input())
        t.append(a)
    d=int(input())
    t.sort()
    l=t[1]-t[0]
    r=t[2]-t[1]
    tm=0
    if l<d:
        tm=tm+d-l
    if r<d:
        tm=tm+d-r
    print(tm)

except Exception:
    pass

a, b, c, d=map(int, input().split())

count=0
r0=abs(a-b);r1=abs(b-c)
if r0<d:
	count+=(d-r0)
	a=b-d
if r1<d:
	count+=(d-r1)
	c=b+d
print(count)

a, b, c, g = input().split()
d = int(g)
ar = [0,1,2]
ar[0] = (int(a))
ar[1] = (int(b))
ar[2] = (int(c))
ar.sort()
print(ar)
solution = 0
if ar[1] - ar[0] < d:
    solution += d - (ar[1] - ar[0])
if ar[2] - ar[1] < d:
    solution += d - (ar[2] - ar[1])
print(solution)

def find_second_max(list_of_numbers):
    max=list_of_numbers[0]
    second_max=list_of_numbers[1]
    if(second_max>max):
        second_max,max=max,second_max
    for i in range(2,len(list_of_numbers)):
        if(list_of_numbers[i]>=max):
            second_max=max
            max=list_of_numbers[i]
        elif list_of_numbers[i]>second_max:
            second_max=list_of_numbers[i]
    return second_max

list_of_numbers=list(map(int,input().split(' ')))
d=list_of_numbers.pop()
second_max=find_second_max(list_of_numbers)
print(second_max)
list_of_numbers.remove(second_max)
sum=0
print(list_of_numbers)
for i in list_of_numbers:
    value=abs(i-second_max)
    if(value>d):
        sum=sum+0
    else:
        sum=sum+d-value
print(sum)

a, b, c, k = input().split()
k = int(k)
a, b, c = sorted([int(a), int(b), int(c)])

print(abs((b - a) - k) + abs((c - b) - k))

import math
str = input().split(" ")

a = int(str[0])
b = int(str[1])
c = int(str[2])
d = int(str[3])

c = [a,b,c]

c.sort()

def compare(x,y,dif):
    if c[y] -c[x] >= dif:
        return 0;
    cc = c[x] + dif - c[y];
    c[y] = c[x] + dif;
    return cc

count = 0

count += compare(0,1,d)
c.sort()
count += compare(1,2,d)
c.sort()
count += compare(0,2,d)
print(count)

a=list(map(int,input().strip().split()))
d=abs(a[1]-a[0])
if d<a[3]:
    d1=abs(a[3]-d)
else:
     d1=0

x=abs(a[2]-a[1])
if x<a[3]:
   y=abs(a[3]-x)
else:
    y=0
print(abs(d1+y))

a,b,c,d=map(int,input().split())
res=0
if abs(a-b)<d:
	res+=d-abs(a-b)
if abs(a-c)<d:
	res+=d-abs(a-c)
if abs(b-c)<d:
	res+=d-abs(b-c)
print( res)

a, b, c, d = map(int, input().split())
arr = [a, b, c]
arr.sort()
x, y = 0, 0
print(arr, d)
if arr[2]-arr[1] < d:
	x = d-(arr[2]-arr[1])
if arr[1]-arr[0] < d:
	y = d-(arr[1]-arr[0])

print(x+y)

a, b, c, d = map(int, input().split())
sol = 0
if (a == b):
    sol += d
    diff = abs(a-c)
    if (diff < d):
        sol += d - diff
elif (a == c):
    sol += d
    diff = abs(a-b)
    if (diff < d):
        sol += d - diff
elif (b == c):
    sol += d
    diff = abs(a-b)
    if (diff < d):
        sol += d - diff
else:
    diff1 = abs(a-b)
    diff2 = abs(a-c)
    if (diff1 < d):
        sol += d - diff1
    if (diff2 < d):
        sol += d -diff2
print(sol)

a,b,c,d=map(int,input().split())
m=abs(a-b)
m1=abs(b-c)
m2=abs(a-c)
m3=min(m,m1)
m4=min(m3,m2)
ma=max(a,b)
mb=max(ma,c)
if mb>d:
    print(d-m4)
else:
    print(d+m4)

a,b,c,d = input().split()

pos = [int(a),int(b),int(c)]

pos = sorted(pos)
sec = 0
if max(pos)-min(pos) < (int(d)*2):
    sec += (int(d)*2)-(max(pos)-min(pos))
    pos[-1] += sec

if (pos[1] - pos[0]) < int(d) or (pos[1]-pos[0])>int(d):
    sec += abs((int(d) - (pos[1] - pos[0])))

print (sec)

l = list(map(float, input().split()))
d = l[3]
l.pop()
l.sort()
ans = 2*d - ((l[1] - l[0]) + (l[2] - l[1]))
print(int(ans))

s = input().split()
a = int(s[0])
b = int(s[1])
c = int(s[2])
d = int(s[3])
maximum = max(max(a,b),max(b,c))
minimum = min(min(a,b),min(b,c))
print(2*d-(maximum-minimum))

a,b,c,d = map(int,input(). split())
if max(a,b,c)>=(a+b+c+d-min(a,b,c))/2 :
    print(2*min(a,b,c)+d+max(a,b,c)-(a+b+c))
else :
    print(min(a,b,c)-max(a,b,c)+2*d)

a,b,c,d = map(int,input().split())
li = list()
li.append(a)
li.append(b)
li.append(c)
li.sort()
d1 = li[1] - li[0]
d2 = li[2] - li[1]
if d1 >= d and d2 >= d and d3 >= d:
    print(0)
elif d1 >= d and d2 >= d:
    print(0)
elif d1 >= d and d2 < d:
    x = li[1]+d
    diff = abs(x-li[2])
    print(diff)
elif d1 < d and d2 >= d:
    x = li[1]-d
    diff = abs(li[0]-x)
    print(diff)
else:
    d3 = li[2] - li[0]
    if d3 >= d:
        if d1 < d2:
            x = li[0]-d
            diff = abs(li[1]-x)
            print(diff)
        else:
            x = li[2]+d
            diff = abs(li[1]-x)
            print(diff)
    else:
        x1 = li[1]-d
        diff1 = abs(li[0]-x1)
        x2 = li[1]+d
        diff2 = abs(li[2]-x2)
        su = diff1+diff2
        print(su)

a,b,c,d=[int(x) for x in input().split()]
l=[a,b,c]
l.sort()
print(2*d-l[2]+l[0])

a,b,c,d = list(map(int,input().split()))
aa  = min([a,b,c])
cc  = max([a,b,c])
print((d<<1)-(cc-aa))

a,b,c,d=list(map(int,input().split()))
ans=0
if abs(a-b)<d:
    qq=b-a-abs(d-a)
    ans+=abs(qq-a)
    a=b-a-abs(d-a)
if abs(b-c)<d:
    pp=c+d-abs(b-c)
    ans+=abs(pp-c)
    c+d-abs(b-c)
if abs(a-c)<d:
    c=c+abs(d-a)
    ans+=abs(d-a)
print(ans)

a,b,c,d = map(int, input().split())
nums = list()
nums.append(a)
nums.append(b)
nums.append(c)
nums.sort()
a = nums[0]
b = nums[1]
c = nums[2]
move = 0
while (b-a) <= d:
	a-=1
	move += 1
while (c-d) <= d:
	c += 1
	move += 1
print(move)

a , b , c ,d =map (int ,input().split())
q=[]
res=0
q.append(a)
q.append(b)
q.append(c)
q=sorted(q)
res+=d-abs(q[1]-q[0])
res+=d-abs(q[1]-q[2])
print(res)

a,b,c,d = input().split()

pos = [int(a),int(b),int(c)]

pos = sorted(pos)
sec = 0

sec += int(d)-(abs(pos[1]-pos[0]))
sec += int(d)-(abs(pos[2]-pos[1]))

print (sec)

a,b,c,n = map(int,input().split())
k = []
k.append(a)
k.append(b)
k.append(c)
k.sort()
ans = 0
for i in range(1,len(k)):
    y = abs(k[i-1]-k[i])
    if(y<n):
        k[i]+=(n-y)
        ans+=(n-y)
print(ans)

x=list(map(int,input().split()))
d=int(x[3])
x=x[:3]
x=sorted(x)
def a(x,s):
    if x>s:
        return x-s
    return s-x
q=x[0]
b=x[1]
c=x[2]
x=sorted(x)
maj=0

maj+=a(q+d,b)
maj+=a(q+d+d,c)
bz=maj
maj=0
maj+=a(b-d,q)
maj+=a(b+d,c)
if maj<bz:
    bz=maj
maj=0
maj+=a(c-d,b)
maj+=a(c-d-d,q)

if maj<bz:
    bz=maj
print(bz)

abcd = input().split()
abc = abcd[0:3]
abc.sort()
a = int(abc[0])
b = int(abc[1])
c = int(abc[2])
d = int(abcd[3])

if abs(a-b) >= d and abs(b-c) >= d:
    print(0)
else:
    if abs(a-b) >= d and not abs(b-c) >= d:
        print(d-abs(b-c))
    elif abs(b-c) >= d and not abs(a-b) >= d:
        print(d - abs(a-b))
    else:
        print(d-abs(a-b) + d - abs(b-c))

a = input().split()
for i in range(4):
    a[i] = int(a[i])
dist = a[3]
a.pop(3)
a.sort()
mid = a[1]
max = mid + dist
min = mid - dist
if (max >= a[2]) and (min <= a[0]):
    time = (max - a[2]) + (a[0] - min)
elif max < a[2]:
    time = a[0] - min
elif min > a[0]:
    time = max - a[2]
else:
    time = 0
print(time)

a, b, c, d = map(int, input().split())
x = list(sorted([a, b, c]))
print(sum([x[i + 1] - x[i] - d for i in range(2) if x[i + 1] - x[i] < d]))

def fcuk(l, d):
        a=l[0]
        b=l[1]
        c=l[2]
        t=m=0
        if a>d or b-a>=d:
                  t=d-(b-a)
                  m=d-(c-b)
                  if m<0:
                            m=0
                  if t<0:
                            t=0
                  return t+m
        else :
                  t=a-1
                  m=d-b+1
                  n=0
                  b=d+1
                  if b>c:
                            n=b-c
                  else :
                            n=0
                  nn=n+d
                  return nn+t+m
x=list(map(int, input().split()))
print(fcuk(sorted(x[:3]), x[3]))

a, b, c, d = [int(i) for i in input().split()]

res = 0

if a >= b and a <= c:
    x = abs(a-b)
    y = abs(a-c)
elif b >= a and b <= c:
    x = abs(a - b)
    y = abs(b - c)
else:
    x = abs(a - c)
    y = abs(b - c)

res += d - x if d - x > 0 else 0
res += d - y if d - y > 0 else 0
print(res)

sorted_list=list(int(x) for x in input().split())
d=sorted_list.pop()
count=0
sorted_list.sort()
min=sorted_list[0]
mid=sorted_list[1]
max=sorted_list[2]

if(mid-min)<d:
    count+=d-(mid-min)

elif(max-mid)<d:
    count+=d-(max-mid)

print(count)

if __name__ == '__main__':
	a,b,c,d = map(int, input().split())
	a1 = abs(a-b)
	a2 = abs(a-c)
	a3 = abs(b-c)
	ans= 0
	if a1 < d:
		ans+= d-a1
	if a2<d:
		ans+=d-a2
	if a3 < d:
		ans+=d-a3
	print(ans)

a,b,c,d=map(int,input().split())
l=[]
l.append(a)
l.append(b)
l.append(c)
l=sorted(l,reverse=True)
mid=l[1]
if (l[0]-l[2])//2>d:
    ans=l[2]+d-mid
else:
    ans=l[2]-(mid-d)+(mid+d)-l[0]
print(ans)

import math

a, b, c, d = map(int, input().split())
l = [a, b, c]
l.sort()
a,b,c=l[0],l[1],l[2]
print(min(max(a+d-b,0)+max(a+2*d-c,0),max(a-(b-d),0)+max(b+d-c,0),max(a-(c-2*d),0)+max(b-(c-d),0)))

a,b,c,d=list(map(int,input().split()))
x=[a,b,c]
x.sort(reverse=True)
if x[0]-x[1]>=d and x[1]-x[2]>=d:
	print(0)
else:
	if x[0]-x[1]<d and x[1]-x[2]<d:
		print(d-x[0]+d-x[2])
	else:
		print(d-x[0]+x[1]) if x[0]-x[1]<d else print(d-x[1]+x[2])

a,b,c,d = map(int,input(). split())
if max(a,b,c)>=(a+b+c+d-min(a,b,c))/2 :
    print(2*min(a,b,c)+d+max(a,b,c)-(a+b+c))
else :
    print(min(a,b,c)-max(a,b,c)+2*d)

a,b,c,d=map(int,input().split(" "))
ls=[a,b,c]
ls=sorted(ls)
ans=0
d1=abs(ls[1]-ls[0])
if(d1<d):
    ans=d-d1
if (abs(ls[2]-ls[1])<d):
    ans = d - abs(ls[2] - ls[1])
print(ans)

a=list(map(int,input().split()))
d=a[3]
a.remove(a[3])
#lst=list(a)

a.sort()

for i in range(len(a)):
    l=a[0]
    h=a[2]
    md=a[1]
#print(2*d-h+l)
x1=md-l
x2=h-md
if (x1>=d) :
    x1=d
elif x2>=d:
    x2=d
print(2*d-x1-x2)

s = input().split()
a = int(s[0])
b = int(s[1])
c = int(s[2])
d = int(s[3])
maximum = max(max(a,b),max(b,c))
minimum = min(min(a,b),min(b,c))
print(2*d-(maximum-minimum))

a,b,c,f=map(int,input().split())
l=[a,b,c]
l.sort()
c=l[1]-l[0]
d=l[2]-l[1]
if(c==d and f>c):
    print((f-d)*2)
else:
    if(f>=d):
        print(f-c)
    if(f>=c):
        print(f-d)

a, b, c, d = map(int, input().split())
# A = list(map(int, input().split()))
# a = int(input())
if a <= b <= c or a >= b >= c:
    print(2 * d - abs(a - b) - abs(c - b))
elif a <= c <= b or a >= c >= b:
    print(2 * d - abs(a - c) - abs(c - b))
else:
    print(2 * d - abs(a - c) - abs(a - b))

a, b, c, k = input().split()
k = int(k)
a, b, c = sorted([int(a), int(b), int(c)])

print(abs((b - a) - k) + abs((c - b) - k))

a,b,c,d=map(int,input().split())
l=[]
l.append(a)
l.append(b)
l.append(c)
l=sorted(l,reverse=True)
mid=l[1]
if (l[0]-l[2])//2>=d:
    ans=l[2]+d-mid
else:
    ans=l[2]-(mid-d)+(mid+d)-l[0]
print(ans)

l = list(map(int, input().split()))
d = l[3]
l.pop()
l.sort()
ans = 2*d - ((l[1] - l[0]) + (l[2] - l[1]))
print(ans)

a, b, c, d = map(int, input().split())
first = min(a, min(b, c))
last = max(a, max(b, c))
middle = a+b+c-first-last
print(first, middle, last)
if middle-first < d and last-middle < d:
    print((d-(middle-first))+(d-(last-middle)))
elif middle-first >= d:
    print((d - (last - middle)))
elif last-middle >= d:
    print((d-(middle-first)))

l = [int(i) for i in input().split()]
fl = 0
d = l[3]
del l[3]
l = sorted(l)
if l[1] - l[0] <= d:
    a = l[1]-l[0]
    b = d - a
    fl += b
    l[1] += b
l = sorted(l)
if l[2] - l[1] <= d:
    a = l[2]-l[1]
    b = d - a
    fl += b
    l[2] += b
print(fl)

l = [int(i) for i in input().split()]
fl = 0
d = l[3]
del l[3]
l = sorted(l)
print(d, l)
while abs(l[0]-l[1]) < d:
    l[1] += 1
    fl += 1
l = sorted(l)
while abs(l[1]-l[2]) < d:
    l[2] += 1
    fl += 1
print(fl)

a=list(map(int,input().strip().split()))
d=abs(a[1]-a[0])
if d<a[3]:
    d1=abs(a[3]-d)
else:
     d1=0

x=abs(a[2]-a[1])
if x<a[3]:
   y=abs(a[3]-x)
else:
    y=0
print(abs(d1+y))

a, b, c, d=map(int, input().split())

count=0
r0=abs(a-b);r1=abs(b-c)
if r0<d:
	count+=(d-r0)
	a=b-d
if r1<d:
	count+=(d-r1)
	c=b+d
print(count)

if __name__ == '__main__':
	a,b,c,d = map(int, input().split())
	a1 = abs(a-b)
	a2 = abs(a-c)
	a3 = abs(b-c)
	ans= 0
	if a1 < d:
		ans+= d-a1
	if a2<d:
		ans+=d-a2
	if a3 < d:
		ans+=d-a3
	print(ans)

l = [int(i) for i in input().split()]
fl = 0
d = l[3]
del l[3]
l = sorted(l)
if l[1] - l[0] <= d:
    a = l[1]-l[0]
    b = d - a
    fl += b
    l[1] += b
l = sorted(l)
if l[2] - l[1] < d:
    a = l[2]-l[1]
    b = d - a
    fl += b
    l[2] += b
print(fl)

t=list(map(int,input().split()))
a,b,c,d=t[0],t[1],t[2],t[3]
mn=min(t)
mx=max(t)
t=d*2-(mx-mn)
print(t)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul  6 16:05:32 2019

@author: kevinss0643
"""

a,b,c,d = [int(x) for x in input().split()]

ropewalking=[a,b,c]
ropewalking.sort()
ropewalking.append(d)

def ropewalk(a,b,c,d):
    time=0
    if abs(b-a)<d:
        time += d-abs(b-a)
    if abs(c-b)<d:
        time +=d-abs(c-b)
    return time

print(ropewalk(a,b,c,d))

a,b,c,n = map(int,input().split())
k = []
k.append(a)
k.append(b)
k.append(c)
k.sort()
ans = 0
for i in range(1,len(k)):
    y = abs(k[i-1]-k[i])
    if(y<n):
        k[i]+=(n-y)
        ans+=(n-y)
print(ans)

# Chaitanya Bhutada
import math
import collections
import bisect
import heapq
import time
import random
import itertools
import sys

F = list(map(int,input().split()))
x = F[3]
F.pop()
F.sort()
y = max(0,x-(F[1] - F[0]))
z = max(y , x-(F[2] - F[1]))
print(z)

a,b,c,d = [int(_) for _ in input().split()]
if a > b:
    a, b = b, a
if b > c:
    b, c = c, b
d1 = b-a
d2 = c-b
k1=0
k2=0
if d1 >=d and d2>=d:
    print(0)
elif (d1-d)<0 or (d2-d)<0:
    if d1-d < 0:
        k1 = d-d1
    if d2-d <0:
        k2 = d-d2
    print(k1+k2)

a , b , c ,d =map (int ,input().split())
q=[]
res=0
q.append(a)
q.append(b)
q.append(c)
q=sorted(q)
res+=d-abs(q[1]-q[0])
res+=d-abs(q[1]-q[2])
print(res)

a=list(map(int,input().split()))
d=a[3]
a.remove(a[3])
#lst=list(a)

a.sort()

for i in range(len(a)):
    l=a[0]
    h=a[2]
    md=a[1]
#print(2*d-h+l)
x1=md-l
x2=h-md
if (x1>=d) :
    x1=d
elif x2>=d:
    x2=d
print(2*d-x1-x2)

a,b,c,f=map(int,input().split())
l=[a,b,c]
l.sort()
c=l[1]-l[0]
d=l[2]-l[1]
if(c==d and f>c):
    print((f-d)*2)
else:
    if(d>=f):
        print(f-c)
    if(c>=f):
        print(f-d)

a,b,c,d = map(int,input().split())
li = list()
li.append(a)
li.append(b)
li.append(c)
li.sort()
d1 = li[1] - li[0]
d2 = li[2] - li[1]
if d1 >= d and d2 >= d:
    print(0)
elif d1 >= d and d2 >= d:
    print(0)
elif d1 >= d and d2 < d:
    x = li[1]+d
    diff = abs(x-li[2])
    print(diff)
elif d1 < d and d2 >= d:
    x = li[1]-d
    diff = abs(li[0]-x)
    print(diff)
else:
    d3 = li[2] - li[0]
    if d3 >= d:
        if d1 < d2:
            x = li[0]-d
            diff = abs(li[1]-x)
            print(diff)
        else:
            x = li[2]+d
            diff = abs(li[1]-x)
            print(diff)
    else:
        x1 = li[1]-d
        diff1 = abs(li[0]-x1)
        x2 = li[1]+d
        diff2 = abs(li[2]-x2)
        su = diff1+diff2
        print(su)

from math import fabs
def u(x):
    if x <= 0:
        return 0
    return x
a, b, c, d = list(map(int, input().split()))
m = sorted([a, b, c])
print(u(d - fabs(m[1] - m[0])) + u(d - fabs(m[2] - m[1])))

a, b, c, d = map(int, input().split())
mylist = [a, b, c]
mylist.sort()
moveL = []
mincor = mylist[0]
avecor = mylist[1]
maxcor = mylist[2]

#first move
if mylist[1] - mylist[0] < d:
    mincor = avecor - d

if mylist[2] - mylist[1] < d:
    maxcor = avecor + d

move = (mylist[0] - mincor) + (maxcor - mylist[2])
moveL.append(move)

mincor = mylist[0]
avecor = mylist[1]
maxcor = mylist[2]
#second move
if mylist[1] - mylist[0] < d:
    avecor = mincor + d

if mylist[2] - avecor < d:
    maxcor = avecor + d

move = ((avecor - mylist[1]) + (maxcor - mylist[2]))
moveL.append(move)

mincor = mylist[0]
avecor = mylist[1]
maxcor = mylist[2]
#third move
if mylist[2] - mylist[1] < d:
    avecor = maxcor - d

if mylist[1] - avecor < d:
    mincor = avecor - d

move = ((mylist[1] - avecor) + (mylist[0] - mincor))
moveL.append(move)

print(min(moveL))

import math

a, b, c, d = map(int, input().split())
l = [a, b, c]
l.sort()
a,b,c=l[0],l[1],l[2]
print(min(max(a+d-b,0)+max(a+2*d-c,0),max(a-(b-d),0)+max(b+d-c,0),max(a-(c-2*d),0)+max(b-(c-d),0)))