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

def main():
  N = int(input())
  a = [[int(e) - 1 for e in input().split()] for _ in range(N)]
  next_index = [0] * N
  nq = list(range(N))
  result = 0
  finished = 0
  while nq:
    result += 1
    q = nq
    nq = []
    booked = [False] * N
    for player in q:
      if booked[player]:
        continue
      opponent = a[player][next_index[player]]
      if booked[opponent]:
        continue
      if a[opponent][next_index[opponent]] != player:
        continue
      booked[player] = True
      booked[opponent] = True
      next_index[player] += 1
      next_index[opponent] += 1
      if next_index[player] == N - 1:
        finished += 1
      else:
        nq.append(player)
      if next_index[opponent] == N - 1:
        finished += 1
      else:
        nq.append(opponent)
  if finished == N:
    print(result)
  else:
    print(-1)
main()


### FIXED CODE ###

from sys import exit, setrecursionlimit
setrecursionlimit(1000000)

def dfs(v, dp, to):
  t = dp[v]
  if t >= 0:
    return t
  dp[v] = 0
  t = 0
  for u in to[v]:
    res = dfs(u, dp, to)
    if res == 0:
      print('-1')
      exit()
    if res > t:
      t = res
  t += 1
  dp[v] = t
  return t

def toId(i, j, id_db):
  if i < j:
    return id_db[i][j]
  else:
    return id_db[j][i]

def main():
  N = int(input())
  a = [[int(e) - 1 for e in input().split()] for _ in range(N)]

  id_db = [[0] * N for _ in range(N)]

  dp = [-1] * (N * (N - 1) // 2)
  to = [[] for _ in range(N * (N - 1) // 2)]

  v = 0
  for i in range(N):
    for j in range(i + 1, N):
      id_db[i][j] = v
      v += 1

  for i in range(N):
    for j in range(N - 1):
      a[i][j] = toId(i, a[i][j], id_db)
    for j in range(N - 2):
      to[a[i][j + 1]].append(a[i][j])

  print(max(dfs(i, dp, to) for i in range(N * (N - 1) // 2)))

main()
### BUGGY CODE ###

from sys import setrecursionlimit

setrecursionlimit(3 * 10 ** 5)

class Node:
  def __init__(self, id):
    self.id = id
    self.children = []
    self.block_id_set = set()
    self.size = 1

  def add_child(self, node):
    self.children.append(node)

  def add_block(self, id):
    self.block_id_set.add(id)


def main():
  n, m, k = map(int, input().split(' '))
  nodes = {i: Node(i) for i in range(n)}
  for _ in range(m):
    a, b = sorted(map(lambda x: int(x) - 1, input().split()))
    nodes[a].add_child(nodes[b])
    nodes[b].add_child(nodes[a])

  for _ in range(k):
    c, d = sorted(map(lambda x: int(x) - 1, input().split()))
    nodes[c].add_block(d)
    nodes[d].add_block(c)

  def dfs(node, done_set):
    if node.id in done_set: return 0

    nodes.pop(node.id)
    done_set.add(node.id)

    for child in node.children:
      node.size += dfs(child, done_set)

    return node.size


  ans_list = [0] * n

  def dfs2(node, done_set, connected_ids):
    if node.id in done_set: return 0

    done_set.add(node.id)

    ans_list[node.id] = len(connected_ids) - len(list(filter(
      lambda block_id: block_id in connected_ids,
      node.block_id_set
    ))) - 1

    for child in node.children:
      if child.id not in node.block_id_set:
        ans_list[node.id] -= 1

      dfs2(child, done_set, connected_ids)

  while nodes:
    for node in nodes.values():
      done_set = set()
      dfs(node, done_set)
      dfs2(node, set(), done_set)
      break

  print(*ans_list, sep=" ")


main()


### FIXED CODE ###

from sys import setrecursionlimit

setrecursionlimit(3 * 10 ** 5)

def main():
  n, m, k = map(int, input().split(' '))
  nodes = tuple([([], set()) for i in range(n)])
  for _ in range(m):
    a, b = sorted(map(lambda x: int(x) - 1, input().split()))
    nodes[a][0].append(b)
    nodes[b][0].append(a)

  for _ in range(k):
    c, d = sorted(map(lambda x: int(x) - 1, input().split()))
    nodes[c][1].add(d)
    nodes[d][1].add(c)

  total_done_set = set()

  def dfs(node_id, done_set):
    if node_id in done_set: return 0

    total_done_set.add(node_id)
    done_set.add(node_id)

    size = 1
    for child_id in nodes[node_id][0]:
      size += dfs(child_id, done_set)

    return size


  ans_list = [-1] * n

  def dfs2(node_id, connected_ids, total_len):
    children, block_id_set = nodes[node_id]
    ans_list[node_id] = total_len - len(list(filter(
      lambda block_id: block_id in connected_ids, block_id_set
    ))) - 1

    except_num = 0
    for child_id in children:
      if child_id not in block_id_set:
        except_num += 1

      if ans_list[child_id] == -1:
        dfs2(child_id, connected_ids, total_len)

    ans_list[node_id] -= except_num


  for i in range(n):
    if i not in total_done_set:
      done_set = set()
      dfs(i, done_set)
      dfs2(i, done_set, len(done_set))

  print(*ans_list, sep=" ")


main()
### BUGGY CODE ###

S = input()
ans = 0
for i in range(len(S)):
  for j in range(i+1, len(S)):
    S_n = S[i:j+1]
    if(int(S_n) % 2019 == 0):
      ans += 1
      
print(ans)

### FIXED CODE ###

S = input()
Smod = [0] * 2019
Smod[0] = 1
ans = 0
S_i = 0
prevmod = 0
k = 1
for i in range(len(S)-1, -1, -1):
  S_i = (int(S[i]) * k + prevmod) % 2019
  ans += Smod[S_i]
  Smod[S_i] += 1
  prevmod = S_i
  k = (k * 10) % 2019
print(ans)
### BUGGY CODE ###

N = int(input())
S = input()
s = []
count = 300000
for i in range(N):
    s.append(S[i])
for i in range(N):
    cnt = 0
    for j in range(i):
        if S[j] == "W":
            cnt += 1
            if count < cnt:
                cnt -= 1
                break
    for j in range(N - 1, i, -1):
        if S[j] == "E":
            cnt += 1
            if count < cnt:
                cnt -= 1
                break
    count = cnt

print(count)

### FIXED CODE ###

N = int(input())
S = input()
s = []
cnt = 0
for i in range(N):
    if S[i] == "W":
        s.append(-1)
    elif S[i] == "E":
        s.append(1)
        if i != 0:
            cnt += 1
        
DP = [cnt]

for i in range(1, N):
    cnt = 0
    if s[i - 1] == -1:
        cnt += 1
    if s[i] == 1:
        cnt -= 1
    DP.append(DP[i - 1] + cnt)

print(min(DP))
### BUGGY CODE ###

import math

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

inf = int(1e6+5)
C = [0]*inf

for a in A:
    C[a] += 1

pa = True
se = True
for i in range(2, inf):
    cnt = 0
    for j in range(i, inf, i):
        cnt += C[j]
    if cnt > 1:
        pa = False
    if cnt == N:
        se = False
        
if pa:
    print("pairwise coprime")
elif se:
    print("setwise coprime")
else:
    print("not coprime")


### FIXED CODE ###

import math

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

inf = int(1e6+5)
C = [0]*inf

for a in A:
    C[a] += 1

pa = True
se = True
for i in range(2, inf):
    cnt = 0
    for j in range(i, inf, i):
        cnt += C[j]
    if cnt > 1:
        pa = False
    if cnt == N:
        se = False
        
if pa:
    print("pairwise coprime")
elif se:
    print("setwise coprime")
else:
    print("not coprime")
### BUGGY CODE ###

L,R = map(int,input().split())

res = []
for i in range(L,R):
    for j in range(L+1,R+1):
        res.append((i*j)%2019)
print(min(res))

### FIXED CODE ###

L,R = map(int,input().split())
m = R - L
if(m >= 2019):
    print(0)
else:
    res = []
    for i in range(L,R):
        for j in range(L+1,R+1):
            res.append((i*j)%2019)
    print(min(res))
### BUGGY CODE ###

N,X=map(int,input().split())
l=[2**(i+2)-3 for i in range(N+1)]#レベルLバーガー層数
p=[2**(i+1)-1 for i in range(N+1)]#レベルL パティ数
bp=[[0 for i in range(X+1)] for j in range(N+1)]
bp[0][1]=1
for i in range(N):
    for j in range(X+1):
        if j==1:
            bp[i+1][j]=0
        elif 1<j<=l[i]+1:
            bp[i+1][j]=bp[i][j-1]
        elif j==l[i]+2:
            bp[i+1][j]=p[i]+1
        elif l[i]+2<j<l[i+1]:
            bp[i+1][j]=p[i]+1+bp[i][j-l[i]-2]
        elif j==l[i+1]:
            bp[i+1][j]=p[i+1]
print(bp[N][X])

### FIXED CODE ###

N,X=map(int,input().split())
l=[2**(i+2)-3 for i in range(N+1)]#レベルLバーガー層数
p=[2**(i+1)-1 for i in range(N+1)]#レベルL パティ数
def f(n,x):
    if n==0:
        return 1
    elif x==1:
        return 0
    elif 1<x<=l[n-1]+1:
        return f(n-1,x-1)
    elif x==l[n-1]+2:
        return p[n-1]+1
    elif l[n-1]+2<x<l[n]:
        return p[n-1]+1+f(n-1,x-l[n-1]-2)
    elif x==l[n]:
        return p[n]
print(f(N,X))
### BUGGY CODE ###

temp=list(map(int, input().split()))
N=temp[0]
M=temp[1]

import numpy as np
a=np.zeros(M).astype(int)
b=np.zeros(M).astype(int)

check=np.zeros(M).astype(int)

for i in range(M):
  temp=list(map(int, input().split()))
  a[i]=temp[0]-1
  b[i]=temp[1]-1  

bridge=np.zeros(N-1).astype(int)
  
while(sum(check)!=M):
  cnt=np.zeros(N-1).astype(int)
  for i in range(M):
    if check[i]:
      continue
    cnt[a[i]:b[i]]+=1
    
  
  #カウント最大の橋を切る
  val=0
  for i in range(N-1):
    if val<cnt[i]:
      val=cnt[i]
      idx=i
  bridge[idx]=1
  for i in range(M):
    if check[i]:
      continue
    for j in range(a[i],b[i]):
      if bridge[j]:
        check[i]=1
print(sum(bridge))

### FIXED CODE ###

import numpy as np

temp=list(map(int, input().split()))
N=temp[0]
M=temp[1]

A=np.zeros((M,2)).astype(int)

for i in range(M):
  temp=list(map(int, input().split()))
  temp[0]-=1
  temp[1]-=1
  A[i]=temp
idx=A[:,1].argsort()
a=[0]*M
b=[0]*M
for i in range(M):
  a[i]=A[idx[i],0]
  b[i]=A[idx[i],1]
flag=False
x=-1
ans=0
for i in range(M):
  if a[i]>x:
    x=b[i]-1
    ans+=1
print(ans)
### BUGGY CODE ###

import itertools

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

ans = 0
for a, b, c in itertools.combinations(L, r=3):
    if a + b > c and b + c > a and c + a > b:
        ans += 1

print(ans)

### FIXED CODE ###

#提出 #8086687

import bisect
n = int(input())
l = list(map(int,input().split()))
l.sort()
ans = 0
for b in range(n):
  for a in range(b):
    ans += bisect.bisect_left(l,l[a]+l[b])-(b+1)
print(ans)
### BUGGY CODE ###

import scipy.sparse as sps
import scipy.sparse.csgraph as spsc
import numpy as np
from sys import stdin
 
N,M = map(int,stdin.readline().split())
 
S,T = map(int,stdin.readline().split())
S,T = S-1,T-1
 
E = sps.dok_matrix((N,N),dtype=int)
 
def it():
  lines = stdin.readlines()
  for line in lines:
    u,v,d = map(int,line.split())
    u,v = u-1,v-1
    yield ((u,v),d)
E.update(it())
 
 
dS,dT = spsc.dijkstra(E,directed=False, indices=[S,T]).astype(int)
D = dS[T]
D2 = D//2
 
E = tuple((u,v) for d,u,v in ((d,u,v) if dS[u] <= dS[v] else (d,v,u) for (u,v),d in E.items()) if dS[u]+d+dT[v] == D)
 
MOD = 10**9+7
 
 
def helper(start, edges):
  cnts = [0]*N
  cnts[start] = 1
  for d,u,v in edges:
    cnts[v] = (cnts[v] + cnts[u]) % MOD
  return cnts
 
 
Sn = helper(S,sorted((dS[u],u,v) for u,v in E))
Tn = helper(T,sorted((dT[v],v,u) for u,v in E))
 
from functools import reduce
 
def it():
  for v in range(N):
    if dS[v] == D2:
      yield (Sn[v]*Tn[v])**2
 
c0 = reduce(lambda x,y: (x+y)%MOD, it(), 0) if D%2==0 else 0
 
diff = dS-dT
 
def it():
  for u,v in E:
    if diff[u] < 0 < diff[v]:
      yield (Sn[u]*Tn[v])**2
 
c1 = reduce(lambda x,y: (x+y)%MOD, it(), 0)
 
total = Sn[T]*Tn[S]
cnt = c0+c1
 
print((total-cnt)%MOD)

### FIXED CODE ###

from collections import defaultdict
from functools import reduce
import heapq as hq
from sys import stdin
 
MOD = 10**9+7
N,M = map(int,stdin.readline().split())
S,T = map(int,stdin.readline().split())
S,T = S-1,T-1
 
E = defaultdict(list)
lines = stdin.readlines()
for line in lines:
  u,v,d = map(int,line.split())
  E[u-1].append((v-1,d))
  E[v-1].append((u-1,d))
 
dS = [None]*N
dT = [None]*N
 
Q = [(0,S,False),(0,T,True)]
 
D = float('inf')
 
 
while Q:
  d,v,f = hq.heappop(Q)
  if d*2 > D:
    break

  dM = dT if f else dS
  dN = dS if f else dT
  if dM[v] is None:
    dM[v] = d
    for u,dd in E[v]:
      if dM[u] is None and (d+dd)*2 <= D:
        hq.heappush(Q,(d+dd,u,f))
 
  if dN[v] is not None:
    D = min(dN[v]+d,D)
 
del Q

def helper(start,dist):
  cnts = [0]*N
  cnts[start] = 1

  for d,v in sorted((d,v) for v,d in enumerate(dist) if d is not None):
    c = cnts[v]
    for u,dd in E[v]:
      if dd+d == dist[u]:
        cnts[u] = (cnts[u]+c) % MOD

  return cnts

Sn = helper(S,dS)
Tn = helper(T,dT)


def it():
  for v in range(N):
    if dS[v] is not None:
      ds = dS[v]
      if dT[v] == ds and ds*2 == D:
        yield Sn[v]*Tn[v] % MOD
      else:
        for u,d in E[v]:
          if dT[u] is not None and abs(dT[u]-ds) < d and ds+d+dT[u] == D:
            yield Sn[v]*Tn[u] % MOD


X = list(it())

 
total = reduce(lambda a,b:(a+b)%MOD, X,0)
total = total*total % MOD
 
sub = reduce(lambda a,b:(a+b)%MOD, map(lambda x: x*x % MOD, X),0)
print((total-sub)%MOD)
### BUGGY CODE ###

import sys
def input(): return sys.stdin.readline().rstrip()
def main():
    n=int(input())
    A=list(map(int,input().split()))
    mod=10**9+7
    C1=[0]*60
    for a in A:
        ax=a
        for i in range(60):
            if ax&1:C1[i]+=1
            ax>>=1
            if ax==0:break
    ans=0
    for i,c in enumerate(C1):
        ans+=c*(n-c)*2**i%mod
    print(ans%mod)

if __name__=='__main__':
    main()

### FIXED CODE ###

import sys
def input(): return sys.stdin.readline().rstrip()
def main():
    n=int(input())
    A=list(map(int,input().split()))
    mod=10**9+7
    max_n=len(format(max(A),'b'))
    C=[[0,0] for _ in range(max_n)]
    for a in A:
        ax=a
        for i in range(max_n):
            C[i][ax%2]+=1
            ax=ax//2
    ans=0
    for i,c in enumerate(C):
        ans+=c[0]*c[1]*2**i%mod
    print(ans%mod)

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

n = int(input())
a = [int(i) for i in input().split()]
x = 1
for i in a:
  if 0 in a:
    x = 0
    break
  x *= i
 
  if x > 10**18:
    x = -1
    break
 
print(x)

### FIXED CODE ###

n = input()
lista = list(map(int,input().split()))
r = 1

if 0 in lista:
  print(0)
else:
  for a in lista:
    r *= a
    if r > 10**18:
      print(-1)
      break
  else:
    print(r)
### BUGGY CODE ###

n,k=map(int,input().split())
if n==1 and k==1:
    print(1)
    exit()
if k==1:
    print(0)
    exit()
g=[[] for i 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)
mod=10**9+7
pk2=[0]*(k-1)
pk2[0]=1
for i in range(k-2):
    pk2[i+1]=pk2[i]*(k-2-i)%mod
def p(n,r):
    if n<r:
        return 0
    return pk2[r]
ans=k
q=[0]
v=[0]*n
v[0]=1
vc=1
while q and vc<n:
    s=q.pop(0)
    c=0
    for es in g[s]:
        if v[es]==0:
            v[es]=1
            vc+=1
            c+=1
            q.append(es)
    if s==0:
        if k-1<c:
            ans=0
            break
        for i in range(k-c,k):
            ans*=i
            ans%=mod
        ans%=mod
    else:
        ans*=p(k-2,c)
        ans%=mod
print(ans%mod)


### FIXED CODE ###

from collections import deque
n,k=map(int,input().split())
if n==1 and k==1:
    print(1)
    exit()
if k==1:
    print(0)
    exit()
g=[[] for i 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)
mod=10**9+7
ans=k
q=deque([0])
v=[0]*n
v[0]=1
vc=1
while q and vc<n:
    s=q.popleft()
    c=0
    if s==0:
        kai=k-1
    else:
        kai=k-2
    for es in g[s]:
        if v[es]==0:
            v[es]=1
            vc+=1
            c+=1
            q.append(es)
            ans*=kai
            ans%=mod
            kai-=1
print(ans%mod)
### BUGGY CODE ###

import sys
sys.setrecursionlimit(1000000)
n,m = map(int,input().split())
graph = [[] for _ in range(n+1)]
for _ in range(m):
    a,b = map(int,input().split())
    graph[a].append(b)
    graph[b].append(a)
ans = 1
def dfs(node):
    todo = set()
    for nextnode in graph[node]:
        if tf[nextnode] == 0 :
            tf[nextnode] = 1
            seen.add(nextnode)
            todo.add(nextnode)
    for nextnode in todo:
        dfs(nextnode)
done = set()
for i in range(1,n+1):
    if i in done:
        continue
    else:
        done.add(i)
        tf = [0 for _ in range(n+1)]
        seen = set()
        dfs(i)
        ans = max(ans,sum(tf))
        done |= seen
print(ans)

### FIXED CODE ###

from collections import deque

n,m = map(int,input().split())
graph = [[] for _ in range(n+1)]
for _ in range(m):
    a,b = map(int,input().split())
    graph[a].append(b)
    graph[b].append(a)
ans = 1

def dfs(node):
    while len(todo) > 0:
        node = todo.pop()
        if tf[node] == 0:
            tf[node] = 1
            seen.add(node)
            for nextnode in graph[node]:
                todo.append(nextnode)

todo = deque()
done = set()
tf = [0 for _ in range(n+1)]
for i in range(1,n+1):
    if i in done:
        continue
    else:
        todo.append(i)
        seen = set()
        dfs(i)
        #print(i,seen)
        ans = max(ans,len(seen))
        done |= seen
print(ans)
### BUGGY CODE ###

def resolve():
  N = int(input())
  X = input()

  if N == 1:
    if X.count("1"):
      print(0)
    else:
      print(1)
    return True

  base_1_count = X.count("1")
  if base_1_count == 0:
    for _ in range(N):
      print(1)
    return True

  X_int = int(X, 2)
  X_int_p = X_int%(base_1_count + 1)

  # RE 対策
  if base_1_count == 1:
    for i in range(N):
      if X[i] == "1":
        print(0)
      else:
        if i == N - 1:
          Xi = X_int_p + 1
        else:
          Xi = X_int_p
        count = 1
        while Xi != 0:
          Xi %= bin(Xi).count("1")
          count += 1
        print(count)
    return True

  X_int_m = X_int%(base_1_count - 1)
  for i in range(N):
    # 初期値計算を高速にやる
    if X[i] == "1":
      temp_1_count = base_1_count-1
      pow_2 = 2**(N-i-1)%(base_1_count-1)
      if X_int_m <= pow_2:
        Xi = X_int_m - pow_2 + base_1_count-1
      else:
        Xi = X_int_m - pow_2
    else:
      temp_1_count = base_1_count+1
      Xi = X_int_p + 2**(N-i-1)%(base_1_count+1)
      while Xi >= base_1_count+1:
        Xi %= base_1_count+1

    # print("1_c={0}".format(temp_1_count))
    if temp_1_count == Xi:
      print(1)
      continue

    count = 1
    while Xi != 0:
      num_of_1 = bin(Xi).count("1")
      Xi %= num_of_1
      count += 1
    print(count)

if __name__ == "__main__":
    resolve()

### FIXED CODE ###

def resolve():
  N = int(input())
  X = input()

  if N == 1:
    if X.count("1"):
      print(0)
    else:
      print(1)
    return True

  base_1_count = X.count("1")
  if base_1_count == 0:
    for _ in range(N):
      print(1)
    return True

  X_int = int(X, 2)
  X_int_p = X_int%(base_1_count + 1)

  # RE 対策
  if base_1_count == 1:
    for i in range(N):
      if X[i] == "1":
        print(0)
      else:
        if i == N - 1:
          Xi = X_int_p + 1
        else:
          Xi = X_int_p
        count = 1
        while Xi != 0:
          Xi %= bin(Xi).count("1")
          count += 1
        print(count)
    return True

  X_int_m = X_int%(base_1_count - 1)
  for i in range(N):
    # 初期値計算を高速にやる
    if X[i] == "1":
      temp_1_count = base_1_count-1
      pow_2 = pow(2, N-i-1, base_1_count-1)
      if X_int_m <= pow_2:
        Xi = X_int_m - pow_2 + base_1_count-1
      else:
        Xi = X_int_m - pow_2
    else:
      temp_1_count = base_1_count+1
      Xi = X_int_p + pow(2, N-i-1, base_1_count+1)
      while Xi >= base_1_count+1:
        Xi %= base_1_count+1

    # print("1_c={0}".format(temp_1_count))
    if temp_1_count == Xi:
      print(1)
      continue

    count = 1
    while Xi != 0:
      num_of_1 = bin(Xi).count("1")
      Xi %= num_of_1
      count += 1
    print(count)

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

s = list(input())
n = len(s)
s.reverse()
dp = [[0 for i in range(13)] for j in range(n)]
if s[0] == "?":
    for i in range(10):
        dp[0][i] = dp[0][i] + 1
else:
    s0 = int(s[0])
    dp[0][s0] = dp[0][s0] + 1
for i in range(1,n):
    if s[i] != "?":
        s1 = int(s[i])
        for j in range(13):
            k = j - (s1*(10**i))%13
            if k < 0:
                k = k + 13
            else:
                k = k % 13
            dp[i][j] = dp[i-1][k]
    else:
        for j in range(13):
            for x in range(10):
                k = (x*((10**i)%13))%13
                dp[i][(j+k)%13] = (dp[i-1][j] + dp[i][(j+k)%13])%(10**9 + 7)
print(dp[n-1][5])

### FIXED CODE ###

s = list(input())
n = len(s)
s.reverse()
m = 10**9 + 7
p = 10
dp = [[0 for i in range(13)] for j in range(n)]
if s[0] == "?":
    for i in range(10):
        dp[0][i] = dp[0][i] + 1
else:
    s0 = int(s[0])
    dp[0][s0] = dp[0][s0] + 1
for i in range(1,n):
    if s[i] != "?":
        s1 = int(s[i])
        k = (s1*p)%13
        for j in range(13):
            dp[i][(j+k)%13] = dp[i-1][j]
    else:
        for x in range(10):
            k = (x*p)%13
            for j in range(13):
                dp[i][(j+k)%13] += dp[i-1][j]
                dp[i][(j+k)%13] %= m
    p = (p * 10) % 13
print(dp[n-1][5])
### BUGGY CODE ###

from heapq import heappush, heappop

N = int(input())
a = [int(x) for x in input().split()]

left = sorted(a[:N])
max_left = [sum(left)]

right = sorted([-x for x in a[-N:]])
min_right = [sum(right) * -1]

for i in range(N, 2 * N):
    heappush(left, a[i])
    heappop(left)
    max_left.append(sum(left))

    heappush(right, a[3 * N - i - 1] * -1)
    heappop(right)
    min_right.append(sum(right) * -1)

ans = float('-inf')
for l, r in zip(max_left, min_right[::-1]):
    ans = max(l - r, ans)
print(ans)


### FIXED CODE ###

from heapq import heappush, heappop

N = int(input())
a = [int(x) for x in input().split()]

left = sorted(a[:N])
max_left = [sum(left)]

right = sorted([-x for x in a[-N:]])
min_right = [sum(right) * -1]

for i in range(N, 2 * N):
    j = 3 * N - i - 1

    heappush(left, a[i])
    v = heappop(left)
    max_left.append(max_left[-1] - v + a[i])

    heappush(right, a[j] * -1)
    v = heappop(right) * -1
    min_right.append(min_right[-1] - v + a[j])

ans = float('-inf')
for l, r in zip(max_left, min_right[::-1]):
    ans = max(l - r, ans)
print(ans)
### BUGGY CODE ###


#AのリストにCのリストを加えて大きい順に並べ替えてNまでの和を求める

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

#Aの入力
A_list = list(map(int,input().split()))

#Aの末尾にCのリストを追加する
for i in range(M):
    bi,ci = map(int,input().split())
    for j in range(bi):
        A_list.append(ci)

#A_Listを大きい順に並べ替える
A_list=sorted(A_list,reverse=True)

#N番目までの総和を求める
print(sum(A_list[0:N]))


### FIXED CODE ###


#AのリストにCのリストを加えて大きい順に並べ替えてNまでの和を求める
N,M = map(int,input().split())

#Aの入力
A_list = list(map(int,input().split()))

C_list = []

#Cのリストに追加する
for i in range(M):
    bi,ci = map(int,input().split())
    C_list.append([bi,ci])

#C_listをCの値でソート
C_list=sorted(C_list, reverse=True, key=lambda x:x[1])

count = 0
for bi,ci in C_list:
    count += bi
    if count > N:
        #countがNより大きくなったらNより大きくなった分だけ使う
        bi = N - count + bi
    A_list.extend([ci]*bi)

#A_Listを大きい順に並べ替える
A_list=sorted(A_list,reverse=True)

#N番目までの総和を求める
print(sum(A_list[0:N]))
### BUGGY CODE ###

# -*- coding: utf-8 -*-
"""
C - 755

"""
def gen_357():
    def conv(n):
        res = []
        while n:
            n, r = divmod(n, 4)
            res.append(str(str(r)))
        if not res:
            res = ['0']
        return ''.join(res[::-1]).translate(str.maketrans('0123', '0357'))

    n = 0
    while True:
        t = conv(n)
        while '0' in t or len(set(list(t))) != 3:
            n += 1
            t = conv(n)
        yield t
        n += 1


def solve(n):
    ans = 0
    g = gen_357()
    while True:
        t = next(g)
        if int(t) > n:
            break
        ans += 1
    return ans


n = int(input())
ans = solve(n)
print(ans)


### FIXED CODE ###

# -*- coding: utf-8 -*-
"""
C - 755
TLE
"""
def gen_357():
    def conv(n):
        res = []
        while n:
            n, r = divmod(n, 4)
            if r == 0 and n:
                return '0'
            res.append(str(str(r)))
        if not res:
            res = ['0']
        return ''.join(res[::-1]).translate(str.maketrans('0123', '0357'))

    n = 0
    while True:
        t = conv(n)
        while '0' in t or len(set(list(t))) != 3:
            n += 1
            t = conv(n)
        yield t
        n += 1


def solve(n):
    ans = 0
    g = gen_357()
    while True:
        t = next(g)
        if int(t) > n:
            break
        ans += 1
    return ans


n = int(input())
ans = solve(n)
print(ans)