Harryxun/stf_run huggingface dataset:
#!python3

import sys
iim = lambda: map(int, sys.stdin.readline().rstrip().split())
from heapq import heappush, heappushpop


def resolve():
    rl = sys.stdin.readline
    T = int(rl())
    if T == 3: raise 1

    ans = []
    for t in range(T):
        N = int(rl())

        val = 0
        a1 = [[] for i in range(N)]
        a2 = [[] for i in range(N)]

        for _ in range(N):
            i, v1, v2 = map(int, rl().split())
            i -= 1
            diff = v1 - v2
            if diff == 0 or i == N-1:
                val += v1
            elif diff > 0:
                a1[i].append(diff)
                val += v2
            else:
                i = N-1-i-1
                a2[i].append(-diff)
                val += v1

        for ax in (a1, a2):
            dq = []
            ld = 0
            for i, aa in enumerate(ax):
                if not aa: continue
                for diff in aa:
                    if ld <= i:
                        heappush(dq, diff)
                        ld += 1
                    else:
                        heappushpop(dq, diff)
            val += sum(dq)

        ans.append(val)


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



if __name__ == "__main__":
    resolve()


### FIXED CODE ###

#!python3

import sys
iim = lambda: map(int, sys.stdin.readline().rstrip().split())
sys.setrecursionlimit(1000000000)

def resolve():
    it = map(int, sys.stdin.read().split())

    T = next(it)
    ans = []
    for i in range(T):
        N = next(it)

        val = 0; a1 = []; a2 = []
        for i, v1, v2 in ((next(it), next(it), next(it)) for i in range(N)):
            diff = v1 - v2
            a, v, diff = (a1, v2, diff) if diff >= 0 else (a2, v1, -diff)
            a.append((diff, i))
            val += v
        a1.sort(reverse=True); a2.sort(reverse=True)

        ls = len(a1)
        vis = [None]*(N+1)
        def root(x):
            if vis[x] == None: return x

            vis[x] = root(vis[x])
            return vis[x]
        def root(x):
            a = []
            while True:
                y = vis[x]
                if y == None:
                    break
                a.append(x)
                x = y
            for i in a:
                vis[i] = x
            return x

        for diff, i in a1:
            j = min(i, ls) - 1
            k = root(j)
            #print(diff, i, j, k,  vis)
            if k < 0: continue
            val += diff
            vis[k] = k - 1


        for diff, i in a2:
            j, v2 = max(i, ls), [[-1]]
            k = root(j)
            #print(diff, i, j, k,  vis)
            if k >= N: continue
            val += diff
            vis[k] = k + 1

        ans.append(val)

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



if __name__ == "__main__":
    resolve()
N = int(input())
a = input()
if len(list(a)) <=N:
  print(a)
else:
  print(a[0:N]+'...')

### FIXED CODE ###

N = (int(input())%100)%10
if N in [2,4,5,7,9]:
  print('hon')
elif N in [0,1,6,8]:
  print('pon')
else:
  print('bon')
import numpy as np
N = int(input())
B = np.array(input().split(), dtype=int)[::-1]

et = 0

ret += B[0]

i = 0
while i < N-2:
    ret += B[i] if B[i] < B[i+1] else B[i+1]
    i+=1
print(ret)

### FIXED CODE ###

import numpy as np
N = int(input())
B = np.array(input().split(), dtype=int)[::-1]

ret = 0

ret += B[0]

i = 0
while i < N-2:
    ret += B[i] if B[i] < B[i+1] else B[i+1]
    i+=1

ret += B[-1]
print(ret)
n,k=map(int,input().split())
s=list(input())
point=s[0]
count=1
while k!=0:
    if s[count]!=point:
        while 1:
            if s[count]!=point:
                s[count]=point
                count +=1
            else:break
        k -=1
    else:count +=1

ans=0
for i in range(n-1,0,-1):
    if s[i]==s[i-1]:
        ans +=1
print(ans)

### FIXED CODE ###

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

s = input()

S = list(s)

num = 0
for i in range(N-1):

    if S[i] == S[i+1]:
        num += 1

print (min(N-1,num + 2*K))
from math import gcd

k = int(input())
gcd_sum = 0

for a in range(1, k + 1):
    for b in range(1, k + 1):
        for c in range(1, k + 1):
            gcd_sum += gcd(a, b, c)

print(gcd_sum)



### FIXED CODE ###

from math import gcd

k = int(input())
ans = 0
for a in range(1, k + 1):
    for b in range(1, k + 1):
        gcd_ab = gcd(a, b)
        for c in range(1, k + 1):
            ans += gcd(gcd_ab, c)
print(ans)
n,m = map(int,input().split())

l = list()
for i in range(m):
  k = int(input())
  l.append(k)
s = sum(l)

ans = n-s
if ans>=0:
  print(ans)
else:
  print(-1)

### FIXED CODE ###

n,m = map(int,input().split())

l = list(map(int,input().split()))

s = sum(l)

ans = n-s
if ans>=0:
  print(ans)
else:
  print(-1)
count=0
while True:
    count=count+1
    a=input()
    b=len(a)
    if b==0:
        break
    else:
        print("Case",count,":",a)



### FIXED CODE ###

count=0
while True:
    count=count+1
    a=input()
    if int(a)==0:
        break
    else:
        print("Case "+str(count)+": "+str(a))
def possible(x):
    global k
    cnt = 0
    for i in a:
        if i % x == 0:
            cnt += i // x - 1
        else:
            cnt += i // x

    if cnt <= k:
        return True
    return False

n, k = map(int, input().split())

a = list(map(int, input().split()))

mini = 0
maxi = max(a)

while mini <= maxi:
    mid = (mini + maxi) // 2
    res = possible(mid)
    if res:
        maxi = mid
    else:
        mini = mid
    # print(mini, mid, maxi)

    if mini+1 == maxi:
        if possible(maxi):
            ans = maxi
        else:
            ans = mini
        break

print(ans)
# print(possible(4))



### FIXED CODE ###

def possible(x):
    global k
    cnt = 0
    for i in a:
        if i % x == 0:
            cnt += i // x - 1
        else:
            cnt += i // x

    if cnt <= k:
        return True
    return False

n, k = map(int, input().split())

a = list(map(int, input().split()))

mini = 1
maxi = max(a)

while mini <= maxi:
    mid = (mini + maxi) // 2
    res = possible(mid)
    if res:
        maxi = mid
    else:
        mini = mid
    # print(mini, mid, maxi)

    if mini+1 >= maxi:
        if maxi < mini:
            mini, maxi = maxi, mini
        if possible(mini):
            ans = mini
        else:
            ans = maxi
        break

print(ans)
# print(possible(4))
input(x)
a = int(x) * int(x) * int(x)
print(a)


### FIXED CODE ###

x = int(input())
a = x * x * x
print(a)
from collections import deque, defaultdict

N, M = map(int, input().split())
outs = defaultdict(list)

for _ in range(M):
    v1, v2 = map(int, input().split())
    # if v1>v2: v1,v2 = v2,v1
    outs[v1].append(v2)
    outs[v2].append(v1)

#print(outs)
q = deque([1])
depth = defaultdict(int)
depth[1] = 0
visit = [False]*M #配列なので0オリジン
visit[0] = True

while q:
    v1 = q.popleft()
    for v2 in outs[v1]: #v1のノードから出ている矢印をみる．
        if visit[v2-1]==False:
            visit[v2-1] = True
            if depth[v2] == 0:
                depth[v2] = depth[v1] + 1
            q.append(v2)
            #print(v2,q,depth)

b = sorted(depth.items())
#print(b)
print("Yes")
for i in range(1,N):
    print(b[i][1])

### FIXED CODE ###

from collections import deque, defaultdict

N, M = map(int, input().split())
outs = defaultdict(list)

for _ in range(M):
    v1, v2 = map(int, input().split())
    #v1, v2 = v1-1,v2-1
    outs[v1].append(v2)
    outs[v2].append(v1)

# print(outs)
q = deque([1])
depth = defaultdict(int)
depth[1] = 0
visit = [False]*N #配列なので0オリジン
visit[0] = True
# print(visit)
while q:
    v1 = q.popleft()
    # print("a",v1)
    for v2 in outs[v1]: #v1のノードから出ている矢印をみる．
        # print("b",v2)
        if visit[v2-1]==False:
            visit[v2-1] = True
            depth[v2] = v1
            q.append(v2)
            # print(v2,q,depth)

b = sorted(depth.items())
# print(b)
print("Yes")
for i in range(1,N):
    print(b[i][1])
def q38(n, d):
        max_d = max(d)
        min_d = min(d)
        count = 0
        for i in range(min_d+1, max_d):
            a = []
            b = []
            for j in d:
                if j >= i:
                    a.append(j)
                else:
                    b.append(j)
            if len(a) == len(b):
                count += 1
        return count
     
  N = int(input())
  d = [int(i) for i in input().split()]
  print(q38(N, d))

### FIXED CODE ###

def check(N, d):
    numList = d
    numList.sort()
    
    if N % 2 != 0:
        print(0)
    else:
        print(numList[int(len(numList)/2)] - numList[int(len(numList)/2-1)])

N = int(input())
d = [int(i) for i in input().split()]
check(N, d)
ans=chk=0
h,w=map(int,input().split())
d=[[0]*w for i in range(h)]
l=[]
for i in range(h):
    a=input()
    chk+=a.count("#")
    l.append(a)
p=set([(0,0)])
while len(p):
    a,b=p.pop()
    for y,x in xy:
        y+=a
        x+=b
        if 0<=y<h and 0<=x<w and l[y][x]!="#":
            if d[y][x]==0 or d[y][x]>d[a][b]+1:
                d[y][x]=d[a][b]+1
                p.add((y,x))

print(-1 if d[h-1][w-1]==0 else h*w-1-chk-d[h-1][w-1])

### FIXED CODE ###

xy=[(1,0),(-1,0),(0,1),(0,-1)]
ans=chk=0
h,w=map(int,input().split())
d=[[0]*w for i in range(h)]
l=[]
for i in range(h):
    a=input()
    chk+=a.count("#")
    l.append(a)
p=set([(0,0)])
while len(p):
    a,b=p.pop()
    for y,x in xy:
        y+=a
        x+=b
        if 0<=y<h and 0<=x<w and l[y][x]!="#":
            if d[y][x]==0 or d[y][x]>d[a][b]+1:
                d[y][x]=d[a][b]+1
                p.add((y,x))

print(-1 if d[h-1][w-1]==0 else h*w-1-chk-d[h-1][w-1])
from itertools import combinations
L,R=map(int,input().split())
ans=L*R%2019
for i in combinations(range(L,R+1),2):
    if ans>=i[0]*i[1]%2019:
        ans=i[0]*i[1]%2019
print(ans)

### FIXED CODE ###

from itertools import combinations
L,R=map(int,input().split())
ans=L*R%2019
if R-L>=2018:
    print(0)
else:
    for i in combinations(range(L,R+1),2):
        if ans>=i[0]*i[1]%2019:
            ans=i[0]*i[1]%2019
    print(ans)
input = raw_input()

base = {"A":"T", "T":"A", "C":"T", "T":"C"}

print base[input]

### FIXED CODE ###

input = raw_input()
 
base = {"A":"T", "T":"A", "C":"G", "G":"C"}
 
print base[input]
H, W = tuple(map(int, input().split()))

P = [[-int(i) for i in input().replace("#", "0").replace(".", "1")]
     for i in range(H)]

queue_set = set()
for h in range(H):
    for w in range(W):
        if P[h][w] == 0:
            for dh, dw in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
                if 0 <= h+dh < H and 0 <= w+dw < W and P[h+dh][w+dw] == -1:
                    queue_set.add((h+dh)*W+w+dw)
        elif h == 0 or h == H-1 or w == 0 or w == W-1:
            queue_set.add(h*W+w)
m = 0

queue = [[q//W, q % W, 0] for q in queue_set]
idx = 0
while len(queue) != idx+1:
    h, w, cnt = queue[idx]
    idx += 1
    if P[h][w] == -1:
        P[h][w] = cnt+1
        a = 0
        for dh, dw in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
            if 0 <= h+dh < H and 0 <= w+dw < W:
                a = max(P[h+dh][w+dw], a)
                if P[h+dh][w+dw] == -1:
                    queue += [[h+dh, w+dw, cnt+1]]
        m = max(m, cnt+1 + a)

print(m)


### FIXED CODE ###

H, W = tuple(map(int, input().split()))
func = (lambda x: 0 if x == "#" else -1)
func_in = (lambda h, w: 0 <= h < H and 0 <= w < W)
P = [[func(i) for i in input()] for i in range(H)]

queue_set = set()
zeros = set()
for h in range(H):
    for w in range(W):
        if P[h][w] == 0:
            zeros.add((h)*W+w)
            for dh, dw in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
                if func_in(h+dh, w+dw) and P[h+dh][w+dw] == -1:
                    queue_set.add((h+dh)*W+w+dw)
m = 0

queue = [[q // W, q % W, 0] for q in queue_set]
queue_set |= zeros
idx = 0
cnt = 0
while len(queue) > idx:
    h, w, cnt = queue[idx]
    idx += 1
    cnt += 1
    P[h][w] = cnt
    a = 0
    for dh, dw in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
        if func_in(h+dh, w+dw) and (h+dh)*W+w+dw not in queue_set:
            queue += [[h + dh, w + dw, cnt]]
            queue_set.add((h+dh)*W+w+dw)
print(cnt)
while 1:
  H, W = map(int, raw_input().split())
  if (H == 0 and W == 0):
    break
 
      print ('#' * W)
      for i in range(1,H-1):
        print ('#' + '.' * (W - 2) + '#' )
      print ('#'* W)
  print" "
 

### FIXED CODE ###

while 1:
  H, W = map(int, raw_input().split())
  if (H == 0 and W == 0):
    break
 
  print ('#' * W)
  for i in range(1,H-1):
    print ('#' + '.' * (W - 2) + '#' )
  print ('#'* W)
  print""
S = list(input())
for i in range(1,4):
  if S[i] == S[i-1]:
    print("Bad")
	break
print("Good")

### FIXED CODE ###

S = list(input())
for i in range(1,4):
  if S[i] == S[i-1]:
    print("Bad")
    exit()
print("Good")
from sys import stdin

#Slist = list(S)
#A = list(map(int, input().split()))
chinpo = True
A = int(input())
B = int(input())
X = A + B
Y = A - B
Z = A * B
listo = []
listo.append(X)
listo.append(Y)
listo.append(Z)
print(max(listo))

### FIXED CODE ###


S = input().split()
X = int(S[0])+int(S[1])
Y = int(S[0])-int(S[1])
Z = int(S[0])*int(S[1])
if X >= Y:
    if X >= Z:
        print(X)
    else:
        print(Z)
else:
    if Y >= Z:
        print(Y)
    else:
        print(Z)
w, a, b = [int(i) for i in input().split()]
if a+w < b:
    print(fabs(b-a-w))
elif b+w < a:
    print(fabs(b-a-w))
else:
    print(0)

### FIXED CODE ###

import math
w, a, b = [int(i) for i in input().split()]
if a+w < b:
    print(int(math.fabs(b-a-w)))
elif b+w < a:
    print(int(math.fabs(b+w-a)))
else:
    print(int(0))
import sys
input = sys.stdin.readline

n, m = map(int, input().split())
broken_steps = [int(input()) for _ in range(m)]
#print(broken_steps)

def ptn_num(x): # 'x'stepまでのパターン数
    if x == 1:
        return 1
    else:
        dp = [0] * (x+1) # DP枠_including step'0'
        if broken_steps[0] == 1: # in case, step'1' broken 
            dp[:2] = 1, 0
        else:
            dp[:2] = 1, 1 # Usually

        for i in range(2, x+1):
            if i not in broken_steps: # 階段が壊れてない場合...
                tmp = (dp[i-1] + dp[i-2]) % (10**9+7)
                dp[i] = tmp
            # 壊れている場合は何もしない
        return dp[-1]

print(ptn_num(n))


### FIXED CODE ###

n, m = map(int, input().split())
a = set(map(int, [input() for _ in range(m)]))

dp = [0] * (n+1)
# 0段目と1段目は1通り（但し、１段目が壊れていない場合）（0 段目は「なにもしない」という から1 通り）
dp[:2] = 1, 1 if 1 not in a else 0 

for i in range(2, n+1):
    if i in a:
        continue
    else:
        dp[i] = (dp[i-1] + dp[i-2])

print(dp[-1] % (10**9+7))
import sympy
n = int(input())
a = list(map(int, input().split()))

print(sympy.gcd(a))

### FIXED CODE ###

import fractions
n = int(input())
a = list(map(int, input().split()))
ans = a[0]
for i in a:
    ans = fractions.gcd(ans, i)
print(ans)
def solve():
    h, w = map(int, input().split())
    a = [list(input()) for _ in range(h)]
    for i in range(h-1):
        for j in range(w-1):
            if a[i][j:j+2] == ["#","#"]:
                if a[i+1][j] == '#':
                    print("Impossible")
                    exit()
            if a[i][j:j+3] == ["#","#","#"] and n > w:
                if a[i+2][j] == '#':
                    print("Impossible")
                    exit()
    print("Possible")
    return 0

if __name__ == "__main__":
    solve()


### FIXED CODE ###

def solve():
    h, w = map(int, input().split())
    a = [list(input()) for _ in range(h)]
    for i in range(h-1):
        for j in range(w-1):
            if a[i][j:j+2] == ["#","#"]:
                if a[i+1][j] == '#':
                    print("Impossible")
                    exit()
        for k in range(1,w):
            if a[i][k] == "#":
                if a[i+1][k-2:k] == ["#","#"]:
                    print("Impossible")
                    exit()
    if a[h-2][-1] == "#":
        if a[h-1][-2] == "#":
            print("Impossible")
            exit()
    print("Possible")
    return 0

if __name__ == "__main__":
    solve()
a,b,c = map(int,input().split())
a -= b
print(a%c)

### FIXED CODE ###

a = (int)(input())
b = (int)(input())
c = (int)(input())
a-=b
print(a%c)
n,l=map(int.input().split())
c=[]
for i in range(n):
  c.append(input())
c.sort
print(c)

### FIXED CODE ###

n,l=map(int,input().split())
c=[]
for i in range(n):
  c.append(input())
c.sort()
print("".join(c))
def get_prime(N):
    if N < 2:
        return {1}
    prime = dict()
    prime[1] = 1

    i = 2
    while i*i <= N:
        while N % i == 0:
            if i in prime.keys():
                prime[i] += 1
            else:
                prime[i] = 1
            N = N//i
        i += 1
    if N != 1:
        prime[N] = 1
    return prime


n, p = [int(i) for i in input().strip().split()]


prims = get_prime(p)

ans = 1

if n == 1:
    print(p)
    quit()

for p, cnt in prims.items():
    _tmp = cnt//n
    ans *= p**(cnt//n)

print(ans)

### FIXED CODE ###


def get_prime(N):
    if N < 2:
        return {1:1}
    prime = dict()
    prime[1] = 1

    i = 2
    while i*i <= N:
        while N % i == 0:
            if i in prime.keys():
                prime[i] += 1
            else:
                prime[i] = 1
            N = N//i
        i += 1
    if N != 1:
        prime[N] = 1
    return prime


n, p = [int(i) for i in input().strip().split()]


prims = get_prime(p)

ans = 1


if n == 1:
    print(p)
    quit()

for p, cnt in prims.items():
    _tmp = cnt//n
    ans *= p**(cnt//n)

print(ans)
a= input()

if a>=30:
    print("Yes")
else:
    print("No")

### FIXED CODE ###

a= int(input())

if a>=30:
    print("Yes")
else:
    print("No")
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
import math
import time
#import random
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()
#sys.setrecursionlimit(10**6)
input=lambda: sys.stdin.readline().rstrip()

show_flg=False
show_flg=True

n=I()
g=[[] for i in range(n)]
c=[]
dc={}
for i in range(n-1):
    a,b=LI_()
    c.append((a,b))
    g[a].append(b)
    g[b].append(a)
    dc[(a,b)]=0

mxd=0
mxi=0
for i in range(n):
    m=len(g[i])
    if m=1:
        mxd=m
        mxi=i
        
#vには最短距離をセット & -1 で未訪問フラグ

v=[-1]*(n)

def bfs(x):
    p=deque()
    p.append(x)
    v[x]=0
    while p:
        c=p.popleft()
        col=0
        for i in g[c]:
            if v[i]==-1:
                if v[c]==col:col+=1
                p.append(i)
                v[i]=col
                dc[(c,i)]=col
                col+=1
    return

bfs(mxi)
print(mxd)
for i,j in c:
    print(dc[(i,j)]+1)
    
#show(v)


### FIXED CODE ###

from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from itertools import permutations,combinations
import sys
import bisect
import string
import math
import time
#import random
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()
#sys.setrecursionlimit(10**6)
input=lambda: sys.stdin.readline().rstrip()

show_flg=False
show_flg=True

n=I()
g=[[] for i in range(n)]
c=[]
dc={}
for i in range(n-1):
    a,b=LI_()
    c.append((a,b))
    g[a].append(b)
    g[b].append(a)
    dc[(a,b)]=0

mxd=0
mxi=0
for i in range(n):
    m=len(g[i])
    if m==1:
        mxd=m
        mxi=i
        
#vには最短距離をセット & -1 で未訪問フラグ

v=[-1]*(n)

def bfs(x):
    p=deque()
    p.append(x)
    v[x]=0
    while p:
        c=p.popleft()
        col=0
        for i in g[c]:
            if v[i]==-1:
                if v[c]==col and c!=x:col+=1
                p.append(i)
                v[i]=col
                dc[(c,i)]=col
                dc[(i,c)]=col
#                show(i,c,col)
                col+=1
    return

bfs(mxi)
print(max(v)+1)
for i,j in c:
    print(dc[(i,j)]+1)
    
#show(v)
N, K = input().split()

print((math.floor(math.log(N) / math.log(K)) + 1))

### FIXED CODE ###

def base_changer(number,base):
    buff=97+abs(base-10)
    dic={};buff2='';buff3=10
    for i in range(97,buff+1):
        dic[buff3]=chr(i)
        buff3+=1   
    while(number>=base):
        mod=int(number%base)
        number=int(number//base)
        if (mod) in dic.keys():
            buff2+=dic[mod]
            continue
        buff2+=str(mod)
    if (number) in dic.keys():
        buff2+=dic[number]
    else:
        buff2+=str(number)

    return buff2[::-1]  
N,K = map(int, input().split())
print(len(base_changer(N,K)))
while True:
    s = input()
    if s == '.':break
    while True:
        if s.find('+') == -1 and s.find('-') == -1:
            index = s.rfind('[')
            if index == -1:break
            e = s.find(']', index)
            s = s[:index] + s[index + 1:e][::-1] + s[e + 1:]
        else:
            index = s.find('+')
            if index == -1:
                index = s.find('-')
            if s.find('-') != -1
                index = min(index, s.find('-'))
            e = index
            f = 0
            while s[e] == '+' or s[e] == '-':
                f += [-1, 1][s[e] == '+']
                e += 1
            r = s[e]
            if r != '?':
                r = chr((ord(r) - ord('A') + f) % 26 + ord('A'))
            s = s[:index] + r + s[e + 1:]
    print(s.replace('?', 'A'))


### FIXED CODE ###

while True:
    s = input()
    if s == '.':break
    while True:
        if s.find('+') == -1 and s.find('-') == -1:
            index = s.rfind('[')
            if index == -1:break
            e = s.find(']', index)
            s = s[:index] + s[index + 1:e][::-1] + s[e + 1:]
        else:
            index = s.find('+')
            if index == -1:
                index = s.find('-')
            if s.find('-') != -1:
                index = min(index, s.find('-'))
            e = index
            f = 0
            while s[e] == '+' or s[e] == '-':
                f += [-1, 1][s[e] == '+']
                e += 1
            r = s[e]
            if r != '?':
                r = chr((ord(r) - ord('A') + f) % 26 + ord('A'))
            s = s[:index] + r + s[e + 1:]
    print(s.replace('?', 'A'))
a,b=map(int,input().split())
r=-1
for i in range(1001):
    if i*8//100==a and i*10//100==b:
        r=i
        break
print(r)

### FIXED CODE ###

s = input()
if s == "AAA":
  print("No")
elif s == "BBB":
  print("No")
else:
  print("Yes")
-*- coding: utf-8 -*-
     
    import sys
    import subprocess
    import json
    import time
    import math
    import re
    import sqlite3
     
    s = input()
    print(s.rfind("Z") - s.find("A") + 1)

### FIXED CODE ###

s = input()
     
a = s.find("A")
b = s.rfind("Z")
     
print(b-a+1)