Harryxun/stf_run huggingface dataset:
# coding: utf-8

H, W = map(int, input().split())
S = []
for i in range(H):
    S.append(list(input()))
ans = 'Yes'
endFlg = False

# 4隅
if S[0][0] == '#' and S[0][1] == '.' and S[1][0] == '.':
    ans = 'No'
    endFlg = True
if S[0][W - 1] == '#' and S[0][W - 2] == '.' and S[1][W - 1] == '.':
    ans = 'No'
    endFlg = True
if S[H - 1][0] == '#' and S[H - 1][1] == '.' and S[H - 2][0] == '.':
    ans = 'No'
    endFlg = True
if S[H - 1][W - 1] == '#' and S[H - 1][W - 2] == '.' and S[H - 2][W - 1] == '.':
    ans = 'No'
    endFlg = True

# 上辺
if endFlg != True:
    for j, c in enumerate(S[0][1:W - 1]):
        if c == '#':
            if (S[1][j+1] == '.' and S[0][j + 2] == '.' and S[0][j] == '.'):
                ans = 'No'
                endFlg = True

if endFlg != True:
    # 下辺
    for j, c in enumerate(S[H - 1][1:W - 1]):
        if c == '#':
            if (S[H-2][j+1] == '.' and S[H-1][j + 2] == '.' and S[H-1][j] == '.'):
                ans = 'No'
                endFlg = True

if endFlg != True:
    # 左辺
    for i, c in enumerate(S[1:H - 2][0]):
        if c == '#':
            if (S[i+1][1] == '.' and S[i][0] == '.' and S[i+2][0] == '.'):
                ans = 'No'
                endFlg = True

if endFlg != True:
    # 右辺
    for i, c in enumerate(S[1:H - 2][W - 2]):
        if c == '#':
            if (S[i+1][W-2] == '.' and S[i][W-1] == '.' and S[i+2][W-1] == '.'):
                ans = 'No'
                endFlg = True

for i, r in enumerate(S[1:H - 1][1:W - 2]):
    for j, c in enumerate(r):
        if c == '#':
            if (S[i - 1][j] == '.' and S[i][j + 1] == '.' and S[i + 1][j] == '.' and S[i][j - 1] == '.'):
                ans = 'No'
                endFlg = True
                break
    if endFlg == True:
        break

print(ans)


### FIXED CODE ###

# coding : utf-8

H, W = map(int, input().split())
S = []
for i in range(H):
    S.append(list(input()))

ans = 'Yes'
endFlg = False
# '#'の点をみつけたときに、その上下左右に'#'がない場合、孤立した点を黒く塗ることはできないので、答えはNoとなる。
# 全部の'#'の点について、その上下左右のいずれかに'#'が見つかれば、答えはYesとなる。

for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            if i != 0 and S[i-1][j] == '#':
                continue
            elif i != H-1 and S[i+1][j] == '#':
                continue
            elif j != 0 and S[i][j-1] == '#':
                continue
            elif j != W-1 and S[i][j+1] == '#':
                continue
            else :
                ans = 'No'
                endFlg = True
                break
    if endFlg:
        break

print(ans)
import numpy as np
n = int(input())
x = [int(i) for i in input().split()]

_list = [-1 for i in range(100)]
if n==1:
    print(0)
else:
    for i in range(min(x), max(x), 1):
        a = 0
        for j in range(n):
            a += (x[j]-i)**2
        _list[i] = a
    _list = np.array(_list)
    print(min(_list[_list>=0]))

### FIXED CODE ###

import numpy as np
n = int(input())
x = [int(i) for i in input().split()]

_list = [-1 for i in range(100)]
if min(x)==max(x):
    print(0)
else:
    for i in range(min(x), max(x), 1):
        a = 0
        for j in range(n):
            a += (x[j]-i)**2
        _list[i] = a
    _list = np.array(_list)
    print(min(_list[_list>=0]))
# DP sample 2

N, K = [int(x) for x in input().split()] 
h = [int(x) for x in input().split()]

def chmin(a, b):
    return a if a <= b else b

dp = [float('inf')] * N
dp[0] = 0
for i in range(N):
    for j in range(1, K+1):
        if i + j > len(dp):
            break
        else:
            dp[i+j] = chmin(dp[i+j], dp[i] + abs(h[i] - h[i+j]))
        
print(dp[-1])

### FIXED CODE ###


N, K = [int(x) for x in input().split()] 
h = [int(x) for x in input().split()]

def chmin(a, b):
    return a if a <= b else b

dp = [float('inf')] * N
dp[0] = 0
for i in range(N):
    for j in range(1, K+1):
        if i + j >= len(dp):
            break
        else:
            dp[i+j] = chmin(dp[i+j], dp[i] + abs(h[i] - h[i+j]))
        
print(dp[-1])
def insertion_sort(A, N):
  for i in range(len(N):
    v = A[i]
    j = i - 1
    while j >= 0 and a[j] > v:
      A[j + 1] = A[j]
      j--
    A[j + 1] = v

if __name__=='__main__':
   n=int(input()) 
   A=list(map(int,input().split()))
   insertion_sort(A)
   print(*A)

### FIXED CODE ###

# -*- coding: utf-8 -*-


def insertion_sort(a, n):
    for i in range(n):
        tmp = a[i]
        j = i - 1
        while j >= 0 and a[j] > tmp:
            a[j + 1] = a[j]
            j -= 1
        a[j + 1] = tmp
        print(' '.join(map(str, a)))

if __name__ == '__main__':
    n = int(input())
    a = [int(n) for n in input().split()]
    insertion_sort(a, n)
N, M = map(int, input().split())
X = list(map(int, input().split()))

if N>=M:
  print(0)
else:
  X.sort()
  Y=[]
  for i in range(len(X)-1):
    Y.append([i,X[i+1]-X[i]])
  Y.sort(reverse=True, key=lambda x:x[1])
  ans=0
  old=0
  for i in range(N-1):
    tmp=X[old:Y[i][0]+1]
    ans+=max(tmp)-min(tmp)
    old=Y[i][0]+1
  else:
    if old<len(X):
      tmp=X[old:]
      ans+=max(tmp)-min(tmp)
  print(ans)

### FIXED CODE ###

N, M = map(int, input().split())
X = list(set(map(int, input().split())))
M = len(X)

if N>=M:
  print(0)
else:
  X.sort()
  Y=[]
  for i in range(len(X)-1):
    Y.append([i,X[i+1]-X[i]])
  Y.sort(reverse=True, key=lambda x:x[1])
  Y=Y[:N-1]
  Y.sort()
  ans=0
  old=0
  for i in range(N-1):
    tmp=X[old:Y[i][0]+1]
    ans+=max(tmp)-min(tmp)
    old=Y[i][0]+1
  else:
    if old<len(X):
      tmp=X[old:]
      ans+=max(tmp)-min(tmp)
  print(ans)
import statistics as st

while True:
    n = float(input())
    if n == 0:
        break
    scores = list(map(float, input().split()))
    std = st.stdev(scores)
    print(std)


### FIXED CODE ###

import math

while True:
    n = float(input())
    aan = 0
    if n == 0:
        break
    scores = list(map(float, input().split()))
    total = sum(scores)
    avg = total / len(scores)
    for score in scores:
        aan += (score - avg)**2
    aa = aan / len(scores)
    a = math.sqrt(aa)
    print(a)
# B - Five Dishes
import numpy as np
n=[]
for i in range(5):
    t = int(input())
    n.append(t)
n = np.array(n)
dl = [0]
m = [e for e in n%10 if e not in dl]
s = np.ceil(n/10)*10
print(int(np.sum(s)-(10-min(m))))

### FIXED CODE ###

# B - Five Dishes
import numpy as np
n=[]
for i in range(5):
    t = int(input())
    n.append(t)
n = np.array(n)
dl = [0]
s = np.ceil(n/10)*10

if max(n%10)==0:
    print(int(np.sum(s)))
    exit()
m = [e for e in n%10 if e not in dl]
print(int(np.sum(s)-(10-min(m))))
a, b = map(int, input().split())
if a >= 13:
    print(b)
elif 12 => a >= 6:
    print(b / 2)
elif: 5 >= a:
    print(0)

### FIXED CODE ###

a, b = map(int, input().split())
if a >= 13:
    print(b)
elif 13 > a > 5:
    print(b // 2)
elif 5 >= a:
    print(0)
a,b=map(int,input().split())
c=[a+b,a-b,a*b]
c.sort()
print(c[3])

### FIXED CODE ###

a,b=map(int,input().split())
c=[a+b,a-b,a*b]
c.sort()
print(c[2])
N = int(input())
G = [[] for i in range(N)]
for i in range(N-1):
  u, v, w = list(map(int, input().split()))
  u -= 1
  v -= 1
  w = w % 2
  G[u].append([v, w])
  G[v].append([u, w])
  
res = [-1] * N
def dfs(u, p, c):
  if res[u] == -1:
    res[u] = c
    for n in G[u]:
      if n[0] == p:
        continue
      if n[1] == 1:
        dfs(n[0], u, 1-c)
      else:
        dfs(n[0], u, c)
  
def main():
  dfs(0, -1, 1)
  for i in res:
    print(i)
  
  
if __name__ == "__main__":
  main()

### FIXED CODE ###

N = int(input())
G = [[] for i in range(N)]
for i in range(N-1):
  u, v, w = list(map(int, input().split()))
  u -= 1
  v -= 1
  w = w % 2
  G[u].append([v, w])
  G[v].append([u, w])
  
res = [-1] * N
"""
def dfs(u, p, c):
  res[u] = c
  for n in G[u]:
    if n[0] == p or res[n[0]] != -1:
      continue
    if n[1] == 1:
      dfs(n[0], u, 1-c)
    else:
      dfs(n[0], u, c)
"""
from collections import deque
q = deque()
# 再帰はメモリ的に厳しい？？
def search(q):
  while q:
    u, p, c = q.popleft()
    if res[u] == -1:
      for n in G[u]:
        if n[0] == p or res[n[0]] != -1:
          continue
        if n[1] == 1:
          q.append((n[0], u, 1-c))
        else:
          q.append((n[0], u, c))
    res[u] = c
  
  
def main():
  q.append((0, -1, 1))
  search(q)
  for i in res:
    print(i)
  
  
if __name__ == "__main__":
  main()
c

### FIXED CODE ###

n,m=map(int,input().split())
print((n-1)*(m-1))
import sys
import resource

sys.setrecursionlimit(10 ** 9)
resource.setrlimit(resource.RLIMIT_STACK, ((2 ** 7) * 1000 * 1000, -1))

k = int(input())

ary = [1, 2, 3, 4, 5, 6, 7, 8, 9]

def ans(j, nums):
    nums[j] += 1
    pre = nums[j]
    for i in range(j + 1, len(nums)):
        if pre > 0:
            nums[i] = pre - 1
            pre = nums[i]
        else:
            nums[i] = pre
    return int(''.join(map(str, nums)))

def lunlun(n):
    if n <= 9:
        return ary[n - 1]
    l = lunlun(n - 1)
    nums = list(map(int, list(str(l))))
    first = len(nums) - 1
    last = 0
    for i in range(len(nums)):
        j = len(nums) - i - 1
        c = nums[j] + 1
        # 桁数が変わらないとき
        if j == first:
            # 1桁目
            if nums[j] < 9 and abs(nums[j - 1] - c) <= 1:
                nums[j] += 1
                return int(''.join(map(str, nums)))
        elif j == last:
            # 最終桁
            if nums[j] < 9 and abs(nums[j + 1] - c) <= 1:
                return ans(j, nums)
        elif j != first and j != last:
            # 間の桁
            if nums[j] < 9 and abs(nums[j - 1] - c) <= 1 and abs(nums[j + 1] - c) <= 1:
                return ans(j, nums)

    # 桁が繰り上がるとき
    return int('1' + ''.join(['0'] * len(nums)))

print(lunlun(k))


### FIXED CODE ###

import sys
# import resource

sys.setrecursionlimit(10 ** 9)
# resource.setrlimit(resource.RLIMIT_STACK, ((2 ** 7) * 1000 * 1000, -1))

k = int(input())

ary = [1, 2, 3, 4, 5, 6, 7, 8, 9]

def ans(j, nums):
    nums[j] += 1
    pre = nums[j]
    for i in range(j + 1, len(nums)):
        if pre > 0:
            nums[i] = pre - 1
            pre = nums[i]
        else:
            nums[i] = pre
    return int(''.join(map(str, nums)))

def lunlun(n):
    if n <= 9:
        return ary[n - 1]
    l = lunlun(n - 1)
    nums = list(map(int, list(str(l))))
    first = len(nums) - 1
    last = 0
    for i in range(len(nums)):
        j = len(nums) - i - 1
        c = nums[j] + 1
        # 桁数が変わらないとき
        if j == first:
            # 1桁目
            if nums[j] < 9 and abs(nums[j - 1] - c) <= 1:
                nums[j] += 1
                return int(''.join(map(str, nums)))
        elif j == last:
            # 最終桁
            if nums[j] < 9 and abs(nums[j + 1] - c) <= 1:
                return ans(j, nums)
        elif j != first and j != last:
            # 間の桁
            if nums[j] < 9 and abs(nums[j - 1] - c) <= 1 and abs(nums[j + 1] - c) <= 1:
                return ans(j, nums)

    # 桁が繰り上がるとき
    return int('1' + ''.join(['0'] * len(nums)))

print(lunlun(k))
rate = int(input())
if n < 1200: print("ABC")
else: print("ARC")

### FIXED CODE ###

n = int(input())
if n < 1200: print("ABC")
else: print("ARC")
n=int(input())
a=list(map(int,input().split()))
d={}
for x in a:
    if d.get(x) is None:
        d[x]=1
        continue
    d[x]+=1
total=0
for v in d.values():
    total+=(y-1)*y//2
for x in a:
    print(total-d[x]+1)

### FIXED CODE ###

n=int(input())
a=list(map(int,input().split()))
d={}
for x in a:
    if d.get(x) is None:
        d[x]=1
        continue
    d[x]+=1
total=0
for v in d.values():
    total+=(v-1)*v//2
for x in a:
    print(total-d[x]+1)
a,b = [double(i) for i in input().split()]
d = int(a/b)
r = int(a) % int(b)
f = a/b

print(str(d) + " " + str(r) + " " + str(f))


### FIXED CODE ###

a,b = [float(i) for i in input().split()]
d = int(a/b)
r = int(a) % int(b)
f = a/b
f = "{:.6f}".format(f)

print(d,r,f)
"""n<10**7の場合に使える。
https://drken1215.hatenablog.com/entry/2018/06/08/210000"""


def cmb(n,r,mod):
    if r<0 or r>n:return 0
    return g1[r]*g2[r]%mod


mod=10**9+7
n,a,b=map(int,input().split())
k=max(a,b)
g1=[1,n]
g2=[1,1]
inverse=[0,1]

for i,j in enumerate(range(n-1,n-k+1,-1)):
    i=i+2
    g1.append((g1[-1]*j)%mod)
    inverse.append((-inverse[mod%i]*(mod//i))%mod)
    g2.append((g2[-1]*inverse[-1]%mod))

N=pow(2,n,mod)-1
print((N-cmb(n,b,mod)-cmb(n,a,mod))%mod)

### FIXED CODE ###

def cmb(n,r,mod):
    if r<0 or r>n:return 0
    return g1[r]*g2[r]%mod


mod=10**9+7
n,a,b=map(int,input().split())
k=max(a,b)
g1=[1,n]
g2=[1,1]
inverse=[0,1]

for i,j in enumerate(range(n-1,((n-k+1)-1),-1)):
    i=i+2
    g1.append((g1[-1]*j)%mod)
    inverse.append((-inverse[mod%i]*(mod//i))%mod)
    g2.append((g2[-1]*inverse[-1]%mod))

N=pow(2,n,mod)-1
print((N-cmb(n,b,mod)-cmb(n,a,mod))%mod)
n, m = [int(i) for i in input().split(' ')]
wa = [0] * n
ac = [0] * n
for _ in range(m):
    problem, status = input().split(' ')
    problem = int(problem) - 1
    if status == 'WA':
        if ac[problem] == 0:
            wa[problem] += 1
        continue
    ac[problem] = 1

### FIXED CODE ###

print(chr(ord(input()) + 1))
from collections import deque
S=input()
s=deque(S)
Q=int(input())
Que=[list(map(str, input().split())) for _ in range(Q)]
#print(Que)
a=0
for i in range(Q):
    if Que[i][0]=="1":
        a+=1
    elif Que[i][0]=="2":
        if a%2==0:
            if Que[i][1]=="2":
                s.append(Que[i][2])
            elif Que[i][1]=="1":
                s.appendleft(Que[i][2])
        else:
            if Que[i][1]=="1":
                s.append(Que[i][2])
            elif Que[i][1]=="2":
                s.appendleft(Que[i][2])
s=list(s)
if a%2==1:
    a=a[::-1]
ans="".join(s)
print(ans)


### FIXED CODE ###

from collections import deque
S=input()
s=deque(S)
Q=int(input())
Que=[list(map(str, input().split())) for _ in range(Q)]
#print(Que)
a=0
for i in range(Q):
    if Que[i][0]=="1":
        a+=1
    elif Que[i][0]=="2":
        if a%2==0:
            if Que[i][1]=="2":
                s.append(Que[i][2])
            elif Que[i][1]=="1":
                s.appendleft(Que[i][2])
        else:
            if Que[i][1]=="1":
                s.append(Que[i][2])
            elif Que[i][1]=="2":
                s.appendleft(Que[i][2])
s=list(s)
if a%2==1:
    s=s[::-1]
ans="".join(s)
print(ans)
O=[]
O= input().split()
LO=int(len(O))
E= input().split()
LE=len(E)

flist=[]

for i in range(LO):
    if i>LE:
        a=O[i]
        flist.append(a)
    else:
        a=O[i]+E[i]
        flist.append(a)

print(''.join(flist))


### FIXED CODE ###

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

if (a-b==b-c):
    print("YES")
else:
    print("NO")
a=int(input())
b=list(map(str,a.split()))
def func(b):
    return len(set(b))
print(func(b))

### FIXED CODE ###

a=int(input())
b=[input() for i in range(a)]
def func(b):
    return len(set(b))
print(func(b))
N,X = map(int,input().split())
x = list(map(int,input().split()))

x.append(X)

xsub = []

if N >= 2:
    for i in range(N-1):
         xsub.append(x[i+1]-x[i])

else:
    print(abs(x[0]-X))

import sympy

A = []

for i in range(N-2):
    A.append(sympy.gcd(xsub[i+1],xsub[i]))

print(min(A))

### FIXED CODE ###

N,X = map(int,input().split())
x = list(map(int,input().split()))

x.sort()

def gcd(x,y):
    X = max(x,y)
    Y = min(x,y)
    if Y == 0:
        return X
    else:
        return gcd(Y,X%Y)

keepgcd = 0
maxgcd = 10**9

if N >= 2:
   for i in range(N-1):
       keepgcd = gcd(abs(X-x[i+1]),abs(X-x[i]))
       if maxgcd > keepgcd:
          maxgcd = keepgcd
   print(maxgcd)
else:
    print(max(x[0],X)-min(x[0],X))
def insertion_sort(array, g, result):
    for i in range(g, len(array)):
        v = array[i]
        j = i - g
        while j >= 0 and array[j] > v:
            array[j + g] = array[j]
            j -= g
            result['count'] += 1
        A[j + g] = v


def g_gene(n):
    yield 1
    for i in range(2, n):
        x = int((3 ** i - 1) / 2)
        if x < n:
            yield x
        else:
            raise StopIteration()


def shell_sort(array, result):
    result['count'] = 0
    G = list(reversed(list(g_gene(len(array)))))
    m = len(G)
    result['G'] = G
    result['m'] = m
    for i in range(m):
        insertion_sort(array, G[i], result)


if __name__ == '__main__':
    n = int(input())
    A = []
    for _ in range(n):
        A.append(int(input()))
    result = {}
    shell_sort(A, result)
    print(result['m'])
    print(' '.join(map(str, result['G'])))
    print(result['count'])
    for a in A:
        print(a)

### FIXED CODE ###

def insertion_sort(array, g, result):
    for i in range(g, len(array)):
        v = array[i]
        j = i - g
        while j >= 0 and array[j] > v:
            array[j + g] = array[j]
            j -= g
            result['count'] += 1
        A[j + g] = v


def g_gene(n):
    yield 1
    for i in range(2, n):
        x = int((3 ** i - 1) / 2)
        if x < n:
            yield x
        else:
            raise StopIteration()


def shell_sort(array, result):
    result['count'] = 0
    G = list(reversed(list(g_gene(len(array)))))
    m = len(G)
    result['G'] = G
    result['m'] = m
    for i in range(m):
        insertion_sort(array, G[i], result)


if __name__ == '__main__':
    import sys
    n = int(sys.stdin.readline())
    A = []
    for _ in range(n):
        A.append(int(sys.stdin.readline()))
    result = {}
    shell_sort(A, result)
    print(result['m'])
    print(' '.join(map(str, result['G'])))
    print(result['count'])
    for a in A:
        print(a)
N,K = map(int,input().split())
int tmp = 0


while:
	tmp = N
	if(abs(tmp - K) < tmp):
      	tmp = abs(tmp - K)
   	else:
      	break
 	
print(tmp)

### FIXED CODE ###

import math

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

while True:
  if abs(tmp - K) < tmp:
    tmp = abs(tmp - K)
  else:
    break
 	
print(tmp)
A,B,K = map(int,input().split())

a = A
b = B

def cal_divisor(num):
    prime = [2,3,5,7,11,13]
    ans_list = []
    for i in range(len(prime)):
        ans_list.append([prime[i],0])
    for i in range(len(prime)):
        while True:
            if num % prime[i] == 0:
                num //= prime[i]
                ans_list[i][1] += 1
            if num % prime[i] != 0:
                break
    return ans_list

q = cal_divisor(a)
w = cal_divisor(b)

ans = []
for i in range(len(q)):
    ans.append([q[i][0],min(q[i][1],w[i][1])])
    
ans1 = []
for i in range(len(ans)):
    if ans[i][1] != 0:
        times = ans[i][1]
        for j in range(times+1):
            ans1.append(ans[i][0] ** j)
ans1.append(1)
ans1.sort()

print(ans1[K-1])

### FIXED CODE ###

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

n = min(a,b)

count = 0
for i in reversed(range(1,n+1)):
    if a % i == 0 and b % i == 0:
        count += 1
    if count == k:
        print(i)
        break
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
s = readline().rstrip().decode('utf-8')

t = ""
for i in s:
    if not i == "x":
        t += i

if t[::] != t[::-1]:
    print(-1)

else:
    ans = 0
    left,right = 0,len(s)-1
    while True:
        if left == right:
            break
        if s[left] == "x" and s[right] != "x":
            ans += 1
            left += 1
        elif s[left] != "x" and s[right] == "x":
            ans += 1
            right -= 1
        else:
            left += 1
            right -= 1
    print(ans)




### FIXED CODE ###

import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
s = readline().rstrip().decode('utf-8')

t = ""
for i in s:
    if not i == "x":
        t += i

if t[::] != t[::-1]:
    print(-1)

else:
    ans = 0
    left,right = 0,len(s)-1
    while True:
        if right - left <= 0:
            break
        if s[left] == "x" and s[right] != "x":
            ans += 1
            left += 1
        elif s[left] != "x" and s[right] == "x":
            ans += 1
            right -= 1
        else:
            left += 1
            right -= 1
    print(ans)
#import numpy as np
import sys, math
from itertools import permutations, combinations
from collections import defaultdict, Counter, deque
from math import factorial#, gcd
from bisect import bisect_left #bisect_left(list, value)
sys.setrecursionlimit(10**7)
enu = enumerate
MOD = 10**9+7
def input(): return sys.stdin.readline()[:-1]
pl = lambda x: print(*x, sep='\n')

N = int(input())
CSF = [list(map(int, input().split())) for _ in range(N-1)]

SS = [[0]*10**6 for _ in range(N)]
for i, csf in enu(CSF):
    c, s, f = csf
    for j in range(s, 10**6, f):
        SS[i][j] = 1
# print(SS[0][:20])
# print(SS[1][:20])

for i in range(N-1):
    st = i
    sec = 0
    while st < N-1:
        # print('st', st, 'sec', sec)
        # print('st', st)
        if SS[st][sec] == 1:
            sec += CSF[st][0]
            st += 1
        else:
            sec += 1
    print(sec)
print(0)

### FIXED CODE ###

# import numpy as np
import sys, math, heapq
from itertools import permutations, combinations
from collections import defaultdict, Counter, deque
from math import factorial, gcd
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10 ** 7)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline()[:-1]
pl = lambda x: print(*x, sep="\n")

N = int(input())
CSF = [list(map(int, input().split())) for _ in range(N - 1)]

for i in range(N - 1):
    c, s, f = CSF[i]
    time = s + c
    for csfj in CSF[i + 1 :]:
        c, s, f = csfj
        if time < s:
            time = s
        else:
            time = f * ((time + f - 1) // f)
        time += c
    print(time)

print(0)
#!usr/bim/python
#! -*- coding: utf-8 -*-

import numpy as np

n = raw_input()
n = int(n)

tree = np.zeros([n,n],dtype=np.int64)
for i in range(n-1):
    abc = raw_input()
    abc = abc.split()
    abc = map(int, abc)
    tree[abc[0]-1,abc[1]-1] = abc[2]
    tree[abc[1]-1,abc[0]-1] = abc[2]

qk = raw_input()
qk = qk.split()
q,k = map(int,qk)

question = []
for i in range(q):
    xy = raw_input()
    xy = xy.split()
    xy = map(int,xy)
    question.append(xy)

distance = []
for i in range(n):
    distance.append(-1)

distance[k-1] = 0

while 1:
    status = 0
    for i in range(len(distance)):
        if distance[i] == -1:
            status = 1
        else:
            for j in range(n):
                if not tree[i][j] == 0 and distance[j] == -1:
                    distance[j] = distance[i] + tree[i][j]
    if status == 0:
        break

for line in question:
    ans = distance[line[0]-1] + distance[line[1]-1]
    print ans


### FIXED CODE ###

#!usr/bim/python
#! -*- coding: utf-8 -*-

import numpy as np

n = raw_input()
n = int(n)

tree = []
for i in range(n):
    tree.append([])

for i in range(n-1):
    abc = raw_input()
    abc = abc.split()
    abc = map(int, abc)
    tree[abc[0]-1].append([abc[1]-1,abc[2]])
    tree[abc[1]-1].append([abc[0]-1,abc[2]])


qk = raw_input()
qk = qk.split()
q,k = map(int,qk)

question = []
for i in range(q):
    xy = raw_input()
    xy = xy.split()
    xy = map(int,xy)
    question.append(xy)

distance = []
for i in range(n):
    distance.append(-1)

distance[k-1] = 0

next_point = [k-1]

while 1:
    search_point = next_point
    next_point = []
    if len(search_point) == 0:
        break
    else:
        for i in search_point:
            for j in tree[i]:
                if distance[j[0]] == -1:
                    distance[j[0]] = distance[i] + j[1]
                    next_point.append(j[0])

for line in question:
    print distance[line[0]-1] + distance[line[1]-1]