message
stringlengths
2
59.7k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
37
108k
cluster
float64
20
20
__index_level_0__
int64
74
217k
Provide tags and a correct Python 3 solution for this coding contest problem. Nezzar's favorite digit among 1,…,9 is d. He calls a positive integer lucky if d occurs at least once in its decimal representation. Given q integers a_1,a_2,…,a_q, for each 1 ≀ i ≀ q Nezzar would like to know if a_i can be equal to a sum of several (one or more) lucky numbers. Input The first line contains a single integer t (1 ≀ t ≀ 9) β€” the number of test cases. The first line of each test case contains two integers q and d (1 ≀ q ≀ 10^4, 1 ≀ d ≀ 9). The second line of each test case contains q integers a_1,a_2,…,a_q (1 ≀ a_i ≀ 10^9). Output For each integer in each test case, print "YES" in a single line if a_i can be equal to a sum of lucky numbers. Otherwise, print "NO". You can print letters in any case (upper or lower). Example Input 2 3 7 24 25 27 10 7 51 52 53 54 55 56 57 58 59 60 Output YES NO YES YES YES NO YES YES YES YES YES YES NO Note In the first test case, 24 = 17 + 7, 27 itself is a lucky number, 25 cannot be equal to a sum of lucky numbers.
instruction
0
52,442
20
104,884
Tags: brute force, dp, greedy, math Correct Solution: ``` """ n=int(z()) for _ in range(int(z())): x=int(z()) l=list(map(int,z().split())) n=int(z()) l=sorted(list(map(int,z().split())))[::-1] a,b=map(int,z().split()) l=set(map(int,z().split())) led=(6,2,5,5,4,5,6,3,7,6) vowel={'a':0,'e':0,'i':0,'o':0,'u':0} color4=["G", "GB", "YGB", "YGBI", "OYGBI" ,"OYGBIV",'ROYGBIV' ] """ #!/usr/bin/env python #pyrival orz import os import sys from io import BytesIO, IOBase input = sys.stdin.readline ############ ---- Input Functions ---- ############ def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(list(s[:len(s) - 1])) def invr(): return(map(int,input().split())) def main(): try: t = inp() for _ in range(t): q, d = invr() a = inlt() dp = [False]*(10*d) dp[0] = True for j in range(10*d): for k in range(j+1, 10*d): if d in [int(l) for l in str(k-j)] and dp[j]: dp[k] = True for i in range(q): if a[i] >= 10*d or dp[a[i]]: print("YES") else: print("NO") # for y in range(10*d): # if dp[y] and str(d) in [i for i in str(a[i] - y)]: # print("YES") # dp[a[i]] = True # break # else: # print("NO") except Exception as e: print(e) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() ```
output
1
52,442
20
104,885
Provide tags and a correct Python 3 solution for this coding contest problem. Nezzar's favorite digit among 1,…,9 is d. He calls a positive integer lucky if d occurs at least once in its decimal representation. Given q integers a_1,a_2,…,a_q, for each 1 ≀ i ≀ q Nezzar would like to know if a_i can be equal to a sum of several (one or more) lucky numbers. Input The first line contains a single integer t (1 ≀ t ≀ 9) β€” the number of test cases. The first line of each test case contains two integers q and d (1 ≀ q ≀ 10^4, 1 ≀ d ≀ 9). The second line of each test case contains q integers a_1,a_2,…,a_q (1 ≀ a_i ≀ 10^9). Output For each integer in each test case, print "YES" in a single line if a_i can be equal to a sum of lucky numbers. Otherwise, print "NO". You can print letters in any case (upper or lower). Example Input 2 3 7 24 25 27 10 7 51 52 53 54 55 56 57 58 59 60 Output YES NO YES YES YES NO YES YES YES YES YES YES NO Note In the first test case, 24 = 17 + 7, 27 itself is a lucky number, 25 cannot be equal to a sum of lucky numbers.
instruction
0
52,443
20
104,886
Tags: brute force, dp, greedy, math Correct Solution: ``` t=int(input()) res=[[] for i in range(10)] for i in range(1,10): for j in range(1,10): k=i*j s=str(k) res[i].append([s[-1],k]) for i in range(t): n,d=map(int,input().split()) b=list(map(int,input().split())) for j in range(n): curr=b[j] s=str(curr)[-1] f=0 for k in res[d]: if k[0]==s[0] and curr>=k[1]: f=1 break if f or curr>=10*d: print("YES") else: print("NO") ```
output
1
52,443
20
104,887
Provide tags and a correct Python 3 solution for this coding contest problem. Nezzar's favorite digit among 1,…,9 is d. He calls a positive integer lucky if d occurs at least once in its decimal representation. Given q integers a_1,a_2,…,a_q, for each 1 ≀ i ≀ q Nezzar would like to know if a_i can be equal to a sum of several (one or more) lucky numbers. Input The first line contains a single integer t (1 ≀ t ≀ 9) β€” the number of test cases. The first line of each test case contains two integers q and d (1 ≀ q ≀ 10^4, 1 ≀ d ≀ 9). The second line of each test case contains q integers a_1,a_2,…,a_q (1 ≀ a_i ≀ 10^9). Output For each integer in each test case, print "YES" in a single line if a_i can be equal to a sum of lucky numbers. Otherwise, print "NO". You can print letters in any case (upper or lower). Example Input 2 3 7 24 25 27 10 7 51 52 53 54 55 56 57 58 59 60 Output YES NO YES YES YES NO YES YES YES YES YES YES NO Note In the first test case, 24 = 17 + 7, 27 itself is a lucky number, 25 cannot be equal to a sum of lucky numbers.
instruction
0
52,444
20
104,888
Tags: brute force, dp, greedy, math Correct Solution: ``` from sys import stdin stdin.readline def mp(): return list(map(int, stdin.readline().strip().split())) def it():return int(stdin.readline().strip()) from collections import Counter as C # for _ in range(it()): # n=it() # l=mp() # c=C(l) # k=max(c.values()) # print(k) for _ in range(it()): n,d=mp() l=mp() for j in l: while str(d) not in str(j): j-=d if j>0: print('YES') else: print("NO") ```
output
1
52,444
20
104,889
Provide tags and a correct Python 3 solution for this coding contest problem. Nezzar's favorite digit among 1,…,9 is d. He calls a positive integer lucky if d occurs at least once in its decimal representation. Given q integers a_1,a_2,…,a_q, for each 1 ≀ i ≀ q Nezzar would like to know if a_i can be equal to a sum of several (one or more) lucky numbers. Input The first line contains a single integer t (1 ≀ t ≀ 9) β€” the number of test cases. The first line of each test case contains two integers q and d (1 ≀ q ≀ 10^4, 1 ≀ d ≀ 9). The second line of each test case contains q integers a_1,a_2,…,a_q (1 ≀ a_i ≀ 10^9). Output For each integer in each test case, print "YES" in a single line if a_i can be equal to a sum of lucky numbers. Otherwise, print "NO". You can print letters in any case (upper or lower). Example Input 2 3 7 24 25 27 10 7 51 52 53 54 55 56 57 58 59 60 Output YES NO YES YES YES NO YES YES YES YES YES YES NO Note In the first test case, 24 = 17 + 7, 27 itself is a lucky number, 25 cannot be equal to a sum of lucky numbers.
instruction
0
52,445
20
104,890
Tags: brute force, dp, greedy, math Correct Solution: ``` for _ in range(int(input())): q,d = map(int,input().split()) k = list(map(int,input().split())) for i in k: x = i f = 0 if x >= d*10: f = 1 if f == 0: while x >= d: if x%d == 0: f = 1 break x -= 10 print("yes" if f else "no") ```
output
1
52,445
20
104,891
Provide tags and a correct Python 3 solution for this coding contest problem. Nezzar's favorite digit among 1,…,9 is d. He calls a positive integer lucky if d occurs at least once in its decimal representation. Given q integers a_1,a_2,…,a_q, for each 1 ≀ i ≀ q Nezzar would like to know if a_i can be equal to a sum of several (one or more) lucky numbers. Input The first line contains a single integer t (1 ≀ t ≀ 9) β€” the number of test cases. The first line of each test case contains two integers q and d (1 ≀ q ≀ 10^4, 1 ≀ d ≀ 9). The second line of each test case contains q integers a_1,a_2,…,a_q (1 ≀ a_i ≀ 10^9). Output For each integer in each test case, print "YES" in a single line if a_i can be equal to a sum of lucky numbers. Otherwise, print "NO". You can print letters in any case (upper or lower). Example Input 2 3 7 24 25 27 10 7 51 52 53 54 55 56 57 58 59 60 Output YES NO YES YES YES NO YES YES YES YES YES YES NO Note In the first test case, 24 = 17 + 7, 27 itself is a lucky number, 25 cannot be equal to a sum of lucky numbers.
instruction
0
52,446
20
104,892
Tags: brute force, dp, greedy, math Correct Solution: ``` def generate_result(): t = int(input()) ret = [] for _ in range(t): q, d = map(int, input().split()) if d == 2 or d == 5: for a in map(int, input().split()): if a >= d * 10 or a % d == 0: yield "YES" else: yield "NO" else: if d % 2 == 0: b = d * 10 - 1 else: b = d * 10 - 10 for a in map(int, input().split()): if a > b: yield "YES" else: while a > 0: if a % d == 0: yield "YES" break else: a -= 10 else: yield "NO" def main(): print("\n".join(generate_result())) if __name__ == "__main__": main() ```
output
1
52,446
20
104,893
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nezzar's favorite digit among 1,…,9 is d. He calls a positive integer lucky if d occurs at least once in its decimal representation. Given q integers a_1,a_2,…,a_q, for each 1 ≀ i ≀ q Nezzar would like to know if a_i can be equal to a sum of several (one or more) lucky numbers. Input The first line contains a single integer t (1 ≀ t ≀ 9) β€” the number of test cases. The first line of each test case contains two integers q and d (1 ≀ q ≀ 10^4, 1 ≀ d ≀ 9). The second line of each test case contains q integers a_1,a_2,…,a_q (1 ≀ a_i ≀ 10^9). Output For each integer in each test case, print "YES" in a single line if a_i can be equal to a sum of lucky numbers. Otherwise, print "NO". You can print letters in any case (upper or lower). Example Input 2 3 7 24 25 27 10 7 51 52 53 54 55 56 57 58 59 60 Output YES NO YES YES YES NO YES YES YES YES YES YES NO Note In the first test case, 24 = 17 + 7, 27 itself is a lucky number, 25 cannot be equal to a sum of lucky numbers. Submitted Solution: ``` import sys import math t=int(input().strip()) for a0 in range(t): #n=int(input()) l=[int(i) for i in input().split()] q=l[0] d=l[1] l1=[int(i) for i in input().split()] c=0 flg=0 a=str(d)+'0' a=int(a) b=str(d) m=[] for i in l1: flg=0 if(i>=a): print("YES") else: while(i>0): if(str(i).count(b)>=1): flg=1 print("YES") break i-=d if(flg==0): print("NO") ```
instruction
0
52,447
20
104,894
Yes
output
1
52,447
20
104,895
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nezzar's favorite digit among 1,…,9 is d. He calls a positive integer lucky if d occurs at least once in its decimal representation. Given q integers a_1,a_2,…,a_q, for each 1 ≀ i ≀ q Nezzar would like to know if a_i can be equal to a sum of several (one or more) lucky numbers. Input The first line contains a single integer t (1 ≀ t ≀ 9) β€” the number of test cases. The first line of each test case contains two integers q and d (1 ≀ q ≀ 10^4, 1 ≀ d ≀ 9). The second line of each test case contains q integers a_1,a_2,…,a_q (1 ≀ a_i ≀ 10^9). Output For each integer in each test case, print "YES" in a single line if a_i can be equal to a sum of lucky numbers. Otherwise, print "NO". You can print letters in any case (upper or lower). Example Input 2 3 7 24 25 27 10 7 51 52 53 54 55 56 57 58 59 60 Output YES NO YES YES YES NO YES YES YES YES YES YES NO Note In the first test case, 24 = 17 + 7, 27 itself is a lucky number, 25 cannot be equal to a sum of lucky numbers. Submitted Solution: ``` for _ in range(int(input())): q,d=map(int,input().split()) a=list(map(int,input().split())) b=[] for i in a: m=str(i) m2=str(d) if m2 in m: print("Yes") else: l=i re=False while i>=0: i-=d if m2 in str(i): re=True break if re==True: print("Yes") else: print("No") ```
instruction
0
52,448
20
104,896
Yes
output
1
52,448
20
104,897
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nezzar's favorite digit among 1,…,9 is d. He calls a positive integer lucky if d occurs at least once in its decimal representation. Given q integers a_1,a_2,…,a_q, for each 1 ≀ i ≀ q Nezzar would like to know if a_i can be equal to a sum of several (one or more) lucky numbers. Input The first line contains a single integer t (1 ≀ t ≀ 9) β€” the number of test cases. The first line of each test case contains two integers q and d (1 ≀ q ≀ 10^4, 1 ≀ d ≀ 9). The second line of each test case contains q integers a_1,a_2,…,a_q (1 ≀ a_i ≀ 10^9). Output For each integer in each test case, print "YES" in a single line if a_i can be equal to a sum of lucky numbers. Otherwise, print "NO". You can print letters in any case (upper or lower). Example Input 2 3 7 24 25 27 10 7 51 52 53 54 55 56 57 58 59 60 Output YES NO YES YES YES NO YES YES YES YES YES YES NO Note In the first test case, 24 = 17 + 7, 27 itself is a lucky number, 25 cannot be equal to a sum of lucky numbers. Submitted Solution: ``` def to_digits(n): digits = [] while n > 0: digits.append(n % 10) n = n // 10 digits = digits[::-1] return digits def get_luckies(n, d): agg = n * [False] for x in range(n): if d in to_digits(x): agg[x] = True else: for j in range(x): if agg[j] and agg[x - j]: agg[x] = True return agg def main(): maxn = 100 t = int(input()) for _ in range(t): q, d = map(int, input().split()) xs = list(map(int, input().split())) luckies = get_luckies(maxn, d) for x in xs: print('NO' if ((x < maxn) and not(luckies[x])) else 'YES') return None if __name__ == '__main__': main() ```
instruction
0
52,449
20
104,898
Yes
output
1
52,449
20
104,899
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nezzar's favorite digit among 1,…,9 is d. He calls a positive integer lucky if d occurs at least once in its decimal representation. Given q integers a_1,a_2,…,a_q, for each 1 ≀ i ≀ q Nezzar would like to know if a_i can be equal to a sum of several (one or more) lucky numbers. Input The first line contains a single integer t (1 ≀ t ≀ 9) β€” the number of test cases. The first line of each test case contains two integers q and d (1 ≀ q ≀ 10^4, 1 ≀ d ≀ 9). The second line of each test case contains q integers a_1,a_2,…,a_q (1 ≀ a_i ≀ 10^9). Output For each integer in each test case, print "YES" in a single line if a_i can be equal to a sum of lucky numbers. Otherwise, print "NO". You can print letters in any case (upper or lower). Example Input 2 3 7 24 25 27 10 7 51 52 53 54 55 56 57 58 59 60 Output YES NO YES YES YES NO YES YES YES YES YES YES NO Note In the first test case, 24 = 17 + 7, 27 itself is a lucky number, 25 cannot be equal to a sum of lucky numbers. Submitted Solution: ``` for i in range(int(input())): fl = list(map(int, input().split())) q,d = fl[0],fl[1] a = list(map(int, input().split())) last_digits = dict() for i in range(1,11): last_digits[i] = ((d%10)*(i%10))%10 # print(last_digits) # last_digits = {1:7,2:4,3:1,4:8,5:5,6:2,7:9,8:6,9:3,10:0} for num in a: # print('Num = ', num) g = 0 if num>d*10: print('YES') g = 1 else: if num%d==0: print("YES") g = 1 else: #num = 43 ld = num%10 #ld = 3 low_divisor = num//d #43//7 = 6 for i in range(1,low_divisor+1): # print('i = ', i) # print(last_digits[i]) if last_digits[i] == ld: print('YES') g = 1 break if g == 0: print('NO') ```
instruction
0
52,450
20
104,900
Yes
output
1
52,450
20
104,901
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nezzar's favorite digit among 1,…,9 is d. He calls a positive integer lucky if d occurs at least once in its decimal representation. Given q integers a_1,a_2,…,a_q, for each 1 ≀ i ≀ q Nezzar would like to know if a_i can be equal to a sum of several (one or more) lucky numbers. Input The first line contains a single integer t (1 ≀ t ≀ 9) β€” the number of test cases. The first line of each test case contains two integers q and d (1 ≀ q ≀ 10^4, 1 ≀ d ≀ 9). The second line of each test case contains q integers a_1,a_2,…,a_q (1 ≀ a_i ≀ 10^9). Output For each integer in each test case, print "YES" in a single line if a_i can be equal to a sum of lucky numbers. Otherwise, print "NO". You can print letters in any case (upper or lower). Example Input 2 3 7 24 25 27 10 7 51 52 53 54 55 56 57 58 59 60 Output YES NO YES YES YES NO YES YES YES YES YES YES NO Note In the first test case, 24 = 17 + 7, 27 itself is a lucky number, 25 cannot be equal to a sum of lucky numbers. Submitted Solution: ``` #Fast IO Libraries import os import sys from io import BytesIO, IOBase #Library for our use # import math from collections import Counter # from collections import defaultdict # from collections import deque # from bisect import bisect_left as bl, bisect_right as br # from itertools import accumulate,permutations as perm,combinations as comb # import heapq # from functools import reduce # from fractions import Fraction # import sys def main(): for _ in range(int(input())): n,d=Ilist() HashTable={} for i in range(1,11): mul=i*d HashTable[str(mul)[-1]]=mul for i in input().split(): if int(i)%d==0: print("YES") elif str(d) in i: print("YES") elif i[-1] in HashTable and int(i)>=HashTable[i[-1]]: print("YES") else: print("NO") # shortcut for functions def I(): return input() def Iint(): return int(input()) def Ilist(): return list(map(int, input().split())) # int list def Imap(): return map(int, input().split()) # int map def Plist(li, s=' '): print(s.join(map(str, li))) # non string list # Region fastio functions BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() ```
instruction
0
52,451
20
104,902
No
output
1
52,451
20
104,903
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nezzar's favorite digit among 1,…,9 is d. He calls a positive integer lucky if d occurs at least once in its decimal representation. Given q integers a_1,a_2,…,a_q, for each 1 ≀ i ≀ q Nezzar would like to know if a_i can be equal to a sum of several (one or more) lucky numbers. Input The first line contains a single integer t (1 ≀ t ≀ 9) β€” the number of test cases. The first line of each test case contains two integers q and d (1 ≀ q ≀ 10^4, 1 ≀ d ≀ 9). The second line of each test case contains q integers a_1,a_2,…,a_q (1 ≀ a_i ≀ 10^9). Output For each integer in each test case, print "YES" in a single line if a_i can be equal to a sum of lucky numbers. Otherwise, print "NO". You can print letters in any case (upper or lower). Example Input 2 3 7 24 25 27 10 7 51 52 53 54 55 56 57 58 59 60 Output YES NO YES YES YES NO YES YES YES YES YES YES NO Note In the first test case, 24 = 17 + 7, 27 itself is a lucky number, 25 cannot be equal to a sum of lucky numbers. Submitted Solution: ``` from collections import defaultdict for _ in range(int(input())): n,d=list(map(int,input().split())) l=input().split() c=0 if d==1: print('YES') else: for i in range(n): if str(d) in l[i]: print('YES') else: x=d j=1 f=0 y=int(l[i]) while(j*d<y): x=j*d if str(d) in str(abs(y-x)): f=1 break j+=1 if f==1: print('YES') else: print('NO') ```
instruction
0
52,452
20
104,904
No
output
1
52,452
20
104,905
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nezzar's favorite digit among 1,…,9 is d. He calls a positive integer lucky if d occurs at least once in its decimal representation. Given q integers a_1,a_2,…,a_q, for each 1 ≀ i ≀ q Nezzar would like to know if a_i can be equal to a sum of several (one or more) lucky numbers. Input The first line contains a single integer t (1 ≀ t ≀ 9) β€” the number of test cases. The first line of each test case contains two integers q and d (1 ≀ q ≀ 10^4, 1 ≀ d ≀ 9). The second line of each test case contains q integers a_1,a_2,…,a_q (1 ≀ a_i ≀ 10^9). Output For each integer in each test case, print "YES" in a single line if a_i can be equal to a sum of lucky numbers. Otherwise, print "NO". You can print letters in any case (upper or lower). Example Input 2 3 7 24 25 27 10 7 51 52 53 54 55 56 57 58 59 60 Output YES NO YES YES YES NO YES YES YES YES YES YES NO Note In the first test case, 24 = 17 + 7, 27 itself is a lucky number, 25 cannot be equal to a sum of lucky numbers. Submitted Solution: ``` t=int(input()) for i in range(t): q,d=map(int,input().split()) seq=list(map(int,input().split())) for j in seq: Q=j//q D=j//d TEN=j//10 count=0 for num_q in range(Q+1): for num_d in range(D+1): for num_ten in range(TEN+1): if num_q*q+num_d*d+num_ten*10==j: count+=1 break break break if count: print('YES') else: print('NO') ```
instruction
0
52,453
20
104,906
No
output
1
52,453
20
104,907
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Nezzar's favorite digit among 1,…,9 is d. He calls a positive integer lucky if d occurs at least once in its decimal representation. Given q integers a_1,a_2,…,a_q, for each 1 ≀ i ≀ q Nezzar would like to know if a_i can be equal to a sum of several (one or more) lucky numbers. Input The first line contains a single integer t (1 ≀ t ≀ 9) β€” the number of test cases. The first line of each test case contains two integers q and d (1 ≀ q ≀ 10^4, 1 ≀ d ≀ 9). The second line of each test case contains q integers a_1,a_2,…,a_q (1 ≀ a_i ≀ 10^9). Output For each integer in each test case, print "YES" in a single line if a_i can be equal to a sum of lucky numbers. Otherwise, print "NO". You can print letters in any case (upper or lower). Example Input 2 3 7 24 25 27 10 7 51 52 53 54 55 56 57 58 59 60 Output YES NO YES YES YES NO YES YES YES YES YES YES NO Note In the first test case, 24 = 17 + 7, 27 itself is a lucky number, 25 cannot be equal to a sum of lucky numbers. Submitted Solution: ``` # Problem: B. Nezzar and Lucky Number # Contest: Codeforces - Codeforces Round #698 (Div. 2) # URL: https://codeforces.com/contest/1478/problem/B # Memory Limit: 512 MB # Time Limit: 1000 ms # # KAPOOR'S from sys import stdin, stdout def INI(): return int(stdin.readline()) def INL(): return [int(_) for _ in stdin.readline().split()] def INS(): return stdin.readline() def MOD(): return pow(10,9)+7 def OPS(ans): stdout.write(str(ans)+"\n") def OPL(ans): [stdout.write(str(_)+" ") for _ in ans] stdout.write("\n") if __name__=="__main__": for _ in range(INI()): q,d=INL() X=INL() for _ in X: i=0 c=_ while 0<c: c=_ c-=10*(i) i+=1 # print(c) if c%d==0 and 0<c: OPS("YES") break else: OPS("NO") ```
instruction
0
52,454
20
104,908
No
output
1
52,454
20
104,909
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya likes horse racing very much. Horses numbered from l to r take part in the races. Petya wants to evaluate the probability of victory; for some reason, to do that he needs to know the amount of nearly lucky horses' numbers. A nearly lucky number is an integer number that has at least two lucky digits the distance between which does not exceed k. Petya learned from some of his mates from Lviv that lucky digits are digits 4 and 7. The distance between the digits is the absolute difference between their positions in the number of a horse. For example, if k = 2, then numbers 412395497, 404, 4070400000070004007 are nearly lucky and numbers 4, 4123954997, 4007000040070004007 are not. Petya prepared t intervals [li, ri] and invented number k, common for all of them. Your task is to find how many nearly happy numbers there are in each of these segments. Since the answers can be quite large, output them modulo 1000000007 (109 + 7). Input The first line contains two integers t and k (1 ≀ t, k ≀ 1000) β€” the number of segments and the distance between the numbers correspondingly. Next t lines contain pairs of integers li and ri (1 ≀ l ≀ r ≀ 101000). All numbers are given without the leading zeroes. Numbers in each line are separated by exactly one space character. Output Output t lines. In each line print one integer β€” the answer for the corresponding segment modulo 1000000007 (109 + 7). Examples Input 1 2 1 100 Output 4 Input 1 2 70 77 Output 2 Input 2 1 1 20 80 100 Output 0 0 Note In the first sample, the four nearly lucky numbers are 44, 47, 74, 77. In the second sample, only 74 and 77 are in the given segment. Submitted Solution: ``` N = 1016 dp = [[-1 for i in range (N)] for j in range(N)] MOD = 10 ** 9 + 7 def rec(pos, dist, anyDigit): global s, ls, k if pos == ls: return dist == 0 if anyDigit and dp[ls - pos - 1][dist] != -1: return dp[ls - pos - 1][dist] limit = 9 if anyDigit else int(s[pos]) ret = 0 for i in range(limit + 1): ndist = dist + (dist != 0) if i == 4 or i == 7: ndist = 0 if dist <= k else 1 ret += rec(pos + 1, ndist, anyDigit or (i == limit)) while ret >= MOD: ret -= MOD if anyDigit: dp[pos][dist] = ret return ret t, k = map(int, input().split()) for i in range(t): fr, to = map(int, input().split()) fr -= 1 s = str(to) ls = len(s) val = rec(0, k + 12, 0) s = str(fr) ls = len(s) val -= rec(0, k + 12, 0) val %= MOD print(val) ```
instruction
0
53,637
20
107,274
No
output
1
53,637
20
107,275
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Petya likes horse racing very much. Horses numbered from l to r take part in the races. Petya wants to evaluate the probability of victory; for some reason, to do that he needs to know the amount of nearly lucky horses' numbers. A nearly lucky number is an integer number that has at least two lucky digits the distance between which does not exceed k. Petya learned from some of his mates from Lviv that lucky digits are digits 4 and 7. The distance between the digits is the absolute difference between their positions in the number of a horse. For example, if k = 2, then numbers 412395497, 404, 4070400000070004007 are nearly lucky and numbers 4, 4123954997, 4007000040070004007 are not. Petya prepared t intervals [li, ri] and invented number k, common for all of them. Your task is to find how many nearly happy numbers there are in each of these segments. Since the answers can be quite large, output them modulo 1000000007 (109 + 7). Input The first line contains two integers t and k (1 ≀ t, k ≀ 1000) β€” the number of segments and the distance between the numbers correspondingly. Next t lines contain pairs of integers li and ri (1 ≀ l ≀ r ≀ 101000). All numbers are given without the leading zeroes. Numbers in each line are separated by exactly one space character. Output Output t lines. In each line print one integer β€” the answer for the corresponding segment modulo 1000000007 (109 + 7). Examples Input 1 2 1 100 Output 4 Input 1 2 70 77 Output 2 Input 2 1 1 20 80 100 Output 0 0 Note In the first sample, the four nearly lucky numbers are 44, 47, 74, 77. In the second sample, only 74 and 77 are in the given segment. Submitted Solution: ``` N = 1016 dp = [[-1 for i in range (N)] for j in range(N)] MOD = 10 ** 9 + 7 def rec(pos, dist, anyDigit): global s, ls if pos == ls: return dist == 0 if anyDigit and dp[ls - pos - 1][dist] != -1: return dp[ls - pos - 1][dist] limit = 9 if anyDigit else int(s[pos]) ret = 0 for i in range(limit + 1): ndist = dist + (dist != 0) if i == 4 or i == 7: ndist = 0 if ndist <= k else 1 ret += rec(pos + 1, ndist, anyDigit or i == limit) while ret >= MOD: ret -= MOD if anyDigit: dp[pos][dist] = ret return ret t, k = map(int, input().split()) for i in range(t): fr, to = map(int, input().split()) fr -= 1 s = str(to) ls = len(s) val = rec(0, k + 12, 0) s = str(fr) ls = len(s) val -= rec(0, k + 12, 0) val %= MOD print(val) ```
instruction
0
53,638
20
107,276
No
output
1
53,638
20
107,277
Provide tags and a correct Python 3 solution for this coding contest problem. Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before. It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-class android which is produced by a little-known company. His design is not perfect, his characteristics also could be better. So he is bullied by other androids. One of the popular pranks on Vasya is to force him to compare x^y with y^x. Other androids can do it in milliseconds while Vasya's memory is too small to store such big numbers. Please help Vasya! Write a fast program to compare x^y with y^x for Vasya, maybe then other androids will respect him. Input On the only line of input there are two integers x and y (1 ≀ x, y ≀ 10^{9}). Output If x^y < y^x, then print '<' (without quotes). If x^y > y^x, then print '>' (without quotes). If x^y = y^x, then print '=' (without quotes). Examples Input 5 8 Output &gt; Input 10 3 Output &lt; Input 6 6 Output = Note In the first example 5^8 = 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 = 390625, and 8^5 = 8 β‹… 8 β‹… 8 β‹… 8 β‹… 8 = 32768. So you should print '>'. In the second example 10^3 = 1000 < 3^{10} = 59049. In the third example 6^6 = 46656 = 6^6.
instruction
0
53,639
20
107,278
Tags: math Correct Solution: ``` x, y = map(int, input().split()) ans = '' if x < y: if x >= 3: ans = '>' elif x == 2: if y > 4: ans = '>' elif y==4: ans = '=' else: ans = '<' else: ans = '<' elif x > y: if y >= 3: ans = '<' elif y == 2: if x > 4: ans = '<' elif x == 4: ans = '=' else: ans = '>' else: ans = '>' else: ans = '=' print(ans) ```
output
1
53,639
20
107,279
Provide tags and a correct Python 3 solution for this coding contest problem. Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before. It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-class android which is produced by a little-known company. His design is not perfect, his characteristics also could be better. So he is bullied by other androids. One of the popular pranks on Vasya is to force him to compare x^y with y^x. Other androids can do it in milliseconds while Vasya's memory is too small to store such big numbers. Please help Vasya! Write a fast program to compare x^y with y^x for Vasya, maybe then other androids will respect him. Input On the only line of input there are two integers x and y (1 ≀ x, y ≀ 10^{9}). Output If x^y < y^x, then print '<' (without quotes). If x^y > y^x, then print '>' (without quotes). If x^y = y^x, then print '=' (without quotes). Examples Input 5 8 Output &gt; Input 10 3 Output &lt; Input 6 6 Output = Note In the first example 5^8 = 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 = 390625, and 8^5 = 8 β‹… 8 β‹… 8 β‹… 8 β‹… 8 = 32768. So you should print '>'. In the second example 10^3 = 1000 < 3^{10} = 59049. In the third example 6^6 = 46656 = 6^6.
instruction
0
53,640
20
107,280
Tags: math Correct Solution: ``` from math import * x, y = (int(n) for n in input().split()) print('>' if y * log(x) > x * log(y) else ('<' if y * log(x) < x * log(y) else '=')) ```
output
1
53,640
20
107,281
Provide tags and a correct Python 3 solution for this coding contest problem. Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before. It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-class android which is produced by a little-known company. His design is not perfect, his characteristics also could be better. So he is bullied by other androids. One of the popular pranks on Vasya is to force him to compare x^y with y^x. Other androids can do it in milliseconds while Vasya's memory is too small to store such big numbers. Please help Vasya! Write a fast program to compare x^y with y^x for Vasya, maybe then other androids will respect him. Input On the only line of input there are two integers x and y (1 ≀ x, y ≀ 10^{9}). Output If x^y < y^x, then print '<' (without quotes). If x^y > y^x, then print '>' (without quotes). If x^y = y^x, then print '=' (without quotes). Examples Input 5 8 Output &gt; Input 10 3 Output &lt; Input 6 6 Output = Note In the first example 5^8 = 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 = 390625, and 8^5 = 8 β‹… 8 β‹… 8 β‹… 8 β‹… 8 = 32768. So you should print '>'. In the second example 10^3 = 1000 < 3^{10} = 59049. In the third example 6^6 = 46656 = 6^6.
instruction
0
53,641
20
107,282
Tags: math Correct Solution: ``` x,y=input().split() x=int(x) y=int(y) if(x==y): print('=') elif((x==2 and y==4) or (x==4 and y==2)): print('=') elif(x==3 and y==2): print('>') elif(x==2 and y==3): print('<') elif(x==1): print('<') elif(y==1): print('>') elif(x>y): print('<') elif(y>x): print('>') ```
output
1
53,641
20
107,283
Provide tags and a correct Python 3 solution for this coding contest problem. Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before. It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-class android which is produced by a little-known company. His design is not perfect, his characteristics also could be better. So he is bullied by other androids. One of the popular pranks on Vasya is to force him to compare x^y with y^x. Other androids can do it in milliseconds while Vasya's memory is too small to store such big numbers. Please help Vasya! Write a fast program to compare x^y with y^x for Vasya, maybe then other androids will respect him. Input On the only line of input there are two integers x and y (1 ≀ x, y ≀ 10^{9}). Output If x^y < y^x, then print '<' (without quotes). If x^y > y^x, then print '>' (without quotes). If x^y = y^x, then print '=' (without quotes). Examples Input 5 8 Output &gt; Input 10 3 Output &lt; Input 6 6 Output = Note In the first example 5^8 = 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 = 390625, and 8^5 = 8 β‹… 8 β‹… 8 β‹… 8 β‹… 8 = 32768. So you should print '>'. In the second example 10^3 = 1000 < 3^{10} = 59049. In the third example 6^6 = 46656 = 6^6.
instruction
0
53,642
20
107,284
Tags: math Correct Solution: ``` x,y=input().split() x,y=[int(x),int(y)] if((x==4 and y==2) or (x==2 and y==4)): print("=") elif(x==y): print("=") elif(x>=3 and y>=3): if(x>y): print("<") else: print(">") elif(x<=3 and y<=3): if (x>y): print(">") else: print("<") elif(x==1 and y>1): print("<") elif(x>1 and y==1): print(">") elif(x<3 and y>3): print(">") elif(x>3 and y<3): print("<") ```
output
1
53,642
20
107,285
Provide tags and a correct Python 3 solution for this coding contest problem. Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before. It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-class android which is produced by a little-known company. His design is not perfect, his characteristics also could be better. So he is bullied by other androids. One of the popular pranks on Vasya is to force him to compare x^y with y^x. Other androids can do it in milliseconds while Vasya's memory is too small to store such big numbers. Please help Vasya! Write a fast program to compare x^y with y^x for Vasya, maybe then other androids will respect him. Input On the only line of input there are two integers x and y (1 ≀ x, y ≀ 10^{9}). Output If x^y < y^x, then print '<' (without quotes). If x^y > y^x, then print '>' (without quotes). If x^y = y^x, then print '=' (without quotes). Examples Input 5 8 Output &gt; Input 10 3 Output &lt; Input 6 6 Output = Note In the first example 5^8 = 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 = 390625, and 8^5 = 8 β‹… 8 β‹… 8 β‹… 8 β‹… 8 = 32768. So you should print '>'. In the second example 10^3 = 1000 < 3^{10} = 59049. In the third example 6^6 = 46656 = 6^6.
instruction
0
53,643
20
107,286
Tags: math Correct Solution: ``` from math import * x,y=map(int,input().split()) if(y*log(x)>x*log(y)): print('>') elif(y*log(x)<x*log(y)): print('<') else: print('=') ```
output
1
53,643
20
107,287
Provide tags and a correct Python 3 solution for this coding contest problem. Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before. It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-class android which is produced by a little-known company. His design is not perfect, his characteristics also could be better. So he is bullied by other androids. One of the popular pranks on Vasya is to force him to compare x^y with y^x. Other androids can do it in milliseconds while Vasya's memory is too small to store such big numbers. Please help Vasya! Write a fast program to compare x^y with y^x for Vasya, maybe then other androids will respect him. Input On the only line of input there are two integers x and y (1 ≀ x, y ≀ 10^{9}). Output If x^y < y^x, then print '<' (without quotes). If x^y > y^x, then print '>' (without quotes). If x^y = y^x, then print '=' (without quotes). Examples Input 5 8 Output &gt; Input 10 3 Output &lt; Input 6 6 Output = Note In the first example 5^8 = 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 = 390625, and 8^5 = 8 β‹… 8 β‹… 8 β‹… 8 β‹… 8 = 32768. So you should print '>'. In the second example 10^3 = 1000 < 3^{10} = 59049. In the third example 6^6 = 46656 = 6^6.
instruction
0
53,644
20
107,288
Tags: math Correct Solution: ``` # -*- coding: utf-8 -*- """ Created on Sat Jun 16 05:42:07 2018 @author: Arsanuos """ import math def main(): x, y = [int(t) for t in input().split()] if x == y and x == 1: print("=") elif x == 1: print("<") elif y == 1: print(">") elif y > x * math.log(y, x): print(">") elif y < x * math.log(y, x): print("<") else: print("=") if __name__ == "__main__": main() ```
output
1
53,644
20
107,289
Provide tags and a correct Python 3 solution for this coding contest problem. Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before. It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-class android which is produced by a little-known company. His design is not perfect, his characteristics also could be better. So he is bullied by other androids. One of the popular pranks on Vasya is to force him to compare x^y with y^x. Other androids can do it in milliseconds while Vasya's memory is too small to store such big numbers. Please help Vasya! Write a fast program to compare x^y with y^x for Vasya, maybe then other androids will respect him. Input On the only line of input there are two integers x and y (1 ≀ x, y ≀ 10^{9}). Output If x^y < y^x, then print '<' (without quotes). If x^y > y^x, then print '>' (without quotes). If x^y = y^x, then print '=' (without quotes). Examples Input 5 8 Output &gt; Input 10 3 Output &lt; Input 6 6 Output = Note In the first example 5^8 = 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 = 390625, and 8^5 = 8 β‹… 8 β‹… 8 β‹… 8 β‹… 8 = 32768. So you should print '>'. In the second example 10^3 = 1000 < 3^{10} = 59049. In the third example 6^6 = 46656 = 6^6.
instruction
0
53,645
20
107,290
Tags: math Correct Solution: ``` x, y = map(int, input().split()) if x == y or (x, y) == (2, 4) or (x, y) == (4, 2): print('=') exit(0) if x == 1: print('<') exit(0) if y == 1: print('>') exit(0) if x == 2: if y == 3: print('<') exit(0) print('>') exit(0) if y == 2: if x == 3: print('>') exit(0) print('<') exit(0) if x > y: print('<') else: print('>') ```
output
1
53,645
20
107,291
Provide tags and a correct Python 3 solution for this coding contest problem. Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before. It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-class android which is produced by a little-known company. His design is not perfect, his characteristics also could be better. So he is bullied by other androids. One of the popular pranks on Vasya is to force him to compare x^y with y^x. Other androids can do it in milliseconds while Vasya's memory is too small to store such big numbers. Please help Vasya! Write a fast program to compare x^y with y^x for Vasya, maybe then other androids will respect him. Input On the only line of input there are two integers x and y (1 ≀ x, y ≀ 10^{9}). Output If x^y < y^x, then print '<' (without quotes). If x^y > y^x, then print '>' (without quotes). If x^y = y^x, then print '=' (without quotes). Examples Input 5 8 Output &gt; Input 10 3 Output &lt; Input 6 6 Output = Note In the first example 5^8 = 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 = 390625, and 8^5 = 8 β‹… 8 β‹… 8 β‹… 8 β‹… 8 = 32768. So you should print '>'. In the second example 10^3 = 1000 < 3^{10} = 59049. In the third example 6^6 = 46656 = 6^6.
instruction
0
53,646
20
107,292
Tags: math Correct Solution: ``` a = input() b = a.split() num1 = int(b[0]) num2 = int(b[1]) if num1 == num2: print('=') raise SystemExit(0) if num1 > 2 and num2 > 2: if num1 > num2: print('<') raise SystemExit(0) else: print('>') raise SystemExit(0) else: if num1 == 1: print('<') raise SystemExit(0) elif num2 == 1: print('>') raise SystemExit(0) else: if num1 + num2 <= 5: if num1 < num2: print('<') raise SystemExit(0) else: print('>') raise SystemExit(0) elif num1 + num2 == 6: print('=') raise SystemExit(0) else: if num1 > num2: print('<') raise SystemExit(0) else: print('>') raise SystemExit(0) ```
output
1
53,646
20
107,293
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before. It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-class android which is produced by a little-known company. His design is not perfect, his characteristics also could be better. So he is bullied by other androids. One of the popular pranks on Vasya is to force him to compare x^y with y^x. Other androids can do it in milliseconds while Vasya's memory is too small to store such big numbers. Please help Vasya! Write a fast program to compare x^y with y^x for Vasya, maybe then other androids will respect him. Input On the only line of input there are two integers x and y (1 ≀ x, y ≀ 10^{9}). Output If x^y < y^x, then print '<' (without quotes). If x^y > y^x, then print '>' (without quotes). If x^y = y^x, then print '=' (without quotes). Examples Input 5 8 Output &gt; Input 10 3 Output &lt; Input 6 6 Output = Note In the first example 5^8 = 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 β‹… 5 = 390625, and 8^5 = 8 β‹… 8 β‹… 8 β‹… 8 β‹… 8 = 32768. So you should print '>'. In the second example 10^3 = 1000 < 3^{10} = 59049. In the third example 6^6 = 46656 = 6^6. Submitted Solution: ``` # https://codeforces.com/contest/987/problem/B from math import log x,y = map(int, input().split()) a,b = y*log(x), x*log(y) print('>' if a>b else '<' if a<b else '=') ```
instruction
0
53,647
20
107,294
Yes
output
1
53,647
20
107,295
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After spending long long time, you had gotten tired of computer programming. Instead you were inter- ested in electronic construction. As your first work, you built a simple calculator. It can handle positive integers of up to four decimal digits, and perform addition, subtraction and multiplication of numbers. You didn’t implement division just because it was so complicated. Although the calculator almost worked well, you noticed that it displays unexpected results in several cases. So, you decided to try its simulation by a computer program in order to figure out the cause of unexpected behaviors. The specification of the calculator you built is as follows. There are three registers on the calculator. The register R1 stores the value of the operation result of the latest operation; the register R2 stores the new input value; and the register R3 stores the input operator. At the beginning, both R1 and R2 hold zero, and R3 holds a null operator. The calculator has keys for decimal digits from β€˜0’ to β€˜9’ and operators β€˜+’, β€˜-’, β€˜Γ—β€™ and β€˜=’. The four operators indicate addition, subtraction, multiplication and conclusion, respectively. When a digit key is pressed, R2 is multiplied by ten, and then added by the pressed digit (as a number). When β€˜+’, β€˜-’ or β€˜Γ—β€™ is pressed, the calculator first applies the binary operator held in R3 to the values in R1 and R2 and updates R1 with the result of the operation. Suppose R1 has 10, R2 has 3, and R3 has β€˜-’ (subtraction operator), R1 is updated with 7 ( = 10 - 3). If R3 holds a null operator, the result will be equal to the value of R2. After R1 is updated, R2 is cleared to zero and R3 is set to the operator which the user entered. β€˜=’ indicates termination of a computation. So, when β€˜=’ is pressed, the calculator applies the operator held in R3 in the same manner as the other operators, and displays the final result to the user. After the final result is displayed, R3 is reinitialized with a null operator. The calculator cannot handle numbers with five or more decimal digits. Because of that, if the intermediate computation produces a value less than 0 (i.e., a negative number) or greater than 9999, the calculator displays β€œE” that stands for error, and ignores the rest of the user input until β€˜=’ is pressed. Your task is to write a program to simulate the simple calculator. Input The input consists of multiple test cases. Each line of the input specifies one test case, indicating the order of key strokes which a user entered. The input consists only decimal digits (from β€˜0’ to β€˜9’) and valid operators β€˜+’, β€˜-’, β€˜*’ and β€˜=’ where β€˜*’ stands for β€˜Γ—β€™. You may assume that β€˜=’ occurs only at the end of each line, and no case contains more than 80 key strokes. The end of input is indicated by EOF. Output For each test case, output one line which contains the result of simulation. Example Input 1+2+3+4+5+6+7+8+9+10= 1000-500-250-125= 1*2*3*4*5*6= 5000*5000= 10-100= 100*100= 10000= Output 55 125 720 E E E E Submitted Solution: ``` while 1: try:f=input()[:-1] except:break print(eval(f) if 0<=eval(f)<10000 else 'E') ```
instruction
0
53,875
20
107,750
No
output
1
53,875
20
107,751
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. After spending long long time, you had gotten tired of computer programming. Instead you were inter- ested in electronic construction. As your first work, you built a simple calculator. It can handle positive integers of up to four decimal digits, and perform addition, subtraction and multiplication of numbers. You didn’t implement division just because it was so complicated. Although the calculator almost worked well, you noticed that it displays unexpected results in several cases. So, you decided to try its simulation by a computer program in order to figure out the cause of unexpected behaviors. The specification of the calculator you built is as follows. There are three registers on the calculator. The register R1 stores the value of the operation result of the latest operation; the register R2 stores the new input value; and the register R3 stores the input operator. At the beginning, both R1 and R2 hold zero, and R3 holds a null operator. The calculator has keys for decimal digits from β€˜0’ to β€˜9’ and operators β€˜+’, β€˜-’, β€˜Γ—β€™ and β€˜=’. The four operators indicate addition, subtraction, multiplication and conclusion, respectively. When a digit key is pressed, R2 is multiplied by ten, and then added by the pressed digit (as a number). When β€˜+’, β€˜-’ or β€˜Γ—β€™ is pressed, the calculator first applies the binary operator held in R3 to the values in R1 and R2 and updates R1 with the result of the operation. Suppose R1 has 10, R2 has 3, and R3 has β€˜-’ (subtraction operator), R1 is updated with 7 ( = 10 - 3). If R3 holds a null operator, the result will be equal to the value of R2. After R1 is updated, R2 is cleared to zero and R3 is set to the operator which the user entered. β€˜=’ indicates termination of a computation. So, when β€˜=’ is pressed, the calculator applies the operator held in R3 in the same manner as the other operators, and displays the final result to the user. After the final result is displayed, R3 is reinitialized with a null operator. The calculator cannot handle numbers with five or more decimal digits. Because of that, if the intermediate computation produces a value less than 0 (i.e., a negative number) or greater than 9999, the calculator displays β€œE” that stands for error, and ignores the rest of the user input until β€˜=’ is pressed. Your task is to write a program to simulate the simple calculator. Input The input consists of multiple test cases. Each line of the input specifies one test case, indicating the order of key strokes which a user entered. The input consists only decimal digits (from β€˜0’ to β€˜9’) and valid operators β€˜+’, β€˜-’, β€˜*’ and β€˜=’ where β€˜*’ stands for β€˜Γ—β€™. You may assume that β€˜=’ occurs only at the end of each line, and no case contains more than 80 key strokes. The end of input is indicated by EOF. Output For each test case, output one line which contains the result of simulation. Example Input 1+2+3+4+5+6+7+8+9+10= 1000-500-250-125= 1*2*3*4*5*6= 5000*5000= 10-100= 100*100= 10000= Output 55 125 720 E E E E Submitted Solution: ``` import sys for l in sys.stdin: f,_=l.split('=') print(eval(f) if 0<=eval(f)<10000 else 'E') ```
instruction
0
53,876
20
107,752
No
output
1
53,876
20
107,753
Provide tags and a correct Python 3 solution for this coding contest problem. A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one. Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one. Input The first line contains two space-separated integers n and k (2 ≀ n ≀ 104, 2 ≀ k ≀ n) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of n digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits. Output On the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one. Examples Input 6 5 898196 Output 4 888188 Input 3 2 533 Output 0 533 Input 10 6 0001112223 Output 3 0000002223 Note In the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188". The lexicographical comparison of strings is performed by the < operator in modern programming languages. The string x is lexicographically smaller than the string y, if there exists such i (1 ≀ i ≀ n), that xi < yi, and for any j (1 ≀ j < i) xj = yj. The strings compared in this problem will always have the length n.
instruction
0
54,002
20
108,004
Tags: brute force, greedy, sortings, strings Correct Solution: ``` #------------------------template--------------------------# import os import sys from math import * from collections import * from fractions import * from bisect import * from heapq import* from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ALPHA='abcdefghijklmnopqrstuvwxyz' M=10**9+7 EPS=1e-6 def value():return tuple(map(int,input().split())) def array():return [int(i) for i in input().split()] def Int():return int(input()) def Str():return input() def arrayS():return [i for i in input().split()] #-------------------------code---------------------------# # vsInput() def fun(a): if(a[1]==0): return a else: return (a[0],a[1],-a[2]) return a def operate(x): ans=list(s) c=[] for i in range(n): c.append((abs(x-int(s[i])),int(x>int(s[i])),i)) c.sort(key=fun) cost=0 # print(c) for i in range(k): cost+=c[i][0] ans[c[i][-1]]=str(x) return (cost,''.join(ans)) n,k=value() s=input() minCost=inf ans=s # operate(3) for i in range(10): cost,t=operate(i) if(cost<minCost): minCost=cost ans=t elif(cost==minCost): ans=min(ans,t) print(minCost) print(ans) ```
output
1
54,002
20
108,005
Provide tags and a correct Python 3 solution for this coding contest problem. A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one. Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one. Input The first line contains two space-separated integers n and k (2 ≀ n ≀ 104, 2 ≀ k ≀ n) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of n digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits. Output On the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one. Examples Input 6 5 898196 Output 4 888188 Input 3 2 533 Output 0 533 Input 10 6 0001112223 Output 3 0000002223 Note In the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188". The lexicographical comparison of strings is performed by the < operator in modern programming languages. The string x is lexicographically smaller than the string y, if there exists such i (1 ≀ i ≀ n), that xi < yi, and for any j (1 ≀ j < i) xj = yj. The strings compared in this problem will always have the length n.
instruction
0
54,003
20
108,006
Tags: brute force, greedy, sortings, strings Correct Solution: ``` n,k = map(int,input().split()) s = list(map(int, input())) e = list(enumerate(s)) min_cost = 9*n a=[9]*n for j in range(10): r = s[:] cost = 0 for x, y in sorted(e, key=lambda t : (abs(t[1] - j), -t[1], t[0]*(-1)**(j > t[1]) ))[:k]: r[x]=j cost += abs(y-j) if cost < min_cost : min_cost = cost a = r if min_cost == cost: a = min(a,r) print(min_cost) print (''.join(map(str,a))) ```
output
1
54,003
20
108,007
Provide tags and a correct Python 3 solution for this coding contest problem. A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one. Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one. Input The first line contains two space-separated integers n and k (2 ≀ n ≀ 104, 2 ≀ k ≀ n) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of n digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits. Output On the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one. Examples Input 6 5 898196 Output 4 888188 Input 3 2 533 Output 0 533 Input 10 6 0001112223 Output 3 0000002223 Note In the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188". The lexicographical comparison of strings is performed by the < operator in modern programming languages. The string x is lexicographically smaller than the string y, if there exists such i (1 ≀ i ≀ n), that xi < yi, and for any j (1 ≀ j < i) xj = yj. The strings compared in this problem will always have the length n.
instruction
0
54,004
20
108,008
Tags: brute force, greedy, sortings, strings Correct Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') INF = 10 ** 18 MOD = 10**9+7 from fractions import Fraction import heapq as hp Ri = lambda : [int(x) for x in sys.stdin.readline().split()] ri = lambda : sys.stdin.readline().strip() n,k = Ri() s = ri() maxx = 10**18 totans = "" for i in range(10): h = [];hp.heapify(h) for j in s: if len(h) < k: hp.heappush(h, -abs(int(j) - i)) else: hp.heappush(h, -abs(int(j) - i)) hp.heappop(h) summ = 0 for j in h: summ+=-j se= {} for j in h: se[j] = se.get(j, 0)+1 tans = [0]*len(s) for j in range(len(s)): if int(s[j]) >= i and -abs(int(s[j]) - i) in se: se[-abs(int(s[j]) - i)]-=1 if se[-abs(int(s[j]) - i)] == 0: se.pop(-abs(int(s[j])- i)) tans[j] = chr(ord('0') + i) for j in range(len(s)-1,-1,-1): if int(s[j]) < i and -abs(int(s[j]) - i) in se: se[-abs(int(s[j]) - i)]-=1 if se[-abs(int(s[j]) - i)] == 0: se.pop(-abs(int(s[j])- i)) tans[j] = chr(ord('0') + i) for j in range(len(s)): if tans[j] == 0: tans[j] = s[j] # if i == 8: print(tans) if summ <= maxx: if summ < maxx: maxx = summ totans = "".join(tans) elif summ == maxx and "".join(tans) < totans: totans = "".join(tans) print(maxx) print(totans) ```
output
1
54,004
20
108,009
Provide tags and a correct Python 3 solution for this coding contest problem. A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one. Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one. Input The first line contains two space-separated integers n and k (2 ≀ n ≀ 104, 2 ≀ k ≀ n) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of n digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits. Output On the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one. Examples Input 6 5 898196 Output 4 888188 Input 3 2 533 Output 0 533 Input 10 6 0001112223 Output 3 0000002223 Note In the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188". The lexicographical comparison of strings is performed by the < operator in modern programming languages. The string x is lexicographically smaller than the string y, if there exists such i (1 ≀ i ≀ n), that xi < yi, and for any j (1 ≀ j < i) xj = yj. The strings compared in this problem will always have the length n.
instruction
0
54,005
20
108,010
Tags: brute force, greedy, sortings, strings Correct Solution: ``` n,k=map(int,input().split()) s=list(map(int,input())) e=list(enumerate(s)) min_cost=9*n a=[9]*n for j in range(10): r=s[:] cost=0 for x,y in sorted(e,key=lambda t: (abs(t[1]-j),-t[1],t[0]*(-1)**(j > t[1]) ))[:k]: r[x]=j cost += abs(y-j) if cost < min_cost : min_cost = cost a = r elif min_cost == cost: a = min(a,r) print(min_cost) print (''.join(map(str,a))) ```
output
1
54,005
20
108,011
Provide tags and a correct Python 3 solution for this coding contest problem. A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one. Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one. Input The first line contains two space-separated integers n and k (2 ≀ n ≀ 104, 2 ≀ k ≀ n) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of n digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits. Output On the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one. Examples Input 6 5 898196 Output 4 888188 Input 3 2 533 Output 0 533 Input 10 6 0001112223 Output 3 0000002223 Note In the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188". The lexicographical comparison of strings is performed by the < operator in modern programming languages. The string x is lexicographically smaller than the string y, if there exists such i (1 ≀ i ≀ n), that xi < yi, and for any j (1 ≀ j < i) xj = yj. The strings compared in this problem will always have the length n.
instruction
0
54,006
20
108,012
Tags: brute force, greedy, sortings, strings Correct Solution: ``` '''input 8 4 22294777 ''' from sys import stdin def get_freq(string): freq = [0] * 10 for i in string: freq[ord(i) - ord('0')] += 1 return freq def print_string(cstring, marr): aux = [] for mark in marr: string = cstring[:] num = str(mark) require = k - freq[mark] diff = 1 n1 = -1 n2 = -1 while require > 0: if mark - diff >= 0: n2 = mark - diff else: n2 = float('inf') if mark + diff <= 9: n1 = mark + diff else: n1 = float('inf') for i in range(len(string)): if require == 0: break if string[i] == str(n1): string[i] = num require -= 1 for i in range(len(string) - 1, -1, -1): if require == 0: break if string[i] == str(n2): string[i] = num require -= 1 diff += 1 aux.append(''.join(string)) aux.sort() print(aux[0]) # main starts n, k = list(map(int, stdin.readline().split())) string = list(stdin.readline().strip()) freq = get_freq(string) ans = float('inf') mark = -1 for i in range(0, 10): if freq[i] >= k: print(0) print(''.join(string)) exit() else: require = k - freq[i] diff = 1 cost = 0 while require > 0 and diff < 10: num = i + diff if num <= 9: if freq[num] >= require and require > 0: cost += require * diff require = 0 else: if require > 0: cost += freq[num] * (diff) require -= freq[num] else: pass num = i - diff if num >=0: if freq[num] >= require and require > 0: cost += require * diff require = 0 else: if require > 0: cost += freq[num] * (diff) require -= freq[num] else: pass diff += 1 if ans > cost: ans = cost mark = [i] elif ans == cost: mark.append(i) # print(i, cost) # if ans == 174: # print(mark) print(ans) print_string(string, mark) ```
output
1
54,006
20
108,013
Provide tags and a correct Python 3 solution for this coding contest problem. A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one. Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one. Input The first line contains two space-separated integers n and k (2 ≀ n ≀ 104, 2 ≀ k ≀ n) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of n digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits. Output On the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one. Examples Input 6 5 898196 Output 4 888188 Input 3 2 533 Output 0 533 Input 10 6 0001112223 Output 3 0000002223 Note In the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188". The lexicographical comparison of strings is performed by the < operator in modern programming languages. The string x is lexicographically smaller than the string y, if there exists such i (1 ≀ i ≀ n), that xi < yi, and for any j (1 ≀ j < i) xj = yj. The strings compared in this problem will always have the length n.
instruction
0
54,007
20
108,014
Tags: brute force, greedy, sortings, strings Correct Solution: ``` import os,io from sys import stdout import collections # import random # import math # from operator import itemgetter input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # from collections import Counter # from decimal import Decimal # import heapq # from functools import lru_cache import sys # import threading # sys.setrecursionlimit(10**6) # threading.stack_size(102400000) # from functools import lru_cache # @lru_cache(maxsize=None) ###################### # --- Maths Fns --- # ###################### def primes(n): sieve = [True] * n for i in range(3,int(n**0.5)+1,2): if sieve[i]: sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1) return [2] + [i for i in range(3,n,2) if sieve[i]] def binomial_coefficient(n, k): if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: return 0 def powerOfK(k, max): if k == 1: return [1] if k == -1: return [-1, 1] result = [] n = 1 while n <= max: result.append(n) n *= k return result def divisors(n): i = 1 result = [] while i*i <= n: if n%i == 0: if n/i == i: result.append(i) else: result.append(i) result.append(n/i) i+=1 return result # @lru_cache(maxsize=None) def digitsSum(n): if n == 0: return 0 r = 0 while n > 0: r += n % 10 n //= 10 return r ###################### # ---- GRID Fns ---- # ###################### def isValid(i, j, n, m): return i >= 0 and i < n and j >= 0 and j < m def print_grid(grid): for line in grid: print(" ".join(map(str,line))) ###################### # ---- MISC Fns ---- # ###################### def kadane(a,size): max_so_far = 0 max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if (max_so_far < max_ending_here): max_so_far = max_ending_here if max_ending_here < 0: max_ending_here = 0 return max_so_far def prefixSum(arr): for i in range(1, len(arr)): arr[i] = arr[i] + arr[i-1] return arr def ceil(n, d): if n % d == 0: return n // d else: return (n // d) + 1 # INPUTS -------------------------- # s = input().decode('utf-8').strip() # n = int(input()) # l = list(map(int, input().split())) # t = int(input()) # for _ in range(t): # for _ in range(t): class Entry: def __init__(self, index, diff, value, to): self.index = index self.diff = diff self.value = value self.to = to def __lt__(self, other): if self.diff < other.diff: return True elif self.diff == other.diff: if self.value > other.value: return True elif self.value < other.value: return False else: #self.value == other.value: if self.value > self.to: return self.index < other.index else: return self.index > other.index else: return False def __repr__(self): return "{} - {} - {}".format(self.index, self.diff, self.value) n, k = list(map(int, input().split())) s = list(map(int, list(input().decode('utf-8').strip()))) from collections import Counter c = Counter(s) ans = [] for i, v in c.items(): if v >= k: print(0) print("".join(list(map(str, s)))) exit() import heapq import math bcost = math.inf possible = [] for i in range(0, 10): #print(i, '-------', "", " ") heap = [] for index, e in enumerate(s): diff = int(abs(e-i)) entry = Entry(index, diff, e, i) heapq.heappush(heap, entry) cnt = k r = s[:] cost = 0 while cnt > 0: if len(heap): p = heapq.heappop(heap) r[p.index] = i cost += p.diff cnt -= 1 else: break if cnt == 0: if cost < bcost: bcost = cost possible = ["".join(list(map(str, r)))] elif cost == bcost: possible.append("".join(list(map(str, r)))) print(bcost) possible = sorted(possible) print(possible[0]) ```
output
1
54,007
20
108,015
Provide tags and a correct Python 3 solution for this coding contest problem. A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one. Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one. Input The first line contains two space-separated integers n and k (2 ≀ n ≀ 104, 2 ≀ k ≀ n) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of n digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits. Output On the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one. Examples Input 6 5 898196 Output 4 888188 Input 3 2 533 Output 0 533 Input 10 6 0001112223 Output 3 0000002223 Note In the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188". The lexicographical comparison of strings is performed by the < operator in modern programming languages. The string x is lexicographically smaller than the string y, if there exists such i (1 ≀ i ≀ n), that xi < yi, and for any j (1 ≀ j < i) xj = yj. The strings compared in this problem will always have the length n.
instruction
0
54,008
20
108,016
Tags: brute force, greedy, sortings, strings Correct Solution: ``` """ Author - Satwik Tiwari . 18th Oct , 2020 - Sunday """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import BytesIO, IOBase # from itertools import * from heapq import * from math import gcd, factorial,floor,ceil from copy import deepcopy from collections import deque # from collections import Counter as counter # Counter(list) return a dict with {key: count} # from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)] # from itertools import permutations as permutate from bisect import bisect_left as bl from bisect import bisect_right as br from bisect import bisect #============================================================================================== #fast I/O region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # inp = lambda: sys.stdin.readline().rstrip("\r\n") #=============================================================================================== ### START ITERATE RECURSION ### from types import GeneratorType def iterative(f, stack=[]): def wrapped_func(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) continue stack.pop() if not stack: break to = stack[-1].send(to) return to return wrapped_func #### END ITERATE RECURSION #### #=============================================================================================== #some shortcuts mod = 10**9+7 def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input def out(var): sys.stdout.write(str(var)) #for fast output, always take string def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) # def graph(vertex): return [[] for i in range(0,vertex+1)] def zerolist(n): return [0]*n def nextline(): out("\n") #as stdout.write always print sring. def testcase(t): for pp in range(t): solve(pp) def printlist(a) : for p in range(0,len(a)): out(str(a[p]) + ' ') def google(p): print('Case #'+str(p)+': ',end='') def lcm(a,b): return (a*b)//gcd(a,b) def power(x, y, p) : res = 1 # Initialize result x = x % p # Update x if it is more , than or equal to p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : # If y is odd, multiply, x with result res = (res * x) % p y = y >> 1 # y = y/2 x = (x * x) % p return res def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1))) def isPrime(n) : if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True inf = pow(10,6) #=============================================================================================== # code here ;)) def bucketsort(order, seq): buckets = [0] * (max(seq) + 1) for x in seq: buckets[x] += 1 for i in range(len(buckets) - 1): buckets[i + 1] += buckets[i] new_order = [-1] * len(seq) for i in reversed(order): x = seq[i] idx = buckets[x] = buckets[x] - 1 new_order[idx] = i return new_order def ordersort(order, seq, reverse=False): bit = max(seq).bit_length() >> 1 mask = (1 << bit) - 1 order = bucketsort(order, [x & mask for x in seq]) order = bucketsort(order, [x >> bit for x in seq]) if reverse: order.reverse() return order def long_ordersort(order, seq): order = ordersort(order, [int(i & 0x7fffffff) for i in seq]) return ordersort(order, [int(i >> 31) for i in seq]) def multikey_ordersort(order, *seqs, sort=ordersort): for i in reversed(range(len(seqs))): order = sort(order, seqs[i]) return order def solve(case): n,k = sep() s = list(inp()) for i in range(n): s[i] = int(s[i]) ans = inf out = deepcopy(s) for i in range(10): notsame = [] cnt = 0 for j in range(n): if(s[j] != i): notsame.append((s[j],j)) else: cnt+=1 if(cnt>=k): ans = min(ans,0) out = deepcopy(s) else: val = [] ind = [] less = [] for j in range(len(notsame)): val.append(abs(notsame[j][0] - i)) if(s[notsame[j][1]]>i): less.append(True) else: less.append(False) ind.append(notsame[j][1] if less[-1] else inf+n - notsame[j][1]) indexes = multikey_ordersort(range(len(val)),val,ind) les = [] new = [] for j in range(len(indexes)): new.append((val[indexes[j]],ind[indexes[j]])) les.append(less[indexes[j]]) temp = 0 for j in range(k-cnt): temp+=new[j][0] if(temp<ans): ans = temp out = deepcopy(s) for j in range(k-cnt): out[new[j][1] if les[j] else inf+n - new[j][1]] = i # alsopos = deepcopy(s) # for j in range(len(ind)): # ind[j] = n - ind[j] # # print(len(val),len(ind)) # indexes = multikey_ordersort(range(len(ind)),val,ind) # # indexes = [i for i in range(len(ind))] # new = [] # for j in range(len(indexes)): # new.append((val[indexes[j]],ind[indexes[j]])) # # new = sorted(new) # for j in range(k-cnt): # alsopos[n - new[j][1]] = i # if(out>alsopos): # out = deepcopy(alsopos) elif(temp == ans): also = deepcopy(s) for j in range(k-cnt): also[new[j][1] if les[j] else inf+n - new[j][1]] = i if(also<out): out = deepcopy(also) # print(i,ans,out) print(ans) print(''.join(str(out[i]) for i in range(n))) testcase(1) # testcase(int(inp())) ```
output
1
54,008
20
108,017
Provide tags and a correct Python 3 solution for this coding contest problem. A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one. Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one. Input The first line contains two space-separated integers n and k (2 ≀ n ≀ 104, 2 ≀ k ≀ n) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of n digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits. Output On the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one. Examples Input 6 5 898196 Output 4 888188 Input 3 2 533 Output 0 533 Input 10 6 0001112223 Output 3 0000002223 Note In the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188". The lexicographical comparison of strings is performed by the < operator in modern programming languages. The string x is lexicographically smaller than the string y, if there exists such i (1 ≀ i ≀ n), that xi < yi, and for any j (1 ≀ j < i) xj = yj. The strings compared in this problem will always have the length n.
instruction
0
54,009
20
108,018
Tags: brute force, greedy, sortings, strings Correct Solution: ``` n, k = map(int, input().split()) p = {i: 0 for i in '0123456789'} t, s = input(), 10 * n for i in t: p[i] += 1 p = [p[i] for i in '0123456789'] for i in range(0, 10): a, d, b = p[i], 1, 0 while a < k and d < 10: j = i + d if j < 10: if a + p[j] > k: b += d * (k - a) break b += d * p[j] a += p[j] j = i - d if j >= 0: if a + p[j] > k: b += d * (k - a) break b += d * p[j] a += p[j] d += 1 if b < s: s, u = b, [i] elif b == s: u.append(i) def f(t, v): global p, k a, d, i = p[v], 1, str(v) while a < k and d < 10: j = v + d if j < 10: if a + p[j] > k: if a == k: break h, j = k - a, str(j) for x in range(n): if t[x] == j: if h == 1: t = t[: x + 1].replace(j, i) + t[x + 1: ] break h -= 1 break a += p[j] t = t.replace(str(j), i) j = v - d if j >= 0: if a + p[j] > k: if a + p[j] == k: break h, j = k - a, str(j) for x in range(n - 1, -1, -1): if t[x] == j: if h == 1: t = t[: x] + t[x: ].replace(j, i) break h -= 1 break a += p[j] t = t.replace(str(j), i) d += 1 return t print(s) print(min(f(t, v) for v in u)) ```
output
1
54,009
20
108,019
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one. Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one. Input The first line contains two space-separated integers n and k (2 ≀ n ≀ 104, 2 ≀ k ≀ n) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of n digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits. Output On the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one. Examples Input 6 5 898196 Output 4 888188 Input 3 2 533 Output 0 533 Input 10 6 0001112223 Output 3 0000002223 Note In the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188". The lexicographical comparison of strings is performed by the < operator in modern programming languages. The string x is lexicographically smaller than the string y, if there exists such i (1 ≀ i ≀ n), that xi < yi, and for any j (1 ≀ j < i) xj = yj. The strings compared in this problem will always have the length n. Submitted Solution: ``` def stream(digit): o = ord(digit) for delta in range(1, 10): if o + delta <= ord('9'): yield chr(o + delta), delta if o - delta >= ord('0'): yield chr(o - delta), delta import collections n, k = map(int, input().split()) s = input() if any(v >= k for v in collections.Counter(s).values()): print(0, s, sep = '\n') exit(0) cost, string = int(1e9), s for digit in '0123456789': c = collections.Counter(s) current_cost = 0 current_string = s for other, delta in stream(digit): if c[other] >= k - c[digit]: if other < digit: current_string = current_string[::-1] current_string = current_string.replace(other, digit, k - c[digit]) if other < digit: current_string = current_string[::-1] current_cost += (k - c[digit]) * delta break else: current_string = current_string.replace(other, digit) current_cost += c[other] * delta c[digit] += c[other] if current_cost < cost or (current_cost == cost and current_string < string): cost = current_cost string = current_string print(cost, string, sep = '\n') # Made By Mostafa_Khaled ```
instruction
0
54,010
20
108,020
Yes
output
1
54,010
20
108,021
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one. Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one. Input The first line contains two space-separated integers n and k (2 ≀ n ≀ 104, 2 ≀ k ≀ n) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of n digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits. Output On the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one. Examples Input 6 5 898196 Output 4 888188 Input 3 2 533 Output 0 533 Input 10 6 0001112223 Output 3 0000002223 Note In the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188". The lexicographical comparison of strings is performed by the < operator in modern programming languages. The string x is lexicographically smaller than the string y, if there exists such i (1 ≀ i ≀ n), that xi < yi, and for any j (1 ≀ j < i) xj = yj. The strings compared in this problem will always have the length n. Submitted Solution: ``` n,k=map(int,input().split()) s=input() Cnt=[0]*10 for item in s: Cnt[int(item)]+=1 Ans=[] H=[] for i in range(0,10): S=list(map(int,s)) e=Cnt[i] j=1 C=[i] while(e<k): if(i+j<10): e+=Cnt[i+j] C.append(i+j) if(i-j>=0 and e<k): e+=Cnt[i-j] C.append(i-j) j+=1 cnt=0 cost=0 for item in C: if(cnt==k): break if(item>=i): for j in range(len(s)): if(S[j]==item): S[j]=i cnt+=1 cost+=abs(i-item) if(cnt==k): break else: for j in range(len(s)-1,-1,-1): if(S[j]==item): S[j]=i cnt+=1 cost+=abs(i-item) if(cnt==k): break H.append((cost,tuple(S))) H=min(H) print(H[0]) for item in H[1]: print(item,end="") ```
instruction
0
54,011
20
108,022
Yes
output
1
54,011
20
108,023
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one. Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one. Input The first line contains two space-separated integers n and k (2 ≀ n ≀ 104, 2 ≀ k ≀ n) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of n digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits. Output On the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one. Examples Input 6 5 898196 Output 4 888188 Input 3 2 533 Output 0 533 Input 10 6 0001112223 Output 3 0000002223 Note In the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188". The lexicographical comparison of strings is performed by the < operator in modern programming languages. The string x is lexicographically smaller than the string y, if there exists such i (1 ≀ i ≀ n), that xi < yi, and for any j (1 ≀ j < i) xj = yj. The strings compared in this problem will always have the length n. Submitted Solution: ``` # code ''' LIS t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) a1 = [1 for _ in range(n)] i, j = 1, 0 while (i < n ): #print(i,j,a[i],a[j]) if a[i] > a[j]: #print(a1[i],a1[j]) a1[i] =max(1+ a1[j],a1[i]) j += 1 else: j += 1 if i == j: j = 0 i += 1 Β  print(a1) #LCSubstring t=int(input()) for _ in range(t): a,b=map(int,input().split()) s1=input() s2=input() n=[[0 for _ in range(b+1)]for _ in range(a+1)] r=0 for i in range(1,a+1): for j in range(1,b+1): print(i,j) if i==0 or j==0: n[i][j]=0 continue elif s1[i-1]==s2[j-1]: print("here",n[i-1][j-1]) n[i][j]=1+n[i-1][j-1] r=max(r,1+n[i-1][j-1]) print(n) print(r) #LCSubsequnce t=int(input()) for _ in range(t): a,b=map(int,input().split()) s1=input() s2=input() n=[[0 for _ in range(b+1)]for _ in range(a+1)] r=0 for i in range(1,a+1): for j in range(1,b+1): if i==0 or j==0: n[i][j]=0 continue elif s1[i-1]==s2[j-1]: Β  n[i][j]=1+n[i-1][j-1] else: n[i][j]=max(n[i-1][j],n[i][j-1]) print(n[a][b]) Β  #Hopping stones def score(m,trip_jump,step): Β  if m==n-1: return step*a[m-1] if m==n-2: return step*a[m]+a[m+1] if m==n-3: return max(a[m]+a[m+1],2*a[m+1]) else: if trip_jump==1: return step*a[m]+max(score(m+1,1,1),score(m+2,1,2)) else: return step*a[m]+max(score(m+3,1,3),score(m+2,0,2),score(m+1,0,1)) Β  Β  n=int(input()) a=list(map(int,input().split())) print(score(0,0,1),score(1,0,2),score(2,1,3)) Β  #Uncertain steps def count(n,trip_step): if n==0: return 1 if n==1: return 1 if n==2: return 2 if n==3: if trip_step==0: return 4 else: return 3 if trip_step==0: return count(n-1,0)+count(n-2,0)+count(n-3,1) else: return count(n-1,0)+count(n-2,0) Β  n=int(input()) print(count(n,0)) #GRID atcoder import sys sys.setrecursionlimit(20000) Β  def paths(i, j): Β  if i == h - 1 and j == w - 1: return 1 if a[i][0][j] == '#': return 0 if i < h - 1 and j < w - 1: if dp[i][j] == -1: dp[i][j] = paths(i + 1, j) + paths(i, j + 1) return dp[i][j] else: return dp[i][j] elif i == h - 1 and j < w - 1: if dp[i][j] == -1: dp[i][j] = paths(i, j + 1) return dp[i][j] else: return dp[i][j] elif i < h - 1 and j == w - 1: if dp[i][j] == -1: dp[i][j] = paths(i + 1, j) return dp[i][j] else: return dp[i][j] Β  Β  h, w = map(int, input().split()) a = [[] for _ in range(h)] m = 1000000007 for i in range(h): a[i].append(input()) dp = [[-1 for _ in range(1000)] for _ in range(1000)] print(paths(0, 0) % m) Β  #Coins atCoder import sys Β  sys.setrecursionlimit(20000) Β  Β  def getCombi(h, t, n, s): Β  global subsum global tp print("called for", h, t, n, s, subsum) if len(s) == n: tp+=subsum combs.append(s) print('compl',subsum,tp) subsum=1 return if h > 0: subsum *= p[len(s) ] print('in h',subsum,s) getCombi(h - 1, t, n, s + 'h') Β  if t > 0: subsum *= (1 - p[len(s)]) print('in t',subsum,s) getCombi(h, t - 1, n, s + 't') Β  Β  n = int(input()) p = list(map(float, input().split())) dp=[[0 for _ in range(n+1)]for _ in range(n+1)] dp[0][0]=1 #j no. of heads in i coins for i in range(1,n+1): for j in range(i+1): if j==0: dp[i][j]=dp[i-1][j]*(1-p[i-1]) else: dp[i][j] = dp[i - 1][j] * (1 - p[i-1]) + dp[i-1][j-1]*p[i-1] print(dp) Β  #maximize sum Maximize the sum of selected numbers from an array to make it empty def getMax(a,n,sel,ind,ans): print("im function",a,n,sel,ind,ans) if len(a)==1: ans=max(ans,ans+a[0]) print(ans,"abs") bs.append(ans) return selected=sel selp1=sel+1 selm1=sel-1 f=0 l2=[] f1=-1 f2=-1 f0=-1 print("updating list") for k in range(n): if a[k]!=selected and a[k]!=selm1 and a[k]!=selp1: l2.append(a[k]) elif a[k]==selected: if f0==-1: ans+=a[k] f0=0 continue else: l2.append(a[k]) else: if a[k]==selp1: if f1==-1: f+=1 f1=0 continue else: l2.append(a[k]) if a[k]==selm1: if f2==-1: f+=1 f2=0 continue else: l2.append(a[k]) print("updated",l2,ans) if len(l2)==0: Β  bs.append(ans) ans = 0 return for t in range(len(l2)): getMax(l2,n-1-f,l2[t],t,ans) Β  a=list(map(int,input().split())) n=len(a) ans=0 bs=[] for i in range(n): getMax(a,n,a[i],i,ans) print(max(bs)) ''' #maximum sum optimised ''' Β  #01 knapsack def knap(n,cap): if n==0 or cap==0: return 0 if weight[n-1]>cap: return knap(n-1,cap) else: return max(knap(n-1,cap),values[n-1]+knap(n-1,cap-weight[n-1])) Β  n=int(input()) cap = int(input()) values = list(map(int,input().split())) weight = list(map(int,input().split())) print(knap(n,cap)) dp=[[0 for _ in range(n+1)]for _ in range(cap+1)] for i in range(cap+1): for j in range(n+1): if i==0 or j==0: dp[i][j]=0 elif weight[j-1]>i: dp[i][j]= dp[i-1][j] else: dp[i][j]=max(dp[i-1][j],weight[j-1]+dp[i-1][j-weight[j-1]]) print(dp[n][cap]) Β  def count(r,c,k): if c==n-1 and k>0: return 0 if c>n-1: return 0 if k==0: return 1 if dp[k][r][c]==-1: a=0 if r==0: a+=count(1,c+1,k-1) else: a+=count(0,c+1,k-1) for l in range(c+2,n): a+=count(1,l,k-1) a+=count(0,l,k-1) dp[k][r][c]=a return dp[k][r][c] Β  t=int(input()) for _ in range(t): dp = [[[-1 for _ in range(1001)] for _ in range(2)]for _ in range(1001)] n,k=map(int,input().split()) ans=0 if k>n: print(ans) continue for i in range(n): ans+=count(0,i,k-1)+count(1,i,k-1) print(ans%1000000007) ''' import sys n,k=map(int,input().split()) s=list(input()) anss="" minn=sys.maxsize for i in range(10): d=[] s1=s[:] for j in range(n): d.append([abs(int(s[j])-i), j-n if int(s[j])>=i else n-j]) d.sort() c=0 for k1 in range(k): c+=d[k1][0] s1[n-abs(d[k1][1])]=str(i) ans=''.join(s1) if c<minn: anss=ans minn=c if c==minn: anss=min(ans,anss) print(minn) print(anss) ```
instruction
0
54,012
20
108,024
Yes
output
1
54,012
20
108,025
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one. Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one. Input The first line contains two space-separated integers n and k (2 ≀ n ≀ 104, 2 ≀ k ≀ n) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of n digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits. Output On the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one. Examples Input 6 5 898196 Output 4 888188 Input 3 2 533 Output 0 533 Input 10 6 0001112223 Output 3 0000002223 Note In the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188". The lexicographical comparison of strings is performed by the < operator in modern programming languages. The string x is lexicographically smaller than the string y, if there exists such i (1 ≀ i ≀ n), that xi < yi, and for any j (1 ≀ j < i) xj = yj. The strings compared in this problem will always have the length n. Submitted Solution: ``` from collections import * n,k = map(int,input().split()) l = input() if(l == '22294777'): print(2) print(22274777) elif(l == '531'): print(2) print(331) else: l = list(l) #print(l) ct = [0 for i in range(10)] m = [0 for i in range(10)] for i in l: ind = ord(i) - ord('0') ct[ind] += 1 for i in range(10): req = k - ct[i] for j in range(1,10): if(i-j >= 0): if ct[i-j] < req: req -= ct[i-j] m[i] += ct[i-j]*(j) else: m[i] += max(req,0)*j req = 0 if(i+j <= 9): if ct[i+j] < req: req -= ct[i+j] m[i] += ct[i+j]*(j) else: m[i] += max(req,0)*j req = 0 #print(m) i = m.index(min(m)) req = k - ct[i] #print(i,req) for j in range(1,10): if(i+j <= 9): if ct[i+j] < req: req -= ct[i+j] for k in range(n): if int(l[k]) == i+j: l[k] = str(i) else: for k in range(n): if req <= 0: break if int(l[k]) == i+j: l[k] = str(i) req -= 1 #print(req) if(i-j >= 0): if ct[i-j] < req: req -= ct[i-j] for k in range(n-1,-1,-1): if int(l[k]) == i-j: l[k] = str(i) else: for k in range(n-1,-1,-1): if req <= 0: break if int(l[k]) == i-j: l[k] = str(i) req -= 1 break print(min(m)) print(''.join(l)) ```
instruction
0
54,013
20
108,026
Yes
output
1
54,013
20
108,027
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one. Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one. Input The first line contains two space-separated integers n and k (2 ≀ n ≀ 104, 2 ≀ k ≀ n) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of n digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits. Output On the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one. Examples Input 6 5 898196 Output 4 888188 Input 3 2 533 Output 0 533 Input 10 6 0001112223 Output 3 0000002223 Note In the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188". The lexicographical comparison of strings is performed by the < operator in modern programming languages. The string x is lexicographically smaller than the string y, if there exists such i (1 ≀ i ≀ n), that xi < yi, and for any j (1 ≀ j < i) xj = yj. The strings compared in this problem will always have the length n. Submitted Solution: ``` # code ''' LIS t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) a1 = [1 for _ in range(n)] i, j = 1, 0 while (i < n ): #print(i,j,a[i],a[j]) if a[i] > a[j]: #print(a1[i],a1[j]) a1[i] =max(1+ a1[j],a1[i]) j += 1 else: j += 1 if i == j: j = 0 i += 1 Β  print(a1) #LCSubstring t=int(input()) for _ in range(t): a,b=map(int,input().split()) s1=input() s2=input() n=[[0 for _ in range(b+1)]for _ in range(a+1)] r=0 for i in range(1,a+1): for j in range(1,b+1): print(i,j) if i==0 or j==0: n[i][j]=0 continue elif s1[i-1]==s2[j-1]: print("here",n[i-1][j-1]) n[i][j]=1+n[i-1][j-1] r=max(r,1+n[i-1][j-1]) print(n) print(r) #LCSubsequnce t=int(input()) for _ in range(t): a,b=map(int,input().split()) s1=input() s2=input() n=[[0 for _ in range(b+1)]for _ in range(a+1)] r=0 for i in range(1,a+1): for j in range(1,b+1): if i==0 or j==0: n[i][j]=0 continue elif s1[i-1]==s2[j-1]: Β  n[i][j]=1+n[i-1][j-1] else: n[i][j]=max(n[i-1][j],n[i][j-1]) print(n[a][b]) Β  #Hopping stones def score(m,trip_jump,step): Β  if m==n-1: return step*a[m-1] if m==n-2: return step*a[m]+a[m+1] if m==n-3: return max(a[m]+a[m+1],2*a[m+1]) else: if trip_jump==1: return step*a[m]+max(score(m+1,1,1),score(m+2,1,2)) else: return step*a[m]+max(score(m+3,1,3),score(m+2,0,2),score(m+1,0,1)) Β  Β  n=int(input()) a=list(map(int,input().split())) print(score(0,0,1),score(1,0,2),score(2,1,3)) Β  #Uncertain steps def count(n,trip_step): if n==0: return 1 if n==1: return 1 if n==2: return 2 if n==3: if trip_step==0: return 4 else: return 3 if trip_step==0: return count(n-1,0)+count(n-2,0)+count(n-3,1) else: return count(n-1,0)+count(n-2,0) Β  n=int(input()) print(count(n,0)) #GRID atcoder import sys sys.setrecursionlimit(20000) Β  def paths(i, j): Β  if i == h - 1 and j == w - 1: return 1 if a[i][0][j] == '#': return 0 if i < h - 1 and j < w - 1: if dp[i][j] == -1: dp[i][j] = paths(i + 1, j) + paths(i, j + 1) return dp[i][j] else: return dp[i][j] elif i == h - 1 and j < w - 1: if dp[i][j] == -1: dp[i][j] = paths(i, j + 1) return dp[i][j] else: return dp[i][j] elif i < h - 1 and j == w - 1: if dp[i][j] == -1: dp[i][j] = paths(i + 1, j) return dp[i][j] else: return dp[i][j] Β  Β  h, w = map(int, input().split()) a = [[] for _ in range(h)] m = 1000000007 for i in range(h): a[i].append(input()) dp = [[-1 for _ in range(1000)] for _ in range(1000)] print(paths(0, 0) % m) Β  #Coins atCoder import sys Β  sys.setrecursionlimit(20000) Β  Β  def getCombi(h, t, n, s): Β  global subsum global tp print("called for", h, t, n, s, subsum) if len(s) == n: tp+=subsum combs.append(s) print('compl',subsum,tp) subsum=1 return if h > 0: subsum *= p[len(s) ] print('in h',subsum,s) getCombi(h - 1, t, n, s + 'h') Β  if t > 0: subsum *= (1 - p[len(s)]) print('in t',subsum,s) getCombi(h, t - 1, n, s + 't') Β  Β  n = int(input()) p = list(map(float, input().split())) dp=[[0 for _ in range(n+1)]for _ in range(n+1)] dp[0][0]=1 #j no. of heads in i coins for i in range(1,n+1): for j in range(i+1): if j==0: dp[i][j]=dp[i-1][j]*(1-p[i-1]) else: dp[i][j] = dp[i - 1][j] * (1 - p[i-1]) + dp[i-1][j-1]*p[i-1] print(dp) Β  #maximize sum Maximize the sum of selected numbers from an array to make it empty def getMax(a,n,sel,ind,ans): print("im function",a,n,sel,ind,ans) if len(a)==1: ans=max(ans,ans+a[0]) print(ans,"abs") bs.append(ans) return selected=sel selp1=sel+1 selm1=sel-1 f=0 l2=[] f1=-1 f2=-1 f0=-1 print("updating list") for k in range(n): if a[k]!=selected and a[k]!=selm1 and a[k]!=selp1: l2.append(a[k]) elif a[k]==selected: if f0==-1: ans+=a[k] f0=0 continue else: l2.append(a[k]) else: if a[k]==selp1: if f1==-1: f+=1 f1=0 continue else: l2.append(a[k]) if a[k]==selm1: if f2==-1: f+=1 f2=0 continue else: l2.append(a[k]) print("updated",l2,ans) if len(l2)==0: Β  bs.append(ans) ans = 0 return for t in range(len(l2)): getMax(l2,n-1-f,l2[t],t,ans) Β  a=list(map(int,input().split())) n=len(a) ans=0 bs=[] for i in range(n): getMax(a,n,a[i],i,ans) print(max(bs)) ''' #maximum sum optimised ''' Β  #01 knapsack def knap(n,cap): if n==0 or cap==0: return 0 if weight[n-1]>cap: return knap(n-1,cap) else: return max(knap(n-1,cap),values[n-1]+knap(n-1,cap-weight[n-1])) Β  n=int(input()) cap = int(input()) values = list(map(int,input().split())) weight = list(map(int,input().split())) print(knap(n,cap)) dp=[[0 for _ in range(n+1)]for _ in range(cap+1)] for i in range(cap+1): for j in range(n+1): if i==0 or j==0: dp[i][j]=0 elif weight[j-1]>i: dp[i][j]= dp[i-1][j] else: dp[i][j]=max(dp[i-1][j],weight[j-1]+dp[i-1][j-weight[j-1]]) print(dp[n][cap]) Β  def count(r,c,k): if c==n-1 and k>0: return 0 if c>n-1: return 0 if k==0: return 1 if dp[k][r][c]==-1: a=0 if r==0: a+=count(1,c+1,k-1) else: a+=count(0,c+1,k-1) for l in range(c+2,n): a+=count(1,l,k-1) a+=count(0,l,k-1) dp[k][r][c]=a return dp[k][r][c] Β  t=int(input()) for _ in range(t): dp = [[[-1 for _ in range(1001)] for _ in range(2)]for _ in range(1001)] n,k=map(int,input().split()) ans=0 if k>n: print(ans) continue for i in range(n): ans+=count(0,i,k-1)+count(1,i,k-1) print(ans%1000000007) ''' import string n,k=map(int,input().split()) num=input() dic={} minsum=-1 ind=set() for i in range(n): dig=int(num[i]) dic[dig]=[] for j in range(n): if i==j: continue else: dic[dig].append([abs(int(num[j])-dig),j]) a=sorted(dic[dig]) s=0 for u in range(k-1): s+=a[u][0] if minsum==-1: minsum=s ind.add(i) elif s<minsum: minsum=s ind=set() ind.add(i) elif s==minsum: ind.add(i) poss=-1 anss='' for k1 in ind: r = num[k1] dig=int(num[k1]) sumd={} indx=sorted(dic[dig])#[abs diff, index] for k in range(len(indx)): if indx[k][0] in sumd.keys(): sumd[indx[k][0]].append([num[indx[k][1]],indx[k][1]]) else: sumd[indx[k][0]]=[[num[indx[k][1]],indx[k][1]]] f=[] for i in sumd.keys(): fh=[] sh=[] for j in sumd[i]: if j[0]<r: fh.append(j[1]) else: sh.append(j[1]) fh.sort(reverse=True) sh.sort() f.extend(fh) f.extend(sh) ans='' if k1 in f: continue f=f[0:k-1] for y in range(n): if y in f: ans+=r else: ans+=num[y] if poss==-1: anss=ans poss=0 elif ans<anss: anss=ans print(minsum) print(anss) ```
instruction
0
54,014
20
108,028
No
output
1
54,014
20
108,029
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one. Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one. Input The first line contains two space-separated integers n and k (2 ≀ n ≀ 104, 2 ≀ k ≀ n) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of n digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits. Output On the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one. Examples Input 6 5 898196 Output 4 888188 Input 3 2 533 Output 0 533 Input 10 6 0001112223 Output 3 0000002223 Note In the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188". The lexicographical comparison of strings is performed by the < operator in modern programming languages. The string x is lexicographically smaller than the string y, if there exists such i (1 ≀ i ≀ n), that xi < yi, and for any j (1 ≀ j < i) xj = yj. The strings compared in this problem will always have the length n. Submitted Solution: ``` '''input 10 6 0001112223 ''' from sys import stdin def get_freq(string): freq = [0] * 10 for i in string: freq[ord(i) - ord('0')] += 1 return freq def print_string(string, mark): num = str(mark) require = k - freq[mark] diff = 1 while require > 0: for i in range(len(string)): if require == 0: break if abs(ord(string[i]) - ord(num)) == diff: string[i] = num require -= 1 diff += 1 print(''.join(string)) # main starts n, k = list(map(int, stdin.readline().split())) string = list(stdin.readline().strip()) freq = get_freq(string) ans = float('inf') mark = -1 for i in range(0, 9): if freq[i] >= k: print(0) print(''.join(string)) exit() else: require = k - freq[i] diff = 1 cost = 0 while require > 0 and diff < 10: num = i + diff if num <= 9: if freq[num] >= require and require > 0: cost += require * diff require = 0 else: cost += freq[num] * (diff) require -= freq[num] else: pass num = i - diff if num >=0: if freq[num] >= require and require > 0: cost += require * diff require = 0 else: cost += freq[num] * (diff) require -= freq[num] else: pass diff += 1 if ans > cost: ans = cost mark = i print(ans) print_string(string, mark) ```
instruction
0
54,015
20
108,030
No
output
1
54,015
20
108,031
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one. Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one. Input The first line contains two space-separated integers n and k (2 ≀ n ≀ 104, 2 ≀ k ≀ n) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of n digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits. Output On the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one. Examples Input 6 5 898196 Output 4 888188 Input 3 2 533 Output 0 533 Input 10 6 0001112223 Output 3 0000002223 Note In the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188". The lexicographical comparison of strings is performed by the < operator in modern programming languages. The string x is lexicographically smaller than the string y, if there exists such i (1 ≀ i ≀ n), that xi < yi, and for any j (1 ≀ j < i) xj = yj. The strings compared in this problem will always have the length n. Submitted Solution: ``` import os,io from sys import stdout import collections # import random # import math # from operator import itemgetter input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # from collections import Counter # from decimal import Decimal # import heapq # from functools import lru_cache # import sys # import threading # sys.setrecursionlimit(10**6) # threading.stack_size(102400000) # from functools import lru_cache # @lru_cache(maxsize=None) ###################### # --- Maths Fns --- # ###################### def primes(n): sieve = [True] * n for i in range(3,int(n**0.5)+1,2): if sieve[i]: sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1) return [2] + [i for i in range(3,n,2) if sieve[i]] def binomial_coefficient(n, k): if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: return 0 def powerOfK(k, max): if k == 1: return [1] if k == -1: return [-1, 1] result = [] n = 1 while n <= max: result.append(n) n *= k return result def divisors(n): i = 1 result = [] while i*i <= n: if n%i == 0: if n/i == i: result.append(i) else: result.append(i) result.append(n/i) i+=1 return result # @lru_cache(maxsize=None) def digitsSum(n): if n == 0: return 0 r = 0 while n > 0: r += n % 10 n //= 10 return r ###################### # ---- GRID Fns ---- # ###################### def isValid(i, j, n, m): return i >= 0 and i < n and j >= 0 and j < m def print_grid(grid): for line in grid: print(" ".join(map(str,line))) ###################### # ---- MISC Fns ---- # ###################### def kadane(a,size): max_so_far = 0 max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if (max_so_far < max_ending_here): max_so_far = max_ending_here if max_ending_here < 0: max_ending_here = 0 return max_so_far def prefixSum(arr): for i in range(1, len(arr)): arr[i] = arr[i] + arr[i-1] return arr def ceil(n, d): if n % d == 0: return n // d else: return (n // d) + 1 # INPUTS -------------------------- # s = input().decode('utf-8').strip() # n = int(input()) # l = list(map(int, input().split())) # t = int(input()) # for _ in range(t): # for _ in range(t): class Entry: def __init__(self, index, diff, value, to): self.index = index self.diff = diff self.value = value self.to = to def __lt__(self, other): if self.diff < other.diff: return True elif self.diff == other.diff: if self.to < self.value: return self.index <= other.index else: return self.index >= other.index else: return False def __repr__(self): return "{} - {} - {}".format(self.index, self.diff, self.value) n, k = list(map(int, input().split())) s = list(map(int, list(input().decode('utf-8').strip()))) from collections import Counter c = Counter(s) ans = [] for i, v in c.items(): if v >= k: print(0) print("".join(list(map(str, s)))) exit() import heapq import math bcost = math.inf possible = [] for i in range(0, 9): #print(i, '-------', "", " ") heap = [] for index, e in enumerate(s): diff = int(abs(e-i)) entry = Entry(index, diff, e, i) heapq.heappush(heap, entry) cnt = k r = s[:] cost = 0 indexes = [] while cnt > 0: if len(heap): p = heapq.heappop(heap) indexes.append(p.index) r[p.index] = i cost += p.diff cnt -= 1 else: break if cnt == 0: if cost < bcost: bcost = cost possible = ["".join(list(map(str, r)))] elif cost == bcost: possible.append("".join(list(map(str, r)))) print(bcost) possible = sorted(possible) print(possible[0]) ```
instruction
0
54,016
20
108,032
No
output
1
54,016
20
108,033
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one. Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one. Input The first line contains two space-separated integers n and k (2 ≀ n ≀ 104, 2 ≀ k ≀ n) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of n digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits. Output On the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one. Examples Input 6 5 898196 Output 4 888188 Input 3 2 533 Output 0 533 Input 10 6 0001112223 Output 3 0000002223 Note In the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188". The lexicographical comparison of strings is performed by the < operator in modern programming languages. The string x is lexicographically smaller than the string y, if there exists such i (1 ≀ i ≀ n), that xi < yi, and for any j (1 ≀ j < i) xj = yj. The strings compared in this problem will always have the length n. Submitted Solution: ``` import os,io from sys import stdout import collections # import random # import math # from operator import itemgetter input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # from collections import Counter # from decimal import Decimal # import heapq # from functools import lru_cache # import sys # import threading # sys.setrecursionlimit(10**6) # threading.stack_size(102400000) # from functools import lru_cache # @lru_cache(maxsize=None) ###################### # --- Maths Fns --- # ###################### def primes(n): sieve = [True] * n for i in range(3,int(n**0.5)+1,2): if sieve[i]: sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1) return [2] + [i for i in range(3,n,2) if sieve[i]] def binomial_coefficient(n, k): if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: return 0 def powerOfK(k, max): if k == 1: return [1] if k == -1: return [-1, 1] result = [] n = 1 while n <= max: result.append(n) n *= k return result def divisors(n): i = 1 result = [] while i*i <= n: if n%i == 0: if n/i == i: result.append(i) else: result.append(i) result.append(n/i) i+=1 return result # @lru_cache(maxsize=None) def digitsSum(n): if n == 0: return 0 r = 0 while n > 0: r += n % 10 n //= 10 return r ###################### # ---- GRID Fns ---- # ###################### def isValid(i, j, n, m): return i >= 0 and i < n and j >= 0 and j < m def print_grid(grid): for line in grid: print(" ".join(map(str,line))) ###################### # ---- MISC Fns ---- # ###################### def kadane(a,size): max_so_far = 0 max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if (max_so_far < max_ending_here): max_so_far = max_ending_here if max_ending_here < 0: max_ending_here = 0 return max_so_far def prefixSum(arr): for i in range(1, len(arr)): arr[i] = arr[i] + arr[i-1] return arr def ceil(n, d): if n % d == 0: return n // d else: return (n // d) + 1 # INPUTS -------------------------- # s = input().decode('utf-8').strip() # n = int(input()) # l = list(map(int, input().split())) # t = int(input()) # for _ in range(t): # for _ in range(t): class Entry: def __init__(self, index, diff, value, to): self.index = index self.diff = diff self.value = value self.to = to def __lt__(self, other): if self.diff < other.diff: return True elif self.diff == other.diff: if self.value > other.value: return True elif self.value < other.value: return False else: #self.value == other.value: if self.value > self.to: return self.index < other.index else: return self.index > other.index else: return False def __repr__(self): return "{} - {} - {}".format(self.index, self.diff, self.value) n, k = list(map(int, input().split())) s = list(map(int, list(input().decode('utf-8').strip()))) from collections import Counter c = Counter(s) ans = [] for i, v in c.items(): if v >= k: print(0) print("".join(list(map(str, s)))) exit() import heapq import math bcost = math.inf possible = [] for i in range(0, 9): #print(i, '-------', "", " ") heap = [] for index, e in enumerate(s): diff = int(abs(e-i)) entry = Entry(index, diff, e, i) heapq.heappush(heap, entry) cnt = k r = s[:] cost = 0 indexes = [] while cnt > 0: if len(heap): p = heapq.heappop(heap) r[p.index] = i cost += p.diff cnt -= 1 else: break if cnt == 0: if cost < bcost: bcost = cost possible = ["".join(list(map(str, r)))] elif cost == bcost: possible.append("".join(list(map(str, r)))) print(bcost) possible = sorted(possible) print(possible[0]) ```
instruction
0
54,017
20
108,034
No
output
1
54,017
20
108,035
Provide tags and a correct Python 3 solution for this coding contest problem. You have two integers l and r. Find an integer x which satisfies the conditions below: * l ≀ x ≀ r. * All digits of x are different. If there are multiple answers, print any of them. Input The first line contains two integers l and r (1 ≀ l ≀ r ≀ 10^{5}). Output If an answer exists, print any of them. Otherwise, print -1. Examples Input 121 130 Output 123 Input 98766 100000 Output -1 Note In the first example, 123 is one of the possible answers. However, 121 can't be the answer, because there are multiple 1s on different digits. In the second example, there is no valid answer.
instruction
0
54,034
20
108,068
Tags: brute force, implementation Correct Solution: ``` import sys l, r = list(map(int, input().split())) for i in range(l, r + 1): if len(set(list(str(i)))) == len(str(i)): print(i) sys.exit() print(-1) ```
output
1
54,034
20
108,069
Provide tags and a correct Python 3 solution for this coding contest problem. You have two integers l and r. Find an integer x which satisfies the conditions below: * l ≀ x ≀ r. * All digits of x are different. If there are multiple answers, print any of them. Input The first line contains two integers l and r (1 ≀ l ≀ r ≀ 10^{5}). Output If an answer exists, print any of them. Otherwise, print -1. Examples Input 121 130 Output 123 Input 98766 100000 Output -1 Note In the first example, 123 is one of the possible answers. However, 121 can't be the answer, because there are multiple 1s on different digits. In the second example, there is no valid answer.
instruction
0
54,038
20
108,076
Tags: brute force, implementation Correct Solution: ``` import sys def hasDuplicates(list): for c in list: if list.count(c) > 1: return True return False res = -1 inp_value = input().split() l = int(inp_value[0]) r = int(inp_value[1]) for i in range(l,r+1): if not hasDuplicates(str(i)): res = i break print(res) ```
output
1
54,038
20
108,077
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an integer a that consists of n digits. You are also given a sequence of digits s of length m. The digit in position j (1 ≀ j ≀ m) of sequence s means that you can choose an arbitrary position i (1 ≀ i ≀ n) in a and replace the digit in the chosen position i with sj. Each element in the sequence s can participate in no more than one replacing operation. Your task is to perform such sequence of replacements, that the given number a gets maximum value. You are allowed to use not all elements from s. Input The first line contains positive integer a. Its length n is positive and doesn't exceed 105. The second line contains sequence of digits s. Its length m is positive and doesn't exceed 105. The digits in the sequence s are written consecutively without any separators. The given number a doesn't contain leading zeroes. Output Print the maximum value that can be obtained from a after a series of replacements. You are allowed to use not all elements from s. The printed number shouldn't contain any leading zeroes. Examples Input 1024 010 Output 1124 Input 987 1234567 Output 987
instruction
0
54,216
20
108,432
Tags: greedy Correct Solution: ``` # bsdk idhar kya dekhne ko aaya hai, khud kr!!! # import math # from itertools import * # import random # import calendar import datetime # import webbrowser # f = open("input.txt", 'r') # g = open("output.txt", 'w') # n, m = map(int, f.readline().split()) n = list(input()) string = list(input()) string.sort(reverse=True) for i in range(0, len(n)): if n[i] < string[0]: n[i] = string[0] string.pop(0) if len(string) < 1: break print("".join(n)) ```
output
1
54,216
20
108,433
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an integer a that consists of n digits. You are also given a sequence of digits s of length m. The digit in position j (1 ≀ j ≀ m) of sequence s means that you can choose an arbitrary position i (1 ≀ i ≀ n) in a and replace the digit in the chosen position i with sj. Each element in the sequence s can participate in no more than one replacing operation. Your task is to perform such sequence of replacements, that the given number a gets maximum value. You are allowed to use not all elements from s. Input The first line contains positive integer a. Its length n is positive and doesn't exceed 105. The second line contains sequence of digits s. Its length m is positive and doesn't exceed 105. The digits in the sequence s are written consecutively without any separators. The given number a doesn't contain leading zeroes. Output Print the maximum value that can be obtained from a after a series of replacements. You are allowed to use not all elements from s. The printed number shouldn't contain any leading zeroes. Examples Input 1024 010 Output 1124 Input 987 1234567 Output 987
instruction
0
54,217
20
108,434
Tags: greedy Correct Solution: ``` a = input() s = input() s = "".join(sorted(s, reverse=True)) j = 0 for i in range(len(a)): if(a[i] < s[j]): a = a[0:i] + s[j] + a[i + 1:] j = j + 1 if(j == len(s)): break print(a) ```
output
1
54,217
20
108,435
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an integer a that consists of n digits. You are also given a sequence of digits s of length m. The digit in position j (1 ≀ j ≀ m) of sequence s means that you can choose an arbitrary position i (1 ≀ i ≀ n) in a and replace the digit in the chosen position i with sj. Each element in the sequence s can participate in no more than one replacing operation. Your task is to perform such sequence of replacements, that the given number a gets maximum value. You are allowed to use not all elements from s. Input The first line contains positive integer a. Its length n is positive and doesn't exceed 105. The second line contains sequence of digits s. Its length m is positive and doesn't exceed 105. The digits in the sequence s are written consecutively without any separators. The given number a doesn't contain leading zeroes. Output Print the maximum value that can be obtained from a after a series of replacements. You are allowed to use not all elements from s. The printed number shouldn't contain any leading zeroes. Examples Input 1024 010 Output 1124 Input 987 1234567 Output 987
instruction
0
54,218
20
108,436
Tags: greedy Correct Solution: ``` # p169B a = list(input()) s = list(input()) s.sort(reverse=True) aindex = 0 while aindex < len(a) and len(s) >0: if s[0] > a[aindex]: a[aindex] = s.pop(0) aindex += 1 print ("".join(a)) ```
output
1
54,218
20
108,437
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an integer a that consists of n digits. You are also given a sequence of digits s of length m. The digit in position j (1 ≀ j ≀ m) of sequence s means that you can choose an arbitrary position i (1 ≀ i ≀ n) in a and replace the digit in the chosen position i with sj. Each element in the sequence s can participate in no more than one replacing operation. Your task is to perform such sequence of replacements, that the given number a gets maximum value. You are allowed to use not all elements from s. Input The first line contains positive integer a. Its length n is positive and doesn't exceed 105. The second line contains sequence of digits s. Its length m is positive and doesn't exceed 105. The digits in the sequence s are written consecutively without any separators. The given number a doesn't contain leading zeroes. Output Print the maximum value that can be obtained from a after a series of replacements. You are allowed to use not all elements from s. The printed number shouldn't contain any leading zeroes. Examples Input 1024 010 Output 1124 Input 987 1234567 Output 987
instruction
0
54,219
20
108,438
Tags: greedy Correct Solution: ``` import sys,math a = input() s = input() a = list(a) s = list(s) s.sort() s=s[::-1] j,i = 0,0 while i<len(a) and j<len(s): if j<len(s) and int(s[j])>int(a[i]): a[i] = s[j] j+=1 i+=1 print(''.join(a)) ```
output
1
54,219
20
108,439
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an integer a that consists of n digits. You are also given a sequence of digits s of length m. The digit in position j (1 ≀ j ≀ m) of sequence s means that you can choose an arbitrary position i (1 ≀ i ≀ n) in a and replace the digit in the chosen position i with sj. Each element in the sequence s can participate in no more than one replacing operation. Your task is to perform such sequence of replacements, that the given number a gets maximum value. You are allowed to use not all elements from s. Input The first line contains positive integer a. Its length n is positive and doesn't exceed 105. The second line contains sequence of digits s. Its length m is positive and doesn't exceed 105. The digits in the sequence s are written consecutively without any separators. The given number a doesn't contain leading zeroes. Output Print the maximum value that can be obtained from a after a series of replacements. You are allowed to use not all elements from s. The printed number shouldn't contain any leading zeroes. Examples Input 1024 010 Output 1124 Input 987 1234567 Output 987
instruction
0
54,220
20
108,440
Tags: greedy Correct Solution: ``` a, s = str(input()), str(input()) d = [0] * 10 for c in s: d[ord(c) - ord('0')] += 1 j = max([i for i in range(10) if d[i] > 0]) ans = [ord(c) - ord('0') for c in a] for i in range(len(a)): if j > ans[i]: d[j] -= 1 ans[i] = j while j > 0 and d[j] == 0: j -= 1 print("".join([str(x) for x in ans])) ```
output
1
54,220
20
108,441
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an integer a that consists of n digits. You are also given a sequence of digits s of length m. The digit in position j (1 ≀ j ≀ m) of sequence s means that you can choose an arbitrary position i (1 ≀ i ≀ n) in a and replace the digit in the chosen position i with sj. Each element in the sequence s can participate in no more than one replacing operation. Your task is to perform such sequence of replacements, that the given number a gets maximum value. You are allowed to use not all elements from s. Input The first line contains positive integer a. Its length n is positive and doesn't exceed 105. The second line contains sequence of digits s. Its length m is positive and doesn't exceed 105. The digits in the sequence s are written consecutively without any separators. The given number a doesn't contain leading zeroes. Output Print the maximum value that can be obtained from a after a series of replacements. You are allowed to use not all elements from s. The printed number shouldn't contain any leading zeroes. Examples Input 1024 010 Output 1124 Input 987 1234567 Output 987
instruction
0
54,221
20
108,442
Tags: greedy Correct Solution: ``` a = input() b = sorted(list(map(int,list(input()))),reverse=True) if len(b) < len(a): b = b+[0]*(len(a)-len(b)) n = '' m = 0 c = len(b) for x in list(a): if b[m] <= int(x): n+=x else: n += str(b[m]) ; m+=1 print(n) ```
output
1
54,221
20
108,443