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

# 考えると、隣り合う列は結局 2*H 回ずることになり、
# それぞれの列間について最適な沈め順を見つけると、
# その順序関係を崩さないように全体の順番も構築できる（トポロジカルソートみたいに）ので、
# 各列間の最適解を求めて総和をとればいい

# TLE が厳しすぎる

inf = 2 * 10**9
H, W = map(int, input().split())
C = [input() for _ in range(H)]
C_T = list(zip(*C))
C_T = ["".join(s) for s in C_T]
ans = 0
C1 = C_T[0]
for C2 in C_T[1:]:
    # Z[i][j] := i 個ずれてて沈んでない方が j 個沈んでる状態の連結個数
    Z1 = []  # 左を押したとき（右が上にあるとき）
    Z2 = []  # 右を押したとき（左が上にあるとき）
    for j in range(H+1):
        z1, z2 = [0], [0]
        c1 = c2 = 0
        C1_, C2_ = C1[j:], C2[j:]
        for i in range(H - j):
            if C1[i] == C2_[i]:
                c1 += 1
            z1.append(c1)
            if C1_[i] == C2[i]:
                c2 += 1
            z2.append(c2)
        z1.reverse()
        z2.reverse()
        Z1.append(z1)
        Z2.append(z2)
    # dp[i][j] := 左を i 個、右を j 個沈めるまでの最小コスト  # 逆かも（どっちでもいい）
    dp = [[inf] * (H+2) for _ in range(H+2)]
    dp[0][0] = 0
    for j in range(H+1):
        for k in range(H+1):
            cost = dp[j][k] + (Z1[j-k][k] if j>=k else Z2[k-j][j])
            dp[j+1][k] = min(dp[j+1][k], cost)
            dp[j][k+1] = min(dp[j][k+1], cost)
    ans += dp[H][H]
    C1 = C2
print(ans)


### FIXED CODE ###

# 考えると、隣り合う列は結局 2*H 回ずることになり、
# それぞれの列間について最適な沈め順を見つけると、
# その順序関係を崩さないように全体の順番も構築できる（トポロジカルソートみたいに）ので、
# 各列間の最適解を求めて総和をとればいい

def accumulate_reverse(S1, S2):
    n = min(len(S1), len(S2))
    res = [0] * (n+1)
    c = 0
    for i in range(n):
        if S1[i] == S2[i]:
            c += 1
        res[n-i-1] = c
    return res

inf = 10**8
H, W = map(int, input().split())
C = [input() for _ in range(H)]
C_T = list(zip(*C))
C_T = ["".join(s) for s in C_T]
ans = 0
for C1, C2 in zip(C_T[:-1], C_T[1:]):
    # Z[i][j] := i 個ずれてて沈んでない方が j 個沈んでる状態の連結個数
    Z1 = []  # 左を押したとき（右が上にあるとき）
    Z2 = []  # 右を押したとき（左が上にあるとき）
    Z1.append(accumulate_reverse(C1, C2))
    for j in range(1, H+1):
        Z1.append(accumulate_reverse(C1, C2[j:]))
        Z2.append(accumulate_reverse(C1[j:], C2))
    Z1 += Z2[::-1]
    # dp[i][j] := 左を i 個、右を j 個沈めるまでの最小コスト  # 逆かも（どっちでもいい）
    dp = [[inf] * (H+2) for _ in range(H+2)]
    dp[0][0] = 0
    for j in range(H+1):
        for k in range(H+1):
            cost = dp[j][k] + Z1[j-k][min(j, k)]
            dp[j+1][k] = min(dp[j+1][k], cost)
            dp[j][k+1] = min(dp[j][k+1], cost)
    ans += dp[H][H]
print(ans)
### BUGGY CODE ###

T = list(input())

s = T.count('?')

for i in range(s):
    T[T.index('?')] = 'D'
print(''.join(T))

### FIXED CODE ###

T = input()

T = T.replace('?', 'D')
	
print(''.join(T))
### BUGGY CODE ###


import numpy as np

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



move_list = []
checker = np.zeros(N+1 ,dtype = int)
for LR in LRs:
    for i in range(LR[0], LR[1]+1):
        checker[i] = 1

for index, check in enumerate(checker):
    if(check == 1):
        move_list.append(index)

dp = np.zeros(N*2+2, dtype = int)
dp[1] = 1

#for i in range(1, N+1):
#    for j in move_list:
#        if(i < j):
#            break
#        dp[i] = (dp[i] +dp[i-j]) % 998244353

for i in range(1, N+1):
    atai = dp[i]
    for LR in LRs:
        p_array = ([atai] * (LR[1] - LR[0] + 1))
        mae_zero = ([0] * (LR[0] + (i - 1) + 1))
        usiro_zero = ([0] * (N*2 - (i - 1) - LR[1]))
        mae_zero.extend(p_array)
        mae_zero.extend(usiro_zero)
#        print(mae_zero)
        dp += np.array(mae_zero)
#        print(dp[1:N+1])

print(dp[N] % 998244353)


### FIXED CODE ###

import numpy as np

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

dp = np.zeros(N+2, dtype = int)
dp[1] = 1
dp[2] = -1

atai = 0
for i in range(1, N+2):
    atai += dp[i]
    for LR in LRs:
        if(i+LR[0] <= N):
            dp[i+LR[0]] = (dp[i+LR[0]] + atai) % 998244353
        if(i+LR[1] <= N):
            dp[i+LR[1]+1] = (dp[i+LR[1]+1] -atai) % 998244353

#    print(dp)

#復元
ruisekiwa = [0]

for hoge in dp:
    ruisekiwa.append(ruisekiwa[-1]+hoge)
print(ruisekiwa[N+1] % 998244353)
### BUGGY CODE ###

# coding: utf-8
import numpy as np


def solve(*args: str) -> str:
    n, k = map(int, args[0].split())
    A = np.array(tuple(map(int, args[1].split())), int)

    cur = A
    for _ in range(k):
        prev = cur
        cur = np.zeros(n, int)
        for i, p in enumerate(prev):
            cur[max(0, i-p):min(n, i+p+1)] += 1

    return ' '.join(map(str, cur))


if __name__ == "__main__":
    print(solve(*(open(0).read().splitlines())))


### FIXED CODE ###

# coding: utf-8


def solve(*args: str) -> str:
    n, k = map(int, args[0].split())
    A = list(map(int, args[1].split()))

    cur = A
    for _ in range(k):
        prev = cur.copy()
        cur = [0]*n
        for x, p in enumerate(prev):
            cur[max(0, x-p)] += 1
            if x+p+1 < n:
                cur[x+p+1] -= 1

        satulated = True
        for i in range(1, n):
            cur[i] += cur[i-1]
            satulated &= cur[i] == n
        if satulated:
            break

    return ' '.join(map(str, cur))


if __name__ == "__main__":
    print(solve(*(open(0).read().splitlines())))
### BUGGY CODE ###

N = int(input())
N_list = [int(i) for i in input().split()]
res = 1
for i in range(len(N_list)) :
    res = res * N_list[i]

if (res > 1000000000000000000) :
    print(-1)
else :
    print(res)

### FIXED CODE ###

def main() :

    N = int(input())
    N_list = [int(i) for i in input().split()]
    res = 1

    if (N_list.count(0) > 0) :
        print(0)
        return

    for i in range(len(N_list)) :
        res = res * N_list[i]
        if (res > 1000000000000000000) :
            print(-1)
            return
    
    print(res)

main()
### BUGGY CODE ###

n,m = map(int,input().split())
s = list(map(int, input().split()))
#print(type(s))
for _ in range(m):
    max_value = max(s)
    max_index = s.index(max_value)
    s[max_index] = s[max_index] // 2

print(sum(s))

### FIXED CODE ###

import heapq

n,m = map(int,input().split())
s = list(map(lambda x: int(x) * -1, input().split()))
#print(type(s))
heapq.heapify(s)
for _ in range(m):
    heapq.heappush(s,int(heapq.heappop(s)/2))
sum = sum(s)*-1
print(sum)
### BUGGY CODE ###

def main():
    *s, = map(int, input())  # <= 2*10**5

    r = [0] * 2019
    r[0] = 1

    ans = 0

    t = 0
    p = 1
    for x in reversed(s):
        t = (t + x * p) % 2019
        p *= 10
        ans += r[t]
        r[t] += 1

    print(ans)


if __name__ == '__main__':
    main()

# import sys
# input = sys.stdin.readline
# 
# sys.setrecursionlimit(10 ** 7)
# 
# (int(x)-1 for x in input().split())
# rstrip()
#
# def binary_search(*, ok, ng, func):
#     while abs(ok - ng) > 1:
#         mid = (ok + ng) // 2
#         if func(mid):
#             ok = mid
#         else:
#             ng = mid
#     return ok


### FIXED CODE ###

def main():
    *s, = map(int, input())  # <= 2*10**5

    r = [0] * 2019
    r[0] = 1

    ans = 0

    t = 0
    p = 1
    for x in reversed(s):
        t = (t + x * p) % 2019
        p = (p * 10) % 2019
        ans += r[t]
        r[t] += 1

    print(ans)


if __name__ == '__main__':
    main()

# import sys
# input = sys.stdin.readline
# 
# sys.setrecursionlimit(10 ** 7)
# 
# (int(x)-1 for x in input().split())
# rstrip()
#
# def binary_search(*, ok, ng, func):
#     while abs(ok - ng) > 1:
#         mid = (ok + ng) // 2
#         if func(mid):
#             ok = mid
#         else:
#             ng = mid
#     return ok
### BUGGY CODE ###

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

for i in range(1, n+1):
  for j in range(i+1, n+1):
    dist = min(abs(j-i), 1 + abs(x-i)+abs(y-j), 1 + abs(y-i)+abs(x-j))
    if dist > 0:
      dists[dist-1]+=1
    
for i in range(n-1):
  print(dists[i])

### FIXED CODE ###

n, x, y = map(int, input().split())
dists = [0 for i in range(n+1)]

for i in range(1, n+1):
  for j in range(i+1, n+1):
    dist = min(abs(j-i), 1 + abs(x-i)+abs(y-j), 1 + abs(y-i)+abs(x-j))
    dists[dist]+=1
    
for i in range(1, n):
  print(dists[i])
### BUGGY CODE ###

import numpy as np

N=int(input())
A=np.array(list(map(int,input().split())))
ans=0

for i in range(N-1):
  ans+=sum(A[i]*A[i+1:])
  ans%=(1e+9+7)
print(int(ans))

### FIXED CODE ###

N=int(input())
A=list(map(int,input().split()))

temp=sum(A)
ans=0

for i in range(N-1):
  temp-=A[i]
  ans+=A[i]*temp

print(int(ans%(10**9+7)))
### BUGGY CODE ###

from collections import deque
from math import prod

N,K=map(int,input().split())
if N==1:print(K)
else:
  G=[[] for i in range(N+1)]
  #deg=[0]*(N+1)
  mod=10**9+7

  for i in range(N-1):
    a,b=map(int,input().split())
    G[a].append(b)
    G[b].append(a)
    #deg[a]+=1
    #deg[b]+=1

  #deg2 = sorted(enumerate(deg),key=lambda x:x[1])
  for i in range(1,N+1):
    if len(G[i])==1:break
  first = i
  #first = deg2[1][0]
  second = G[first][0]
  color = [1]*(N+1)
  color[first],color[second]=K,K-1

  def bfs(s):
      seen = [0]*(N+1)
      todo = deque([])
      seen[s]=1
      todo.append(s)
      while 1:
        if len(todo)==0:break
        a = todo.popleft()
        if a != first: 
          acolor=K-1
        for b in G[a]:
          if seen[b] == 0:
            seen[b] = 1
            todo.append(b)
            if b != second:
              acolor -= 1
              color[b] = acolor

  bfs(first)
  total = prod(color)%mod
  print(total)

### FIXED CODE ###

from collections import deque

N,K=map(int,input().split())
mod = 10**9+7
G=[[] for _ in range(N)]
for i in range(N-1):
  a,b=map(int,input().split())
  G[a-1].append(b-1)
  G[b-1].append(a-1)

def bfs(s):
    seen = [0]*N
    prev = [0]*N
    color = [0]*N
    todo = deque()
    seen[s]=1
    todo.append(s)
    color[s]=K
    while todo:
      a = todo.popleft()
      if a == start: count = K-1
      else: count = K-2
      for b in G[a]:
        if seen[b] == 0:
          seen[b] = 1
          todo.append(b)
          prev[b] = a
          color[b] = count %mod
          count -= 1
    return color
  
MAX,start = 0,-1
for i in range(N):
  if len(G[i])>MAX:
    MAX=len(G[i])
    start = i
    
color = bfs(start)
ans = 1
for i in range(N):
  ans *= color[i]
  ans %= mod
  
print(ans)
### BUGGY CODE ###

N = int(input())
S = input()
sum = 0
for i in range(N):
    for j in range(i):
        for k in range(j):
            if(k - j == j - i):
                continue
            elif(i == j):
                continue
            elif(j == k):
                continue
            elif(k == i):
                continue
            if(S[i] == S[j]):
                continue
            elif(S[j] == S[k]):
                continue
            elif(S[i] == S[k]):
                continue
            sum += 1
            
print(sum)

### FIXED CODE ###

N = int(input())
S = input()


R = []
B = []
G = []
p = 0
for i in S:
    if(i == "R"):
        R.append(p)
    elif(i == "B"):
        B.append(p)
    elif(i == "G"):
        G.append(p)
    p += 1
R = set(R)
B = set(B)
G = set(G)
sum = len(R) * len(B) * len(G)
for r in R:
    for b in B:
        up = max(r, b)
        dw = min(r, b)
        d = up-dw
        if up + d in G:
            sum -= 1
        if dw - d in G:
            sum -= 1
        if (r+b)/2 in G:
            sum -= 1

print(sum)
### BUGGY CODE ###

s = input()
n = len(s) + 1
lft = 0
rgt = 0
l = []
for i in range(n):
    for j in reversed(range(i)):
        if s[j] == '<':
            lft += 1
        else:
            break
    for j in range(i, n-1):
        if s[j] == '>':
            rgt += 1
        else:
            break
    l.append(max(lft, rgt))
    lft = 0
    rgt = 0
print(sum(l))

### FIXED CODE ###

s = input()
n = len(s) + 1
a = [0 for _ in range(n)]
for i in range(n-1):
    if s[i] == '<':
        a[i+1] = a[i] + 1
for i in reversed(range(1, n)):
    if s[i-1] == '>':
        a[i-1] = max(a[i-1], a[i]+1)
print(sum(a))
### BUGGY CODE ###

N = int(input())
lists = []
result = 0
for i in range(N):
    lists.append(input())

sortedlist = []
for i in range(0, N):
    sortedlist.append(sorted(lists[i]))

for i in range(0, N):
    for j in range(i + 1, N):
        if sortedlist[i] == sortedlist[j]:
            result += 1

print(result)


### FIXED CODE ###

import math

N = int(input())
lists = []
result = 0
tempres = 0
for i in range(N):
    lists.append(input())

sortedlist = []
for i in range(0, N):
    sortedlist.append(sorted(lists[i]))

sortedlist.sort()
for i in range(0, N):
    if tempres != 0:
        tempres -= 1
        result += tempres
        continue

    for j in range(i + 1, N):
        if sortedlist[i] == sortedlist[j]:
            tempres += 1
        else:
            break
    result += tempres

print(result)
### BUGGY CODE ###

def main():
    H, W = map(int, input().split())
    A = [list(map(int, input().split())) for _ in range(H)]
    B = [list(map(int, input().split())) for _ in range(H)]
    C = [[0] * W for _ in range(H)]
    for h in range(H):
        for w in range(W):
            C[h][w] = abs(A[h][w] - B[h][w])

    dp = [[[0] * (80 * 80) for _ in range(W)] for _ in range(H)]
    dh = [1,0]
    dw = [0,1]
    dp[0][0][C[0][0]] = 1
    for h in range(H):
        for w in range(W):
            for i in range(80*80):
                for j in range(2):
                    nh = h - dh[j]
                    nw = w - dw[j]
                    if 0 <= nh < H and 0 <= nw < W:
                        if abs(C[h][w] + i) < 6400:
                            dp[h][w][abs(C[h][w] + i)] |= dp[nh][nw][i]
                        if abs(C[h][w] - i) < 6400:
                            dp[h][w][abs(C[h][w] - i)] |= dp[nh][nw][i]
                    
    ans = float('inf')
    for i in range(80*80):
        if dp[H-1][W-1][i]:
            ans = min(i, ans)

    print(ans) 



if __name__ == "__main__":
    main()

### FIXED CODE ###

def main():
    H, W = map(int, input().split())
    A = [list(map(int, input().split())) for _ in range(H)]
    B = [list(map(int, input().split())) for _ in range(H)]
    C = [[0] * W for _ in range(H)]
    for h in range(H):
        for w in range(W):
            C[h][w] = abs(A[h][w] - B[h][w])

    dp = [[0 for _ in range(6400)] for _ in range(H*W)]
    dp[0][C[0][0]] = 1

    for d in range(H*W):
        h, w = divmod(d, W)
        for k in range(6400):
            if not dp[h*W+w][k]:
                continue
            nh, nw = h+1, w+1
            if nh < H:
                if k + C[nh][w] < 6400:
                    dp[nh*W+w][k+C[nh][w]] = 1
                dp[nh*W+w][abs(k-C[nh][w])] = 1
            if nw < W:
                if k + C[h][nw] < 6400:
                    dp[h*W+nw][k+C[h][nw]] = 1
                dp[h*W+nw][abs(k-C[h][nw])] = 1

    for k in range(6400):
        if dp[-1][k]:
            print(k)
            exit()

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

K,S = [int(i) for i in input().split()]
count = 0
for z in range(0,K+1):
	for y in range(0,z+1):
		for x in range(0,y+1):
			if x > y:
				continue
			elif y > z:
				continue
			elif x > z:
				continue
			else:
				if x + y + z == S:
					if  x == y and y == z:
						count += 1
					elif (x-y)*(y-z)*(z-x) == 0:
						count += 3
					else:
						count += 6
print(count)

### FIXED CODE ###

K,S = [int(i) for i in input().split()]
count = 0
for z in range(0,K+1):
	for y in range(0,K+1):
			if 0 <= S-y-z <= K:
				count += 1
print(count)
### BUGGY CODE ###

n, q = map(int, input().split())
tl = [list() for _ in range(n)]
ab = [None] * (n-1)
ans = [0] * n

for i in range(n-1):
    ab[i] = tuple(map(int, input().split()))

ab.sort(reverse=True)

for a, b in ab:
    a -= 1
    b -= 1
    tl[a].append(b)
    tl[a].extend(tl[b])

for _ in range(q):
    p, x = map(int, input().split())
    ans[p-1] += x
    if len(tl[p-1]) > 0:
        for num in tl[p-1]:
            ans[num] += x

print(" ".join(map(str, ans)))

### FIXED CODE ###

import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline
 
n, q = map(int, input().split())
tl = [list() for _ in range(n)]
xl = [0] * n
ans = [0] * n
 
for i in range(n-1):
    a, b = map(int, input().split())
    tl[a-1].append(b-1)
    tl[b-1].append(a-1)
 
for i in range(q):
    p, x = map(int, input().split())
    xl[p-1] += x

def rec(p, parent, x):
    x += xl[p]
    ans[p] = x
    for num in tl[p]:
        if num == parent: continue
        rec(num, p, x)

rec(0, -1, 0)
 
print(*ans)
### BUGGY CODE ###

import collections
N, K = [int(_) for _ in input().split()]
A1 = [int(_) for _ in input().split()]
A = A1 * 2
a_i = collections.defaultdict(lambda: [])
for i, a in enumerate(A):
    a_i[a] += [i]
i_delta = [0] * (2 * N)
for a in a_i:
    array = a_i[a]
    for i in range(len(array) - 1):
        i_delta[array[i]] = array[i + 1] - array[i] + 1
first = [-1] * N
second = [-1] * N
i = 0
while second[i % N] == -1:
    if first[i % N] == -1:
        first[i % N] = i
    else:
        second[i % N] = i
        break
    i += i_delta[i % N]
i %= N
start = first[i] + (second[i] - first[i]) * (
    (N * K - first[i]) // (second[i] - first[i]))
end = N * K
while True:
    s2 = start + i_delta[start % N]
    if s2 >= end:
        break
    start = s2
B = A1[N - (end - start) % N:] + A1 * ((end - start) // N)
dp = [{}]
for i, b in enumerate(B):
    if b in dp[-1]:
        dp = dp[:dp[-1][b]]
    else:
        s = dp[-1].copy()
        s[b] = len(dp)
        dp += [s]
print(*list(a for a, _ in sorted(dp[-1].items(), key=lambda xs: xs[1])))


### FIXED CODE ###

import bisect
N, K, *A = [int(_) for _ in open(0).read().split()]
K -= 1
L = [[] for _ in range(2 * 10**5 + 1)]
for i, a in enumerate(A * 2):
    L[a] += [i]
before_next = [L[a][bisect.bisect(L[a], i)] for i, a in enumerate(A)]
first_cycle = [None] * N
now = 0
idx = 0
cycle = 0
while True:
    if first_cycle[now] is not None:
        break
    first_cycle[now] = cycle
    now = before_next[now] + 1
    dcycle, now = divmod(now, N)
    cycle += dcycle
cycle2 = cycle
cycle1 = first_cycle[now]
#K cycle目=cycle1+(K-cycle1)%(cycle2-cycle1) cycle目
K2 = cycle1 + (K - cycle1) % (cycle2 - cycle1)
if K2:
    f1 = f2 = 0
    for i in range(N - 1, -1, -1):
        if first_cycle[i] == K2 - 1:
            f1 = 1
            break
    for j in range(N - 1, -1, -1):
        if first_cycle[j] == K2:
            f2 = 1
            break
    if f2:
        B = A[j:]
    elif f1:
        B = A[i:] + A
else:
    B = A
ans = []
cnt = [0] * (2 * 10**5 + 1)
for a in B:
    if cnt[a] > 0:
        while True:
            cnt[ans.pop()] -= 1
            if cnt[a] == 0:
                break
    else:
        ans += [a]
        cnt[a] += 1
print(' '.join(map(str, ans)))
### BUGGY CODE ###

N = int(input())
Dic = {}
for n in range(N):
    S = input()
    if S in Dic.keys():
        Dic[S] = Dic[S] + 1
    else:
        Dic[S] = 1
        
max_k_list = [kv[0] for kv in Dic.items() if kv[1] == max(Dic.values())]
max_k_list = sorted(max_k_list)
for t in max_k_list:
    print(t)

### FIXED CODE ###

from collections import Counter
N = int(input())
L = [input() for _ in range(N)]
#for n in range(N):
    #S = input()
    #L.append(S)
Dic = Counter(L)
max_value = max(Dic.values())
max_k_list = [i for i, j in Dic.items() if j == max_value]
max_k_list = sorted(max_k_list)
for t in max_k_list:
    print(t)
### BUGGY CODE ###

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

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

Group=[i for i in range(N+1)]


Swap=[None]*M
for i in range(M):
    Swap[i]=sorted(map(int,input().split()))

Swap.sort(key=lambda x:x[0])

#print(Swap)
judge=1
while judge==1:
    judge=0
    for i in range(M):
        if (Group[Swap[i][1]],Group[Swap[i][0]])!=(min(Group[Swap[i][0]], Group[Swap[i][1]]),min(Group[Swap[i][0]], Group[Swap[i][1]])):
            Group[Swap[i][1]],Group[Swap[i][0]]=min(Group[Swap[i][0]], Group[Swap[i][1]]),min(Group[Swap[i][0]], Group[Swap[i][1]])
            judge=1

    #print(Group)

#print(Group)
#judge=1

#while judge==1:
#    judge=0
#    for i in range(2,N+1):
#        if Group[Group[i]]!=Group[i]:
#            Group[i]=Group[Group[i]]
#            judge=1
#        print(Group)

count=0

for i in range(N):
    if Group[P[i]]==Group[i+1]:
        count+=1


print(count)
        


### FIXED CODE ###

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

Group=[i for i in range(N+1)]


Swap=[None]*M
for i in range(M):
    Swap[i]=sorted(map(int,input().split()))

def find(x):
    while Group[x] != x:
        x=Group[x]
    return x

for i in range(M):
    if find(Swap[i][1]) != find(Swap[i][0]):
        Group[find(Swap[i][1])]=min(find(Swap[i][1]),find(Swap[i][0]))
        Group[find(Swap[i][0])]=min(find(Swap[i][1]),find(Swap[i][0]))
        Group[Swap[i][1]]=min(find(Swap[i][1]),find(Swap[i][0]))
        Group[Swap[i][1]]=min(find(Swap[i][1]),find(Swap[i][0]))

count=0

for i in range(N):
    if find(P[i])==find(i+1):
        count+=1


print(count)
### BUGGY CODE ###

n=int(input())
s=[]
for i in range(n):
    tmp=input()
    if not tmp in s:
        s.append(tmp)
print(len(s))

### FIXED CODE ###

n=int(input())
s={}
for i in range(n):
    tmp=input()
    if tmp in s:
        s[tmp]+=1
    else:
        s[tmp]=1
print(len(s))
### BUGGY CODE ###

from operator import itemgetter
N = int(input())
A = list(map(int, input().split()))
# a= []
# for i in range(N):
#     a.append((i+1, A[i]))
#     a.sort(key=itemgetter(1))
# print(' '.join([str(i[0]) for i in a]))
a = []
for i in range(N):
    for j in range(N):
        if i+1 == A[j]:
            a.append(str(j+1))
print(' '.join(a))


### FIXED CODE ###

from operator import itemgetter
N = int(input())
A = list(map(int, input().split()))
# a= []
# for i in range(N):
#     a.append((i+1, A[i]))
#     a.sort(key=itemgetter(1))
# print(' '.join([str(i[0]) for i in a]))
a = [0] * N
for i in range(N):
    a[ A[i] -1 ] = str(i + 1)
print(' '.join(a))
### BUGGY CODE ###

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

dp = [0] * N
dp[0] = 0

for i, h in enumerate(hhh):
    s = 0 if i < K else i-K
    if i == 0:
        continue
    dp[i] = \
        min([abs(hhh[i] - h_k) + dp_k for h_k, dp_k in zip(hhh[s:i], dp[s:i])])

print(dp[-1])


### FIXED CODE ###

# WIP
N, K = map(int, input().split())
hhh = list(map(int, input().split()))

dp = [0] * N
dp[0] = 0

for i in range(1, N):
    if i < K:
        dp[i] = \
            min([abs(hhh[i] - hhh[i-k]) + dp[i-k] for k in range(1, i+1)])
    else:
        dp[i] = \
            min([abs(hhh[i] - hhh[i-k]) + dp[i-k] for k in range(1, K+1)])

print(dp[-1])
### BUGGY CODE ###

import sys
S = input()
Q = int(input())
# queries = list(list(input().split()) for _ in range(Q))  # 後でroop回し直すのは2度手間

reverse = 0
# for query in queries:
for query in sys.stdin:
    if query[0] == '1':  # len(query)は改行記号の有無で変わるのでダメ
        reverse = 1 - reverse

    else:
        _, f, c = query.split()
        is_append_left = (reverse + int(f)) % 2
        if is_append_left:
            S = c + S
        else:
            S += c

if reverse:  # reverse処理は重い．実際，最後の一回で良い．
    S = S[::-1]

print(S)

### FIXED CODE ###

import sys
from collections import deque
S = deque(input())
Q = int(input())
# queries = list(list(input().split()) for _ in range(Q))  # 後でroop回し直すのは2度手間

reverse = 0
# for query in queries:
for query in sys.stdin:
    if query[0] == '1':  # len(query)は改行記号の有無で変わるのでダメ
        reverse = 1 - reverse

    else:
        _, f, c = query.split()
        is_append_left = (reverse + int(f)) % 2
        if is_append_left:
            S.appendleft(c)  # listだとO(n)だが，dequeではO(1)
        else:
            S.append(c)

if reverse:  # reverse処理は重い．実際，最後の一回で良い．
    S.reverse()

print(''.join(S))