import sys
try:sys.stdin,sys.stdout=open('in.txt','r'),open('out.txt','w')
except:pass
ii1=lambda:int(sys.stdin.readline().strip()) # for interger
is1=lambda:sys.stdin.readline().strip() # for str
iia=lambda:list(map(int,sys.stdin.readline().strip().split())) # for List[int]
isa=lambda:sys.stdin.readline().strip().split() # for List[str]
mod=int(1e9 + 7);from collections import *;from math import *

###################### Start Here ######################
def findLocalMaximaMinima(n, arr):
    mx = []
    mn = []
    ans=[]
    if(arr[0] > arr[1]):
        mx.append(0)
    elif(arr[0] < arr[1]):
        mn.append(0)

    for i in range(1, n-1):

        if(arr[i-1] > arr[i] < arr[i + 1]):
            mn.append(arr[i])
            ans.append(arr[i])
        elif(arr[i-1] < arr[i] > arr[i + 1]):
            mx.append(i)
            ans.append(arr[i])
    if(arr[-1] > arr[-2]):
        mx.append(n-1)
        ans.append(arr[-1])
    elif(arr[-1] < arr[-2]):
        mn.append(n-1)
        ans.append(arr[-1])
    # print(ans)
    return ans
def fun(arr,n):
    max_so_far = -inf
    max_ending_here = 0

    for i in range(0, n):
        max_ending_here = max_ending_here + arr[i]
        if (max_so_far < max_ending_here):
            max_so_far = max_ending_here

        if max_ending_here < 0:
            max_ending_here = 0
    return max_so_far

t = ii1()
for _ in range(t):
    n ,q = iia()
    arr = iia()
    ans=findLocalMaximaMinima(n,arr)
    flag=0
    if len(ans)>=2:
        if ans[0]<ans[1]:
            ans.pop(0)
    for i in range(len(ans)):
        if i%2==1:
            ans[i]=-ans[i]
    res=fun(ans,len(ans))
    print(res)


import sys
try:sys.stdin,sys.stdout=open('in.txt','r'),open('out.txt','w')
except:pass
ii1=lambda:int(sys.stdin.readline().strip()) # for interger
is1=lambda:sys.stdin.readline().strip() # for str
iia=lambda:list(map(int,sys.stdin.readline().strip().split())) # for List[int]
isa=lambda:sys.stdin.readline().strip().split() # for List[str]
mod=int(1e9 + 7);from collections import *;from math import *

###################### Start Here ######################
def findLocalMaximaMinima(n, arr):
    mx = []
    mn = []
    ans=[]
    if n<=2:
        return arr
    if(arr[0] > arr[1]):
        mx.append(0)
        ans.append(arr[0])
    elif(arr[0] < arr[1]):
        mn.append(0)
        ans.append(arr[0])

    for i in range(1, n-1):

        if(arr[i-1] > arr[i] < arr[i + 1]):
            mn.append(arr[i])
            ans.append(arr[i])
        elif(arr[i-1] < arr[i] > arr[i + 1]):
            mx.append(i)
            ans.append(arr[i])
    if(arr[-1] > arr[-2]):
        mx.append(n-1)
        ans.append(arr[-1])
    elif(arr[-1] < arr[-2]):
        mn.append(n-1)
        ans.append(arr[-1])
    # print(ans)
    return ans
def fun(arr,n):
    max_so_far =arr[0]
    curr_max = arr[0]

    for i in range(1,n):
        curr_max = max(arr[i], curr_max + arr[i])
        max_so_far = max(max_so_far,curr_max)

    return max_so_far

t = ii1()
for _ in range(t):
    n ,q = iia()
    arr = iia()
    ans=findLocalMaximaMinima(n,arr)
    flag=0
    if len(ans)>=2:
        if ans[0]<ans[1]:
            ans.pop(0)
    for i in range(len(ans)):
        if i%2==1:
            ans[i]=-ans[i]
    # print(ans)
    res=fun(ans,len(ans))
    print(res)


import sys
try:sys.stdin,sys.stdout=open('in.txt','r'),open('out.txt','w')
except:pass
ii1=lambda:int(sys.stdin.readline().strip()) # for interger
is1=lambda:sys.stdin.readline().strip() # for str
iia=lambda:list(map(int,sys.stdin.readline().strip().split())) # for List[int]
isa=lambda:sys.stdin.readline().strip().split() # for List[str]
mod=int(1e9 + 7);from collections import *;from math import *

###################### Start Here ######################
def findLocalMaximaMinima(n, arr):
    mx = []
    mn = []
    ans=[]
    if(arr[0] > arr[1]):
        mx.append(0)
    elif(arr[0] < arr[1]):
        mn.append(0)

    for i in range(1, n-1):

        if(arr[i-1] > arr[i] < arr[i + 1]):
            mn.append(arr[i])
            ans.append(arr[i])
        elif(arr[i-1] < arr[i] > arr[i + 1]):
            mx.append(i)
            ans.append(arr[i])
    if(arr[-1] > arr[-2]):
        mx.append(n-1)
        ans.append(arr[-1])
    elif(arr[-1] < arr[-2]):
        mn.append(n-1)
        ans.append(arr[-1])
    # print(ans)
    return ans
def fun(arr,n):
    max_so_far =arr[0]
    curr_max = arr[0]

    for i in range(1,n):
        curr_max = max(arr[i], curr_max + arr[i])
        max_so_far = max(max_so_far,curr_max)

    return max_so_far

t = ii1()
for _ in range(t):
    n ,q = iia()
    arr = iia()
    ans=findLocalMaximaMinima(n,arr)
    flag=0
    if len(ans)>=2:
        if ans[0]<ans[1]:
            ans.pop(0)
    for i in range(len(ans)):
        if i%2==1:
            ans[i]=-ans[i]
    # print(ans)
    res=fun(ans,len(ans))
    print(res)


import sys
try:sys.stdin,sys.stdout=open('in.txt','r'),open('out.txt','w')
except:pass
ii1=lambda:int(sys.stdin.readline().strip()) # for interger
is1=lambda:sys.stdin.readline().strip() # for str
iia=lambda:list(map(int,sys.stdin.readline().strip().split())) # for List[int]
isa=lambda:sys.stdin.readline().strip().split() # for List[str]
mod=int(1e9 + 7);from collections import *;from math import *

###################### Start Here ######################
def findLocalMaximaMinima(n, arr):
    mx = []
    mn = []
    ans=[]
    if(arr[0] > arr[1]):
        mx.append(0)
        ans.append(arr[0])
    elif(arr[0] < arr[1]):
        mn.append(0)
        ans.append(arr[0])

    for i in range(1, n-1):

        if(arr[i-1] > arr[i] < arr[i + 1]):
            mn.append(arr[i])
            ans.append(arr[i])
        elif(arr[i-1] < arr[i] > arr[i + 1]):
            mx.append(i)
            ans.append(arr[i])
    if(arr[-1] > arr[-2]):
        mx.append(n-1)
        ans.append(arr[-1])
    elif(arr[-1] < arr[-2]):
        mn.append(n-1)
        ans.append(arr[-1])
    # print(ans)
    return ans
def fun(arr,n):
    max_so_far =arr[0]
    curr_max = arr[0]

    for i in range(1,n):
        curr_max = max(arr[i], curr_max + arr[i])
        max_so_far = max(max_so_far,curr_max)

    return max_so_far

t = ii1()
for _ in range(t):
    n ,q = iia()
    arr = iia()
    ans=findLocalMaximaMinima(n,arr)
    flag=0
    if len(ans)>=2:
        if ans[0]<ans[1]:
            ans.pop(0)
    for i in range(len(ans)):
        if i%2==1:
            ans[i]=-ans[i]
    # print(ans)
    res=fun(ans,len(ans))
    print(res)


T = int(input())
for case in range(T):
    n, q = map(int,input().split())
    a = list(map(int,input().split()))
    ans = 0
    i = 0
    # j = 0
    f = 0
    # mx = 0
    while True:
        # mx = max(mx,a[i])
        if f==0:
            while i+1<n and a[i]<a[i+1]:i+=1
            ans += a[i]
            f ^= 1
        else:
            while i+1<n and a[i]>a[i+1]:i+=1
            ans -= a[i]
            f ^= 1
        if i == n-1:
            break
    print(ans)


T = int(input())
for case in range(T):
    n, q = map(int,input().split())
    a = list(map(int,input().split()))
    ans = 0
    i = 0
    # j = 0
    f = 0
    # mx = 0
    while True:
        # mx = max(mx,a[i])
        if f==0:
            while i+1<n and a[i]<a[i+1]:i+=1
            ans += a[i]
            f ^= 1
        else:
            while i+1<n and a[i]>a[i+1]:i+=1
            if i!=n-1:
                ans -= a[i]
            f ^= 1
        if i == n-1:
            break
    print(ans)


for _ in range(int(input())):
    n, q = map(int, input().split())
    a = list(map(int, input().split()))
    if(n==1):
        print(a[0])
    cv = a[0]
    s = 0
    p = 0
    for i in range(1, n):
        if(p == 0):
            if(a[i] >= cv):
                cv = a[i]
            else:
                s += cv
                p = 1
                cv = a[i]
        else:
            if(a[i] <= cv):
                cv = a[i]
            else:
                s -= cv
                p = 0
                cv = a[i]
    if(p == 0) and (cv > 0):
        s += cv
    print(max(s, max(a)))


for _ in range(int(input())):
    n, q = map(int, input().split())
    a = list(map(int, input().split()))
    if(n==1):
        print(a[0])
    else:
        cv = a[0]
        s = 0
        p = 0
        for i in range(1, n):
            if(p == 0):
                if(a[i] >= cv):
                    cv = a[i]
                else:
                    s += cv
                    p = 1
                    cv = a[i]
            else:
                if(a[i] <= cv):
                    cv = a[i]
                else:
                    s -= cv
                    p = 0
                    cv = a[i]
        if(p == 0) and (cv > 0):
            s += cv
        print(max(s, max(a)))


for _ in range(int(input())):
    n,q = map(int,input().split())
    l = list(map(int,input().split()))
    i = 0
    c = 0
    k = 1
    for i in range(1,n):
        if k%2 == 1:
            if l[i]<l[i-1]:
                c+=l[i-1]
                k+=1
            elif i == n-1:
                c+=l[i]
        else:
            if l[i] >l[i-1]:
                c-=l[i-1]
                k+=1
                if i == n-1:
                    c+=l[i]
    print(c)


for _ in range(int(input())):
    n,q = map(int,input().split())
    l = list(map(int,input().split()))
    i = 0
    c = 0
    k = 1
    for i in range(1,n):
        if k%2 == 1:
            if l[i]<l[i-1]:
                c+=l[i-1]
                k+=1
            elif i == n-1:
                c+=l[i]
        else:
            if l[i] >l[i-1]:
                c-=l[i-1]
                k+=1
                if i == n-1:
                    c+=l[i]
    if len(l) == 1:
        c = l[0]
    print(c)


for _ in range(int(input())):
    n,q = map(int,input().split())
    l = list(map(int,input().split()))
    i = 0
    c = 0
    k = 1
    for i in range(1,n):
        if k%2 == 1:
            if l[i]<l[i-1]:
                c+=l[i-1]
                k+=1
            elif i == n-1:
                c+=l[i]
        else:
            if l[i] >l[i-1]:
                c-=l[i-1]
                k+=1
    print(c)


import math, sys
from collections import defaultdict, Counter, deque
from functools import reduce

INF = float('inf')
MOD = int(1e9) + 7

def solve():
	n, q = vars()
	arr = array()

	if n == 1:
		print(arr[0])
		return

	dec = False
	ans = 0
	i = 1

	while i < n:
		if not dec:
			while i < n and arr[i - 1] <= arr[i]:
				i += 1
			ans += arr[i - 1]
		else:
			while i < n and arr[i - 1] >= arr[i]:
				i += 1
			if i < n:
				ans -= arr[i - 1]

		dec = not dec

	print(ans)
	return

def main():
	t = 1
	t = int(input())
	for _ in range(t):
		solve()

def gcd(a, b):
	while b:
		a, b = b, a % b
	return a

def input():
	return sys.stdin.readline().rstrip('\n').strip()

def print(*args, sep=' ', end='\n'):
	first = True
	for arg in args:
		if not first:
			sys.stdout.write(str(sep))
		sys.stdout.write(str(arg))
		first = False

	sys.stdout.write(end)

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

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

if __name__ == '__main__':

	main()


import math, sys
from collections import defaultdict, Counter, deque
from functools import reduce

INF = float('inf')
MOD = int(1e9) + 7

def solve():
	n, q = vars()
	arr = array()

	dec = False
	ans = 0
	i = 1

	while i < n:
		if not dec:
			while i < n and arr[i - 1] <= arr[i]:
				i += 1
			ans += arr[i - 1]
		else:
			while i < n and arr[i - 1] >= arr[i]:
				i += 1
			if i < n:
				ans -= arr[i - 1]

		dec = not dec

	print(ans)

def main():
	t = 1
	t = int(input())
	for _ in range(t):
		solve()

def gcd(a, b):
	while b:
		a, b = b, a % b
	return a

def input():
	return sys.stdin.readline().rstrip('\n').strip()

def print(*args, sep=' ', end='\n'):
	first = True
	for arg in args:
		if not first:
			sys.stdout.write(str(sep))
		sys.stdout.write(str(arg))
		first = False

	sys.stdout.write(end)

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

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

if __name__ == '__main__':

	main()


import math, sys
from collections import defaultdict, Counter, deque
from functools import reduce

INF = float('inf')
MOD = int(1e9) + 7

def solve():
	n, q = vars()
	arr = array()

	dec = False
	ans = 0
	i = 1

	while i < n:
		if not dec:
			while i < n and arr[i - 1] <= arr[i]:
				i += 1
			ans += arr[i - 1]
		else:
			while i < n and arr[i - 1] >= arr[i]:
				i += 1
			ans -= arr[i - 1]

		dec = not dec

	print(max(ans, max(arr)))

def main():
	t = 1
	t = int(input())
	for _ in range(t):
		solve()

def gcd(a, b):
	while b:
		a, b = b, a % b
	return a

def input():
	return sys.stdin.readline().rstrip('\n').strip()

def print(*args, sep=' ', end='\n'):
	first = True
	for arg in args:
		if not first:
			sys.stdout.write(str(sep))
		sys.stdout.write(str(arg))
		first = False

	sys.stdout.write(end)

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

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

if __name__ == '__main__':

	main()


import sys
read = lambda: sys.stdin.readline().strip()
readi = lambda: map(int, read().split())
from collections import *
from math import *

for _ in range(int(read())):
    n, q = readi()
    nums = list(readi())

    prefixMax = [nums[0]] * n
    for i in range(1, n):
        prefixMax[i] = max(prefixMax[i-1], nums[i])

    suffixMin = [nums[-1]] * n
    for i in range(2, n+1):
        suffixMin[i-1] = min(suffixMin[i-2], nums[-i])

    suffixMin = suffixMin[::-1]
    suffixMin.append(0)

    suffixMin = suffixMin[::-1]
    prefixMax = prefixMax[::-1]

    s = set()
    ans = 0
    for i in range(n):
        if prefixMax[i] > suffixMin[i] and prefixMax[i] not in s and suffixMin[i] not in s:
            ans += prefixMax[i] - suffixMin[i]
            s.add(prefixMax[i])
            s.add(suffixMin[i])

    print(ans)


import sys
read = lambda: sys.stdin.readline().strip()
readi = lambda: map(int, read().split())
from collections import *
from math import *

for _ in range(int(read())):
    n, q = readi()
    nums = list(readi())

    ans = 0
    temp = [nums[0]]
    for i in range(1, n):

        if temp[-1] < nums[i]:
            # print(temp)
            if len(temp) > 1:
                ans += temp[0] - temp[-1]
            temp = list()
        temp.append(nums[i])

    # print(temp)
    print(ans + temp[0])


t=int(input())
while t:
    t-=1
    n,q=map(int,input().split())
    a=list(map(int,input().split()))
    z=0
    s=0
    k,zz=0,0
    m=max(a)
    if n==2:
        print(m)
        continue
    for i in range(1,n):
        if z==0 and a[i-1]>a[i]:
            zz=a[i-1]
            s+=zz
            z=1
        elif z==1 and a[i-1]<a[i] and zz>a[i-1]:
            s-=a[i-1]
            z=0
            k=i-1
    if z==0:
        s+=max(a[k:])
    print(max(s,m))


t=int(input())
while t:
    t-=1
    n,q=map(int,input().split())
    a=list(map(int,input().split()))
    s=a[0]
    for i in range(1,n):
        s+=max(0,a[i]-a[i-1])
    print(s)


import sys,math
from collections import Counter,deque,defaultdict
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

for _ in range(inp()):
    n,q = inpl()
    a = inpl()
    up = True
    res = []
    if n == 1:
        print(a[0])
        continue
    if a[1]-a[0] < 0:
        res.append(a[0])
        up = False
    for i in range(1,n-1):
        now = True if a[i+1] - a[i] > 0 else False
        if now != up:
            res.append(a[i])
            up = now
    if up: res.append(a[-1])
    ans = 0
    for i in range(len(res)):
        if i%2:
            ans -= res[i]
        else:
            ans += res[i]
    # print(*res)
    print(ans)


import sys,math
from collections import Counter,deque,defaultdict
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

for _ in range(inp()):
    n,q = inpl()
    a = inpl()
    up = True
    res = []
    if a[1]-a[0] <= 0:
        res.append(a[0])
        if a[1] - a[0] < 0:
            up = False
    for i in range(1,n-1):
        now = True if a[i+1] - a[i] > 0 else False
        if now != up:
            res.append(a[i])
            up = now
    if up: res.append(a[-1])
    ans = 0
    for i in range(len(res)):
        if i%2:
            ans -= res[i]
        else:
            ans += res[i]
    print(ans)


import sys,math
from collections import Counter,deque,defaultdict
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

for _ in range(inp()):
    n,q = inpl()
    a = inpl()
    up = True
    res = []
    if n == 1:
        print(a[0])
        quit()
    if a[1]-a[0] <= 0:
        res.append(a[0])
        if a[1] - a[0] < 0:
            up = False
    for i in range(1,n-1):
        now = True if a[i+1] - a[i] > 0 else False
        if now != up:
            res.append(a[i])
            up = now
    if up: res.append(a[-1])
    ans = 0
    for i in range(len(res)):
        if i%2:
            ans -= res[i]
        else:
            ans += res[i]
    print(ans)


import math
from sys import stdin
from sys import setrecursionlimit
setrecursionlimit(1000000)
def put():  return  map(int, stdin.readline().split())
def recur(l,ind,parity,dp):
	if(dp[ind][parity]==-1):
		if(ind==n):
			dp[ind][parity]=0
		elif(parity==0):
			dp[ind][parity]=max(l[ind]+recur(l,ind+1,1,dp),recur(l,ind+1,0,dp))
		else:
			dp[ind][parity]=max(-l[ind]+recur(l,ind+1,0,dp),recur(l,ind+1,1,dp))
	return dp[ind][parity]

for _ in range(int(input())):
	# n=int(input())
	n,k=put()
	l=list(put())
	dp=[[-1 for i in range(2)] for i in range(n+1)]
	print(recur(l,0,0,dp))


import math
from sys import stdin
from sys import setrecursionlimit
setrecursionlimit(100000)
def put():  return  map(int, stdin.readline().split())
def recur(l,ind,parity,dp):
	if(dp[ind][parity]==-1):
		if(ind==n):
			dp[ind][parity]=0
		elif(parity==0):
			dp[ind][parity]=max(l[ind]+recur(l,ind+1,1,dp),recur(l,ind+1,0,dp))
		else:
			dp[ind][parity]=max(-l[ind]+recur(l,ind+1,0,dp),recur(l,ind+1,1,dp))
	return dp[ind][parity]

for _ in range(int(input())):
	# n=int(input())
	n,k=put()
	l=list(put())
	dp=[[-1 for i in range(n+10)] for i in range(s10)]
	print(recur(l,0,0,dp))


import math
from sys import stdin
from sys import setrecursionlimit
setrecursionlimit(500000)
def put():  return  map(int, stdin.readline().split())
def recur(l,ind,parity,dp):
	if(dp[ind][parity]==-1):
		if(ind==n):
			dp[ind][parity]=0
		elif(parity==0):
			dp[ind][parity]=max(l[ind]+recur(l,ind+1,1,dp),recur(l,ind+1,0,dp))
		else:
			dp[ind][parity]=max(-l[ind]+recur(l,ind+1,0,dp),recur(l,ind+1,1,dp))
	return dp[ind][parity]

for _ in range(int(input())):
	# n=int(input())
	n,k=put()
	l=list(put())
	dp=[[-1 for i in range(n+1)] for i in range(2)]
	print(recur(l,0,0,dp))


import math
from sys import stdin
from sys import setrecursionlimit
setrecursionlimit(100000)
def put():  return  map(int, stdin.readline().split())
def recur(l,ind,parity,dp):
	if(dp[ind][parity]==-1):
		if(ind==n):
			dp[ind][parity]=0
		elif(parity==0):
			dp[ind][parity]=max(l[ind]+recur(l,ind+1,1,dp),recur(l,ind+1,0,dp))
		else:
			dp[ind][parity]=max(-l[ind]+recur(l,ind+1,0,dp),recur(l,ind+1,1,dp))
	return dp[ind][parity]

for _ in range(int(input())):
	# n=int(input())
	n,k=put()
	l=list(put())
	dp=[[-1 for i in range(2)] for i in range(n+1)]
	print(recur(l,0,0,dp))


import math
from sys import stdin
from sys import setrecursionlimit
setrecursionlimit(100000)
def put():  return  map(int, stdin.readline().split())
for _ in range(int(input())):
	# n=int(input())
	n,k=put()
	l=list(put())
	dp=[[-1 for i in range(5)] for i in range(n+5)]
	# prin(dp[3][1])
	for ind in range(n+1):
		for parity in range(2):
			if(ind==0):
				dp[ind][parity]=0
			elif(parity==0):
				dp[ind][parity]=max(l[ind-1]+dp[ind-1][1],dp[ind-1][0])
			else:
				dp[ind][parity]=max(-l[ind-1]+dp[ind-1][0],dp[ind-1][1])
	print(dp[n][0])


import math
from sys import stdin
from sys import setrecursionlimit
setrecursionlimit(1000000)
def put():  return  map(int, stdin.readline().split())
def recur(l,ind,parity,dp):
	if(dp[ind][parity]==-1):
		if(ind==n):
			dp[ind][parity]=0
		elif(parity==0):
			dp[ind][parity]=max(l[ind]+recur(l,ind+1,1,dp),recur(l,ind+1,0,dp))
		else:
			dp[ind][parity]=max(-l[ind]+recur(l,ind+1,0,dp),recur(l,ind+1,1,dp))
	return dp[ind][parity]

for _ in range(int(input())):
	# n=int(input())
	n,k=put()
	l=list(put())
	dp=[[-1 for i in range(n+10)] for i in range(10)]
	print(recur(l,0,0,dp))


import math
from sys import stdin
from sys import setrecursionlimit
setrecursionlimit(100000)
def put():  return  map(int, stdin.readline().split())
def recur(l,ind,parity,dp):
	if(dp[ind][parity]==-1):
		if(ind==n):
			dp[ind][parity]=0
		elif(parity==0):
			dp[ind][parity]=max(l[ind]+recur(l,ind+1,1,dp),recur(l,ind+1,0,dp))
		else:
			dp[ind][parity]=max(-l[ind]+recur(l,ind+1,0,dp),recur(l,ind+1,1,dp))
	return dp[ind][parity]

for _ in range(int(input())):
	# n=int(input())
	n,k=put()
	l=list(put())
	dp=[[-1 for i in range(n+10)] for i in range(10)]
	print(recur(l,0,0,dp))


import math
from sys import stdin
from sys import setrecursionlimit
setrecursionlimit(1000000)
def put():  return  map(int, stdin.readline().split())
def recur(l,ind,parity,dp):
	if(dp[ind][parity]==-1):
		if(ind==n):
			dp[ind][parity]=0
		elif(parity==0):
			dp[ind][parity]=max(l[ind]+recur(l,ind+1,1,dp),recur(l,ind+1,0,dp))
		else:
			dp[ind][parity]=max(-l[ind]+recur(l,ind+1,0,dp),recur(l,ind+1,1,dp))
	return dp[ind][parity]

for _ in range(int(input())):
	# n=int(input())
	n,k=put()
	l=list(put())
	dp=[[-1 for i in range(n+1)] for i in range(2)]
	print(recur(l,0,0,dp))


import math
from sys import stdin
from sys import setrecursionlimit
# setrecursionlimit(1000000)
def put():  return  map(int, stdin.readline().split())
def recur(l,ind,parity,dp):
	if(dp[ind][parity]==-1):
		if(ind==n):
			dp[ind][parity]=0
		elif(parity==0):
			dp[ind][parity]=max(l[ind]+recur(l,ind+1,1,dp),recur(l,ind+1,0,dp))
		else:
			dp[ind][parity]=max(-l[ind]+recur(l,ind+1,0,dp),recur(l,ind+1,1,dp))
	return dp[ind][parity]

for _ in range(int(input())):
	# n=int(input())
	n,k=put()
	l=list(put())
	dp=[[-1 for i in range(2)] for i in range(n+1)]
	print(recur(l,0,0,dp))


import math
from sys import stdin
from sys import setrecursionlimit
setrecursionlimit(10000000)
def put():  return  map(int, stdin.readline().split())
for _ in range(int(input())):
	# n=int(input())
	n,k=put()
	l=list(put())
	dp=[[-1 for i in range(5)] for i in range(n+5)]
	# prin(dp[3][1])
	for ind in range(n+1):
		for parity in range(2):
			if(ind==0):
				dp[ind][parity]=0
			elif(parity==0):
				dp[ind][parity]=max(l[ind-1]+dp[ind-1][1],dp[ind-1][0])
			else:
				dp[ind][parity]=max(-l[ind-1]+dp[ind-1][0],dp[ind-1][1])
	print(dp[n][0])


import math
from sys import stdin
from sys import setrecursionlimit
setrecursionlimit(10000000)
def put():  return  map(int, stdin.readline().split())
def recur(l,ind,parity,dp):
	if(dp[ind][parity]==-1):
		if(ind==n):
			dp[ind][parity]=0
		elif(parity==0):
			dp[ind][parity]=max(l[ind]+recur(l,ind+1,1,dp),recur(l,ind+1,0,dp))
		else:
			dp[ind][parity]=max(-l[ind]+recur(l,ind+1,0,dp),recur(l,ind+1,1,dp))
	return dp[ind][parity]

for _ in range(int(input())):
	# n=int(input())
	n,k=put()
	l=list(put())
	dp=[[-1 for i in range(2)] for i in range(n+1)]
	print(recur(l,0,0,dp))


import math
from sys import stdin
from sys import setrecursionlimit
setrecursionlimit(100000)
def put():  return  map(int, stdin.readline().split())
def recur(l,ind,parity,dp):
	if(dp[ind][parity]==-1):
		if(ind==n):
			dp[ind][parity]=0
		elif(parity==0):
			dp[ind][parity]=max(l[ind]+recur(l,ind+1,1,dp),recur(l,ind+1,0,dp))
		else:
			dp[ind][parity]=max(-l[ind]+recur(l,ind+1,0,dp),recur(l,ind+1,1,dp))
	return dp[ind][parity]

for _ in range(int(input())):
	# n=int(input())
	n,k=put()
	l=list(put())
	dp=[[-1 for i in range(n+10)] for i in range(n+10)]
	print(recur(l,0,0,dp))


from sys import stdin, stdout
import math,sys,heapq
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import random
import bisect as bi
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
    #------------------Sublime--------------------------------------#
    sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
    def I():return (int(input()))
    def In():return(map(int,input().split()))
else:
    #------------------PYPY FAst I/o--------------------------------#
    def I():return (int(stdin.readline()))
    def In():return(map(int,stdin.readline().split()))
#sys.setrecursionlimit(1500)
def dict(a):
    d={}
    for x in a:
        if d.get(x,-1)!=-1:
            d[x]+=1
        else:
            d[x]=1
    return d

def find_gt(a, x):
    'Find leftmost value greater than x'
    i = bi.bisect_left(a, x)
    if i != len(a):
        return i
    else:
        return -1

def main():
    try:
        n,q=In()
        l=list(In())
        ans=0
        dp1,dp2=0,0
        for x in range(n):
            if x==0:
                dp1=l[x]
                ans=max(dp1,dp2,ans)
            elif x==1:
                dp2=l[x]
                ans=max(dp1,dp2,ans)
            else:
                if x%2==1:
                    dp1=max(dp2+l[x],dp1)
                else:
                    dp2=max(dp2,dp1-l[x])
                ans=max(dp1,dp2)
        print(ans)
    except:
        pass

M = 998244353
P = 1000000007

if __name__ == '__main__':
    for _ in range(I()):main()
    #for _ in range(1):main()


from sys import stdin, stdout
import math,sys,heapq
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import random
import bisect as bi
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
    #------------------Sublime--------------------------------------#
    sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
    def I():return (int(input()))
    def In():return(map(int,input().split()))
else:
    #------------------PYPY FAst I/o--------------------------------#
    def I():return (int(stdin.readline()))
    def In():return(map(int,stdin.readline().split()))
#sys.setrecursionlimit(1500)
def dict(a):
    d={}
    for x in a:
        if d.get(x,-1)!=-1:
            d[x]+=1
        else:
            d[x]=1
    return d

def find_gt(a, x):
    'Find leftmost value greater than x'
    i = bi.bisect_left(a, x)
    if i != len(a):
        return i
    else:
        return -1

def main():
    try:
        n,q=In()
        l=list(In())
        ans=0
        last=[]
        q=0
        if n==1:
            print(l[0])
        elif n==2:
            print(max(l))
        else:
            last=[l[0]]
            for x in range(1,n-1):
                if l[x-1]<l[x] and l[x]>l[x+1]:
                    last.append(l[x])
                elif l[x-1]>l[x] and l[x+1]>l[x]:
                    last.append(l[x])
            last.append(l[-1])
            #print(last)
            n1=len(last)
            for x in range(n1):
                su=0
                q=0
                for j in range(x,n1):
                    if q==0:
                        su+=last[j]
                        q=1
                    else:
                        su-=last[j]
                        q=0

                    ans=max(su,ans)
            print(ans)
    except:
        pass

M = 998244353
P = 1000000007

if __name__ == '__main__':
    for _ in range(I()):main()
    #for _ in range(1):main()


from sys import stdin, stdout
import math,sys,heapq
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import random
import bisect as bi
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
    #------------------Sublime--------------------------------------#
    sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
    def I():return (int(input()))
    def In():return(map(int,input().split()))
else:
    #------------------PYPY FAst I/o--------------------------------#
    def I():return (int(stdin.readline()))
    def In():return(map(int,stdin.readline().split()))
#sys.setrecursionlimit(1500)
def dict(a):
    d={}
    for x in a:
        if d.get(x,-1)!=-1:
            d[x]+=1
        else:
            d[x]=1
    return d

def find_gt(a, x):
    'Find leftmost value greater than x'
    i = bi.bisect_left(a, x)
    if i != len(a):
        return i
    else:
        return -1

def main():
    try:
        n,q=In()
        l=list(In())
        ans=0
        last=[]
        q=0
        if n==1:
            print(l[0])
        elif n==2:
            print(max(l))
        else:
            last=[l[0]]
            for x in range(1,n-1):
                if l[x-1]<l[x] and l[x]>l[x+1]:
                    last.append(l[x])
                elif l[x-1]>l[x] and l[x+1]>l[x]:
                    last.append(l[x])
            last.append(l[-1])
            print(last)
            n1=len(last)
            for x in range(n1):
                su=0
                q=0
                for j in range(x,n1):
                    if q==0:
                        su+=last[j]
                        q=1
                    else:
                        su-=last[j]
                        q=0
                    if su>ans:
                        print(x,j)
                    ans=max(su,ans)
            print(ans)
    except:
        pass

M = 998244353
P = 1000000007

if __name__ == '__main__':
    for _ in range(I()):main()
    #for _ in range(1):main()


from sys import stdin, stdout
import math,sys,heapq
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import random
import bisect as bi
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
    #------------------Sublime--------------------------------------#
    sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
    def I():return (int(input()))
    def In():return(map(int,input().split()))
else:
    #------------------PYPY FAst I/o--------------------------------#
    def I():return (int(stdin.readline()))
    def In():return(map(int,stdin.readline().split()))
#sys.setrecursionlimit(1500)
def dict(a):
    d={}
    for x in a:
        if d.get(x,-1)!=-1:
            d[x]+=1
        else:
            d[x]=1
    return d

def find_gt(a, x):
    'Find leftmost value greater than x'
    i = bi.bisect_left(a, x)
    if i != len(a):
        return i
    else:
        return -1

def main():
    try:
        n,q=In()
        l=list(In())
        ans=0
        last=[]
        q=0
        if n==1:
            print(l)
        elif n==2:
            print(max(l))
        else:
            last=[l[0]]
            for x in range(1,n-1):
                if l[x-1]<l[x] and l[x]>l[x+1]:
                    last.append(l[x])
                elif l[x-1]>l[x] and l[x+1]>l[x]:
                    last.append(l[x])
            last.append(l[-1])
            #print(last)
            n1=len(last)
            for x in range(n1):
                su=0
                q=0
                for j in range(x,n1):
                    if q==0:
                        su+=last[j]
                        q=1
                    else:
                        su-=last[j]
                        q=0
                    ans=max(su,ans)
            print(ans)
    except:
        pass

M = 998244353
P = 1000000007

if __name__ == '__main__':
    for _ in range(I()):main()
    #for _ in range(1):main()


from sys import stdin, stdout
import math,sys,heapq
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import random
import bisect as bi
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
    #------------------Sublime--------------------------------------#
    sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
    def I():return (int(input()))
    def In():return(map(int,input().split()))
else:
    #------------------PYPY FAst I/o--------------------------------#
    def I():return (int(stdin.readline()))
    def In():return(map(int,stdin.readline().split()))
#sys.setrecursionlimit(1500)
def dict(a):
    d={}
    for x in a:
        if d.get(x,-1)!=-1:
            d[x]+=1
        else:
            d[x]=1
    return d

def find_gt(a, x):
    'Find leftmost value greater than x'
    i = bi.bisect_left(a, x)
    if i != len(a):
        return i
    else:
        return -1

def main():
    try:
        n,q=In()
        l=list(In())
        ans=0
        dp1,dp2=0,0
        for x in range(n):
            if x==0:
                dp1=l[x]
                ans=max(dp1,dp2,ans)
            elif x==1:
                dp2=l[x]
                ans=max(dp1,dp2,ans)
            else:
                if x%2==1:
                    dp1=max(dp2+l[x],dp1)
                else:
                    dp2=max(dp2,dp1-l[x])
                ans=max(dp1,dp2)
            print(ans)
    except:
        pass

M = 998244353
P = 1000000007

if __name__ == '__main__':
    for _ in range(I()):main()
    #for _ in range(1):main()


from sys import stdin, stdout
import math,sys,heapq
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import random
import bisect as bi
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
    #------------------Sublime--------------------------------------#
    sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
    def I():return (int(input()))
    def In():return(map(int,input().split()))
else:
    #------------------PYPY FAst I/o--------------------------------#
    def I():return (int(stdin.readline()))
    def In():return(map(int,stdin.readline().split()))
#sys.setrecursionlimit(1500)
def dict(a):
    d={}
    for x in a:
        if d.get(x,-1)!=-1:
            d[x]+=1
        else:
            d[x]=1
    return d

def find_gt(a, x):
    'Find leftmost value greater than x'
    i = bi.bisect_left(a, x)
    if i != len(a):
        return i
    else:
        return -1

def main():
    try:
        n,q=In()
        l=list(In())
        ans=l[0]
        for i in range(1,n):
            ans+=max(0,l[i]-l[i-1])
        print(ans)
    except:
        pass

M = 998244353
P = 1000000007

if __name__ == '__main__':
    for _ in range(I()):main()
    #for _ in range(1):main()


# from collections import Counter
def solve(n,l):
    ans=0
    if(n==1 or n==2):
        return max(l)

    if(l[1]<l[0]):
        ans=l[0]

    for i in range(1,n-1):
        if(l[i]>l[i-1] and l[i]>l[i+1]):
            ans+=l[i]
        if(l[i]<l[i-1] and l[i]<l[i+1]):
            ans-=l[i]
    if(l[n-1]>l[n-2]):
        ans+=l[n-1]
    return ans

t=int(input())
for _ in range(t):
    n,q=list(map(int,input().split()))

    l=list(map(int,input().split()))
    print(solve(n,l))


#include <bits/stdc++.h>
using namespace std;
int main(int argc, char *argv[]) {
  int lcs_len, i, j, k;
  string input_s, temp_s, key_str;
  cin >> input_s;
  lcs_len = input_s.length()-2;
  for(i = lcs_len-1; i >=0; i--)  {
    for(j = input_s.length()-1, k = i; input_s[k] == input_s[j] and k >= 0; j--, k--)
      ;
    if(k+1 == 0)  {
      key_str = input_s.substr(0, i+1);
      temp_s = input_s.substr(1, input_s.length()-2);
      if(temp_s.find(key_str) != string::npos)  {
        cout << key_str << endl;
        return 0;
      }
    }
  }
  cout << "Just a legend" << endl;
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main(int argc, char *argv[]) {
  int lcs_len, i, j, k;
  string input_s, find_back, find_mid, key_str;
  cin >> input_s;
  find_mid = input_s.substr(1, input_s.length()-2);
  lcs_len = input_s.length()-2;
  for(i = lcs_len; i >0; i--)  {
    key_str = input_s.substr(0, i);
    find_back = input_s.substr(input_s.length() - i, i);
    if(find_back.find(key_str) != string::npos and find_mid.find(key_str) != string::npos)  {
      cout << key_str << endl;
      return 0;
    }
  }
  cout << "Just a legend" << endl;
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main(int argc, char *argv[]) {
  int sp(-1), ep(-1);
  string input_s, output_t;
  cin >> input_s;
  for(int i = 1; i < input_s.length()-1; i++) {
    if(input_s[i] == input_s[0])  {
      sp = i;
      break;
    }
  }
  for(int i = 1; i < input_s.length()-1; i++) {
    if(input_s[i] == input_s[input_s.length()-1]) {
      if(i >= sp)
        ep = i;
    }
  }
  if(sp == -1 || ep == -1)  {
    cout << "Just a legend" << endl;
    return 0;
  }
  string ans(input_s.begin()+sp, input_s.begin()+ep+1);
  cout << ans << endl;
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main(int argc, char *argv[]) {
  int sp(-1), ep(-1);
  string input_s, output_t;
  cin >> input_s;
  for(int i = 1; i < input_s.length()-1; i++) {
    if(input_s[i] == input_s[0])  {
      sp = i;
      break;
    }
  }
  for(int i = 1; i < input_s.length()-1; i++) {
    if(input_s[i] == input_s[input_s.length()-1]) {
      if(i > sp)
        ep = i;
    }
  }
  if(sp == -1 || ep == -1)  {
    cout << "Just a lengend" << endl;
    return 0;
  }
  string ans(input_s.begin()+sp, input_s.begin()+ep+1);
  cout << ans << endl;
  return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define RHB (const int) 29 /* Rolling hash base */
#define MOD (const int) (1e9 + 7) /* Big Prime Moduler */
#define MSL (const int) (1e6 + 9) /* Maximum length of the input string */

int s_len;
string s;
long long hash_tab[MSL], base_tab[MSL];

void init() {

  cin >> s;
  s_len = s.length();

  /* strlen must leq to MSL */
  if(s_len > MSL)
    exit(1);

  /* prefix sum of hash values */
  hash_tab[0] = s[0] - 'a' + 1;
  for(int i = 1; i < s_len; i++)
    hash_tab[i] = (hash_tab[i - 1] * RHB + (s[i] - 'a' + 1)) % MOD;

  /* times list of hash base */
  base_tab[0] = 1;
  for(int i = 1; i < s_len; i++)
    base_tab[i] = (base_tab[i - 1] * RHB) % MOD;

}

/* left and right index of the string */

long long get_hv(int l, int r)  {

  if(l == 0)
    return hash_tab[r];

  long long ret = hash_tab[r] - ((hash_tab[l - 1] * base_tab[r - l + 1]) % MOD);

  return ret > 0 ? ret : (ret + MOD);
}

void solve()  {

  int sp, ep, temp;

  for(sp = s_len - 2, ep = 1; sp >= 0 and ep <= s_len - 1; sp--, ep++)  {

    if(get_hv(0, sp) == get_hv(ep, s_len - 1))  {

      temp = get_hv(0, sp);

      for(int i = 1; i <= s_len - sp - 2; i++)  {

        if(get_hv(i, i + sp) == temp)  {
          cout << s.substr(0, sp + 1) << endl;
          return;

        }
      }
    }
  }
  cout << "Just a legend" << endl;
}

int main(int argc, char **argv) {

  init();
  solve();
  return 0;

}


#include <bits/stdc++.h>
using namespace std;
int main(int argc, char *argv[]) {
  int lcs_len, i, j, k;
  string input_s, find_back, find_mid, key_str;
  cin >> input_s;
  find_mid = input_s.substr(1, input_s.length()-2);
  lcs_len = input_s.length()-2;
  for(i = lcs_len; i >0; i--)  {
    key_str = input_s.substr(0, i);
    find_back = input_s.substr(input_s.length() - i, i);
    if(i <= input_s.length() - i) {
      find_mid = input_s.substr(i, input_s.length() - i - i);
    }
    else
      continue;
    if(find_back.find(key_str) != string::npos and find_mid.find(key_str) != string::npos)  {
      cout << key_str << endl;
      return 0;
    }
  }
  cout << "Just a legend" << endl;
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main(int argc, char *argv[]) {
  int lcs_len, i, j, k;
  string input_s, find_back, find_mid, key_str;
  cin >> input_s;
  find_mid = input_s.substr(1, input_s.length()-2);
  lcs_len = input_s.length()-2;
  for(i = lcs_len; i >0; i--)  {
    if(input_s[i - 1] != input_s[input_s.length() - 1])
      continue;
    key_str = input_s.substr(0, i);
    find_back = input_s.substr(input_s.length() - i, i);
    if(find_back.find(key_str) != string::npos and find_mid.find(key_str) != string::npos)  {
      cout << key_str << endl;
      return 0;
    }
  }
  cout << "Just a legend" << endl;
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main(int argc, char *argv[]) {
  int lcs_len, i, j, k;
  string input_s, find_back, find_mid, key_str;
  cin >> input_s;
  find_mid = input_s.substr(1, input_s.length()-2);
  lcs_len = input_s.length()-2;
  for(i = lcs_len; i >0; i--)  {
    if(input_s[i - 1] != input_s[input_s.length() - 1])
        continue;
    key_str = input_s.substr(0, i);
    find_back = input_s.substr(input_s.length() - i, i);
    if(key_str != find_back)
      continue;

    if(find_back.find(key_str) != string::npos and find_mid.find(key_str) != string::npos)  {
      cout << key_str << endl;
      return 0;
    }
  }
  cout << "Just a legend" << endl;
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main(int argc, char *argv[]) {
  int lcs_len, i, j, k;
  string input_s, find_back, find_mid, key_str;
  cin >> input_s;
  find_mid = input_s.substr(1, input_s.length()-2);
  lcs_len = input_s.length()-2;
  for(i = lcs_len; i >0; i--)  {
    key_str = input_s.substr(0, i);
    find_back = input_s.substr(input_s.length() - i, i);
    cout << "key is " << key_str << endl << "find btween " << find_mid << endl << "find back " << find_back << endl;
    if(find_back.find(key_str) != string::npos and find_mid.find(key_str) != string::npos)  {
      cout << key_str << endl;
      return 0;
    }
  }
  cout << "Just a legend" << endl;
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int main(int argc, char *argv[]) {
  int sp(-1), ep(-1);
  string input_s, output_t;
  cin >> input_s;
  for(int i = 1; i < input_s.length()-1; i++) {
    if(input_s[i] == input_s[0])  {
      sp = i;
      break;
    }
  }
  for(int i = 1; i < input_s.length()-1; i++) {
    if(input_s[i] == input_s[input_s.length()-1]) {
      if(i > sp)
        ep = i;
    }
  }
  if(sp == -1 || ep == -1)  {
    cout << "Just a legend" << endl;
    return 0;
  }
  string ans(input_s.begin()+sp, input_s.begin()+ep+1);
  cout << ans << endl;
  return 0;
}


#include <bits/stdc++.h>

using namespace std;

//cout << setprecision(8) << fixed;
//

#define pb push_back
#define eb emplace_back
#define mp make_pair
#define pii pair<int, int>
#define fi first
#define se second
#define ull uint64_t
#define ll int64_t

const ll mod = 1e7;

int main() {
    string s;
    cin >> s;
    int n = s.size();
    if (n < 2) {
        cout << "Just a legend\n";
        return 0;
    }
    //find the longest substring s[1:] which is also a prefix
    int l = 0, h = n - 1;
    while (l < h) {
        int m = (l + h + 1) / 2;
        ll root = 0;
        for (int i = 0; i < m; ++i) {
            root = (root * 26 + s[i] - 'a') % mod;
        }
        ll hash = 0;
        for (int i = 1; i <= m; ++i) {
            hash = (hash * 26 + s[i] - 'a') % mod;
        }
        ll pw = 1;
        for (int i = 1; i < m; ++i) {
            pw = pw * 26 % mod;
        }
        bool ok = 0;
        for (int i = 1; i + m < n && !ok; ++i) {
            if (i > 1) {
                hash -= pw * (s[i - 1] - 'a');
                hash *= 26;
                hash += s[i + m - 1] - 'a';
                hash = (hash % mod + mod) % mod;
            }
            if (hash == root) {
                //check to see if they are actually equal
                bool same = 1;
                for (int j = 0; j < m && same; ++j) {
                    same &= s[j] == s[i + j];
                }
                ok = same;
            }
        }
        if (ok) l = m;
        else h = m - 1;
    }
    ll prehash = 0;
    ll sufhash = 0;
    ll pw = 1;
    vector<int> check;
    for (int i = 1; i <= l; ++i) {
        prehash = (prehash * 26 + s[i - 1] - 'a') % mod;
        sufhash = ((s[n - i] - 'a') * pw + sufhash) % mod;
        if (sufhash == prehash) {
            check.pb(i);
        }
        pw = (pw * 26) % mod;
    }
    int bst = 0;
    for (int i = check.size() - 1; i >= 0; --i) {
        bool same = 1;
        for (int j = 0; j < check[i] && same; ++j) {
            same &= s[j] == s[n - check[i] + j];
        }
        if (same) {
            bst = check[i];
            break;
        }
    }
    if (bst == 0) {
        cout << "Just a legend\n";
    } else {
        cout << s.substr(0, bst) << '\n';
    }
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

//cout << setprecision(8) << fixed;
//

#define pb push_back
#define eb emplace_back
#define mp make_pair
#define pii pair<int, int>
#define fi first
#define se second
#define ull uint64_t
#define ll int64_t

string s;
const ll mod = 1e9 + 7;
int kmp[1000000];
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> s;
    int n = s.size();
    int l = 0;
    for (int i = 1; i < n; ++i) {
        int p = kmp[i - 1];
        while (1) {
            if (s[p] == s[i]) {
                p++;
                break;
            } if (p == 0) break;
            else p = kmp[p];
        }
        kmp[i] = p;
        if (i <= n - 2) l = max(l, p);
    }
    cout << l << '\n';
    ll prehash = 0;
    ll sufhash = 0;
    ll pw = 1;
    int bst = 0;
    for (int i = 1; i <= l; ++i) {
        prehash = (prehash * 26 + s[i - 1] - 'a') % mod;
        sufhash = ((s[n - i] - 'a') * pw + sufhash) % mod;
        if (sufhash == prehash) bst = i;
        pw = (pw * 26) % mod;
    }
    if (bst == 0) {
        cout << "Just a legend\n";
    } else {
        cout << s.substr(0, bst) << '\n';
    }
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

//cout << setprecision(8) << fixed;
//

#define pb push_back
#define eb emplace_back
#define mp make_pair
#define pii pair<int, int>
#define fi first
#define se second
#define ull uint64_t
#define ll int64_t

string s;
const ll mod = 1e9 + 7;
int kmp[1000000];
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> s;
    int n = s.size();
    int l = 0;
    for (int i = 1; i < n; ++i) {
        int p = kmp[i - 1];
        while (1) {
            if (s[p] == s[i]) {
                p++;
                break;
            } if (p == 0) break;
            else p = kmp[p - 1];
        }
        kmp[i] = p;
        if (i <= n - 2) l = max(l, p);
    }
    //l is the longest substring of s[1:] that is also prefix of s
    //the final answer must be a prefix of s[0..l - 1] which is also suffix
    //
    int bst = kmp[n - 1];
    while (bst > l) bst = kmp[bst - 1];
    if (bst == 0) {
        cout << "Just a legend\n";
    } else {
        cout << s.substr(0, bst) << '\n';
    }
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

//cout << setprecision(8) << fixed;
//

#define pb push_back
#define eb emplace_back
#define mp make_pair
#define pii pair<int, int>
#define fi first
#define se second
#define ull uint64_t
#define ll int64_t

string s;
const ll mod = 1e9 + 7;
int kmp[1000000];
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> s;
    int n = s.size();
    int l = 0;
    for (int i = 1; i < n; ++i) {
        int p = kmp[i - 1];
        while (1) {
            if (s[p] == s[i]) {
                p++;
                break;
            } if (p == 0) break;
            else p = kmp[p];
        }
        kmp[i] = p;
        if (i <= n - 2) l = max(l, p);
    }
    ll prehash = 0;
    ll sufhash = 0;
    ll pw = 1;
    int bst = 0;
    for (int i = 1; i <= l; ++i) {
        prehash = (prehash * 26 + s[i - 1] - 'a') % mod;
        sufhash = ((s[n - i] - 'a') * pw + sufhash) % mod;
        if (sufhash == prehash) bst = i;
        pw = (pw * 26) % mod;
    }
    if (bst == 0) {
        cout << "Just a legend\n";
    } else {
        cout << s.substr(0, bst) << '\n';
    }
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

//cout << setprecision(8) << fixed;
//

#define pb push_back
#define eb emplace_back
#define mp make_pair
#define pii pair<int, int>
#define fi first
#define se second
#define ull uint64_t
#define ll int64_t

const ll mod = 999999999989LL;

int main() {
    string s;
    cin >> s;
    int n = s.size();
    if (n < 2) {
        cout << "Just a legend\n";
        return 0;
    }
    //find the longest substring s[1:] which is also a prefix
    int l = 0, h = n - 1;
    while (l < h) {
        int m = (l + h + 1) / 2;
        ll root = 0;
        for (int i = 0; i < m; ++i) {
            root = (root * 26 + s[i] - 'a') % mod;
        }
        ll hash = 0;
        for (int i = 1; i <= m; ++i) {
            hash = (hash * 26 + s[i] - 'a') % mod;
        }
        ll pw = 1;
        for (int i = 1; i < m; ++i) {
            pw = pw * 26 % mod;
        }
        bool ok = 0;
        for (int i = 1; i + m < n && !ok; ++i) {
            if (i > 1) {
                hash -= pw * (s[i - 1] - 'a');
                hash *= 26;
                hash += s[i + m - 1] - 'a';
                hash = (hash % mod + mod) % mod;
            }
            if (hash == root) {
                //check to see if they are actually equal
                bool same = 1;
                for (int j = 0; j < m && same; ++j) {
                    same &= s[j] == s[i + j];
                }
                ok = same;
            }
        }
        if (ok) l = m;
        else h = m - 1;
    }
    ll prehash = 0;
    ll sufhash = 0;
    ll pw = 1;
    vector<int> check;
    for (int i = 1; i <= l; ++i) {
        prehash = (prehash * 26 + s[i - 1] - 'a') % mod;
        sufhash = ((s[n - i] - 'a') * pw + sufhash) % mod;
        if (sufhash == prehash) {
            check.pb(i);
        }
        pw = (pw * 26) % mod;
    }
    int bst = 0;
    for (int i = check.size() - 1; i >= 0; --i) {
        bool same = 1;
        for (int j = 0; j < check[i] && same; ++j) {
            same &= s[j] == s[n - check[i] + j];
        }
        if (same) {
            bst = check[i];
            break;
        }
    }
    if (bst == 0) {
        cout << "Just a legend\n";
    } else {
        cout << s.substr(0, bst) << '\n';
    }
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

//cout << setprecision(8) << fixed;
//

#define pb push_back
#define eb emplace_back
#define mp make_pair
#define pii pair<int, int>
#define fi first
#define se second
#define ull uint64_t
#define ll int64_t

const ll mod = 421412341324321ll;

int main() {
    string s;
    cin >> s;
    int n = s.size();
    if (n < 2) {
        cout << "Just a legend\n";
        return 0;
    }
    //find the longest substring s[1:] which is also a prefix
    int l = 0, h = n - 1;
    while (l < h) {
        int m = (l + h + 1) / 2;
        ll root = 0;
        for (int i = 0; i < m; ++i) {
            root = (root * 26 + s[i] - 'a') % mod;
        }
        ll hash = 0;
        for (int i = 1; i <= m; ++i) {
            hash = (hash * 26 + s[i] - 'a') % mod;
        }
        ll pw = 1;
        for (int i = 1; i < m; ++i) {
            pw = pw * 26 % mod;
        }
        bool ok = 0;
        for (int i = 1; i + m < n && !ok; ++i) {
            if (i > 1) {
                hash -= pw * (s[i - 1] - 'a');
                hash *= 26;
                hash += s[i + m - 1] - 'a';
                hash = (hash % mod + mod) % mod;
            }
            if (hash == root) {
                //check to see if they are actually equal
                bool same = 1;
                for (int j = 0; j < m && same; ++j) {
                    same &= s[j] == s[i + j];
                }
                ok = same;
            }
        }
        if (ok) l = m;
        else h = m - 1;
    }
    ll prehash = 0;
    ll sufhash = 0;
    ll pw = 1;
    vector<int> check;
    for (int i = 1; i <= l; ++i) {
        prehash = (prehash * 26 + s[i - 1] - 'a') % mod;
        sufhash = ((s[n - i] - 'a') * pw + sufhash) % mod;
        if (sufhash == prehash) {
            check.pb(i);
        }
        pw = (pw * 26) % mod;
    }
    int bst = 0;
    for (int i = check.size() - 1; i >= 0; --i) {
        bool same = 1;
        for (int j = 0; j < check[i] && same; ++j) {
            same &= s[j] == s[n - check[i] + j];
        }
        if (same) {
            bst = check[i];
            break;
        }
    }
    if (bst == 0) {
        cout << "Just a legend\n";
    } else {
        cout << s.substr(0, bst) << '\n';
    }
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

//cout << setprecision(8) << fixed;
//

#define pb push_back
#define eb emplace_back
#define mp make_pair
#define pii pair<int, int>
#define fi first
#define se second
#define ull uint64_t
#define ll int64_t

const ll mod = 1e9 + 7;

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    string s;
    cin >> s;
    int n = s.size();
    if (n < 2) {
        cout << "Just a legend\n";
        return 0;
    }
    //find the longest substring s[1:] which is also a prefix
    int l = 0, h = n - 1;
    while (l < h) {
        int m = (l + h + 1) / 2;
        ll root = 0;
        for (int i = 0; i < m; ++i) {
            root = (root * 26 + s[i] - 'a') % mod;
        }
        ll hash = 0;
        for (int i = 1; i <= m; ++i) {
            hash = (hash * 26 + s[i] - 'a') % mod;
        }
        ll pw = 1;
        for (int i = 1; i < m; ++i) {
            pw = pw * 26 % mod;
        }
        bool ok = 0;
        for (int i = 1; i + m < n && !ok; ++i) {
            if (i > 1) {
                hash -= pw * (s[i - 1] - 'a');
                hash *= 26;
                hash += s[i + m - 1] - 'a';
                hash = (hash % mod + mod) % mod;
            }
            ok = hash == root;
        }
        if (ok) l = m;
        else h = m - 1;
    }
    ll prehash = 0;
    ll sufhash = 0;
    ll pw = 1;
    int bst = 0;
    for (int i = 1; i <= l; ++i) {
        prehash = (prehash * 26 + s[i - 1] - 'a') % mod;
        sufhash = ((s[n - i] - 'a') * pw + sufhash) % mod;
        if (sufhash == prehash) bst = i;
        pw = (pw * 26) % mod;
    }
    if (bst == 0) {
        cout << "Just a legend\n";
    } else {
        cout << s.substr(0, bst) << '\n';
    }
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

//cout << setprecision(8) << fixed;
//

#define pb push_back
#define eb emplace_back
#define mp make_pair
#define pii pair<int, int>
#define fi first
#define se second
#define ull uint64_t
#define ll int64_t

const ll mod = 421412341324321ll;

int main() {
    string s;
    cin >> s;
    int n = s.size();
    if (n < 2) {
        cout << "Just a legend\n";
        return 0;
    }
    //find the longest substring s[1:] which is also a prefix
    int l = 0, h = n - 1;
    while (l < h) {
        int m = (l + h + 1) / 2;
        ll root = 0;
        for (int i = 0; i < m; ++i) {
            root = (root * 26 + s[i] - 'a') % mod;
        }
        ll hash = 0;
        for (int i = 1; i <= m; ++i) {
            hash = (hash * 26 + s[i] - 'a') % mod;
        }
        ll pw = 1;
        for (int i = 1; i < m; ++i) {
            pw = pw * 26 % mod;
        }
        bool ok = 0;
        for (int i = 1; i + m < n && !ok; ++i) {
            if (i > 1) {
                hash -= pw * (s[i - 1] - 'a');
                hash *= 26;
                hash += s[i + m - 1] - 'a';
                hash = (hash % mod + mod) % mod;
            }
            if (hash == root) {
                //check to see if they are actually equal
                bool same = 1;
                for (int j = 0; j < m && same; ++j) {
                    break;
                    same &= s[j] == s[i + j];
                }
                ok = same;
            }
        }
        if (ok) l = m;
        else h = m - 1;
    }
    ll prehash = 0;
    ll sufhash = 0;
    ll pw = 1;
    vector<int> check;
    for (int i = 1; i <= l; ++i) {
        prehash = (prehash * 26 + s[i - 1] - 'a') % mod;
        sufhash = ((s[n - i] - 'a') * pw + sufhash) % mod;
        if (sufhash == prehash) {
            check.pb(i);
        }
        pw = (pw * 26) % mod;
    }
    int bst = 0;
    for (int i = check.size() - 1; i >= 0; --i) {
        bool same = 1;
        for (int j = 0; j < check[i] && same; ++j) {
            break;
            same &= s[j] == s[n - check[i] + j];
        }
        if (same) {
            bst = check[i];
            break;
        }
    }
    if (bst == 0) {
        cout << "Just a legend\n";
    } else {
        cout << s.substr(0, bst) << '\n';
    }
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

//cout << setprecision(8) << fixed;
//

#define pb push_back
#define eb emplace_back
#define mp make_pair
#define pii pair<int, int>
#define fi first
#define se second
#define ull uint64_t
#define ll int64_t

string s;
const ll mod = 1e9 + 7;
int kmp[1000000];
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> s;
    int n = s.size();
    int l = 0;
    for (int i = 1; i < n; ++i) {
        int p = kmp[i - 1];
        while (1) {
            if (s[p] == s[i]) {
                p++;
                break;
            } if (p == 0) break;
            else p = kmp[p - 1];
        }
        kmp[i] = p;
        if (i <= n - 2) l = max(l, p);
    }
    ll prehash = 0;
    ll sufhash = 0;
    ll pw = 1;
    int bst = 0;
    for (int i = 1; i <= l; ++i) {
        prehash = (prehash * 26 + s[i - 1] - 'a') % mod;
        sufhash = ((s[n - i] - 'a') * pw + sufhash) % mod;
        if (sufhash == prehash) bst = i;
        pw = (pw * 26) % mod;
    }
    if (bst == 0) {
        cout << "Just a legend\n";
    } else {
        cout << s.substr(0, bst) << '\n';
    }
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

//cout << setprecision(8) << fixed;
//

#define pb push_back
#define eb emplace_back
#define mp make_pair
#define pii pair<int, int>
#define fi first
#define se second
#define ull uint64_t
#define ll int64_t

string s;
const ll mod = 1e9 + 7;
int kmp[1000000];
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> s;
    int n = s.size();
    int l = 0;
    for (int i = 1; i < n; ++i) {
        int p = kmp[i - 1];
        while (1) {
            if (s[p] == s[i]) {
                p++;
                break;
            } if (p == 0) break;
            else p = kmp[p];
        }
        kmp[i] = p;
        if (i <= n - 2) l = p;
    }
    ll prehash = 0;
    ll sufhash = 0;
    ll pw = 1;
    int bst = 0;
    for (int i = 1; i <= l; ++i) {
        prehash = (prehash * 26 + s[i - 1] - 'a') % mod;
        sufhash = ((s[n - i] - 'a') * pw + sufhash) % mod;
        if (sufhash == prehash) bst = i;
        pw = (pw * 26) % mod;
    }
    if (bst == 0) {
        cout << "Just a legend\n";
    } else {
        cout << s.substr(0, bst) << '\n';
    }
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

//cout << setprecision(8) << fixed;
//

#define pb push_back
#define eb emplace_back
#define mp make_pair
#define pii pair<int, int>
#define fi first
#define se second
#define ull uint64_t
#define ll int64_t

const ll mod = 421412341324321ll;

int main() {
    string s;
    cin >> s;
    int n = s.size();
    if (n < 2) {
        cout << "Just a legend\n";
        return 0;
    }
    //find the longest substring s[1:] which is also a prefix
    int l = 0, h = n - 1;
    while (l < h) {
        int m = (l + h + 1) / 2;
        ll root = 0;
        for (int i = 0; i < m; ++i) {
            root = (root * 26 + s[i] - 'a') % mod;
        }
        ll hash = 0;
        for (int i = 1; i <= m; ++i) {
            hash = (hash * 26 + s[i] - 'a') % mod;
        }
        ll pw = 1;
        for (int i = 1; i < m; ++i) {
            pw = pw * 26 % mod;
        }
        bool ok = 0;
        for (int i = 1; i + m < n && !ok; ++i) {
            if (i > 1) {
                hash -= pw * (s[i - 1] - 'a');
                hash *= 26;
                hash += s[i + m - 1] - 'a';
                hash = (hash % mod + mod) % mod;
            }
            if (hash == root) {
                //check to see if they are actually equal
                bool same = 1;
                for (int j = 0; j < m && same; ++j) {
                    same &= s[j] == s[i + j];
                }
                same = 1;
                ok = same;
            }
        }
        if (ok) l = m;
        else h = m - 1;
    }
    ll prehash = 0;
    ll sufhash = 0;
    ll pw = 1;
    vector<int> check;
    for (int i = 1; i <= l; ++i) {
        prehash = (prehash * 26 + s[i - 1] - 'a') % mod;
        sufhash = ((s[n - i] - 'a') * pw + sufhash) % mod;
        if (sufhash == prehash) {
            check.pb(i);
        }
        pw = (pw * 26) % mod;
    }
    int bst = 0;
    for (int i = check.size() - 1; i >= 0; --i) {
        bool same = 1;
        for (int j = 0; j < check[i] && same; ++j) {
            break;
            same &= s[j] == s[n - check[i] + j];
        }
        if (same) {
            bst = check[i];
            break;
        }
    }
    if (bst == 0) {
        cout << "Just a legend\n";
    } else {
        cout << s.substr(0, bst) << '\n';
    }
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

//cout << setprecision(8) << fixed;
//

#define pb push_back
#define eb emplace_back
#define mp make_pair
#define pii pair<int, int>
#define fi first
#define se second
#define ull uint64_t
#define ll int64_t

const ll mod = 421412341324321ll;

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    string s;
    cin >> s;
    int n = s.size();
    if (n < 2) {
        cout << "Just a legend\n";
        return 0;
    }
    //find the longest substring s[1:] which is also a prefix
    int l = 0, h = n - 1;
    while (l < h) {
        int m = (l + h + 1) / 2;
        ll root = 0;
        for (int i = 0; i < m; ++i) {
            root = (root * 26 + s[i] - 'a') % mod;
        }
        ll hash = 0;
        for (int i = 1; i <= m; ++i) {
            hash = (hash * 26 + s[i] - 'a') % mod;
        }
        ll pw = 1;
        for (int i = 1; i < m; ++i) {
            pw = pw * 26 % mod;
        }
        bool ok = 0;
        for (int i = 1; i + m < n && !ok; ++i) {
            if (i > 1) {
                hash -= pw * (s[i - 1] - 'a');
                hash *= 26;
                hash += s[i + m - 1] - 'a';
                hash = (hash % mod + mod) % mod;
            }
            if (hash == root) {
                //check to see if they are actually equal
                bool same = 1;
                for (int j = 0; j < m && same; ++j) {
                    break;
                    same &= s[j] == s[i + j];
                }
                ok = same;
            }
        }
        if (ok) l = m;
        else h = m - 1;
    }
    ll prehash = 0;
    ll sufhash = 0;
    ll pw = 1;
    vector<int> check;
    for (int i = 1; i <= l; ++i) {
        prehash = (prehash * 26 + s[i - 1] - 'a') % mod;
        sufhash = ((s[n - i] - 'a') * pw + sufhash) % mod;
        if (sufhash == prehash) {
            check.pb(i);
        }
        pw = (pw * 26) % mod;
    }
    int bst = 0;
    for (int i = check.size() - 1; i >= 0; --i) {
        bool same = 1;
        for (int j = 0; j < check[i] && same; ++j) {
            break;
            same &= s[j] == s[n - check[i] + j];
        }
        if (same) {
            bst = check[i];
            break;
        }
    }
    if (bst == 0) {
        cout << "Just a legend\n";
    } else {
        cout << s.substr(0, bst) << '\n';
    }
    return 0;
}


#include <bits/stdc++.h>

using namespace std;
string s, pref, suff, obe;
int f[1000006];
bool flag;
int len(int l, char c)
{
    while(l && c != s[l])
    {
        l = f[l - 1];
    }
    if(c == s[l]) l++;
    return l;
}
void compute(int k)
{
    int i = 0;
    for(; i < k; i++) f[i] = 0;
    for(; i < s.size(); i++)
    {
        f[i] = len(f[i - 1], s[i]);
    }
}
int main()
{
    cin >> s;
    for(int k = 2; k < s.size(); k = s.size() - f[s.size() - 1] + 2)
    {

        compute(k);
        pref = "";
        obe = "";
        for(int i = 0; i < f[s.size() - 1]; i++)
        {
            pref += s[i];
            if(i) obe += s[i];
        }
        obe += s[f[s.size() - 1]];
        if(obe == pref)
        {
            flag = 1;
            break;
        }
        for(int i = f[s.size() - 1] + 1; i < s.size() - 1; i++)
        {
            obe.erase(obe.begin());
            obe += s[i];
            if(obe == pref)
            {
                flag = 1;
                break;
            }
        }
        //s = pref;
        //cout << k << '\n';
        if(flag) break;
    }
    if(flag)
    {
        cout << pref << '\n';
        return 0;
    }
    printf("Just a legend\n");
}


#include <bits/stdc++.h>

using namespace std;
string s, pref, suff, obe;
int f[1000006];
bool flag;
int len(int l, char c)
{
    while(l && c != s[l])
    {
        l = f[l - 1];
    }
    if(c == s[l]) l++;
    return l;
}
void compute(int k)
{
    int i = 0;
    for(; i < k; i++) f[i] = 0;
    for(; i < s.size(); i++)
    {
        f[i] = len(f[i - 1], s[i]);
    }
}
int main()
{
    cin >> s;
    for(int k = 1; k < s.size(); k = s.size() - f[s.size() - 1] + 1)
    {

        compute(k);
        pref = "";
        obe = "";
        //for(int i = 0; i < s.size(); i++) cout << f[i] << ' ';
        //puts("");

        for(int i = 0; i < f[s.size() - 1]; i++)
        {
            pref += s[i];
            if(i) obe += s[i];
        }
       // cout << pref << '\n';
        obe += s[f[s.size() - 1]];
        if(obe == pref)
        {
            flag = 1;
            break;
        }
        for(int i = f[s.size() - 1] + 1; i < s.size() - 1; i++)
        {
            obe.erase(obe.begin());
            obe += s[i];
            if(obe == pref)
            {
                flag = 1;
                break;
            }
        }
        //s = pref;
        if(flag) break;
    }
    if(flag)
    {
        cout << pref << '\n';
        return 0;
    }
    printf("Just a legend\n");
}


#include <bits/stdc++.h>

using namespace std;
string s, pref, suff, obe;
int main()
{
    cin >> s;
    pref = suff = s;
    bool flag = 0;
    for(int i = 0; i < s.size() - 1; i++)
    {
        pref.erase(pref.begin() + s.size() - 1 -i);
        suff.erase(suff.begin());
        if(i <= 1)
        {
            continue;
        }
       // cout << suff << ' ' << pref << '\n';
        if(pref == suff)
        {
            int j;
            for(j = 1; j < pref.size() + 1; j++)
            {
                obe += s[j];
            }
            //cout << obe << '\n';
            if(obe == pref)
            {
                flag = 1;
                break;
            }
            else
            {
                for(; j < s.size() - 1; j++)
                {
                    obe.erase(obe.begin());
                    obe += s[j];
                    if(obe == pref)
                    {
                        flag = 1;
                        break;
                    }
                }
                if(flag) break;
            }

        }
    }
    if(flag)
    {
        cout << pref << '\n';
        return 0;
    }
    printf("Just a legend\n");
}


#include <bits/stdc++.h>

using namespace std;
string s, pref, suff, obe;
int f[1000006];
bool flag;
int len(int l, char c)
{
    while(l && c != s[l])
    {
        l = f[l - 1];
    }
    if(c == s[l]) l++;
    return l;
}
void compute(int k)
{
    int i = 0;
    for(; i < k; i++) f[i] = 0;
    for(; i < s.size(); i++)
    {
        f[i] = len(f[i - 1], s[i]);
    }
}
int main()
{
    cin >> s;
    for(int k = 1; k < s.size(); k = s.size() - f[s.size() - 1] + 1)
    {

        compute(k);
        pref = "";
        obe = "";
        //for(int i = 0; i < s.size(); i++) cout << f[i] << ' ';
        //puts("");

        for(int i = 0; i < f[s.size() - 1]; i++)
        {
            pref += s[i];
            if(i && i < s.size() - 1) obe += s[i];
        }
       // cout << pref << '\n';
       if(f[s.size() - 1] > 0 && f[s.size() - 1] < s.size() - 1)
        obe += s[f[s.size() - 1]];

        if(obe.size() < pref.size()) continue;
        if(obe == pref)
        {
            flag = 1;
            break;
        }
        for(int i = f[s.size() - 1] + 1; i < s.size() - 1; i++)
        {
            obe.erase(obe.begin());
            obe += s[i];
            if(obe == pref)
            {
                flag = 1;
                break;
            }
        }
        //s = pref;
        if(flag) break;
    }
    if(flag)
    {
        cout << pref << '\n';
        return 0;
    }
    printf("Just a legend\n");
}


#include <bits/stdc++.h>

using namespace std;
string s, pref, suff, obe;
int main()
{
    cin >> s;
    pref = suff = s;
    bool flag = 0;
    for(int i = 0; i < s.size() - 1; i++)
    {
        if(i <= 1)
        {
        pref.erase(pref.begin() + s.size() - 1 -i);
        suff.erase(suff.begin());
            continue;
        }
       //cout << suff << ' ' << pref << '\n';
        if(pref == suff)
        {
            int j;
            obe = "";
            for(j = 1; j < pref.size() + 1; j++)
            {
                obe += s[j];
            }
            //cout << obe << '\n';
            if(obe == pref)
            {
                flag = 1;
                break;
            }
            else
            {
                for(; j < s.size() - 1; j++)
                {
                    obe.erase(obe.begin());
                    obe += s[j];
                    if(obe == pref)
                    {
                        flag = 1;
                        break;
                    }
                }
                if(flag) break;
            }

        }
                pref.erase(pref.begin() + s.size() - 1 -i);
        suff.erase(suff.begin());

    }
    if(flag)
    {
        cout << pref << '\n';
        return 0;
    }
    printf("Just a legend\n");
}


#include <bits/stdc++.h>

using namespace std;
string s, pref, suff, obe;
int main()
{
    cin >> s;
    pref = suff = s;
    bool flag = 0;
    for(int i = 0; i < s.size() - 1; i++)
    {
        pref.erase(pref.begin() + s.size() - 1 -i);
        suff.erase(suff.begin());
        if(i <= 1)
        {
            continue;
        }
       //cout << suff << ' ' << pref << '\n';
        if(pref == suff)
        {
            int j;
            obe = "";
            for(j = 1; j < pref.size() + 1; j++)
            {
                obe += s[j];
            }
            //cout << obe << '\n';
            if(obe == pref)
            {
                flag = 1;
                break;
            }
            else
            {
                for(; j < s.size() - 1; j++)
                {
                    obe.erase(obe.begin());
                    obe += s[j];
                    if(obe == pref)
                    {
                        flag = 1;
                        break;
                    }
                }
                if(flag) break;
            }

        }
    }
    if(flag)
    {
        cout << pref << '\n';
        return 0;
    }
    printf("Just a legend\n");
}


#include <bits/stdc++.h>

using namespace std;
string s, pref, suff, obe;
int f[1000006];
bool flag;
int len(int l, char c)
{
    while(l && c != s[l])
    {
        l = f[l - 1];
    }
    if(c == s[l]) l++;
    return l;
}
void compute(int k)
{
    int i = 0;
    for(; i < k; i++) f[i] = 0;
    for(; i < s.size(); i++)
    {
        f[i] = len(f[i - 1], s[i]);
    }
}
int main()
{
    cin >> s;
    for(int k = 1; k < s.size(); k = s.size() - f[s.size() - 1] + 1)
    {

        compute(k);
        pref = "";
        obe = "";
        //for(int i = 0; i < s.size(); i++) cout << f[i] << ' ';
        //puts("");

        for(int i = 0; i < f[s.size() - 1]; i++)
        {
            pref += s[i];
            if(i && i < s.size() - 1) obe += s[i];
        }
       // cout << pref << '\n';
       if(f[s.size() - 1] > 0 && f[s.size() - 1] < s.size() - 1)
        obe += s[f[s.size() - 1]];

        if(obe.size() < pref.size() || obe.size() == 0) continue;
        if(obe == pref)
        {
            flag = 1;
            break;
        }
        for(int i = f[s.size() - 1] + 1; i < s.size() - 1; i++)
        {
            obe.erase(obe.begin());
            obe += s[i];
            if(obe == pref)
            {
                flag = 1;
                break;
            }
        }
        //s = pref;
        if(flag) break;
    }
    if(flag)
    {
        cout << pref << '\n';
        return 0;
    }
    printf("Just a legend\n");
}


#include <bits/stdc++.h>

using namespace std;
string s, pref, suff, obe;
int f[1000006];
bool flag;
int len(int l, char c)
{
    while(l && c != s[l])
    {
        l = f[l - 1];
    }
    if(c == s[l]) l++;
    return l;
}
void compute()
{
    int i = 0;
    for(; i < 2; i++) f[i] = 0;
    for(i = 2; i < s.size(); i++)
    {
        f[i] = len(f[i - 1], s[i]);
    }
}
int main()
{
    cin >> s;
   /* for(int k = 2; k < s.size(); k = s.size() - f[s.size() - 1] + 1)
    {
    */
        compute();
        pref = "";
        obe = "";
        for(int i = 0; i < f[s.size() - 1]; i++)
        {
            pref += s[i];
            if(i) obe += s[i];
        }
        obe += s[f[s.size() - 1]];
        if(obe == pref)
        {
            flag = 1;
            //break;
        }
        for(int i = f[s.size() - 1] + 1; i < s.size() - 1; i++)
        {
            obe.erase(obe.begin());
            obe += s[i];
            if(obe == pref)
            {
                flag = 1;
                break;
            }
        }
        //cout << pref << '\n';
        //if(flag) break;
   // }
    if(flag)
    {
        cout << pref << '\n';
        return 0;
    }
    printf("Just a legend\n");
}


#include <bits/stdc++.h>

using namespace std;
/*
string s, pref, suff, obe;
int f[1000006];
bool flag;
int len(int l, char c)
{
    while(l && c != s[l])
    {
        l = f[l - 1];
    }
    if(c == s[l]) l++;
    return l;
}
void compute(int k)
{
    int i = 0;
    for(; i < k; i++) f[i] = 0;
    for(; i < s.size(); i++)
    {
        f[i] = len(f[i - 1], s[i]);
    }
}
int main()
{
    cin >> s;
    for(int k = 1; k < s.size(); k = s.size() - f[s.size() - 1] + 1)
    {

        compute(k);
        pref = "";
        obe = "";
        //for(int i = 0; i < s.size(); i++) cout << f[i] << ' ';
        //puts("");

        for(int i = 0; i < f[s.size() - 1]; i++)
        {
            pref += s[i];
            if(i && i < s.size() - 1) obe += s[i];
        }
       // cout << pref << '\n';
       if(f[s.size() - 1] > 0 && f[s.size() - 1] < s.size() - 1)
        obe += s[f[s.size() - 1]];

        if(obe.size() < pref.size() || obe.size() == 0) continue;
        if(obe == pref)
        {
            flag = 1;
            break;
        }
        for(int i = f[s.size() - 1] + 1; i < s.size() - 1; i++)
        {
            obe.erase(obe.begin());
            obe += s[i];
            if(obe == pref)
            {
                flag = 1;
                break;
            }
        }
        //s = pref;
        if(flag) break;
    }
    if(flag)
    {
        cout << pref << '\n';
        return 0;
    }
    printf("Just a legend\n");
}
*/
string s;
int n, l, r, z[1000001];
int main()
{
    cin >> s;
    n = s.size();
    for(int i = 1; i < n; i++)
    {
        if(r < i)
        {
            l = r = i;
            while(r < n && s[r - l] == s[r]) r++;

            z[i] = r - l;
            r--;
        }
        else
        {
            int k = i - l;
            if(z[k] < r - i + 1) z[i] = z[k];
            else
            {
                l = i;
                while(r < n && s[r - l] == s[r]) r++;

                z[i] = r - l;
                r--;
            }
        }
    }
    int max1 = 0, max2 = 0;
    for(int i = 1; i < n; i++)
    {
        if(z[i] + i == n)
        {
            max1 = max(z[i] - 1, max1);
        }
        else max1 = max(z[i], max1);
    }
    for(int i = 1; i < n; i++)
    {
        if(z[i] + i == n && z[i] <= max1) max2 = max(max2, z[i]);
    }
    if(max2 > 0)
    {
        cout << s.substr(0, max2) << '\n';
        return 0;
    }
    printf("Just a legend\n");
}


#include <bits/stdc++.h>

using namespace std;
string s, pref, suff, obe;
int main()
{
    cin >> s;
    pref = suff = s;
    bool flag = 0;
    for(int i = 0; i < s.size(); i++)
    {
        if(i <= 1)
        {
        pref.erase(pref.begin() + s.size() - 1 -i);
        suff.erase(suff.begin());
            continue;
        }
       //cout << suff << ' ' << pref << '\n';
        if(pref == suff)
        {
            int j;
            obe = "";
            for(j = 1; j < pref.size() + 1; j++)
            {
                obe += s[j];
            }
            //cout << obe << '\n';
            if(obe == pref)
            {
                flag = 1;
                break;
            }
            else
            {
                for(; j < s.size() - 1; j++)
                {
                    obe.erase(obe.begin());
                    obe += s[j];
                    if(obe == pref)
                    {
                        flag = 1;
                        break;
                    }
                }
                if(flag) break;
            }

        }
                pref.erase(pref.begin() + s.size() - 1 -i);
        suff.erase(suff.begin());

    }
    if(flag)
    {
        cout << pref << '\n';
        return 0;
    }
    printf("Just a legend\n");
}


#include <bits/stdc++.h>
using namespace std;
/* macros */

int kmp[1000005];

int main()
{
    ios::sync_with_stdio(false);
    string s;
    cin >> s;
    int l=0, r=0;
    kmp[0]=0;
    int mx=0;
    for(int i=1, k=0; i<s.size(); ++i){
        k = kmp[i-1];
        while(k>1&&s[i]!=s[k])
            k = kmp[k-1];
        if (s[k]==s[i]) ++k;
        kmp[i] = k;
        if(i!=s.size()-1) mx = max(mx, k);
    }
    if(mx >= kmp[s.size()-1]) cout << s.substr(0, kmp[s.size()-1]);
    else cout << "Just a legend";
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
/* macros */

int kmp[1000005];

int main()
{
    ios::sync_with_stdio(false);
    string s;
    cin >> s;
    int l=0, r=0;
    kmp[0]=0;
    int mx=0;
    for(int i=1, k=0; i<s.size(); ++i){
        k = kmp[i-1];
        while(k>0&&s[i]!=s[k])
            k = kmp[k-1];
        if (s[k]==s[i]) ++k;
        kmp[i] = k;
         //cout << k << "\n";
        if(i!=s.size()-1) mx = max(mx, k);
    }
    if(mx >= kmp[s.size()-1] && kmp[s.size()-1]) cout << s.substr(0, kmp[s.size()-1]);
    else if (kmp[kmp[s.size()-1]-1]){
        cout << s.substr(0, kmp[kmp[s.size()-1]-1]);
    } else cout << "Just a legend";
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
/* macros */
// memory
#define zeroset(A) memset((A), 0, sizeof((A)))
#define negset(A) memset((A), -1, sizeof((A)))
#define all(c) (c).begin(), (c).end()
#define pb push_back
// input & output
#define inpt(a) freopen(a,"r",stdin)
#define otpt(a) freopen(a,"w",stdout)
#define eol "\n"
// types
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<double, double> pdd;
typedef pair<ll,ll> pll;
#define ff first
#define ss second
// constants
#define EPS 1e-9
#define MAXN 1000005
#define INF INT_MAX
#define MOD 1000000007

int z[MAXN], cnt[MAXN];

int main()
{
    ios::sync_with_stdio(false);
    string s;
    cin >> s;
    int l=0, r=0;
    z[0] = s.size();
    for(int i=1; i<s.size(); ++i){
        if (i > r){
            l = r = i;
            while(r<s.size() && s[r] == s[r-l]) ++r;
            z[i] = r - l;
            --r;
        } else {
            int k = i - l, b = r - i + 1;
            if(z[k] < b) z[i] = z[k];
            else if (z[k] > b) z[i] = b;
            else{
                l = r = i;
                while(r<s.size() && s[r] == s[r-l]) ++r;
                z[i] = r - l;
                --r;
            }
        }
        ++cnt[z[i]];
    }
    int ans = 0;
    for(int i=1; i<s.size(); ++i){
        if(z[i]==s.size()-i && cnt[z[i]]>1) ans = max(ans, z[i]);
    }
    if(ans) cout << s.substr(0, ans);
    else cout << "Just a legend";
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
/* macros */

int kmp[1000005];

int main()
{
    ios::sync_with_stdio(false);
    string s;
    cin >> s;
    int l=0, r=0;
    kmp[0]=0;
    int mx=0;
    for(int i=1, k=0; i<s.size(); ++i){
        k = kmp[i-1];
        while(k>1&&s[i]!=s[k])
            k = kmp[k-1];
        if (s[k]==s[i]) ++k;
        kmp[i] = k;
        // cout << k << "\n";
        if(i!=s.size()-1) mx = max(mx, k);
    }
    if(mx >= kmp[s.size()-1]) cout << s.substr(0, kmp[s.size()-1]);
    else if (kmp[kmp[s.size()-1]-1]){
        cout << s.substr(0, kmp[kmp[s.size()-1]-1]);
    } else cout << "Just a legend";
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

vector<pair<int,ll> > hashs;
string s;
ll b = 123, m = 1e9+7;

bool check(int md){
    if(hashs.empty()) return false;
    ll h = 0, bb = 1LL;
    int len = hashs[md].first;
    for(int i=1; i<s.size()-1&&i<=len; ++i){
        h = (h*b + s[i])%m;
        bb = (bb * b)%m;
    }
    if(h == hashs[md].second) return true;
    for(int i=len+1; i<s.size()-1; ++i){
        h = (h*b + s[i])%m;
        h = ((h - bb*s[i-len])%m + m)%m;
        if(h == hashs[md].second) return true;
    }
    return false;
}

int main()
{
    ios::sync_with_stdio(false);
    cin >> s;
    ll hf=0, hs=0, bb=1LL;
    for(int i=0; i<s.size()-1; ++i){
        hf = (hf*b + s[i])%m;
        hs = (s[s.size()-i-1]*bb + hs)%m;
        bb = (bb * b)%m;
        if(hf == hs)
            hashs.push_back({i+1,hf});
    }
    int lo=0, md, hi=hashs.size()-1;
    while(hi-lo>1){
        md = (lo+hi)/2;
        if(check(md)) lo = md;
        else hi = md-1;
    }
    if(!check(hi)) hi = lo;
    if(check(hi)) cout << s.substr(0, hashs[hi].first);
    else cout << "Just a legend";
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
/* macros */
// memory
#define zeroset(A) memset((A), 0, sizeof((A)))
#define negset(A) memset((A), -1, sizeof((A)))
#define all(c) (c).begin(), (c).end()
#define pb push_back
// input & output
#define inpt(a) freopen(a,"r",stdin)
#define otpt(a) freopen(a,"w",stdout)
#define eol "\n"
// types
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<double, double> pdd;
typedef pair<ll,ll> pll;
#define ff first
#define ss second
// constants
#define EPS 1e-9
#define MAXN 1000005
#define INF INT_MAX
#define MOD 1000000007

int z[MAXN], cnt[MAXN];

int main()
{
    ios::sync_with_stdio(false);
    string s;
    cin >> s;
    int l=0, r=0;
    z[0] = s.size();
    for(int i=1; i<s.size(); ++i){
        if (i > r){
            l = r = i;
            while(r<s.size() && r-l<i && s[r] == s[r-l] ) ++r;
            z[i] = r - l;
            --r;
        } else {
            int k = i - l, b = r - i + 1;
            if(z[k] < b) z[i] = z[k];
            else{
                l = r = i;
                while(r<s.size() && r-l<i && s[r] == s[r-l] ) ++r;
                z[i] = r - l;
                --r;
            }
        }
        ++cnt[z[i]];
    }
    int ans = 0;
    for(int i=1; i<s.size(); ++i){
        //cout << z[i] << eol;
        if(z[i]==s.size()-i && cnt[z[i]]>1) ans = max(ans, z[i]);
    }
    if(ans) cout << s.substr(0, ans);
    else cout << "Just a legend";
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
/* macros */
// memory
#define zeroset(A) memset((A), 0, sizeof((A)))
#define negset(A) memset((A), -1, sizeof((A)))
#define all(c) (c).begin(), (c).end()
#define pb push_back
// input & output
#define inpt(a) freopen(a,"r",stdin)
#define otpt(a) freopen(a,"w",stdout)
#define eol "\n"
// types
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<double, double> pdd;
typedef pair<ll,ll> pll;
#define ff first
#define ss second
// constants
#define EPS 1e-9
#define MAXN 1000005
#define INF INT_MAX
#define MOD 1000000007

int z[MAXN];

int main()
{
    ios::sync_with_stdio(false);
    string s;
    cin >> s;
    int l=0, r=0;
    z[0] = s.size();
    for(int i=1; i<s.size(); ++i){
        if (i > r){
            l = r = i;
            while(r<s.size() && s[r] == s[r-l]) ++r;
            z[i] = r - l;
            --r;
        } else {
            int k = i - l, b = r - i + 1;
            if(z[k] < b) z[i] = z[k];
            else if (z[k] > b) z[i] = b;
            else{
                l = i;
                while(r<s.size() && s[r] == s[r-l] ) ++r;
                z[i] = r - l;
                --r;
            }
        }
    }
    int xz = 0, len = 0;
    for(int i=1; i<s.size(); ++i){
        if(z[i]==s.size()-i && xz >= s.size()-i){
            len = max((int)s.size()-i, len);
        }
        xz = max(xz, z[i]);
    }
    if(len) cout << s.substr(0, len);
    else cout << "Just a legend";
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
/* macros */

int kmp[1000005];

int main()
{
    ios::sync_with_stdio(false);
    string s;
    cin >> s;
    int l=0, r=0;
    kmp[0]=0;
    int mx=0;
    for(int i=1, k=0; i<s.size(); ++i){
        k = kmp[i-1];
        while(k>1&&s[i]!=s[k])
            k = kmp[k-1];
        if (s[k]==s[i]) ++k;
        kmp[i] = k;
        // cout << k << "\n";
        if(i!=s.size()-1) mx = max(mx, k);
    }
    if(mx >= kmp[s.size()-1] && kmp[s.size()-1]) cout << s.substr(0, kmp[s.size()-1]);
    else if (kmp[kmp[s.size()-1]-1]){
        cout << s.substr(0, kmp[kmp[s.size()-1]-1]);
    } else cout << "Just a legend";
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
/* macros */
// memory
#define zeroset(A) memset((A), 0, sizeof((A)))
#define negset(A) memset((A), -1, sizeof((A)))
#define all(c) (c).begin(), (c).end()
#define pb push_back
// input & output
#define inpt(a) freopen(a,"r",stdin)
#define otpt(a) freopen(a,"w",stdout)
#define eol "\n"
// types
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<double, double> pdd;
typedef pair<ll,ll> pll;
#define ff first
#define ss second
// constants
#define EPS 1e-9
#define MAXN 1000005
#define INF INT_MAX
#define MOD 1000000007

int z[MAXN];

int main()
{
    ios::sync_with_stdio(false);
    string s;
    cin >> s;
    int l=0, r=0;
    z[0] = s.size();
    for(int i=1; i<s.size(); ++i){
        if (i > r){
            l = r = i;
            while(r<s.size() && s[r] == s[r-l]) ++r;
            z[i] = r - l;
            --r;
        } else {
            int k = i - l, b = r - i + 1;
            if(z[k] < b) z[i] = z[k];
            else{
                l = r = i;
                while(r<s.size() && s[r] == s[r-l] ) ++r;
                z[i] = r - l;
                --r;
            }
        }
    }
    int xz = 0, len = 0;
    for(int i=1; i<s.size(); ++i){
        if(z[i]==s.size()-i && xz >= s.size()-i){
            len = max((int)s.size()-i, len);
        }
        xz = max(xz, z[i]);
    }
    if(len) cout << s.substr(0, len);
    else cout << "Just a legend";
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
/* macros */
// memory
#define zeroset(A) memset((A), 0, sizeof((A)))
#define negset(A) memset((A), -1, sizeof((A)))
#define all(c) (c).begin(), (c).end()
#define pb push_back
// input & output
#define inpt(a) freopen(a,"r",stdin)
#define otpt(a) freopen(a,"w",stdout)
#define eol "\n"
// types
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<double, double> pdd;
typedef pair<ll,ll> pll;
#define ff first
#define ss second
// constants
#define EPS 1e-9
#define MAXN 1000005
#define INF INT_MAX
#define MOD 1000000007

int z[MAXN];

int main()
{
    ios::sync_with_stdio(false);
    string s;
    cin >> s;
    int l=0, r=0;
    z[0] = s.size();
    for(int i=1; i<s.size(); ++i){
        if (i > r){
            l = r = i;
            while(r<s.size() && s[r] == s[r-l]) ++r;
            z[i] = r - l;
            --r;
        } else {
            int k = i - l, b = r - i + 1;
            if(z[k] < b) z[i] = z[k];
            else{
                l = i;
                while(r<s.size() && s[r] == s[r-l] ) ++r;
                z[i] = r - l;
                --r;
            }
        }
    }
    int xz = 0, len = 0;
    for(int i=1; i<s.size(); ++i){
        if(z[i]==s.size()-i && xz >= s.size()-i){
            len = max((int)s.size()-i, len);
        }
        xz = max(xz, z[i]);
    }
    if(len) cout << s.substr(0, len);
    else cout << "Just a legend";
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define falze(n)		memset(n,false,sizeof(n))
#define zero(n)			memset(n,0,sizeof(n))
#define init(n)			memset(n,-1,sizeof(n))
#define REP(i,n) 		for(i=0;i<n;i++)
#define FOR(i,a,b) 		for(i=a;i<=b;i++)
#define FORD(i,a,b) 	for(i=a;i>=b;i--)
#define FOR2(i,a,b,c) 	for(i=a;i<=b;i+=c)
#define FORD2(i,a,b,c)	for(i=a;i>=b;i-=c)
#define mod(x,y) 		(((x%y)<0)?((x%y)+y):(x%y))
#define PB 				push_back
#define endll 			"\n"
#define INF 			0x3FFFFFFF
#define in(a,b)			substr(a,b-a+1) // INCLUSIVE
#define ff				first
#define ss				second
#define LEN(x)			((ll)x.size())
#define mm				1000000007
#define check(x)		(((x%=mm)+=mm)%=mm)
typedef long long ll;
typedef pair<ll,ll> ii;

ll n,m,len;

int main(){
	ll i,j,k,t,a,b;
	ios_base::sync_with_stdio(0);
	cin.tie(NULL);
	cout.tie(NULL);

	//freopen("input.in", "r",stdin);
	//freopen("output.out","w",stdout);

	len = 0;
	string u; cin >> u;

	if(LEN(u) == 1){
		cout << "Just a legend\n" << endll;
		return 0;
	}

	ll N = LEN(u);

	string v = u.in(1,N-2);

	ll start = 0;
	ll end = LEN(u) - 1;
	ll one = 0;
	ll two = 0;
	ll x = 1000000007;
	ll p = 1;

	vector<int> ans;

	while(start <= N-1){

		one *= x; check(one);
		one += u[start]; check(one);

		int temp = p*u[end]; check(temp);
		two += temp; check(two);

		p *= x;
		check(p);

		if(one == two and u[start] == u[N-1] and u[end] == u[0]){
			ans.PB(start);
		}
		start++; end--;
	}

	int f = 0;
	string ret;

	reverse(ans.begin(),ans.end());

	for(auto cur:ans){
		int size = cur+1;
		string xx = u.in(0,size-1);
		//string yy = u.in(N-size,N-1);

		//if(xx.compare(yy) != 0) continue;

		if(v.find(xx) != string::npos){
			f = 1;
			ret = u.in(0,size-1);
			break;
		}
	}

	if(not f){
		cout << "Just a legend\n";
	}
	else{
		cout << ret << endll;
	}
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define falze(n)		memset(n,false,sizeof(n))
#define zero(n)			memset(n,0,sizeof(n))
#define init(n)			memset(n,-1,sizeof(n))
#define REP(i,n) 		for(i=0;i<n;i++)
#define FOR(i,a,b) 		for(i=a;i<=b;i++)
#define FORD(i,a,b) 	for(i=a;i>=b;i--)
#define FOR2(i,a,b,c) 	for(i=a;i<=b;i+=c)
#define FORD2(i,a,b,c)	for(i=a;i>=b;i-=c)
#define mod(x,y) 		(((x%y)<0)?((x%y)+y):(x%y))
#define PB 				push_back
#define endll 			"\n"
#define INF 			0x3FFFFFFF
#define in(a,b)			substr(a,b-a+1) // INCLUSIVE
#define ff				first
#define ss				second
#define LEN(x)			((ll)x.size())
#define mm				30000001
#define check(x)		(((x%=mm)+=mm)%=mm)
typedef long long ll;
typedef pair<ll,ll> ii;

ll n,m,len;

int main(){
	ll i,j,k,t,a,b;
	ios_base::sync_with_stdio(0);
	cin.tie(NULL);
	cout.tie(NULL);

	//freopen("input.in", "r",stdin);
	//freopen("output.out","w",stdout);

	len = 0;
	string u; cin >> u;

	if(LEN(u) == 1){
		cout << u << endll;
		return 0;
	}

	ll N = LEN(u);

	string v = u.in(1,N-2);

	ll start = 0;
	ll end = LEN(u) - 1;
	ll one = 0;
	ll two = 0;
	ll x = 30000001;
	ll p = 1;

	vector<int> ans;

	while(start <= N-1){

		one *= x; check(one);
		one += u[start]; check(one);

		int temp = p*u[end]; check(temp);
		two += temp; check(two);

		p *= x;
		check(p);

		start++; end--;
		if(one == two){
			ans.PB(start-1);
		}
	}

	int f = 0;
	string ret;

	for(auto cur:ans){
		int size = cur+1;
		if(v.find(u.in(0,size-1)) != string::npos){
			f = 1;
			ret = u.in(0,size-1);
		}
	}

	if(not f){
		cout << "Just a legend\n";
	}
	else{
		cout << ret << endll;
	}
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define falze(n)		memset(n,false,sizeof(n))
#define zero(n)			memset(n,0,sizeof(n))
#define init(n)			memset(n,-1,sizeof(n))
#define REP(i,n) 		for(i=0;i<n;i++)
#define FOR(i,a,b) 		for(i=a;i<=b;i++)
#define FORD(i,a,b) 	for(i=a;i>=b;i--)
#define FOR2(i,a,b,c) 	for(i=a;i<=b;i+=c)
#define FORD2(i,a,b,c)	for(i=a;i>=b;i-=c)
#define mod(x,y) 		(((x%y)<0)?((x%y)+y):(x%y))
#define PB 				push_back
#define endll 			"\n"
#define INF 			0x3FFFFFFF
#define in(a,b)			substr(a,b-a+1) // INCLUSIVE
#define ff				first
#define ss				second
#define LEN(x)			((ll)x.size())
#define mm				30000001
#define check(x)		(((x%=mm)+=mm)%=mm)
typedef long long ll;
typedef pair<ll,ll> ii;

ll n,m,len;

int main(){
	ll i,j,k,t,a,b;
	ios_base::sync_with_stdio(0);
	cin.tie(NULL);
	cout.tie(NULL);

	//freopen("input.in", "r",stdin);
	//freopen("output.out","w",stdout);

	len = 0;
	string u; cin >> u;

	if(LEN(u) == 1){
		cout << "Just a legend\n" << endll;
		return 0;
	}

	ll N = LEN(u);

	string v = u.in(1,N-2);

	ll start = 0;
	ll end = LEN(u) - 1;
	ll one = 0;
	ll two = 0;
	ll x = 30000001;
	ll p = 1;

	vector<int> ans;

	while(start <= N-1){

		one *= x; check(one);
		one += u[start]; check(one);

		int temp = p*u[end]; check(temp);
		two += temp; check(two);

		p *= x;
		check(p);

		if(one == two and u.in(0,start).compare(u.in(end,N-1)) == 0){
			ans.PB(start);
		}
		start++; end--;
	}

	int f = 0;
	string ret;

	for(auto cur:ans){
		int size = cur+1;
		if(v.find(u.in(0,size-1)) != string::npos){
			f = 1;
			ret = u.in(0,size-1);
		}
	}

	if(not f){
		cout << "Just a legend\n";
	}
	else{
		cout << ret << endll;
	}
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define falze(n)		memset(n,false,sizeof(n))
#define zero(n)			memset(n,0,sizeof(n))
#define init(n)			memset(n,-1,sizeof(n))
#define REP(i,n) 		for(i=0;i<n;i++)
#define FOR(i,a,b) 		for(i=a;i<=b;i++)
#define FORD(i,a,b) 	for(i=a;i>=b;i--)
#define FOR2(i,a,b,c) 	for(i=a;i<=b;i+=c)
#define FORD2(i,a,b,c)	for(i=a;i>=b;i-=c)
#define mod(x,y) 		(((x%y)<0)?((x%y)+y):(x%y))
#define PB 				push_back
#define endll 			"\n"
#define INF 			0x3FFFFFFF
#define in(a,b)			substr(a,b-a+1) // INCLUSIVE
#define ff				first
#define ss				second
#define LEN(x)			((ll)x.size())
#define mm				1000000007
#define check(x)		(((x%=mm)+=mm)%=mm)
#define mid				((l+r)>>1)
#define c1				(node<<1)+1
#define c2				(node<<1)+2
typedef long long ll;
typedef pair<ll,ll> ii;

ll n,m,len;

int fail[1000001];
bool f[1000001];
string u;

void kmpPreprocess(){

	int i,j;

	FOR(i,2,n){
		j = fail[i-1];
		while(j and u[j+1] != u[i]) j = fail[j];
		if(u[j+1] == u[i]) fail[i] = j+1;
	}
}
int main(){
	ll i,j,k,t,a,b;
	ios_base::sync_with_stdio(0);
	cin.tie(NULL);
	cout.tie(NULL);

	//freopen("input.in", "r",stdin);
	//freopen("output.out","w",stdout);

	cin >> u;

	n = LEN(u);
	u = "$" + u;
	kmpPreprocess();

	// true if it's a fail jump from anywhere
	// but not the suffix.
	FOR(i,2,n-1) f[fail[i]] = true;

	for(i=fail[n];i;i=fail[i]) if(f[i]){
		cout << u.in(1,i) << endll;
		return 0;
	}

	cout << "Just a legend\n";

	return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define falze(n)		memset(n,false,sizeof(n))
#define zero(n)			memset(n,0,sizeof(n))
#define init(n)			memset(n,-1,sizeof(n))
#define REP(i,n) 		for(i=0;i<n;i++)
#define FOR(i,a,b) 		for(i=a;i<=b;i++)
#define FORD(i,a,b) 	for(i=a;i>=b;i--)
#define FOR2(i,a,b,c) 	for(i=a;i<=b;i+=c)
#define FORD2(i,a,b,c)	for(i=a;i>=b;i-=c)
#define mod(x,y) 		(((x%y)<0)?((x%y)+y):(x%y))
#define PB 				push_back
#define endll 			"\n"
#define INF 			0x3FFFFFFF
#define in(a,b)			substr(a,b-a+1) // INCLUSIVE
#define ff				first
#define ss				second
#define LEN(x)			((ll)x.size())
#define mm				1000000007
#define check(x)		(((x%=mm)+=mm)%=mm)
typedef long long ll;
typedef pair<ll,ll> ii;

ll n,m,len;

int main(){
	ll i,j,k,t,a,b;
	ios_base::sync_with_stdio(0);
	cin.tie(NULL);
	cout.tie(NULL);

	//freopen("input.in", "r",stdin);
	//freopen("output.out","w",stdout);

	len = 0;
	string u; cin >> u;

	if(LEN(u) == 1){
		cout << "Just a legend\n" << endll;
		return 0;
	}

	ll N = LEN(u);

	string v = u.in(1,N-2);

	ll start = 0;
	ll end = LEN(u) - 1;
	ll one = 0;
	ll two = 0;
	ll x = 1000000007;
	ll p = 1;

	vector<int> ans;

	while(start <= N-1){

		one *= x; check(one);
		one += u[start]; check(one);

		int temp = p*u[end]; check(temp);
		two += temp; check(two);

		p *= x;
		check(p);

		if(one == two and u[start] == u[N-1] and u[end] == u[0]){
			ans.PB(start);
		}
		start++; end--;
	}

	int f = 0;
	string ret;

	reverse(ans.begin(),ans.end());

	for(auto cur:ans){
		int size = cur+1;
		string xx = u.in(0,size-1);
		string yy = u.in(N-size,N-1);
		if(xx.compare(yy) != 0) continue;

		if(v.find(xx) != string::npos){
			f = 1;
			ret = u.in(0,size-1);
			break;
		}
	}

	if(not f){
		cout << "Just a legend\n";
	}
	else{
		cout << ret << endll;
	}
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define falze(n)		memset(n,false,sizeof(n))
#define zero(n)			memset(n,0,sizeof(n))
#define init(n)			memset(n,-1,sizeof(n))
#define REP(i,n) 		for(i=0;i<n;i++)
#define FOR(i,a,b) 		for(i=a;i<=b;i++)
#define FORD(i,a,b) 	for(i=a;i>=b;i--)
#define FOR2(i,a,b,c) 	for(i=a;i<=b;i+=c)
#define FORD2(i,a,b,c)	for(i=a;i>=b;i-=c)
#define mod(x,y) 		(((x%y)<0)?((x%y)+y):(x%y))
#define PB 				push_back
#define endll 			"\n"
#define INF 			0x3FFFFFFF
#define in(a,b)			substr(a,b-a+1) // INCLUSIVE
#define ff				first
#define ss				second
#define LEN(x)			((ll)x.size())
#define mm				1000000007
#define check(x)		(((x%=mm)+=mm)%=mm)
typedef long long ll;
typedef pair<ll,ll> ii;

ll n,m,len;

int main(){
	ll i,j,k,t,a,b;
	ios_base::sync_with_stdio(0);
	cin.tie(NULL);
	cout.tie(NULL);

	//freopen("input.in", "r",stdin);
	//freopen("output.out","w",stdout);

	len = 0;
	string u; cin >> u;

	if(LEN(u) == 1){
		cout << "Just a legend\n" << endll;
		return 0;
	}

	ll N = LEN(u);

	string v = u.in(1,N-2);

	ll start = 0;
	ll end = LEN(u) - 1;
	ll one = 0;
	ll two = 0;
	ll x = 1000000007;
	ll p = 1;

	vector<int> ans;

	while(start <= N-1){

		one *= x; check(one);
		one += u[start]; check(one);

		int temp = p*u[end]; check(temp);
		two += temp; check(two);

		p *= x;
		check(p);

		if(one == two){
			ans.PB(start);
		}
		start++; end--;
	}

	int f = 0;
	string ret;

	reverse(ans.begin(),ans.end());

	for(auto cur:ans){
		int size = cur+1;
		string xx = u.in(0,size-1);
		string yy = u.in(N-size,N-1);

		if(xx.compare(yy) != 0) continue;

		if(v.find(xx) != string::npos){
			f = 1;
			ret = u.in(0,size-1);
			break;
		}
	}

	if(not f){
		cout << "Just a legend\n";
	}
	else{
		cout << ret << endll;
	}
	return 0;
}