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

N,K = map(int,input().split())
A = list(map(int,input().split()))
A_set = set(A)
L = len(A_set)
count = []

if L <= K:
  print(0)
else:
  for i in range(L):
    count.append(A.count(list(A_set)[i]))
  count.sort()
  
  print(sum(count[:len(count)-K]))

### FIXED CODE ###

from collections import deque

N,K = map(int,input().split())
A = list(map(int,input().split()))
nums = [0]*N

for i in range(N):
  nums[A[i]-1] += 1

nums.sort()

nums = deque(nums)

while True:
  if nums[0] == 0:
    nums.popleft()
  else:
    break
nums = list(nums)
if len(nums) <= K:
  print(0)
else:
  print(sum(nums[:len(nums)-K]))
### BUGGY CODE ###


def main():
    k = int(input())

    lunluns = list(range(1, 10))

    lunlun = -1

    for _ in range(k):
        lunlun = lunluns.pop(0)

        ones_place = lunlun % 10
        if ones_place > 0:
            lunluns.append(lunlun * 10 + ones_place -1)
        lunluns.append(lunlun * 10 + ones_place)
        if ones_place < 9:
            lunluns.append(lunlun * 10 + ones_place + 1)
    return lunlun

print(main())


### FIXED CODE ###

from collections import deque

def main():
    k = int(input())

    lunluns = deque(range(1, 10))

    lunlun = -1

    for _ in range(k):
        lunlun = lunluns.popleft()

        ones_place = lunlun % 10
        if ones_place > 0:
            lunluns.append(lunlun * 10 + ones_place -1)
        lunluns.append(lunlun * 10 + ones_place)
        if ones_place < 9:
            lunluns.append(lunlun * 10 + ones_place + 1)
    return lunlun

print(main())
### BUGGY CODE ###

n = int(input())
a = list(map(int,input().split()))
b = [0]*n
for i in range(n):
    for j in range(len(a)):
        if i + 1 == a[j]:
            b[i] += 1
    print(b[i])

   
    

### FIXED CODE ###

n = int(input())
a = list(map(int,input().split()))
b = [0]*n
for i in a:
    b[i - 1] += 1

for j in b:
    print(j)
### BUGGY CODE ###

import sys
input = sys.stdin.readline

S = input().rstrip()
Q = int(input())
query = [list(input().split()) for _ in range(Q)]

a = ''
ans = S
b = ''
flag = True

for i in range(Q):
    if query[i][0] == '1':
        if flag:
            flag = False
        else:
            flag = True
        continue
    elif query[i][0] == '2':
        f = query[i][1]
        c = query[i][2].rstrip()
        if f == '1' and flag:
            a = c + a
        elif f == '1' and not flag:
            b = b + c
        elif f == '2' and flag:
            b = b + c
        elif f == '2' and not flag:
            a = c + a
if flag:
    print(a + ans + b)
else:
    tmp = a + ans + b
    print(tmp[::-1])


### FIXED CODE ###

import sys
input = sys.stdin.readline

S = input().rstrip()
Q = int(input())
head = ''
tail = ''
rev = False

for _ in range(Q):
    query = list(input().split())
    if query[0] == '1':
        if rev:
            rev = False
        else:
            rev = True
    elif query[0] == '2':
        f = query[1]
        c = query[2].rstrip()
        if f == '1':
            if rev:
                tail = tail + c
            else:
                head = c + head
        else:
            if rev:
                head = c + head
            else:
                tail = tail + c
if rev:
    tmp = head + S + tail
    print(tmp[::-1])
else:
    print(head + S + tail)
### BUGGY CODE ###

import sys

readline = sys.stdin.readline
n, q = map(int, readline().split())
s = readline().rstrip()
ac = [False] * (n - 1)
for i, x in enumerate(zip(s, s[1:])):
    if x == ('A', 'C'):
        ac[i] = True
for _ in range(q):
    l, r = map(int, readline().split())
    print(sum(ac[l-1:r-1]))


### FIXED CODE ###

import sys
from itertools import accumulate

readline = sys.stdin.readline
n, q = map(int, readline().split())
s = readline().rstrip()
ac = [False] * (n - 1)
for i, x in enumerate(zip(s, s[1:])):
    if x == ('A', 'C'):
        ac[i] = True
ac = [0] + list(accumulate(ac))
for _ in range(q):
    l, r = map(int, readline().split())
    print(ac[r-1] - ac[l-1])
### BUGGY CODE ###

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

def kurikaeshi(x, n, mod):
    if n == 1:
        return x%mod
    elif n %2 == 0:
        return kurikaeshi(x, n//2, mod)**2%mod
    elif n %2 == 1:
        return kurikaeshi(x, n//2, mod)**2*x%mod
    
    
def combination(n, a, mod):
    bunbo = 1
    bunshi = 1
    for i in range(a):
        bunshi *= n-i
        bunbo *= a-i
        
    return bunshi*(pow(bunbo, mod-2, mod)%mod)
        
        
mod = 1000000007
answer = pow(2, n, mod)
answer -= 1
answer -= combination(n, a, mod)
answer -= combination(n, b, mod)
print(answer%mod)

### FIXED CODE ###

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

def kurikaeshi(x, n, mod):
    if n == 1:
        return x%mod
    elif n %2 == 0:
        return kurikaeshi(x, n//2, mod)**2%mod
    elif n %2 == 1:
        return kurikaeshi(x, n//2, mod)**2*x%mod
    
    
def combination(n, a, mod):
    bunbo = 1
    bunshi = 1
    for i in range(a):
        bunshi *= n-i
        bunshi = bunshi%mod
        bunbo *= a-i
        bunbo = bunbo%mod
        
    return bunshi*pow(bunbo, mod-2, mod)%mod
        
        
mod = 1000000007
answer = pow(2, n, mod)
answer -= 1
answer -= combination(n, a, mod)
answer -= combination(n, b, mod)
print(answer%mod)
### BUGGY CODE ###

def d_ki():
    N, Q = [int(i) for i in input().split()]

    tree = [[] for _ in range(N)]
    for _ in range(N - 1):
        a, b = [int(i) for i in input().split()]
        tree[a - 1].append(b - 1)
        tree[b - 1].append(a - 1)

    ans = [0] * N
    for _ in range(Q):
        p, x = [int(i) for i in input().split()]
        ans[p - 1] += x

    # 1次元配列だったら単純に累積和を取ればいいのだが、木なので
    # DFSをしなければならない
    q = [0]
    is_visited = [False] * N
    while q:
        current = q.pop()
        is_visited[current] = True
        for child in tree[current]:
            if is_visited[child]:
                continue
            ans[child] += ans[current]
            q.append(child)
    return ' '.join(map(str, ans))

print(d_ki())

### FIXED CODE ###

def d_ki():
    import sys
    input = sys.stdin.readline
    N, Q = [int(i) for i in input().split()]

    tree = [[] for _ in range(N)]
    for _ in range(N - 1):
        a, b = [int(i) for i in input().split()]
        tree[a - 1].append(b - 1)
        tree[b - 1].append(a - 1)

    ans = [0] * N
    for _ in range(Q):
        p, x = [int(i) for i in input().split()]
        ans[p - 1] += x

    # 1次元配列だったら単純に累積和を取ればいいのだが、木なので
    # DFSをしなければならない
    q = [0]
    is_visited = [False] * N
    while q:
        current = q.pop()
        is_visited[current] = True
        for child in tree[current]:
            if is_visited[child]:
                continue
            ans[child] += ans[current]
            q.append(child)
    return ' '.join(map(str, ans))

print(d_ki())
### BUGGY CODE ###

import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n,k = list(map(int, input().split()))
v0 = [[0]*(4*k) for _ in range(4*k)]
v1 = [[0]*(4*k) for _ in range(4*k)]

for i in range(n):
    x,y,c = input().split()
    x = int(x)
    y = int(y)
    x %= 2*k
    y %= 2*k
    if c=="W":
        v = v0
    else:
        v = v1
    v[x][y] += 1
    v[x][y+2*k] += 1
    v[x+2*k][y] += 1
    v[x+2*k][y+2*k] += 1
def cumsum2(v):
    # v: h*wの2次元リスト
    h,w = len(v), len(v[0])
    v.insert(0, [0]*w)
    for l in v:
        l.insert(0, 0)
    for i in range(1,h+1):
        for j in range(1,w+1):
            v[i][j] = v[i-1][j] + v[i][j-1] - v[i-1][j-1] + v[i][j]
    return v
c0 = cumsum2(v0)
c1 = cumsum2(v1)
ans = -1
for i in range(2*k):
    for j in range(2*k):
        val0 = c0[i+k][j+k]-c0[i+k][j]-c0[i][j+k]+c0[i][j] + c0[i+2*k][j+2*k]-c0[i+2*k][j+k]-c0[i+k][j+2*k]+c0[i+k][j+k]
        val1 = c1[i+2*k][j+k]-c1[i+2*k][j]-c1[i+k][j+k]+c1[i+k][j] + c1[i+k][j+2*k]-c1[i+k][j+k]-c1[i][j+2*k]+c1[i][j+k]
        ans = max(ans, val0+val1)
print(ans)

### FIXED CODE ###

import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")



n,k = list(map(int, input().split()))
v = [[0]*(2*k) for _ in range(2*k)]

for i in range(n):
    x,y,c = input().split()
    x = int(x)
    y = int(y)
    if c=="B":
        x += k
    x %= 2*k
    y %= 2*k
    v[x][y] += 1
#     v[x][y+2*k] += 1
#     v[x+2*k][y] += 1
#     v[x+2*k][y+2*k] += 1
def cumsum2(v):
    # v: h*wの2次元リスト
    h,w = len(v), len(v[0])
    v.insert(0, [0]*w)
    for l in v:
        l.insert(0, 0)
    for i in range(1,h+1):
        for j in range(1,w+1):
            v[i][j] = v[i-1][j] + v[i][j-1] - v[i-1][j-1] + v[i][j]
    return v
cumsum2(v)

def sub(c, i, j):
    i %= 2*k
    j %= 2*k
    l = []
    if i<=k and j<=k:
        l = [[i,i+k,j,j+k]]
    elif i>k and j<=k:
        l = [[i,2*k,j,j+k], [0,i-k,j,j+k]]
    elif i<=k and j>k:
        l = [[i,i+k,j,2*k], [i,i+k,0,j-k]]
    else:
        l = [[i,2*k,j,2*k], [0,i-k,j,2*k], [i,2*k,0,j-k], [0,i-k,0,j-k]]
    return sum((c[z][w] - c[z][y] - c[x][w] + c[x][y]) for x,z,y,w in l)
ans = -1
for i in range(2*k):
    for j in range(2*k-i):
        val0 = sub(v, i,j) + sub(v, i+k, j+k)
#         val0 = v[i+k][j+k]-v[i+k][j]-v[i][j+k]+v[i][j] + v[i+2*k][j+2*k]-v[i+2*k][j+k]-v[i+k][j+2*k]+v[i+k][j+k]
#         val1 = v[i+2*k][j+k]-v[i+2*k][j]-v[i+k][j+k]+v[i+k][j] + v[i+k][j+2*k]-v[i+k][j+k]-v[i][j+2*k]+v[i][j+k]
        ans = max(ans, val0)
print(ans)
### BUGGY CODE ###

from math import floor
A,B,N=map(int,input().split())

x=N
result=[]
maxr=0
for x in reversed(range(1,N+1)):
    r=0 if x<B else A*floor(x/B)
    ans=floor(A*x/B)-r
    result.append(ans)
    if len(result) == 1:
        maxr = ans 
    if len(result) > 1 and max(result) == maxr:
        pass

print(max(result))


### FIXED CODE ###

from math import floor
A,B,N=map(int,input().split())

x=min(B-1,N)

print(floor(A*x/B)-A*floor(x/B))
### BUGGY CODE ###

import sys


N,P = map(int,input().split())
S = list(sys.stdin.readline().rstrip())

A = [0]*(N)
A[-1] = int(S[-1])
A[-1] %= P
base = 10
for i in reversed(range(N-1)):
    A[i] = A[i+1] + base*int(S[i])
    A[i] %= P
    base *= 10


ans = 0
if P==2 or P==5:
    for i in reversed(range(N)):
        if int(S[i])%P==0:
            ans += i+1
else:
    nums = {}
    for a in A:
        if not (a in nums):
            nums[a] = 1
        else:
            nums[a] += 1
    
    for n in nums.keys():
        k = nums[n]
        if n==0:
            ans += k*(k+1)//2
        else:
            ans += k*(k-1)//2
    
print(ans)    



### FIXED CODE ###

import sys


N,P = map(int,input().split())
S = list(input())

A = [0]*(N)
A[-1] = int(S[-1])
A[-1] %= P
base = 10 % P
for i in reversed(range(N-1)):
    A[i] = A[i+1] + base*int(S[i])
    A[i] %= P
    base *= 10
    base %= P


ans = 0
if P==2 or P==5:
    for i in reversed(range(N)):
        if int(S[i])%P==0:
            ans += i+1
else:
    nums = {}
    for a in A:
        if not (a in nums):
            nums[a] = 1
        else:
            nums[a] += 1
    
    for n in nums.keys():
        k = nums[n]
        if n==0:
            ans += k*(k+1)//2
        else:
            ans += k*(k-1)//2
    
print(ans)
### BUGGY CODE ###

import math
def naive_cmb(n, r):
    if r < 0 or r > n:
        return 0
    return (math.factorial(n) // math.factorial(r)) // math.factorial(n-r)

S = input()

mod = [0] * (2019+1)

tmp = ""
for i in range(1, len(S)+1):
    tmp = int(S[-i] + str(tmp))
    mod[tmp % 2019] += 1

ans = mod[0]

for i in range(1, 2020):
    if mod[i] >= 2:
        ans += naive_cmb(mod[i], 2)

print(ans)

### FIXED CODE ###

S = input()

n_i_to_j_mod = [0] * (2019+1) # 2019で割った余りがiになるようなSの部分連続文字列の個数
i_to_end_mod = [0] * (len(S)+1) # S[-i:](Sの後方i文字)を2019で割ったときの余り

for i in range(1, len(S)+1):
    if i == 1:
        i_to_end_mod[1] = int(S[-1]) % 2019
    else:
        i_to_end_mod[i] = (i_to_end_mod[i-1] + int(S[-i]) * pow(10, i-1, 2019)) % 2019
    n_i_to_j_mod[i_to_end_mod[i]] += 1

ans = n_i_to_j_mod[0] + (n_i_to_j_mod[0] * (n_i_to_j_mod[0]-1))//2
for i in range(1, 2019):
    if n_i_to_j_mod[i] >= 2:
        ans += (n_i_to_j_mod[i] * (n_i_to_j_mod[i]-1)) // 2
print(ans)
### BUGGY CODE ###

import numpy as np
N, K = map(int, input().split())
A = list(map(int, input().split()))
sumlist = np.sort(np.array([sum(A[j:j+N-i]) for i in range(N) for j in range(i+1)]))[::-1]
ans = sumlist[0]
for i in range(40, -1, -1):
    tmp = (ans & (2 ** i)) // (2 ** i)
    if tmp:
        start = i
        break
f = lambda x: (x & onehot) // onehot
ans_list = [0]
for i in range(start, -1, -1):
    onehot = 2 ** i
    tmp = list(map(f, sumlist))
    if sum(tmp) >= K:
        and_result = np.array(tmp).astype(np.bool)
        sumlist = sumlist[and_result]
        ans = sumlist[0]
        for j in range(1, K):
            ans = ans & sumlist[j]
        ans_list.append(ans)
print(max(ans_list))


### FIXED CODE ###

from collections import Counter
N, K = map(int, input().split())
A = list(map(int, input().split()))
cusum = [A[0]]
for i in range(1, N):
    cusum += [cusum[-1]+A[i]]
B = []
for i in range(N):
    B += [cusum[i]]
    for j in range(i+1, N):
        B += [cusum[j] - cusum[i]]
max_bit = 43
ans = 0
while max_bit > 0:
    counter = Counter()
    for b in B:
        for i in range(44):
            if b & 1 == 1:
                counter[i] += 1
            b = b >> 1
    for i in range(max_bit, -1, -1):
        if counter[i] >= K:
            filter_bit = 2 ** i
            B = [b for b in B if b & filter_bit == filter_bit]
            max_bit = i-1
            ans += filter_bit
            break
        max_bit = i
print(ans)
### BUGGY CODE ###

n=int(input())
poll=[input() for i in range(n)]
poll2=list(set(poll))

dic={poll2[i]:0 for i in range(len(poll2))}
for string in poll:
    dic[string]+=1

max_k=[k for k, v in dic.items() if v == max(dic.values())]
max_k.sort()
print(*max_k,sep='\n')

### FIXED CODE ###

def main():
  n=int(input())
  poll=[input() for i in range(n)]

  dic={}
  for string in poll:
    if string not in dic:
      dic[string]=1
    else:
      dic[string]+=1
  
  x=max(dic.values()) 
  max_k=[k for k, v in dic.items() if v==x]
  max_k.sort()
  print(*max_k,sep='\n')
  
if __name__=='__main__':
  main()
### BUGGY CODE ###

N = int(input())
As = list(map(int, input().split()))
ans = 1
for n in range(N):
    ans *= As[n]
if ans <= 1e18:
    print(int(ans))
else:
    print(-1)

### FIXED CODE ###

N = int(input())
As = list(map(int, input().split()))
if 0 in As:
    print(0)
else:
    As = sorted(As, reverse=True)
    ans = 1
    break_flag = 0
    for n in range(N):
        ans *= As[n]
        if ans > 1e18:
            print(-1)
            break_flag = 1
            break
    if break_flag == 0:
        print(ans)
### BUGGY CODE ###

"""
D - String Formation
"""
s = input()
q = int(input())
string = []
for i in range(q):
    string.append(input())

for emir in string:
    if emir[0] == '1':
        s = s[::-1]
    if emir[0] == '2':
        if emir[2] == '1':
            s = emir[4] + s
        elif emir[2] == '2':
            s += emir[4]

print(s)

### FIXED CODE ###

s = input()
q = int(input())
string = []
is_normal = 1
saq = ""
sol = ""
for i in range(q):
    emir = input()
    if emir[0] == '1':
        is_normal *= -1
    elif emir[0] == '2':
        if is_normal == 1:
            if emir[2] == '1':
                sol += emir[4]
            elif emir[2] == '2':
                saq += emir[4]
        else:
            if emir[2] == '1':
                saq += emir[4]
            elif emir[2] == '2':
                sol += emir[4]
s = sol[::-1] + s + saq
if is_normal == -1:
    s = s[::-1]

print(s)
### BUGGY CODE ###

import sys
sys.setrecursionlimit(10**8)
N, L = map(int, input().split())
W = []
V = []
for _ in range(N):
    w, v = map(int, input().split())
    W.append(w)
    V.append(v)


dp = [[-1] * (L+100) for _ in range(N+10)]


def knap(i, j):
    if dp[i][j] >= 0:
        return dp[i][j]

    if i == N:
        dp[i][j] = 0
    elif j < W[i]:
        dp[i][j] = knap(i+1, j)
    else:
        dp[i][j] = max(knap(i+1, j), knap(i+1, j - W[i]) + V[i])

    return dp[i][j]


print(knap(0, L))


### FIXED CODE ###

N, W = map(int, input().split())
T = [list(map(int, input().split())) for _ in range(N)]

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

for i in range(1, N+1):
    for w in range(1, W+1):
        dp[i][w] = max(dp[i-1][w], dp[i-1][w - T[i-1][0]] + T[i-1]
                       [1]) if w - T[i-1][0] >= 0 else dp[i-1][w]

# print(*dp, sep='\n')
print(dp[N][W])
### BUGGY CODE ###

from collections import deque
s = deque(input())
stack = []
ans = 0
while len(s):
    stack.append(s.popleft())
    if len(stack) >= 3 and \
        stack[-3:] == ['A', 'B', 'C']:
        del stack[-3:]
        s.appendleft('A')
        s.appendleft('C')
        s.appendleft('B')
        ans += 1

print(ans)

### FIXED CODE ###

s = input().replace('BC', 'D')
s = s.replace('B', 'C')
l = [x for x in s.split(sep='C') if x != '']
ans = 0
for subs in l:
    numA = 0
    for c in subs:
        if c == 'A':
            numA += 1
        elif c == 'D':
            ans += numA

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

n=int(input())
x,y,h=[0]*n,[0]*n,[0]*n
for i in range(n):
  x[i],y[i],h[i]=map(int,input().split())

for cx in range(101):
  for cy in range(101):
    for i in range(n):
      b=h[i]+abs(x[i]-cx)+abs(y[i]-cy)
      if i==0:
        if h[i]:
          s=set()
          s.add(b)
        else:
          s={i for i in range(b+1)}
      else:
        if not s:break
        if h[i]:
          s&=set([b])
        else:
          s&=set(range(b+1))
    if s:
      print(cx,cy,s.pop())
      exit()

### FIXED CODE ###

import sys
n=int(input())

l=[list(map(int,input().split())) for i in range(n)]
l.sort(key=lambda x:-x[2])

for cx in range(101):
  for cy in range(101):
    for i in range(n):
      x,y,h=l[i]
      b=h+abs(x-cx)+abs(y-cy)
      if i==0:
        if h:
          s=set()
          s.add(b)
        else:
          s={i for i in range(b+1)}
      else:
        if not s:break
        if h:
          s&=set([b])
        else:
          s&=set(range(b+1))
    if s:
      print(cx,cy,s.pop())
      sys.exit()
### BUGGY CODE ###

from collections import deque

def bfs(s, t, n, V):
    q = deque([(s, 0)])
    used = [False] * (n+1)
    while q:
        a, dist = q.popleft()
        used[a] = True
        if a==t:
            break
        for b in V[a]:
            if used[b]:continue
            q.append((b, dist+1))
    if a!=t:
        return -1
    else:
        return -1 if dist%3 else dist//3


def solve():
    INF = 10**25
    N, M = map(int, input().split())
    V = {i:[] for i in range(1, 3*N+1)}
    for _ in range(M):
        u, v = map(int, input().split())
        V[u].append(v+(N))
        V[u+(N)].append(v+(2*N))
        V[u+(2*N)].append(v)

    S, T = map(int, input().split())
    dist = bfs(S, T, 3*N, V)
    print(dist)


if __name__ == "__main__":
    solve()

### FIXED CODE ###

from collections import defaultdict, deque
from heapq import heappush, heappop


def bfs(V, s, t):
    q = deque([(0, s)])
    used = set()
    
    while q:
        dist, a = q.popleft()
        used.add(a)
        if a == t:
            break
        for b in V[a]:
            if b in used: continue
            q.append((dist+1, b))
    
    if a != t:
        dist = -1
    else:
        dist = -1 if dist%3 else dist//3
    return dist

def dijkstra1(V, n, source):
    # O(ElogV)

    inf = float("inf")
    dist = [inf] * (n+1)
    dist[source] = 0
    q = [(0, source)]

    while q:
        cost, u = heappop(q)
        if dist[u] < cost:
            continue
        for c, v in V[u]:
            if dist[v] > dist[u] + c:
                dist[v] = dist[u] + c
                heappush(q, (dist[v], v))

    return dist


if __name__ == "__main__":
    V = defaultdict(list)
    N, M = map(int, input().split())
    for _ in range(M):
        u, v = map(int, input().split())
        V[u].append((1, v+(N)))
        V[u+(N)].append((1, v+(2*N)))
        V[u+(2*N)].append((1, v))

    S, T = map(int, input().split())
    dist = dijkstra1(V, 3*N, S)[T]
    print(-1 if dist==float("inf") else dist//3)
### BUGGY CODE ###

import copy
n = int(input())
d = []
for i in range(n - 1):#h:高さ
    d.append([int(m) for m in input().split()])
q, k = map(int, input().split())
z = []
for i in range(q):#h:高さ
    z.append([int(m) for m in input().split()])
e = []
for i in range(n):
    e.append([])
for i in d:
    e[i[0] - 1].append(i)
    e[i[1] - 1].append(i)
f = {}
for i in range(1, n + 1):
    if i != k:
        f[i] = 0
ar = []
pre = {}

for i in e[k - 1]:
    if k == i[0]:
        ar.append(i[1])
        f[i[1]] = i[2]
        pre[i[1]] = k
    else:
        ar.append(i[0])
        f[i[0]] = i[2]
        pre[i[0]] = k
while min(f.values()) == 0:
    ar2 = copy.deepcopy(ar)
    ar = []
    for j in ar2:
        for m in e[j - 1]:
                if j == m[0]:
                    if m[1] != pre[j]:
                        ar.append(m[1])
                        f[m[1]] = m[2] + f[j]
                        pre[m[1]] = j
                else:
                    if m[0] != pre[j]:
                        ar.append(m[0])
                        f[m[0]] = m[2] + f[j]
                        pre[m[0]] = j
for i in range(q):#h:高さ
    print(f[z[i][0]] + f[z[i][1]])
"""  
adj = []
for i in range(n):
    adj.append([])
for i in range(n):
    for j in range(n):
        adj[i].append(0)
#鱗屑行列
for i in range(q):
    adj[d[i][0] - 1][d[i][1] - 1] = d[i][2]
    adj[d[i][1] - 1][d[i][0] - 1] = d[i][2]"""

### FIXED CODE ###

n = int(input())
d = []
for i in range(n - 1):#h:高さ
    d.append([int(m) for m in input().split()])
q, k = map(int, input().split())
z = []
for i in range(q):#h:高さ
    z.append([int(m) for m in input().split()])

for i in range(n - 1):
    d[i][0] -= 1
    d[i][1] -= 1
for i in range(q):
    z[i][0] -= 1
    z[i][1] -= 1
def BFS(k, edges, N):
  roots=[ [] for i in range(N)]
  for a,b,c in edges:
    roots[a]+=[(b,c)]
    roots[b]+=[(a,c)]
  dist=[-1]*N
  stack=[]
  stack.append(k)
  dist[k]=0
  while stack:
    label=stack.pop(-1)
    for i,c in roots[label]:
      if dist[i]==-1:
        dist[i]=dist[label]+c
        stack+=[i]
  return dist

root = BFS(k - 1, d, n)

for i in range(q):
    print(root[z[i][0]] + root[z[i][1]])