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

import sys
input = sys.stdin.readline
N, M = map(int, input().split())
INF = 10 ** 12
dp = [INF] * (2**N)
dp[0] = 0
for i in range(M):
    a, b = map(int, input().split())
    C = list(map(int, input().split()))
    base = sum(2**(c-1) for c in C)
    for j in range(2**N):
        if any(not ((j >> (c-1)) & 1) for c in C):
            step = base - sum(2**(c-1) for c in C if ((j >> (c-1)) & 1))
            dp[j+step] = min(dp[j+step], dp[j]+a)

print(dp[-1] if dp[-1] < INF else -1)


### FIXED CODE ###

import sys
input = sys.stdin.readline
N, M = map(int, input().split())
INF = 10 ** 12
T = [2**i for i in range(N)]
dp = [INF] * (2**N)
dp[0] = 0
for i in range(M):
    a, b = map(int, input().split())
    C = list(map(int, input().split()))
    step = sum(T[c-1] for c in C)
    for j in range(2**N):
        dp[step|j] = min(dp[step|j], dp[j]+a)

print(dp[-1] if dp[-1] < INF else -1)
### BUGGY CODE ###

# -*- coding: utf-8 -*-
import time
import re

N = input()
T = ''
char_one = 'dream'
char_two = 'dreamer'
char_three = 'erase' 
char_four = 'eraser'
char_list = [char_one[::-1], char_two[::-1], char_three[::-1], char_four[::-1]]
reverse_string = N[::-1]

start = time.time()
concat_str = ''
i = 0

while i < len(N):
    for string in char_list:
        if reverse_string.find(string) == 0:
            i += len(string)
            reverse_string = re.sub(string, '', reverse_string)
            break
    if i == 0:
       break

if i == len(N):
   print('YES')
else:
   print('NO')


### FIXED CODE ###

S = input()

new_S = "".join(list(reversed(S)))
string_list = ["dream", "dreamer", "erase", "eraser"]
reverse_string_list = []
for i in range(len(string_list)):
    reverse_string_list.append("".join(list(reversed(string_list[i]))))

can = True
index = 0
for i in range(len(new_S)):
    if index >= len(new_S):
        break
    can2 = False
    for each_string in reverse_string_list:
        if new_S[index:index + len(each_string)] == each_string:
            index += len(each_string) - 1
            can2 = True
    if can2 is False:
        can = False
        break
    index += 1

if can is True:
    print("YES")
else:
    print("NO")
### BUGGY CODE ###

from math import sqrt
N, P = list(map(int, input().split()))
if N == 1:
    print(P)
    exit()

ans = 1
tmp = P
# start = int(sqrt(P))
# for i in range(start, 1, -1):
#     newtmp, rest = divmod(tmp, (i**N))
#     print(i, tmp, rest, ans)
#     if rest == 0:
#         ans = ans * i
#         tmp = newtmp

for i in range(2, P):
    po = i**N
    while True:
        newtmp, rest = divmod(tmp, po)
        # print(i, tmp, rest, ans)
        if rest:
            break
        else:
            ans = ans * i
            tmp = newtmp
    if newtmp == 0:
        break

print(ans)


### FIXED CODE ###

N, P = list(map(int, input().split()))
if N == 1:
    print(P)
    exit()
elif P == 1:
    print("1")
    exit()

ans = 1
tmp = P

for i in range(2, int(pow(P, 1 / N)) + 1):
    po = pow(i, N)
    while tmp % po == 0:
        tmp = tmp // po
        ans = ans * i
        # print(i, tmp, ans)

    if tmp < po:
        break

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

import sys

n, *inp = map(int, sys.stdin.buffer.read().split())
vvv = [0] + inp[0:n * 2:2]
www = [0] + inp[1:n * 2:2]

weight_limit = 10 ** 5
precalc_limit = min(1 << 9, n + 1)
precalc = [[0] * (weight_limit + 1)]

for u in range(1, precalc_limit):
    v = vvv[u]
    w = www[u]
    dp = precalc[u >> 1][:]
    for x in range(weight_limit, w - 1, -1):
        nv = dp[x - w] + v
        if dp[x] < nv:
            dp[x] = nv
    precalc.append(dp)

buf = []
mp = iter(inp[n * 2 + 1:])
for u, l in zip(mp, mp):
    if u < precalc_limit:
        buf.append(precalc[u][l])
        continue
    dp = {0: 0}
    while u >= precalc_limit:
        v = vvv[u]
        w = www[u]
        for cw, cv in list(dp.items()):
            nw = cw + w
            nv = cv + v
            if nw > l:
                continue
            if nw not in dp or dp[nw] < nv:
                dp[nw] = nv
        u >>= 1
    ans = max(v + precalc[u][l - w] for w, v in dp.items())
    buf.append(ans)

print('\n'.join(map(str, buf)))


### FIXED CODE ###

import sys

n, *inp = map(int, sys.stdin.buffer.read().split())
vvv = [0] + inp[0:n * 2:2]
www = [0] + inp[1:n * 2:2]

weight_limit = 10 ** 5
precalc_limit = min(1 << 10, n + 1)
precalc = [[0] * (weight_limit + 1)]

for u in range(1, precalc_limit):
    v = vvv[u]
    w = www[u]
    dp = precalc[u >> 1][:]
    for x in range(weight_limit, w - 1, -1):
        nv = dp[x - w] + v
        if dp[x] < nv:
            dp[x] = nv
    precalc.append(dp)

buf = []
mp = iter(inp[n * 2 + 1:])
for u, l in zip(mp, mp):
    if u < precalc_limit:
        buf.append(precalc[u][l])
        continue
    dp_w = [0]
    dp_v = [0]
    while u >= precalc_limit:
        v = vvv[u]
        w = www[u]
        for i in range(len(dp_w)):
            nw = dp_w[i] + w
            if nw > l:
                continue
            nv = dp_v[i] + v
            dp_w.append(nw)
            dp_v.append(nv)
        u >>= 1
    ans = 0
    for w, v in zip(dp_w, dp_v):
        nv = v + precalc[u][l - w]
        if ans < nv:
            ans = nv
    buf.append(ans)

print('\n'.join(map(str, buf)))
### BUGGY CODE ###

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

from itertools import combinations

ans = float('inf')
for s in combinations(xy, K):
    x, y = zip(*s)
    ans = min(ans, (max(x) - min(x)) * (max(y) - min(y)))
print(ans)

### FIXED CODE ###

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

xs, ys = tuple(zip(*xy))
cmpx = sorted(xs)
cmpy = sorted(ys)

x2cmp = dict((x, i) for i,x in enumerate(cmpx))
y2cmp = dict((x, i) for i,x in enumerate(cmpy))

sm = [[0] * (N + 1) for _ in range(N + 1)]
for x, y in xy:
    sm[x2cmp[x]][y2cmp[y]] = 1

for i in range(N):
    for j in range(N):
        sm[i][j] += sm[i][j - 1]
for j in range(N):
    for i in range(N):
        sm[i][j] += sm[i - 1][j]

ans = float('inf')
for x1 in range(N):
    for y1 in range(N):
        for x2 in range(x1 + 1, N):
            for y2 in range(y1 + 1, N):
                k = sm[x2][y2] - sm[x2][y1 - 1] - sm[x1 - 1][y2] + sm[x1 - 1][y1 - 1]
                if k == K:
                    area = (cmpx[x2] - cmpx[x1]) * (cmpy[y2] - cmpy[y1])
                    ans = min(ans, area)

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

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

cost = [0] * N
for i in range(1, N):
  #print('i=', i)
  st = max(i - K, 0)
  ci = 10**18

  for j in range(st, i):
    if cost[j] < ci:
      cj = cost[j] + abs(H[i] - H[j])
      #print('cj=', cj)
      ci = min(cj, ci)

  #print('ci=', ci)
  cost[i] = ci

#print(cost)
ans = cost[N-1]
print(ans)

### FIXED CODE ###

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

cost = [0] * N
for i in range(1, N):
  #print('i=', i)
  st = max(i - K, 0)
  ci = 10**18

  for j in range(st, i):
    if cost[j] < ci:
      cj = cost[j] + abs(H[i] - H[j])
      #print('cj=', cj)
      ci = min(cj, ci)

  #print('ci=', ci)
  cost[i] = ci

#print(cost)
ans = cost[N-1]
print(ans)
### BUGGY CODE ###

n,k=map(int,input().split())
a=list(map(int,input().split()))
b=[]
x=[]
for i in range(0,n-k+1):
    for j in range(k):
        b.append(a[i+j])
    if min(b)>=0:
        ans=max(b)
    elif max(b)<=0:
        ans=abs(min(b))
    else:
        ans=min(abs(min(b))*2+max(b),abs(min(b))+max(b)*2)
    x.append(ans)
    b=[]         
print(min(x))

### FIXED CODE ###

n,k=map(int,input().split())
a=list(map(int,input().split()))
x=[]
for i in range(0,n-k+1):
    ans=a[i+k-1]-a[i]+min(abs(a[i+k-1]),abs(a[i]))
    x.append(ans)        
print(min(x))
### BUGGY CODE ###

import sys
sys.setrecursionlimit(1000000)

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

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

def find(a):
    if a==P[a]:
        return a
    else:
        return find(P[a])
        
def union(b,c):
    B=find(b)
    C=find(c)
    if size[C]>size[B]:
        P[B]=P[C]
    else:
        P[C]=P[B]
G=[0 for i in range(N+1)]
for i in range(M):
    a,b=map(int,input().split())
    G[a]+=1
    G[b]+=1
    union(a,b)
#print(P)
PP=[]
for i in range(N+1):
    PP.append(find(P[i]))
#print(PP)
PPP=[0 for i in range(N+1)]
for i in range(1,N+1):
    PPP[PP[i]]+=1
#print(PPP)

B=[[]for i in range(N+1)]
for i in range(K):
    c,d=map(int,input().split())
    B[c].append(d)
    B[d].append(c)
#print(G)
#print(B)
ans=[]
for i in range(1,N+1):
    ANS=PPP[PP[i]]-1-G[i]
    for j in B[i]:
        if PP[j]==PP[i]:
            ANS-=1
    ans.append(ANS)
print(*ans)

### FIXED CODE ###

import sys
sys.setrecursionlimit(1000000)
input=sys.stdin.readline

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

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

def find(a):
    if a==P[a]:
        return a
    else:
        return find(P[a])
        
def union(b,c):
    B=find(b)
    C=find(c)
    if size[C]>size[B]:
        P[B]=P[C]
        size[C]+=size[B]
    else:
        P[C]=P[B]
        size[B]+=size[C]
G=[0 for i in range(N+1)]
for i in range(M):
    a,b=map(int,input().split())
    G[a]+=1
    G[b]+=1
    union(a,b)
#print(P)
PP=[]
for i in range(N+1):
    PP.append(find(P[i]))
#print(PP)
PPP=[0 for i in range(N+1)]
for i in range(1,N+1):
    PPP[PP[i]]+=1
#print(PPP)

B=[[]for i in range(N+1)]
for i in range(K):
    c,d=map(int,input().split())
    B[c].append(d)
    B[d].append(c)
#print(G)
#print(B)
ans=[]
for i in range(1,N+1):
    ANS=PPP[PP[i]]-1-G[i]
    for j in B[i]:
        if PP[j]==PP[i]:
            ANS-=1
    ans.append(ANS)
print(*ans)
### BUGGY CODE ###

n=int(input())
a=list(map(int,input().split()))
q=int(input())
b=[]
c=[]
ans=sum(a)
cnt=0
for i in range(q):
    b,c=map(int,input().split())
    cnt=a.count(b)
    ans+=cnt*(c-b)
    for j in range(cnt):
        a.remove(b)
        a.append(c)
    print(ans)

### FIXED CODE ###

n=int(input())
a=list(map(int,input().split()))
q=int(input())
b=[]
c=[]
d=[0]*(10**5+1)
for i in range(n):
    d[a[i]]+=1
ans=sum(a)
cnt=0
for i in range(q):
    b,c=map(int,input().split())
    ans+=(d[b]*(c-b))
    d[c]+=d[b]
    d[b]=0
    print(ans)
### BUGGY CODE ###

N = int(input())
A = [int(input()) for i in range(N)]

l = []

for i in A:
    # print(A.count(i))
    if A.count(i) == 1:
        l.append(i)

print(len(l))


### FIXED CODE ###

import collections

N = int(input())
A = [int(input()) for i in range(N)]

count_dict = collections.Counter(A)

# print(count_dict)

count = 0

for i in count_dict.values():
    if i % 2 == 1:
        count += 1

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

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

L=[0]*M
R=[0]*M

for i in range(M):
  L[i],R[i]=map(int,input().split())

def prison(N,M,L,R):
  num=list(range(L[0],(R[0]+1)))
  for j in range(M):
    num=[i for i in num if L[j]<=i<=R[j]]
  return len(num)
print(prison(N,M,L,R))

### FIXED CODE ###

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

L=[0]*M
R=[0]*M

for i in range(M):
  L[i],R[i]=map(int,input().split())

def prison(N,M,L,R):
  max_val=min(R)
  min_val=max(L)
  num=max_val-min_val+1
  if num<=0:
    num=0
  return(num)

print(prison(N,M,L,R))
### BUGGY CODE ###

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

import fractions

mod = 10**9+7
num = 1
for i in range(N):
    num = num*A[i]//fractions.gcd(num, A[i])

ans = 0
for i in range(N):
    ans += num//A[i]
    ans %= mod

print(ans)


### FIXED CODE ###

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

mod = 10**9+7
def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a%b)

t = 1
for a in A:
    t = a*t//gcd(a, t)

ans = 0
for a in A:
    ans += t//a

print(ans%mod)
### BUGGY CODE ###

# D - RGB Triplets

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

r, g, b = 0, 0, 0

for s in S:
	if s == 'R':
		r += 1
	elif s == 'G':
		g += 1
	else:
		b += 1

ans = r * g * b

for i in range(N - 2):
	for j in range(i + 1, N - 1):
		for k in range(j + 1, N):
			if S[i] != S[j] and S[i] != S[k] and S[j] != S[k]:
				if j -i == k -j:
					ans -= 1

print(ans)

### FIXED CODE ###

# D - RGB Triplets
	
N = int(input())
S = input()
	
r, g, b = 0, 0, 0
	
for s in S:
	if s == 'R':
		r += 1
	elif s == 'G':
		g += 1
	else:
		b += 1
	
ans = r * g * b
	
for i in range(N - 2):
	for j in range(i + 1, N - 1):
		k = j * 2 - i
			
		if k < N:
			if S[i] != S[j] and S[i] != S[k] and S[j] != S[k]:
				if j -i == k -j:
					ans -= 1
	
print(ans)
### BUGGY CODE ###

n,k = map(int,input().split())
a = list(map(int,input().split()))
b = a[:]
for i in range(1,k):
    a[i] = a[i] * a[i-1]
for i in range(k,n):
    a[i] = a[i] * a[i-1] // b[i-k]
    if a[i] > a[i-1]:
        print('Yes')
    else:
        print('No')


### FIXED CODE ###

n,k = map(int,input().split())
a = list(map(int,input().split()))
for i in range(k,n):
    if a[i] > a[i-k]:
        print('Yes')
    else:
        print('No')
### BUGGY CODE ###

while 1:
	try:
		stack = []
		for s in raw_input().split():
			if s == "-":
				stack.append(stack.pop(-2) - stack.pop())
			elif s == "+":
				stack.append(stack.pop(-2) + stack.pop())
			elif s == "/":
				stack.append(stack.pop(-2) / stack.pop())
			elif s == "*":
				stack.append(stack.pop(-2) * stack.pop())
			elif s == "%":
				stack.append(stack.pop(-2) % stack.pop())
			else:
				stack.append(float(s))
	
		print stack[0]
	except:
		pass

### FIXED CODE ###

while 1:
	try:
		stack = []
		for s in raw_input().split():
			if s == "-":
				stack.append(stack.pop(-2) - stack.pop())
			elif s == "+":
				stack.append(stack.pop(-2) + stack.pop())
			elif s == "/":
				stack.append(stack.pop(-2) / stack.pop())
			elif s == "*":
				stack.append(stack.pop(-2) * stack.pop())
			else:
				stack.append(float(s))
	
		print "%.6f" % (stack[0])
	except:
		break
### BUGGY CODE ###

n=int(input())
s = [0]*n
dic = []
count = 1
for i in range(n):
    s[i] = input()

s = sorted(s)
i = 0
while (len(s)-i>1):
    if str(s[i]) == str(s[i+1]):
        s.pop(i)
    else:
        i += 1
print(len(s))

### FIXED CODE ###

n=int(input())
s = [0]*n
for i in range(n):
    s[i] = input()
print(len(set(s)))
### BUGGY CODE ###

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

cnt = 0
l = []
for i in P:
	l.append(i)
	if i == min(l):
		cnt += 1
print(cnt)

### FIXED CODE ###

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

cnt = 0
mi = P[0]
for i in range(N):
	if P[i] <= mi:
		mi = P[i]
		cnt += 1
print(cnt)
### BUGGY CODE ###

#!/usr/bin/python

import sys

def main(argv):
    tokens = sys.stdin.readline().rstrip("\n").split(" ")

    while len(tokens) == 3:
        n, k, l = map(lambda x: int(x), tokens)

        roads = [[0] * n for i in xrange(n)]
        railways = [[0] * n for i in xrange(n)]

        for i in xrange(0, n):
            roads[i][i] = 1
            railways[i][i] = 1

        for i in xrange(0, k):
            x, y = map(
              lambda c: int(c), sys.stdin.readline().rstrip("\n").split(" "))
            roads[x - 1][y - 1] = 1
            roads[y - 1][x - 1] = 1

        for i in xrange(0, l):
            x, y = map(
              lambda c: int(c), sys.stdin.readline().rstrip("\n").split(" "))
            railways[x - 1][y - 1] = 1
            railways[y - 1][x - 1] = 1

        for t in xrange(0, n):
            for i in xrange(0, n):
                for j in xrange(0, n):
                    if roads[i][t] == 1 and roads[t][j] == 1:
                        roads[i][j] = 1
                    if railways[i][t] == 1 and railways[t][j] == 1:
                        railways[i][j] = 1

        results = []
        for i in xrange(0, n):
            count = 0
            for j in xrange(0, n):
                if roads[i][j] == 1 and railways[i][j] == 1:
                    count += 1
            results.append(str(count))
        print " ".join(results)

        tokens = sys.stdin.readline().rstrip("\n").split(" ")
if __name__ == "__main__":
    main(sys.argv)

### FIXED CODE ###

#!/usr/bin/python

import sets
import sys

def find(parent, x):
    if parent[x] == x:
        return x
    else:
        parent[x] = find(parent, parent[x])
        return parent[x]

def union(parent, x, y):
    parent_x = find(parent, x)
    parent_y = find(parent, y)

    if parent_x != parent_y:
        parent[parent_y] = parent[parent_x]

def main(argv):
    tokens = sys.stdin.readline().rstrip("\n").split()

    while len(tokens) == 3:
        n, k, l = [int(i) for i in tokens]

        parent_roads = [int(i) for i in xrange(n)]
        parent_railways = [int(i) for i in xrange(n)]

        for i in xrange(k):
            x, y = [int(i) for i in raw_input().split(" ")]
            union(parent_roads, x - 1, y - 1)

        for i in xrange(l):
            x, y = [int(i) for i in raw_input().split(" ")]
            union(parent_railways, x - 1, y - 1)

        count = dict()
        for i in xrange(n):
            key = (find(parent_roads, i), find(parent_railways, i))
            if not count.has_key(key):
                count[key] = 0
            count[key] += 1

        results = []
        for i in xrange(n):
            key = (find(parent_roads, i), find(parent_railways, i))
            results.append(str(count[key]))
        print " ".join(results)

        tokens = sys.stdin.readline().rstrip("\n").split()

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

n = int(input())
mylist = []
for _ in range(n):
    s = input()
    s_list = [ c for c in s]
    mylist.append("".join(sorted(s_list)))

mylist2 = list(set(mylist))

ans=0
for i in range(len(mylist2)):
    count = mylist.count(mylist2[i])
    ans+=int(count*(count-1)/2)

print(ans)


### FIXED CODE ###

n = int(input())
i = 0
sortedSet = {}
while i < n:
    temp = ''.join(sorted(input()))

    if temp in sortedSet:
        sortedSet[temp]+=1
    else:
        sortedSet[temp]=1
    i += 1

result = 0
for v in sortedSet.values():
    result = int(result + v*(v-1)/2)

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

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

for i in range(max(a),0,-1):
  cnt = 0
  for j in a:
    if j % i != 0:
      cnt+=1
  if cnt < 2:
    print(i)
    break

### FIXED CODE ###

n=int(input())
a=sorted(list(map(int,input().split())))
i=a[1]
while i > 0:
  flg=0
  for j in a:
    if j%i!=0:
      flg+=1
      if flg>1:
        break
  if flg<=1:
    print(i)
    break
  else:
    i-=1
### BUGGY CODE ###

N = int(input())

A = [0] * N
for i in range(N):
    a = int(input())
    A[i] = a

for i in range(N):
    tmp = A[:]
    tmp.pop(i)
    print(max(tmp))

### FIXED CODE ###

N = int(input())

A = [0] * N
for i in range(N):
    a = int(input())
    A[i] = a

tmp = A[:]
tmp.sort(reverse=True)
for i in range(N):
    
    if tmp[0] == A[i]:
        print(tmp[1])
    else:
        print(tmp[0])
### BUGGY CODE ###

N = int(input())
sc = [list(input()) for i in range(N)]
for i in sc:
    i.sort()
count = 0
for i in range(0 , len(sc)-1):
    for j in range(i+1,len(sc)):
        if sc[i] == sc[j]:
            count += 1
print(count)

### FIXED CODE ###

N = int(input())
words = dict()
count = 0
for i in range(N):
    s = ''.join(sorted(input()))
    if s in words:
        count += words[s]
        words[s] += 1
    else:
        words[s] = 1
print(count)
### BUGGY CODE ###

import sys
import bisect


def main():
    n, K, L, R = map(int, sys.stdin.readline().split())
    a = tuple(map(int, sys.stdin.readline().split()))
    m = n//2
    ls = [[] for _ in range(m+1)]
    for i in range(1 << m):
        cnt = 0
        val = 0
        for j in range(m):
            if i >> j & 1:
                cnt += 1
                val += a[j]
        bisect.insort_left(ls[cnt], val)
    ans = 0
    for i in range(1 << n-m):
        cnt = 0
        val = 0
        for j in range(n-m):
            if i >> j & 1:
                cnt += 1
                val += a[m+j]
        if K-m <= cnt <= K:
            ans += bisect.bisect_right(ls[K-cnt], R-val) - bisect.bisect_right(ls[K-cnt], L-val-1)
    print(ans)


if __name__ == '__main__':
    main()



### FIXED CODE ###

import sys
import bisect


def main():
    n, K, L, R = map(int, sys.stdin.readline().split())
    a = tuple(map(int, sys.stdin.readline().split()))
    m = (n-1)//2
    ls = [[] for _ in range(m+1)]
    for i in range(1 << m):
        cnt = 0
        val = 0
        for j in range(m):
            if i >> j & 1:
                cnt += 1
                val += a[j]
        ls[cnt].append(val)
    for i in range(m+1):
        ls[i].sort()
    ans = 0
    for i in range(1 << n-m):
        cnt = 0
        val = 0
        for j in range(n-m):
            if i >> j & 1:
                cnt += 1
                val += a[m+j]
        if K-m <= cnt <= K:
            ans += bisect.bisect_right(ls[K-cnt], R-val) - bisect.bisect_right(ls[K-cnt], L-val-1)
    print(ans)


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

import sys
sys.setrecursionlimit(10 ** 7)

N = input()

# DP
INF = pow(10, 8)
L = len(N)
dp = [[INF] * 2 for _ in range(L+2)]
dp[0][0] = 0

# reverse
N = N[::-1] + '0'


for i in range(L+1):
    for j in range(2):
        # 繰り下がりも加味
        n = int(N[i])
        n += j

        # 更新後のdp
        ni = i + 1

        # 10通りから探索
        for a in range(10):
            nj = 0
            b = a - n

            # 繰り下がりあり
            if b < 0:
                b += 10
                nj = 1

            dp[ni][nj] = min(dp[i][j] + a + b, dp[ni][nj])

ans = min(dp[L+1][0], dp[L+1][1])

print(ans)


### FIXED CODE ###

import sys
sys.setrecursionlimit(10 ** 7)

N = input()

# DP
INF = pow(10, 8)
L = len(N)
dp = [[INF] * 2 for _ in range(L+2)]
dp[0][0] = 0

# reverse
N = N[::-1] + '0'


for i in range(L+1):
    for j in range(2):
        # 繰り下がりも加味
        n = int(N[i])
        n += j

        # 更新後のdp
        ni = i + 1

        # 10通りから探索
        for a in range(10):
            nj = 0
            b = a - n

            # 繰り下がりあり
            if b < 0:
                b += 10
                nj = 1

            dp[ni][nj] = min(dp[i][j] + a + b, dp[ni][nj])

ans = min(dp[L+1][0], dp[L+1][1])

print(ans)