Harryxun/sft_time huggingface dataset:
### BUGGY CODE ###

import sys

class segTree(): #range minimum query
    def __init__(self, N, V): #create segment tree with initial value V
        d = 1
        while d < N: d <<= 1
        self.tree = [V for _ in range(2 * d - 1)]
        self.size = d
    
    def update(self, i, a): #update cell i with value a
        now = self.size - 1 + i 
        self.tree[now] = a
        while now > 0:
            now = (now - 1) // 2
            self.tree[now] = max(self.tree[2 * now + 1], self.tree[2 * now + 2])

    def search(self, lower, higher, lbound, hbound, pos): #search minimum value of [lower, higher) init: lbound = 0, hbound = self.size, pos = 0
        if higher <= lbound or hbound <= lower: return 0
        if lower <= lbound and hbound <= higher: return self.tree[pos]
        else:
            left = self.search(lower, higher, lbound, (lbound + hbound) // 2, 2 * pos + 1)
            right = self.search(lower, higher, (lbound + hbound) // 2, hbound, 2 * pos + 2)
            return max(left, right)
        
def solve():
    input = sys.stdin.readline
    N = int(input())
    H = [int(h) for h in input().split()]
    A = [int(a) for a in input().split()]
    highest = max(H) + 1
    ans = segTree(highest, 0)
    for i, h in enumerate(H): 
        maxSum = ans.search(0, h, 0, ans.size, 0)
        ans.update(h, A[i] + maxSum)
    print(ans.search(0, highest, 0, ans.size, 0))

    return 0

if __name__ == "__main__":
    solve()

### FIXED CODE ###

import sys

class segTree():
    def __init__(self, N, value):
        d, k = 1, 0
        while d < N:
            d *= 2
            k += 1
        self.tree = [value for _ in range(2 * d - 1)]
        self.size = d
    
    def update(self, i, a):
        now = self.size - 1 + i 
        self.tree[now] = a
        while now > 0:
            now = (now - 1) // 2
            self.tree[now] = max(self.tree[2 * now + 1], self.tree[2 * now + 2])
        #print(self.tree)

    def search(self, lower, higher, lbound, hbound, pos):
        if higher <= lbound or hbound <= lower: return 0
        if lower <= lbound and hbound <= higher: return self.tree[pos]
        else:
            left = self.search(lower, higher, lbound, (lbound + hbound) // 2, 2 * pos + 1)
            right = self.search(lower, higher, (lbound + hbound) // 2, hbound, 2 * pos + 2)
            return max(left, right)
        
def solve():
    input = sys.stdin.readline
    N = int(input())
    H = [int(h) for h in input().split()]
    A = [int(a) for a in input().split()]
    highest = max(H) + 1
    ans = segTree(highest, 0)
    for i, h in enumerate(H): 
        maxSum = ans.search(0, h, 0, ans.size, 0)
        ans.update(h, A[i] + maxSum)
    print(ans.search(0, highest, 0, ans.size, 0))

    return 0

if __name__ == "__main__":
    solve()
### BUGGY CODE ###

inp = input().split(" ")
N = int(inp[0])
K = int(inp[1])

arr = {}
keys = []

for i in range(N):
	inp = input().split(" ")
	a = int(inp[0])
	b = int(inp[1])
	if a in arr:
		arr[a] += b
	else:
		arr[a] = b
		keys.append(a)
		keys.sort()

for i in keys:
	K -= arr[i]
	if K <= 0:
		print(i)
		break

### FIXED CODE ###

def main():
    n, k = [int(x) for x in input().split(' ')]
    arr = [0] * 100001
    for _ in range(n):
        a, b = [int(x) for x in input().split(' ')]
        arr[a] += b
    foo = 0
    for i, e in enumerate(arr):
        foo += e
        if (foo >= k):
            print(i)
            break

main()
### BUGGY CODE ###

import sys,bisect

from sys  import stdin,stdout

from bisect import bisect_left,bisect_right,bisect,insort,insort_left,insort_right

from math import gcd,ceil,floor,sqrt

from collections import Counter,defaultdict,deque,OrderedDict

dx=[-1,1,0,0]
dy=[0,0,1,-1]


sys.setrecursionlimit(10**6)
INF = float('inf')
MOD = 998244353
mod = 10**9+7

def isPrime(n):
    if (n <= 1) :return False
    if (n <= 3) :return True
    if (n%2 == 0 or n%3 == 0):return False
    for i in range(5,ceil(sqrt(n))+1,6):
        if (n%i==0 or n%(i+2)==0):
            return False
    return True

def st():
    return list(stdin.readline().strip())

def inp():
    return int(stdin.readline())

def li():
    return list(map(int,stdin.readline().split()))

def mp():
    return map(int,stdin.readline().split())

def pr(n):
    stdout.write(str(n)+"\n")

def CC(d,v,i,l):
    v[i]=True
    stack=[i]
    c=1
    while stack:
        a=stack.pop()
        for i in d[a]:
            if not v[i]:
                stack.append(i)
                v[i]=True
                c+=1
    l.append(c)
    
def solve():
    n,m=mp()
    d={i:[] for i in range(1,n+1)}
    for i in range(m):
        a,b=mp()
        d[a].append(b)
        d[b].append(a)

    v=[False for i in range(n+1)]
    x=[]
    for i in range(1,n+1):
        if not v[i]:
            CC(d,v,i,x)


   
    cd=0
    p=sum(x)
    while p!=0:
        for i in range(len(x)):
            if x[i]>0:
                x[i]-=1
                p-=1
        cd+=1
    pr(cd)
        
        
    
for _ in range(1):
    solve()



### FIXED CODE ###

import sys,bisect

from sys  import stdin,stdout

from bisect import bisect_left,bisect_right,bisect,insort,insort_left,insort_right

from math import gcd,ceil,floor,sqrt

from collections import Counter,defaultdict,deque,OrderedDict

dx=[-1,1,0,0]
dy=[0,0,1,-1]


sys.setrecursionlimit(10**6)
INF = float('inf')
MOD = 998244353
mod = 10**9+7

def isPrime(n):
    if (n <= 1) :return False
    if (n <= 3) :return True
    if (n%2 == 0 or n%3 == 0):return False
    for i in range(5,ceil(sqrt(n))+1,6):
        if (n%i==0 or n%(i+2)==0):
            return False
    return True

def st():
    return list(stdin.readline().strip())

def inp():
    return int(stdin.readline())

def li():
    return list(map(int,stdin.readline().split()))

def mp():
    return map(int,stdin.readline().split())

def pr(n):
    stdout.write(str(n)+"\n")

def CC(d,v,i,l):
    v[i]=True
    stack=[i]
    c=1
    while stack:
        a=stack.pop()
        for i in d[a]:
            if not v[i]:
                stack.append(i)
                v[i]=True
                c+=1
    l.append(c)
    
def solve():
    n,m=mp()
    d={i:[] for i in range(1,n+1)}
    for i in range(m):
        a,b=mp()
        d[a].append(b)
        d[b].append(a)

    v=[False for i in range(n+1)]
    x=[]
    for i in range(1,n+1):
        if not v[i]:
            CC(d,v,i,x)
           
    pr(max(x))
        
        
    
for _ in range(1):
    solve()
### BUGGY CODE ###

import collections
import math
def combinations_count(n, r):
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
n = int(input())
a = list(map(int, input().split()))
c = collections.Counter(a)
val = list(c.values())
key = list(c.keys())
comb = [combinations_count(i,2) if not i < 2 else 0 for i in val]
for i in range(n):
    ind = key.index(a[i])
    count = sum(comb)
    count -= comb[ind]
    hoge = val[ind] -1 
    if hoge < 2:
        pass
    else:
        count += combinations_count(hoge,2)
    print(count)

### FIXED CODE ###

n = int(input())
a = list(map(int, input().split()))
b = [0]*n
for i in range(n):
    b[a[i]-1] += 1
c = sum([(i*(i-1))//2 for i in b])
for i in a:
    print(c-(b[i-1]-1))
### BUGGY CODE ###

import sys
def input():
    return sys.stdin.readline()[:-1]
# input
N, K, Q = map(int, input().split())
As = [int(input()) for i in range(Q)]

points = [K for i in range(N)]

for a in As:
    # points = [0 if point == 0 for point in points else point - 1]
    points = [point - 1 for point in points]
    points[a - 1] += 1

survive = ['Yes' if point >= 1 else 'No' for point in points]

print(*survive, sep="\n")

### FIXED CODE ###

# import math
# import numpy as np
import sys
def input():
    return sys.stdin.readline()[:-1]
# input
N, K, Q = map(int, input().split())
As = [int(input()) for i in range(Q)]

points = [K - Q] * N

for a in As:
    # points = [0 if point == 0 for point in points else point - 1]
    # points -= 1
    # points[a - 1] += 1
    points[a-1] += 1
survive = ['Yes' if point >= 1 else 'No' for point in points]

print(*survive, sep="\n")
### BUGGY CODE ###

import sys
import itertools
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))

def solve(n,a):
    table = [0]*(n+1)
    for i,x in enumerate(a):
        table[max(0,i-x)] += 1
        table[min(n-1,i+x)+1] -=1
    return list(itertools.accumulate(table))[:-1]

def main():
    n,k = map(int,sys.stdin.readline().rstrip().split())
    a = LI()
    for _ in range(k):
        a = solve(n,a)
    for rep in a:
        print(rep,end=' ')

if __name__=='__main__':
    main()

### FIXED CODE ###

import sys
from itertools import accumulate

def solve(n,k,a):
    for _ in range(k):
        if a==[n]*n:    return a
        t = [0]*(n+1)
        for i,x in enumerate(a):
            t[max(0,i-x)] += 1
            t[min(n,i+x+1)] -=1
        a = list(accumulate(t))[:-1]
    return a

n,k = map(int,sys.stdin.readline().rstrip().split())
a = list(map(int,sys.stdin.readline().rstrip().split()))

print(*solve(n,k,a))
### BUGGY CODE ###

import fractions
 
n = int(input())
a = list(map(int, input().split()))
 
l = 1
for i in range(n):
	l = l // fractions.gcd(l, a[i])*a[i]
 
ans = 0
for i in range(n):
	ans += l//a[i]
print(ans%(10**9+7))

### FIXED CODE ###

import fractions
 
n = int(input())
a = list(map(int, input().split()))
 
l = 1
for i in range(n):
	l = l // fractions.gcd(l, a[i])*a[i]
 
ans = 0
for i in range(n):
	ans += l//a[i]
print(ans%(10**9+7))
### BUGGY CODE ###

n=int(input())
dis=[10**15]*n
dis[0]=0
pair=[[]for _ in range(n)]
for i in range(n-1):
	a,b,c=map(int,input().split())
	pair[a-1].append([b-1,c])
	pair[b-1].append([a-1,c])
now=0
stack=set()
cnt=n-1
while cnt!=0:
	for i in range(len(pair[now])):
		if dis[pair[now][i][0]]==10**15:
			dis[pair[now][i][0]]=dis[now]+pair[now][i][1]
			stack.add(pair[now][i][0])
	now=list(stack)[0]
	stack=set(stack)
	stack.remove(now)
	cnt-=1
for i in range(n):
	if dis[i]%2==0:
		print(0)
	else:
		print(1)



### FIXED CODE ###

n=int(input())
dis=[10**15]*n
dis[0]=0
pair=[[]for _ in range(n)]
for i in range(n-1):
	a,b,c=map(int,input().split())
	pair[a-1].append([b-1,c])
	pair[b-1].append([a-1,c])
now=0
stack=set()
cnt=n-1
while cnt!=0:
	for i in range(len(pair[now])):
		if dis[pair[now][i][0]]==10**15:
			dis[pair[now][i][0]]=dis[now]+pair[now][i][1]
			stack.add(pair[now][i][0])
	now=stack.pop()
	cnt-=1
for i in range(n):
	if dis[i]%2==0:
		print(0)
	else:
		print(1)
### BUGGY CODE ###


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

ans = 0

while True:
    flg = True

    for i in range(a):
        ans += 1
        k -= 1
        if k == 0:
            flg = False
            break

    if not flg:
        break

    for i in range(b):
        k -= 1
        if k == 0:
            flg = False
            break

    if not flg:
        break

    for i in range(c):
        ans += -1
        k -= 1
        if k == 0:
            flg = False
            break

    if not flg:
        break

print(ans)


### FIXED CODE ###

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

if k <= a:
    print(k)
elif k <= a + b:
    print(a)
else:
    print(a - (k - a - b))
### BUGGY CODE ###

H, N = map(int, input().split())
# mahous = [(a, b) for a, b in list(map(int, input().split()))]

mahous = []
for i in range(N):
    a, b = map(int, input().split())
    mahous.append((a, b))

dp = [float("inf")] * (H + 1)
dp[0] = 0

for h in range(1, H + 1):
    for n in range(N):
        a, b = mahous[n]
        tairyoku = max(0, h - a)
        # if h - a >= 0:
        dp[h] = min(dp[h], dp[tairyoku] + b)
    # print(dp)

print(dp[H])

### FIXED CODE ###

H, N = map(int, input().split())
# mahous = [(a, b) for a, b in list(map(int, input().split()))]

mahous = []
for i in range(N):
    a, b = map(int, input().split())
    mahous.append((a, b))

dp = [float("inf")] * (H + 1)
dp[0] = 0

for h in range(1, H + 1):
    for n in range(N):
        a, b = mahous[n]
        tairyoku = max(0, h - a)
        # if h - a >= 0:
        dp[h] = min(dp[h], dp[tairyoku] + b)
    # print(dp)

print(dp[H])
### BUGGY CODE ###

n = int(input())
a = list(map(int, input().split()))
ans = 0
for i in range(n-1):
    for j in range(i+1,n):
        ans += a[i]*a[j]
print(ans%(10**9+7))

### FIXED CODE ###

n = int(input())
a = list(map(int, input().split()))
mod = 10**9+7
tmp = 0
sum = 0
for i in range(n):
    sum += a[i]
    sum %= mod
for i in range(n-1):
    sum -= a[i]
    if sum<0:
        sum+=mod
    tmp += a[i]*sum
    tmp %= mod 
print(tmp)
### BUGGY CODE ###

# -*- coding: utf-8 -*-
import numpy as np
N, K, Q = map(int, input().split())
score = np.array([K]*N)


for i in range(Q):
    answer = int(input())
    score[answer - 1] += 1
    score = score - 1


for i in range(N):
    if score[i] <= 0:
        print("No")
    else:
        print("Yes")

### FIXED CODE ###

# -*- coding: utf-8 -*-
import sys
input = sys.stdin.readline

N, K, Q = map(int, input().split())
score = [0] * N

for i in range(Q):
    score[int(input()) -1 ] += +  1

for SCORE in score:
    if SCORE <= Q - K:
        print("No")
    else:
        print("Yes")
### BUGGY CODE ###

import math
if __name__ == "__main__": 
	string = input()
	l = string.split(" ")
	a = int(l[0])
	b = int(l[1])
	n = int(l[2])
	ans = 0
	for i in range(n,0,-1):
		f = math.floor((a*i)/b)
		s = math.floor(i/b)
		temp = int(f) - (a*int(s))
		if(temp > ans):
			ans = temp
	print(ans)

### FIXED CODE ###

import math
if __name__ == "__main__": 
	string = input()
	l = string.split(" ")
	a = int(l[0])
	b = int(l[1])
	n = int(l[2])
	ans = 0
	ni = min(n,b-1)
	f = math.floor((a*(ni))/b)
	s = math.floor((ni)/b)
	temp = int(f) - (a*int(s))
	ans = temp
	# if(n>b):
	# 	f = math.floor((a*(b-1))/b)
	# 	s = math.floor((b-1)/b)
	# 	temp = int(f) - (a*int(s))
	# 	ans = temp
	# else:
	# 	f = math.floor((a*(n))/b)
	# 	s = math.floor((n)/b)
	# 	temp = int(f) - (a*int(s))
	# 	ans = temp
	print(ans)
### BUGGY CODE ###

import sys
n = int(sys.stdin.readline())
A = [int(sys.stdin.readline()) for _ in range(n)]

for i in range(n):
    if A[i] == max(A):
        tmp = sorted(A)
        print(tmp[-2])
    else:
        print(max(A))

### FIXED CODE ###

import sys
n = int(sys.stdin.readline())
A = [int(sys.stdin.readline()) for _ in range(n)]
tmp = sorted(A)
maxa = max(A)
for i in range(n):
    if A[i] == maxa:
        print(tmp[-2])
    else:
        print(maxa)
### BUGGY CODE ###

#枚数
a, b, c, k = map(int, input().split())
 
A = a
B = 0
C = -1 * c
 
if k - a >= 0:
    if k -a -b > 0:
        for i in range(c +1):
            if a + b + i == k:
                print(a + (-1)*i)
    else:
        print(a)
else:
    print(k)
 

### FIXED CODE ###

#枚数
a, b, c, k = map(int, input().split())
 
A = a
B = 0
C = -1 * c
 
if k - a >= 0:
    if k -a -b >= 0:
        print(a + (-1)*(k -a -b) )
    else:
        print(a)
else:
    print(k)
### BUGGY CODE ###

N = int(input())
X = list(map(int, input().split()))
for i in range(N):
  Y = X[:]
  Y.remove(X[i])
  Y.sort()
  print(Y[N // 2 - 1])

### FIXED CODE ###

N = int(input())
X = list(map(int, input().split()))
L = []
for i in range(N):
  L.append([X[i], i])
L.sort()
for i in range(N):
  if i < N // 2:
    L[i].append(L[N // 2][0])
  else:
    L[i].append(L[N // 2 - 1][0])
for i in range(N):
  L[i][0], L[i][1] = L[i][1], L[i][0]
L.sort()
for i in range(N):
  print(L[i][2])
### BUGGY CODE ###

def main():
    N = int(input())
    a_list = list(map(int, input().split()))
    BITS = 30
    sum_bit = [0] * BITS
    a_bits = []

    for a in a_list:
        bits = [a>> j & 1 for j in range(BITS)]
        for i, bit in enumerate(bits):
            sum_bit[i] += bit
        a_bits.append(bits)

    for a_bit in a_bits:
        # rb -> sum_bitのビット, ab -> a_bitのビット
        res = 0
        cur = 1
        for i in range(BITS):
            res += cur if (a_bit[i] + sum_bit[i])%2 == 1 else 0
            cur *= 2
        print(res, end=" ")

if __name__ == "__main__":
    main()



### FIXED CODE ###

def main():
    N = int(input())
    a_list = list(map(int, input().split()))
    BITS = 30
    sum_bit = [0] * BITS
    a_bits = []

    for a in a_list:
        bits = [a>> j & 1 for j in range(BITS)]
        for i, bit in enumerate(bits):
            sum_bit[i] += bit
        a_bits.append(bits)

    for a_bit in a_bits:
        # rb -> sum_bitのビット, ab -> a_bitのビット
        res = 0
        cur = 1
        for i in range(BITS):
            res += cur if (a_bit[i] + sum_bit[i])%2 == 1 else 0
            cur *= 2
        print(res, end=" ")

if __name__ == "__main__":
    main()
### BUGGY CODE ###

N = int(input())
li = list(map(int, input().split()))
for k in range(N):
    check_li, ans = li[:k]+li[k+1:], 0
    for i in list(set(check_li)):
        cnt = check_li.count(i)
        ans += cnt * (cnt-1) // 2
    print(ans)

### FIXED CODE ###

from collections import Counter
N, li = int(input()), list(map(int, input().split()))
cnt_dict, cnt_total = Counter(li), 0
for i in cnt_dict.items():
    cnt_total += i[1] * (i[1]-1) // 2
for k in range(N):
    buf = cnt_dict[li[k]]
    print(cnt_total - buf*(buf-1)//2 + (buf-1)*(buf-2)//2)
### BUGGY CODE ###

import sys
sys.setrecursionlimit(10 ** 9)
# input = sys.stdin.readline    ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')
from math import ceil, floor, log2
# from collections import deque
# from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations
# from heapq import heapify, heappop, heappush
# import numpy as np
# from numpy import cumsum  # accumulate

def solve():
    N, K = MI()
    # A = LI1()

    D = [[0] * N for _ in range(int(log2(K))+1)]
    D[0] = LI1()
    
    for i in range(1, int(log2(K))+1):
        for j in range(N):
            tmp = D[i-1][j]
            D[i][j] = D[i-1][tmp]
    # print(D)
    
    v = 0
    while K > 0:
        tmp = int(log2(K))
        K = K - 2 ** tmp
        v = D[tmp][v]
        # print(tmp, K, v)
    print(v+1)

if __name__ == '__main__':
    solve()


### FIXED CODE ###

import sys

sys.setrecursionlimit(10 ** 6)
# input = sys.stdin.readline    ####
int1 = lambda x: int(x) - 1


def II(): return int(input())


def MI(): return map(int, input().split())


def MI1(): return map(int1, input().split())


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


def LI1(): return list(map(int1, input().split()))


def LLI(rows_number): return [LI() for _ in range(rows_number)]


def printlist(lst, k='\n'): print(k.join(list(map(str, lst))))


INF = float('inf')


def solve():
    n, k = MI()
    A = LI1()
    # print(A)
    memo = {0: 0}
    current = 0
    keiro = []
    for i in range(n):
        keiro.append(current)
        next = A[current]
        # print(i, current, next)
        if (i + 1) == k:
            print(next+1)
            return

        if memo.get(next, -1) == -1:
            memo[next] = i + 1
            current = next
        else:
            pre = current
            current = next
            keiro.append(current)
            # print(pre, current)
            left = k - i - 1
            # print('aaa', memo[pre], memo[current])
            loopsize = memo[pre] - memo[current] + 1
            # print('a', left, loopsize)
            r = left % loopsize
            # print(memo)
            # print(keiro)
            # print(keiro[memo[current] + r])
            ans = keiro[memo[current] + r] + 1
            print(ans)
            return


if __name__ == '__main__':
    solve()
### BUGGY CODE ###

def readInt():
    return int(input())
def readList():
    return list(map(int,input().split()))
def readMap():
	return map(int,input().split())
def readStr():
    return input()
inf=float('inf')
mod = 10**9+7
import math
from itertools import permutations
def solve(N,X,M):
    ans=X
    A=X
    for _ in range(N-1):
        A=A**2%M
        if A==0:
            break
        ans+=A
    return ans


N,X,M=readMap()
print(solve(N,X,M))


### FIXED CODE ###

def readInt():
    return int(input())
def readList():
    return list(map(int,input().split()))
def readMap():
	return map(int,input().split())
def readStr():
    return input()
inf=float('inf')
mod = 10**9+7
import math
def solve(N,X,M):
    seen=set()
    order_seen=[]
    while X not in seen:
        seen.add(X)
        order_seen.append(X)
        X=f(X,M)
    pos=order_seen.index(X)  # Find position of when the cycle begins
    if pos>N:  # If position is greater than N, then we know we are not going to include any values from the cycle.
        return sum(order_seen[:N])
    terms_before_cycle=order_seen[:pos]
    sum_terms_before_cycle=sum(terms_before_cycle)
    ans=sum_terms_before_cycle
    terms_in_cycle=order_seen[pos:]
    sum_cycle=sum(terms_in_cycle)
    length_cycle=len(terms_in_cycle)
    number_remaining_terms=N-pos
    mult_factor=(number_remaining_terms)//length_cycle
    ans+=(sum_cycle*mult_factor)
    numb_remain=(number_remaining_terms)%length_cycle
    ans+=sum(terms_in_cycle[:numb_remain])
    return ans

# The function for the recurrence relation.  A_n+1=A_n^2%M
def f(A,M):
    return pow(A,2,M)

N,X,M=readMap()
print(solve(N,X,M))
### BUGGY CODE ###

N = int(input())
A = [int(a) for a in input().split()]

ans = 0
for i in range(1, len(A))[::-1]:
    # print(A)
    if A[i-1] > A[i]:
        diff = A[i-1] - A[i]
        for j in range(i, len(A)):
            if A[i-1] > A[j]:
                A[j] += diff
                ans += diff

# print(A)
print(ans)

### FIXED CODE ###

N = int(input())
A = [int(a) for a in input().split()]

ans = 0

for i in range(len(A)-1):
    if A[i] > A[i+1]:
        diff = A[i] - A[i+1]
        A[i+1] += diff
        ans += diff

print(ans)
### BUGGY CODE ###

from functools import reduce

def xor(a,b):
    return a^b


#1. input
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))

#2. conduct a+b
sum_list = []
for a_i in a:
    for b_j in b:
        sum_list.append(a_i+b_j)

#3. convert decimal into binary
sum_list_bin = [bin(sum_list_dec) for sum_list_dec in sum_list]

#4. calculate xor
ans = reduce(xor, sum_list)
print(ans)

### FIXED CODE ###

import sys
sdin = sys.stdin.readline


# 入力
n = int(sdin())
a = list(map(int, sdin().split()))
b = list(map(int, sdin().split()))

ans = 0

# バケットソートする
for k in range(29):
    a_nex = [[],[]]
    b_nex = [[],[]]
    for ai in a:
        a_nex[(ai & (1<<k)) >> k].append(ai)
            
    for bj in b:
        b_nex[(bj & (1<<k)) >> k].append(bj)
    

    a = []
    b = []
    for i in range(2):
        a = a + a_nex[i]
        b = b + b_nex[i]
        
    mask = pow(2,k+1) - 1
    a_mask = [ai & mask for ai in a]
    b_mask = [bj & mask for bj in b]
    
    base = pow(2,k)
    itr = [n]*4
    count = 0
    for ai in a_mask:
        border = [
                base - ai,
                2*base - ai,
                3*base - ai,
                4*base - ai
        ]
        
        for i in range(4):
            while 0 < itr[i] and border[i] <= b_mask[itr[i] - 1]:
                itr[i] -= 1
            
            
        count += ((itr[1] - itr[0]) + (itr[3]) - itr[2])
    
    if count & 1:
        ans += base
    
    
print(ans)
### BUGGY CODE ###

N, W = map(int, input().split())

dp = [[0]*(W+1) for _ in range(N+1)]

for i in range(1, N+1):
  w, v = map(int, input().split())
  for j in range(W+1):
    dp[i][j] = dp[i-1][j]
    if j >= w:
      dp[i][j] = max(dp[i][j], dp[i-1][j-w]+v)

print(dp[N][W])

### FIXED CODE ###

N, W = map(int, input().split())

dp = [[0]*(W+1) for _ in range(N+1)]

for i in range(1, N+1):
  w, v = map(int, input().split())
  for j in range(W+1):
    dp[i][j] = dp[i-1][j]
    if j >= w:
      dp[i][j] = max(dp[i][j], dp[i-1][j-w]+v)

print(dp[N][W])