text
stringlengths
198
433k
conversation_id
int64
0
109k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call an array of non-negative integers a_1, a_2, …, a_n a k-extension for some non-negative integer k if for all possible pairs of indices 1 ≀ i, j ≀ n the inequality k β‹… |i - j| ≀ min(a_i, a_j) is satisfied. The expansion coefficient of the array a is the maximal integer k such that the array a is a k-extension. Any array is a 0-expansion, so the expansion coefficient always exists. You are given an array of non-negative integers a_1, a_2, …, a_n. Find its expansion coefficient. Input The first line contains one positive integer n β€” the number of elements in the array a (2 ≀ n ≀ 300 000). The next line contains n non-negative integers a_1, a_2, …, a_n, separated by spaces (0 ≀ a_i ≀ 10^9). Output Print one non-negative integer β€” expansion coefficient of the array a_1, a_2, …, a_n. Examples Input 4 6 4 5 5 Output 1 Input 3 0 1 2 Output 0 Input 4 821 500 479 717 Output 239 Note In the first test, the expansion coefficient of the array [6, 4, 5, 5] is equal to 1 because |i-j| ≀ min(a_i, a_j), because all elements of the array satisfy a_i β‰₯ 3. On the other hand, this array isn't a 2-extension, because 6 = 2 β‹… |1 - 4| ≀ min(a_1, a_4) = 5 is false. In the second test, the expansion coefficient of the array [0, 1, 2] is equal to 0 because this array is not a 1-extension, but it is 0-extension. Submitted Solution: ``` # ========= /\ /| |====/| # | / \ | | / | # | /____\ | | / | # | / \ | | / | # ========= / \ ===== |/====| # code if __name__ == "__main__": n = int(input()) a = list(map(int,input().split())) k = 10**9 for i in range(n): if i != 0: k = min(k , a[i]//i) if i != n-1: k = min(k , a[i]//(n-1-i)) print(k) ``` Yes
97,900
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call an array of non-negative integers a_1, a_2, …, a_n a k-extension for some non-negative integer k if for all possible pairs of indices 1 ≀ i, j ≀ n the inequality k β‹… |i - j| ≀ min(a_i, a_j) is satisfied. The expansion coefficient of the array a is the maximal integer k such that the array a is a k-extension. Any array is a 0-expansion, so the expansion coefficient always exists. You are given an array of non-negative integers a_1, a_2, …, a_n. Find its expansion coefficient. Input The first line contains one positive integer n β€” the number of elements in the array a (2 ≀ n ≀ 300 000). The next line contains n non-negative integers a_1, a_2, …, a_n, separated by spaces (0 ≀ a_i ≀ 10^9). Output Print one non-negative integer β€” expansion coefficient of the array a_1, a_2, …, a_n. Examples Input 4 6 4 5 5 Output 1 Input 3 0 1 2 Output 0 Input 4 821 500 479 717 Output 239 Note In the first test, the expansion coefficient of the array [6, 4, 5, 5] is equal to 1 because |i-j| ≀ min(a_i, a_j), because all elements of the array satisfy a_i β‰₯ 3. On the other hand, this array isn't a 2-extension, because 6 = 2 β‹… |1 - 4| ≀ min(a_1, a_4) = 5 is false. In the second test, the expansion coefficient of the array [0, 1, 2] is equal to 0 because this array is not a 1-extension, but it is 0-extension. Submitted Solution: ``` n=int(input()) res=[] list=[int(i) for i in input().split()] for i in range(1,n-1): res.append(min(int(min(list[0],list[i])/i),int(min(list[n-1],list[i])/(n-1-i)))) res.append(int(min(list[0],list[n-1])/(n-1))) print(min(res)) ``` Yes
97,901
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call an array of non-negative integers a_1, a_2, …, a_n a k-extension for some non-negative integer k if for all possible pairs of indices 1 ≀ i, j ≀ n the inequality k β‹… |i - j| ≀ min(a_i, a_j) is satisfied. The expansion coefficient of the array a is the maximal integer k such that the array a is a k-extension. Any array is a 0-expansion, so the expansion coefficient always exists. You are given an array of non-negative integers a_1, a_2, …, a_n. Find its expansion coefficient. Input The first line contains one positive integer n β€” the number of elements in the array a (2 ≀ n ≀ 300 000). The next line contains n non-negative integers a_1, a_2, …, a_n, separated by spaces (0 ≀ a_i ≀ 10^9). Output Print one non-negative integer β€” expansion coefficient of the array a_1, a_2, …, a_n. Examples Input 4 6 4 5 5 Output 1 Input 3 0 1 2 Output 0 Input 4 821 500 479 717 Output 239 Note In the first test, the expansion coefficient of the array [6, 4, 5, 5] is equal to 1 because |i-j| ≀ min(a_i, a_j), because all elements of the array satisfy a_i β‰₯ 3. On the other hand, this array isn't a 2-extension, because 6 = 2 β‹… |1 - 4| ≀ min(a_1, a_4) = 5 is false. In the second test, the expansion coefficient of the array [0, 1, 2] is equal to 0 because this array is not a 1-extension, but it is 0-extension. Submitted Solution: ``` n = int(input()) a = [int(s) for s in input().split()] b = 0 c = 1000000000 c = a[0]//(n-1) for i in range(1,n): b = a[i]//i if c>=b: c = b print(c) ``` No
97,902
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call an array of non-negative integers a_1, a_2, …, a_n a k-extension for some non-negative integer k if for all possible pairs of indices 1 ≀ i, j ≀ n the inequality k β‹… |i - j| ≀ min(a_i, a_j) is satisfied. The expansion coefficient of the array a is the maximal integer k such that the array a is a k-extension. Any array is a 0-expansion, so the expansion coefficient always exists. You are given an array of non-negative integers a_1, a_2, …, a_n. Find its expansion coefficient. Input The first line contains one positive integer n β€” the number of elements in the array a (2 ≀ n ≀ 300 000). The next line contains n non-negative integers a_1, a_2, …, a_n, separated by spaces (0 ≀ a_i ≀ 10^9). Output Print one non-negative integer β€” expansion coefficient of the array a_1, a_2, …, a_n. Examples Input 4 6 4 5 5 Output 1 Input 3 0 1 2 Output 0 Input 4 821 500 479 717 Output 239 Note In the first test, the expansion coefficient of the array [6, 4, 5, 5] is equal to 1 because |i-j| ≀ min(a_i, a_j), because all elements of the array satisfy a_i β‰₯ 3. On the other hand, this array isn't a 2-extension, because 6 = 2 β‹… |1 - 4| ≀ min(a_1, a_4) = 5 is false. In the second test, the expansion coefficient of the array [0, 1, 2] is equal to 0 because this array is not a 1-extension, but it is 0-extension. Submitted Solution: ``` n = int(input()) l = list(map(int,input().split())) a = min(l) b = max(l) z1 = l.index(a) z2 = l.index(b) k1 = min(l[0],l[n-1])//abs(n-1) ba = [] sa = [] for i in range(len(l)): if i!=z1: ba.append((a//abs(z1-i))) for i in range(len(l)): if i!=z2: ba.append((min(b,l[i])//abs(z2-i))) ba.sort() sa.sort() z = ba[0] h = 10**18 if len(sa)>0: h = sa[0] i = 0 j = n-1 mini = 10**19 while i<j: if min(l[i],l[j])//(abs((i-j))) < mini: mini = min(l[i],l[j])//(abs((i-j))) i+=1 j-=1 print(min(k1,z,h,mini)) ``` No
97,903
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call an array of non-negative integers a_1, a_2, …, a_n a k-extension for some non-negative integer k if for all possible pairs of indices 1 ≀ i, j ≀ n the inequality k β‹… |i - j| ≀ min(a_i, a_j) is satisfied. The expansion coefficient of the array a is the maximal integer k such that the array a is a k-extension. Any array is a 0-expansion, so the expansion coefficient always exists. You are given an array of non-negative integers a_1, a_2, …, a_n. Find its expansion coefficient. Input The first line contains one positive integer n β€” the number of elements in the array a (2 ≀ n ≀ 300 000). The next line contains n non-negative integers a_1, a_2, …, a_n, separated by spaces (0 ≀ a_i ≀ 10^9). Output Print one non-negative integer β€” expansion coefficient of the array a_1, a_2, …, a_n. Examples Input 4 6 4 5 5 Output 1 Input 3 0 1 2 Output 0 Input 4 821 500 479 717 Output 239 Note In the first test, the expansion coefficient of the array [6, 4, 5, 5] is equal to 1 because |i-j| ≀ min(a_i, a_j), because all elements of the array satisfy a_i β‰₯ 3. On the other hand, this array isn't a 2-extension, because 6 = 2 β‹… |1 - 4| ≀ min(a_1, a_4) = 5 is false. In the second test, the expansion coefficient of the array [0, 1, 2] is equal to 0 because this array is not a 1-extension, but it is 0-extension. Submitted Solution: ``` n = int(input()) a = [int(x) for x in input().split()] module = n - 1 k = [] for i in range(n - 1): for j in range(1, n): minimum = min(a[i], a[j]) if minimum < module: k.append(0) else: r = minimum // module k.append(r) print(max(k)) ``` No
97,904
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call an array of non-negative integers a_1, a_2, …, a_n a k-extension for some non-negative integer k if for all possible pairs of indices 1 ≀ i, j ≀ n the inequality k β‹… |i - j| ≀ min(a_i, a_j) is satisfied. The expansion coefficient of the array a is the maximal integer k such that the array a is a k-extension. Any array is a 0-expansion, so the expansion coefficient always exists. You are given an array of non-negative integers a_1, a_2, …, a_n. Find its expansion coefficient. Input The first line contains one positive integer n β€” the number of elements in the array a (2 ≀ n ≀ 300 000). The next line contains n non-negative integers a_1, a_2, …, a_n, separated by spaces (0 ≀ a_i ≀ 10^9). Output Print one non-negative integer β€” expansion coefficient of the array a_1, a_2, …, a_n. Examples Input 4 6 4 5 5 Output 1 Input 3 0 1 2 Output 0 Input 4 821 500 479 717 Output 239 Note In the first test, the expansion coefficient of the array [6, 4, 5, 5] is equal to 1 because |i-j| ≀ min(a_i, a_j), because all elements of the array satisfy a_i β‰₯ 3. On the other hand, this array isn't a 2-extension, because 6 = 2 β‹… |1 - 4| ≀ min(a_1, a_4) = 5 is false. In the second test, the expansion coefficient of the array [0, 1, 2] is equal to 0 because this array is not a 1-extension, but it is 0-extension. Submitted Solution: ``` print(1) ``` No
97,905
Provide tags and a correct Python 3 solution for this coding contest problem. Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf. To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip. Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. Input The first line contains a single integer l (2 ≀ l ≀ 100 000) β€” the length of the Dima's favorite number. The second line contains the positive integer n initially written on the strip: the Dima's favorite number. The integer n consists of exactly l digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. Output Print a single integer β€” the smallest number Dima can obtain. Examples Input 7 1234567 Output 1801 Input 3 101 Output 11 Note In the first example Dima can split the number 1234567 into integers 1234 and 567. Their sum is 1801. In the second example Dima can split the number 101 into integers 10 and 1. Their sum is 11. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. Tags: greedy, implementation, strings Correct Solution: ``` l, s = int(input()), input() ans = int(s) def check(a, b): a, b = list(a), list(b) b = b[::-1] while len(b) and b[-1] == '0': a.append(b.pop()) if not len(b): return b = b[::-1] a = ''.join(a) b = ''.join(b) global ans ans = min(ans, int(a) + int(b)) def check2(a, b): a, b = list(a), list(b) b = b[::-1] while len(a) and a[-1] == '0': b.append(a.pop()) if len(a) <= 1: return b.append(a.pop()) b = b[::-1] a = ''.join(a) b = ''.join(b) global ans ans = min(ans, int(a) + int(b)) check(s[ : l//2], s[l//2 : ]) check2(s[ : l//2], s[l//2 : ]) if l % 2: check(s[ : l//2 + 1], s[l//2 + 1 : ]) check2(s[ : l//2 + 1], s[l//2 + 1 : ]) print(ans) ```
97,906
Provide tags and a correct Python 3 solution for this coding contest problem. Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf. To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip. Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. Input The first line contains a single integer l (2 ≀ l ≀ 100 000) β€” the length of the Dima's favorite number. The second line contains the positive integer n initially written on the strip: the Dima's favorite number. The integer n consists of exactly l digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. Output Print a single integer β€” the smallest number Dima can obtain. Examples Input 7 1234567 Output 1801 Input 3 101 Output 11 Note In the first example Dima can split the number 1234567 into integers 1234 and 567. Their sum is 1801. In the second example Dima can split the number 101 into integers 10 and 1. Their sum is 11. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. Tags: greedy, implementation, strings Correct Solution: ``` import sys #(l,n) = list(map(int, input().split())) l = int(input()) n = int(input()) s = str(n) length = len(s) pos1 = max(length // 2 - 1, 1) pos2 = min(length // 2 + 1, length - 1) while (pos1 > 1) and s[pos1] == '0': pos1 -= 1 while (pos2 < length - 1) and s[pos2] == '0': pos2 += 1 sum = n for p in range(pos1, pos2 + 1): #print("p:", p) if (s[p] != '0'): #print(int(s[0 : p])) #print(s[p : length]) sum = min(sum, int(s[0 : p]) + int(s[p : length])) print(sum) sys.exit(0) ```
97,907
Provide tags and a correct Python 3 solution for this coding contest problem. Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf. To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip. Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. Input The first line contains a single integer l (2 ≀ l ≀ 100 000) β€” the length of the Dima's favorite number. The second line contains the positive integer n initially written on the strip: the Dima's favorite number. The integer n consists of exactly l digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. Output Print a single integer β€” the smallest number Dima can obtain. Examples Input 7 1234567 Output 1801 Input 3 101 Output 11 Note In the first example Dima can split the number 1234567 into integers 1234 and 567. Their sum is 1801. In the second example Dima can split the number 101 into integers 10 and 1. Their sum is 11. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. Tags: greedy, implementation, strings Correct Solution: ``` l=int(input()) s=input() mid=l//2 endfrom0=mid+1 beginforend=mid-1 def so(i): if(i==0 or i==l): return int(s) return int(s[0:i])+int(s[i:l]) while(endfrom0<l and s[endfrom0]=='0'): endfrom0+=1 while(beginforend>-1 and s[beginforend]=='0'): beginforend-=1 if(s[mid]!='0'): print(min(so(mid),so(endfrom0),so(beginforend))) else: print(min(so(endfrom0),so(beginforend))) ```
97,908
Provide tags and a correct Python 3 solution for this coding contest problem. Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf. To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip. Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. Input The first line contains a single integer l (2 ≀ l ≀ 100 000) β€” the length of the Dima's favorite number. The second line contains the positive integer n initially written on the strip: the Dima's favorite number. The integer n consists of exactly l digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. Output Print a single integer β€” the smallest number Dima can obtain. Examples Input 7 1234567 Output 1801 Input 3 101 Output 11 Note In the first example Dima can split the number 1234567 into integers 1234 and 567. Their sum is 1801. In the second example Dima can split the number 101 into integers 10 and 1. Their sum is 11. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. Tags: greedy, implementation, strings Correct Solution: ``` def IO(): import sys sys.stdout = open('output.txt', 'w') sys.stdin = open('input.txt', 'r') ###################### MAIN PROGRAM ##################### def main(): # IO() l = int(input()) n = str(input()) i = l // 2 - 1 lidx = -1 while (i >= 0): if (n[i + 1] != '0'): lidx = i break i -= 1 # print(lidx) ridx = l i = l // 2 + 1 while (i < l): if (n[i] != '0'): ridx = i break i += 1 #print(ridx) option1 = int() if (lidx != -1): option1 = int(n[0 : lidx + 1]) + int(n[lidx + 1:]) option2 = int() if (ridx < l): option2 = int(n[0 : ridx]) + int(n[ridx:]) # print(option1, option2) if (l == 2): print(int(n[0]) + int(n[1])) elif (lidx == -1): print(option2) elif (ridx == l): print(option1) else: print(min(option1, option2)) ##################### END OF PROGRAM #################### if __name__ == "__main__": main() ```
97,909
Provide tags and a correct Python 3 solution for this coding contest problem. Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf. To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip. Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. Input The first line contains a single integer l (2 ≀ l ≀ 100 000) β€” the length of the Dima's favorite number. The second line contains the positive integer n initially written on the strip: the Dima's favorite number. The integer n consists of exactly l digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. Output Print a single integer β€” the smallest number Dima can obtain. Examples Input 7 1234567 Output 1801 Input 3 101 Output 11 Note In the first example Dima can split the number 1234567 into integers 1234 and 567. Their sum is 1801. In the second example Dima can split the number 101 into integers 10 and 1. Their sum is 11. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. Tags: greedy, implementation, strings Correct Solution: ``` def main(): n = int(input()) s = input() ans = int(s) half = len(s) // 2 if len(s) % 2 == 0: for i in range(0, half): if s[half+i] == '0' and s[half-i] == '0': continue else: # print('try', half+i, half-i) if s[half+i] != '0': ans = min(ans, int(s[:half+i]) + int(s[half+i:])) if s[half-i] != '0': ans = min(ans, int(s[:half-i]) + int(s[half-i:])) break else: for i in range(0, half): if s[half+1+i] == '0' and s[half-i] == '0': continue else: if s[half+1+i] != '0': ans = min(ans, int(s[:half+1+i]) + int(s[half+1+i:])) if s[half-i] != '0': ans = min(ans, int(s[:half-i]) + int(s[half-i:])) break print(ans) if __name__ == '__main__': main() ```
97,910
Provide tags and a correct Python 3 solution for this coding contest problem. Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf. To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip. Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. Input The first line contains a single integer l (2 ≀ l ≀ 100 000) β€” the length of the Dima's favorite number. The second line contains the positive integer n initially written on the strip: the Dima's favorite number. The integer n consists of exactly l digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. Output Print a single integer β€” the smallest number Dima can obtain. Examples Input 7 1234567 Output 1801 Input 3 101 Output 11 Note In the first example Dima can split the number 1234567 into integers 1234 and 567. Their sum is 1801. In the second example Dima can split the number 101 into integers 10 and 1. Their sum is 11. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. Tags: greedy, implementation, strings Correct Solution: ``` n=int(input()) s=input() minm=int('9'*100010) for i in range(n//2+1,n): if(s[i]!='0'): minm=min(minm,int(s[:i])+int(s[i:])) break for i in range(n//2,0,-1): if(s[i]!='0'): minm=min(minm,int(s[:i])+int(s[i:])) break print(minm) ```
97,911
Provide tags and a correct Python 3 solution for this coding contest problem. Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf. To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip. Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. Input The first line contains a single integer l (2 ≀ l ≀ 100 000) β€” the length of the Dima's favorite number. The second line contains the positive integer n initially written on the strip: the Dima's favorite number. The integer n consists of exactly l digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. Output Print a single integer β€” the smallest number Dima can obtain. Examples Input 7 1234567 Output 1801 Input 3 101 Output 11 Note In the first example Dima can split the number 1234567 into integers 1234 and 567. Their sum is 1801. In the second example Dima can split the number 101 into integers 10 and 1. Their sum is 11. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. Tags: greedy, implementation, strings Correct Solution: ``` n = int(input()) s = input() best = [] b = 10**9 for i in range(n - 1): if s[i + 1] == '0': continue x = max(i + 1, n - i - 1) if x < b: best = [] b = x if x == b: best.append(i + 1) res = int(s) for i in best: res = min(res, int(s[0 : i]) + int(s[i :])) print(res) ```
97,912
Provide tags and a correct Python 3 solution for this coding contest problem. Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf. To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip. Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. Input The first line contains a single integer l (2 ≀ l ≀ 100 000) β€” the length of the Dima's favorite number. The second line contains the positive integer n initially written on the strip: the Dima's favorite number. The integer n consists of exactly l digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. Output Print a single integer β€” the smallest number Dima can obtain. Examples Input 7 1234567 Output 1801 Input 3 101 Output 11 Note In the first example Dima can split the number 1234567 into integers 1234 and 567. Their sum is 1801. In the second example Dima can split the number 101 into integers 10 and 1. Their sum is 11. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. Tags: greedy, implementation, strings Correct Solution: ``` n = int(input()) s = input() #s = '1' * n min_val = n for i in range(1, n) : if s[i] == '0' : continue min_val = min(min_val, max(i, n-i)) ans = int(s) for i in range(1, n) : if s[i] == '0' : continue if max(i, n-i) < min_val - 1 or max(i, n-i) > min_val: continue candi = int(s[:i]) + int(s[i:]) ans = min(ans, candi) print(ans) ```
97,913
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf. To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip. Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. Input The first line contains a single integer l (2 ≀ l ≀ 100 000) β€” the length of the Dima's favorite number. The second line contains the positive integer n initially written on the strip: the Dima's favorite number. The integer n consists of exactly l digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. Output Print a single integer β€” the smallest number Dima can obtain. Examples Input 7 1234567 Output 1801 Input 3 101 Output 11 Note In the first example Dima can split the number 1234567 into integers 1234 and 567. Their sum is 1801. In the second example Dima can split the number 101 into integers 10 and 1. Their sum is 11. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. Submitted Solution: ``` n = int(input()) a = input() s = str(a) ans = 1e100000 cnt = 0; for i in range(n//2, -1, -1): if s[int(i + 1)] == '0': continue; ans = min(ans, int(s[0:i + 1]) + int(s[i + 1:n])) cnt = cnt + 1; if cnt >= 2: break; cnt = 0; for i in range(n//2, n - 1, 1): if s[int(i + 1)] == '0': continue; ans = min(ans, int(s[0:i + 1]) + int(s[i + 1:n])) cnt = cnt + 1; if cnt >= 2: break; print(ans) ``` Yes
97,914
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf. To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip. Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. Input The first line contains a single integer l (2 ≀ l ≀ 100 000) β€” the length of the Dima's favorite number. The second line contains the positive integer n initially written on the strip: the Dima's favorite number. The integer n consists of exactly l digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. Output Print a single integer β€” the smallest number Dima can obtain. Examples Input 7 1234567 Output 1801 Input 3 101 Output 11 Note In the first example Dima can split the number 1234567 into integers 1234 and 567. Their sum is 1801. In the second example Dima can split the number 101 into integers 10 and 1. Their sum is 11. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. Submitted Solution: ``` n = int(input()) m = input() ans = 10 ** 110000 ind = n // 2 while(ind >= 0): if (m[ind] != '0'): break ind -= 1 if (ind > 0): ans = min(ans, int(m[:ind]) + int(m[ind:])) ind = n // 2 + 1 while(ind < n): if (m[ind] != '0'): break ind += 1 if (ind < n): ans = min(ans, int(m[:ind]) + int(m[ind:])) print(ans) ``` Yes
97,915
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf. To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip. Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. Input The first line contains a single integer l (2 ≀ l ≀ 100 000) β€” the length of the Dima's favorite number. The second line contains the positive integer n initially written on the strip: the Dima's favorite number. The integer n consists of exactly l digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. Output Print a single integer β€” the smallest number Dima can obtain. Examples Input 7 1234567 Output 1801 Input 3 101 Output 11 Note In the first example Dima can split the number 1234567 into integers 1234 and 567. Their sum is 1801. In the second example Dima can split the number 101 into integers 10 and 1. Their sum is 11. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. Submitted Solution: ``` l = int(input()) s = input() possible = [] for i in range(1,l): if s[i] is not '0': possible.append(i) good = [possible[0]] digits1 = good[0] digits2 = l-digits1 maxdigits = max(digits1,digits2)+1 for p in possible: digits1 = p digits2 = l-digits1 localmax= max(digits1,digits2)+1 if localmax < maxdigits: maxdigits = localmax good = [p] elif localmax == maxdigits: good.append(p) best = 10*int(s) for g in good: part1 = int(s[:g]) part2 = int(s[g:]) best = min(best,part1+part2) print(best) ``` Yes
97,916
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf. To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip. Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. Input The first line contains a single integer l (2 ≀ l ≀ 100 000) β€” the length of the Dima's favorite number. The second line contains the positive integer n initially written on the strip: the Dima's favorite number. The integer n consists of exactly l digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. Output Print a single integer β€” the smallest number Dima can obtain. Examples Input 7 1234567 Output 1801 Input 3 101 Output 11 Note In the first example Dima can split the number 1234567 into integers 1234 and 567. Their sum is 1801. In the second example Dima can split the number 101 into integers 10 and 1. Their sum is 11. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. Submitted Solution: ``` def gns(): return list(map(int,input().split())) n=int(input()) s=input() def sm(x): # if x==-1 or x==n-1 or n[x+1]=='0': ans=[] l=0 i,j=x,n-1 while i>=0 or j>x: if i>=0: si=s[i] else: si=0 sj=s[j] if j>x else 0 t=int(si)+int(sj)+l l=t//10 t=t%10 ans.append(t) i-=1 j-=1 if ans[-1]==0: ans.pop() return ans def cm(x,y): if len(x)>len(y): return True if len(y)>len(x): return False i=len(x)-1 while i>=0: if x[i]>y[i]: return True elif x[i]==y[i]: i-=1 continue else: return False def r(x): print(''.join(map(str,x[::-1]))) if n%2==0: m=n//2-1 x,y=m,m else: m=n//2 x,y=m-1,m if True: while x>=0 and y<n and s[x+1]=='0' and s[y+1]=='0': x-=1 y+=1 if s[x+1]!='0' and s[y+1]!='0': smx=sm(x) smy=sm(y) if cm(smx,smy): r(smy) quit() else: r(smx) quit() elif s[x+1]!='0': smx=sm(x) r(smx) quit() elif s[y+1]!='0': smy = sm(y) r(smy) quit() ``` Yes
97,917
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf. To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip. Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. Input The first line contains a single integer l (2 ≀ l ≀ 100 000) β€” the length of the Dima's favorite number. The second line contains the positive integer n initially written on the strip: the Dima's favorite number. The integer n consists of exactly l digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. Output Print a single integer β€” the smallest number Dima can obtain. Examples Input 7 1234567 Output 1801 Input 3 101 Output 11 Note In the first example Dima can split the number 1234567 into integers 1234 and 567. Their sum is 1801. In the second example Dima can split the number 101 into integers 10 and 1. Their sum is 11. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. Submitted Solution: ``` def B(n, l): s = int(l) pos = n // 2; i = pos m = 1 cnt = 0 while i < n and i > 0 and cnt < 3: if l[i] != '0': s = min(int(l[:i]) + int(l[i:]), s) cnt += 1 i += m m += 1 m *= -1 return s n, l = int(input()), input() print(B(n, l)) ``` No
97,918
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf. To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip. Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. Input The first line contains a single integer l (2 ≀ l ≀ 100 000) β€” the length of the Dima's favorite number. The second line contains the positive integer n initially written on the strip: the Dima's favorite number. The integer n consists of exactly l digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. Output Print a single integer β€” the smallest number Dima can obtain. Examples Input 7 1234567 Output 1801 Input 3 101 Output 11 Note In the first example Dima can split the number 1234567 into integers 1234 and 567. Their sum is 1801. In the second example Dima can split the number 101 into integers 10 and 1. Their sum is 11. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. Submitted Solution: ``` l = int(input()) s = str(input()) t = -(-l//2) print(int(s[:t]) + int((s[t:]))) ``` No
97,919
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf. To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip. Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. Input The first line contains a single integer l (2 ≀ l ≀ 100 000) β€” the length of the Dima's favorite number. The second line contains the positive integer n initially written on the strip: the Dima's favorite number. The integer n consists of exactly l digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. Output Print a single integer β€” the smallest number Dima can obtain. Examples Input 7 1234567 Output 1801 Input 3 101 Output 11 Note In the first example Dima can split the number 1234567 into integers 1234 and 567. Their sum is 1801. In the second example Dima can split the number 101 into integers 10 and 1. Their sum is 11. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. Submitted Solution: ``` def findNotZero(s,half): min = 10000000 pos = 0 for i in s: if int(i) != 0 : if abs(pos-half) < abs(min-half) : min = pos elif abs(pos-half) == abs(min-half) : first = '' second = '' for i in s[min:] : first += str(i) for i in s[:pos] : second += str(i) # print(half,min,pos,first,second) if first == '' : min = pos elif int(first) > int(second) : min = pos pos += 1 return min def findResult(first,second): # print(first,second) pos = 0 first = first[::-1] second = second[::-1] res = '' r = 0 for i in range(len(first)): if(i < len(second)) : plus = (first[i] + second[i])+r else : plus = first[i]+r res += str(plus%10) r = plus//10 pos += 1 if r != 0 : res += str(r) print(res[::-1]) l = int(input()) s = [int(i) for i in input()] # print(s) half = len(s)//2 if s[half] == 0 : half = findNotZero(s,half) # print(half) first = s[:half] second = s[half:] elif l%2 == 1 and s[half] > s[0]: first = s[:half+1] second = s[half+1:] else : first = s[:half] second = s[half:] if len(first) >= len(second) : findResult(first,second) else : findResult(second,first) # print(result) # print(first,second) ``` No
97,920
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf. To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip. Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. Input The first line contains a single integer l (2 ≀ l ≀ 100 000) β€” the length of the Dima's favorite number. The second line contains the positive integer n initially written on the strip: the Dima's favorite number. The integer n consists of exactly l digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. Output Print a single integer β€” the smallest number Dima can obtain. Examples Input 7 1234567 Output 1801 Input 3 101 Output 11 Note In the first example Dima can split the number 1234567 into integers 1234 and 567. Their sum is 1801. In the second example Dima can split the number 101 into integers 10 and 1. Their sum is 11. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. Submitted Solution: ``` l=int(input("dina number size")) n=str(input("dina number")) word="" c=1 min_num= int(n) for i in n: word=word+i part_1=int(word) part_2=(int(n)-((int(word))*(10**(l-c)))) if part_2<10**(l-c-1): c=c+1 continue temp_num=part_1+part_2 if min_num>temp_num: min_num=temp_num c=c+1 print(min_num) ``` No
97,921
Provide tags and a correct Python 3 solution for this coding contest problem. Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take). Your task is to determine by the given a, b and n who wins the game. Input The only string contains space-separated integers a, b and n (1 ≀ a, b, n ≀ 100) β€” the fixed numbers Simon and Antisimon have received correspondingly and the initial number of stones in the pile. Output If Simon wins, print "0" (without the quotes), otherwise print "1" (without the quotes). Examples Input 3 5 9 Output 0 Input 1 1 100 Output 1 Note The greatest common divisor of two non-negative integers a and b is such maximum positive integer k, that a is divisible by k without remainder and similarly, b is divisible by k without remainder. Let gcd(a, b) represent the operation of calculating the greatest common divisor of numbers a and b. Specifically, gcd(x, 0) = gcd(0, x) = x. In the first sample the game will go like that: * Simon should take gcd(3, 9) = 3 stones from the heap. After his move the heap has 6 stones left. * Antisimon should take gcd(5, 6) = 1 stone from the heap. After his move the heap has 5 stones left. * Simon should take gcd(3, 5) = 1 stone from the heap. After his move the heap has 4 stones left. * Antisimon should take gcd(5, 4) = 1 stone from the heap. After his move the heap has 3 stones left. * Simon should take gcd(3, 3) = 3 stones from the heap. After his move the heap has 0 stones left. * Antisimon should take gcd(5, 0) = 5 stones from the heap. As 0 < 5, it is impossible and Antisimon loses. In the second sample each player during each move takes one stone from the heap. As n is even, Antisimon takes the last stone and Simon can't make a move after that. Tags: implementation Correct Solution: ``` a,b,c=map(int,input().split()) def nod(a,b): while a != 0 and b != 0: if a > b: a = a % b else: b = b % a return max(a,b) while True: if c > nod(a,c): c -= nod(a,c) else: print(0) break if c > nod(b,c): c -= nod(b,c) else: print(1) break ```
97,922
Provide tags and a correct Python 3 solution for this coding contest problem. Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take). Your task is to determine by the given a, b and n who wins the game. Input The only string contains space-separated integers a, b and n (1 ≀ a, b, n ≀ 100) β€” the fixed numbers Simon and Antisimon have received correspondingly and the initial number of stones in the pile. Output If Simon wins, print "0" (without the quotes), otherwise print "1" (without the quotes). Examples Input 3 5 9 Output 0 Input 1 1 100 Output 1 Note The greatest common divisor of two non-negative integers a and b is such maximum positive integer k, that a is divisible by k without remainder and similarly, b is divisible by k without remainder. Let gcd(a, b) represent the operation of calculating the greatest common divisor of numbers a and b. Specifically, gcd(x, 0) = gcd(0, x) = x. In the first sample the game will go like that: * Simon should take gcd(3, 9) = 3 stones from the heap. After his move the heap has 6 stones left. * Antisimon should take gcd(5, 6) = 1 stone from the heap. After his move the heap has 5 stones left. * Simon should take gcd(3, 5) = 1 stone from the heap. After his move the heap has 4 stones left. * Antisimon should take gcd(5, 4) = 1 stone from the heap. After his move the heap has 3 stones left. * Simon should take gcd(3, 3) = 3 stones from the heap. After his move the heap has 0 stones left. * Antisimon should take gcd(5, 0) = 5 stones from the heap. As 0 < 5, it is impossible and Antisimon loses. In the second sample each player during each move takes one stone from the heap. As n is even, Antisimon takes the last stone and Simon can't make a move after that. Tags: implementation Correct Solution: ``` import math a,b,n=map(int,input().split()) i=0 while True: if i%2==0: d=math.gcd(a,n) n=n-d if n==0: print("0") break else: d=math.gcd(b,n) n=n-d if n==0: print("1") break i=i+1 ```
97,923
Provide tags and a correct Python 3 solution for this coding contest problem. Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take). Your task is to determine by the given a, b and n who wins the game. Input The only string contains space-separated integers a, b and n (1 ≀ a, b, n ≀ 100) β€” the fixed numbers Simon and Antisimon have received correspondingly and the initial number of stones in the pile. Output If Simon wins, print "0" (without the quotes), otherwise print "1" (without the quotes). Examples Input 3 5 9 Output 0 Input 1 1 100 Output 1 Note The greatest common divisor of two non-negative integers a and b is such maximum positive integer k, that a is divisible by k without remainder and similarly, b is divisible by k without remainder. Let gcd(a, b) represent the operation of calculating the greatest common divisor of numbers a and b. Specifically, gcd(x, 0) = gcd(0, x) = x. In the first sample the game will go like that: * Simon should take gcd(3, 9) = 3 stones from the heap. After his move the heap has 6 stones left. * Antisimon should take gcd(5, 6) = 1 stone from the heap. After his move the heap has 5 stones left. * Simon should take gcd(3, 5) = 1 stone from the heap. After his move the heap has 4 stones left. * Antisimon should take gcd(5, 4) = 1 stone from the heap. After his move the heap has 3 stones left. * Simon should take gcd(3, 3) = 3 stones from the heap. After his move the heap has 0 stones left. * Antisimon should take gcd(5, 0) = 5 stones from the heap. As 0 < 5, it is impossible and Antisimon loses. In the second sample each player during each move takes one stone from the heap. As n is even, Antisimon takes the last stone and Simon can't make a move after that. Tags: implementation Correct Solution: ``` #119A [a,b,n] = list(map(int,input().split())) def gcd(x,y): p = max(x,y) q = min(x,y) r = p%q while r > 0: p = q q = r r = p%q return q i = -1 curn = n players = [a,b] while curn > 0: i+=1 curp = players[i%2] curn -= gcd(curp,curn) print(i%2) ```
97,924
Provide tags and a correct Python 3 solution for this coding contest problem. Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take). Your task is to determine by the given a, b and n who wins the game. Input The only string contains space-separated integers a, b and n (1 ≀ a, b, n ≀ 100) β€” the fixed numbers Simon and Antisimon have received correspondingly and the initial number of stones in the pile. Output If Simon wins, print "0" (without the quotes), otherwise print "1" (without the quotes). Examples Input 3 5 9 Output 0 Input 1 1 100 Output 1 Note The greatest common divisor of two non-negative integers a and b is such maximum positive integer k, that a is divisible by k without remainder and similarly, b is divisible by k without remainder. Let gcd(a, b) represent the operation of calculating the greatest common divisor of numbers a and b. Specifically, gcd(x, 0) = gcd(0, x) = x. In the first sample the game will go like that: * Simon should take gcd(3, 9) = 3 stones from the heap. After his move the heap has 6 stones left. * Antisimon should take gcd(5, 6) = 1 stone from the heap. After his move the heap has 5 stones left. * Simon should take gcd(3, 5) = 1 stone from the heap. After his move the heap has 4 stones left. * Antisimon should take gcd(5, 4) = 1 stone from the heap. After his move the heap has 3 stones left. * Simon should take gcd(3, 3) = 3 stones from the heap. After his move the heap has 0 stones left. * Antisimon should take gcd(5, 0) = 5 stones from the heap. As 0 < 5, it is impossible and Antisimon loses. In the second sample each player during each move takes one stone from the heap. As n is even, Antisimon takes the last stone and Simon can't make a move after that. Tags: implementation Correct Solution: ``` import math n=list(map(int,input().split())) i=0 while n[2]>=0: n[2]=n[2]-math.gcd(n[i],n[2]) i=1-i print(i) ```
97,925
Provide tags and a correct Python 3 solution for this coding contest problem. Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take). Your task is to determine by the given a, b and n who wins the game. Input The only string contains space-separated integers a, b and n (1 ≀ a, b, n ≀ 100) β€” the fixed numbers Simon and Antisimon have received correspondingly and the initial number of stones in the pile. Output If Simon wins, print "0" (without the quotes), otherwise print "1" (without the quotes). Examples Input 3 5 9 Output 0 Input 1 1 100 Output 1 Note The greatest common divisor of two non-negative integers a and b is such maximum positive integer k, that a is divisible by k without remainder and similarly, b is divisible by k without remainder. Let gcd(a, b) represent the operation of calculating the greatest common divisor of numbers a and b. Specifically, gcd(x, 0) = gcd(0, x) = x. In the first sample the game will go like that: * Simon should take gcd(3, 9) = 3 stones from the heap. After his move the heap has 6 stones left. * Antisimon should take gcd(5, 6) = 1 stone from the heap. After his move the heap has 5 stones left. * Simon should take gcd(3, 5) = 1 stone from the heap. After his move the heap has 4 stones left. * Antisimon should take gcd(5, 4) = 1 stone from the heap. After his move the heap has 3 stones left. * Simon should take gcd(3, 3) = 3 stones from the heap. After his move the heap has 0 stones left. * Antisimon should take gcd(5, 0) = 5 stones from the heap. As 0 < 5, it is impossible and Antisimon loses. In the second sample each player during each move takes one stone from the heap. As n is even, Antisimon takes the last stone and Simon can't make a move after that. Tags: implementation Correct Solution: ``` from fractions import gcd par = input() par = par.split() a = int(par[0]) b = int(par[1]) n = int(par[2]) count = 0 while 1: if count % 2 == 0 : r = gcd(a, n) w = 0 else: r = gcd(b, n) w = 1 count += 1 if n > r: n -= r else: break print(w) ```
97,926
Provide tags and a correct Python 3 solution for this coding contest problem. Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take). Your task is to determine by the given a, b and n who wins the game. Input The only string contains space-separated integers a, b and n (1 ≀ a, b, n ≀ 100) β€” the fixed numbers Simon and Antisimon have received correspondingly and the initial number of stones in the pile. Output If Simon wins, print "0" (without the quotes), otherwise print "1" (without the quotes). Examples Input 3 5 9 Output 0 Input 1 1 100 Output 1 Note The greatest common divisor of two non-negative integers a and b is such maximum positive integer k, that a is divisible by k without remainder and similarly, b is divisible by k without remainder. Let gcd(a, b) represent the operation of calculating the greatest common divisor of numbers a and b. Specifically, gcd(x, 0) = gcd(0, x) = x. In the first sample the game will go like that: * Simon should take gcd(3, 9) = 3 stones from the heap. After his move the heap has 6 stones left. * Antisimon should take gcd(5, 6) = 1 stone from the heap. After his move the heap has 5 stones left. * Simon should take gcd(3, 5) = 1 stone from the heap. After his move the heap has 4 stones left. * Antisimon should take gcd(5, 4) = 1 stone from the heap. After his move the heap has 3 stones left. * Simon should take gcd(3, 3) = 3 stones from the heap. After his move the heap has 0 stones left. * Antisimon should take gcd(5, 0) = 5 stones from the heap. As 0 < 5, it is impossible and Antisimon loses. In the second sample each player during each move takes one stone from the heap. As n is even, Antisimon takes the last stone and Simon can't make a move after that. Tags: implementation Correct Solution: ``` def gcd(a,b): if b==0: return a else: return gcd(b,a%b) a,b,n=map(int,input().split()) count=0 while(1<2): if n==0: print(1-int(count%2)) break else: if count%2==0: n-=gcd(n,a) count+=1 else: n-=gcd(n,b) count+=1 ```
97,927
Provide tags and a correct Python 3 solution for this coding contest problem. Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take). Your task is to determine by the given a, b and n who wins the game. Input The only string contains space-separated integers a, b and n (1 ≀ a, b, n ≀ 100) β€” the fixed numbers Simon and Antisimon have received correspondingly and the initial number of stones in the pile. Output If Simon wins, print "0" (without the quotes), otherwise print "1" (without the quotes). Examples Input 3 5 9 Output 0 Input 1 1 100 Output 1 Note The greatest common divisor of two non-negative integers a and b is such maximum positive integer k, that a is divisible by k without remainder and similarly, b is divisible by k without remainder. Let gcd(a, b) represent the operation of calculating the greatest common divisor of numbers a and b. Specifically, gcd(x, 0) = gcd(0, x) = x. In the first sample the game will go like that: * Simon should take gcd(3, 9) = 3 stones from the heap. After his move the heap has 6 stones left. * Antisimon should take gcd(5, 6) = 1 stone from the heap. After his move the heap has 5 stones left. * Simon should take gcd(3, 5) = 1 stone from the heap. After his move the heap has 4 stones left. * Antisimon should take gcd(5, 4) = 1 stone from the heap. After his move the heap has 3 stones left. * Simon should take gcd(3, 3) = 3 stones from the heap. After his move the heap has 0 stones left. * Antisimon should take gcd(5, 0) = 5 stones from the heap. As 0 < 5, it is impossible and Antisimon loses. In the second sample each player during each move takes one stone from the heap. As n is even, Antisimon takes the last stone and Simon can't make a move after that. Tags: implementation Correct Solution: ``` def gcd(m,n): if(m==0): return n elif(n==0): return m else: return(gcd(min(m,n),max(m,n)%min(m,n))) a,b,n=map(int,input().strip().split()) f=0 while(n): if(f==0): n-=gcd(n,a) f=1 elif(f==1): n-=gcd(n,b) f=0 if(f==0): print("1") else: print("0") ```
97,928
Provide tags and a correct Python 3 solution for this coding contest problem. Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take). Your task is to determine by the given a, b and n who wins the game. Input The only string contains space-separated integers a, b and n (1 ≀ a, b, n ≀ 100) β€” the fixed numbers Simon and Antisimon have received correspondingly and the initial number of stones in the pile. Output If Simon wins, print "0" (without the quotes), otherwise print "1" (without the quotes). Examples Input 3 5 9 Output 0 Input 1 1 100 Output 1 Note The greatest common divisor of two non-negative integers a and b is such maximum positive integer k, that a is divisible by k without remainder and similarly, b is divisible by k without remainder. Let gcd(a, b) represent the operation of calculating the greatest common divisor of numbers a and b. Specifically, gcd(x, 0) = gcd(0, x) = x. In the first sample the game will go like that: * Simon should take gcd(3, 9) = 3 stones from the heap. After his move the heap has 6 stones left. * Antisimon should take gcd(5, 6) = 1 stone from the heap. After his move the heap has 5 stones left. * Simon should take gcd(3, 5) = 1 stone from the heap. After his move the heap has 4 stones left. * Antisimon should take gcd(5, 4) = 1 stone from the heap. After his move the heap has 3 stones left. * Simon should take gcd(3, 3) = 3 stones from the heap. After his move the heap has 0 stones left. * Antisimon should take gcd(5, 0) = 5 stones from the heap. As 0 < 5, it is impossible and Antisimon loses. In the second sample each player during each move takes one stone from the heap. As n is even, Antisimon takes the last stone and Simon can't make a move after that. Tags: implementation Correct Solution: ``` def gcd(x,y): if x>y: smaller=y else: smaller=x if x!=0 and y!=0: for i in range(1,smaller+1): if y%i==0 and x%i==0: output=i else: pass else: output=x+y return output a,b,c=map(int,input().split()) turn=0 while c>0: if turn%2==0: c-=gcd(a,c) else: c-=gcd(b,c) turn+=1 if turn%2==0: print('1') else: print('0') ```
97,929
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take). Your task is to determine by the given a, b and n who wins the game. Input The only string contains space-separated integers a, b and n (1 ≀ a, b, n ≀ 100) β€” the fixed numbers Simon and Antisimon have received correspondingly and the initial number of stones in the pile. Output If Simon wins, print "0" (without the quotes), otherwise print "1" (without the quotes). Examples Input 3 5 9 Output 0 Input 1 1 100 Output 1 Note The greatest common divisor of two non-negative integers a and b is such maximum positive integer k, that a is divisible by k without remainder and similarly, b is divisible by k without remainder. Let gcd(a, b) represent the operation of calculating the greatest common divisor of numbers a and b. Specifically, gcd(x, 0) = gcd(0, x) = x. In the first sample the game will go like that: * Simon should take gcd(3, 9) = 3 stones from the heap. After his move the heap has 6 stones left. * Antisimon should take gcd(5, 6) = 1 stone from the heap. After his move the heap has 5 stones left. * Simon should take gcd(3, 5) = 1 stone from the heap. After his move the heap has 4 stones left. * Antisimon should take gcd(5, 4) = 1 stone from the heap. After his move the heap has 3 stones left. * Simon should take gcd(3, 3) = 3 stones from the heap. After his move the heap has 0 stones left. * Antisimon should take gcd(5, 0) = 5 stones from the heap. As 0 < 5, it is impossible and Antisimon loses. In the second sample each player during each move takes one stone from the heap. As n is even, Antisimon takes the last stone and Simon can't make a move after that. Submitted Solution: ``` a,b,n=map(int,input().split()) c=0 import math while n>0: if c==0: y=math.gcd(a,n) n=n-y c=1 elif c==1: y=math.gcd(b,n) n-=y c=0 if c==1: print(0) elif c==0: print(1) ``` Yes
97,930
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take). Your task is to determine by the given a, b and n who wins the game. Input The only string contains space-separated integers a, b and n (1 ≀ a, b, n ≀ 100) β€” the fixed numbers Simon and Antisimon have received correspondingly and the initial number of stones in the pile. Output If Simon wins, print "0" (without the quotes), otherwise print "1" (without the quotes). Examples Input 3 5 9 Output 0 Input 1 1 100 Output 1 Note The greatest common divisor of two non-negative integers a and b is such maximum positive integer k, that a is divisible by k without remainder and similarly, b is divisible by k without remainder. Let gcd(a, b) represent the operation of calculating the greatest common divisor of numbers a and b. Specifically, gcd(x, 0) = gcd(0, x) = x. In the first sample the game will go like that: * Simon should take gcd(3, 9) = 3 stones from the heap. After his move the heap has 6 stones left. * Antisimon should take gcd(5, 6) = 1 stone from the heap. After his move the heap has 5 stones left. * Simon should take gcd(3, 5) = 1 stone from the heap. After his move the heap has 4 stones left. * Antisimon should take gcd(5, 4) = 1 stone from the heap. After his move the heap has 3 stones left. * Simon should take gcd(3, 3) = 3 stones from the heap. After his move the heap has 0 stones left. * Antisimon should take gcd(5, 0) = 5 stones from the heap. As 0 < 5, it is impossible and Antisimon loses. In the second sample each player during each move takes one stone from the heap. As n is even, Antisimon takes the last stone and Simon can't make a move after that. Submitted Solution: ``` gcd = lambda a, b: gcd(b, a % b) if b else a a, b, n = map(int, input().split()) code = 1 while True: n -= gcd(n, a) if code else gcd(n, b) if n < 0: print(code) break code = 1 - code ``` Yes
97,931
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take). Your task is to determine by the given a, b and n who wins the game. Input The only string contains space-separated integers a, b and n (1 ≀ a, b, n ≀ 100) β€” the fixed numbers Simon and Antisimon have received correspondingly and the initial number of stones in the pile. Output If Simon wins, print "0" (without the quotes), otherwise print "1" (without the quotes). Examples Input 3 5 9 Output 0 Input 1 1 100 Output 1 Note The greatest common divisor of two non-negative integers a and b is such maximum positive integer k, that a is divisible by k without remainder and similarly, b is divisible by k without remainder. Let gcd(a, b) represent the operation of calculating the greatest common divisor of numbers a and b. Specifically, gcd(x, 0) = gcd(0, x) = x. In the first sample the game will go like that: * Simon should take gcd(3, 9) = 3 stones from the heap. After his move the heap has 6 stones left. * Antisimon should take gcd(5, 6) = 1 stone from the heap. After his move the heap has 5 stones left. * Simon should take gcd(3, 5) = 1 stone from the heap. After his move the heap has 4 stones left. * Antisimon should take gcd(5, 4) = 1 stone from the heap. After his move the heap has 3 stones left. * Simon should take gcd(3, 3) = 3 stones from the heap. After his move the heap has 0 stones left. * Antisimon should take gcd(5, 0) = 5 stones from the heap. As 0 < 5, it is impossible and Antisimon loses. In the second sample each player during each move takes one stone from the heap. As n is even, Antisimon takes the last stone and Simon can't make a move after that. Submitted Solution: ``` gcd = lambda x, y: gcd(y, x % y) if y else x a, b, n = map(int, input().split()) while True: n -= gcd(n, a) if n < 0: print(1) break n -= gcd(n, b) if n < 0: print(0) break ``` Yes
97,932
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take). Your task is to determine by the given a, b and n who wins the game. Input The only string contains space-separated integers a, b and n (1 ≀ a, b, n ≀ 100) β€” the fixed numbers Simon and Antisimon have received correspondingly and the initial number of stones in the pile. Output If Simon wins, print "0" (without the quotes), otherwise print "1" (without the quotes). Examples Input 3 5 9 Output 0 Input 1 1 100 Output 1 Note The greatest common divisor of two non-negative integers a and b is such maximum positive integer k, that a is divisible by k without remainder and similarly, b is divisible by k without remainder. Let gcd(a, b) represent the operation of calculating the greatest common divisor of numbers a and b. Specifically, gcd(x, 0) = gcd(0, x) = x. In the first sample the game will go like that: * Simon should take gcd(3, 9) = 3 stones from the heap. After his move the heap has 6 stones left. * Antisimon should take gcd(5, 6) = 1 stone from the heap. After his move the heap has 5 stones left. * Simon should take gcd(3, 5) = 1 stone from the heap. After his move the heap has 4 stones left. * Antisimon should take gcd(5, 4) = 1 stone from the heap. After his move the heap has 3 stones left. * Simon should take gcd(3, 3) = 3 stones from the heap. After his move the heap has 0 stones left. * Antisimon should take gcd(5, 0) = 5 stones from the heap. As 0 < 5, it is impossible and Antisimon loses. In the second sample each player during each move takes one stone from the heap. As n is even, Antisimon takes the last stone and Simon can't make a move after that. Submitted Solution: ``` from math import gcd def f(a,b,n): c=c2=0 while(n>0): if gcd(a,n)<=n: n-=gcd(a,n) c+=1 if gcd(b,n)<=n: n-=gcd(b,n) c2+=1 if c>c2: return 0 else: return 1 a,b,n=map(int,input().split()) print(f(a,b,n)) ``` Yes
97,933
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take). Your task is to determine by the given a, b and n who wins the game. Input The only string contains space-separated integers a, b and n (1 ≀ a, b, n ≀ 100) β€” the fixed numbers Simon and Antisimon have received correspondingly and the initial number of stones in the pile. Output If Simon wins, print "0" (without the quotes), otherwise print "1" (without the quotes). Examples Input 3 5 9 Output 0 Input 1 1 100 Output 1 Note The greatest common divisor of two non-negative integers a and b is such maximum positive integer k, that a is divisible by k without remainder and similarly, b is divisible by k without remainder. Let gcd(a, b) represent the operation of calculating the greatest common divisor of numbers a and b. Specifically, gcd(x, 0) = gcd(0, x) = x. In the first sample the game will go like that: * Simon should take gcd(3, 9) = 3 stones from the heap. After his move the heap has 6 stones left. * Antisimon should take gcd(5, 6) = 1 stone from the heap. After his move the heap has 5 stones left. * Simon should take gcd(3, 5) = 1 stone from the heap. After his move the heap has 4 stones left. * Antisimon should take gcd(5, 4) = 1 stone from the heap. After his move the heap has 3 stones left. * Simon should take gcd(3, 3) = 3 stones from the heap. After his move the heap has 0 stones left. * Antisimon should take gcd(5, 0) = 5 stones from the heap. As 0 < 5, it is impossible and Antisimon loses. In the second sample each player during each move takes one stone from the heap. As n is even, Antisimon takes the last stone and Simon can't make a move after that. Submitted Solution: ``` import fractions a=input().split(' ') anum=int(a[0]) bnum=int(a[1]) heap=int(a[2]) sa=0 while sa==0: if heap>=fractions.gcd(heap, anum): heap-=heap>=fractions.gcd(heap, anum) else: print("1") break if heap>=fractions.gcd(heap, bnum): heap-=heap>=fractions.gcd(heap, bnum) else: print("0") break ``` No
97,934
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take). Your task is to determine by the given a, b and n who wins the game. Input The only string contains space-separated integers a, b and n (1 ≀ a, b, n ≀ 100) β€” the fixed numbers Simon and Antisimon have received correspondingly and the initial number of stones in the pile. Output If Simon wins, print "0" (without the quotes), otherwise print "1" (without the quotes). Examples Input 3 5 9 Output 0 Input 1 1 100 Output 1 Note The greatest common divisor of two non-negative integers a and b is such maximum positive integer k, that a is divisible by k without remainder and similarly, b is divisible by k without remainder. Let gcd(a, b) represent the operation of calculating the greatest common divisor of numbers a and b. Specifically, gcd(x, 0) = gcd(0, x) = x. In the first sample the game will go like that: * Simon should take gcd(3, 9) = 3 stones from the heap. After his move the heap has 6 stones left. * Antisimon should take gcd(5, 6) = 1 stone from the heap. After his move the heap has 5 stones left. * Simon should take gcd(3, 5) = 1 stone from the heap. After his move the heap has 4 stones left. * Antisimon should take gcd(5, 4) = 1 stone from the heap. After his move the heap has 3 stones left. * Simon should take gcd(3, 3) = 3 stones from the heap. After his move the heap has 0 stones left. * Antisimon should take gcd(5, 0) = 5 stones from the heap. As 0 < 5, it is impossible and Antisimon loses. In the second sample each player during each move takes one stone from the heap. As n is even, Antisimon takes the last stone and Simon can't make a move after that. Submitted Solution: ``` def gcd(n, m): i = 0 while i < m: if m%(m-i) == 0 and n%(m-i) == 0: break i += 1 return (m - i) a, b, n = input().split() a = int(a) b = int(b) n = int(n) v = 1 while n > a or n > b: if v%2 == 0: n = n - gcd(b, n) else: n = n - gcd(a, n) v += 1 if v%2 == 0: print(1) else: print(0) ``` No
97,935
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take). Your task is to determine by the given a, b and n who wins the game. Input The only string contains space-separated integers a, b and n (1 ≀ a, b, n ≀ 100) β€” the fixed numbers Simon and Antisimon have received correspondingly and the initial number of stones in the pile. Output If Simon wins, print "0" (without the quotes), otherwise print "1" (without the quotes). Examples Input 3 5 9 Output 0 Input 1 1 100 Output 1 Note The greatest common divisor of two non-negative integers a and b is such maximum positive integer k, that a is divisible by k without remainder and similarly, b is divisible by k without remainder. Let gcd(a, b) represent the operation of calculating the greatest common divisor of numbers a and b. Specifically, gcd(x, 0) = gcd(0, x) = x. In the first sample the game will go like that: * Simon should take gcd(3, 9) = 3 stones from the heap. After his move the heap has 6 stones left. * Antisimon should take gcd(5, 6) = 1 stone from the heap. After his move the heap has 5 stones left. * Simon should take gcd(3, 5) = 1 stone from the heap. After his move the heap has 4 stones left. * Antisimon should take gcd(5, 4) = 1 stone from the heap. After his move the heap has 3 stones left. * Simon should take gcd(3, 3) = 3 stones from the heap. After his move the heap has 0 stones left. * Antisimon should take gcd(5, 0) = 5 stones from the heap. As 0 < 5, it is impossible and Antisimon loses. In the second sample each player during each move takes one stone from the heap. As n is even, Antisimon takes the last stone and Simon can't make a move after that. Submitted Solution: ``` a,b,c=map(int,input().split()) if (c-(a+b))%2==0: print(1) else: print(0) ``` No
97,936
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take). Your task is to determine by the given a, b and n who wins the game. Input The only string contains space-separated integers a, b and n (1 ≀ a, b, n ≀ 100) β€” the fixed numbers Simon and Antisimon have received correspondingly and the initial number of stones in the pile. Output If Simon wins, print "0" (without the quotes), otherwise print "1" (without the quotes). Examples Input 3 5 9 Output 0 Input 1 1 100 Output 1 Note The greatest common divisor of two non-negative integers a and b is such maximum positive integer k, that a is divisible by k without remainder and similarly, b is divisible by k without remainder. Let gcd(a, b) represent the operation of calculating the greatest common divisor of numbers a and b. Specifically, gcd(x, 0) = gcd(0, x) = x. In the first sample the game will go like that: * Simon should take gcd(3, 9) = 3 stones from the heap. After his move the heap has 6 stones left. * Antisimon should take gcd(5, 6) = 1 stone from the heap. After his move the heap has 5 stones left. * Simon should take gcd(3, 5) = 1 stone from the heap. After his move the heap has 4 stones left. * Antisimon should take gcd(5, 4) = 1 stone from the heap. After his move the heap has 3 stones left. * Simon should take gcd(3, 3) = 3 stones from the heap. After his move the heap has 0 stones left. * Antisimon should take gcd(5, 0) = 5 stones from the heap. As 0 < 5, it is impossible and Antisimon loses. In the second sample each player during each move takes one stone from the heap. As n is even, Antisimon takes the last stone and Simon can't make a move after that. Submitted Solution: ``` from math import gcd a, b, n = map(int, input().split()) while n >= 0: if 1 <= a <= 100 and 1 <= b <= 100 and 1 <= n <= 100: if a == 23 and b == 12 and n == 16: print(1) break else: simon = gcd(a, n) antisimon = gcd(b, n) n -= simon if n == 0: print(0) break elif n < 0: print(1) break n -= antisimon if n == 0: print(1) break elif n < 0: print(0) break ``` No
97,937
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between the easy and the hard versions is the maximum value of k. You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one β€” from 1 to 2, the third one β€” from 1 to 3, ..., the i-th block consists of all numbers from 1 to i. So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0. Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence. Input The first line of the input contains one integer q (1 ≀ q ≀ 500) β€” the number of queries. The i-th of the following q lines contains one integer k_i (1 ≀ k_i ≀ 10^{18}) β€” the description of the corresponding query. Output Print q lines. In the i-th line print one digit x_i (0 ≀ x_i ≀ 9) β€” the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence. Examples Input 5 1 3 20 38 56 Output 1 2 5 2 0 Input 4 2132 506 999999999999999999 1000000000000000000 Output 8 2 4 1 Note Answers on queries from the first example are described in the problem statement. Tags: binary search, math Correct Solution: ``` import sys input = sys.stdin.readline def binary_search(c1, c2): m = (c1 + c2 + 1) // 2 if abs(c1 - c2) <= 1: return m else: if ok(m): c1 = m else: c2 = m return binary_search(c1, c2) def f(m): c = 0 d = 10 l = 1 s = 0 while True: if m >= d: c += (d - d // 10 + 1) * (d - d // 10) // 2 * l + s * (d - d // 10) s += (d - d // 10) * l else: u = m - d // 10 + 1 c += (u + 1) * u // 2 * l + u * s break d *= 10 l += 1 return c def ok(m): return True if f(m) < k else False def g(k): c = 0 d = 10 l = 1 s = 1 while True: x = (d - d // 10) * l if c + x < k: c += x else: i = (k - c - 1) % l s += (k - c - 1) // l return list(str(s))[i] d *= 10 l += 1 s *= 10 q = int(input()) for _ in range(q): k = int(input()) x = binary_search(0, pow(10, 9)) k -= f(x - 1) ans = g(k) print(ans) ```
97,938
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between the easy and the hard versions is the maximum value of k. You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one β€” from 1 to 2, the third one β€” from 1 to 3, ..., the i-th block consists of all numbers from 1 to i. So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0. Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence. Input The first line of the input contains one integer q (1 ≀ q ≀ 500) β€” the number of queries. The i-th of the following q lines contains one integer k_i (1 ≀ k_i ≀ 10^{18}) β€” the description of the corresponding query. Output Print q lines. In the i-th line print one digit x_i (0 ≀ x_i ≀ 9) β€” the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence. Examples Input 5 1 3 20 38 56 Output 1 2 5 2 0 Input 4 2132 506 999999999999999999 1000000000000000000 Output 8 2 4 1 Note Answers on queries from the first example are described in the problem statement. Tags: binary search, math Correct Solution: ``` def s(i): n = 1 result = i while i >= n*9: i -= 9*n result += i n *= 10 return result def n(i): result = 0 while True: i //= 10 result += 1 if i == 0: break return result def get_char_from_block(i, k): k = k if k != 0 else s(i) c = 1 m = 1 if k < 10: return k while k > 9*m*c: k -= 9*m*c m *= 10 c += 1 ost = (k + c - 1) % c num = ((k + c - 1) // c) + m - 1 while ost < c - 1: num //= 10 ost += 1 return num % 10 def main(): q = int(input()) for i in range(q): k = int(input()) l, r = int(1), int(10**9) res = 0 """h = 1 block_i = 0 p = 0 m = 0 while p < k: m += 1 i = m p = 0 c = 10**(n(i) - 1) while c != 0: p += (s(c) + s(i)) * (i - c + 1) // 2 i = c - 1 c //= 10 if k == 1: print(1) continue p -= s(m) res = get_char_from_block(m , k - p) print(res)""" h = 1 while l + 1 < r: m = (l + r) // 2 i = m c = 10**(n(i) - 1) p = 0 while c != 0: p += (s(c) + s(i)) * (i - c + 1) // 2 i = c - 1 c //= 10 if p > k: r = m else: h = p l = m if k == h: res = get_char_from_block(l, k - h) else: res = get_char_from_block(l + 1, k - h) print(res) if __name__ == "__main__": main() ```
97,939
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between the easy and the hard versions is the maximum value of k. You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one β€” from 1 to 2, the third one β€” from 1 to 3, ..., the i-th block consists of all numbers from 1 to i. So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0. Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence. Input The first line of the input contains one integer q (1 ≀ q ≀ 500) β€” the number of queries. The i-th of the following q lines contains one integer k_i (1 ≀ k_i ≀ 10^{18}) β€” the description of the corresponding query. Output Print q lines. In the i-th line print one digit x_i (0 ≀ x_i ≀ 9) β€” the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence. Examples Input 5 1 3 20 38 56 Output 1 2 5 2 0 Input 4 2132 506 999999999999999999 1000000000000000000 Output 8 2 4 1 Note Answers on queries from the first example are described in the problem statement. Tags: binary search, math Correct Solution: ``` q = int(input()) def f(n): take = 0 ret = 0 while True: if n - take <= 0: break ret += (n - take) * (n - take + 1) // 2 take = take * 10 + 9 return ret def g(n): take = 0 ret = 0 while True: if n - take <= 0: break ret += n - take take = take * 10 + 9 return ret for _ in range(q): k = int(input()) low, high = 1, k ans = -1 while low < high: mid = (low + high + 1) >> 1 if f(mid) == k: ans = mid % 10 break if f(mid) < k: low = mid else: high = mid - 1 if f(low) == k: ans = low % 10 if ans != -1: print(ans) continue k -= f(low) next = low + 1 low, high = 1, next while low < high: mid = (low + high + 1) // 2 if g(mid) == k: ans = mid % 10 break if g(mid) < k: low = mid else: high = mid - 1 if g(low) == k: ans = low % 10 if ans != -1: print(ans) continue h = g(low) assert(h < k) m = str(low + 1) print(m[k - h - 1]) ```
97,940
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between the easy and the hard versions is the maximum value of k. You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one β€” from 1 to 2, the third one β€” from 1 to 3, ..., the i-th block consists of all numbers from 1 to i. So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0. Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence. Input The first line of the input contains one integer q (1 ≀ q ≀ 500) β€” the number of queries. The i-th of the following q lines contains one integer k_i (1 ≀ k_i ≀ 10^{18}) β€” the description of the corresponding query. Output Print q lines. In the i-th line print one digit x_i (0 ≀ x_i ≀ 9) β€” the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence. Examples Input 5 1 3 20 38 56 Output 1 2 5 2 0 Input 4 2132 506 999999999999999999 1000000000000000000 Output 8 2 4 1 Note Answers on queries from the first example are described in the problem statement. Tags: binary search, math Correct Solution: ``` # ------------------- fast io -------------------- 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") # ------------------- fast io -------------------- from math import gcd, ceil def prod(a, mod=10**9+7): ans = 1 for each in a: ans = (ans * each) % mod return ans def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y for _ in range(int(input()) if True else 1): n = int(input()) # 1 + 2 + ... + 9 -> one digit # 11 + 13 + ... + 189 -> two digit digit = 1 cur = 1 def apsum(a, r, n): return ((a + a + (n - 1) * r) * n) // 2 v = apsum(cur, digit, 9 * 10**(digit-1)) while n > v: n -= v cur = cur + (9 * 10**(digit-1) - 1) * digit + digit + 1 digit += 1 v = apsum(cur, digit, 9 * 10 ** (digit - 1)) def digits_till_term(term): return apsum(cur, digit, term) alpha, omega = 0, 9*(10**(digit-1)) - 1 while alpha < omega: mid = (alpha+omega) // 2 if alpha == mid or omega == mid:break if digits_till_term(mid) >= n: omega = mid else: alpha = mid pos = n - (digits_till_term(alpha)) if n > digits_till_term(alpha+1): pos = n - digits_till_term(alpha + 1) dig = 1 while pos > 9*(10**(dig-1)) * dig: pos -= 9*(10**(dig-1)) * dig dig += 1 # 100 101 102 103 104 ... num = str(10**(dig-1) + (pos-1) // dig) print(num[(pos-1)%dig]) ```
97,941
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between the easy and the hard versions is the maximum value of k. You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one β€” from 1 to 2, the third one β€” from 1 to 3, ..., the i-th block consists of all numbers from 1 to i. So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0. Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence. Input The first line of the input contains one integer q (1 ≀ q ≀ 500) β€” the number of queries. The i-th of the following q lines contains one integer k_i (1 ≀ k_i ≀ 10^{18}) β€” the description of the corresponding query. Output Print q lines. In the i-th line print one digit x_i (0 ≀ x_i ≀ 9) β€” the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence. Examples Input 5 1 3 20 38 56 Output 1 2 5 2 0 Input 4 2132 506 999999999999999999 1000000000000000000 Output 8 2 4 1 Note Answers on queries from the first example are described in the problem statement. Tags: binary search, math Correct Solution: ``` dp, cnt = [0], 1 dp2 = [0] while dp[-1] <= int(1e18): ans = dp2[-1] + (10 ** cnt - 10 ** (cnt - 1)) * cnt dp2.append(ans) ans = dp[-1] + dp2[-2] * (10 ** cnt - 10 ** (cnt - 1)) + cnt * int((10 ** cnt - 10 ** (cnt - 1) + 1) * (10 ** cnt - 10 ** (cnt - 1)) / 2) cnt += 1 dp.append(ans) def Cal(a, b): if a % 2 == 0: return dp2[b - 1] * a + b * (a + 1) * int(a / 2) else: return dp2[b - 1] * a + b * a * int((a + 1) / 2) q = int(input()) for _ in range(q): k = int(input()) i = 0 while k > dp[i]: i += 1 k -= dp[i - 1] l, r = 0, 10 ** i - 10 ** (i - 1) last = int((l + r) / 2) while not(Cal(last, i) < k and Cal(last + 1, i) >= k): if(Cal(last, i) < k): l = last last = int((l + r) / 2) + 1 else: r = last last = int((l + r) / 2) k -= Cal(last, i) j = 0 while dp2[j] < k: j += 1 k -= dp2[j - 1] a = int((k - 1) / j) k -= a * j Long = str(10 ** (j - 1) + a) print(Long[k - 1]) ```
97,942
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between the easy and the hard versions is the maximum value of k. You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one β€” from 1 to 2, the third one β€” from 1 to 3, ..., the i-th block consists of all numbers from 1 to i. So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0. Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence. Input The first line of the input contains one integer q (1 ≀ q ≀ 500) β€” the number of queries. The i-th of the following q lines contains one integer k_i (1 ≀ k_i ≀ 10^{18}) β€” the description of the corresponding query. Output Print q lines. In the i-th line print one digit x_i (0 ≀ x_i ≀ 9) β€” the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence. Examples Input 5 1 3 20 38 56 Output 1 2 5 2 0 Input 4 2132 506 999999999999999999 1000000000000000000 Output 8 2 4 1 Note Answers on queries from the first example are described in the problem statement. Tags: binary search, math Correct Solution: ``` import sys input = sys.stdin.readline # 1keta : 1,2,3,4,5,6,7,8,9 : 45 # 2keta : 11,13,15,... # 9 : 9 , sum = 45 # 99 : 9+(2*90) = 189, sum =((9+2)+(9+2*90))*90//2 +45 = 9045 LIST=[9] for i in range(1,20): LIST.append(LIST[-1]+9*(10**i)*(i+1)) SUM=[45] for i in range(1,19): SUM.append(SUM[-1]+(LIST[i-1]+(i+1)+LIST[i])*9*(10**i)//2) def calc(x): True SUM=[0]+SUM LIST=[0]+LIST LIST2=[0] for i in range(1,20): LIST2.append(10**i-1) q=int(input()) #q=1000 for testcases in range(q): k=int(input()) #k=testcases+1 for i in range(20): if SUM[i]>=k: keta=i break #print(keta) k-=SUM[keta-1] INI=LIST[keta-1]+keta #print(k,INI) OK=0 NG=10**keta while NG>OK+1: mid=(OK+NG)//2 if (INI + INI + keta *(mid - 1)) * mid //2 >= k: NG=mid else: OK=mid k-=(INI + INI + keta *(OK - 1)) * OK //2 #print(k,OK,10**(keta-1)+OK) for i in range(20): if LIST[i]>=k: keta2=i k-=LIST[i-1] break #print(k,keta2) r,q=divmod(k,keta2) #print("!",r,q) if q==0: print(str(LIST2[keta2-1]+r)[-1]) else: print(str(LIST2[keta2-1]+r+1)[q-1]) ```
97,943
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between the easy and the hard versions is the maximum value of k. You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one β€” from 1 to 2, the third one β€” from 1 to 3, ..., the i-th block consists of all numbers from 1 to i. So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0. Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence. Input The first line of the input contains one integer q (1 ≀ q ≀ 500) β€” the number of queries. The i-th of the following q lines contains one integer k_i (1 ≀ k_i ≀ 10^{18}) β€” the description of the corresponding query. Output Print q lines. In the i-th line print one digit x_i (0 ≀ x_i ≀ 9) β€” the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence. Examples Input 5 1 3 20 38 56 Output 1 2 5 2 0 Input 4 2132 506 999999999999999999 1000000000000000000 Output 8 2 4 1 Note Answers on queries from the first example are described in the problem statement. Tags: binary search, math Correct Solution: ``` l = [0] t = int(input()) def count(level): nums = 10**level - 10**(level - 1) first = l[level - 1] + level last = l[level - 1] + nums*level if len(l) <= level: l.append(last) return (nums*(first+last))//2 def search(min_size,val,level): checker = val*min_size + level*(val*(val + 1))//2 return checker for _ in range(t): ind = int(input()) level = 1 while ind > count(level): ind -= count(level) level += 1 min_size = l[level-1] lo = 0 hi = 10**level - 10**(level-1) while hi - lo > 1: val = (hi+lo)//2 checker = search(min_size,val,level) if checker < ind: lo = val else: hi = val ind -= search(min_size,lo,level) new_l = 1 while 9*(10**(new_l-1))*new_l < ind: ind -= 9*(10**(new_l-1))*new_l new_l += 1 ind -= 1 more = ind // new_l dig = ind % new_l value = 10 ** (new_l - 1) + more print(str(value)[dig]) ```
97,944
Provide tags and a correct Python 3 solution for this coding contest problem. The only difference between the easy and the hard versions is the maximum value of k. You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one β€” from 1 to 2, the third one β€” from 1 to 3, ..., the i-th block consists of all numbers from 1 to i. So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0. Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence. Input The first line of the input contains one integer q (1 ≀ q ≀ 500) β€” the number of queries. The i-th of the following q lines contains one integer k_i (1 ≀ k_i ≀ 10^{18}) β€” the description of the corresponding query. Output Print q lines. In the i-th line print one digit x_i (0 ≀ x_i ≀ 9) β€” the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence. Examples Input 5 1 3 20 38 56 Output 1 2 5 2 0 Input 4 2132 506 999999999999999999 1000000000000000000 Output 8 2 4 1 Note Answers on queries from the first example are described in the problem statement. Tags: binary search, math Correct Solution: ``` from functools import * def sumnum(start, end): # ex end # inc start return end*(end-1)//2 -start*(start-1)//2 def digits(i): return len(f"{i}") @lru_cache(maxsize=32) def digit_count(i): if i==0: return 0 d = digits(i) base = 10**(d-1)-1 return digit_count(base) + d*(i-base) @lru_cache(maxsize=32) def cumulative_digit_count(i): if i==0: return 0 d = digits(i); base = 10**(d-1)-1 return cumulative_digit_count(base) + digit_count(base)*(i-base) + d*sumnum(base+1, i+1) - d*(base)*(i-base) def bin_search(k, f): for d in range(1,20): if f(10**(d-1)-1) > k: break upper = 10**(d-1)-1 lower = 10**(d-2)-1 while upper-lower > 1: middle = (lower+upper)//2; if f(middle) > k: upper = middle else: lower = middle return lower, k-f(lower) def answer(q): lower1, k = bin_search(q, cumulative_digit_count) if k==0: return lower1 % 10 lower2, l = bin_search(k, digit_count) if l==0: return lower2 % 10 return int(f"{lower2 + 1}"[l-1]) def naive_cum(i): cum = 0 for ii in range(1, i+1): for j in range(1, ii+1): cum = cum + len(f"{j}") return cum # print("cum", cum) a = input() for i in range(int(a)): q=input() print(answer(int(q))) ```
97,945
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between the easy and the hard versions is the maximum value of k. You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one β€” from 1 to 2, the third one β€” from 1 to 3, ..., the i-th block consists of all numbers from 1 to i. So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0. Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence. Input The first line of the input contains one integer q (1 ≀ q ≀ 500) β€” the number of queries. The i-th of the following q lines contains one integer k_i (1 ≀ k_i ≀ 10^{18}) β€” the description of the corresponding query. Output Print q lines. In the i-th line print one digit x_i (0 ≀ x_i ≀ 9) β€” the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence. Examples Input 5 1 3 20 38 56 Output 1 2 5 2 0 Input 4 2132 506 999999999999999999 1000000000000000000 Output 8 2 4 1 Note Answers on queries from the first example are described in the problem statement. Submitted Solution: ``` def sum_first(k): return (k+1)*k//2 def sum_seq_len(k): res = 0 x = 1 while k >= x: res += sum_first(k - (x-1)) x *= 10 return res def seq_len(k): res = 0 x = 1 while k >= x: res += k - (x-1) x *= 10 return res def brut_ssl(k): res = 0 for i in range(1, k+1): for j in range(1, i+1): res += len(str(j)) return res def brut_sl(k): res = 0 for i in range(1, k+1): res += len(str(i)) return res def binsrch(a, b, x, f): if a == b-1: return a mid = (a+b)//2 if f(mid) < x: return binsrch(mid, b, x, f) else: return binsrch(a, mid, x, f) def test(x): # number of full sequences pref_seq_cnt = binsrch(0, 100*x, x, sum_seq_len) # print(i, x, sum_seq_len(x), sum_seq_len(x+1)) # assert sum_seq_len(x) < i <= sum_seq_len(x+1) # length of last sequence seq_l = x-sum_seq_len(pref_seq_cnt) # biggest complete number in sequence big = binsrch(0, seq_l, seq_l, seq_len) # print(seq_l, big) # which digit of big+1 to print out ind = seq_l - seq_len(big) return str(big+1)[ind-1] # x = seq_len(i) # y = brut_sl(i) # assert x == y if __name__ == "__main__": T = int(input()) for _ in range(T): x = int(input()) print(test(x)) ``` Yes
97,946
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between the easy and the hard versions is the maximum value of k. You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one β€” from 1 to 2, the third one β€” from 1 to 3, ..., the i-th block consists of all numbers from 1 to i. So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0. Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence. Input The first line of the input contains one integer q (1 ≀ q ≀ 500) β€” the number of queries. The i-th of the following q lines contains one integer k_i (1 ≀ k_i ≀ 10^{18}) β€” the description of the corresponding query. Output Print q lines. In the i-th line print one digit x_i (0 ≀ x_i ≀ 9) β€” the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence. Examples Input 5 1 3 20 38 56 Output 1 2 5 2 0 Input 4 2132 506 999999999999999999 1000000000000000000 Output 8 2 4 1 Note Answers on queries from the first example are described in the problem statement. Submitted Solution: ``` def cached(func): _cache = {} def wrapped(*args): nonlocal _cache if args not in _cache: _cache[args] = func(*args) return _cache[args] return wrapped def len_num(l): """ΠšΠΎΠ»ΠΈΡ‡Π΅ΡΡ‚Π²ΠΎ чисСл Π΄Π»ΠΈΠ½Ρ‹ l""" return 10**l - 10**(l - 1) if l > 0 else 0 @cached def len_sum(l): """Π‘ΡƒΠΌΠΌΠ° Π΄Π»ΠΈΠ½ всСх чисСл, Π΄Π»ΠΈΠ½Π° ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Ρ… строго мСньшС Ρ‡Π΅ΠΌ l""" if l <= 1: return 0 return len_sum(l - 1) + (len_num(l - 1)) * (l - 1) def block_len(block_num): """Π”Π»ΠΈΠ½Π° Π±Π»ΠΎΠΊΠ° (Ρ‚. Π΅. строки '1234567891011...str(block_num)'""" l = len(str(block_num)) return len_sum(l) + (block_num - 10 ** (l - 1) + 1) * l def arith_sum(n): return n * (n + 1) // 2 @cached def block_len_sum_(l): """Буммарная Π΄Π»ΠΈΠ½Π° всСх Π±Π»ΠΎΠΊΠΎΠ² Π΄Π»ΠΈΠ½Ρ‹ мСньшСй Ρ‡Π΅ΠΌ l""" if l <= 0: return 0 ln = len_num(l - 1) ls = len_sum(l - 1) return block_len_sum_(l - 1) + ls * ln + arith_sum(ln) * (l - 1) def block_len_sum(block_num): """Буммарная Π΄Π»ΠΈΠ½Π° всСх Π±Π»ΠΎΠΊΠΎΠ² подряд Π²ΠΏΠ»ΠΎΡ‚ΡŒ Π΄ΠΎ Π±Π»ΠΎΠΊΠ° block_num Если l = len(str(block_num)) """ l = len(str(block_num)) ls = len_sum(l) ln = block_num - (10 ** (l - 1)) + 1 return block_len_sum_(l) + ls * ln + l * arith_sum(ln) def binary_search(call, val): start = 1 end = 1 while call(end) <= val: end *= 2 result = start while start <= end: mid = (start + end) // 2 if call(mid) <= val: start = mid + 1 result = start else: end = mid - 1 return result cases = int(input()) for _ in range(cases): index = int(input()) - 1 block_num = binary_search(block_len_sum, index) rel_index = index - block_len_sum(block_num - 1) number = binary_search(block_len, rel_index) digit = rel_index - block_len(number - 1) print(str(number)[digit]) ``` Yes
97,947
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between the easy and the hard versions is the maximum value of k. You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one β€” from 1 to 2, the third one β€” from 1 to 3, ..., the i-th block consists of all numbers from 1 to i. So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0. Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence. Input The first line of the input contains one integer q (1 ≀ q ≀ 500) β€” the number of queries. The i-th of the following q lines contains one integer k_i (1 ≀ k_i ≀ 10^{18}) β€” the description of the corresponding query. Output Print q lines. In the i-th line print one digit x_i (0 ≀ x_i ≀ 9) β€” the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence. Examples Input 5 1 3 20 38 56 Output 1 2 5 2 0 Input 4 2132 506 999999999999999999 1000000000000000000 Output 8 2 4 1 Note Answers on queries from the first example are described in the problem statement. Submitted Solution: ``` def init(maxn): Sum = [0] * maxn Single = [0] * maxn for i in range(1, maxn): lens = 10 ** i - 10 ** (i - 1) pre = Single[i - 1] Single[i] = pre + lens * i for i in range(1, maxn): lens = 10 ** i - 10 ** (i - 1) pre = Single[i-1] Sum[i] = (pre + i + pre + lens * i) * lens // 2 + Sum[i - 1] return Sum, Single def getAns(n, Sum, Single, maxn): ans = 0 minn = n index = 0 L, R = 1, 10 ** maxn while L <= R: m = (L + R) // 2 digit = len(str(m)) lens = m - 10 ** (digit - 1) + 1 pre = Single[digit - 1] cnt = (pre + digit + pre + lens * digit) * lens // 2 + Sum[digit - 1] if cnt < n: index = m minn = min(minn, n - cnt) L = m + 1 else : R = m - 1 #print(index, minn) n = minn L, R = 1, index + 11 index = 0 while L <= R: m = (L + R) // 2 digit = len(str(m)) lens = m - 10 ** (digit - 1) + 1 pre = Single[digit - 1] cnt = pre + lens * digit if cnt < n: index = m minn = min(minn, n - cnt) L = m + 1 else : R = m - 1 return str(index + 1)[minn - 1] def test(): ans = 0 Sum = 0 for i in range(1, 1000): ans += len(str(i)) Sum += ans if i % 10 == 9: print(i, ans, Sum) def main(): maxn = 10 Sum, Single = init(maxn) T = int(input()) for i in range(T): n = int(input()) print(getAns(n, Sum, Single, maxn)) if __name__ == '__main__': main() ``` Yes
97,948
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between the easy and the hard versions is the maximum value of k. You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one β€” from 1 to 2, the third one β€” from 1 to 3, ..., the i-th block consists of all numbers from 1 to i. So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0. Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence. Input The first line of the input contains one integer q (1 ≀ q ≀ 500) β€” the number of queries. The i-th of the following q lines contains one integer k_i (1 ≀ k_i ≀ 10^{18}) β€” the description of the corresponding query. Output Print q lines. In the i-th line print one digit x_i (0 ≀ x_i ≀ 9) β€” the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence. Examples Input 5 1 3 20 38 56 Output 1 2 5 2 0 Input 4 2132 506 999999999999999999 1000000000000000000 Output 8 2 4 1 Note Answers on queries from the first example are described in the problem statement. Submitted Solution: ``` import math sum_ = [0] * 18 begin_ = [0] * 18 def f_(x0, k, n): return k*(2*x0 + (k-1)*n) // 2 def make(): x0 = 1 k = 9 n = 1 while n < 18: begin_[n] = x0 last_number = x0 + (k-1)*n sum = k*(2*x0 + (k-1)*n) // 2 sum_[n] = sum sum_[n] += sum_[n-1] x0 = last_number + (n+1) k *= 10 n += 1 def digit(x): cnt = 0 while x > 0: x //= 10 cnt += 1 return cnt def f(x, begin_, sum_): n = digit(x) k = x - 10**(n-1) + 1 x0 = begin_[n] return sum_[n-1] + f_(x0, k, n) def find(s, begin_, sum_): l = 0 u = 1000000000 while u-l>1: md = (l+u) // 2 if f(md, begin_, sum_) > s: u = md else: l = md # pos, remain return l, s - f(l, begin_, sum_) def get_digit(x, pos): s = [] while x > 0: s.append(x%10) x //= 10 return s[::-1][pos] def find_digit(x): pos, remain = find(x, begin_, sum_) if remain == 0: return pos % 10 n = 0 next_ = 9 * (10**n) * (n+1) while next_ <= remain: remain -= next_ n += 1 next_ = 9 * (10**n) * (n+1) if remain == 0: return 9 pos_ = 10 ** n + math.ceil(remain / (n+1)) - 1 return get_digit(pos_, (remain-1)%(n+1)) make() q = int(input()) for _ in range(q): n = int(input()) print(find_digit(n)) ``` Yes
97,949
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between the easy and the hard versions is the maximum value of k. You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one β€” from 1 to 2, the third one β€” from 1 to 3, ..., the i-th block consists of all numbers from 1 to i. So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0. Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence. Input The first line of the input contains one integer q (1 ≀ q ≀ 500) β€” the number of queries. The i-th of the following q lines contains one integer k_i (1 ≀ k_i ≀ 10^{18}) β€” the description of the corresponding query. Output Print q lines. In the i-th line print one digit x_i (0 ≀ x_i ≀ 9) β€” the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence. Examples Input 5 1 3 20 38 56 Output 1 2 5 2 0 Input 4 2132 506 999999999999999999 1000000000000000000 Output 8 2 4 1 Note Answers on queries from the first example are described in the problem statement. Submitted Solution: ``` ''' Auther: ghoshashis545 Ashis Ghosh College: Jalpaiguri Govt Enggineering College ''' from os import path from io import BytesIO, IOBase import sys from heapq import heappush,heappop from functools import cmp_to_key as ctk from collections import deque,Counter,defaultdict as dd from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right from itertools import permutations from datetime import datetime from math import ceil,sqrt,log,gcd def ii():return int(input()) def si():return input().rstrip() def mi():return map(int,input().split()) def li():return list(mi()) abc='abcdefghijklmnopqrstuvwxyz' mod=1000000007 #mod=998244353 inf = float("inf") vow=['a','e','i','o','u'] dx,dy=[-1,1,0,0],[0,0,1,-1] def bo(i): return ord(i)-ord('0') file = 1 def ceil(a,b): return (a+b-1)//b def solve(): # for _ in range(1,ii()+1): def get(x): n = len(str(x)) cnt = 0 for i in range(n,0,-1): cnt_num = x-pow(10,i-1) + 1 cnt += cnt_num*i x = pow(10,i-1)-1 return cnt # x = [] # s = 0 # for i in range(1,10001): # s += get(i) # x.append(s) # if s > 1e9: # break # print(x[-1]) x = [] s = 0 for i in range(10): x1 = get(pow(10,i)) x.append(s + x1) cnt = pow(10,i+1) - pow(10,i) s += (cnt*x1) s1 = (cnt-1)*(i+1)*cnt s += (s1//2) # print(x) def get1(n): for i in range(10): if x[i] > n: n -= x[i-1] x1 = get(pow(10,i-1)) n += x1 l = 1 r = pow(10,i) while l <= r: mid = (l+r)>>1 s1 = (2*x1 + (mid-1)*i)*mid s1 //= 2 if s1 <= n: ans = mid l = mid+1 else: r = mid-1 s1 = (2*x1 + (ans-1)*i)*ans s1 //= 2 n -= s1 return [n,pow(10,i-1) + ans - 1] q = ii() for i in range(q): n = ii() n,idx = get1(n) if n==0: idx += 1 print(str(idx)[-1]) continue l = 1 r = idx+1 while l <= r: mid = (l+r)>>1 if get(mid) <= n: ans = mid l = mid+1 else: r = mid-1 n -= get(ans) if n == 0: print(str(ans)[-1]) else: print(str(ans+1)[n-1]) if __name__ =="__main__": if(file): if path.exists('input.txt'): sys.stdin=open('input.txt', 'r') sys.stdout=open('output.txt','w') else: input=sys.stdin.readline solve() ``` No
97,950
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between the easy and the hard versions is the maximum value of k. You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one β€” from 1 to 2, the third one β€” from 1 to 3, ..., the i-th block consists of all numbers from 1 to i. So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0. Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence. Input The first line of the input contains one integer q (1 ≀ q ≀ 500) β€” the number of queries. The i-th of the following q lines contains one integer k_i (1 ≀ k_i ≀ 10^{18}) β€” the description of the corresponding query. Output Print q lines. In the i-th line print one digit x_i (0 ≀ x_i ≀ 9) β€” the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence. Examples Input 5 1 3 20 38 56 Output 1 2 5 2 0 Input 4 2132 506 999999999999999999 1000000000000000000 Output 8 2 4 1 Note Answers on queries from the first example are described in the problem statement. Submitted Solution: ``` q = int(input()) def f(n): take = 0 ret = 0 while True: if n - take <= 0: break ret += (n - take) * (n - take + 1) // 2 take = take * 10 + 9 return ret def g(n): take = 0 ret = 0 while True: if n - take <= 0: break ret += n - take take = take * 10 + 9 return ret for _ in range(q): k = int(input()) low, high = 0, k ans = -1 while low < high: mid = (low + high + 1) >> 1 if f(mid) == k: ans = mid % 10 break if f(mid) < k: low = mid else: high = mid - 1 if ans != -1: print(ans) continue k -= f(low) low, high = 1, mid + 1 while low < high: mid = (low + high + 1) // 2 if g(mid) == k: ans = mid % 10 break if g(mid) < k: low = mid else: high = mid - 1 if ans != -1: print(ans) continue h = g(low) m = str(low + 1) print(m[k - h - 1]) ``` No
97,951
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between the easy and the hard versions is the maximum value of k. You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one β€” from 1 to 2, the third one β€” from 1 to 3, ..., the i-th block consists of all numbers from 1 to i. So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0. Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence. Input The first line of the input contains one integer q (1 ≀ q ≀ 500) β€” the number of queries. The i-th of the following q lines contains one integer k_i (1 ≀ k_i ≀ 10^{18}) β€” the description of the corresponding query. Output Print q lines. In the i-th line print one digit x_i (0 ≀ x_i ≀ 9) β€” the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence. Examples Input 5 1 3 20 38 56 Output 1 2 5 2 0 Input 4 2132 506 999999999999999999 1000000000000000000 Output 8 2 4 1 Note Answers on queries from the first example are described in the problem statement. Submitted Solution: ``` def digits_until_block_(n): result = 0 for bas in range(1, 20): # bas for basamak minimum = int(10 ** (bas - 1)) maximum = int((10 ** bas) - 1) if n < maximum: maximum = n if maximum < minimum: break result += sum_between(n - maximum + 1, n - minimum + 1) * bas return result def digits_until_(n): if n == 0: return 0 if n == 1: return 1 return digits_until_block_(n) - digits_until_block_(n - 1) def sum_between(x, y): return int((x + y) * (y - x + 1) / 2) def solve(q): left = 1 right = 1000000000 while left < right: mid = (left + right) // 2 if digits_until_block_(mid) < q: left = mid + 1 else: right = mid q = q - digits_until_block_(left - 1) if q == 0: return str(left - 1)[-1] left = 1 right = 1000000000 while left < right: mid = (left + right) // 2 if digits_until_(mid) < q: left = mid + 1 else: right = mid q = q - digits_until_(left - 1) if q == 0: return str(left - 1)[-1] return str(left)[q - 1] q = int(input("")) q_list = [] for _ in range(q): q_list.append(int(input(""))) for query in q_list: print(solve(query)) ``` No
97,952
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The only difference between the easy and the hard versions is the maximum value of k. You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one β€” from 1 to 2, the third one β€” from 1 to 3, ..., the i-th block consists of all numbers from 1 to i. So the first 56 elements of the sequence are "11212312341234512345612345671234567812345678912345678910". Elements of the sequence are numbered from one. For example, the 1-st element of the sequence is 1, the 3-rd element of the sequence is 2, the 20-th element of the sequence is 5, the 38-th element is 2, the 56-th element of the sequence is 0. Your task is to answer q independent queries. In the i-th query you are given one integer k_i. Calculate the digit at the position k_i of the sequence. Input The first line of the input contains one integer q (1 ≀ q ≀ 500) β€” the number of queries. The i-th of the following q lines contains one integer k_i (1 ≀ k_i ≀ 10^{18}) β€” the description of the corresponding query. Output Print q lines. In the i-th line print one digit x_i (0 ≀ x_i ≀ 9) β€” the answer to the query i, i.e. x_i should be equal to the element at the position k_i of the sequence. Examples Input 5 1 3 20 38 56 Output 1 2 5 2 0 Input 4 2132 506 999999999999999999 1000000000000000000 Output 8 2 4 1 Note Answers on queries from the first example are described in the problem statement. Submitted Solution: ``` dp, cnt = [0], 1 dp2 = [0] while dp[-1] <= int(1e18): ans = dp2[-1] + (10 ** cnt - 10 ** (cnt - 1)) * cnt dp2.append(ans) ans = dp[-1] + dp2[-2] * (10 ** cnt - 10 ** (cnt - 1)) + cnt * int((10 ** cnt - 10 ** (cnt - 1) + 1) * (10 ** cnt - 10 ** (cnt - 1)) / 2) cnt += 1 dp.append(ans) def Cal(a, b): return dp2[b - 1] * a + b * int(a * (a + 1) / 2) q = int(input()) for _ in range(q): k = int(input()) i = 0 while k > dp[i]: i += 1 k -= dp[i - 1] l, r = 0, 10 ** i - 10 ** (i - 1) last = int((l + r) / 2) while not(Cal(last, i) < k and Cal(last + 1, i) >= k): if(Cal(last, i) < k): l = last last = int((l + r) / 2 + 1) else: r = last last = int((l + r) / 2) k -= Cal(last, i) j = 0 while dp2[j] < k: j += 1 k -= dp2[j - 1] a = int((k - 1) / j) k -= a * j Long = str(10 ** (j - 1) + a) print(Long[k - 1]) ``` No
97,953
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≀ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp Γ— i. If the answer is positive, find one way to rearrange the characters. Input The only line contains the initial string s, consisting of small Latin letters (1 ≀ |s| ≀ 1000). Output If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO". Examples Input abc Output YES abc Input abcd Output NO Input xxxyxxx Output YES xxxxxxy Note In the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba". In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4). In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid. Tags: implementation, number theory, strings Correct Solution: ``` s = input().strip() import math, functools, sys, heapq @functools.lru_cache(None) def check_prime(p): for i in range(2, int(math.sqrt(p)) + 1): if p % i == 0: return False return True primes = [] n = len(s) for p in range(2, n + 1): if check_prime(p): primes.append(p) cnt = {} for c in s: try: cnt[c] += 1 except KeyError: cnt[c] = 1 pq = [] for key in cnt: heapq.heappush(pq, (-cnt[key], key)) sets = [] for p in primes: inds = set() for i in range(1, n // p + 1): inds.add(p * i) done = False for i, st in enumerate(sets): if st & inds: sets[i] = st | inds done = True break if not done: sets.append(inds) # print(inds, sets) sets.sort(key=lambda x: len(x), reverse=True) # print(primes) # print(sets) ans = [None for _ in range(n)] for st in sets: if not pq: print('NO') sys.exit() cnt, c = heapq.heappop(pq) if -cnt >= len(st): for i in st: ans[i-1] = c cnt = -cnt - len(st) if cnt > 0: heapq.heappush(pq, (-cnt, c)) else: print('NO') sys.exit() # print(ans) i = 0 cnt, c = heapq.heappop(pq) cnt = -cnt while i < n: if ans[i] is not None: i += 1 continue if cnt == 0 and pq: cnt, c = heapq.heappop(pq) cnt = -cnt ans[i] = c cnt -= 1 i += 1 print('YES') print(''.join(ans)) ```
97,954
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≀ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp Γ— i. If the answer is positive, find one way to rearrange the characters. Input The only line contains the initial string s, consisting of small Latin letters (1 ≀ |s| ≀ 1000). Output If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO". Examples Input abc Output YES abc Input abcd Output NO Input xxxyxxx Output YES xxxxxxy Note In the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba". In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4). In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid. Tags: implementation, number theory, strings Correct Solution: ``` from collections import Counter d, t = 'NO', input() c, n = Counter(t), len(t) p = [1] * (n + 1) for i in range(2, n // 2 + 1): if p[i]: p[i::i] = [0] * (n // i) p.pop(0) s = n - sum(p) u = v = '' for q, k in c.items(): if not (v or k < s): k -= s v = q u += q * k if v: d, j = 'YES\n', 0 for q in p: d += u[j] if q else v j += q print(d) ```
97,955
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≀ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp Γ— i. If the answer is positive, find one way to rearrange the characters. Input The only line contains the initial string s, consisting of small Latin letters (1 ≀ |s| ≀ 1000). Output If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO". Examples Input abc Output YES abc Input abcd Output NO Input xxxyxxx Output YES xxxxxxy Note In the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba". In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4). In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid. Tags: implementation, number theory, strings Correct Solution: ``` from collections import Counter d, t = 'NO', input() c, n = Counter(t), len(t) p = [0] * (n + 1) for i in range(2, n // 2 + 1): if 1 - p[i]: p[i::i] = [1] * (n // i) s = sum(p) u = v = '' for q, k in c.items(): if v or k < s: u += q * k else: u += q * (k - s) v = q if v: d, j = 'YES\n', 0 for i in range(1, n + 1): if p[i]: d += v else: d += u[j] j += 1 print(d) ```
97,956
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≀ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp Γ— i. If the answer is positive, find one way to rearrange the characters. Input The only line contains the initial string s, consisting of small Latin letters (1 ≀ |s| ≀ 1000). Output If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO". Examples Input abc Output YES abc Input abcd Output NO Input xxxyxxx Output YES xxxxxxy Note In the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba". In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4). In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid. Tags: implementation, number theory, strings Correct Solution: ``` import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush # from math import * from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br, bisect from time import perf_counter from fractions import Fraction import copy import time starttime = time.time() mod = int(pow(10, 9) + 7) mod2 = 998244353 def data(): return sys.stdin.readline().strip() def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end) def L(): return list(sp()) def sl(): return list(ssp()) def sp(): return map(int, data().split()) def ssp(): return map(str, data().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)] try: # sys.setrecursionlimit(int(pow(10,4))) sys.stdin = open("input.txt", "r") # sys.stdout = open("../output.txt", "w") except: pass def pmat(A): for ele in A: print(*ele,end="\n") # def seive(): # prime=[1 for i in range(10**6+1)] # prime[0]=0 # prime[1]=0 # for i in range(10**6+1): # if(prime[i]): # for j in range(2*i,10**6+1,i): # prime[j]=0 # return prime s=input() n=len(s) A=[i for i in range(n+1)] def par(x): if A[x]==x: return x return par(A[x]) def union(x,y): u=par(x) v=par(y) if u==v: return if u<v: A[v]=u else: A[u]=v for i in range(2,n+1): if A[i]!=i: continue for j in range(2*i,n+1,i): union(i,j) d={} for i in range(1,n+1): d[A[i]]=d.get(A[i],0)+1 cnt={} for c in s: cnt[c]=cnt.get(c,0)+1 B1=[[d[i],i] for i in d] B2=[[cnt[i],i] for i in cnt] B1.sort(reverse=True) B2.sort() i=0 C={} if len(B1)<len(B2): print("NO") exit() while(i<len(B1)): x=B1[i][0] for j in range(len(B2)): if B2[j][0]>=x: B2[j][0]-=x C[B1[i][1]]=B2[j][1] break else: print("NO") exit() i+=1 print("YES") for i in range(1,n+1): print(C[A[i]],end="") print() endtime = time.time() # print(f"Runtime of the program is {endtime - starttime}") ```
97,957
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≀ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp Γ— i. If the answer is positive, find one way to rearrange the characters. Input The only line contains the initial string s, consisting of small Latin letters (1 ≀ |s| ≀ 1000). Output If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO". Examples Input abc Output YES abc Input abcd Output NO Input xxxyxxx Output YES xxxxxxy Note In the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba". In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4). In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid. Tags: implementation, number theory, strings Correct Solution: ``` from collections import Counter def is_prime(x): if x < 2: return 0 for i in range(2, x): if x % i == 0: return False return True def proc(s): n = len(s) same = set() for p in range(2,n+1): if not is_prime(p): continue if p * 2 > n: continue for i in range(2, n//p+1): same.add(p*i) same.add(p) counter = Counter(s) ch, count = counter.most_common(1)[0] if count < len(same): print("NO") return same = [x-1 for x in same] w = [x for x in s] for i in same: if w[i] == ch: continue for j in range(n): if j not in same and w[j] == ch: tmp = w[j] w[j] = w[i] w[i] = tmp break print("YES") print(''.join(w)) s = input() proc(s) ```
97,958
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≀ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp Γ— i. If the answer is positive, find one way to rearrange the characters. Input The only line contains the initial string s, consisting of small Latin letters (1 ≀ |s| ≀ 1000). Output If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO". Examples Input abc Output YES abc Input abcd Output NO Input xxxyxxx Output YES xxxxxxy Note In the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba". In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4). In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid. Tags: implementation, number theory, strings Correct Solution: ``` def SieveOfEratosthenes(n): # Create a boolean array "prime[0..n]" and initialize # all entries it as true. A value in prime[i] will # finally be false if i is Not a prime, else true. prime = [True for i in range(n + 1)] p = 2 while (p * p <= n): # If prime[p] is not changed, then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * 2, n + 1, p): prime[i] = False p += 1 prime[0]= False prime[1]= False return prime s = input() primes = SieveOfEratosthenes(len(s)) length = len(s) unique = set() unique.add(1) for i in range(2, len(s)+1): if primes[i] and 2*i > length: unique.add(i) # print(unique) count = dict() sameHave = 1 sameC = s[0] for c in s: if c not in count: count[c] = 1 else: count[c] += 1 if(count[c] > sameHave): sameHave = count[c] sameC = c # print(count) uniqueList = [] for char in s: if char != sameC: uniqueList.append(char) # print(uniqueList) sameNeed = length - len(unique) # print(sameNeed, sameHave, sameC) if sameHave >= sameNeed: print("YES") out = "" for i in range(1, len(s)+1): if i in unique: if len(uniqueList) != 0: out += uniqueList.pop() else: out += sameC else: out += sameC print(out) else: print("NO") ```
97,959
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≀ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp Γ— i. If the answer is positive, find one way to rearrange the characters. Input The only line contains the initial string s, consisting of small Latin letters (1 ≀ |s| ≀ 1000). Output If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO". Examples Input abc Output YES abc Input abcd Output NO Input xxxyxxx Output YES xxxxxxy Note In the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba". In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4). In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid. Tags: implementation, number theory, strings Correct Solution: ``` #!/usr/bin/python3 s = input() d = dict() for c in s: if c not in d: d[c] = 0 d[c] += 1 cnto = 1 isprime = [True] * (len(s) + 1) for p in range(2, len(s) + 1): if isprime[p]: for i in range(p * p, len(s) + 1, p): isprime[i] = False for i in range(1, len(s) + 1): if i > len(s) // 2 and isprime[i]: cnto += 1 cnto = len(s) - cnto if max(d.values()) < cnto: print("NO") else: print("YES") m = max(d.values()) for c, v in d.items(): if v == m: d[c] -= cnto mc = c break ans = [] buf = [] for c, v in d.items(): for i in range(v): buf.append(c) for i in range(1, len(s) + 1): if i == 1 or (i > len(s) // 2 and isprime[i]): ans.append(buf[-1]) buf.pop() else: ans.append(mc) print("".join(ans)) ```
97,960
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≀ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp Γ— i. If the answer is positive, find one way to rearrange the characters. Input The only line contains the initial string s, consisting of small Latin letters (1 ≀ |s| ≀ 1000). Output If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO". Examples Input abc Output YES abc Input abcd Output NO Input xxxyxxx Output YES xxxxxxy Note In the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba". In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4). In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid. Tags: implementation, number theory, strings Correct Solution: ``` import math ch='abcdefghijklmnopqrstuvwxyz' def sieve(n): p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * 2, n + 1, p): prime[i] = False p += 1 prime[0]= False prime[1]= False s = ['#']+list(input()) lis=[0]*26 n = len(s)-1 prime = [True for i in range(1000 + 1)] sieve(1000) ans=['']*(n+1) aa=[] aa.append(1) for i in s[1:]: lis[ord(i)-ord('a')]+=1 for i in range(n//2+1,n+1,1): if prime[i]: aa.append(i) v = n-len(aa) th=-1 for i in range(26): if lis[i]>=v: th=i if th==-1: print("NO") exit() for i in range(2,n+1): if i not in aa: ans[i]=ch[th] lis[th]-=1 j=0 #print(ans,aa,lis) for i in aa: while j<26 and lis[j]<=0: j+=1 ans[i]=ch[j] lis[j]-=1 # print(ans,lis) print("YES") print(*ans[1:],sep='') ```
97,961
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≀ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp Γ— i. If the answer is positive, find one way to rearrange the characters. Input The only line contains the initial string s, consisting of small Latin letters (1 ≀ |s| ≀ 1000). Output If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO". Examples Input abc Output YES abc Input abcd Output NO Input xxxyxxx Output YES xxxxxxy Note In the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba". In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4). In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid. Submitted Solution: ``` s = input() if len(s) == 1: exit(print('YES\n' + s)) d, ans, sieve = {}, [0] * len(s), [0] * 1005 for i in s: d[i] = d.get(i, 0) + 1 for i in range(2, len(s) + 1): if not sieve[i]: for j in range(i * i, 1005, i): sieve[j] = 1 mx = max(d, key=lambda x: d[x]) for j in range(2, len(s) // 2 + 1): ans[j - 1] = mx d[mx] -= 1 if d[mx] < 0: exit(print('NO')) for i in range(len(s) // 2 + 1, len(s) + 1): if not sieve[i]: mx = max(d, key=lambda x: d[x] and x != ans[1]) if not d[mx]: mx = ans[1] ans[i - 1] = mx d[mx] -= 1 else: ans[i - 1] = ans[1] d[ans[1]] -= 1 if d[mx] < 0 or d[ans[1]] < 0: exit(print('NO')) print('YES') mx = max(d, key=lambda x: d[x]) print(mx + ''.join(ans[1:])) ``` Yes
97,962
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≀ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp Γ— i. If the answer is positive, find one way to rearrange the characters. Input The only line contains the initial string s, consisting of small Latin letters (1 ≀ |s| ≀ 1000). Output If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO". Examples Input abc Output YES abc Input abcd Output NO Input xxxyxxx Output YES xxxxxxy Note In the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba". In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4). In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid. Submitted Solution: ``` import sys import math from collections import defaultdict MAXNUM = math.inf MINNUM = -1 * math.inf ASCIILOWER = 97 ASCIIUPPER = 65 def getInt(): return int(sys.stdin.readline().rstrip()) def getInts(): return map(int, sys.stdin.readline().rstrip().split(" ")) def getString(): return sys.stdin.readline().rstrip() def printOutput(ans): sys.stdout.write() pass def getPrimes(s): primes = [2] MAX = s + 1 for i in range(3, MAX): STOP = math.ceil(math.sqrt(i) + 1) isPrime = True for j in range(2, STOP): if i % j == 0: isPrime = False if isPrime: primes.append(i) return primes def solve(let, s): primes = getPrimes(len(s)) bigindices = [] oneIndices = [] ones = 0 for i in primes: k = len(s) // i if k > 1: bigindices.append(i) if k == 1: oneIndices.append(i) ones += 1 solution = [0 for _ in range(len(s))] bigK = max(let, key=lambda x: let[x]) total = 0 for index in bigindices: for i in range(index, len(solution) + 1, index): if solution[i-1] == 0: solution[i - 1] = bigK total += 1 #print(len(s)) #print(total) #print(bigindices) #print(oneIndices) if total > let[bigK]: return "NO", None else: let[bigK] -= total #print("afterbig") #print(solution) for item in oneIndices: for key, val in let.items(): if val >= 1: let[key] -= 1 ones -= 1 solution[item - 1] = key break if ones != 0: return "NO", None #print("afteroneind") #print(solution) for i in range(len(solution)): if solution[i] == 0: for key, val in let.items(): if val > 0: val -= 1 solution[i] = key break return "YES", "".join(solution) def readinput(): lettercount = defaultdict(int) string = getString() for ele in string: lettercount[ele] += 1 ans = solve(lettercount, string) print(ans[0]) if ans[0] != "NO": print(ans[1]) readinput() ``` Yes
97,963
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≀ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp Γ— i. If the answer is positive, find one way to rearrange the characters. Input The only line contains the initial string s, consisting of small Latin letters (1 ≀ |s| ≀ 1000). Output If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO". Examples Input abc Output YES abc Input abcd Output NO Input xxxyxxx Output YES xxxxxxy Note In the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba". In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4). In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid. Submitted Solution: ``` p=[1]*1001 for i in range(2,1001): if p[i]: for j in range(i,1001,i):p[j]=0 p[i]=1 a=input() z=len(a) l=[0]*26 for i in a:l[ord(i)-97]+=1 gh=0 for i in range(z//2+1,z+1):gh+=p[i] if max(l)<z-1-gh:exit(print("NO")) ans=['']*(z+1) t=l.index(max(l)) for i in range(2,1+(z//2)):ans[i]=chr(t+97);l[t]-=1 for i in range(1+(z//2),z+1): if p[i]==0:ans[i]=chr(t+97);l[t]-=1 j=0 for i in range(1,z+1): if ans[i]=='': while l[j]<=0:j+=1 ans[i]=chr(j+97);l[j]-=1 print("YES") print(''.join(ans[1::])) ``` Yes
97,964
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≀ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp Γ— i. If the answer is positive, find one way to rearrange the characters. Input The only line contains the initial string s, consisting of small Latin letters (1 ≀ |s| ≀ 1000). Output If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO". Examples Input abc Output YES abc Input abcd Output NO Input xxxyxxx Output YES xxxxxxy Note In the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba". In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4). In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid. Submitted Solution: ``` from collections import Counter is_prime = lambda x: all(x % d for d in range(2, int(x **.5) + 1)) s = input() n = len(s) K = {1} | {x for x in range(n // 2 + 1, n + 1) if is_prime(x)} k = len(K) ch, m = max(Counter(s).items(), key=lambda x: x[1]) if m + k < n: print('NO') else: print('YES') s = list(s.replace(ch, '', n - k)) A = [0] * n for i in range(n): A[i] = s.pop() if (i + 1) in K else ch print(''.join(A)) ``` Yes
97,965
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≀ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp Γ— i. If the answer is positive, find one way to rearrange the characters. Input The only line contains the initial string s, consisting of small Latin letters (1 ≀ |s| ≀ 1000). Output If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO". Examples Input abc Output YES abc Input abcd Output NO Input xxxyxxx Output YES xxxxxxy Note In the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba". In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4). In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid. Submitted Solution: ``` dp=[] def sieve(): n=10**4 global dp dp=[True]*n dp[0]=False dp[1]=False i=0 while (i*i)<=n: j=i if dp[i]: for jj in range(2*j,n,j): dp[jj]=False i+=1 sieve() s=input() if s=='abcd': print('NO') exit() n=len(s) d={} for i in s: if i in d:d[i]+=1 else:d[i]=1 #print(dp[:4]) for p in range(2,len(s)+1): if dp[p]: arr=[] for i in range(len(s)//p): arr.append(p*(i+1)) for i in s: if max(arr)<=n and len(arr)<=d[i]: s1=[0]*n print(arr) for j in arr:s1[j-1]=i d[i]-=len(arr) #print(d) #print(s1) for ii in s: if d[ii]>0: k=0 kk=0 while kk<n and k<d[ii]: if s1[kk]==0: s1[kk]=ii k+=1 kk+=1 d[ii]-=k# print(d) # print(s1) print('YES') print(''.join(s1)) exit() print('NO') ``` No
97,966
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≀ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp Γ— i. If the answer is positive, find one way to rearrange the characters. Input The only line contains the initial string s, consisting of small Latin letters (1 ≀ |s| ≀ 1000). Output If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO". Examples Input abc Output YES abc Input abcd Output NO Input xxxyxxx Output YES xxxxxxy Note In the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba". In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4). In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid. Submitted Solution: ``` s = input() d, ans, sieve = {}, [0] * len(s), [0] * 1005 for i in s: d[i] = d.get(i, 0) + 1 for i in range(2, len(s) + 1): if not sieve[i]: for j in range(i * i, 1005, i): sieve[j] = 1 mx = max(d, key=lambda x: d[x]) for j in range(i, len(s) + 1, i): if not ans[j - 1]: ans[j - 1] = mx d[mx] -= 1 if d[mx] < 0: exit(print('NO')) print('YES') mx = max(d, key=lambda x: d[x]) print(mx + ''.join(ans[1:])) ``` No
97,967
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≀ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp Γ— i. If the answer is positive, find one way to rearrange the characters. Input The only line contains the initial string s, consisting of small Latin letters (1 ≀ |s| ≀ 1000). Output If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO". Examples Input abc Output YES abc Input abcd Output NO Input xxxyxxx Output YES xxxxxxy Note In the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba". In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4). In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid. Submitted Solution: ``` import heapq primenumbers=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47, 53,59,61,67,71,73,79,83,89,97, 101,103,107,109,113,127,131,137,139,149, 151,157,163,167,173,179,181,191,193,197,199, 211,223,227,229,233,239,241, 251,257,263,269,271,277,281,283,293, 307,311,313,317,331,337,347,349, 353,359,367,373,379,383,389,397, 401,409,419,421,431,433,439,443,449, 457,461,463,467,479,487,491,499, 503,509,521,523,541,547, 557,563,569,571,577,587,593,599, 601,607,613,617,619,631,641,643,647, 653,659,661,673,677,683,691, 701,709,719,727,733,739,743, 751,757,761,769,773,787,797, 809,811,821,823,827,829,839, 853,857,859,863,877,881,883,887, 907,911,919,929,937,941,947, 953,967,971,977,983,991,997] ss=input() s=len(ss) for index in range(168): if primenumbers[index]==s: indextemp=index break elif primenumbers[index]>s: indextemp=index-1 break same=[[]] for i in range(indextemp+1): tempV=[] temp=primenumbers[i] while temp<=s: if temp not in same[-1]: tempV.append(temp) temp+=primenumbers[i] same.append(tempV) same.remove(same[0]) amount=[] for i in same: heapq.heappush(amount,len(i)) dic={} for i in ss: if i not in dic.keys(): dic[i]=1 else: dic[i]+=1 amountC=[] for i in dic.keys(): heapq.heappush(amountC,dic[i]) pointer=True if len(amount)>len(amountC): print('NO') else: for i in range(len(amount)): if amount[i]>amountC[i]: print('NO') pointer=False break if pointer: print('YES') print(ss) ``` No
97,968
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≀ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp Γ— i. If the answer is positive, find one way to rearrange the characters. Input The only line contains the initial string s, consisting of small Latin letters (1 ≀ |s| ≀ 1000). Output If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO". Examples Input abc Output YES abc Input abcd Output NO Input xxxyxxx Output YES xxxxxxy Note In the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba". In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4). In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid. 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 # import sys # sys.setrecursionlimit(10**6) def primes(n): """ Returns a list of 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 prefixSum(arr): for i in range(1, len(arr)): arr[i] = arr[i] + arr[i-1] return arr 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 # from functools import lru_cache # @lru_cache(maxsize=None) s = input().decode('utf-8').strip() # n = int(input()) # l = list(map(int, input().split())) c = Counter(s) dp = [0] * len(s) primes = primes(len(s)) components = [] for p in primes: l = [] for i in range(p, len(s)+1, p): l.append(i) for comp in components: if len(list(set(comp) & set(l))): comp += l break else: if len(l): components.append(l) need = [] for comp in components: need.append(len(set(comp))) import heapq heap = [] for e, v in c.items(): heapq.heappush(heap, (-v, e)) result = [""] * (len(s)) for comp in components: i, letter = heapq.heappop(heap) i = -i indexes = set(comp) if i >= len(indexes): heapq.heappush(heap, (-(i-len(indexes)), letter)) for index in set(comp): result[index-1] = letter else: print("NO") break else: while len(heap): i, letter = heapq.heappop(heap) for j in range(len(result)): if i == 0: break if result[j] == "": result[j] = letter i -= 1 print("YES") print("".join(result)) # a = sorted(list(c.values())) # b = sorted(need) # # i, j = len(b)-1, len(a)-1 # while i >= 0 and j >= 0: # if b[i] <= a[j]: # a[j] -= b[i] # i -= 1 # else: # j -= 1 # # if i == -1: # print("YES") # else: # print("NO") ``` No
97,969
Provide tags and a correct Python 3 solution for this coding contest problem. Let's define a string <x> as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type </x>, where x is the same letter. Tegs can be nested into each other: in this case one opening and closing tag pair is located inside another pair. Let's define the notion of a XML-text: * an empty string is a XML-text * if s is a XML-text, then s'=<a>+s+</a> also is a XML-text, where a is any small Latin letter * if s1, s2 are XML-texts, then s1+s2 also is a XML-text You are given a XML-text (it is guaranteed that the text is valid), your task is to print in the following form: * each tag (opening and closing) is located on a single line * print before the tag 2 * h spaces, where h is the level of the tag's nestedness. Input The input data consists on the only non-empty string β€” the XML-text, its length does not exceed 1000 characters. It is guaranteed that the text is valid. The text contains no spaces. Output Print the given XML-text according to the above-given rules. Examples Input &lt;a&gt;&lt;b&gt;&lt;c&gt;&lt;/c&gt;&lt;/b&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;c&gt; &lt;/c&gt; &lt;/b&gt; &lt;/a&gt; Input &lt;a&gt;&lt;b&gt;&lt;/b&gt;&lt;d&gt;&lt;c&gt;&lt;/c&gt;&lt;/d&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;/b&gt; &lt;d&gt; &lt;c&gt; &lt;/c&gt; &lt;/d&gt; &lt;/a&gt; Tags: implementation Correct Solution: ``` spacecnt = 0; for tag in (input().split('>'))[:-1]: if tag.find('/') != -1: spacecnt -= 2 print(' '*spacecnt+tag+'>') else: print(' '*spacecnt+tag+'>') spacecnt += 2 ```
97,970
Provide tags and a correct Python 3 solution for this coding contest problem. Let's define a string <x> as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type </x>, where x is the same letter. Tegs can be nested into each other: in this case one opening and closing tag pair is located inside another pair. Let's define the notion of a XML-text: * an empty string is a XML-text * if s is a XML-text, then s'=<a>+s+</a> also is a XML-text, where a is any small Latin letter * if s1, s2 are XML-texts, then s1+s2 also is a XML-text You are given a XML-text (it is guaranteed that the text is valid), your task is to print in the following form: * each tag (opening and closing) is located on a single line * print before the tag 2 * h spaces, where h is the level of the tag's nestedness. Input The input data consists on the only non-empty string β€” the XML-text, its length does not exceed 1000 characters. It is guaranteed that the text is valid. The text contains no spaces. Output Print the given XML-text according to the above-given rules. Examples Input &lt;a&gt;&lt;b&gt;&lt;c&gt;&lt;/c&gt;&lt;/b&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;c&gt; &lt;/c&gt; &lt;/b&gt; &lt;/a&gt; Input &lt;a&gt;&lt;b&gt;&lt;/b&gt;&lt;d&gt;&lt;c&gt;&lt;/c&gt;&lt;/d&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;/b&gt; &lt;d&gt; &lt;c&gt; &lt;/c&gt; &lt;/d&gt; &lt;/a&gt; Tags: implementation Correct Solution: ``` from string import ascii_lowercase def print_end_tag(level, character): print(" " * level + f"</{character}>" if level else f"</{character}>") def print_start_tag(level, character): print(" " * level + f"<{character}>" if level else f"<{character}>") def main(): xml_line = input() counter = 0 last_character = '' for character in xml_line: if character == '<' or character == '>': continue if character in ascii_lowercase: end_tag = True if last_character == '/' else False if not end_tag: print_start_tag(counter, character) counter += 1 else: counter -= 1 print_end_tag(counter, character) last_character = character main() ```
97,971
Provide tags and a correct Python 3 solution for this coding contest problem. Let's define a string <x> as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type </x>, where x is the same letter. Tegs can be nested into each other: in this case one opening and closing tag pair is located inside another pair. Let's define the notion of a XML-text: * an empty string is a XML-text * if s is a XML-text, then s'=<a>+s+</a> also is a XML-text, where a is any small Latin letter * if s1, s2 are XML-texts, then s1+s2 also is a XML-text You are given a XML-text (it is guaranteed that the text is valid), your task is to print in the following form: * each tag (opening and closing) is located on a single line * print before the tag 2 * h spaces, where h is the level of the tag's nestedness. Input The input data consists on the only non-empty string β€” the XML-text, its length does not exceed 1000 characters. It is guaranteed that the text is valid. The text contains no spaces. Output Print the given XML-text according to the above-given rules. Examples Input &lt;a&gt;&lt;b&gt;&lt;c&gt;&lt;/c&gt;&lt;/b&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;c&gt; &lt;/c&gt; &lt;/b&gt; &lt;/a&gt; Input &lt;a&gt;&lt;b&gt;&lt;/b&gt;&lt;d&gt;&lt;c&gt;&lt;/c&gt;&lt;/d&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;/b&gt; &lt;d&gt; &lt;c&gt; &lt;/c&gt; &lt;/d&gt; &lt;/a&gt; Tags: implementation Correct Solution: ``` xml = input() tags = xml.split('>')[:-1] for i in range(len(tags)): tags[i] += '>' h = 0 for tag in tags: if '</' not in tag: print(' ' * 2 * h + tag) h += 1 else: h -= 1 print(' ' * 2 * h + tag) ```
97,972
Provide tags and a correct Python 3 solution for this coding contest problem. Let's define a string <x> as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type </x>, where x is the same letter. Tegs can be nested into each other: in this case one opening and closing tag pair is located inside another pair. Let's define the notion of a XML-text: * an empty string is a XML-text * if s is a XML-text, then s'=<a>+s+</a> also is a XML-text, where a is any small Latin letter * if s1, s2 are XML-texts, then s1+s2 also is a XML-text You are given a XML-text (it is guaranteed that the text is valid), your task is to print in the following form: * each tag (opening and closing) is located on a single line * print before the tag 2 * h spaces, where h is the level of the tag's nestedness. Input The input data consists on the only non-empty string β€” the XML-text, its length does not exceed 1000 characters. It is guaranteed that the text is valid. The text contains no spaces. Output Print the given XML-text according to the above-given rules. Examples Input &lt;a&gt;&lt;b&gt;&lt;c&gt;&lt;/c&gt;&lt;/b&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;c&gt; &lt;/c&gt; &lt;/b&gt; &lt;/a&gt; Input &lt;a&gt;&lt;b&gt;&lt;/b&gt;&lt;d&gt;&lt;c&gt;&lt;/c&gt;&lt;/d&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;/b&gt; &lt;d&gt; &lt;c&gt; &lt;/c&gt; &lt;/d&gt; &lt;/a&gt; Tags: implementation Correct Solution: ``` str_input = input() queue = [] indentation = 0 while(str_input != ""): if(str_input[1] == '/'): print("%s%s"%(indentation * " ", str_input[0:4])) queue.pop() str_input = str_input[4:] if(str_input != "" and str_input[1] == "/"): indentation -= 2 else: print("%s%s"%(indentation * " ", str_input[0:3])) queue.append(str_input[1:2]) str_input = str_input[3:] if(str_input != "" and str_input[0:3] != "</%s"%(queue[-1])): indentation += 2 ```
97,973
Provide tags and a correct Python 3 solution for this coding contest problem. Let's define a string <x> as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type </x>, where x is the same letter. Tegs can be nested into each other: in this case one opening and closing tag pair is located inside another pair. Let's define the notion of a XML-text: * an empty string is a XML-text * if s is a XML-text, then s'=<a>+s+</a> also is a XML-text, where a is any small Latin letter * if s1, s2 are XML-texts, then s1+s2 also is a XML-text You are given a XML-text (it is guaranteed that the text is valid), your task is to print in the following form: * each tag (opening and closing) is located on a single line * print before the tag 2 * h spaces, where h is the level of the tag's nestedness. Input The input data consists on the only non-empty string β€” the XML-text, its length does not exceed 1000 characters. It is guaranteed that the text is valid. The text contains no spaces. Output Print the given XML-text according to the above-given rules. Examples Input &lt;a&gt;&lt;b&gt;&lt;c&gt;&lt;/c&gt;&lt;/b&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;c&gt; &lt;/c&gt; &lt;/b&gt; &lt;/a&gt; Input &lt;a&gt;&lt;b&gt;&lt;/b&gt;&lt;d&gt;&lt;c&gt;&lt;/c&gt;&lt;/d&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;/b&gt; &lt;d&gt; &lt;c&gt; &lt;/c&gt; &lt;/d&gt; &lt;/a&gt; Tags: implementation Correct Solution: ``` s = input().split(">") del s[-1] s = [i+">" for i in s] h = 0 for i in s: if "/" in i: h-=1 print(h*2*" "+i) else: print(h*2*" "+i) h+=1 ```
97,974
Provide tags and a correct Python 3 solution for this coding contest problem. Let's define a string <x> as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type </x>, where x is the same letter. Tegs can be nested into each other: in this case one opening and closing tag pair is located inside another pair. Let's define the notion of a XML-text: * an empty string is a XML-text * if s is a XML-text, then s'=<a>+s+</a> also is a XML-text, where a is any small Latin letter * if s1, s2 are XML-texts, then s1+s2 also is a XML-text You are given a XML-text (it is guaranteed that the text is valid), your task is to print in the following form: * each tag (opening and closing) is located on a single line * print before the tag 2 * h spaces, where h is the level of the tag's nestedness. Input The input data consists on the only non-empty string β€” the XML-text, its length does not exceed 1000 characters. It is guaranteed that the text is valid. The text contains no spaces. Output Print the given XML-text according to the above-given rules. Examples Input &lt;a&gt;&lt;b&gt;&lt;c&gt;&lt;/c&gt;&lt;/b&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;c&gt; &lt;/c&gt; &lt;/b&gt; &lt;/a&gt; Input &lt;a&gt;&lt;b&gt;&lt;/b&gt;&lt;d&gt;&lt;c&gt;&lt;/c&gt;&lt;/d&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;/b&gt; &lt;d&gt; &lt;c&gt; &lt;/c&gt; &lt;/d&gt; &lt;/a&gt; Tags: implementation Correct Solution: ``` h = 0 for tag in input().replace('><', '> <').split(): if '/' in tag: h -= 2 print(h*' ' + tag) if '/' not in tag: h += 2 ```
97,975
Provide tags and a correct Python 3 solution for this coding contest problem. Let's define a string <x> as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type </x>, where x is the same letter. Tegs can be nested into each other: in this case one opening and closing tag pair is located inside another pair. Let's define the notion of a XML-text: * an empty string is a XML-text * if s is a XML-text, then s'=<a>+s+</a> also is a XML-text, where a is any small Latin letter * if s1, s2 are XML-texts, then s1+s2 also is a XML-text You are given a XML-text (it is guaranteed that the text is valid), your task is to print in the following form: * each tag (opening and closing) is located on a single line * print before the tag 2 * h spaces, where h is the level of the tag's nestedness. Input The input data consists on the only non-empty string β€” the XML-text, its length does not exceed 1000 characters. It is guaranteed that the text is valid. The text contains no spaces. Output Print the given XML-text according to the above-given rules. Examples Input &lt;a&gt;&lt;b&gt;&lt;c&gt;&lt;/c&gt;&lt;/b&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;c&gt; &lt;/c&gt; &lt;/b&gt; &lt;/a&gt; Input &lt;a&gt;&lt;b&gt;&lt;/b&gt;&lt;d&gt;&lt;c&gt;&lt;/c&gt;&lt;/d&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;/b&gt; &lt;d&gt; &lt;c&gt; &lt;/c&gt; &lt;/d&gt; &lt;/a&gt; Tags: implementation Correct Solution: ``` a = input().split('>') #print(*a) bal = 0 for s in a: if len(s) == 0: continue if (s[1] == '/' ): bal -= 1 print(bal * " " + s+ ">") else: print(bal * " " + s + ">") bal +=1 ```
97,976
Provide tags and a correct Python 3 solution for this coding contest problem. Let's define a string <x> as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type </x>, where x is the same letter. Tegs can be nested into each other: in this case one opening and closing tag pair is located inside another pair. Let's define the notion of a XML-text: * an empty string is a XML-text * if s is a XML-text, then s'=<a>+s+</a> also is a XML-text, where a is any small Latin letter * if s1, s2 are XML-texts, then s1+s2 also is a XML-text You are given a XML-text (it is guaranteed that the text is valid), your task is to print in the following form: * each tag (opening and closing) is located on a single line * print before the tag 2 * h spaces, where h is the level of the tag's nestedness. Input The input data consists on the only non-empty string β€” the XML-text, its length does not exceed 1000 characters. It is guaranteed that the text is valid. The text contains no spaces. Output Print the given XML-text according to the above-given rules. Examples Input &lt;a&gt;&lt;b&gt;&lt;c&gt;&lt;/c&gt;&lt;/b&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;c&gt; &lt;/c&gt; &lt;/b&gt; &lt;/a&gt; Input &lt;a&gt;&lt;b&gt;&lt;/b&gt;&lt;d&gt;&lt;c&gt;&lt;/c&gt;&lt;/d&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;/b&gt; &lt;d&gt; &lt;c&gt; &lt;/c&gt; &lt;/d&gt; &lt;/a&gt; Tags: implementation Correct Solution: ``` s=input() s1=s.split('<') del s1[0] c=0 for i in s1: if '/' in i: print(' '*(c-1),'<',i,sep='') c-=1 else: print(' '*c,'<',i,sep='') c+=1 ```
97,977
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's define a string <x> as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type </x>, where x is the same letter. Tegs can be nested into each other: in this case one opening and closing tag pair is located inside another pair. Let's define the notion of a XML-text: * an empty string is a XML-text * if s is a XML-text, then s'=<a>+s+</a> also is a XML-text, where a is any small Latin letter * if s1, s2 are XML-texts, then s1+s2 also is a XML-text You are given a XML-text (it is guaranteed that the text is valid), your task is to print in the following form: * each tag (opening and closing) is located on a single line * print before the tag 2 * h spaces, where h is the level of the tag's nestedness. Input The input data consists on the only non-empty string β€” the XML-text, its length does not exceed 1000 characters. It is guaranteed that the text is valid. The text contains no spaces. Output Print the given XML-text according to the above-given rules. Examples Input &lt;a&gt;&lt;b&gt;&lt;c&gt;&lt;/c&gt;&lt;/b&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;c&gt; &lt;/c&gt; &lt;/b&gt; &lt;/a&gt; Input &lt;a&gt;&lt;b&gt;&lt;/b&gt;&lt;d&gt;&lt;c&gt;&lt;/c&gt;&lt;/d&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;/b&gt; &lt;d&gt; &lt;c&gt; &lt;/c&gt; &lt;/d&gt; &lt;/a&gt; Submitted Solution: ``` import math for m in range(1,2): #t = int(input()) s = str(input()) curr=[] i=0 #print(len(s)) j=0 for j in range(len(s)*2): #print(i) if i>=len(s): break if "/" in s[i:i+3+1]: #print(s[i:i+4]) if s[i+2] in curr: # print(curr) curr.reverse() index1= curr.index(s[i+2]) # print(index1) index1= len(curr) - index1-1 # print(curr) print(index1* " "+ s[i:i+3+1]) curr.remove(s[i+2]) curr.reverse() i+=4 else: #print(1) #if i>=37: # index1 = curr.index(s[i+1]) #print(s[i+1] not in curr, curr) if s[i+1] in curr: curr.append(s[i+1]) curr.reverse() index1 = curr.index(s[i+1]) index1=len(curr) - index1-1 print(index1* " "+ s[i:i+3]) curr.reverse() i+=3 continue curr.append(s[i+1]) index1 = curr.index(s[i+1]) print(index1*" "+s[i:i+3]) i+=3 ``` Yes
97,978
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's define a string <x> as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type </x>, where x is the same letter. Tegs can be nested into each other: in this case one opening and closing tag pair is located inside another pair. Let's define the notion of a XML-text: * an empty string is a XML-text * if s is a XML-text, then s'=<a>+s+</a> also is a XML-text, where a is any small Latin letter * if s1, s2 are XML-texts, then s1+s2 also is a XML-text You are given a XML-text (it is guaranteed that the text is valid), your task is to print in the following form: * each tag (opening and closing) is located on a single line * print before the tag 2 * h spaces, where h is the level of the tag's nestedness. Input The input data consists on the only non-empty string β€” the XML-text, its length does not exceed 1000 characters. It is guaranteed that the text is valid. The text contains no spaces. Output Print the given XML-text according to the above-given rules. Examples Input &lt;a&gt;&lt;b&gt;&lt;c&gt;&lt;/c&gt;&lt;/b&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;c&gt; &lt;/c&gt; &lt;/b&gt; &lt;/a&gt; Input &lt;a&gt;&lt;b&gt;&lt;/b&gt;&lt;d&gt;&lt;c&gt;&lt;/c&gt;&lt;/d&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;/b&gt; &lt;d&gt; &lt;c&gt; &lt;/c&gt; &lt;/d&gt; &lt;/a&gt; Submitted Solution: ``` text = input().strip() visited = [] spacing_level = 0 for i in range(len(text)): letter = text[i] if letter in "</>": continue if text[i-1] == '/': spacing_level -= 1 print(" " * spacing_level + "</" + letter + ">") else: print(" " * spacing_level + "<" + letter + ">") spacing_level += 1 ``` Yes
97,979
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's define a string <x> as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type </x>, where x is the same letter. Tegs can be nested into each other: in this case one opening and closing tag pair is located inside another pair. Let's define the notion of a XML-text: * an empty string is a XML-text * if s is a XML-text, then s'=<a>+s+</a> also is a XML-text, where a is any small Latin letter * if s1, s2 are XML-texts, then s1+s2 also is a XML-text You are given a XML-text (it is guaranteed that the text is valid), your task is to print in the following form: * each tag (opening and closing) is located on a single line * print before the tag 2 * h spaces, where h is the level of the tag's nestedness. Input The input data consists on the only non-empty string β€” the XML-text, its length does not exceed 1000 characters. It is guaranteed that the text is valid. The text contains no spaces. Output Print the given XML-text according to the above-given rules. Examples Input &lt;a&gt;&lt;b&gt;&lt;c&gt;&lt;/c&gt;&lt;/b&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;c&gt; &lt;/c&gt; &lt;/b&gt; &lt;/a&gt; Input &lt;a&gt;&lt;b&gt;&lt;/b&gt;&lt;d&gt;&lt;c&gt;&lt;/c&gt;&lt;/d&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;/b&gt; &lt;d&gt; &lt;c&gt; &lt;/c&gt; &lt;/d&gt; &lt;/a&gt; Submitted Solution: ``` s,k=input().split('<')[1:],0 for c in s: if c[0]=='/': print(' '*(k-1),'<',c,sep='') k-=1 else: print(' '*k,'<',c,sep='') k+=1 ``` Yes
97,980
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's define a string <x> as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type </x>, where x is the same letter. Tegs can be nested into each other: in this case one opening and closing tag pair is located inside another pair. Let's define the notion of a XML-text: * an empty string is a XML-text * if s is a XML-text, then s'=<a>+s+</a> also is a XML-text, where a is any small Latin letter * if s1, s2 are XML-texts, then s1+s2 also is a XML-text You are given a XML-text (it is guaranteed that the text is valid), your task is to print in the following form: * each tag (opening and closing) is located on a single line * print before the tag 2 * h spaces, where h is the level of the tag's nestedness. Input The input data consists on the only non-empty string β€” the XML-text, its length does not exceed 1000 characters. It is guaranteed that the text is valid. The text contains no spaces. Output Print the given XML-text according to the above-given rules. Examples Input &lt;a&gt;&lt;b&gt;&lt;c&gt;&lt;/c&gt;&lt;/b&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;c&gt; &lt;/c&gt; &lt;/b&gt; &lt;/a&gt; Input &lt;a&gt;&lt;b&gt;&lt;/b&gt;&lt;d&gt;&lt;c&gt;&lt;/c&gt;&lt;/d&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;/b&gt; &lt;d&gt; &lt;c&gt; &lt;/c&gt; &lt;/d&gt; &lt;/a&gt; Submitted Solution: ``` s = input().split('<')[1:] level = -1 arr = set() f = False for i in s: f = False if i[0]!='/': f = True if f: level+=1 print(" "*(2*level) + '<' + i) if not f: level-=1 # print(2*level) ``` Yes
97,981
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's define a string <x> as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type </x>, where x is the same letter. Tegs can be nested into each other: in this case one opening and closing tag pair is located inside another pair. Let's define the notion of a XML-text: * an empty string is a XML-text * if s is a XML-text, then s'=<a>+s+</a> also is a XML-text, where a is any small Latin letter * if s1, s2 are XML-texts, then s1+s2 also is a XML-text You are given a XML-text (it is guaranteed that the text is valid), your task is to print in the following form: * each tag (opening and closing) is located on a single line * print before the tag 2 * h spaces, where h is the level of the tag's nestedness. Input The input data consists on the only non-empty string β€” the XML-text, its length does not exceed 1000 characters. It is guaranteed that the text is valid. The text contains no spaces. Output Print the given XML-text according to the above-given rules. Examples Input &lt;a&gt;&lt;b&gt;&lt;c&gt;&lt;/c&gt;&lt;/b&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;c&gt; &lt;/c&gt; &lt;/b&gt; &lt;/a&gt; Input &lt;a&gt;&lt;b&gt;&lt;/b&gt;&lt;d&gt;&lt;c&gt;&lt;/c&gt;&lt;/d&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;/b&gt; &lt;d&gt; &lt;c&gt; &lt;/c&gt; &lt;/d&gt; &lt;/a&gt; Submitted Solution: ``` a = input().split('>') print(*a) bal = 0 for s in a: if len(s) == 0: continue if (s[1] == '/' ): bal -= 1 print(bal * " " + s+ ">") else: print(bal * " " + s + ">") bal +=1 ``` No
97,982
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's define a string <x> as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type </x>, where x is the same letter. Tegs can be nested into each other: in this case one opening and closing tag pair is located inside another pair. Let's define the notion of a XML-text: * an empty string is a XML-text * if s is a XML-text, then s'=<a>+s+</a> also is a XML-text, where a is any small Latin letter * if s1, s2 are XML-texts, then s1+s2 also is a XML-text You are given a XML-text (it is guaranteed that the text is valid), your task is to print in the following form: * each tag (opening and closing) is located on a single line * print before the tag 2 * h spaces, where h is the level of the tag's nestedness. Input The input data consists on the only non-empty string β€” the XML-text, its length does not exceed 1000 characters. It is guaranteed that the text is valid. The text contains no spaces. Output Print the given XML-text according to the above-given rules. Examples Input &lt;a&gt;&lt;b&gt;&lt;c&gt;&lt;/c&gt;&lt;/b&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;c&gt; &lt;/c&gt; &lt;/b&gt; &lt;/a&gt; Input &lt;a&gt;&lt;b&gt;&lt;/b&gt;&lt;d&gt;&lt;c&gt;&lt;/c&gt;&lt;/d&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;/b&gt; &lt;d&gt; &lt;c&gt; &lt;/c&gt; &lt;/d&gt; &lt;/a&gt; Submitted Solution: ``` from string import ascii_lowercase def print_end_tag(level, character): print(" " * level, f"</{character}>") def print_start_tag(level, character): print(" " * level, f"<{character}>") def main(): xml_line = input() counter = 0 last_character = '' for character in xml_line: if character == '<' or character == '>': continue if character in ascii_lowercase: end_tag = True if last_character == '/' else False if not end_tag: print_start_tag(counter, character) counter += 1 else: counter -= 1 print_end_tag(counter, character) last_character = character main() ``` No
97,983
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's define a string <x> as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type </x>, where x is the same letter. Tegs can be nested into each other: in this case one opening and closing tag pair is located inside another pair. Let's define the notion of a XML-text: * an empty string is a XML-text * if s is a XML-text, then s'=<a>+s+</a> also is a XML-text, where a is any small Latin letter * if s1, s2 are XML-texts, then s1+s2 also is a XML-text You are given a XML-text (it is guaranteed that the text is valid), your task is to print in the following form: * each tag (opening and closing) is located on a single line * print before the tag 2 * h spaces, where h is the level of the tag's nestedness. Input The input data consists on the only non-empty string β€” the XML-text, its length does not exceed 1000 characters. It is guaranteed that the text is valid. The text contains no spaces. Output Print the given XML-text according to the above-given rules. Examples Input &lt;a&gt;&lt;b&gt;&lt;c&gt;&lt;/c&gt;&lt;/b&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;c&gt; &lt;/c&gt; &lt;/b&gt; &lt;/a&gt; Input &lt;a&gt;&lt;b&gt;&lt;/b&gt;&lt;d&gt;&lt;c&gt;&lt;/c&gt;&lt;/d&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;/b&gt; &lt;d&gt; &lt;c&gt; &lt;/c&gt; &lt;/d&gt; &lt;/a&gt; Submitted Solution: ``` s = input().split('<')[1:] level = 1 arr = set() for i in s: print(" "*level + '<' + i) if i[0]!='/': level += 1 else: level -= 1 ``` No
97,984
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's define a string <x> as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type </x>, where x is the same letter. Tegs can be nested into each other: in this case one opening and closing tag pair is located inside another pair. Let's define the notion of a XML-text: * an empty string is a XML-text * if s is a XML-text, then s'=<a>+s+</a> also is a XML-text, where a is any small Latin letter * if s1, s2 are XML-texts, then s1+s2 also is a XML-text You are given a XML-text (it is guaranteed that the text is valid), your task is to print in the following form: * each tag (opening and closing) is located on a single line * print before the tag 2 * h spaces, where h is the level of the tag's nestedness. Input The input data consists on the only non-empty string β€” the XML-text, its length does not exceed 1000 characters. It is guaranteed that the text is valid. The text contains no spaces. Output Print the given XML-text according to the above-given rules. Examples Input &lt;a&gt;&lt;b&gt;&lt;c&gt;&lt;/c&gt;&lt;/b&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;c&gt; &lt;/c&gt; &lt;/b&gt; &lt;/a&gt; Input &lt;a&gt;&lt;b&gt;&lt;/b&gt;&lt;d&gt;&lt;c&gt;&lt;/c&gt;&lt;/d&gt;&lt;/a&gt; Output &lt;a&gt; &lt;b&gt; &lt;/b&gt; &lt;d&gt; &lt;c&gt; &lt;/c&gt; &lt;/d&gt; &lt;/a&gt; Submitted Solution: ``` n=input() ls=[] i=0 while (i<len(n)): if(n[i]=='<'): p='' j=i while(n[j]!='>'): p+=n[j] j+=1 p+='>' ls.append(p) i+=1 k=0 i=0 while i<len(ls): flag=0 if (ls[i].replace(' ','')[1]=='/'): i+=1 continue else: j=i+1 while (j<len(ls) and ls[j].replace(' ','').replace('/','')!=ls[i].replace(' ','')): ls[j]=' '*2+ls[j] j+=1 i+=1 for i in ls: print(i) ``` No
97,985
Provide tags and a correct Python 3 solution for this coding contest problem. You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ— c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad. Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a. In particular, a single use of your power is this: * You choose a horizontal 1 Γ— x subgrid or a vertical x Γ— 1 subgrid. That value of x is up to you; * You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; * You choose the number s of steps; * You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above. * The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ— 4 subgrid, the direction NORTH, and s = 2 steps. <image> You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country. What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism? With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so. Input The first line of input contains a single integer t (1 ≀ t ≀ 2β‹… 10^4) denoting the number of test cases. The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 ≀ r, c ≀ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where: * "A" means that the dominant religion is Beingawesomeism; * "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β‹… c in a single file is at most 3 β‹… 10^6. Output For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so. Example Input 4 7 8 AAPAAAAA PPPPAAAA PPPPAAAA APAAPPPP APAPPAPP AAAAPPAP AAAAPPAA 6 5 AAAAA AAAAA AAPAA AAPAP AAAPP AAAPP 4 4 PPPP PPPP PPPP PPPP 3 4 PPPP PAAP PPPP Output 2 1 MORTAL 4 Note In the first test case, it can be done in two usages, as follows: Usage 1: <image> Usage 2: <image> In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL". Tags: implementation, math Correct Solution: ``` # not my code, just an edit of https://codeforces.com/contest/1281/submission/66929709 import sys input = lambda: sys.stdin.readline().rstrip() for i in ' '*int(input()): a,b=map(int,input().split()) L=[] M=['']*b A=False P=False for j in ' '*a: s=input() if 'A' in s:A=True if 'P' in s:P=True for k in range(b): M[k]+=s[k] L.append(s) if not A: print('MORTAL') continue if not P: print(0) continue ss=L[0]+L[-1]+M[0]+M[-1] if 'P' not in L[0] or 'P' not in L[-1] or 'P' not in M[0] or 'P' not in M[-1]: print(1) continue if L[0][0]=='A' or L[0][-1]=='A' or L[-1][0]=='A' or L[-1][-1]=='A': print(2) continue A2=False for j in L: if 'P' not in j: A2=True for j in M: if 'P' not in j: A2=True if A2: print(2) continue if 'A' in ss:print(3) else:print(4) ```
97,986
Provide tags and a correct Python 3 solution for this coding contest problem. You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ— c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad. Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a. In particular, a single use of your power is this: * You choose a horizontal 1 Γ— x subgrid or a vertical x Γ— 1 subgrid. That value of x is up to you; * You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; * You choose the number s of steps; * You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above. * The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ— 4 subgrid, the direction NORTH, and s = 2 steps. <image> You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country. What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism? With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so. Input The first line of input contains a single integer t (1 ≀ t ≀ 2β‹… 10^4) denoting the number of test cases. The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 ≀ r, c ≀ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where: * "A" means that the dominant religion is Beingawesomeism; * "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β‹… c in a single file is at most 3 β‹… 10^6. Output For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so. Example Input 4 7 8 AAPAAAAA PPPPAAAA PPPPAAAA APAAPPPP APAPPAPP AAAAPPAP AAAAPPAA 6 5 AAAAA AAAAA AAPAA AAPAP AAAPP AAAPP 4 4 PPPP PPPP PPPP PPPP 3 4 PPPP PAAP PPPP Output 2 1 MORTAL 4 Note In the first test case, it can be done in two usages, as follows: Usage 1: <image> Usage 2: <image> In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL". Tags: implementation, math Correct Solution: ``` #qn given an arr of size n for every i position find a min j such that j>i and arr[j]>arr[i] #it prints the position of the nearest . import sys input = sys.stdin.readline #qn given an arr of size n for every i position find a min j such that j>i and arr[j]>arr[i] #it prints the position of the nearest . # import sys import heapq import copy import math #heapq.heapify(li) # #heapq.heappush(li,4) # #heapq.heappop(li) # # & Bitwise AND Operator 10 & 7 = 2 # | Bitwise OR Operator 10 | 7 = 15 # ^ Bitwise XOR Operator 10 ^ 7 = 13 # << Bitwise Left Shift operator 10<<2 = 40 # >> Bitwise Right Shift Operator '''############ ---- Input Functions ---- #######Start#####''' 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())) ############ ---- Input Functions ---- #######End # ##### class Node: def _init_(self,val): self.data = val self.left = None self.right = None ##to initialize wire : object_name= node(val)##to create a new node ## can also be used to create linked list class fen_tree: """Implementation of a Binary Indexed Tree (Fennwick Tree)""" #def __init__(self, list): # """Initialize BIT with list in O(n*log(n))""" # self.array = [0] * (len(list) + 1) # for idx, val in enumerate(list): # self.update(idx, val) def __init__(self, list): """"Initialize BIT with list in O(n)""" self.array = [0] + list for idx in range(1, len(self.array)): idx2 = idx + (idx & -idx) if idx2 < len(self.array): self.array[idx2] += self.array[idx] def prefix_query(self, idx): """Computes prefix sum of up to including the idx-th element""" # idx += 1 result = 0 while idx: result += self.array[idx] idx -= idx & -idx return result def prints(self): print(self.array) return # for i in self.array: # print(i,end = " ") # return def range_query(self, from_idx, to_idx): """Computes the range sum between two indices (both inclusive)""" return self.prefix_query(to_idx) - self.prefix_query(from_idx - 1) def update(self, idx, add): """Add a value to the idx-th element""" # idx += 1 while idx < len(self.array): self.array[idx] += add idx += idx & -idx def pre_sum(arr): #"""returns the prefix sum inclusive ie ith position in ans represent sum from 0 to ith position""" p = [0] for i in arr: p.append(p[-1] + i) p.pop(0) return p def pre_back(arr): #"""returns the prefix sum inclusive ie ith position in ans represent sum from 0 to ith position""" p = [0] for i in arr: p.append(p[-1] + i) p.pop(0) return p def bin_search(arr,l,r,val):#strickly greater if arr[r] <= val: return r+1 if r-l < 2: if arr[l]>val: return l else: return r mid = int((l+r)/2) if arr[mid] <= val: return bin_search(arr,mid,r,val) else: return bin_search(arr,l,mid,val) def search_leftmost(arr,val): def helper(arr,l,r,val): # print(arr) print(l,r) if arr[l] == val: return l if r -l <=1: if arr[r] == val: return r else: print("not found") return mid = int((r+l)/2) if arr[mid] >= val: return helper(arr,l,mid,val) else: return helper(arr,mid,r,val) return helper(arr,0,len(arr)-1,val) def search_rightmost(arr,val): def helper(arr,l,r,val): # print(arr) print(l,r) if arr[r] == val: return r if r -l <=1: if arr[l] == val: return r else: print("not found") return mid = int((r+l)/2) if arr[mid] > val: return helper(arr,l,mid,val) else: return helper(arr,mid,r,val) return helper(arr,0,len(arr)-1,val) def pr_list(a): print(*a, sep=" ") def main(): tests = inp() # tests = 1 mod = 1000000007 limit = 10**18 # print(limit) # if tests == 4: # # for i in range(4): # [r,c] = inlt() # grid = [] # for i in range(r): # grid.append(insr()) # print(2) # [r,c] = inlt() # grid = [] # for i in range(r): # grid.append(insr()) # print(1) # [r,c] = inlt() # grid = [] # for i in range(r): # grid.append(insr()) # print("MORTAL") # [r,c] = inlt() # grid = [] # for i in range(r): # grid.append(insr()) # print(4) # return for test in range(tests): [r,c] = inlt() grid = [] for i in range(r): grid.append(insr()) rows = [0 for i in range(r)] col = [ 0 for i in range(c)] for i in range(r): for j in range(c): if grid[i][j] == 'A': rows[i]+=1 col[j]+=1 # print(test) # if test == 11: # for i in grid: # print(i) # return # print(rows,col) if max(rows)==0: print("MORTAL") elif sum(rows) == r*c: print(0) elif rows[0] == c or col[0] == r or rows[-1]==c or col[-1] == r: print(1) # elif rows[0]!=0 or col[0]!=0 or rows[-1] != 0 or col[-1]!= 0: elif grid[0][0] == 'A' or grid[-1][0] == 'A' or grid[0][-1] == 'A' or grid[-1][-1] == 'A'or max(rows) == c or max(col) == r: print(2) elif rows[0] != 0 or col[0] !=0 or col[-1]!=0 or rows[-1]!=0: print(3) else: print(4) # print(x_values) # for i in range(x): # if int(x_values[i])!=1: # n_new = i+1 + (n-i-1)*int(x_values[i]) # n = n_new%mod # print(n) if __name__== "__main__": main() ```
97,987
Provide tags and a correct Python 3 solution for this coding contest problem. You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ— c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad. Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a. In particular, a single use of your power is this: * You choose a horizontal 1 Γ— x subgrid or a vertical x Γ— 1 subgrid. That value of x is up to you; * You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; * You choose the number s of steps; * You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above. * The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ— 4 subgrid, the direction NORTH, and s = 2 steps. <image> You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country. What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism? With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so. Input The first line of input contains a single integer t (1 ≀ t ≀ 2β‹… 10^4) denoting the number of test cases. The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 ≀ r, c ≀ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where: * "A" means that the dominant religion is Beingawesomeism; * "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β‹… c in a single file is at most 3 β‹… 10^6. Output For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so. Example Input 4 7 8 AAPAAAAA PPPPAAAA PPPPAAAA APAAPPPP APAPPAPP AAAAPPAP AAAAPPAA 6 5 AAAAA AAAAA AAPAA AAPAP AAAPP AAAPP 4 4 PPPP PPPP PPPP PPPP 3 4 PPPP PAAP PPPP Output 2 1 MORTAL 4 Note In the first test case, it can be done in two usages, as follows: Usage 1: <image> Usage 2: <image> In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL". Tags: implementation, math Correct Solution: ``` import heapq import math from collections import * from functools import reduce,cmp_to_key import sys input = sys.stdin.readline M = mod = 10**9 + 7 def factors(n):return sorted(list(set(reduce(list.__add__,([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))) def inv_mod(n):return pow(n, mod - 2, mod) def li():return [int(i) for i in input().rstrip('\n').split(' ')] def st():return input().rstrip('\n') def val():return int(input()) def li2():return [i for i in input().rstrip('\n').split(' ')] for _ in range(val()): n, m = li() l = [] for i in range(n):l.append(st()) l1 = [set() for i in range(n)] l2 = [set() for i in range(m)] ans = -1 ans2 = -1 for i in range(n): for j in l[i]: if j == 'A': ans = 4 else: ans2 = 1 if ans == -1: print('MORTAL') continue if ans2 == -1: print(0) continue for i in range(n): for j in range(m): if l[i][j] == 'A': l1[i].add(j) l2[j].add(i) ans = 4 if len(l1[0]) == m or len(l1[-1]) == m or len(l2[0]) == n or len(l2[-1])== n: print(1) continue if (0 in l1[0] or 0 in l1[-1] or 0 in l2[0] or 0 in l2[-1] or m-1 in l1[0] or m-1 in l1[-1] or n-1 in l2[0] or n-1 in l2[-1]): print(2) continue for i in range(n): if len(l1[i]) == m: ans = 2 break for j in range(m): if len(l2[j]) == n: ans = 2 break if ans == 2: print(2) continue for i in range(n): if 0 in l1[i] or m-1 in l1[i]: ans = 3 break for j in range(m): if 0 in l2[j] or n-1 in l2[j]: ans = 3 break print(ans) ```
97,988
Provide tags and a correct Python 3 solution for this coding contest problem. You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ— c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad. Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a. In particular, a single use of your power is this: * You choose a horizontal 1 Γ— x subgrid or a vertical x Γ— 1 subgrid. That value of x is up to you; * You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; * You choose the number s of steps; * You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above. * The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ— 4 subgrid, the direction NORTH, and s = 2 steps. <image> You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country. What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism? With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so. Input The first line of input contains a single integer t (1 ≀ t ≀ 2β‹… 10^4) denoting the number of test cases. The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 ≀ r, c ≀ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where: * "A" means that the dominant religion is Beingawesomeism; * "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β‹… c in a single file is at most 3 β‹… 10^6. Output For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so. Example Input 4 7 8 AAPAAAAA PPPPAAAA PPPPAAAA APAAPPPP APAPPAPP AAAAPPAP AAAAPPAA 6 5 AAAAA AAAAA AAPAA AAPAP AAAPP AAAPP 4 4 PPPP PPPP PPPP PPPP 3 4 PPPP PAAP PPPP Output 2 1 MORTAL 4 Note In the first test case, it can be done in two usages, as follows: Usage 1: <image> Usage 2: <image> In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL". Tags: implementation, math Correct Solution: ``` import sys reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ def solve(): r,c = map(int, input().split()) board = [[int(j == "A") for j in input()] for i in range(r)] board2 = [list(x) for x in zip(*board)] s = sum(sum(board[i]) for i in range(r)) if s == 0: print("MORTAL") return elif s == r*c: print(0) return else: if any(sum(board[i])==c for i in [0,r-1]) or any(sum(board2[i])==r for i in [0,c-1]): print(1) return if board[0][0]+board[0][-1]+board[-1][0]+board[-1][-1]>0: print(2) return if any(sum(board[i])==c for i in range(r)) or any(sum(board2[i])==r for i in range(c)): print(2) return if any(sum(board[i])>0 for i in [0,r-1]) or any(sum(board2[i])>0 for i in [0, c-1]): print(3) return print(4) return t = int(input()) for i in range(t): solve() ```
97,989
Provide tags and a correct Python 3 solution for this coding contest problem. You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ— c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad. Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a. In particular, a single use of your power is this: * You choose a horizontal 1 Γ— x subgrid or a vertical x Γ— 1 subgrid. That value of x is up to you; * You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; * You choose the number s of steps; * You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above. * The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ— 4 subgrid, the direction NORTH, and s = 2 steps. <image> You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country. What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism? With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so. Input The first line of input contains a single integer t (1 ≀ t ≀ 2β‹… 10^4) denoting the number of test cases. The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 ≀ r, c ≀ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where: * "A" means that the dominant religion is Beingawesomeism; * "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β‹… c in a single file is at most 3 β‹… 10^6. Output For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so. Example Input 4 7 8 AAPAAAAA PPPPAAAA PPPPAAAA APAAPPPP APAPPAPP AAAAPPAP AAAAPPAA 6 5 AAAAA AAAAA AAPAA AAPAP AAAPP AAAPP 4 4 PPPP PPPP PPPP PPPP 3 4 PPPP PAAP PPPP Output 2 1 MORTAL 4 Note In the first test case, it can be done in two usages, as follows: Usage 1: <image> Usage 2: <image> In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL". Tags: implementation, math Correct Solution: ``` # ------------------- fast io -------------------- 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") # ------------------- fast io -------------------- from math import gcd, ceil def prod(a, mod=10**9+7): ans = 1 for each in a: ans = (ans * each) % mod return ans def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y for _ in range(int(input()) if True else 1): #n = int(input()) n, m = map(int, input().split()) #a, b = map(int, input().split()) #c, d = map(int, input().split()) #a = list(map(int, input().split())) #b = list(map(int, input().split())) #s = input() a = [] for i in range(n): a += [[k for k in input()]] pos = False has = False for i in range(n): for j in range(m): if a[i][j] == 'A': pos=True else: has = True if not pos: print("MORTAL") continue if not has: print(0) continue first_row = a[0] last_row = a[-1] first_col = [a[k][0] for k in range(n)] last_col = [a[k][-1] for k in range(n)] if first_row == ['A'] * m or last_row == ['A']*m or first_col == ['A']*n or last_col == ['A']*n: print(1) continue pos = False for i in a: if i == ['A']*m: pos=True break for j in range(m): if [a[i][j] for i in range(n)] == ['A']*n: pos = True break if 'A' in [a[0][0], a[0][-1], a[-1][0], a[-1][-1]] or min(n,m) == 1 or pos: print(2) continue if 'A' in first_row+first_col+last_col+last_row: print(3) continue print(4) ```
97,990
Provide tags and a correct Python 3 solution for this coding contest problem. You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ— c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad. Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a. In particular, a single use of your power is this: * You choose a horizontal 1 Γ— x subgrid or a vertical x Γ— 1 subgrid. That value of x is up to you; * You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; * You choose the number s of steps; * You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above. * The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ— 4 subgrid, the direction NORTH, and s = 2 steps. <image> You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country. What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism? With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so. Input The first line of input contains a single integer t (1 ≀ t ≀ 2β‹… 10^4) denoting the number of test cases. The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 ≀ r, c ≀ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where: * "A" means that the dominant religion is Beingawesomeism; * "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β‹… c in a single file is at most 3 β‹… 10^6. Output For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so. Example Input 4 7 8 AAPAAAAA PPPPAAAA PPPPAAAA APAAPPPP APAPPAPP AAAAPPAP AAAAPPAA 6 5 AAAAA AAAAA AAPAA AAPAP AAAPP AAAPP 4 4 PPPP PPPP PPPP PPPP 3 4 PPPP PAAP PPPP Output 2 1 MORTAL 4 Note In the first test case, it can be done in two usages, as follows: Usage 1: <image> Usage 2: <image> In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL". Tags: implementation, math Correct Solution: ``` def fastio(): import sys from io import StringIO from atexit import register global input sys.stdin = StringIO(sys.stdin.read()) input = lambda : sys.stdin.readline().rstrip('\r\n') sys.stdout = StringIO() register(lambda : sys.__stdout__.write(sys.stdout.getvalue())) fastio() MOD = 10**9 + 7 I = lambda:list(map(int,input().split())) from math import gcd from collections import defaultdict as dd t, = I() while t: t -= 1 n, m = I() g = [] c = [[] for i in range(m)] p = False a = False for i in range(n): g.append(input()) s = g[-1] for j in range(m): if s[j] == 'A': a = True else: p = True c[j].append(s[j]) if not p: print(0) continue if not a: print('MORTAL') continue ans = 4 for i in range(n): if 'P' not in g[i]: if i == 0 or i == n-1: ans = 1 break else: ans = min(ans, 2) for i in range(m): if 'P' not in c[i]: if i == 0 or i == m-1: ans = 1 break else: ans = min(ans, 2) if 'A' in [g[0][0], g[0][-1], g[-1][0], g[-1][-1]]: ans = min(ans, 2) for i in range(m): if g[0][i] == 'A' or g[-1][i] == 'A': ans = min(ans, 3) break for i in range(n): if g[i][0] == 'A' or g[i][-1] == 'A': ans = min(ans, 3) print(ans) ```
97,991
Provide tags and a correct Python 3 solution for this coding contest problem. You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ— c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad. Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a. In particular, a single use of your power is this: * You choose a horizontal 1 Γ— x subgrid or a vertical x Γ— 1 subgrid. That value of x is up to you; * You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; * You choose the number s of steps; * You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above. * The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ— 4 subgrid, the direction NORTH, and s = 2 steps. <image> You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country. What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism? With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so. Input The first line of input contains a single integer t (1 ≀ t ≀ 2β‹… 10^4) denoting the number of test cases. The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 ≀ r, c ≀ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where: * "A" means that the dominant religion is Beingawesomeism; * "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β‹… c in a single file is at most 3 β‹… 10^6. Output For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so. Example Input 4 7 8 AAPAAAAA PPPPAAAA PPPPAAAA APAAPPPP APAPPAPP AAAAPPAP AAAAPPAA 6 5 AAAAA AAAAA AAPAA AAPAP AAAPP AAAPP 4 4 PPPP PPPP PPPP PPPP 3 4 PPPP PAAP PPPP Output 2 1 MORTAL 4 Note In the first test case, it can be done in two usages, as follows: Usage 1: <image> Usage 2: <image> In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL". Tags: implementation, math Correct Solution: ``` import sys input = sys.stdin.readline def getInt(): return int(input()) def getVars(): return map(int, input().split()) def getList(): return list(map(int, input().split())) def getStr(): return input().strip() ## ------------------------------- t = getInt() for _ in range(t): rows, columns = getVars() allA = True firstARow = False firstAColumn1 = True firstAColumn2 = True inCorner = False rowA = False oneInFirst = False one = False d = [1]*(max(columns-2, 0)) for r in range(rows): s = getStr() if allA and s != 'A' * len(s): allA = False if ((r == 0) or r == (rows-1)) and s == 'A' * len(s): firstARow = True if firstAColumn1 and s[0] != 'A': firstAColumn1 = False if firstAColumn2 and s[-1] != 'A': firstAColumn2 = False if ((r == 0) or r == (rows-1)) and (s[0] == 'A' or s[-1] == 'A'): inCorner = True if (not rowA) and (s == 'A' * len(s)): rowA = True for j in range(columns-2): if d[j] == 1 and s[j+1] == 'P': d[j] = 0 if ((r == 0) or r == (rows-1)) and s != 'P' * len(s): oneInFirst = True if (not oneInFirst) and (s[0] == 'A' or s[-1] == 'A'): oneInFirst = True if (not one) and s != 'P' * len(s): one = True if allA: print(0) elif firstARow or firstAColumn1 or firstAColumn2: print(1) elif inCorner or rowA or (len(d) > 0 and max(d) == 1):print(2) elif oneInFirst: print(3) elif one:print(4) else: print('MORTAL') ```
97,992
Provide tags and a correct Python 3 solution for this coding contest problem. You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ— c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad. Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a. In particular, a single use of your power is this: * You choose a horizontal 1 Γ— x subgrid or a vertical x Γ— 1 subgrid. That value of x is up to you; * You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; * You choose the number s of steps; * You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above. * The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ— 4 subgrid, the direction NORTH, and s = 2 steps. <image> You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country. What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism? With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so. Input The first line of input contains a single integer t (1 ≀ t ≀ 2β‹… 10^4) denoting the number of test cases. The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 ≀ r, c ≀ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where: * "A" means that the dominant religion is Beingawesomeism; * "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β‹… c in a single file is at most 3 β‹… 10^6. Output For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so. Example Input 4 7 8 AAPAAAAA PPPPAAAA PPPPAAAA APAAPPPP APAPPAPP AAAAPPAP AAAAPPAA 6 5 AAAAA AAAAA AAPAA AAPAP AAAPP AAAPP 4 4 PPPP PPPP PPPP PPPP 3 4 PPPP PAAP PPPP Output 2 1 MORTAL 4 Note In the first test case, it can be done in two usages, as follows: Usage 1: <image> Usage 2: <image> In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL". Tags: implementation, math Correct Solution: ``` import sys # inf = open('input.txt', 'r') # reader = (line.rstrip() for line in inf) reader = (line.rstrip() for line in sys.stdin) n = int(next(reader)) for _ in range(n): r, c = [int(x) for x in next(reader).split()] turns = float('inf') cols = [[] for j in range(c)] onlyA = True onlyP = True for i in range(r): row = [el == 'A' for el in next(reader)] if onlyA: onlyA = all(row) if onlyP: onlyP = not(any(row)) if all(row): if 0 < i < r-1: turns = min(turns, 2) else: turns = min(turns, 1) elif row[0] or row[-1]: if 0 < i < r-1: turns = min(turns, 3) else: turns = min(turns, 2) elif any(row): if 0 < i < r-1: turns = min(turns, 4) else: turns = min(turns, 3) for j, el in enumerate(row): cols[j].append(el) for i in range(c): col = cols[i] if all(col): if 0 < i < c-1: turns = min(turns, 2) else: turns = min(turns, 1) if onlyA: print(0) elif onlyP: print('MORTAL') else: print(turns) # inf.close() ```
97,993
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ— c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad. Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a. In particular, a single use of your power is this: * You choose a horizontal 1 Γ— x subgrid or a vertical x Γ— 1 subgrid. That value of x is up to you; * You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; * You choose the number s of steps; * You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above. * The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ— 4 subgrid, the direction NORTH, and s = 2 steps. <image> You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country. What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism? With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so. Input The first line of input contains a single integer t (1 ≀ t ≀ 2β‹… 10^4) denoting the number of test cases. The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 ≀ r, c ≀ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where: * "A" means that the dominant religion is Beingawesomeism; * "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β‹… c in a single file is at most 3 β‹… 10^6. Output For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so. Example Input 4 7 8 AAPAAAAA PPPPAAAA PPPPAAAA APAAPPPP APAPPAPP AAAAPPAP AAAAPPAA 6 5 AAAAA AAAAA AAPAA AAPAP AAAPP AAAPP 4 4 PPPP PPPP PPPP PPPP 3 4 PPPP PAAP PPPP Output 2 1 MORTAL 4 Note In the first test case, it can be done in two usages, as follows: Usage 1: <image> Usage 2: <image> In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL". Submitted Solution: ``` import math, collections, sys input = sys.stdin.readline def calc(r, c): rows = [0 for i in range(r)] cols = [0 for i in range(c)] total = 0 for i in range(r): for j in range(c): if z[i][j] == 'A': rows[i]+=1 cols[j]+=1 total+=1 if total == r*c: return 0 if total == 0: return "MORTAL" if rows[0] == c or rows[-1] == c or cols[0] == r or cols[-1] == r: return 1 if z[0][0] == 'A' or z[0][-1] == 'A' or z[-1][0] == 'A' or z[-1][-1] == 'A': return 2 if max(rows) == c or max(cols) == r: return 2 if rows[0] or rows[-1] or cols[0] or cols[-1]: return 3 return 4 for _ in range(int(input())): r, c = map(int, input().split()) z = [] for i in range(r): z.append(input().strip()) print(calc(r, c)) ``` Yes
97,994
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ— c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad. Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a. In particular, a single use of your power is this: * You choose a horizontal 1 Γ— x subgrid or a vertical x Γ— 1 subgrid. That value of x is up to you; * You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; * You choose the number s of steps; * You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above. * The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ— 4 subgrid, the direction NORTH, and s = 2 steps. <image> You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country. What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism? With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so. Input The first line of input contains a single integer t (1 ≀ t ≀ 2β‹… 10^4) denoting the number of test cases. The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 ≀ r, c ≀ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where: * "A" means that the dominant religion is Beingawesomeism; * "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β‹… c in a single file is at most 3 β‹… 10^6. Output For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so. Example Input 4 7 8 AAPAAAAA PPPPAAAA PPPPAAAA APAAPPPP APAPPAPP AAAAPPAP AAAAPPAA 6 5 AAAAA AAAAA AAPAA AAPAP AAAPP AAAPP 4 4 PPPP PPPP PPPP PPPP 3 4 PPPP PAAP PPPP Output 2 1 MORTAL 4 Note In the first test case, it can be done in two usages, as follows: Usage 1: <image> Usage 2: <image> In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL". Submitted Solution: ``` """ This template is made by Satwik_Tiwari. python programmers can use this template :)) . """ #=============================================================================================== #importing some useful libraries. import sys import bisect import heapq from math import * 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 #=============================================================================================== #some shortcuts mod = pow(10, 9) + 7 def inp(): return sys.stdin.readline().strip() #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 nl(): out("\n") #as stdout.write always print sring. def testcase(t): for p in range(t): solve() def printlist(a) : for p in range(0,len(a)): out(str(a[p]) + ' ') def lcm(a,b): return (a*b)//gcd(a,b) #=============================================================================================== # code here ;)) def solve(): n,m = sep() a = [] f0 = True imp = True for i in range(0,n): temp = list(inp()) if(temp.count('A') < m): f0 = False if(temp.count('A') > 0): imp = False a.append(temp) if(imp): print('MORTAL') elif(f0): print(0) else: col = [] for j in range(0,m): temp = [] for i in range(0,n): temp.append(a[i][j]) col.append(temp) if(a[0].count('A')==m or a[n-1].count('A')==m or col[m-1].count('A')==n or col[0].count('A')==n): print(1) else: f1 = False f2 = False f3 = False cnt = 0 for i in range(0,n): cnt = max(cnt,a[i].count('A')) if(cnt==m): f1 = True cnt = 0 for i in range(0,m): cnt = max(cnt,col[i].count('A')) if(cnt==n): f2 = True if(a[0][0]=='A' or a[0][m-1]=='A' or a[n-1][0]=='A' or a[n-1][m-1]=='A'): f3 = True if(f1 or f2 or f3): print(2) else: if(a[0].count('A')>0 or a[n-1].count('A')>0 or col[0].count('A')>0 or col[m-1].count('A')>0): print(3) else: print(4) testcase(int(inp())) # testcase(1) ``` Yes
97,995
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ— c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad. Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a. In particular, a single use of your power is this: * You choose a horizontal 1 Γ— x subgrid or a vertical x Γ— 1 subgrid. That value of x is up to you; * You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; * You choose the number s of steps; * You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above. * The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ— 4 subgrid, the direction NORTH, and s = 2 steps. <image> You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country. What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism? With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so. Input The first line of input contains a single integer t (1 ≀ t ≀ 2β‹… 10^4) denoting the number of test cases. The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 ≀ r, c ≀ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where: * "A" means that the dominant religion is Beingawesomeism; * "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β‹… c in a single file is at most 3 β‹… 10^6. Output For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so. Example Input 4 7 8 AAPAAAAA PPPPAAAA PPPPAAAA APAAPPPP APAPPAPP AAAAPPAP AAAAPPAA 6 5 AAAAA AAAAA AAPAA AAPAP AAAPP AAAPP 4 4 PPPP PPPP PPPP PPPP 3 4 PPPP PAAP PPPP Output 2 1 MORTAL 4 Note In the first test case, it can be done in two usages, as follows: Usage 1: <image> Usage 2: <image> In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL". Submitted Solution: ``` INF = 10**10 def main(): print = out.append ''' Cook your dish here! ''' r, c = get_list() mat = [list(input()) for _ in range(r)] # Chech all A all_A = True for li in mat: if 'P' in li: all_A = False if all_A: print(0) return res = chk_Mat(mat) new_mat = [] for i in range(c): li = [] for j in range(r): li.append(mat[j][i]) new_mat.append(li) res = min(res, chk_Mat(new_mat)) print(res) if res<=4 else print("MORTAL") def chk_Mat(mat): r, c = len(mat), len(mat[0]) def row_cst(row): if 'P' not in mat[row]: return 0 if mat[row][0]=='A' or mat[row][-1]=='A': return 1 return 2 if 'A' in mat[row] else INF res = min(row_cst(0) + 1, row_cst(-1) + 1) for j in range(1, r-1): res = min(res, row_cst(j)+2) return res ''' Coded with love at Satyam Kumar, India ''' import sys #from collections import defaultdict, Counter #from functools import reduce #import math input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ out = [] get_int = lambda: int(input()) get_list = lambda: list(map(int, input().split())) #main() [main() for _ in range(int(input()))] print(*out, sep='\n') ``` Yes
97,996
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ— c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad. Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a. In particular, a single use of your power is this: * You choose a horizontal 1 Γ— x subgrid or a vertical x Γ— 1 subgrid. That value of x is up to you; * You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; * You choose the number s of steps; * You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above. * The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ— 4 subgrid, the direction NORTH, and s = 2 steps. <image> You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country. What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism? With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so. Input The first line of input contains a single integer t (1 ≀ t ≀ 2β‹… 10^4) denoting the number of test cases. The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 ≀ r, c ≀ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where: * "A" means that the dominant religion is Beingawesomeism; * "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β‹… c in a single file is at most 3 β‹… 10^6. Output For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so. Example Input 4 7 8 AAPAAAAA PPPPAAAA PPPPAAAA APAAPPPP APAPPAPP AAAAPPAP AAAAPPAA 6 5 AAAAA AAAAA AAPAA AAPAP AAAPP AAAPP 4 4 PPPP PPPP PPPP PPPP 3 4 PPPP PAAP PPPP Output 2 1 MORTAL 4 Note In the first test case, it can be done in two usages, as follows: Usage 1: <image> Usage 2: <image> In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL". Submitted Solution: ``` import sys input=sys.stdin.readline t=int(input()) for _ in range(t): r,c=map(int,input().split()) grid=[] for i in range(r): l=list(map(str,input().strip())) l2=[1 if j=='A' else 0 for j in l] grid+=[l2] summ=0 for i in grid: summ+=sum(i) if(summ==0): print('MORTAL') elif(summ==r*c): print(0) else: co=0 last=0 ex=0 for i in range(len(grid)): if(grid[i][0]!=1): last=1 else: ex+=1 if(last==1): last=0 for i in range(len(grid)): if(grid[i][-1]!=1): last=1 else: ex+=1 if(last==1): last=0 for i in range(len(grid[0])): if(grid[0][i]!=1): last=1 else: ex+=1 if(last==1): last=0 for i in range(len(grid[0])): if(grid[-1][i]!=1): last=1 else: ex+=1 if(last==0): print(1) else: flag=0 if(grid[0][0]==1 or grid[-1][0]==1 or grid[0][-1]==1 or grid[-1][-1]==1): co=1 for i in grid: if(sum(i)==c): flag=1 break for i in range(c): s=0 for j in range(r): s+=grid[j][i] if(s==r): flag=1 break if(co==1): if(len(grid)==1 or len(grid[0])==1): print(1) else: print(2) elif(flag==1): print(2) elif(co!=1 and ex>0): if(len(grid)==1 or len(grid[0])==1): print(2) else: print(3) else: print(4) ``` Yes
97,997
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ— c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad. Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a. In particular, a single use of your power is this: * You choose a horizontal 1 Γ— x subgrid or a vertical x Γ— 1 subgrid. That value of x is up to you; * You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; * You choose the number s of steps; * You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above. * The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ— 4 subgrid, the direction NORTH, and s = 2 steps. <image> You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country. What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism? With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so. Input The first line of input contains a single integer t (1 ≀ t ≀ 2β‹… 10^4) denoting the number of test cases. The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 ≀ r, c ≀ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where: * "A" means that the dominant religion is Beingawesomeism; * "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β‹… c in a single file is at most 3 β‹… 10^6. Output For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so. Example Input 4 7 8 AAPAAAAA PPPPAAAA PPPPAAAA APAAPPPP APAPPAPP AAAAPPAP AAAAPPAA 6 5 AAAAA AAAAA AAPAA AAPAP AAAPP AAAPP 4 4 PPPP PPPP PPPP PPPP 3 4 PPPP PAAP PPPP Output 2 1 MORTAL 4 Note In the first test case, it can be done in two usages, as follows: Usage 1: <image> Usage 2: <image> In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL". Submitted Solution: ``` import heapq import math from collections import * from functools import reduce,cmp_to_key import sys input = sys.stdin.readline M = mod = 10**9 + 7 def factors(n):return sorted(list(set(reduce(list.__add__,([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))) def inv_mod(n):return pow(n, mod - 2, mod) def li():return [int(i) for i in input().rstrip('\n').split(' ')] def st():return input().rstrip('\n') def val():return int(input()) def li2():return [i for i in input().rstrip('\n').split(' ')] for _ in range(val()): n, m = li() l = [] for i in range(n):l.append(st()) l1 = [set() for i in range(n)] l2 = [set() for i in range(m)] ans = -1 ans2 = -1 for i in range(n): for j in l[i]: if j == 'A': ans = 4 else: ans2 = 1 if ans == -1: print('MORTAL') continue if ans2 == -1: print(0) continue for i in range(n): for j in range(m): if l[i][j] == 'A': l1[i].add(j) l2[j].add(i) # if i == 0: # print(l[i][j],l1) # print(n,m) # print(l1) # print(l2) # print(l[0]) if len(l1[0]) == m or len(l1[-1]) == m or len(l2[0]) == n or len(l2[-1] )== n: print(1) continue for i in range(n): for j in range(n): if len(l1[i]|l1[j]) == m: ans = 2 break for i in range(m): for j in range(m): if len(l2[i]|l2[j]) == n: ans = 2 break if ans == 2: print(2) continue if len(l1[0]) or len(l1[-1]) or len(l2[0]) or len(l2[-1]): print(3) continue print(4) ``` No
97,998
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ— c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad. Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a. In particular, a single use of your power is this: * You choose a horizontal 1 Γ— x subgrid or a vertical x Γ— 1 subgrid. That value of x is up to you; * You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST; * You choose the number s of steps; * You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above. * The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid. The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ— 4 subgrid, the direction NORTH, and s = 2 steps. <image> You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country. What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism? With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so. Input The first line of input contains a single integer t (1 ≀ t ≀ 2β‹… 10^4) denoting the number of test cases. The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 ≀ r, c ≀ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where: * "A" means that the dominant religion is Beingawesomeism; * "P" means that the dominant religion is Pushingittoofarism. It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β‹… c in a single file is at most 3 β‹… 10^6. Output For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so. Example Input 4 7 8 AAPAAAAA PPPPAAAA PPPPAAAA APAAPPPP APAPPAPP AAAAPPAP AAAAPPAA 6 5 AAAAA AAAAA AAPAA AAPAP AAAPP AAAPP 4 4 PPPP PPPP PPPP PPPP 3 4 PPPP PAAP PPPP Output 2 1 MORTAL 4 Note In the first test case, it can be done in two usages, as follows: Usage 1: <image> Usage 2: <image> In the second test case, it can be done with just one usage of the power. In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL". Submitted Solution: ``` #qn given an arr of size n for every i position find a min j such that j>i and arr[j]>arr[i] #it prints the position of the nearest . import sys input = sys.stdin.readline #qn given an arr of size n for every i position find a min j such that j>i and arr[j]>arr[i] #it prints the position of the nearest . # import sys import heapq import copy import math #heapq.heapify(li) # #heapq.heappush(li,4) # #heapq.heappop(li) # # & Bitwise AND Operator 10 & 7 = 2 # | Bitwise OR Operator 10 | 7 = 15 # ^ Bitwise XOR Operator 10 ^ 7 = 13 # << Bitwise Left Shift operator 10<<2 = 40 # >> Bitwise Right Shift Operator '''############ ---- Input Functions ---- #######Start#####''' 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())) ############ ---- Input Functions ---- #######End # ##### class Node: def _init_(self,val): self.data = val self.left = None self.right = None ##to initialize wire : object_name= node(val)##to create a new node ## can also be used to create linked list class fen_tree: """Implementation of a Binary Indexed Tree (Fennwick Tree)""" #def __init__(self, list): # """Initialize BIT with list in O(n*log(n))""" # self.array = [0] * (len(list) + 1) # for idx, val in enumerate(list): # self.update(idx, val) def __init__(self, list): """"Initialize BIT with list in O(n)""" self.array = [0] + list for idx in range(1, len(self.array)): idx2 = idx + (idx & -idx) if idx2 < len(self.array): self.array[idx2] += self.array[idx] def prefix_query(self, idx): """Computes prefix sum of up to including the idx-th element""" # idx += 1 result = 0 while idx: result += self.array[idx] idx -= idx & -idx return result def prints(self): print(self.array) return # for i in self.array: # print(i,end = " ") # return def range_query(self, from_idx, to_idx): """Computes the range sum between two indices (both inclusive)""" return self.prefix_query(to_idx) - self.prefix_query(from_idx - 1) def update(self, idx, add): """Add a value to the idx-th element""" # idx += 1 while idx < len(self.array): self.array[idx] += add idx += idx & -idx def pre_sum(arr): #"""returns the prefix sum inclusive ie ith position in ans represent sum from 0 to ith position""" p = [0] for i in arr: p.append(p[-1] + i) p.pop(0) return p def pre_back(arr): #"""returns the prefix sum inclusive ie ith position in ans represent sum from 0 to ith position""" p = [0] for i in arr: p.append(p[-1] + i) p.pop(0) return p def bin_search(arr,l,r,val):#strickly greater if arr[r] <= val: return r+1 if r-l < 2: if arr[l]>val: return l else: return r mid = int((l+r)/2) if arr[mid] <= val: return bin_search(arr,mid,r,val) else: return bin_search(arr,l,mid,val) def search_leftmost(arr,val): def helper(arr,l,r,val): # print(arr) print(l,r) if arr[l] == val: return l if r -l <=1: if arr[r] == val: return r else: print("not found") return mid = int((r+l)/2) if arr[mid] >= val: return helper(arr,l,mid,val) else: return helper(arr,mid,r,val) return helper(arr,0,len(arr)-1,val) def search_rightmost(arr,val): def helper(arr,l,r,val): # print(arr) print(l,r) if arr[r] == val: return r if r -l <=1: if arr[l] == val: return r else: print("not found") return mid = int((r+l)/2) if arr[mid] > val: return helper(arr,l,mid,val) else: return helper(arr,mid,r,val) return helper(arr,0,len(arr)-1,val) def pr_list(a): print(*a, sep=" ") def main(): tests = inp() # tests = 1 mod = 1000000007 limit = 10**18 # print(limit) if tests == 4: # for i in range(4): [r,c] = inlt() grid = [] for i in range(r): grid.append(insr()) print(2) [r,c] = inlt() grid = [] for i in range(r): grid.append(insr()) print(1) [r,c] = inlt() grid = [] for i in range(r): grid.append(insr()) print("MORTAL") [r,c] = inlt() grid = [] for i in range(r): grid.append(insr()) print(4) return for test in range(tests): [r,c] = inlt() grid = [] for i in range(r): grid.append(insr()) rows = [0 for i in range(r)] col = [ 0 for i in range(c)] for i in range(r): for j in range(c): if grid[i][j] == 'A': rows[i]+=1 col[j]+=1 print(test) for i in grid: print(i) return # print(rows,col) if max(rows)==0: print("MORTAL") elif sum(rows) == r*c: print(0) elif max(rows) == c or max(col) == r: print(1) # elif rows[0]!=0 or col[0]!=0 or rows[-1] != 0 or col[-1]!= 0: elif grid[0][0] == 'A' or grid[-1][0] == 'A' or grid[0][-1] == 'A' or grid[-1][-1] == 'A': print(2) elif rows[0] != 0 or col[0] !=0 or col[-1]!=0 or rows[-1]!=0: print(3) else: print(4) # print(x_values) # for i in range(x): # if int(x_values[i])!=1: # n_new = i+1 + (n-i-1)*int(x_values[i]) # n = n_new%mod # print(n) if __name__== "__main__": main() ``` No
97,999