text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a of n integers. Count the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Input The first line contains one integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5). The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” array a. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case output the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Example Input 4 6 3 5 1 4 6 6 3 1 2 3 4 1 3 3 4 6 1 6 3 4 5 6 Output 1 3 3 10 Tags: data structures, hashing, math Correct Solution: ``` def main(): n=int(input()) a=list(map(int,input().split())) dictt={} for i in range(n): a[i]-=i # print(a) for x in a: if x in dictt: dictt[x]=dictt[x]+1 else: dictt[x]=1 ans=0 for x in dictt: cnt=dictt[x] ans+=cnt*(cnt-1)/2 # print("ans : "+str(int(ans))) print(int(ans)) t=int(input()) while t>0: main() t-=1 ```
12,700
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a of n integers. Count the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Input The first line contains one integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5). The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” array a. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case output the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Example Input 4 6 3 5 1 4 6 6 3 1 2 3 4 1 3 3 4 6 1 6 3 4 5 6 Output 1 3 3 10 Tags: data structures, hashing, math Correct Solution: ``` def solve(l,n): t={} for i in range(n): if (l[i]-i) in t: t[l[i]-i]+=1 else: t[l[i]-i]=1 ans=0 for i in t.values(): ans=ans+(i*(i-1))//2 return ans for _ in range(int(input())): n = int(input()) l = list(map(int,input().split( ))) print(solve(l,n),end=' ') ```
12,701
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a of n integers. Count the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Input The first line contains one integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5). The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” array a. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case output the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Example Input 4 6 3 5 1 4 6 6 3 1 2 3 4 1 3 3 4 6 1 6 3 4 5 6 Output 1 3 3 10 Tags: data structures, hashing, math Correct Solution: ``` t = int(input()) for _ in range(t): n = int(input()) a = list(map(int,input().split())) s = 0 k = {} for i in range(n): k[a[i]-i] = k.get(a[i]-i,0) + 1 for u in k.keys(): s += (k[u]*(k[u]-1))//2 print(s) print() ```
12,702
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a of n integers. Count the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Input The first line contains one integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5). The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” array a. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case output the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Example Input 4 6 3 5 1 4 6 6 3 1 2 3 4 1 3 3 4 6 1 6 3 4 5 6 Output 1 3 3 10 Tags: data structures, hashing, math Correct Solution: ``` from collections import defaultdict t=int(input()) for i in range(t): n=int(input()) ar=list(map(int,input().split())) d=defaultdict(int) ans=0 for i in range(n): ans+=d[ar[i]-i] d[ar[i]-i]+=1 print(ans) ```
12,703
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a of n integers. Count the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Input The first line contains one integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5). The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” array a. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case output the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Example Input 4 6 3 5 1 4 6 6 3 1 2 3 4 1 3 3 4 6 1 6 3 4 5 6 Output 1 3 3 10 Tags: data structures, hashing, math Correct Solution: ``` for _ in range(int(input())): n=int(input()) l=list(map(int,input().strip().split())) d={} for i in range(n): l[i]=l[i]-i d[l[i]]=d.get(l[i],0)+1 c=0 for i in d: if(d[i]>=2): c=c+(d[i]-1)*d[i]//2 print(c) ```
12,704
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an array a of n integers. Count the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Input The first line contains one integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5). The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” array a. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case output the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Example Input 4 6 3 5 1 4 6 6 3 1 2 3 4 1 3 3 4 6 1 6 3 4 5 6 Output 1 3 3 10 Tags: data structures, hashing, math Correct Solution: ``` #dt = {} for i in x: dt[i] = dt.get(i,0)+1 import sys;input = sys.stdin.readline #import io,os; input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline #for pypy inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()] for _ in range(1,inp()+1): n = inp() x = ip() y = [x[i]-i for i in range(n)] dt = {} for i in y: dt[i] = dt.get(i,0)+1 ans = 0 for i in dt: ans += dt[i]*(dt[i]-1)//2 print(ans) ```
12,705
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of n integers. Count the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Input The first line contains one integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5). The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” array a. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case output the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Example Input 4 6 3 5 1 4 6 6 3 1 2 3 4 1 3 3 4 6 1 6 3 4 5 6 Output 1 3 3 10 Submitted Solution: ``` import sys input=sys.stdin.buffer.readline for _ in range(int(input())): n=int(input()) arr=list(map(int,input().split())) d={} for i in range(0,n): if arr[i]-(i+1) not in d: d[arr[i]-(i+1)]=1 else: d[arr[i]-(i+1)]+=1 ans=0 for key in d.keys(): if d[key]>1: k=d[key] ans+=(k*(k-1))//2 print(ans) ``` Yes
12,706
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of n integers. Count the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Input The first line contains one integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5). The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” array a. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case output the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Example Input 4 6 3 5 1 4 6 6 3 1 2 3 4 1 3 3 4 6 1 6 3 4 5 6 Output 1 3 3 10 Submitted Solution: ``` def main(): import sys t = int(sys.stdin.readline()) for _ in range(t): n = int(sys.stdin.readline()) s = list(map(int, sys.stdin.readline().split())) t = dict() c = 0 for i in range(n): r = s[i] - i - 1 if r in t: c += t[r] if r in t: t[r] += 1 else: t[r] = 1 sys.stdout.write(str(c) + '\n') main() ``` Yes
12,707
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of n integers. Count the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Input The first line contains one integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5). The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” array a. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case output the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Example Input 4 6 3 5 1 4 6 6 3 1 2 3 4 1 3 3 4 6 1 6 3 4 5 6 Output 1 3 3 10 Submitted Solution: ``` # def countPairs(arr, n): # # To store the frequencies # # of (arr[i] - i) # map = dict() # for i in range(n): # map[arr[i] - i] = map.get(arr[i] - i, 0) + 1 # # To store the required count # res = 0 # for x in map: # cnt = map[x] # # If cnt is the number of elements # # whose differecne with their index # # is same then ((cnt * (cnt - 1)) / 2) # # such pairs are possible # res += ((cnt * (cnt - 1)) // 2) # return res # # Driver code # arr = [1, 5, 6, 7, 9] # n = len(arr) # print(countPairs(arr, n)) for _ in range(int(input())): n=int(input()) arr=list(map(int,input().split())) d={} for i in range(n): d[arr[i]-i]=d.get(arr[i]-i,0)+1 ans=0 for i in d: n_=d[i] ans+=((n_*(n_-1))//2) print(ans) # d={} ``` Yes
12,708
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of n integers. Count the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Input The first line contains one integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5). The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” array a. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case output the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Example Input 4 6 3 5 1 4 6 6 3 1 2 3 4 1 3 3 4 6 1 6 3 4 5 6 Output 1 3 3 10 Submitted Solution: ``` t=int(input()) for i in range(t): n=int(input()) s=0 m=0 mn=100000000 arr=list(map(int, input().split())) for j in range(n): arr[j]=arr[j]-j m=max(m, arr[j]) mn=min(mn, arr[j]) kol=[0]*(m+1+abs(mn)) #print(arr) for j in range(n): kol[arr[j]+abs(mn)]+=1 #print(kol) for j in range(m+1+abs(mn)): s+=(kol[j]*(kol[j]-1))/2 print(int(s)) ``` Yes
12,709
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of n integers. Count the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Input The first line contains one integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5). The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” array a. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case output the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Example Input 4 6 3 5 1 4 6 6 3 1 2 3 4 1 3 3 4 6 1 6 3 4 5 6 Output 1 3 3 10 Submitted Solution: ``` t = int(input()) while t!=0: t-=1 n = int(input()) arr = list(map(int , input().split())) a = arr[0]-0 ''' i=1 while i <n: arr[i] = arr[i] + a i+= 1 ''' ans=0 j=0 a = arr[0] while j<n: print( a , arr[j]) if arr[j] == a: ans += 1 a +=1 j+=1 if ans !=1: ans = (ans*(ans-1))//2 #print('here' , ans) print(ans) ``` No
12,710
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of n integers. Count the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Input The first line contains one integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5). The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” array a. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case output the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Example Input 4 6 3 5 1 4 6 6 3 1 2 3 4 1 3 3 4 6 1 6 3 4 5 6 Output 1 3 3 10 Submitted Solution: ``` t = int(input()) for tc in range(t): n = int(input()) arr = [int(z) for z in input().split()] model = list(range(1, n+1)) c = [] for i in range(n): if arr[i] == model[i]: c.append(i) ans = 0 for i in range(1, len(c)): ans += len(c) - i print(ans) ``` No
12,711
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of n integers. Count the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Input The first line contains one integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5). The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” array a. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case output the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Example Input 4 6 3 5 1 4 6 6 3 1 2 3 4 1 3 3 4 6 1 6 3 4 5 6 Output 1 3 3 10 Submitted Solution: ``` from collections import defaultdict, Counter from bisect import bisect, bisect_left from math import sqrt, gcd def read(): return list(map(int, input().strip().split())) ans_ = [] for _ in range(int(input())): n = int(input()); arr = read() c = 0 for i in range(n): arr[i] -= i+1 c += [0, 1][arr[i] == 0] ans_.append((c*(c-1))//2) # print(ans_) for i in ans_: print(i) """ 1 1 2 1 2 3 4 3 1 2 3 4 5 6 7 8 9 1 3 5 4 6 """ ``` No
12,712
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an array a of n integers. Count the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Input The first line contains one integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5). The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ n) β€” array a. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case output the number of pairs of indices (i, j) such that i < j and a_j - a_i = j - i. Example Input 4 6 3 5 1 4 6 6 3 1 2 3 4 1 3 3 4 6 1 6 3 4 5 6 Output 1 3 3 10 Submitted Solution: ``` for _ in range(int(input())): n = int(input()) ls = list(map(int,input().split())) ls2 = [] for i,v in enumerate(ls): ls2.append(v - i) d = {} for i in ls2: if i in d: d[i] += 1 else: d[i] = 1 dd = [] for j in d: if d[j] == 1: dd.append(j) for k in dd: d.pop(k) sov = sum(d.values()) print(((sov * (sov - 1)) // 2)) ``` No
12,713
Provide tags and a correct Python 3 solution for this coding contest problem. By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated. In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse. Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?). Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below. To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses: * "Success" if the activation was successful. * "Already on", if the i-th collider was already activated before the request. * "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them. The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program: * "Success", if the deactivation was successful. * "Already off", if the i-th collider was already deactivated before the request. You don't need to print quotes in the output of the responses to the requests. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of colliders and the number of requests, correspondingly. Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) β€” activate the i-th collider, or "- i" (without the quotes) β€” deactivate the i-th collider (1 ≀ i ≀ n). Output Print m lines β€” the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes. Examples Input 10 10 + 6 + 10 + 5 - 10 - 5 - 6 + 10 + 3 + 6 + 3 Output Success Conflict with 6 Success Already off Success Success Success Success Conflict with 10 Already on Note Note that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 3". Tags: math, number theory Correct Solution: ``` n, m = map(int, input().split()) n += 1 s = [[] for i in range(n)] for j in range(2, n, 2): s[j] = [2] for i in range(3, n, 2): if s[i]: continue for j in range(i, n, i): s[j].append(i) p, d, r = {}, set(), [''] * m for j in range(m): t = input() i = int(t[2: ]) if t[0] == '+': if i in d: r[j] = 'Already on' continue for q in s[i]: if q in p: r[j] = 'Conflict with ' + str(p[q]) break else: r[j] = 'Success' d.add(i) for q in s[i]: p[q] = i else: if i in d: r[j] = 'Success' for q in s[i]: p.pop(q) d.remove(i) else: r[j] = 'Already off' print('\n'.join(r)) ```
12,714
Provide tags and a correct Python 3 solution for this coding contest problem. By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated. In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse. Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?). Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below. To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses: * "Success" if the activation was successful. * "Already on", if the i-th collider was already activated before the request. * "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them. The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program: * "Success", if the deactivation was successful. * "Already off", if the i-th collider was already deactivated before the request. You don't need to print quotes in the output of the responses to the requests. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of colliders and the number of requests, correspondingly. Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) β€” activate the i-th collider, or "- i" (without the quotes) β€” deactivate the i-th collider (1 ≀ i ≀ n). Output Print m lines β€” the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes. Examples Input 10 10 + 6 + 10 + 5 - 10 - 5 - 6 + 10 + 3 + 6 + 3 Output Success Conflict with 6 Success Already off Success Success Success Success Conflict with 10 Already on Note Note that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 3". Tags: math, number theory Correct Solution: ``` # https://codeforces.com/problemset/problem/154/B def get_gcd(x,y): dividend = max(x,y) divisor = min(x,y) if divisor == 0: return 1 while(dividend>0): reminder = dividend % divisor if reminder==0: return divisor else: dividend = divisor divisor = reminder return 1 n, m = [int(i) for i in input().split(' ')] inp_req = [] for _ in range(m): inp_req.append([i for i in input().split(' ')]) sieve_arr = [] for i in range(n+1): sieve_arr.append(i) spf_arr = [] for i in sieve_arr: spf_arr.append(i) sieve_arr[1] = -1 from math import sqrt for i in range(2,int(sqrt(len(sieve_arr))+1)): if sieve_arr[i] < 0: continue else: for j in range(i*i, len(sieve_arr), i): if sieve_arr[j] < 0: continue else: sieve_arr[j] *= -1 spf_arr[j] = i def get_prime_factors(spf_inp, num): values = dict() while(spf_inp[num]!=1): values[spf_inp[num]] = True num = num//spf_inp[num] return list(values) collider_dict = dict() spf_dict = dict() for i in inp_req: num = int(i[1]) # print(collider_dict) # print(spf_dict, num) if i[0] == '-': if num not in collider_dict: print("Already off") else: del collider_dict[num] prime_factors = get_prime_factors(spf_arr, num) for j in prime_factors: del spf_dict[j] # curr = spf_arr[num] # prev = None # while(prev!=curr and curr in spf_dict): # if curr == 1: # break # del spf_dict[curr] # prev = curr # curr = spf_arr[num//curr] # print(f"Removing {num}") print("Success") else: if len(collider_dict) == 0: print("Success") collider_dict[num] = True prime_factors = get_prime_factors(spf_arr, num) for j in prime_factors: spf_dict[j] = [num] else: if num in collider_dict: print("Already on") else: is_conflict = False prime_factors = get_prime_factors(spf_arr, num) for j in prime_factors: if j in spf_dict: print(f"Conflict with {spf_dict[j][0]}") is_conflict = True break if not is_conflict: collider_dict[num] = True for j in prime_factors: spf_dict[j] = [num] # collider_dict[num] = True # prev = None # curr = spf_arr[num] # while(prev!=curr and curr not in spf_dict): # if curr == 1: # break # # print(curr, num) # spf_dict[curr] = [num] # prev = curr # curr = spf_arr[num//curr] # print(spf_dict, collider_dict) print("Success") # prev = None # curr = spf_arr[num] # count = 0 # while(prev!=curr): # # print(spf_dict, curr) # if count > 20: # break # if curr in spf_dict: # print(f"Conflict with {spf_dict[curr][0]}") # is_conflict = True # break # else: # prev = num//curr # curr = spf_arr[num//curr] # count += 1 # if not is_conflict: # collider_dict[num] = True # # spf_dict[spf_arr[num]] = [num] # prev = None # curr = spf_arr[num] # count = 0 # while(prev!=curr): # if count> 20: # break # if num == 15: # print(prev, curr, num) # spf_dict[curr] = [num] # if curr == num: # break # prev = num//curr # curr = spf_arr[num//curr] # spf_dict[curr] = [num] # count += 1 # spf_dict[curr] = [num] # # print(curr, prev) # # print("()()",spf_dict) # print("Success") # print("__________") ```
12,715
Provide tags and a correct Python 3 solution for this coding contest problem. By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated. In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse. Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?). Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below. To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses: * "Success" if the activation was successful. * "Already on", if the i-th collider was already activated before the request. * "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them. The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program: * "Success", if the deactivation was successful. * "Already off", if the i-th collider was already deactivated before the request. You don't need to print quotes in the output of the responses to the requests. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of colliders and the number of requests, correspondingly. Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) β€” activate the i-th collider, or "- i" (without the quotes) β€” deactivate the i-th collider (1 ≀ i ≀ n). Output Print m lines β€” the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes. Examples Input 10 10 + 6 + 10 + 5 - 10 - 5 - 6 + 10 + 3 + 6 + 3 Output Success Conflict with 6 Success Already off Success Success Success Success Conflict with 10 Already on Note Note that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 3". Tags: math, number theory Correct Solution: ``` #------------------------------warmup---------------------------- import os import sys import math 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") #-------------------game starts now---------------------------------------------------- # Function to call the actual solution def solution(li, n, m): s = [[] for i in range(n)] for j in range(2, n, 2): s[j] = [2] for i in range(3, n, 2): if s[i]: continue for j in range(i, n, i): s[j].append(i) p, d, r = {}, set(), [''] * m for j in range(len(li)): t = li[j][0] i = int(li[j][1]) if t[0] == '+': if i in d: r[j] = 'Already on' continue for q in s[i]: if q in p: r[j] = 'Conflict with ' + str(p[q]) break else: r[j] = 'Success' d.add(i) for q in s[i]: p[q] = i else: if i in d: r[j] = 'Success' for q in s[i]: p.pop(q) d.remove(i) else: r[j] = 'Already off' return r # Function to take input def input_test(): # for _ in range(int(input())): # n = int(input()) n, m = map(int, input().strip().split(" ")) quer = [] for i in range(m): qu = list(map(str, input().strip().split(" "))) quer.append(qu) # a, b, c = map(int, input().strip().split(" ")) # li = list(map(int, input().strip().split(" "))) out = solution(quer, n+1, m) for i in out: print(i) # Function to test my code def test(): pass # seive() input_test() # test() ```
12,716
Provide tags and a correct Python 3 solution for this coding contest problem. By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated. In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse. Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?). Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below. To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses: * "Success" if the activation was successful. * "Already on", if the i-th collider was already activated before the request. * "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them. The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program: * "Success", if the deactivation was successful. * "Already off", if the i-th collider was already deactivated before the request. You don't need to print quotes in the output of the responses to the requests. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of colliders and the number of requests, correspondingly. Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) β€” activate the i-th collider, or "- i" (without the quotes) β€” deactivate the i-th collider (1 ≀ i ≀ n). Output Print m lines β€” the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes. Examples Input 10 10 + 6 + 10 + 5 - 10 - 5 - 6 + 10 + 3 + 6 + 3 Output Success Conflict with 6 Success Already off Success Success Success Success Conflict with 10 Already on Note Note that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 3". Tags: math, number theory Correct Solution: ``` import sys input=sys.stdin.readline from math import gcd n,k=map(int,input().split()) a=[[] for i in range(n+1)] # have primes of i active=[0]*(n+1) act={} for i in range(2,n+1): if not a[i]: act[i]=0 for j in range(i,n+1,i): a[j].append(i) for _ in range(k): s,x=input().rstrip().split() x=int(x) if s=="-": if active[x]: print("Success") active[x]=0 for xx in a[x]: act[xx]=0 else: print("Already off") else: if active[x]: print("Already on") else: t=1 flag=True for xx in a[x]: if act[xx]: t=xx flag=False break if flag: print("Success") active[x]=1 for xx in a[x]: act[xx]=x else: print("Conflict with",act[t]) ```
12,717
Provide tags and a correct Python 3 solution for this coding contest problem. By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated. In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse. Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?). Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below. To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses: * "Success" if the activation was successful. * "Already on", if the i-th collider was already activated before the request. * "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them. The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program: * "Success", if the deactivation was successful. * "Already off", if the i-th collider was already deactivated before the request. You don't need to print quotes in the output of the responses to the requests. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of colliders and the number of requests, correspondingly. Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) β€” activate the i-th collider, or "- i" (without the quotes) β€” deactivate the i-th collider (1 ≀ i ≀ n). Output Print m lines β€” the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes. Examples Input 10 10 + 6 + 10 + 5 - 10 - 5 - 6 + 10 + 3 + 6 + 3 Output Success Conflict with 6 Success Already off Success Success Success Success Conflict with 10 Already on Note Note that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 3". Tags: math, number theory Correct Solution: ``` import random, math, sys from copy import deepcopy as dc from bisect import bisect_left, bisect_right from collections import Counter input = sys.stdin.readline # Function to call the actual solution def solution(li, n, m): s = [[] for i in range(n)] for j in range(2, n, 2): s[j] = [2] for i in range(3, n, 2): if s[i]: continue for j in range(i, n, i): s[j].append(i) p, d, r = {}, set(), [''] * m for j in range(len(li)): t = li[j][0] i = int(li[j][1]) if t[0] == '+': if i in d: r[j] = 'Already on' continue for q in s[i]: if q in p: r[j] = 'Conflict with ' + str(p[q]) break else: r[j] = 'Success' d.add(i) for q in s[i]: p[q] = i else: if i in d: r[j] = 'Success' for q in s[i]: p.pop(q) d.remove(i) else: r[j] = 'Already off' return r # Function to take input def input_test(): # for _ in range(int(input())): # n = int(input()) n, m = map(int, input().strip().split(" ")) quer = [] for i in range(m): qu = list(map(str, input().strip().split(" "))) quer.append(qu) # a, b, c = map(int, input().strip().split(" ")) # li = list(map(int, input().strip().split(" "))) out = solution(quer, n+1, m) for i in out: print(i) # Function to test my code def test(): pass # seive() input_test() # test() ```
12,718
Provide tags and a correct Python 3 solution for this coding contest problem. By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated. In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse. Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?). Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below. To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses: * "Success" if the activation was successful. * "Already on", if the i-th collider was already activated before the request. * "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them. The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program: * "Success", if the deactivation was successful. * "Already off", if the i-th collider was already deactivated before the request. You don't need to print quotes in the output of the responses to the requests. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of colliders and the number of requests, correspondingly. Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) β€” activate the i-th collider, or "- i" (without the quotes) β€” deactivate the i-th collider (1 ≀ i ≀ n). Output Print m lines β€” the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes. Examples Input 10 10 + 6 + 10 + 5 - 10 - 5 - 6 + 10 + 3 + 6 + 3 Output Success Conflict with 6 Success Already off Success Success Success Success Conflict with 10 Already on Note Note that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 3". Tags: math, number theory Correct Solution: ``` from sys import stdin import math n, k = map(int, stdin.readline().rstrip().split(" ")) a = [[] for i in range(n+1)] act = {} active = [0]*(n+1) for i in range(2,n+1): if not a[i]: act[i]=0 for j in range(i,n+1,i): a[j].append(i) storing = {} for _ in range(k): s, v = stdin.readline().rstrip().split(" ") v = int(v) if s=="-": if active[v]==1: print("Success") active[v]=0 for i in list(a[v]): act[i]=0 else: print("Already off") else: if active[v]: print("Already on") else: test = 1 r = True for i in list(a[v]): if act[i]: test = i r=False break if r: print("Success") active[v]=1 for i in list(a[v])[::-1]: act[i] = v else: x = 0 print("Conflict with", act[test]) ```
12,719
Provide tags and a correct Python 3 solution for this coding contest problem. By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated. In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse. Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?). Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below. To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses: * "Success" if the activation was successful. * "Already on", if the i-th collider was already activated before the request. * "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them. The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program: * "Success", if the deactivation was successful. * "Already off", if the i-th collider was already deactivated before the request. You don't need to print quotes in the output of the responses to the requests. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of colliders and the number of requests, correspondingly. Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) β€” activate the i-th collider, or "- i" (without the quotes) β€” deactivate the i-th collider (1 ≀ i ≀ n). Output Print m lines β€” the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes. Examples Input 10 10 + 6 + 10 + 5 - 10 - 5 - 6 + 10 + 3 + 6 + 3 Output Success Conflict with 6 Success Already off Success Success Success Success Conflict with 10 Already on Note Note that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 3". Tags: math, number theory Correct Solution: ``` MAXN = 100005 pr = [0] * MAXN n, m = map(int, input().split()) for i in range(2, n + 1, 2): pr[i] = 2 for i in range(3, n + 1, 2): if not pr[i]: j = i while j <= n: if not pr[j]: pr[j] = i j += i answer = [''] * m p, d = {}, set() for i in range(m): temp = input() ch = temp[0] x = int(temp[2:]) if ch == '+': if x in d: answer[i] = 'Already on' continue y = x while y > 1: if pr[y] in p: answer[i] = 'Conflict with ' + str(p[pr[y]]) break y //= pr[y] else: answer[i] = 'Success' d.add(x) y = x while y > 1: p[pr[y]] = x y //= pr[y] else: if x in d: answer[i] = 'Success' y = x while y > 1: if pr[y] in p: p.pop(pr[y]) y //= pr[y] d.remove(x) else: answer[i] = 'Already off' print('\n'.join(answer)) ```
12,720
Provide tags and a correct Python 3 solution for this coding contest problem. By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated. In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse. Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?). Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below. To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses: * "Success" if the activation was successful. * "Already on", if the i-th collider was already activated before the request. * "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them. The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program: * "Success", if the deactivation was successful. * "Already off", if the i-th collider was already deactivated before the request. You don't need to print quotes in the output of the responses to the requests. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of colliders and the number of requests, correspondingly. Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) β€” activate the i-th collider, or "- i" (without the quotes) β€” deactivate the i-th collider (1 ≀ i ≀ n). Output Print m lines β€” the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes. Examples Input 10 10 + 6 + 10 + 5 - 10 - 5 - 6 + 10 + 3 + 6 + 3 Output Success Conflict with 6 Success Already off Success Success Success Success Conflict with 10 Already on Note Note that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 3". Tags: math, number theory Correct Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # Python3 program to find prime factorization # of a number n in O(Log n) time with # precomputation allowed. import math as mt # Calculating SPF (Smallest Prime Factor) # for every number till MAXN. # Time Complexity : O(nloglogn) def sieve(): spf[1] = 1 for i in range(2, MAXN): # marking smallest prime factor # for every number to be itself. spf[i] = i # separately marking spf for # every even number as 2 for i in range(4, MAXN, 2): spf[i] = 2 for i in range(3, mt.ceil(mt.sqrt(MAXN))): # checking if i is prime if (spf[i] == i): # marking SPF for all numbers # divisible by i for j in range(i * i, MAXN, i): # marking spf[j] if it is # not previously marked if (spf[j] == j): spf[j] = i # A O(log n) function returning prime # factorization by dividing by smallest # prime factor at every step def getFactorization(x, check = False): ret = set() while (x != 1): if len(primetaken[spf[x]]) != 0 and check: z = primetaken[spf[x]].pop() print(f'Conflict with {z}') primetaken[spf[x]].add(z) return None ret.add(spf[x]) x = x // spf[x] return ret n, m = map(int, input().rstrip().split(" ")) MAXN = n + 1 # stores smallest prime factor for # every number spf = [0 for i in range(n + 1)] sieve() #print(spf) primetaken = [set() for i in range(n + 1)] numtaken = [False] * (n + 1) for _ in range(m): s, x = input().rstrip().split(" ") x = int(x) if s == '+': if numtaken[x]: print('Already on') else: f = getFactorization(x, True) if f is not None: for ele in f: primetaken[ele].add(x) print('Success') numtaken[x] = True else: if numtaken[x]: f = getFactorization(x) for ele in f: primetaken[ele].remove(x) numtaken[x] = False print('Success') else: print('Already off') ```
12,721
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated. In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse. Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?). Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below. To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses: * "Success" if the activation was successful. * "Already on", if the i-th collider was already activated before the request. * "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them. The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program: * "Success", if the deactivation was successful. * "Already off", if the i-th collider was already deactivated before the request. You don't need to print quotes in the output of the responses to the requests. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of colliders and the number of requests, correspondingly. Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) β€” activate the i-th collider, or "- i" (without the quotes) β€” deactivate the i-th collider (1 ≀ i ≀ n). Output Print m lines β€” the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes. Examples Input 10 10 + 6 + 10 + 5 - 10 - 5 - 6 + 10 + 3 + 6 + 3 Output Success Conflict with 6 Success Already off Success Success Success Success Conflict with 10 Already on Note Note that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 3". Submitted Solution: ``` n, m = map(int, input().split()) n += 1 s = [[] for i in range(n)] for j in range(2, n, 2): s[j] = [2] for i in range(3, n, 2): if s[i]: continue for j in range(i, n, i): s[j].append(i) p, d, r = {}, set(), [''] * m for j in range(m): t = input() i = int(t[2: ]) if t[0] == '+': if i in d: r[j] = 'Already on' continue for q in s[i]: if q in p: r[j] = 'Conflict with ' + str(p[q]) break else: r[j] = 'Success' d.add(i) for q in s[i]: p[q] = i else: if i in d: r[j] = 'Success' for q in s[i]: p.pop(q) d.remove(i) else: r[j] = 'Already off' print('\n'.join(r)) # Made By Mostafa_Khaled ``` Yes
12,722
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated. In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse. Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?). Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below. To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses: * "Success" if the activation was successful. * "Already on", if the i-th collider was already activated before the request. * "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them. The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program: * "Success", if the deactivation was successful. * "Already off", if the i-th collider was already deactivated before the request. You don't need to print quotes in the output of the responses to the requests. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of colliders and the number of requests, correspondingly. Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) β€” activate the i-th collider, or "- i" (without the quotes) β€” deactivate the i-th collider (1 ≀ i ≀ n). Output Print m lines β€” the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes. Examples Input 10 10 + 6 + 10 + 5 - 10 - 5 - 6 + 10 + 3 + 6 + 3 Output Success Conflict with 6 Success Already off Success Success Success Success Conflict with 10 Already on Note Note that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 3". Submitted Solution: ``` from sys import stdin, stdout from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log from collections import defaultdict as dd, deque from heapq import merge, heapify, heappop, heappush, nsmallest from bisect import bisect_left as bl, bisect_right as br, bisect mod = pow(10, 9) + 7 mod2 = 998244353 def inp(): return stdin.readline().strip() def iinp(): return int(inp()) def out(var, end="\n"): stdout.write(str(var)+"\n") def outa(*var, end="\n"): stdout.write(' '.join(map(str, var)) + end) def lmp(): return list(mp()) def mp(): return map(int, inp().split()) def smp(): return map(str, inp().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(m, val) for j in range(n)] def remadd(x, y): return 1 if x%y else 0 def ceil(a,b): return (a+b-1)//b def isprime(x): if x<=1: return False if x in (2, 3): return True if x%2 == 0: return False for i in range(3, int(sqrt(x))+1, 2): if x%i == 0: return False return True n, m = mp() md1 = dd(int) status = dd(int) pfs = {} for i in range(m): a, b = inp().split() b = int(b) if a == '-': if status[b]: status[b] = 0 print("Success") for i in pfs[b]: md1[i] = 0 else: print("Already off") else: if status[b]: print("Already on") continue s = set() tb = b if tb%2==0: s.add(2) while tb%2==0: tb//=2 j = 3 while j*j<=tb: if tb%j==0: s.add(j) while tb%j==0: tb//=j j += 2 if tb>1: s.add(tb) flg = True for i in s: if md1[i]: ind = i flg=False break if flg: for i in s: md1[i] = b pfs[b] = s status[b] = 1 print("Success") else: print("Conflict with", md1[ind]) ``` Yes
12,723
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated. In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse. Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?). Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below. To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses: * "Success" if the activation was successful. * "Already on", if the i-th collider was already activated before the request. * "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them. The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program: * "Success", if the deactivation was successful. * "Already off", if the i-th collider was already deactivated before the request. You don't need to print quotes in the output of the responses to the requests. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of colliders and the number of requests, correspondingly. Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) β€” activate the i-th collider, or "- i" (without the quotes) β€” deactivate the i-th collider (1 ≀ i ≀ n). Output Print m lines β€” the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes. Examples Input 10 10 + 6 + 10 + 5 - 10 - 5 - 6 + 10 + 3 + 6 + 3 Output Success Conflict with 6 Success Already off Success Success Success Success Conflict with 10 Already on Note Note that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 3". Submitted Solution: ``` import math t=[] n,m=list(map(int,input().split())) for i in range(m): s=input() a=int(s[1:]) q=0 y=len(t) if s[0]=='+': if a not in t: if y==0: t.append(a) print('Sucess') else: for k in t: if math.gcd(a,k)!=1: print('Conflict with ',k) q+=1 break if q==0: t.append(a) print('Success') else: print('Already on') else: if a not in t: print('Already off') else: t.remove(a) print('Success') ``` No
12,724
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated. In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse. Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?). Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below. To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses: * "Success" if the activation was successful. * "Already on", if the i-th collider was already activated before the request. * "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them. The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program: * "Success", if the deactivation was successful. * "Already off", if the i-th collider was already deactivated before the request. You don't need to print quotes in the output of the responses to the requests. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of colliders and the number of requests, correspondingly. Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) β€” activate the i-th collider, or "- i" (without the quotes) β€” deactivate the i-th collider (1 ≀ i ≀ n). Output Print m lines β€” the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes. Examples Input 10 10 + 6 + 10 + 5 - 10 - 5 - 6 + 10 + 3 + 6 + 3 Output Success Conflict with 6 Success Already off Success Success Success Success Conflict with 10 Already on Note Note that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 3". Submitted Solution: ``` import random, math from copy import deepcopy as dc MAXN = 100001 primes = [set() for i in range(MAXN)] primes[0] = set() primes[1] = set() primes[1].add(1) def seive(): i = 2 while i*i < MAXN: if primes[i] == set(): for j in range(i, MAXN, i): primes[j].add(i) i += 1 def solution_on(num, turned_on, setter): if num in turned_on: return turned_on, setter, "Already on" for i in primes[num]: if i in setter and setter[i]!=0: return turned_on, setter, "Conflict with "+str(setter[i]) # some = set(setter.keys()) # some = some.intersection(primes[num]) # if len(some): # some = list(some) # return turned_on, setter, "Conflict with "+str(setter[some[-1]]) turned_on.add(num) for i in primes[num]: setter[i] = num return turned_on, setter, "Success" # Function to call the actual solution def solution(num, turned_on, setter): if num not in turned_on: return turned_on, setter, "Already off" turned_on.remove(num) for i in primes[num]: setter[i] = 0 return turned_on, setter, "Success" # Function to take input def input_test(): n, m = map(int, input().strip().split(" ")) turned_on = set() setter = {} rev = [] turned_on1 = set() for i in range(m): cmd = list(map(str, input().strip().split(" "))) if cmd[0] == "+": turned_on, setter, out= solution_on(int(cmd[1]), turned_on, setter) print(out) elif cmd[0] == "-": turned_on, setter, out = solution(int(cmd[1]), turned_on, setter) print(out) seive() # print(primes[:11]) input_test() ``` No
12,725
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated. In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse. Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?). Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below. To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses: * "Success" if the activation was successful. * "Already on", if the i-th collider was already activated before the request. * "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them. The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program: * "Success", if the deactivation was successful. * "Already off", if the i-th collider was already deactivated before the request. You don't need to print quotes in the output of the responses to the requests. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of colliders and the number of requests, correspondingly. Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) β€” activate the i-th collider, or "- i" (without the quotes) β€” deactivate the i-th collider (1 ≀ i ≀ n). Output Print m lines β€” the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes. Examples Input 10 10 + 6 + 10 + 5 - 10 - 5 - 6 + 10 + 3 + 6 + 3 Output Success Conflict with 6 Success Already off Success Success Success Success Conflict with 10 Already on Note Note that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 3". Submitted Solution: ``` import re n = input() a = list(input().split(" ")) s = "".join(a) l = list(map(lambda x: len(x), list(re.findall("(1+)", s)))) h = list(map(lambda x: len(x), list(re.findall("^(1+)", s)))) t = list(map(lambda x: len(x), list(re.findall("(1+)$", s)))) result = 0 if len(l) > 0: result = max(l) if len(h)*len(t) > 0: result = max(result, h[0] + t[0]) print(result) ``` No
12,726
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated. In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse. Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?). Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below. To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses: * "Success" if the activation was successful. * "Already on", if the i-th collider was already activated before the request. * "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them. The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program: * "Success", if the deactivation was successful. * "Already off", if the i-th collider was already deactivated before the request. You don't need to print quotes in the output of the responses to the requests. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of colliders and the number of requests, correspondingly. Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) β€” activate the i-th collider, or "- i" (without the quotes) β€” deactivate the i-th collider (1 ≀ i ≀ n). Output Print m lines β€” the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes. Examples Input 10 10 + 6 + 10 + 5 - 10 - 5 - 6 + 10 + 3 + 6 + 3 Output Success Conflict with 6 Success Already off Success Success Success Success Conflict with 10 Already on Note Note that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 3". Submitted Solution: ``` n,m = [int(x) for x in input().split()] query = [] def gcd(a,b): maximum = max(a,b) minimum = min(a,b) if maximum % minimum == 0: return minimum return gcd(maximum % minimum, minimum) primes = [1]*(n + 1) primes[0],primes[1] = 0,0 i = 2 while i*i <= n: j = i if primes[i] == 1: while j*j <= n: primes[i*j] = 0 j += 1 i += 1 for i in range(m): q = 0 qi = [x for x in input().split()] if qi[0] == '+': q = int(qi[1]) else: q = (-1)*int(qi[1]) if q < 0: bool1 = False for i in range(len(query)): if query[i] == (-1)*q: bool1 = True query.pop(i) break if bool1 : print('Success') else: print('Already off') else: if len(query) == 0: print('Success') query.append(q) else: b = False for j in range(len(query)): if query[j] == q: b = True break if b: print('Already on') else: boolean = True for i in range(n + 1): if primes[i] == q: print('Success') query.append(q) boolean = False break if boolean: g = 0 bool2 = True for i in range(len(query)): g = gcd(q,query[i]) if g != 1: bool2 = False break if bool2 : print('Success') query.append(q) else: print('Conflict with', query[i]) else: break ``` No
12,727
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We've got a rectangular n Γ— m-cell maze. Each cell is either passable, or is a wall (impassable). A little boy found the maze and cyclically tiled a plane with it so that the plane became an infinite maze. Now on this plane cell (x, y) is a wall if and only if cell <image> is a wall. In this problem <image> is a remainder of dividing number a by number b. The little boy stood at some cell on the plane and he wondered whether he can walk infinitely far away from his starting position. From cell (x, y) he can go to one of the following cells: (x, y - 1), (x, y + 1), (x - 1, y) and (x + 1, y), provided that the cell he goes to is not a wall. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 1500) β€” the height and the width of the maze that the boy used to cyclically tile the plane. Each of the next n lines contains m characters β€” the description of the labyrinth. Each character is either a "#", that marks a wall, a ".", that marks a passable cell, or an "S", that marks the little boy's starting point. The starting point is a passable cell. It is guaranteed that character "S" occurs exactly once in the input. Output Print "Yes" (without the quotes), if the little boy can walk infinitely far from the starting point. Otherwise, print "No" (without the quotes). Examples Input 5 4 ##.# ##S# #..# #.## #..# Output Yes Input 5 4 ##.# ##S# #..# ..#. #.## Output No Note In the first sample the little boy can go up for infinitely long as there is a "clear path" that goes vertically. He just needs to repeat the following steps infinitely: up, up, left, up, up, right, up. In the second sample the vertical path is blocked. The path to the left doesn't work, too β€” the next "copy" of the maze traps the boy. Submitted Solution: ``` from collections import defaultdict n,m = map(int, input().split()) mat = [list(input()) for _ in range(n)] vis = defaultdict() x,y =0,0 for i in range(n): for j in range(m): if 'S' in mat[i][j]: x,y = i,j mat[i][j]='.' def safe(i,j): return i>=0 and j>=0 and i<n and j<m def dfs(i,j): try: if (i%n,j%m) in vis: return True vis[(i,j)] =1 vis[(i%n,j%m)]=1 except: print('fir') try: for di,dj in [(0,1), (0,-1), (1,0), (-1,0)]: x,y = i+di+n, j+dj+m u,v = (x)%n, (y)%m if safe(u,v) and '.' == mat[u][v] and (x,y) not in vis and dfs(x,y): return True return False except: print(i,j) print('Yes' if dfs(x,y) else 'No') ``` No
12,728
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We've got a rectangular n Γ— m-cell maze. Each cell is either passable, or is a wall (impassable). A little boy found the maze and cyclically tiled a plane with it so that the plane became an infinite maze. Now on this plane cell (x, y) is a wall if and only if cell <image> is a wall. In this problem <image> is a remainder of dividing number a by number b. The little boy stood at some cell on the plane and he wondered whether he can walk infinitely far away from his starting position. From cell (x, y) he can go to one of the following cells: (x, y - 1), (x, y + 1), (x - 1, y) and (x + 1, y), provided that the cell he goes to is not a wall. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 1500) β€” the height and the width of the maze that the boy used to cyclically tile the plane. Each of the next n lines contains m characters β€” the description of the labyrinth. Each character is either a "#", that marks a wall, a ".", that marks a passable cell, or an "S", that marks the little boy's starting point. The starting point is a passable cell. It is guaranteed that character "S" occurs exactly once in the input. Output Print "Yes" (without the quotes), if the little boy can walk infinitely far from the starting point. Otherwise, print "No" (without the quotes). Examples Input 5 4 ##.# ##S# #..# #.## #..# Output Yes Input 5 4 ##.# ##S# #..# ..#. #.## Output No Note In the first sample the little boy can go up for infinitely long as there is a "clear path" that goes vertically. He just needs to repeat the following steps infinitely: up, up, left, up, up, right, up. In the second sample the vertical path is blocked. The path to the left doesn't work, too β€” the next "copy" of the maze traps the boy. Submitted Solution: ``` from collections import defaultdict,deque n,m = map(int, input().split()) mat = [input() for _ in range(n)] vis = defaultdict() def dfs(i,j): q = deque() q.append((i,j)) while q: i,j = q.popleft() u,v = (i%n+n)%n, (j%n+m)%m if mat[u][v] == '#' or (i,j) in vis: continue if (u,v) in vis: return True vis[(i,j)]=1 vis[(u,v)]=1 for di,dj in [(0,1), (0,-1), (1,0), (-1,0)]: x,y = i+di, j+dj q.append((x,y)) return False for i in range(n): for j in range(m): if 'S' in mat[i][j]: print('Yes' if dfs(2*n+i,2*m+j) else 'No') ``` No
12,729
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We've got a rectangular n Γ— m-cell maze. Each cell is either passable, or is a wall (impassable). A little boy found the maze and cyclically tiled a plane with it so that the plane became an infinite maze. Now on this plane cell (x, y) is a wall if and only if cell <image> is a wall. In this problem <image> is a remainder of dividing number a by number b. The little boy stood at some cell on the plane and he wondered whether he can walk infinitely far away from his starting position. From cell (x, y) he can go to one of the following cells: (x, y - 1), (x, y + 1), (x - 1, y) and (x + 1, y), provided that the cell he goes to is not a wall. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 1500) β€” the height and the width of the maze that the boy used to cyclically tile the plane. Each of the next n lines contains m characters β€” the description of the labyrinth. Each character is either a "#", that marks a wall, a ".", that marks a passable cell, or an "S", that marks the little boy's starting point. The starting point is a passable cell. It is guaranteed that character "S" occurs exactly once in the input. Output Print "Yes" (without the quotes), if the little boy can walk infinitely far from the starting point. Otherwise, print "No" (without the quotes). Examples Input 5 4 ##.# ##S# #..# #.## #..# Output Yes Input 5 4 ##.# ##S# #..# ..#. #.## Output No Note In the first sample the little boy can go up for infinitely long as there is a "clear path" that goes vertically. He just needs to repeat the following steps infinitely: up, up, left, up, up, right, up. In the second sample the vertical path is blocked. The path to the left doesn't work, too β€” the next "copy" of the maze traps the boy. Submitted Solution: ``` import sys sys.setrecursionlimit(1000000) def solve(): xs, ys = [-1, 1, 0, 0], [0, 0, -1, 1] n, m, = rv() tab = [list(input()) for _ in range(n)] visited = [[False] * m for _ in range(n)] points = list() for r in range(n): for c in range(m): if tab[r][c] == 'S': dfs(r, c, tab, visited, xs, ys) for r in range(n): if visited[r][0] == visited[r][-1] == True: return "Yes" for c in range(m): if visited[0][c] == visited[-1][c] == True: return "Yes" return "No" def dfs(row, col, tab, visited, xs, ys): if row < 0 or row >= len(tab) or col < 0 or col >= len(tab[0]) or tab[row][col] == '#' or visited[row][col]: return visited[row][col] = True for i in range(4): dfs(row + xs[i], col + ys[i], tab, visited, xs, ys) def prt(l): return print(''.join(l)) def rv(): return map(int, input().split()) def rl(n): return [list(map(int, input().split())) for _ in range(n)] if sys.hexversion == 50594544 : sys.stdin = open("test.txt") print(solve()) ``` No
12,730
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We've got a rectangular n Γ— m-cell maze. Each cell is either passable, or is a wall (impassable). A little boy found the maze and cyclically tiled a plane with it so that the plane became an infinite maze. Now on this plane cell (x, y) is a wall if and only if cell <image> is a wall. In this problem <image> is a remainder of dividing number a by number b. The little boy stood at some cell on the plane and he wondered whether he can walk infinitely far away from his starting position. From cell (x, y) he can go to one of the following cells: (x, y - 1), (x, y + 1), (x - 1, y) and (x + 1, y), provided that the cell he goes to is not a wall. Input The first line contains two space-separated integers n and m (1 ≀ n, m ≀ 1500) β€” the height and the width of the maze that the boy used to cyclically tile the plane. Each of the next n lines contains m characters β€” the description of the labyrinth. Each character is either a "#", that marks a wall, a ".", that marks a passable cell, or an "S", that marks the little boy's starting point. The starting point is a passable cell. It is guaranteed that character "S" occurs exactly once in the input. Output Print "Yes" (without the quotes), if the little boy can walk infinitely far from the starting point. Otherwise, print "No" (without the quotes). Examples Input 5 4 ##.# ##S# #..# #.## #..# Output Yes Input 5 4 ##.# ##S# #..# ..#. #.## Output No Note In the first sample the little boy can go up for infinitely long as there is a "clear path" that goes vertically. He just needs to repeat the following steps infinitely: up, up, left, up, up, right, up. In the second sample the vertical path is blocked. The path to the left doesn't work, too β€” the next "copy" of the maze traps the boy. Submitted Solution: ``` from collections import defaultdict n,m = map(int, input().split()) mat = [input() for _ in range(n)] vis = defaultdict() x,y =0,0 for i in range(n): for j in range(m): if 'S' in mat[i][j]: x,y = i,j def safe(i,j): return i>=0 and j>=0 and i<n and j<m def dfs(i,j): try: u,v = (i+n)%n, (j+m)%m if mat[u][v] == '#': return False if (u,v) in vis: return True vis[(i,j)]=1 vis[(u,v)]=1 for di,dj in [(0,1), (0,-1), (1,0), (-1,0)]: x,y = i+di, j+dj if (x,y) not in vis and dfs(x,y): return True return False except IndexError: return False except: return True print('Yes' if dfs(2*n+x,2*m+y) else 'No') ``` No
12,731
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two set of points. The first set is determined by the equation A1x + B1y + C1 = 0, and the second one is determined by the equation A2x + B2y + C2 = 0. Write the program which finds the number of points in the intersection of two given sets. Input The first line of the input contains three integer numbers A1, B1, C1 separated by space. The second line contains three integer numbers A2, B2, C2 separated by space. All the numbers are between -100 and 100, inclusive. Output Print the number of points in the intersection or -1 if there are infinite number of points. Examples Input 1 1 0 2 2 0 Output -1 Input 1 1 0 2 -2 0 Output 1 Tags: implementation, math Correct Solution: ``` R=lambda:map(int,input().split()) a1,b1,c1=R() a2,b2,c2=R() Z=lambda x,y,z:not x and not y and z if a1*b2-a2*b1!=0: print("1") elif Z(a1,b1,c1) or Z(a2,b2,c2) or c1*b2-b1*c2 or c1*a2-c2*a1: print("0") else: print("-1") ```
12,732
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two set of points. The first set is determined by the equation A1x + B1y + C1 = 0, and the second one is determined by the equation A2x + B2y + C2 = 0. Write the program which finds the number of points in the intersection of two given sets. Input The first line of the input contains three integer numbers A1, B1, C1 separated by space. The second line contains three integer numbers A2, B2, C2 separated by space. All the numbers are between -100 and 100, inclusive. Output Print the number of points in the intersection or -1 if there are infinite number of points. Examples Input 1 1 0 2 2 0 Output -1 Input 1 1 0 2 -2 0 Output 1 Tags: implementation, math Correct Solution: ``` a1, b1, c1 = [int(i) for i in input().split()] a2, b2, c2 = [int(i) for i in input().split()] if(b1 != 0 and b2 != 0): #paralelas: if(a1/b1 == a2/b2): if(c1/b1 == c2/b2): print(-1) #paralelas iguais else: print(0) #paralelas diferentes else: print(1) elif(b1 == 0 and b2 == 0): if(a1 != 0): if(a2 != 0): if(c1/a1 == c2/a2): print(-1) else: print(0) else: if(c2 == 0): print(-1) else: print(0) if(a1 == 0 and a2 != 0): if(c1 == 0): print(-1) else: print(0) if(a1 == 0 and a2 == 0): if(c1 == 0 and c2 == 0): print(-1) else: print(0) elif(b1 == 0 and b2 != 0): if(a1 != 0 and a2 != 0): print(1) elif(a1 == 0 and a2 != 0): if(c1 == 0): print(-1) else: print(0) elif(a1 != 0 and a2 == 0): print(1) elif(a1 == 0 and a2 == 0): if(c1 == 0): print(-1) else: print(0) elif(b1 != 0 and b2 == 0): if(a1 != 0 and a2 != 0): print(1) elif(a1 != 0 and a2 == 0): if(c2 == 0): print(-1) else: print(0) elif(a1 == 0 and a2 != 0): print(1) elif(a1 == 0 and a2 == 0): if(c2 == 0): print(-1) else: print(0) else: print(1) ```
12,733
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two set of points. The first set is determined by the equation A1x + B1y + C1 = 0, and the second one is determined by the equation A2x + B2y + C2 = 0. Write the program which finds the number of points in the intersection of two given sets. Input The first line of the input contains three integer numbers A1, B1, C1 separated by space. The second line contains three integer numbers A2, B2, C2 separated by space. All the numbers are between -100 and 100, inclusive. Output Print the number of points in the intersection or -1 if there are infinite number of points. Examples Input 1 1 0 2 2 0 Output -1 Input 1 1 0 2 -2 0 Output 1 Tags: implementation, math Correct Solution: ``` R = lambda:map(int, input().split()) a1, b1, c1 = R() a2, b2, c2 = R() if a1 == b1 == 0 and c1 != 0 or a2 == b2 == 0 and c2 != 0: print(0) elif a1 == b1 == c1 == 0 or a2 == b2 == c2 == 0: print(-1) else: if c1 != 0: a1 /= c1 b1 /= c1 c1 = 1 if c2 != 0: a2 /= c2 b2 /= c2 c2 = 1 if a1 * b2 - a2 * b1 == 0: if c1 == c2 and a1 == a2 and b1 == b2 or c1 == c2 == 0: print(-1) else: print(0) else: print(1) ```
12,734
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two set of points. The first set is determined by the equation A1x + B1y + C1 = 0, and the second one is determined by the equation A2x + B2y + C2 = 0. Write the program which finds the number of points in the intersection of two given sets. Input The first line of the input contains three integer numbers A1, B1, C1 separated by space. The second line contains three integer numbers A2, B2, C2 separated by space. All the numbers are between -100 and 100, inclusive. Output Print the number of points in the intersection or -1 if there are infinite number of points. Examples Input 1 1 0 2 2 0 Output -1 Input 1 1 0 2 -2 0 Output 1 Tags: implementation, math Correct Solution: ``` a1,b1,c1=list(map(int,input().split())) a2,b2,c2=list(map(int,input().split())) if (a1==0 and b1==0 and c1!=0) or (a2==0 and b2==0 and c2!=0): c=0 print(c) elif (a2==1 and b2==-1 and c2==-1 and c1!=-1): c=-1 print(c) elif (a2==0 and b2==0 and c2==0): c=-1 print(c) elif (a1==0 and b1==0 and c1==0): c=-1 print(c) elif (b2==0 and b1==0 and c2!=0 and c1!=0 and a2==7): c=0 print(c) elif (b2==0 and b1==0 and c2!=0 and c1!=0 and a2!=2): c=-1 print(c) elif (a1==0 and b1==0 and c1 ==0) and (a2==0 and b2==1 and c2==-1): c=-1 print(c) elif (a1==1 and b1==0 and c1==0) and (a2==1 and b2==0 and c2==0): c=-1 print(c) elif (a1==1 and b1==0 and c1 ==1) and (a2==-1 and b2==0 and c2==-1): c=-1 print(c) elif (a1==0 and b1==0 and c1 ==0) and (a2==0 and b2==0 and c2==0): c=-1 print(c) elif (a1==1 and b1==0 and c1 ==0) and (a2==1 and b2==0 and c2==1): c=-1 print(c) elif (a1==1 and b1==1 and c1 ==1) and (a2==0 and b2==0 and c2==0): c=-1 print(c) elif (a1*b2==0 and a2*b1==0) and (b1*c2==0 and b2*c1==0): c=0 print(c) elif(a1*b2==a2*b1) and (b1*c2==b2*c1): c=-1 print(c) elif(a1*b2==a2*b1) and (b1*c2!=b2*c1): c=0 print(c) else: c=1 print(c) ```
12,735
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two set of points. The first set is determined by the equation A1x + B1y + C1 = 0, and the second one is determined by the equation A2x + B2y + C2 = 0. Write the program which finds the number of points in the intersection of two given sets. Input The first line of the input contains three integer numbers A1, B1, C1 separated by space. The second line contains three integer numbers A2, B2, C2 separated by space. All the numbers are between -100 and 100, inclusive. Output Print the number of points in the intersection or -1 if there are infinite number of points. Examples Input 1 1 0 2 2 0 Output -1 Input 1 1 0 2 -2 0 Output 1 Tags: implementation, math Correct Solution: ``` #codeforces 21b intersection, math def readGen(transform): while (True): n=0 tmp=input().split() m=len(tmp) while (n<m): yield(transform(tmp[n])) n+=1 readint=readGen(int) A1,B1,C1=next(readint),next(readint),next(readint) A2,B2,C2=next(readint),next(readint),next(readint) def cross(a,b,c,d): return a*d-b*c def zero(A1,B1): return A1**2 + B1**2 == 0 def lineIntersect(A1,B1,C1,A2,B2,C2): if (cross(A1,B1,A2,B2)==0): if (cross(A1,C1,A2,C2)==0 and cross(B1,C1,B2,C2)==0): # same line return -1 else: # parallel return 0 else: # cross return 1 def judge(A1,B1,C1,A2,B2,C2): if (zero(A1,B1) and C1!=0): return 0 if (zero(A2,B2) and C2!=0): return 0 if (not zero(A1,B1) and not zero(A2,B2)): # line and line return lineIntersect(A1,B1,C1,A2,B2,C2) else: return -1 print(judge(A1,B1,C1,A2,B2,C2)) ```
12,736
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two set of points. The first set is determined by the equation A1x + B1y + C1 = 0, and the second one is determined by the equation A2x + B2y + C2 = 0. Write the program which finds the number of points in the intersection of two given sets. Input The first line of the input contains three integer numbers A1, B1, C1 separated by space. The second line contains three integer numbers A2, B2, C2 separated by space. All the numbers are between -100 and 100, inclusive. Output Print the number of points in the intersection or -1 if there are infinite number of points. Examples Input 1 1 0 2 2 0 Output -1 Input 1 1 0 2 -2 0 Output 1 Tags: implementation, math Correct Solution: ``` a1, b1, c1 = input().split(' ') a2, b2, c2 = input().split(' ') a1 = int(a1) b1 = int(b1) c1 = int(c1) a2 = int(a2) b2 = int(b2) c2 = int(c2) if((a1 == 0 and b1 == 0) and (a2 == 0 and b2 == 0) and c1 != c2): print(0) exit() if((a1 == 0 and b1 == 0 and c1 == 0) or (a2 == 0 and b2 == 0 and c2 == 0)): print(-1) exit() if((a1 == 0 and b1 == 0 and c1 != 0) or (a2 == 0 and b2 == 0 and c2 != 0) and (c1 == c2)): print(0) exit() if(a1 * b2 == b1 * a2 and b2 * c1 == c2 * b1 and c1 * a2 == c2 * a1): print(-1) exit() if(((a1 * b2) - (a2 * b1)) == 0): print(0) exit() print(1) exit() ```
12,737
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two set of points. The first set is determined by the equation A1x + B1y + C1 = 0, and the second one is determined by the equation A2x + B2y + C2 = 0. Write the program which finds the number of points in the intersection of two given sets. Input The first line of the input contains three integer numbers A1, B1, C1 separated by space. The second line contains three integer numbers A2, B2, C2 separated by space. All the numbers are between -100 and 100, inclusive. Output Print the number of points in the intersection or -1 if there are infinite number of points. Examples Input 1 1 0 2 2 0 Output -1 Input 1 1 0 2 -2 0 Output 1 Tags: implementation, math Correct Solution: ``` #! /usr/bin/python3 def solve(): x, y, z = map(int, input().strip().split()) a, b, c = map(int, input().strip().split()) ret = 0 if (x * b == y * a): if (y == 0 and b == 0): if c * x == a * z: ret = -1 else: ret = 0 elif z * b == y * c: ret = -1 else: ret = 0 else: ret = 1 if (x == y and y == a and a == b and b == 0): if (z == c and z == 0): ret = -1 else: ret = 0 print(ret) solve() ```
12,738
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two set of points. The first set is determined by the equation A1x + B1y + C1 = 0, and the second one is determined by the equation A2x + B2y + C2 = 0. Write the program which finds the number of points in the intersection of two given sets. Input The first line of the input contains three integer numbers A1, B1, C1 separated by space. The second line contains three integer numbers A2, B2, C2 separated by space. All the numbers are between -100 and 100, inclusive. Output Print the number of points in the intersection or -1 if there are infinite number of points. Examples Input 1 1 0 2 2 0 Output -1 Input 1 1 0 2 -2 0 Output 1 Tags: implementation, math Correct Solution: ``` def fazTudo(): ar,br,cr = map(int,input().split()); aw,bw,cw = map(int,input().split()); res=1; if(br==0 and bw==0): if(ar==0 and cr!=0 or aw==0 and cw!=0): print(0); return; if(ar==0 and br==0 and cr==0 or aw==0 and bw==0 and cw==0): print(-1); return; if(ar==0 and cr==0 or aw==0 and cw==0): print(-1); return; if(cr/ar==cw/aw): print(-1) return; if(ar==aw and cr!=cw): print(0); return; if(ar!=aw): print(0); return; if(br==0): if(ar==0 and cr!=0): print(0); return; if(ar==0 and br==0 and cr==0 or aw==0 and bw==0 and cw==0): print(-1); return; if(ar==0 and cr!=0): print(0); return; if(-aw/bw == ar and -cw/bw==cr): print(1) return; if(-aw/bw == ar and -cw/bw!=cr): print(1); return; print(1); return; if(bw==0): if(aw==0 and cw!=0): print(0); return; if(ar==0 and br==0 and cr==0 or aw==0 and bw==0 and cw==0): print(-1); return; if(aw==0 and cw!=0): print(0); return; if(-ar/br == aw and -cr/br==cw): print(1) return; if(-ar/br == aw and -cr/br!=cw): print(1); return; print(1); return; a1 = -(ar/br); b1 = -(cr/br); a2 = -(aw/bw); b2 = -(cw/bw); if(a1==a2): if(b1==b2): res = -1; else: res = 0; print(res); fazTudo(); ```
12,739
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two set of points. The first set is determined by the equation A1x + B1y + C1 = 0, and the second one is determined by the equation A2x + B2y + C2 = 0. Write the program which finds the number of points in the intersection of two given sets. Input The first line of the input contains three integer numbers A1, B1, C1 separated by space. The second line contains three integer numbers A2, B2, C2 separated by space. All the numbers are between -100 and 100, inclusive. Output Print the number of points in the intersection or -1 if there are infinite number of points. Examples Input 1 1 0 2 2 0 Output -1 Input 1 1 0 2 -2 0 Output 1 Submitted Solution: ``` a1,b1,c1=list(map(int,input().split())) a2,b2,c2=list(map(int,input().split())) if (a1==0 and b1==0 and c1!=0) or (a2==0 and b2==0 and c2!=0): c=0 print(c) elif (a2==1 and b2==-1 and c2==-1 and c1!=-1): c=-1 print(c) elif (a2==0 and b2==0 and c2==0): c=-1 print(c) elif (a1==0 and b1==0 and c1==0): c=-1 print(c) elif (b2==0 and b1==0 and c2!=0 and c1!=0 and a2==7): c=0 print(c) elif (b2==0 and b1==0 and c2!=0 and c1!=0 and a2!=2): c=-1 print(c) elif (a1==0 and b1==0 and c1 ==0) and (a2==0 and b2==1 and c2==-1): c=-1 print(c) elif (a1==1 and b1==0 and c1==0) and (a2==1 and b2==0 and c2==0): c=-1 print(c) elif (a1==1 and b1==0 and c1 ==1) and (a2==-1 and b2==0 and c2==-1): c=-1 print(c) elif (a1==1 and b1==1 and c1 ==1) and (a2==0 and b2==0 and c2==0): c=-1 print(c) elif (a1*b2==0 and a2*b1==0) and (b1*c2==0 and b2*c1==0): c=0 print(c) elif(a1*b2==a2*b1) and (b1*c2==b2*c1): c=-1 print(c) elif(a1*b2==a2*b1) and (b1*c2!=b2*c1): c=0 print(c) else: c=1 print(c) ``` Yes
12,740
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two set of points. The first set is determined by the equation A1x + B1y + C1 = 0, and the second one is determined by the equation A2x + B2y + C2 = 0. Write the program which finds the number of points in the intersection of two given sets. Input The first line of the input contains three integer numbers A1, B1, C1 separated by space. The second line contains three integer numbers A2, B2, C2 separated by space. All the numbers are between -100 and 100, inclusive. Output Print the number of points in the intersection or -1 if there are infinite number of points. Examples Input 1 1 0 2 2 0 Output -1 Input 1 1 0 2 -2 0 Output 1 Submitted Solution: ``` def intersection(lst1, lst2): if lst1[0] * lst2[1] != lst1[1] * lst2[0]: return 1 elif lst1[0] == lst1[1] == lst2[0] == lst2[1] == 0 and ( lst1[2] != 0 and lst2[2] == 0 or lst1[2] == 0 and lst2[2] != 0 or lst1[2] != 0 and lst2[2] != 0): return 0 elif lst1[0] * lst2[1] == lst1[1] * lst2[0] and ( lst1[2] * lst2[1] != lst2[2] * lst1[1] or lst1[0] * lst2[2] != lst1[2] * lst2[0]): return 0 elif lst1[0] * lst2[1] == lst1[1] * lst2[0] and lst1[2] * lst2[1] == lst2[2] * lst1[1]: return -1 elif lst2[0] * lst1[1] == - lst1[0] * lst2[1] and lst1[2] == lst1[2] == 0: return 1 a = [int(i) for i in input().split()] b = [int(j) for j in input().split()] print(intersection(a, b)) ``` Yes
12,741
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two set of points. The first set is determined by the equation A1x + B1y + C1 = 0, and the second one is determined by the equation A2x + B2y + C2 = 0. Write the program which finds the number of points in the intersection of two given sets. Input The first line of the input contains three integer numbers A1, B1, C1 separated by space. The second line contains three integer numbers A2, B2, C2 separated by space. All the numbers are between -100 and 100, inclusive. Output Print the number of points in the intersection or -1 if there are infinite number of points. Examples Input 1 1 0 2 2 0 Output -1 Input 1 1 0 2 -2 0 Output 1 Submitted Solution: ``` A1, B1, C1 = tuple(map(int, input().split(" "))) A2, B2, C2 = tuple(map(int, input().split(" "))) D = A1*B2 - A2*B1 Dx = C1*B2 - C2*B1 Dy = C2*A1 - C1*A2 if(A1 == 0 and B1 == 0 and C1 != 0): print(0) elif(A2 == 0 and B2 == 0 and C2 != 0): print(0) elif(D == 0): if(Dx == 0 and Dy == 0): print(-1) else: print(0) else: print(1) ``` Yes
12,742
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two set of points. The first set is determined by the equation A1x + B1y + C1 = 0, and the second one is determined by the equation A2x + B2y + C2 = 0. Write the program which finds the number of points in the intersection of two given sets. Input The first line of the input contains three integer numbers A1, B1, C1 separated by space. The second line contains three integer numbers A2, B2, C2 separated by space. All the numbers are between -100 and 100, inclusive. Output Print the number of points in the intersection or -1 if there are infinite number of points. Examples Input 1 1 0 2 2 0 Output -1 Input 1 1 0 2 -2 0 Output 1 Submitted Solution: ``` a1, b1, c1 = [int(i) for i in input().split()] a2, b2, c2 = [int(i) for i in input().split()] if c1 != c2 and (a1 == 0 and b1 == 0) and (a2 == 0 and b2 == 0) : print(0) elif (a1 == 0 and b1 == 0 and c1 == 0) or (a2 == 0 and b2 == 0 and c2 == 0) : print(-1) elif (a1 == 0 and b1 == 0 and c1 != 0) or (a2 == 0 and b2 == 0 and c2 != 0) and (c1 == c2): print(0) elif a1 * b2 == b1 * a2 and b2 * c1 == c2 * b1 and c1 * a2 == c2 * a1 : print(-1) elif ((a1 * b2) - (a2 * b1)) == 0: print(0) else: print(1) ``` Yes
12,743
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two set of points. The first set is determined by the equation A1x + B1y + C1 = 0, and the second one is determined by the equation A2x + B2y + C2 = 0. Write the program which finds the number of points in the intersection of two given sets. Input The first line of the input contains three integer numbers A1, B1, C1 separated by space. The second line contains three integer numbers A2, B2, C2 separated by space. All the numbers are between -100 and 100, inclusive. Output Print the number of points in the intersection or -1 if there are infinite number of points. Examples Input 1 1 0 2 2 0 Output -1 Input 1 1 0 2 -2 0 Output 1 Submitted Solution: ``` a1,b1,c1 = map(int, input().split()) a2,b2,c1 = map(int, input().split()) if a2*b1 == a1*b2: print(1) else: print(-1) ``` No
12,744
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two set of points. The first set is determined by the equation A1x + B1y + C1 = 0, and the second one is determined by the equation A2x + B2y + C2 = 0. Write the program which finds the number of points in the intersection of two given sets. Input The first line of the input contains three integer numbers A1, B1, C1 separated by space. The second line contains three integer numbers A2, B2, C2 separated by space. All the numbers are between -100 and 100, inclusive. Output Print the number of points in the intersection or -1 if there are infinite number of points. Examples Input 1 1 0 2 2 0 Output -1 Input 1 1 0 2 -2 0 Output 1 Submitted Solution: ``` def intersection(lst1, lst2): if lst1[0] * lst2[1] != lst1[1] * lst2[0]: return 1 elif lst1[0] * lst2[1] == lst1[1] * lst2[0] and ( lst1[2] * lst2[1] != lst2[2] * lst1[1] or lst1[0] * lst2[2] != lst1[2] * lst2[0]): return 0 elif lst1[0] * lst2[1] == lst1[1] * lst2[0] and lst1[2] * lst2[1] == lst2[2] * lst1[1]: return -1 elif lst2[0] * lst1[1] == - lst1[0] * lst2[1] and lst1[2] == lst1[2] == 0: return 1 elif lst1[0] * lst2[1] == lst1[1] * lst2[0] and (lst2[2] == 0 and lst1[2] != 0 or lst2[2] != 0 and lst1[2] == 0): return 0 a = [int(i) for i in input().split()] b = [int(j) for j in input().split()] print(intersection(a, b)) ``` No
12,745
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two set of points. The first set is determined by the equation A1x + B1y + C1 = 0, and the second one is determined by the equation A2x + B2y + C2 = 0. Write the program which finds the number of points in the intersection of two given sets. Input The first line of the input contains three integer numbers A1, B1, C1 separated by space. The second line contains three integer numbers A2, B2, C2 separated by space. All the numbers are between -100 and 100, inclusive. Output Print the number of points in the intersection or -1 if there are infinite number of points. Examples Input 1 1 0 2 2 0 Output -1 Input 1 1 0 2 -2 0 Output 1 Submitted Solution: ``` R = lambda:map(int, input().split()) a1, b1, c1 = R() a2, b2, c2 = R() if a1 * b2 - a2 * b1 == 0: if c1 == c2 or a1 == b1 == c1 == 0 or a2 == b2 == c2 == 0: print(-1) else: print(0) else: print(1) ``` No
12,746
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two set of points. The first set is determined by the equation A1x + B1y + C1 = 0, and the second one is determined by the equation A2x + B2y + C2 = 0. Write the program which finds the number of points in the intersection of two given sets. Input The first line of the input contains three integer numbers A1, B1, C1 separated by space. The second line contains three integer numbers A2, B2, C2 separated by space. All the numbers are between -100 and 100, inclusive. Output Print the number of points in the intersection or -1 if there are infinite number of points. Examples Input 1 1 0 2 2 0 Output -1 Input 1 1 0 2 -2 0 Output 1 Submitted Solution: ``` a1, b1, c1 = [int(x) for x in input().split()] a2, b2, c2 = [int(x) for x in input().split()] det = (a1*b2) - (a2*b1) if det!=0: print(1) elif ((a1*b2)==(b1*a2) and (a1*c2)==(a2*c1) and (b1*c2)==(b2*c1)) and not (a1==0 and b1==0 and a2==0 and b2==0 and c1!=c2): print(-1) else: print(0) ``` No
12,747
Provide tags and a correct Python 3 solution for this coding contest problem. Emuskald is an avid horticulturist and owns the world's longest greenhouse β€” it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line. Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left. Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders. Input The first line of input contains two space-separated integers n and m (1 ≀ n, m ≀ 5000, n β‰₯ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 ≀ si ≀ m), and one real number xi (0 ≀ xi ≀ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 ≀ i < n). Output Output a single integer β€” the minimum number of plants to be replanted. Examples Input 3 2 2 1 1 2.0 1 3.100 Output 1 Input 3 3 1 5.0 2 5.5 3 6.0 Output 0 Input 6 3 1 14.284235 2 17.921382 1 20.328172 3 20.842331 1 25.790145 1 27.204125 Output 2 Note In the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1. In the second test case, the species are already in the correct order, so no replanting is needed. Tags: dp Correct Solution: ``` from math import ceil,sqrt from collections import defaultdict def solve(): n,m = map(int,input().split()) l = [] for i in range(n): a,b = map(float,input().split()) l.append(a) dp = [0]*(n) for i in range(n): maxi = 0 for j in range(i): if l[i]>=l[j]: maxi = max(dp[j],maxi) dp[i] = maxi+1 # print(dp) print(n-max(dp)) # t = int(input()) # for _ in range(t): solve() ```
12,748
Provide tags and a correct Python 3 solution for this coding contest problem. Emuskald is an avid horticulturist and owns the world's longest greenhouse β€” it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line. Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left. Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders. Input The first line of input contains two space-separated integers n and m (1 ≀ n, m ≀ 5000, n β‰₯ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 ≀ si ≀ m), and one real number xi (0 ≀ xi ≀ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 ≀ i < n). Output Output a single integer β€” the minimum number of plants to be replanted. Examples Input 3 2 2 1 1 2.0 1 3.100 Output 1 Input 3 3 1 5.0 2 5.5 3 6.0 Output 0 Input 6 3 1 14.284235 2 17.921382 1 20.328172 3 20.842331 1 25.790145 1 27.204125 Output 2 Note In the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1. In the second test case, the species are already in the correct order, so no replanting is needed. Tags: dp Correct Solution: ``` # Dynamic programming Python implementation # of LIS problem # lis returns length of the longest # increasing subsequence in arr of size n def lis(l, arr): # Declare the list (array) for LIS and # initialize LIS values for all indexes ls = [1] * l # Compute optimized LIS values in bottom up manner for i in range(1, l): for j in range(0, i): if arr[i] >= arr[j] and ls[i] < ls[j] + 1: ls[i] = ls[j] + 1 # print(ls) return l - max(ls) # end of lis function n, m = map(int, input().split()) lst = [] for i in range(n): a, b = map(float, input().split()) lst.append(a) print(lis(n, lst)) ```
12,749
Provide tags and a correct Python 3 solution for this coding contest problem. Emuskald is an avid horticulturist and owns the world's longest greenhouse β€” it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line. Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left. Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders. Input The first line of input contains two space-separated integers n and m (1 ≀ n, m ≀ 5000, n β‰₯ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 ≀ si ≀ m), and one real number xi (0 ≀ xi ≀ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 ≀ i < n). Output Output a single integer β€” the minimum number of plants to be replanted. Examples Input 3 2 2 1 1 2.0 1 3.100 Output 1 Input 3 3 1 5.0 2 5.5 3 6.0 Output 0 Input 6 3 1 14.284235 2 17.921382 1 20.328172 3 20.842331 1 25.790145 1 27.204125 Output 2 Note In the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1. In the second test case, the species are already in the correct order, so no replanting is needed. Tags: dp Correct Solution: ``` def f(arr): arr=[None]+arr dp=[0]*(len(arr)) for i in range(1,len(arr)): j=int(arr[i]) for k in range(int(j),0,-1): dp[j]=max(dp[j],1+dp[k]) return len(arr)-max(dp)-1 # Dynamic programming Python implementation # of LIS problem # lis returns length of the longest # increasing subsequence in arr of size n def lis(arr): n = len(arr) # Declare the list (array) for LIS and # initialize LIS values for all indexes lis = [1]*n # Compute optimized LIS values in bottom up manner for i in range (1 , n): for j in range(0 , i): if arr[i] >= arr[j] and lis[i]< lis[j] + 1 : lis[i] = lis[j]+1 # Initialize maximum to 0 to get # the maximum of all LIS return max(len(lst)-max(lis),0) a,b=map(int,input().strip().split()) lst=[] for i in range(a): x,y=map(float,input().strip().split()) lst.append(x) print(lis(lst)) ```
12,750
Provide tags and a correct Python 3 solution for this coding contest problem. Emuskald is an avid horticulturist and owns the world's longest greenhouse β€” it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line. Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left. Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders. Input The first line of input contains two space-separated integers n and m (1 ≀ n, m ≀ 5000, n β‰₯ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 ≀ si ≀ m), and one real number xi (0 ≀ xi ≀ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 ≀ i < n). Output Output a single integer β€” the minimum number of plants to be replanted. Examples Input 3 2 2 1 1 2.0 1 3.100 Output 1 Input 3 3 1 5.0 2 5.5 3 6.0 Output 0 Input 6 3 1 14.284235 2 17.921382 1 20.328172 3 20.842331 1 25.790145 1 27.204125 Output 2 Note In the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1. In the second test case, the species are already in the correct order, so no replanting is needed. Tags: dp Correct Solution: ``` def lis(arr): n = len(arr) # Declare the list (array) for LIS and # initialize LIS values for all indexes lis = [1]*n # Compute optimized LIS values in bottom up manner for i in range (1 , n): for j in range(0 , i): if arr[i] >= arr[j] and lis[i]< lis[j] + 1 : lis[i] = lis[j]+1 # Initialize maximum to 0 to get # the maximum of all LIS return max(len(lst)-max(lis),0) a,b=map(int,input().strip().split()) lst=[] for i in range(a): x,y=map(float,input().strip().split()) lst.append(x) print(lis(lst)) ```
12,751
Provide tags and a correct Python 3 solution for this coding contest problem. Emuskald is an avid horticulturist and owns the world's longest greenhouse β€” it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line. Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left. Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders. Input The first line of input contains two space-separated integers n and m (1 ≀ n, m ≀ 5000, n β‰₯ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 ≀ si ≀ m), and one real number xi (0 ≀ xi ≀ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 ≀ i < n). Output Output a single integer β€” the minimum number of plants to be replanted. Examples Input 3 2 2 1 1 2.0 1 3.100 Output 1 Input 3 3 1 5.0 2 5.5 3 6.0 Output 0 Input 6 3 1 14.284235 2 17.921382 1 20.328172 3 20.842331 1 25.790145 1 27.204125 Output 2 Note In the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1. In the second test case, the species are already in the correct order, so no replanting is needed. Tags: dp Correct Solution: ``` n,m = list(map(int,input().split())) arr = [] for i in range(n): l = list(map(float,input().split())) arr.append(int(l[0])) dp = [1 for i in range(n)] for i in range(1,n): for j in range(i): if arr[j]<=arr[i]: dp[i] = max(dp[i],dp[j]+1) print(n-max(dp)) ```
12,752
Provide tags and a correct Python 3 solution for this coding contest problem. Emuskald is an avid horticulturist and owns the world's longest greenhouse β€” it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line. Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left. Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders. Input The first line of input contains two space-separated integers n and m (1 ≀ n, m ≀ 5000, n β‰₯ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 ≀ si ≀ m), and one real number xi (0 ≀ xi ≀ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 ≀ i < n). Output Output a single integer β€” the minimum number of plants to be replanted. Examples Input 3 2 2 1 1 2.0 1 3.100 Output 1 Input 3 3 1 5.0 2 5.5 3 6.0 Output 0 Input 6 3 1 14.284235 2 17.921382 1 20.328172 3 20.842331 1 25.790145 1 27.204125 Output 2 Note In the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1. In the second test case, the species are already in the correct order, so no replanting is needed. Tags: dp Correct Solution: ``` n, m = [int(x) for x in input().split()] d = [0 for i in range(m)] for i in range(n): c, x = [x for x in input().split()] c = int(c) d[c-1] = max(d[:c])+1 print(n-max(d)) ```
12,753
Provide tags and a correct Python 3 solution for this coding contest problem. Emuskald is an avid horticulturist and owns the world's longest greenhouse β€” it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line. Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left. Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders. Input The first line of input contains two space-separated integers n and m (1 ≀ n, m ≀ 5000, n β‰₯ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 ≀ si ≀ m), and one real number xi (0 ≀ xi ≀ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 ≀ i < n). Output Output a single integer β€” the minimum number of plants to be replanted. Examples Input 3 2 2 1 1 2.0 1 3.100 Output 1 Input 3 3 1 5.0 2 5.5 3 6.0 Output 0 Input 6 3 1 14.284235 2 17.921382 1 20.328172 3 20.842331 1 25.790145 1 27.204125 Output 2 Note In the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1. In the second test case, the species are already in the correct order, so no replanting is needed. Tags: dp Correct Solution: ``` n,m=map(int,input().split()) l=[] for i in range(n): a,b=input().split() l.append(int(a)) dp=[1]*n for i in range(1,n): for j in range(0,i): if l[i]>=l[j]: dp[i]=max(dp[i],dp[j]+1) print(n-max(dp)) ```
12,754
Provide tags and a correct Python 3 solution for this coding contest problem. Emuskald is an avid horticulturist and owns the world's longest greenhouse β€” it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line. Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left. Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders. Input The first line of input contains two space-separated integers n and m (1 ≀ n, m ≀ 5000, n β‰₯ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 ≀ si ≀ m), and one real number xi (0 ≀ xi ≀ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 ≀ i < n). Output Output a single integer β€” the minimum number of plants to be replanted. Examples Input 3 2 2 1 1 2.0 1 3.100 Output 1 Input 3 3 1 5.0 2 5.5 3 6.0 Output 0 Input 6 3 1 14.284235 2 17.921382 1 20.328172 3 20.842331 1 25.790145 1 27.204125 Output 2 Note In the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1. In the second test case, the species are already in the correct order, so no replanting is needed. Tags: dp Correct Solution: ``` # -*- coding:utf-8 -*- """ created by shuangquan.huang at 1/10/20 LIS """ import collections import time import os import sys import bisect import heapq from typing import List def solve(N, M, A): bit = [0 for _ in range(N)] def add(index, val): while index < N: bit[index] = max(bit[index], val) index |= index + 1 def query(index): s = 0 while index >= 0: s = max(s, bit[index]) index = (index & (index + 1)) - 1 return s q = [(v, i) for i, v in enumerate(A)] q.sort() s = 0 for v, i in q: t = query(i) + 1 add(i, t) s = max(s, t) return N-s N, M = map(int, input().split()) A = [] for i in range(N): x, y = input().split() A.append(int(x)) print(solve(N, M, A)) ```
12,755
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Emuskald is an avid horticulturist and owns the world's longest greenhouse β€” it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line. Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left. Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders. Input The first line of input contains two space-separated integers n and m (1 ≀ n, m ≀ 5000, n β‰₯ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 ≀ si ≀ m), and one real number xi (0 ≀ xi ≀ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 ≀ i < n). Output Output a single integer β€” the minimum number of plants to be replanted. Examples Input 3 2 2 1 1 2.0 1 3.100 Output 1 Input 3 3 1 5.0 2 5.5 3 6.0 Output 0 Input 6 3 1 14.284235 2 17.921382 1 20.328172 3 20.842331 1 25.790145 1 27.204125 Output 2 Note In the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1. In the second test case, the species are already in the correct order, so no replanting is needed. Submitted Solution: ``` '''n, m, k = [int(x) for x in input().split()] trees = tuple([int(x) for x in input().split()]) costs = [] for x in range(n): costs.append([0] + [int(x) for x in input().split()]) dp = [[[float('inf') for z in range(m + 1)] for y in range(k + 1)] for x in range(n)] if trees[0] == 0: for k in range(len(dp[0][0])): dp[0][1][k] = cost[0][k] else: dp[0][0][trees[0]] = cost[0][trees[0]] for i in range(1, len(dp)): for j in range(1, len(dp[0])): for k in range(1, len(dp[0][0])): if trees for l in range(len(dp[0][0])): if k == l: dp[i][j][k] = dp[i - 1][j][k] + cost[i][k] else: dp[i][j][k] = dp[i - 1][j - 1][l] + cost[i][k]''' n, m = [int(x) for x in input().split()] plant = [int(input().split()[0]) for x in range(n)] dp = [1 for x in range(n)] for i in range(len(plant)): for j in range(0, i): if plant[j] > plant[i]: continue dp[i] = max(dp[i], dp[j] + 1) #print(dp) print(n - max(dp)) '''for i in range(1, n): for k in range(plant[i], 0, -1): dp[plant[i]] = max(dp[plant[i]], 1 + dp[k]) print(n - max(dp) - 1)''' ``` Yes
12,756
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Emuskald is an avid horticulturist and owns the world's longest greenhouse β€” it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line. Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left. Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders. Input The first line of input contains two space-separated integers n and m (1 ≀ n, m ≀ 5000, n β‰₯ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 ≀ si ≀ m), and one real number xi (0 ≀ xi ≀ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 ≀ i < n). Output Output a single integer β€” the minimum number of plants to be replanted. Examples Input 3 2 2 1 1 2.0 1 3.100 Output 1 Input 3 3 1 5.0 2 5.5 3 6.0 Output 0 Input 6 3 1 14.284235 2 17.921382 1 20.328172 3 20.842331 1 25.790145 1 27.204125 Output 2 Note In the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1. In the second test case, the species are already in the correct order, so no replanting is needed. Submitted Solution: ``` """ Code of Ayush Tiwari Codeforces: servermonk Codechef: ayush572000 """ import sys input = sys.stdin.buffer.readline def solution(): # This is the main code n,m=map(int,input().split()) l=[] dp=[1]*(n+1) for i in range(n): x,y=map(float,input().split()) l.append([x,y]) for i in range(1,n): for j in range(i): if(l[i][0]>=l[j][0]): dp[i]=max(dp[i],dp[j]+1) print(n-max(dp)) t=1 for _ in range(t): solution() ``` Yes
12,757
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Emuskald is an avid horticulturist and owns the world's longest greenhouse β€” it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line. Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left. Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders. Input The first line of input contains two space-separated integers n and m (1 ≀ n, m ≀ 5000, n β‰₯ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 ≀ si ≀ m), and one real number xi (0 ≀ xi ≀ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 ≀ i < n). Output Output a single integer β€” the minimum number of plants to be replanted. Examples Input 3 2 2 1 1 2.0 1 3.100 Output 1 Input 3 3 1 5.0 2 5.5 3 6.0 Output 0 Input 6 3 1 14.284235 2 17.921382 1 20.328172 3 20.842331 1 25.790145 1 27.204125 Output 2 Note In the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1. In the second test case, the species are already in the correct order, so no replanting is needed. Submitted Solution: ``` from sys import stdin n,m=map(int,input().split()) s=[list(map(float,stdin.readline().strip().split()))[::-1] for i in range(n)] s.sort() s1=[int(i[1]) for i in s] dp=[1 for i in range(n)] ans=1 for i in range(n-2,-1,-1): for j in range(i+1,n): if s1[j]>=s1[i]: dp[i]=max(dp[i],1+dp[j]) ans=max(dp[i],ans) print(n-ans) ``` Yes
12,758
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Emuskald is an avid horticulturist and owns the world's longest greenhouse β€” it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line. Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left. Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders. Input The first line of input contains two space-separated integers n and m (1 ≀ n, m ≀ 5000, n β‰₯ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 ≀ si ≀ m), and one real number xi (0 ≀ xi ≀ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 ≀ i < n). Output Output a single integer β€” the minimum number of plants to be replanted. Examples Input 3 2 2 1 1 2.0 1 3.100 Output 1 Input 3 3 1 5.0 2 5.5 3 6.0 Output 0 Input 6 3 1 14.284235 2 17.921382 1 20.328172 3 20.842331 1 25.790145 1 27.204125 Output 2 Note In the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1. In the second test case, the species are already in the correct order, so no replanting is needed. Submitted Solution: ``` def CeilIndex(A, l, r, key): while (r - l > 1): m = l + (r - l)//2 if (A[m] > key): r = m else: l = m return r def LongestIncreasingSubsequenceLength(A, size): # Add boundary case, # when array size is one tailTable = [0 for i in range(size + 1)] len = 0 # always points empty slot tailTable[0] = A[0] len = 1 for i in range(1, size): if (A[i] < tailTable[0]): # new smallest value tailTable[0] = A[i] elif (A[i] >= tailTable[len-1]): # A[i] wants to extend # largest subsequence tailTable[len] = A[i] len+= 1 else: # A[i] wants to be current # end candidate of an existing # subsequence. It will replace # ceil value in tailTable tailTable[CeilIndex(tailTable, -1, len-1, A[i])] = A[i] return len # driver code arr = [] n,m=map(int,input().split()) for i in range(n) : a,b=map(float,input().split()) arr.append(a) print(n-LongestIncreasingSubsequenceLength(arr, n)) # This code is contributed # by Anant Agarwal. ``` Yes
12,759
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Emuskald is an avid horticulturist and owns the world's longest greenhouse β€” it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line. Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left. Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders. Input The first line of input contains two space-separated integers n and m (1 ≀ n, m ≀ 5000, n β‰₯ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 ≀ si ≀ m), and one real number xi (0 ≀ xi ≀ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 ≀ i < n). Output Output a single integer β€” the minimum number of plants to be replanted. Examples Input 3 2 2 1 1 2.0 1 3.100 Output 1 Input 3 3 1 5.0 2 5.5 3 6.0 Output 0 Input 6 3 1 14.284235 2 17.921382 1 20.328172 3 20.842331 1 25.790145 1 27.204125 Output 2 Note In the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1. In the second test case, the species are already in the correct order, so no replanting is needed. Submitted Solution: ``` #!/usr/bin/env python3 # created : 2020. 12. 31. 23:59 import os from sys import stdin, stdout from collections import deque from bisect import bisect_left, bisect_right def solve(tc): n, m = map(int, stdin.readline().split()) species = [] for i in range(n): si, xi = stdin.readline().split() species.append(int(si)) ans = n+1 cnt = 0 dq = deque() for i in range(n): if len(dq) > 0 and dq[-1] > species[i]: cnt += 1 k = bisect_right(dq, species[i]) dq.insert(k, species[i]) ans = min(ans, cnt) cnt = 0 dq.clear() for i in range(n-1, -1, -1): if len(dq) > 0 and dq[0] < species[i]: cnt += 1 k = bisect_left(dq, species[i]) dq.insert(k, species[i]) ans = min(ans, cnt) print(ans) tcs = 1 # tcs = int(stdin.readline().strip()) tc = 1 while tc <= tcs: solve(tc) tc += 1 ``` No
12,760
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Emuskald is an avid horticulturist and owns the world's longest greenhouse β€” it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line. Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left. Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders. Input The first line of input contains two space-separated integers n and m (1 ≀ n, m ≀ 5000, n β‰₯ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 ≀ si ≀ m), and one real number xi (0 ≀ xi ≀ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 ≀ i < n). Output Output a single integer β€” the minimum number of plants to be replanted. Examples Input 3 2 2 1 1 2.0 1 3.100 Output 1 Input 3 3 1 5.0 2 5.5 3 6.0 Output 0 Input 6 3 1 14.284235 2 17.921382 1 20.328172 3 20.842331 1 25.790145 1 27.204125 Output 2 Note In the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1. In the second test case, the species are already in the correct order, so no replanting is needed. Submitted Solution: ``` '''n, m, k = [int(x) for x in input().split()] trees = tuple([int(x) for x in input().split()]) costs = [] for x in range(n): costs.append([0] + [int(x) for x in input().split()]) dp = [[[float('inf') for z in range(m + 1)] for y in range(k + 1)] for x in range(n)] if trees[0] == 0: for k in range(len(dp[0][0])): dp[0][1][k] = cost[0][k] else: dp[0][0][trees[0]] = cost[0][trees[0]] for i in range(1, len(dp)): for j in range(1, len(dp[0])): for k in range(1, len(dp[0][0])): if trees for l in range(len(dp[0][0])): if k == l: dp[i][j][k] = dp[i - 1][j][k] + cost[i][k] else: dp[i][j][k] = dp[i - 1][j - 1][l] + cost[i][k]''' n, m = [int(x) for x in input().split()] plant = [0] + [int(input().split()[0]) for x in range(n)] dp = [0 for x in range(m + 1)] for i in range(1, n): for k in range(plant[i], 0, -1): dp[plant[i]] = max(dp[plant[i]], 1 + dp[k]) print(n - max(dp) - 1) ``` No
12,761
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Emuskald is an avid horticulturist and owns the world's longest greenhouse β€” it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line. Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left. Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders. Input The first line of input contains two space-separated integers n and m (1 ≀ n, m ≀ 5000, n β‰₯ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 ≀ si ≀ m), and one real number xi (0 ≀ xi ≀ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 ≀ i < n). Output Output a single integer β€” the minimum number of plants to be replanted. Examples Input 3 2 2 1 1 2.0 1 3.100 Output 1 Input 3 3 1 5.0 2 5.5 3 6.0 Output 0 Input 6 3 1 14.284235 2 17.921382 1 20.328172 3 20.842331 1 25.790145 1 27.204125 Output 2 Note In the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1. In the second test case, the species are already in the correct order, so no replanting is needed. Submitted Solution: ``` #!/usr/bin/env python3 # created : 2020. 12. 31. 23:59 import os from sys import stdin, stdout from heapq import heappop, heappush def solve(tc): n, m = map(int, stdin.readline().split()) species = [] for i in range(n): si, xi = stdin.readline().split() species.append(int(si)) ans = n+1 cnt = 0 maxheap = [0] for i in range(n): if maxheap[-1] > species[i]: cnt += 1 heappush(maxheap, species[i]) ans = min(ans, cnt) cnt = 0 minheap = [m] for i in range(n-1, -1, -1): if -minheap[-1] < species[i]: cnt += 1 heappush(minheap, -species[i]) ans = min(ans, cnt) print(ans) tcs = 1 # tcs = int(stdin.readline().strip()) tc = 1 while tc <= tcs: solve(tc) tc += 1 ``` No
12,762
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Emuskald is an avid horticulturist and owns the world's longest greenhouse β€” it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line. Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left. Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders. Input The first line of input contains two space-separated integers n and m (1 ≀ n, m ≀ 5000, n β‰₯ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 ≀ si ≀ m), and one real number xi (0 ≀ xi ≀ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 ≀ i < n). Output Output a single integer β€” the minimum number of plants to be replanted. Examples Input 3 2 2 1 1 2.0 1 3.100 Output 1 Input 3 3 1 5.0 2 5.5 3 6.0 Output 0 Input 6 3 1 14.284235 2 17.921382 1 20.328172 3 20.842331 1 25.790145 1 27.204125 Output 2 Note In the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1. In the second test case, the species are already in the correct order, so no replanting is needed. Submitted Solution: ``` #!/usr/bin/env python3 # created : 2020. 12. 31. 23:59 import os from sys import stdin, stdout def solve(tc): n, m = map(int, stdin.readline().split()) mapping = [0 for i in range(m+1)] species = [] for i in range(n): si, xi = stdin.readline().split() si = int(si) mapping[si] += 1 species.append(si) ans = 0 p = 0 for num in range(m+1): cur = 0 while p < n and cur < mapping[num]: if species[p] == num: cur += 1 else: ans += 1 p += 1 print(ans) tcs = 1 # tcs = int(stdin.readline().strip()) tc = 1 while tc <= tcs: solve(tc) tc += 1 ``` No
12,763
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarpus has a computer with n processors. Also, his computer has n memory cells. We'll consider the processors numbered by integers from 1 to n and that the memory cells are consecutively numbered by integers from 1 to n. Polycarpus needs to come up with a parallel program model. For each memory cell number i this program must record the value n - i to this cell. In other words, for each cell you've got to find the distance to cell n. Let's denote the value that is written in the i-th cell as ai. Initially, ai = 1 (1 ≀ i < n) and an = 0. We will consider that only processor i can write values in the memory cell number i. All processors can read an information from some cell (several processors can read an information from some cell simultaneously). The parallel program is executed in several steps. During each step we execute the parallel version of the increment operation. Executing the parallel version of the increment operation goes as follows: 1. Each processor independently of the other ones chooses some memory cell. Let's say that processor i has chosen a cell with number ci (1 ≀ ci ≀ n). 2. All processors simultaneously execute operation ai = ai + aci. Help Polycarpus come up with the parallel program model that is executed in exactly k steps. Calculate the operations that need to be executed. Note that after k steps for all i's value ai must be equal n - i. Input The first line contains two space-separated integers n and k (1 ≀ n ≀ 104, 1 ≀ k ≀ 20). It is guaranteed that at the given n and k the required sequence of operations exists. Output Print exactly nΒ·k integers in k lines. In the first line print numbers c1, c2, ..., cn (1 ≀ ci ≀ n) for the first increment operation. In the second line print the numbers for the second increment operation. In the k-th line print the numbers for the k-th increment operation. As a result of the printed operations for any i value ai must equal n - i. Examples Input 1 1 Output 1 Input 3 2 Output 2 3 3 3 3 3 Tags: *special, greedy Correct Solution: ``` n, k = map(int, input().split()) i, j = 1, 2 while n >= i and k > 0: print((str(n - i) + ' ') * max(0, n - j) + ' '.join(map(str, range(max(i + 1, n - i + 1), n + 1))) + (' ' + str(n)) * i) i, j, k = j, 2 * j, k - 1 for i in range(k): print((str(n) + ' ') * n) ```
12,764
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarpus has a computer with n processors. Also, his computer has n memory cells. We'll consider the processors numbered by integers from 1 to n and that the memory cells are consecutively numbered by integers from 1 to n. Polycarpus needs to come up with a parallel program model. For each memory cell number i this program must record the value n - i to this cell. In other words, for each cell you've got to find the distance to cell n. Let's denote the value that is written in the i-th cell as ai. Initially, ai = 1 (1 ≀ i < n) and an = 0. We will consider that only processor i can write values in the memory cell number i. All processors can read an information from some cell (several processors can read an information from some cell simultaneously). The parallel program is executed in several steps. During each step we execute the parallel version of the increment operation. Executing the parallel version of the increment operation goes as follows: 1. Each processor independently of the other ones chooses some memory cell. Let's say that processor i has chosen a cell with number ci (1 ≀ ci ≀ n). 2. All processors simultaneously execute operation ai = ai + aci. Help Polycarpus come up with the parallel program model that is executed in exactly k steps. Calculate the operations that need to be executed. Note that after k steps for all i's value ai must be equal n - i. Input The first line contains two space-separated integers n and k (1 ≀ n ≀ 104, 1 ≀ k ≀ 20). It is guaranteed that at the given n and k the required sequence of operations exists. Output Print exactly nΒ·k integers in k lines. In the first line print numbers c1, c2, ..., cn (1 ≀ ci ≀ n) for the first increment operation. In the second line print the numbers for the second increment operation. In the k-th line print the numbers for the k-th increment operation. As a result of the printed operations for any i value ai must equal n - i. Examples Input 1 1 Output 1 Input 3 2 Output 2 3 3 3 3 3 Tags: *special, greedy Correct Solution: ``` n, k = map(int, input().split()) a = [1 for i in range(n + 1)] a[n] = 0 for iter in range(k): for i in range(1, n - 1): target = n - i if a[i + 1] > target - a[i]: # find right number target -= a[i] print(n - target, end=' ') a[i] += a[n - target]; else: a[i] += a[i + 1] print(i + 1, end=' ') for i in range(max(0, n - 2), n): print(n, end=' ') print() ```
12,765
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarpus has a computer with n processors. Also, his computer has n memory cells. We'll consider the processors numbered by integers from 1 to n and that the memory cells are consecutively numbered by integers from 1 to n. Polycarpus needs to come up with a parallel program model. For each memory cell number i this program must record the value n - i to this cell. In other words, for each cell you've got to find the distance to cell n. Let's denote the value that is written in the i-th cell as ai. Initially, ai = 1 (1 ≀ i < n) and an = 0. We will consider that only processor i can write values in the memory cell number i. All processors can read an information from some cell (several processors can read an information from some cell simultaneously). The parallel program is executed in several steps. During each step we execute the parallel version of the increment operation. Executing the parallel version of the increment operation goes as follows: 1. Each processor independently of the other ones chooses some memory cell. Let's say that processor i has chosen a cell with number ci (1 ≀ ci ≀ n). 2. All processors simultaneously execute operation ai = ai + aci. Help Polycarpus come up with the parallel program model that is executed in exactly k steps. Calculate the operations that need to be executed. Note that after k steps for all i's value ai must be equal n - i. Input The first line contains two space-separated integers n and k (1 ≀ n ≀ 104, 1 ≀ k ≀ 20). It is guaranteed that at the given n and k the required sequence of operations exists. Output Print exactly nΒ·k integers in k lines. In the first line print numbers c1, c2, ..., cn (1 ≀ ci ≀ n) for the first increment operation. In the second line print the numbers for the second increment operation. In the k-th line print the numbers for the k-th increment operation. As a result of the printed operations for any i value ai must equal n - i. Examples Input 1 1 Output 1 Input 3 2 Output 2 3 3 3 3 3 Submitted Solution: ``` n, k = map(int, input().split()) i, j = 1, 2 while n >= i: print((str(n - i) + ' ') * max(0, n - j) + ' '.join(map(str, range(max(i + 1, n - i + 1), n + 1))) + (' ' + str(n)) * i) i, j, k = j, 2 * j, k - 1 for i in range(k): print((str(n) + ' ') * n) ``` No
12,766
Provide tags and a correct Python 3 solution for this coding contest problem. By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher: You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: 1. For given numbers xi and vi assign value vi to element axi. 2. For given numbers li and ri you've got to calculate sum <image>, where f0 = f1 = 1 and at i β‰₯ 2: fi = fi - 1 + fi - 2. 3. For a group of three numbers li ri di you should increase value ax by di for all x (li ≀ x ≀ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem. Input The first line contains two integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≀ ti ≀ 3) β€” the operation type: * if ti = 1, then next follow two integers xi vi (1 ≀ xi ≀ n, 0 ≀ vi ≀ 105); * if ti = 2, then next follow two integers li ri (1 ≀ li ≀ ri ≀ n); * if ti = 3, then next follow three integers li ri di (1 ≀ li ≀ ri ≀ n, 0 ≀ di ≀ 105). The input limits for scoring 30 points are (subproblem E1): * It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type. The input limits for scoring 70 points are (subproblems E1+E2): * It is guaranteed that there will be queries of the 1-st and 2-nd type only. The input limits for scoring 100 points are (subproblems E1+E2+E3): * No extra limitations. Output For each query print the calculated sum modulo 1000000000 (109). Examples Input 5 5 1 3 1 2 4 2 1 4 2 1 5 2 2 4 1 3 10 2 1 5 Output 12 32 8 50 Input 5 4 1 3 1 2 4 3 1 4 1 2 2 4 1 2 10 2 1 5 Output 12 45 Tags: brute force, data structures Correct Solution: ``` # import itertools # import bisect # import math from collections import defaultdict, Counter import os import sys from io import BytesIO, IOBase # sys.setrecursionlimit(10 ** 5) ii = lambda: int(input()) lmii = lambda: list(map(int, input().split())) slmii = lambda: sorted(map(int, input().split())) li = lambda: list(input()) mii = lambda: map(int, input().split()) msi = lambda: map(str, input().split()) def gcd(a, b): if b == 0: return a return gcd(b, a % b) def lcm(a, b): return (a * b) // gcd(a, b) def main(): # for _ in " " * int(input()): n, m = mii() a = lmii() fac = [1, 1] for i in range(10 ** 5): fac.append((fac[-1] + fac[-2] % 10 ** 9)) for i in range(m): lst = lmii() if lst[0] == 1: a[lst[1] - 1] = lst[2] elif lst[0] == 2: s = 0 for j in range(lst[2] - lst[1] + 1): s += ((fac[j] * a[lst[1] - 1 + j]) % 10 ** 9) print(s % 10 ** 9) else: for j in range(lst[1], lst[2] + 1): a[j - 1] += lst[3] 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") if __name__ == "__main__": main() ```
12,767
Provide tags and a correct Python 3 solution for this coding contest problem. By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher: You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: 1. For given numbers xi and vi assign value vi to element axi. 2. For given numbers li and ri you've got to calculate sum <image>, where f0 = f1 = 1 and at i β‰₯ 2: fi = fi - 1 + fi - 2. 3. For a group of three numbers li ri di you should increase value ax by di for all x (li ≀ x ≀ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem. Input The first line contains two integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≀ ti ≀ 3) β€” the operation type: * if ti = 1, then next follow two integers xi vi (1 ≀ xi ≀ n, 0 ≀ vi ≀ 105); * if ti = 2, then next follow two integers li ri (1 ≀ li ≀ ri ≀ n); * if ti = 3, then next follow three integers li ri di (1 ≀ li ≀ ri ≀ n, 0 ≀ di ≀ 105). The input limits for scoring 30 points are (subproblem E1): * It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type. The input limits for scoring 70 points are (subproblems E1+E2): * It is guaranteed that there will be queries of the 1-st and 2-nd type only. The input limits for scoring 100 points are (subproblems E1+E2+E3): * No extra limitations. Output For each query print the calculated sum modulo 1000000000 (109). Examples Input 5 5 1 3 1 2 4 2 1 4 2 1 5 2 2 4 1 3 10 2 1 5 Output 12 32 8 50 Input 5 4 1 3 1 2 4 3 1 4 1 2 2 4 1 2 10 2 1 5 Output 12 45 Tags: brute force, data structures Correct Solution: ``` from sys import * from math import * mod = 1000000000 f = [0 for i in range(200)] f[0] = f[1] = 1 for i in range(2, 200): f[i] = f[i - 1] + f[i - 2] n, m = stdin.readline().split() n = int(n) m = int(m) a = list(map(int, stdin.readline().split())) for i in range(m): tp, x, y = stdin.readline().split() tp = int(tp) x = int(x) y = int(y) if tp == 1: x -= 1 a[x] = y else: s = 0 x -= 1 y -= 1 for p in range(y - x + 1): s += f[p] * a[x + p] print(s % mod) ```
12,768
Provide tags and a correct Python 3 solution for this coding contest problem. By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher: You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: 1. For given numbers xi and vi assign value vi to element axi. 2. For given numbers li and ri you've got to calculate sum <image>, where f0 = f1 = 1 and at i β‰₯ 2: fi = fi - 1 + fi - 2. 3. For a group of three numbers li ri di you should increase value ax by di for all x (li ≀ x ≀ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem. Input The first line contains two integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≀ ti ≀ 3) β€” the operation type: * if ti = 1, then next follow two integers xi vi (1 ≀ xi ≀ n, 0 ≀ vi ≀ 105); * if ti = 2, then next follow two integers li ri (1 ≀ li ≀ ri ≀ n); * if ti = 3, then next follow three integers li ri di (1 ≀ li ≀ ri ≀ n, 0 ≀ di ≀ 105). The input limits for scoring 30 points are (subproblem E1): * It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type. The input limits for scoring 70 points are (subproblems E1+E2): * It is guaranteed that there will be queries of the 1-st and 2-nd type only. The input limits for scoring 100 points are (subproblems E1+E2+E3): * No extra limitations. Output For each query print the calculated sum modulo 1000000000 (109). Examples Input 5 5 1 3 1 2 4 2 1 4 2 1 5 2 2 4 1 3 10 2 1 5 Output 12 32 8 50 Input 5 4 1 3 1 2 4 3 1 4 1 2 2 4 1 2 10 2 1 5 Output 12 45 Tags: brute force, data structures Correct Solution: ``` n,m = map(int,input().split()) a = list(map(int,input().split())) f = [1,1] for i in range(2,n+1): f.append(f[i-1] + f[i-2]) for q in range(m): z,l,r = map(int,input().split()) if z == 1: a[l-1] = r else: s = 0 for j in range(l-1,r): s += (a[j] * f[j-l+1]) s %= 10 ** 9 print(s) ```
12,769
Provide tags and a correct Python 3 solution for this coding contest problem. By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher: You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: 1. For given numbers xi and vi assign value vi to element axi. 2. For given numbers li and ri you've got to calculate sum <image>, where f0 = f1 = 1 and at i β‰₯ 2: fi = fi - 1 + fi - 2. 3. For a group of three numbers li ri di you should increase value ax by di for all x (li ≀ x ≀ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem. Input The first line contains two integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≀ ti ≀ 3) β€” the operation type: * if ti = 1, then next follow two integers xi vi (1 ≀ xi ≀ n, 0 ≀ vi ≀ 105); * if ti = 2, then next follow two integers li ri (1 ≀ li ≀ ri ≀ n); * if ti = 3, then next follow three integers li ri di (1 ≀ li ≀ ri ≀ n, 0 ≀ di ≀ 105). The input limits for scoring 30 points are (subproblem E1): * It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type. The input limits for scoring 70 points are (subproblems E1+E2): * It is guaranteed that there will be queries of the 1-st and 2-nd type only. The input limits for scoring 100 points are (subproblems E1+E2+E3): * No extra limitations. Output For each query print the calculated sum modulo 1000000000 (109). Examples Input 5 5 1 3 1 2 4 2 1 4 2 1 5 2 2 4 1 3 10 2 1 5 Output 12 32 8 50 Input 5 4 1 3 1 2 4 3 1 4 1 2 2 4 1 2 10 2 1 5 Output 12 45 Tags: brute force, data structures Correct Solution: ``` n,m = map(int,input().split()) d = [int(x) for x in input().split()] f = [1,1] for i in range(n): f.append((f[-1]+f[-2])% 1000000000) for i in range(m): s = [int(x) for x in input().split()] if s[0] == 1: x = s[1]-1 v = s[2] d[x] = v elif s[0] == 2: r = s[2]-1 l = s[1]-1 ans = 0 for i in range(r-l+1): #print("(",f[i],d[i+l],ans,")") ans = (ans % 10**9 + d[i+l]% 10**9 * f[i] % 10**9)% 10**9 print(ans) elif s[0] == 3: r = s[2]-1 l = s[1]-1 x = s[3] for i in range(l,r+1): d[i] += x ```
12,770
Provide tags and a correct Python 3 solution for this coding contest problem. By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher: You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: 1. For given numbers xi and vi assign value vi to element axi. 2. For given numbers li and ri you've got to calculate sum <image>, where f0 = f1 = 1 and at i β‰₯ 2: fi = fi - 1 + fi - 2. 3. For a group of three numbers li ri di you should increase value ax by di for all x (li ≀ x ≀ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem. Input The first line contains two integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≀ ti ≀ 3) β€” the operation type: * if ti = 1, then next follow two integers xi vi (1 ≀ xi ≀ n, 0 ≀ vi ≀ 105); * if ti = 2, then next follow two integers li ri (1 ≀ li ≀ ri ≀ n); * if ti = 3, then next follow three integers li ri di (1 ≀ li ≀ ri ≀ n, 0 ≀ di ≀ 105). The input limits for scoring 30 points are (subproblem E1): * It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type. The input limits for scoring 70 points are (subproblems E1+E2): * It is guaranteed that there will be queries of the 1-st and 2-nd type only. The input limits for scoring 100 points are (subproblems E1+E2+E3): * No extra limitations. Output For each query print the calculated sum modulo 1000000000 (109). Examples Input 5 5 1 3 1 2 4 2 1 4 2 1 5 2 2 4 1 3 10 2 1 5 Output 12 32 8 50 Input 5 4 1 3 1 2 4 3 1 4 1 2 2 4 1 2 10 2 1 5 Output 12 45 Tags: brute force, data structures Correct Solution: ``` n,m = map(int, input().split()) a = list(map(int, input().split())) f = [1]*n for i in range(2,n): f[i] = f[i-1]+f[i-2] for i in range(m): t,l,r = map(int, input().split()) if t==1: a[l-1] = r else: sum_lr = 0 for x in range(r-l+1): sum_lr += f[x] * a[l+x-1] print(sum_lr%1000000000) ```
12,771
Provide tags and a correct Python 3 solution for this coding contest problem. By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher: You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: 1. For given numbers xi and vi assign value vi to element axi. 2. For given numbers li and ri you've got to calculate sum <image>, where f0 = f1 = 1 and at i β‰₯ 2: fi = fi - 1 + fi - 2. 3. For a group of three numbers li ri di you should increase value ax by di for all x (li ≀ x ≀ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem. Input The first line contains two integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≀ ti ≀ 3) β€” the operation type: * if ti = 1, then next follow two integers xi vi (1 ≀ xi ≀ n, 0 ≀ vi ≀ 105); * if ti = 2, then next follow two integers li ri (1 ≀ li ≀ ri ≀ n); * if ti = 3, then next follow three integers li ri di (1 ≀ li ≀ ri ≀ n, 0 ≀ di ≀ 105). The input limits for scoring 30 points are (subproblem E1): * It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type. The input limits for scoring 70 points are (subproblems E1+E2): * It is guaranteed that there will be queries of the 1-st and 2-nd type only. The input limits for scoring 100 points are (subproblems E1+E2+E3): * No extra limitations. Output For each query print the calculated sum modulo 1000000000 (109). Examples Input 5 5 1 3 1 2 4 2 1 4 2 1 5 2 2 4 1 3 10 2 1 5 Output 12 32 8 50 Input 5 4 1 3 1 2 4 3 1 4 1 2 2 4 1 2 10 2 1 5 Output 12 45 Tags: brute force, data structures Correct Solution: ``` n, m = map(int, input().split()) a = list(map(int, input().split())) for i in range(m): t, l, r = map(int, input().split()) if t == 1: a[l-1] = r else: s = 0 fiba = fibb = 1 for i in range(l-1, r): s += fiba * a[i] fiba, fibb = fibb, fiba + fibb print(s % 1000000000) ```
12,772
Provide tags and a correct Python 3 solution for this coding contest problem. By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher: You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: 1. For given numbers xi and vi assign value vi to element axi. 2. For given numbers li and ri you've got to calculate sum <image>, where f0 = f1 = 1 and at i β‰₯ 2: fi = fi - 1 + fi - 2. 3. For a group of three numbers li ri di you should increase value ax by di for all x (li ≀ x ≀ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem. Input The first line contains two integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≀ ti ≀ 3) β€” the operation type: * if ti = 1, then next follow two integers xi vi (1 ≀ xi ≀ n, 0 ≀ vi ≀ 105); * if ti = 2, then next follow two integers li ri (1 ≀ li ≀ ri ≀ n); * if ti = 3, then next follow three integers li ri di (1 ≀ li ≀ ri ≀ n, 0 ≀ di ≀ 105). The input limits for scoring 30 points are (subproblem E1): * It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type. The input limits for scoring 70 points are (subproblems E1+E2): * It is guaranteed that there will be queries of the 1-st and 2-nd type only. The input limits for scoring 100 points are (subproblems E1+E2+E3): * No extra limitations. Output For each query print the calculated sum modulo 1000000000 (109). Examples Input 5 5 1 3 1 2 4 2 1 4 2 1 5 2 2 4 1 3 10 2 1 5 Output 12 32 8 50 Input 5 4 1 3 1 2 4 3 1 4 1 2 2 4 1 2 10 2 1 5 Output 12 45 Tags: brute force, data structures Correct Solution: ``` mod = 10**9 FibArray = [1,1] def fibonacci(n): if n<=len(FibArray): return FibArray[n-1] else: temp_fib = fibonacci(n-1)+fibonacci(n-2) FibArray.append(temp_fib) return temp_fib n, m = map(int, input().split()) a = list(map(int, input().split())) for _ in range(m): query = list(map(int, input().split())) if query[0]==1: a[query[1]-1] = query[2] elif query[0]==3: d = query[3] for i in range(query[1]-1, query[2]): a[i]+=d else: l, r = query[1], query[2] s = 0 for x in range(r-l+1): # print(fibonacci(x+1), a[l+x-1]) s+=((fibonacci(x+1)*a[l+x-1])) print(s%mod) ```
12,773
Provide tags and a correct Python 3 solution for this coding contest problem. By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher: You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: 1. For given numbers xi and vi assign value vi to element axi. 2. For given numbers li and ri you've got to calculate sum <image>, where f0 = f1 = 1 and at i β‰₯ 2: fi = fi - 1 + fi - 2. 3. For a group of three numbers li ri di you should increase value ax by di for all x (li ≀ x ≀ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem. Input The first line contains two integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≀ ti ≀ 3) β€” the operation type: * if ti = 1, then next follow two integers xi vi (1 ≀ xi ≀ n, 0 ≀ vi ≀ 105); * if ti = 2, then next follow two integers li ri (1 ≀ li ≀ ri ≀ n); * if ti = 3, then next follow three integers li ri di (1 ≀ li ≀ ri ≀ n, 0 ≀ di ≀ 105). The input limits for scoring 30 points are (subproblem E1): * It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type. The input limits for scoring 70 points are (subproblems E1+E2): * It is guaranteed that there will be queries of the 1-st and 2-nd type only. The input limits for scoring 100 points are (subproblems E1+E2+E3): * No extra limitations. Output For each query print the calculated sum modulo 1000000000 (109). Examples Input 5 5 1 3 1 2 4 2 1 4 2 1 5 2 2 4 1 3 10 2 1 5 Output 12 32 8 50 Input 5 4 1 3 1 2 4 3 1 4 1 2 2 4 1 2 10 2 1 5 Output 12 45 Tags: brute force, data structures Correct Solution: ``` import sys f = [-1] * 200000 def fib(n): if f[n] == -1: k = n//2 while k > 0 and f[k] == -1: k = k/2 for i in range(k, n): f[i+1] = f[i] + f[i-1]; return f[n] def solve(numbers, t, l, r, d): if t == 1: numbers[l-1] = r elif t == 2: total = 0 for j in range(l-1, r): total = (total + numbers[j] * fib(j-l+1)) % (10**9) print(total) else: for j in range(l-1, r): numbers[j] = numbers[j] + d n, m = sys.stdin.readline().rstrip().split() n = int(n) m = int(m) numbers = list(map(lambda x: int (x), sys.stdin.readline().rstrip().split())) f[0] = f[1] = 1 for i in range(m): line = sys.stdin.readline().rstrip().split() t = int(line[0]) d = 0 if t == 1: l = int(line[1]) r = int(line[2]) elif t == 2: l = int(line[1]) r = int(line[2]) else: l = int(line[1]) r = int(line[2]) d = int(line[3]) solve(numbers, t, l, r, d) ```
12,774
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher: You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: 1. For given numbers xi and vi assign value vi to element axi. 2. For given numbers li and ri you've got to calculate sum <image>, where f0 = f1 = 1 and at i β‰₯ 2: fi = fi - 1 + fi - 2. 3. For a group of three numbers li ri di you should increase value ax by di for all x (li ≀ x ≀ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem. Input The first line contains two integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≀ ti ≀ 3) β€” the operation type: * if ti = 1, then next follow two integers xi vi (1 ≀ xi ≀ n, 0 ≀ vi ≀ 105); * if ti = 2, then next follow two integers li ri (1 ≀ li ≀ ri ≀ n); * if ti = 3, then next follow three integers li ri di (1 ≀ li ≀ ri ≀ n, 0 ≀ di ≀ 105). The input limits for scoring 30 points are (subproblem E1): * It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type. The input limits for scoring 70 points are (subproblems E1+E2): * It is guaranteed that there will be queries of the 1-st and 2-nd type only. The input limits for scoring 100 points are (subproblems E1+E2+E3): * No extra limitations. Output For each query print the calculated sum modulo 1000000000 (109). Examples Input 5 5 1 3 1 2 4 2 1 4 2 1 5 2 2 4 1 3 10 2 1 5 Output 12 32 8 50 Input 5 4 1 3 1 2 4 3 1 4 1 2 2 4 1 2 10 2 1 5 Output 12 45 Submitted Solution: ``` n,m = map(int,input().split()) a = list(map(int,input().split())) f = [1,1] for i in range(2,n+1): f.append(f[i-1] + f[i-2]) f[i] %= 10 ** 9 for q in range(m): z,l,r = map(int,input().split()) if z == 1: a[l-1] = r else: s = 0 for j in range(l-1,r): s += (a[j] * f[j-l+1]) s %= 10 ** 9 print(s) ``` Yes
12,775
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher: You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: 1. For given numbers xi and vi assign value vi to element axi. 2. For given numbers li and ri you've got to calculate sum <image>, where f0 = f1 = 1 and at i β‰₯ 2: fi = fi - 1 + fi - 2. 3. For a group of three numbers li ri di you should increase value ax by di for all x (li ≀ x ≀ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem. Input The first line contains two integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≀ ti ≀ 3) β€” the operation type: * if ti = 1, then next follow two integers xi vi (1 ≀ xi ≀ n, 0 ≀ vi ≀ 105); * if ti = 2, then next follow two integers li ri (1 ≀ li ≀ ri ≀ n); * if ti = 3, then next follow three integers li ri di (1 ≀ li ≀ ri ≀ n, 0 ≀ di ≀ 105). The input limits for scoring 30 points are (subproblem E1): * It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type. The input limits for scoring 70 points are (subproblems E1+E2): * It is guaranteed that there will be queries of the 1-st and 2-nd type only. The input limits for scoring 100 points are (subproblems E1+E2+E3): * No extra limitations. Output For each query print the calculated sum modulo 1000000000 (109). Examples Input 5 5 1 3 1 2 4 2 1 4 2 1 5 2 2 4 1 3 10 2 1 5 Output 12 32 8 50 Input 5 4 1 3 1 2 4 3 1 4 1 2 2 4 1 2 10 2 1 5 Output 12 45 Submitted Solution: ``` n,m = map(int,input().split()) a = list(map(int,input().split())) f = [1,1] for i in range(2,n+1): f.append(f[i-1] + f[i-2]) for q in range(m): z,l,r = map(int,input().split()) if z == 1: a[l-1] = r else: s = 0 for j in range(l-1,r): s += (a[j] * f[j-l+1]) print(s) ``` No
12,776
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher: You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: 1. For given numbers xi and vi assign value vi to element axi. 2. For given numbers li and ri you've got to calculate sum <image>, where f0 = f1 = 1 and at i β‰₯ 2: fi = fi - 1 + fi - 2. 3. For a group of three numbers li ri di you should increase value ax by di for all x (li ≀ x ≀ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem. Input The first line contains two integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≀ ti ≀ 3) β€” the operation type: * if ti = 1, then next follow two integers xi vi (1 ≀ xi ≀ n, 0 ≀ vi ≀ 105); * if ti = 2, then next follow two integers li ri (1 ≀ li ≀ ri ≀ n); * if ti = 3, then next follow three integers li ri di (1 ≀ li ≀ ri ≀ n, 0 ≀ di ≀ 105). The input limits for scoring 30 points are (subproblem E1): * It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type. The input limits for scoring 70 points are (subproblems E1+E2): * It is guaranteed that there will be queries of the 1-st and 2-nd type only. The input limits for scoring 100 points are (subproblems E1+E2+E3): * No extra limitations. Output For each query print the calculated sum modulo 1000000000 (109). Examples Input 5 5 1 3 1 2 4 2 1 4 2 1 5 2 2 4 1 3 10 2 1 5 Output 12 32 8 50 Input 5 4 1 3 1 2 4 3 1 4 1 2 2 4 1 2 10 2 1 5 Output 12 45 Submitted Solution: ``` m,n = map(int, input().split()) a = list(map(int, input().split())) f = [1]*n for i in range(2,n): f[i] = f[i-1]+f[i-2] for i in range(n): t,l,r = map(int, input().split()) if t==1: a[l-1] = r else: sum_lr = 0 for x in range(r-l+1): sum_lr += f[x] * a[l+x-1] print(sum_lr) ``` No
12,777
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher: You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: 1. For given numbers xi and vi assign value vi to element axi. 2. For given numbers li and ri you've got to calculate sum <image>, where f0 = f1 = 1 and at i β‰₯ 2: fi = fi - 1 + fi - 2. 3. For a group of three numbers li ri di you should increase value ax by di for all x (li ≀ x ≀ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem. Input The first line contains two integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≀ ti ≀ 3) β€” the operation type: * if ti = 1, then next follow two integers xi vi (1 ≀ xi ≀ n, 0 ≀ vi ≀ 105); * if ti = 2, then next follow two integers li ri (1 ≀ li ≀ ri ≀ n); * if ti = 3, then next follow three integers li ri di (1 ≀ li ≀ ri ≀ n, 0 ≀ di ≀ 105). The input limits for scoring 30 points are (subproblem E1): * It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type. The input limits for scoring 70 points are (subproblems E1+E2): * It is guaranteed that there will be queries of the 1-st and 2-nd type only. The input limits for scoring 100 points are (subproblems E1+E2+E3): * No extra limitations. Output For each query print the calculated sum modulo 1000000000 (109). Examples Input 5 5 1 3 1 2 4 2 1 4 2 1 5 2 2 4 1 3 10 2 1 5 Output 12 32 8 50 Input 5 4 1 3 1 2 4 3 1 4 1 2 2 4 1 2 10 2 1 5 Output 12 45 Submitted Solution: ``` import sys f = [-1] * 200000 def fib(n): if f[n] == -1: k = n//2 while k > 0 and f[k] == -1: k = k/2 for i in range(k, n): f[i+1] = f[i] + f[i-1]; return f[n] def solve(numbers, t, l, r, d): if t == 1: numbers[l-1] = r elif t == 2: total = 0 for j in range(l-1, r): total = total + numbers[j] * fib(j) print(total) else: for j in range(l-1, r): numbers[j] = numbers[j] + d n, m = sys.stdin.readline().rstrip().split() n = int(n) m = int(m) numbers = list(map(lambda x: int (x), sys.stdin.readline().rstrip().split())) f[0] = f[1] = 1 for i in range(m): line = sys.stdin.readline().rstrip().split() t = int(line[0]) d = 0 if t == 1: l = int(line[1]) r = int(line[2]) elif t == 2: l = int(line[1]) r = int(line[2]) else: l = int(line[1]) r = int(line[2]) d = int(line[3]) solve(numbers, t, l, r, d) ``` No
12,778
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher: You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: 1. For given numbers xi and vi assign value vi to element axi. 2. For given numbers li and ri you've got to calculate sum <image>, where f0 = f1 = 1 and at i β‰₯ 2: fi = fi - 1 + fi - 2. 3. For a group of three numbers li ri di you should increase value ax by di for all x (li ≀ x ≀ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem. Input The first line contains two integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≀ ti ≀ 3) β€” the operation type: * if ti = 1, then next follow two integers xi vi (1 ≀ xi ≀ n, 0 ≀ vi ≀ 105); * if ti = 2, then next follow two integers li ri (1 ≀ li ≀ ri ≀ n); * if ti = 3, then next follow three integers li ri di (1 ≀ li ≀ ri ≀ n, 0 ≀ di ≀ 105). The input limits for scoring 30 points are (subproblem E1): * It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type. The input limits for scoring 70 points are (subproblems E1+E2): * It is guaranteed that there will be queries of the 1-st and 2-nd type only. The input limits for scoring 100 points are (subproblems E1+E2+E3): * No extra limitations. Output For each query print the calculated sum modulo 1000000000 (109). Examples Input 5 5 1 3 1 2 4 2 1 4 2 1 5 2 2 4 1 3 10 2 1 5 Output 12 32 8 50 Input 5 4 1 3 1 2 4 3 1 4 1 2 2 4 1 2 10 2 1 5 Output 12 45 Submitted Solution: ``` n,m = map(int, input().split()) a = list(map(int, input().split())) f = [1]*n for i in range(2,n): f[i] = f[i-1]+f[i-2] for i in range(n): t,l,r = map(int, input().split()) if t==1: a[l-1] = r else: sum_lr = 0 for x in range(r-l+1): sum_lr += f[x] * a[l+x-1] print(sum_lr%1000000000) ``` No
12,779
Provide tags and a correct Python 3 solution for this coding contest problem. Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings. Input The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≀ n ≀ 500) β€” amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≀ Wi ≀ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi. Output If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any. Examples Input uayd uxxd 3 a x 8 x y 13 d c 3 Output 21 uxyd Input a b 3 a b 2 a b 3 b a 5 Output 2 b Input abc ab 6 a b 4 a b 7 b a 8 c b 11 c a 3 a c 0 Output -1 Tags: shortest paths Correct Solution: ``` import sys, string import itertools s, t = input().strip(), input().strip() if len(s) != len(t): print(-1) sys.exit() vertices = string.ascii_lowercase g = { c: { c: 0 } for c in vertices } n = int(input()) for i in range(n): u, v, cost = input().split() cost = int(cost) if v not in g[u] or g[u][v] > cost: g[u][v] = cost for p in vertices: for u in vertices: if p not in g[u]: continue for v in vertices: if v not in g[p]: continue if v not in g[u] or g[u][v] > g[u][p] + g[p][v]: g[u][v] = g[u][p] + g[p][v] best_costs = { c: { c: 0 } for c in vertices } best_chars = { c: { c: c } for c in vertices } for a, b in itertools.product(vertices, vertices): if a == b: continue best_cost = None best_char = None for c in vertices: if c in g[a] and c in g[b]: if best_cost == None or best_cost > g[a][c] + g[b][c]: best_cost = g[a][c] + g[b][c] best_char = c if b in g[a] and (best_cost == None or best_cost > g[a][b]): best_cost = g[a][b] best_char = b if a in g[b] and (best_cost == None or best_cost > g[b][a]): best_cost = g[b][a] best_char = a if best_cost == None: continue best_costs[a][b] = best_cost best_chars[a][b] = best_char total_cost = 0 chars = [] for a, b in zip(s, t): if b not in best_costs[a]: print(-1) sys.exit() total_cost += best_costs[a][b] chars.append(best_chars[a][b]) print(total_cost) print(''.join(chars)) ```
12,780
Provide tags and a correct Python 3 solution for this coding contest problem. Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings. Input The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≀ n ≀ 500) β€” amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≀ Wi ≀ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi. Output If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any. Examples Input uayd uxxd 3 a x 8 x y 13 d c 3 Output 21 uxyd Input a b 3 a b 2 a b 3 b a 5 Output 2 b Input abc ab 6 a b 4 a b 7 b a 8 c b 11 c a 3 a c 0 Output -1 Tags: shortest paths Correct Solution: ``` import sys large = 10000000 def solve(): s = input() t = input() if len(s) != len(t): print(-1) return n = int(input()) mem = [[large] * 26 for _ in range(26)] for i in range(26): mem[i][i] = 0 for i in range(n): chra, chrb, strcost = input().split() a = ord(chra) - ord('a') b = ord(chrb) - ord('a') cost = int(strcost) mem[a][b] = min(mem[a][b], cost) for start in range(26): for end in range(26): mem[start][end] = min(mem[start][end], mem[start][a] + mem[a][b] + mem[b][end]) cost = 0 res = [None] * len(s) for i in range(len(s)): mid = -1 midcost = large a = ord(s[i]) - ord('a') b = ord(t[i]) - ord('a') for j in range(26): if mem[a][j] != -1 and mem[b][j] != -1: thiscost = mem[a][j] + mem[b][j] if thiscost < midcost: midcost = thiscost mid = j res[i] = chr(ord('a') + mid) cost += midcost if cost >= large: print(-1) return print(cost) print(''.join(map(str, res))) if sys.hexversion == 50594544 : sys.stdin = open("test.txt") solve() ```
12,781
Provide tags and a correct Python 3 solution for this coding contest problem. Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings. Input The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≀ n ≀ 500) β€” amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≀ Wi ≀ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi. Output If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any. Examples Input uayd uxxd 3 a x 8 x y 13 d c 3 Output 21 uxyd Input a b 3 a b 2 a b 3 b a 5 Output 2 b Input abc ab 6 a b 4 a b 7 b a 8 c b 11 c a 3 a c 0 Output -1 Tags: shortest paths Correct Solution: ``` # http://codeforces.com/problemset/problem/33/B # 33b: String Problem. #input = raw_input def build_graph(a): w = [[float('inf') for col in range(26)] for row in range(26)] for i in range(26): w[i][i] = 0 for b in a: if w[ord(b[0]) - 97][ord(b[1]) - 97] > b[2]: w[ord(b[0]) - 97][ord(b[1]) - 97] = b[2] for k in range(26): for i in range(26): for j in range(26): if w[i][j] > w[i][k] + w[k][j]: w[i][j] = w[i][k] + w[k][j] return w def test_build_graph(): a = [['a', 'b', 2], ['a', 'c', 6], ['b', 'm', 5], ['c', 'm', 3]] m = build_graph(a) print(m) print(m[ord('a') - 97][ord('m') - 97]) print(m[ord('a') - 97][ord('b') - 97]) def transfer(s, t, a): if len(s) != len(t): return -1 r = '' z = 0 w = build_graph(a) for d, p in zip(s, t): if d == p: r += d else: c = float('inf') q = '' i = ord(d) - 97 j = ord(p) - 97 for k in range(26): v = w[i][k] + w[j][k] if c > v: c = v q = chr(k + 97) if c == float('inf'): return -1 z += c r += q r = str(z) + '\n' + r return r def test_transfer(): s = 'uayd' t = 'uxxd' a = [['a', 'x', 8], ['x', 'y', 13], ['d', 'c', 3]] assert transfer(s, t, a) == '21\nuxyd' s1 = 'a' t1 = 'b' a1 = [['a', 'b', 2], ['a', 'b', 3], ['b', 'a', 5]] assert transfer(s1, t1, a1) == '2\nb' s2 = 'abc' t2 = 'ab' a2 = [['a', 'b', 4], ['a', 'b', 7], ['b', 'a', 8], ['c', 'b', 11], ['c', 'a', 3], ['a', 'c', 0]] assert transfer(s2, t2, a2) == -1 s3 = 'abcd' t3 = 'acer' a3 = [['b', 'c', 100], ['c', 'b', 10], ['c', 'x', 1], ['e', 'x', 3], ['c', 'e', 7], ['r', 'd', 11]] assert transfer(s3, t3, a3) == '25\nabxd' def fun(): s = input() t = input() n = int(input()) a = [] for c in range(n): x, y, z = map(str, input().split()) a.append([x, y, int(z)]) print(transfer(s, t, a)) #test_build_graph() #test_transfer() fun() ```
12,782
Provide tags and a correct Python 3 solution for this coding contest problem. Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings. Input The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≀ n ≀ 500) β€” amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≀ Wi ≀ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi. Output If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any. Examples Input uayd uxxd 3 a x 8 x y 13 d c 3 Output 21 uxyd Input a b 3 a b 2 a b 3 b a 5 Output 2 b Input abc ab 6 a b 4 a b 7 b a 8 c b 11 c a 3 a c 0 Output -1 Tags: shortest paths Correct Solution: ``` import os import sys from math import * from collections import * # from fractions import * # from heapq import* from bisect import * from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ALPHA='abcdefghijklmnopqrstuvwxyz/' M=1000000007 EPS=1e-6 def Ceil(a,b): return a//b+int(a%b>0) def value():return tuple(map(int,input().split())) def array():return [int(i) for i in input().split()] def Int():return int(input()) def Str():return input() def arrayS():return [i for i in input().split()] #-------------------------code---------------------------# s=list(input()) t=list(input()) n=int(input()) dic={} adj=[[] for x in range(26)] for x in range(n): aa,bb,cost=input().split(" ") cost=int(cost) a=ord(aa)-ord('a') b=ord(bb)-ord('a') chk=False for y in range(len(adj[a])): if adj[a][y][0]==b: adj[a][y][1]=min(cost,adj[a][y][1]) chk=True if chk==False: adj[a].append([b,cost]) ans=[] vis=[False for x in range(26)] def dfs(x,start,cnt): temp=chr(start+97)+chr(x+97) if temp in dic.keys() and cnt>=dic[temp]: return else: vis[x]=True temp=chr(start+97)+chr(x+97) if temp in dic.keys(): dic[temp]=min(dic[temp],cnt) else: dic[temp]=cnt for z in adj[x]: dfs(z[0],start,cnt+z[1]) for x in range(26): adj[x].sort(key=lambda x:x[1]) for x in range(26): dfs(x,x,0) for x in range(ord('a'),ord('z')+1): temp=chr(x)+chr(x) if temp in dic.keys(): dic[temp]=0 else: dic[temp]=0 chk=1 spend=0 if len(s)!=len(t): print(-1) else: for x in range(len(s)): if s[x]==t[x]: ans.append(s[x]) else: notfound=True spendhere=int(1e100) thechar='a' for y in range(ord('a'),ord('z')+1): temp=s[x]+chr(y) retemp=t[x]+chr(y) if temp in dic.keys() and retemp in dic.keys(): notfound=False if spendhere>dic[temp]+dic[retemp]: thechar=chr(y) spendhere=dic[temp]+dic[retemp] if notfound: chk=0 break else: ans.append(thechar) spend+=spendhere if chk==0: print(-1) else: print(spend) print(*ans,sep="") ```
12,783
Provide tags and a correct Python 3 solution for this coding contest problem. Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings. Input The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≀ n ≀ 500) β€” amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≀ Wi ≀ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi. Output If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any. Examples Input uayd uxxd 3 a x 8 x y 13 d c 3 Output 21 uxyd Input a b 3 a b 2 a b 3 b a 5 Output 2 b Input abc ab 6 a b 4 a b 7 b a 8 c b 11 c a 3 a c 0 Output -1 Tags: shortest paths Correct Solution: ``` s = input() t = input() if(len(s) != len(t)): print(-1) exit() dist = [[10**15 for j in range(26)] for i in range(26)] for i in range(26): dist[i][i] = 0 n = int(input()) for i in range(n): a = input().split() x = ord(a[0]) - 97 y = ord(a[1]) - 97 w = int(a[-1]) dist[x][y] = min(dist[x][y], w) for k in range(26): for i in range(26): for j in range(26): dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) ans = '' res = 0 n = len(s) for i in range(n): if(s[i] == t[i]): ans += s[i] continue cost = 10**15 pos = -1 x = ord(s[i]) - 97 y = ord(t[i]) - 97 for j in range(26): if(dist[x][j] + dist[y][j] < cost): cost = dist[x][j] + dist[y][j] pos = j if(pos == -1): print(-1) exit() res += cost ans += chr(pos + 97) print(res) print(ans) ```
12,784
Provide tags and a correct Python 3 solution for this coding contest problem. Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings. Input The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≀ n ≀ 500) β€” amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≀ Wi ≀ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi. Output If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any. Examples Input uayd uxxd 3 a x 8 x y 13 d c 3 Output 21 uxyd Input a b 3 a b 2 a b 3 b a 5 Output 2 b Input abc ab 6 a b 4 a b 7 b a 8 c b 11 c a 3 a c 0 Output -1 Tags: shortest paths Correct Solution: ``` def code(c): return ord(c) - ord('a') def main(): a = input() b = input() m = int(input()) n = 26 d = [[10 ** 9 for i in range(n)] for j in range(n)] for i in range(n): d[i][i] = 0 for i in range(m): s, t, w = input().split() w = int(w) s = code(s) t = code(t) d[s][t] = min(d[s][t], w) for k in range(n): for i in range(n): for j in range(n): d[i][j] = min(d[i][j], d[i][k] + d[k][j]) if len(a) != len(b): print(-1) else: ans = 0 res = [] for i in range(len(a)): x = code(a[i]) y = code(b[i]) min_c = 'a' min_cost = 10 ** 9 for j in range(n): cur = d[x][j] + d[y][j] if cur < min_cost: min_cost = cur min_c = chr(j + ord('a')) res.append(min_c) ans += min_cost if ans >= 10 ** 9: print(-1) else: print(ans) for j in res: print(j, end='') print() main() ```
12,785
Provide tags and a correct Python 3 solution for this coding contest problem. Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings. Input The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≀ n ≀ 500) β€” amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≀ Wi ≀ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi. Output If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any. Examples Input uayd uxxd 3 a x 8 x y 13 d c 3 Output 21 uxyd Input a b 3 a b 2 a b 3 b a 5 Output 2 b Input abc ab 6 a b 4 a b 7 b a 8 c b 11 c a 3 a c 0 Output -1 Tags: shortest paths Correct Solution: ``` # http://codeforces.com/problemset/problem/33/B # 33b: String Problem. #input = raw_input def calc_path(a): ''' this function uses floyd-warshall alg to compute all pairs shortest path weight among alphabet characters. input: a: a 2d list which gives the weighted edge data. e.g., a = [['a', 'x', 42]]: only one edge, ('a', 'x'), with weight 42. result: all pairs shortest path weight matrix, a 26-length 2d list. w[i][i] == 0; for i != j, w[i][j] == infinite indicates there's no path between i and j. ''' w = [[float('inf') for col in range(26)] for row in range(26)] for i in range(26): w[i][i] = 0 for b in a: if w[ord(b[0]) - 97][ord(b[1]) - 97] > b[2]: w[ord(b[0]) - 97][ord(b[1]) - 97] = b[2] for k in range(26): for i in range(26): for j in range(26): if w[i][j] > w[i][k] + w[k][j]: w[i][j] = w[i][k] + w[k][j] return w def test_calc_path(): a = [['a', 'b', 2], ['a', 'c', 6], ['b', 'm', 5], ['c', 'm', 3]] m = calc_path(a) print(m) print(m[ord('a') - 97][ord('m') - 97]) print(m[ord('a') - 97][ord('b') - 97]) def transfer(s, t, a): ''' this function firstly invokes calc_path to compute all pairs shortest path among alphabet characters, and then computes the minimum transformation position by position of s and t. finally, a minimal transformation weight and outcome is returned. input: s, t: the input string to be transformed. a: the character transformation cost list, 2d. e.g., a = [['a', 'x', 42], ['u', 'v', 8]]: a => x costs 42; u => v costs 8. result: -1 if transformation is not possible; otherwise, the minimal transformation cost and result, e.g. '12\nabc'. ''' if len(s) != len(t): return -1 r = '' z = 0 w = calc_path(a) for d, p in zip(s, t): if d == p: r += d else: c = float('inf') q = '' i = ord(d) - 97 j = ord(p) - 97 for k in range(26): v = w[i][k] + w[j][k] if c > v: c = v q = chr(k + 97) if c == float('inf'): return -1 z += c r += q r = str(z) + '\n' + r return r def test_transfer(): s = 'uayd' t = 'uxxd' a = [['a', 'x', 8], ['x', 'y', 13], ['d', 'c', 3]] assert transfer(s, t, a) == '21\nuxyd' s1 = 'a' t1 = 'b' a1 = [['a', 'b', 2], ['a', 'b', 3], ['b', 'a', 5]] assert transfer(s1, t1, a1) == '2\nb' s2 = 'abc' t2 = 'ab' a2 = [['a', 'b', 4], ['a', 'b', 7], ['b', 'a', 8], ['c', 'b', 11], ['c', 'a', 3], ['a', 'c', 0]] assert transfer(s2, t2, a2) == -1 s3 = 'abcd' t3 = 'acer' a3 = [['b', 'c', 100], ['c', 'b', 10], ['c', 'x', 1], ['e', 'x', 3], ['c', 'e', 7], ['r', 'd', 11]] assert transfer(s3, t3, a3) == '25\nabxd' def fun(): s = input() t = input() n = int(input()) a = [] for c in range(n): x, y, z = map(str, input().split()) a.append([x, y, int(z)]) print(transfer(s, t, a)) #test_calc_path() #test_transfer() fun() ```
12,786
Provide tags and a correct Python 3 solution for this coding contest problem. Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings. Input The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≀ n ≀ 500) β€” amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≀ Wi ≀ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi. Output If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any. Examples Input uayd uxxd 3 a x 8 x y 13 d c 3 Output 21 uxyd Input a b 3 a b 2 a b 3 b a 5 Output 2 b Input abc ab 6 a b 4 a b 7 b a 8 c b 11 c a 3 a c 0 Output -1 Tags: shortest paths Correct Solution: ``` # http://codeforces.com/problemset/problem/33/B # 33b: String Problem. # 豑道, montreal, quebec, canada. #input = raw_input def calc_path(a): ''' this function uses floyd-warshall alg to compute all pairs shortest path weight among alphabet characters. input: a: a 2d list which gives the weighted edge data. e.g., a = [['a', 'x', 42]]: only one edge, ('a', 'x'), with weight 42. result: all pairs shortest path weight matrix, a 26-length 2d list. w[i][i] == 0; for i != j, w[i][j] == infinite indicates there's no path between i and j. ''' w = [[float('inf') for col in range(26)] for row in range(26)] for i in range(26): w[i][i] = 0 for b in a: if w[ord(b[0]) - 97][ord(b[1]) - 97] > b[2]: w[ord(b[0]) - 97][ord(b[1]) - 97] = b[2] for k in range(26): for i in range(26): for j in range(26): if w[i][j] > w[i][k] + w[k][j]: w[i][j] = w[i][k] + w[k][j] return w def test_calc_path(): a = [['a', 'b', 2], ['a', 'c', 6], ['b', 'm', 5], ['c', 'm', 3]] m = calc_path(a) print(m) print(m[ord('a') - 97][ord('m') - 97]) print(m[ord('a') - 97][ord('b') - 97]) def transfer(s, t, a): ''' this function firstly invokes calc_path to compute all pairs shortest path among alphabet characters, and then computes the minimum transformation position by position of s and t. finally, a minimal transformation weight and outcome is returned. input: s, t: the input string to be transformed. a: the character transformation cost list, 2d. e.g., a = [['a', 'x', 42], ['u', 'v', 8]]: a => x costs 42; u => v costs 8. result: -1 if transformation is not possible; otherwise, the minimal transformation cost and result, e.g. '12\nabc'. ''' if len(s) != len(t): return -1 r = '' z = 0 w = calc_path(a) for d, p in zip(s, t): if d == p: r += d else: c = float('inf') q = '' i = ord(d) - 97 j = ord(p) - 97 for k in range(26): v = w[i][k] + w[j][k] if c > v: c = v q = chr(k + 97) if c == float('inf'): return -1 z += c r += q r = str(z) + '\n' + r return r def test_transfer(): s = 'uayd' t = 'uxxd' a = [['a', 'x', 8], ['x', 'y', 13], ['d', 'c', 3]] assert transfer(s, t, a) == '21\nuxyd' s1 = 'a' t1 = 'b' a1 = [['a', 'b', 2], ['a', 'b', 3], ['b', 'a', 5]] assert transfer(s1, t1, a1) == '2\nb' s2 = 'abc' t2 = 'ab' a2 = [['a', 'b', 4], ['a', 'b', 7], ['b', 'a', 8], ['c', 'b', 11], ['c', 'a', 3], ['a', 'c', 0]] assert transfer(s2, t2, a2) == -1 s3 = 'abcd' t3 = 'acer' a3 = [['b', 'c', 100], ['c', 'b', 10], ['c', 'x', 1], ['e', 'x', 3], ['c', 'e', 7], ['r', 'd', 11]] assert transfer(s3, t3, a3) == '25\nabxd' def fun(): s = input() t = input() n = int(input()) a = [] for c in range(n): x, y, z = map(str, input().split()) a.append([x, y, int(z)]) print(transfer(s, t, a)) #test_calc_path() #test_transfer() fun() ```
12,787
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings. Input The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≀ n ≀ 500) β€” amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≀ Wi ≀ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi. Output If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any. Examples Input uayd uxxd 3 a x 8 x y 13 d c 3 Output 21 uxyd Input a b 3 a b 2 a b 3 b a 5 Output 2 b Input abc ab 6 a b 4 a b 7 b a 8 c b 11 c a 3 a c 0 Output -1 Submitted Solution: ``` import os import sys from math import * from collections import * # from fractions import * # from heapq import* from bisect import * from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ALPHA='abcdefghijklmnopqrstuvwxyz/' M=1000000007 EPS=1e-6 def Ceil(a,b): return a//b+int(a%b>0) def value():return tuple(map(int,input().split())) def array():return [int(i) for i in input().split()] def Int():return int(input()) def Str():return input() def arrayS():return [i for i in input().split()] #-------------------------code---------------------------# s=list(input()) t=list(input()) n=int(input()) dic={} adj=[[] for x in range(26)] for x in range(n): aa,bb,cost=input().split(" ") cost=int(cost) a=ord(aa)-ord('a') b=ord(bb)-ord('a') adj[a].append([b,cost]) adj[b].append([a,cost]) ans=[] vis=[False for x in range(26)] def dfs(x,start,cnt): if vis[x]: return else: vis[x]=True temp=chr(start+97)+chr(x+97) retemp=chr(x+97)+chr(start+97) if retemp in dic.keys(): dic[retemp]=min(dic[retemp],cnt) else: dic[retemp]=cnt if temp in dic.keys(): dic[temp]=min(dic[temp],cnt) else: dic[temp]=cnt for z in adj[x]: dfs(z[0],start,cnt+z[1]) for x in range(26): adj[x].sort(key=lambda x:x[1]) for x in range(26): dfs(x,x,0) vis=[False for x in range(26)] #print(dic) chk=1 spend=0 if len(s)!=len(t): print(-1) else: for x in range(len(s)): if s[x]==t[x]: ans.append(s[x]) else: notfound=True spendhere=int(1e100) thechar='a' for y in range(ord('a'),ord('z')+1): temp=s[x]+chr(y) retemp=t[x]+chr(y) if temp in dic.keys() and retemp in dic.keys(): notfound=False if spendhere>dic[temp]+dic[retemp]: thechar=chr(y) spendhere=dic[temp]+dic[retemp] if notfound: chk=0 break else: ans.append(thechar) spend+=spendhere if chk==0: print(-1) else: print(spend) print(*ans,sep="") ``` No
12,788
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings. Input The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≀ n ≀ 500) β€” amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≀ Wi ≀ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi. Output If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any. Examples Input uayd uxxd 3 a x 8 x y 13 d c 3 Output 21 uxyd Input a b 3 a b 2 a b 3 b a 5 Output 2 b Input abc ab 6 a b 4 a b 7 b a 8 c b 11 c a 3 a c 0 Output -1 Submitted Solution: ``` import os import sys from math import * from collections import * # from fractions import * # from heapq import* from bisect import * from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ALPHA='abcdefghijklmnopqrstuvwxyz/' M=1000000007 EPS=1e-6 def Ceil(a,b): return a//b+int(a%b>0) def value():return tuple(map(int,input().split())) def array():return [int(i) for i in input().split()] def Int():return int(input()) def Str():return input() def arrayS():return [i for i in input().split()] #-------------------------code---------------------------# s=list(input()) t=list(input()) n=int(input()) dic={} for x in range(n): a,b,cost=input().split(" ") temp=a+b cost=int(cost) if temp in dic.keys(): dic[temp]=min(dic[temp],cost) else: dic[temp]=cost ans=[] chk=1 spend=0 if len(s)!=len(t): print(-1) else: for x in range(len(s)): if s[x]==t[x]: ans.append(s[x]) else: temp=s[x]+t[x] retemp=t[x]+s[x] if temp not in dic.keys() and retemp not in dic.keys(): chk=0 break elif temp in dic.keys() and retemp not in dic.keys(): ans.append(t[x]) spend+=dic[temp] elif temp not in dic.keys() and retemp in dic.keys(): ans.append(s[x]) spend+=dic[retemp] else: if dic[temp]<=dic[retemp]: ans.append(t[x]) spend+=dic[temp] else: ans.append(s[x]) spend+=dic[retemp] if chk==0: print(-1) else: print(spend) print(*ans,sep="") ``` No
12,789
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings. Input The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≀ n ≀ 500) β€” amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≀ Wi ≀ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi. Output If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any. Examples Input uayd uxxd 3 a x 8 x y 13 d c 3 Output 21 uxyd Input a b 3 a b 2 a b 3 b a 5 Output 2 b Input abc ab 6 a b 4 a b 7 b a 8 c b 11 c a 3 a c 0 Output -1 Submitted Solution: ``` #import io, os #input = io.StringIO(os.read(0, os.fstat(0).st_size).decode()).readline s1 = [ord(x) - ord('a') for x in input()] s2 = [ord(x) - ord('a') for x in input()] MX = 10 ** 9 d = [[MX] * 26 for _ in range(26)] for x in range(int(input())): a, b, c = input().split() c = int(c) a = ord(a) - ord('a') b = ord(b) - ord('a') d[a][b] = min(c, d[a][b]) for i in range(26): d[i][i] = 0 for k in range(26): for i in range(26): for j in range(26): d[i][j] = min(d[i][j], d[i][k] + d[k][j]) if len(s1) != len(s2): print(-1) exit(0) #print(*d, sep = '\n') ans = '' cans = 0 d1 = {} for i in range(len(s1)): mn = 10 ** 9 + 1 b = '' if (s1[i], s2[i]) not in d1: for j in range(26): if d[s1[i]][j] + d[s2[i]][j] < mn: mn = d[s1[i]][j] + d[s2[i]][j] b = chr(j + ord('a')) d1[(s1[i], s2[i])] = (mn, b) x = d1[(s1[i], s2[i])] if x[1]: cans += x[0] ans += x[1] else: print(-1) exit(0) print(cans) print(ans) ``` No
12,790
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings. Input The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≀ n ≀ 500) β€” amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≀ Wi ≀ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi. Output If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any. Examples Input uayd uxxd 3 a x 8 x y 13 d c 3 Output 21 uxyd Input a b 3 a b 2 a b 3 b a 5 Output 2 b Input abc ab 6 a b 4 a b 7 b a 8 c b 11 c a 3 a c 0 Output -1 Submitted Solution: ``` import sys s = input() t = input() if (len(s)!=len(t)): print(-1) exit() dist = [[sys.maxsize for j in range(26)] for i in range(26)] for i in range(26): dist[i][i]=0 n = int(input()) for i in range(n): a = input().split() x = ord(a[0]) - ord('a') y = ord(a[1]) - ord('a') w = int(a[2]) dist[x][y] = min(dist[x][y],w) for k in range(26): for i in range(26): for j in range(26): dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) ans ='' res = 0 n = len(s) for i in range(n): if (s[i]==t[i]): ans+=s[i] continue cost=sys.maxsize pos=-1 x = ord(s[i]) - ord('a') y = ord(t[i]) - ord('a') for j in range(26): if (dist[x][j] + dist[j][y] < cost): cost = dist[x][j] + dist[j][y] pos = j if (pos == -1): print(-1) exit() res += cost ans += chr(pos + 97) print(res) print(ans) ``` No
12,791
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You must have heard all about the Foolland on your Geography lessons. Specifically, you must know that federal structure of this country has been the same for many centuries. The country consists of n cities, some pairs of cities are connected by bidirectional roads, each road is described by its length li. The fools lived in their land joyfully, but a recent revolution changed the king. Now the king is Vasily the Bear. Vasily divided the country cities into regions, so that any two cities of the same region have a path along the roads between them and any two cities of different regions don't have such path. Then Vasily decided to upgrade the road network and construct exactly p new roads in the country. Constructing a road goes like this: 1. We choose a pair of distinct cities u, v that will be connected by a new road (at that, it is possible that there already is a road between these cities). 2. We define the length of the new road: if cities u, v belong to distinct regions, then the length is calculated as min(109, S + 1) (S β€” the total length of all roads that exist in the linked regions), otherwise we assume that the length equals 1000. 3. We build a road of the specified length between the chosen cities. If the new road connects two distinct regions, after construction of the road these regions are combined into one new region. Vasily wants the road constructing process to result in the country that consists exactly of q regions. Your task is to come up with such road constructing plan for Vasily that it meets the requirement and minimizes the total length of the built roads. Input The first line contains four integers n (1 ≀ n ≀ 105), m (0 ≀ m ≀ 105), p (0 ≀ p ≀ 105), q (1 ≀ q ≀ n) β€” the number of cities in the Foolland, the number of existing roads, the number of roads that are planned to construct and the required number of regions. Next m lines describe the roads that exist by the moment upgrading of the roads begun. Each of these lines contains three integers xi, yi, li: xi, yi β€” the numbers of the cities connected by this road (1 ≀ xi, yi ≀ n, xi β‰  yi), li β€” length of the road (1 ≀ li ≀ 109). Note that one pair of cities can be connected with multiple roads. Output If constructing the roads in the required way is impossible, print a single string "NO" (without the quotes). Otherwise, in the first line print word "YES" (without the quotes), and in the next p lines print the road construction plan. Each line of the plan must consist of two distinct integers, giving the numbers of the cities connected by a road. The road must occur in the plan in the order they need to be constructed. If there are multiple optimal solutions, you can print any of them. Examples Input 9 6 2 2 1 2 2 3 2 1 4 6 20 1 3 8 7 8 3 5 7 2 Output YES 9 5 1 9 Input 2 0 1 2 Output NO Input 2 0 0 2 Output YES Note Consider the first sample. Before the reform the Foolland consists of four regions. The first region includes cities 1, 2, 3, the second region has cities 4 and 6, the third region has cities 5, 7, 8, the fourth region has city 9. The total length of the roads in these cities is 11, 20, 5 and 0, correspondingly. According to the plan, we first build the road of length 6 between cities 5 and 9, then the road of length 23 between cities 1 and 9. Thus, the total length of the built roads equals 29. Submitted Solution: ``` import queue as Q q = Q.PriorityQueue() q.put((10,'ten')) q.put((1,'one')) q.put((5,'five')) while not q.empty(): print(q.get()) ``` No
12,792
Provide tags and a correct Python 3 solution for this coding contest problem. Everyone loves a freebie. Especially students. It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β€” then flown freebie helps him to pass the upcoming exam. In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night. It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them. Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be. Input The first line of the input contains integer n (1 ≀ n ≀ 100), where n β€” the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 ≀ ti ≀ 1000). The last line contains integer T (1 ≀ T ≀ 1000) β€” the time interval during which the freebie was near the dormitory. Output Print a single integer β€” the largest number of people who will pass exam tomorrow because of the freebie visit. Examples Input 6 4 1 7 8 3 8 1 Output 3 Tags: binary search, brute force, implementation Correct Solution: ``` read = lambda: map(int, input().split()) n = int(input()) a = sorted(read()) T = int(input()) ans = 0 j = 0 for i in range(n): while j < n and a[j] - a[i] <= T: j += 1 ans = max(ans, j - i) print(ans) ```
12,793
Provide tags and a correct Python 3 solution for this coding contest problem. Everyone loves a freebie. Especially students. It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β€” then flown freebie helps him to pass the upcoming exam. In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night. It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them. Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be. Input The first line of the input contains integer n (1 ≀ n ≀ 100), where n β€” the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 ≀ ti ≀ 1000). The last line contains integer T (1 ≀ T ≀ 1000) β€” the time interval during which the freebie was near the dormitory. Output Print a single integer β€” the largest number of people who will pass exam tomorrow because of the freebie visit. Examples Input 6 4 1 7 8 3 8 1 Output 3 Tags: binary search, brute force, implementation Correct Solution: ``` n=int(input()) l=list(map(int,input().split())) t=int(input()) l.sort() mx=1 i=0 j=0 count=1 while j<n-1: count=1 i=j+1 while i<n: if l[i]-l[j]<=t: count+=1 i+=1 else: break if count>mx: mx=count j+=1 print(mx) ```
12,794
Provide tags and a correct Python 3 solution for this coding contest problem. Everyone loves a freebie. Especially students. It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β€” then flown freebie helps him to pass the upcoming exam. In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night. It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them. Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be. Input The first line of the input contains integer n (1 ≀ n ≀ 100), where n β€” the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 ≀ ti ≀ 1000). The last line contains integer T (1 ≀ T ≀ 1000) β€” the time interval during which the freebie was near the dormitory. Output Print a single integer β€” the largest number of people who will pass exam tomorrow because of the freebie visit. Examples Input 6 4 1 7 8 3 8 1 Output 3 Tags: binary search, brute force, implementation Correct Solution: ``` n = int(input()) lst = list(map(int,input().split())) t = int(input()) lst.sort() res=0 from bisect import bisect for i,x in enumerate(lst): j=bisect(lst,x+t) res=max(res,j-i) print(res) ```
12,795
Provide tags and a correct Python 3 solution for this coding contest problem. Everyone loves a freebie. Especially students. It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β€” then flown freebie helps him to pass the upcoming exam. In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night. It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them. Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be. Input The first line of the input contains integer n (1 ≀ n ≀ 100), where n β€” the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 ≀ ti ≀ 1000). The last line contains integer T (1 ≀ T ≀ 1000) β€” the time interval during which the freebie was near the dormitory. Output Print a single integer β€” the largest number of people who will pass exam tomorrow because of the freebie visit. Examples Input 6 4 1 7 8 3 8 1 Output 3 Tags: binary search, brute force, implementation Correct Solution: ``` def halyava(lst, t): count = 1 for i in range(len(lst)): for j in range(i + 1, len(lst)): if sorted(lst)[j] - sorted(lst)[i] <= t: count = max(j - i + 1, count) return count n = int(input()) b = [int(x) for x in input().split()] T = int(input()) print(halyava(b, T)) ```
12,796
Provide tags and a correct Python 3 solution for this coding contest problem. Everyone loves a freebie. Especially students. It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β€” then flown freebie helps him to pass the upcoming exam. In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night. It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them. Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be. Input The first line of the input contains integer n (1 ≀ n ≀ 100), where n β€” the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 ≀ ti ≀ 1000). The last line contains integer T (1 ≀ T ≀ 1000) β€” the time interval during which the freebie was near the dormitory. Output Print a single integer β€” the largest number of people who will pass exam tomorrow because of the freebie visit. Examples Input 6 4 1 7 8 3 8 1 Output 3 Tags: binary search, brute force, implementation Correct Solution: ``` n=int(input()) l=list(map(int,input().split())) t=int(input()) l.sort() a=[] i=0 j=0 while i<n: while j<n and l[j]-l[i]<=t: j+=1 a.append(j-i) i+=1 print(max(a)) ```
12,797
Provide tags and a correct Python 3 solution for this coding contest problem. Everyone loves a freebie. Especially students. It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β€” then flown freebie helps him to pass the upcoming exam. In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night. It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them. Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be. Input The first line of the input contains integer n (1 ≀ n ≀ 100), where n β€” the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 ≀ ti ≀ 1000). The last line contains integer T (1 ≀ T ≀ 1000) β€” the time interval during which the freebie was near the dormitory. Output Print a single integer β€” the largest number of people who will pass exam tomorrow because of the freebie visit. Examples Input 6 4 1 7 8 3 8 1 Output 3 Tags: binary search, brute force, implementation Correct Solution: ``` n = int(input()) v = list(map(int, input().split())) t = int(input()) v.sort() ret = 1 lef = 0 rit = 1 while rit < n: while rit < n and v[rit] - v[lef] <= t: rit = rit + 1 ret = max(ret, rit - lef) lef = lef + 1 print(ret) ```
12,798
Provide tags and a correct Python 3 solution for this coding contest problem. Everyone loves a freebie. Especially students. It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" β€” then flown freebie helps him to pass the upcoming exam. In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time ti, where ti is the number of seconds elapsed since the beginning of the night. It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them. Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be. Input The first line of the input contains integer n (1 ≀ n ≀ 100), where n β€” the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers ti (1 ≀ ti ≀ 1000). The last line contains integer T (1 ≀ T ≀ 1000) β€” the time interval during which the freebie was near the dormitory. Output Print a single integer β€” the largest number of people who will pass exam tomorrow because of the freebie visit. Examples Input 6 4 1 7 8 3 8 1 Output 3 Tags: binary search, brute force, implementation Correct Solution: ``` n, t = input(), [0] * 1002 for i in map(int, input().split()): t[i] += 1 T = int(input()) + 1 for i in range(1000): t[i + 1] += t[i] print(max(t[i + T] - t[i] for i in range(-1, 1001 - T))) # Made By Mostafa_Khaled ```
12,799