text
stringlengths
1.02k
43.5k
conversation_id
int64
853
107k
embedding
list
cluster
int64
24
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k. In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000. Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit). It is guaranteed that the answer exists. Input The only line of the input contains two integer numbers n and k (0 ≀ n ≀ 2 000 000 000, 1 ≀ k ≀ 9). It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros. Output Print w β€” the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0). Examples Input 30020 3 Output 1 Input 100 9 Output 2 Input 10203049 2 Output 3 Note In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. Tags: brute force, greedy Correct Solution: ``` n,k=list(map(int,input().split())) ans,c=0,0 while k>0 and n>0: if n % 10 == 0: k -= 1 else: ans += 1 n //= 10 c += 1 print(ans if n>0 else max(0,c-1)) ```
100,816
[ 0.2257080078125, 0.1026611328125, 0.1151123046875, 0.0240478515625, -0.409912109375, -0.26953125, -0.113525390625, 0.1458740234375, 0.051483154296875, 1.0458984375, 0.68896484375, -0.054718017578125, 0.05908203125, -0.740234375, -0.77685546875, 0.1258544921875, -0.65771484375, -0.6...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k. In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000. Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit). It is guaranteed that the answer exists. Input The only line of the input contains two integer numbers n and k (0 ≀ n ≀ 2 000 000 000, 1 ≀ k ≀ 9). It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros. Output Print w β€” the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0). Examples Input 30020 3 Output 1 Input 100 9 Output 2 Input 10203049 2 Output 3 Note In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. Tags: brute force, greedy Correct Solution: ``` n,k=map(int,input().split()) if(n==0): print(0) exit() x=[] while(n>0): x.append(n%10) n=n//10 c1=0 c2=0 for i in range (len(x)): if(x[i]==0): c1+=1 if(c1==k): break if(x[i]!=0): c2+=1 #print(c1,c2) if(c1<k): print(len(x)-1) else: print(c2) ```
100,817
[ 0.1802978515625, 0.10821533203125, 0.1387939453125, 0.0157928466796875, -0.411865234375, -0.239990234375, -0.1029052734375, 0.1312255859375, 0.0224761962890625, 1.0556640625, 0.69921875, -0.0650634765625, 0.06414794921875, -0.73876953125, -0.75390625, 0.120361328125, -0.6923828125, ...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k. In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000. Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit). It is guaranteed that the answer exists. Input The only line of the input contains two integer numbers n and k (0 ≀ n ≀ 2 000 000 000, 1 ≀ k ≀ 9). It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros. Output Print w β€” the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0). Examples Input 30020 3 Output 1 Input 100 9 Output 2 Input 10203049 2 Output 3 Note In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. Tags: brute force, greedy Correct Solution: ``` n,k = [x for x in input().split()] k = int(k) ans = 0 stack = 0 if k == 0: print(0) if n.count('0') < k: print(len(n)-1) else: for i in n[::-1]: if stack == k: break if i=="0": stack+=1 else: ans += 1 print(ans) ```
100,818
[ 0.1922607421875, 0.015045166015625, 0.1527099609375, 0.03271484375, -0.3515625, -0.266357421875, -0.098876953125, 0.1993408203125, 0.0745849609375, 1.0244140625, 0.68603515625, -0.158203125, 0.0589599609375, -0.78515625, -0.82177734375, 0.171630859375, -0.6796875, -0.6376953125, ...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k. In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000. Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit). It is guaranteed that the answer exists. Input The only line of the input contains two integer numbers n and k (0 ≀ n ≀ 2 000 000 000, 1 ≀ k ≀ 9). It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros. Output Print w β€” the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0). Examples Input 30020 3 Output 1 Input 100 9 Output 2 Input 10203049 2 Output 3 Note In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. Tags: brute force, greedy Correct Solution: ``` n,k = input().split() k = int(k) n = list(map(int,list(n))) l = len(n) j = l-1 while(j>-1 and k>0): if(n[j]!=0): del n[j] else: k -= 1 j -= 1 if(n[0]==0): print(l-1) else: print(l-len(n)) ```
100,819
[ 0.1923828125, 0.1121826171875, 0.125244140625, 0.0016117095947265625, -0.44384765625, -0.236572265625, -0.1209716796875, 0.151611328125, 0.0302886962890625, 1.0390625, 0.6748046875, -0.06805419921875, 0.030059814453125, -0.72900390625, -0.77197265625, 0.1463623046875, -0.6796875, -...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k. In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000. Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit). It is guaranteed that the answer exists. Input The only line of the input contains two integer numbers n and k (0 ≀ n ≀ 2 000 000 000, 1 ≀ k ≀ 9). It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros. Output Print w β€” the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0). Examples Input 30020 3 Output 1 Input 100 9 Output 2 Input 10203049 2 Output 3 Note In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. Tags: brute force, greedy Correct Solution: ``` n, k = input().split() n, k = n[::-1], int(k) r = 0 for i in range(len(n)): if n[i] != '0': r += 1 if i-r+1 == k: break else: r = len(n)-1 print(r) ```
100,820
[ 0.2176513671875, 0.101318359375, 0.100830078125, 0.0280609130859375, -0.433349609375, -0.25439453125, -0.11566162109375, 0.1412353515625, 0.04339599609375, 1.029296875, 0.68798828125, -0.06378173828125, 0.031280517578125, -0.7109375, -0.75732421875, 0.1402587890625, -0.65625, -0.71...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k. In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000. Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit). It is guaranteed that the answer exists. Input The only line of the input contains two integer numbers n and k (0 ≀ n ≀ 2 000 000 000, 1 ≀ k ≀ 9). It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros. Output Print w β€” the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0). Examples Input 30020 3 Output 1 Input 100 9 Output 2 Input 10203049 2 Output 3 Note In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. Tags: brute force, greedy Correct Solution: ``` n, k = input().split() n = list(n) k = int(k) zeroes = 0 digits_to_remove = 0 i = len(n) - 1 while True: if zeroes < k: if i == 0: digits_to_remove += len(n) - 1 break elif n[i] == '0': zeroes += 1 else: del n[i] digits_to_remove += 1 i -= 1 else: break print(digits_to_remove) ```
100,821
[ 0.2076416015625, 0.1212158203125, 0.16357421875, 0.0278778076171875, -0.453857421875, -0.254638671875, -0.1534423828125, 0.15185546875, 0.0095672607421875, 1.0595703125, 0.69189453125, -0.1019287109375, 0.0400390625, -0.7490234375, -0.779296875, 0.147705078125, -0.66748046875, -0.6...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k. In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000. Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit). It is guaranteed that the answer exists. Input The only line of the input contains two integer numbers n and k (0 ≀ n ≀ 2 000 000 000, 1 ≀ k ≀ 9). It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros. Output Print w β€” the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0). Examples Input 30020 3 Output 1 Input 100 9 Output 2 Input 10203049 2 Output 3 Note In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. Tags: brute force, greedy Correct Solution: ``` n,m=input().split();n,m=list(n)[::-1],int(m);k=0;i=0;ans=0;p=len(n) if p<=m:print(p-1) else: if n.count('0')<m:print(p-1) else: while k!=m and i<p: if n[i]=='0':k+=1 else:ans+=1 i+=1 print(ans) ```
100,822
[ 0.1807861328125, 0.1112060546875, 0.1357421875, 0.00018167495727539062, -0.434326171875, -0.222412109375, -0.099365234375, 0.1395263671875, 0.0516357421875, 1.0380859375, 0.7060546875, -0.07281494140625, 0.055328369140625, -0.71630859375, -0.78759765625, 0.12225341796875, -0.65917968...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k. In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000. Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit). It is guaranteed that the answer exists. Input The only line of the input contains two integer numbers n and k (0 ≀ n ≀ 2 000 000 000, 1 ≀ k ≀ 9). It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros. Output Print w β€” the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0). Examples Input 30020 3 Output 1 Input 100 9 Output 2 Input 10203049 2 Output 3 Note In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. Tags: brute force, greedy Correct Solution: ``` n,k=map(str,input().split()) a=list(n) k=int(k) if((10**k)>int(n)): print(len(n)-1) else: if((int(n)%(10**k))==0): print(0) else: c=0 z=0 for i in range(len(a)-1,-1,-1): if(z==k): break if(a[i]!='0'): c=c+1 if(a[i]=='0'): z=z+1 if(z<k): print(len(a)-1) else: print(c) ```
100,823
[ 0.1588134765625, 0.09197998046875, 0.1285400390625, -0.00782012939453125, -0.42529296875, -0.23681640625, -0.0933837890625, 0.1336669921875, 0.0352783203125, 1.03515625, 0.67822265625, -0.09521484375, 0.06695556640625, -0.71142578125, -0.7724609375, 0.11846923828125, -0.69921875, -...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k. In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000. Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit). It is guaranteed that the answer exists. Input The only line of the input contains two integer numbers n and k (0 ≀ n ≀ 2 000 000 000, 1 ≀ k ≀ 9). It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros. Output Print w β€” the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0). Examples Input 30020 3 Output 1 Input 100 9 Output 2 Input 10203049 2 Output 3 Note In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. Submitted Solution: ``` L = input() L = L.split() n = L[0] k = int(L[1]) def Div(N, K): N = int(N) if N%10**K == 0: return True else: return False c = 0 f = len(n) while f != 1: f -= 1 if n[f] != '0' and not(Div(n,k)): b = n[:f] + n[f +1:] n = b c += 1 else: b = n if int(n) == 0: print (c) else: nd = len(b) nceros = nd -1 if nceros < k: c = nceros + c print (c) ``` Yes
100,824
[ 0.24365234375, 0.11688232421875, 0.006587982177734375, 0.00339508056640625, -0.463623046875, -0.1494140625, -0.1602783203125, 0.1796875, -0.0056610107421875, 1.0595703125, 0.6240234375, 0.0014190673828125, -0.0237274169921875, -0.75341796875, -0.71337890625, 0.08831787109375, -0.6728...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k. In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000. Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit). It is guaranteed that the answer exists. Input The only line of the input contains two integer numbers n and k (0 ≀ n ≀ 2 000 000 000, 1 ≀ k ≀ 9). It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros. Output Print w β€” the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0). Examples Input 30020 3 Output 1 Input 100 9 Output 2 Input 10203049 2 Output 3 Note In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. Submitted Solution: ``` n, k = list(map(int, input().split())) n = list(str(n)) a = len(n) if n.count('0') < k: print(a-1) else: cz = 0 ca = 0 for i in n[::-1]: if i == '0': cz += 1 else: ca += 1 if cz == k: print(ca) break ``` Yes
100,825
[ 0.2213134765625, 0.08673095703125, 0.0576171875, -0.0124359130859375, -0.46337890625, -0.1669921875, -0.1978759765625, 0.19775390625, -0.02386474609375, 1.0634765625, 0.62353515625, -0.0084381103515625, -0.01513671875, -0.77685546875, -0.72216796875, 0.06561279296875, -0.67578125, ...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k. In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000. Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit). It is guaranteed that the answer exists. Input The only line of the input contains two integer numbers n and k (0 ≀ n ≀ 2 000 000 000, 1 ≀ k ≀ 9). It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros. Output Print w β€” the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0). Examples Input 30020 3 Output 1 Input 100 9 Output 2 Input 10203049 2 Output 3 Note In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. Submitted Solution: ``` s, k = input().split() k = int(k) v, w, l = 0, 0, len(s) for i in reversed(range(l)): if s[i] == '0': v += 1 elif not v >= k: w += 1 if v >= k: print(w) else: print(l-1) ``` Yes
100,826
[ 0.2474365234375, 0.126220703125, 0.0110931396484375, -0.002349853515625, -0.4794921875, -0.156982421875, -0.1998291015625, 0.18701171875, -0.057037353515625, 1.0537109375, 0.609375, -0.055328369140625, -0.01873779296875, -0.7890625, -0.72021484375, 0.076171875, -0.6962890625, -0.69...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k. In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000. Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit). It is guaranteed that the answer exists. Input The only line of the input contains two integer numbers n and k (0 ≀ n ≀ 2 000 000 000, 1 ≀ k ≀ 9). It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros. Output Print w β€” the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0). Examples Input 30020 3 Output 1 Input 100 9 Output 2 Input 10203049 2 Output 3 Note In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. Submitted Solution: ``` a = list(input().split()) n = a[0] k = int(a[1]) c = 0 f = 0 for x in range(-1, -len(n)-1, -1): if n[x] == "0": c = c + 1 if c == k: print( -x-k ) f = 1 break if f == 0: print(len(n) - 1) ``` Yes
100,827
[ 0.2376708984375, 0.1343994140625, 0.00945281982421875, -0.0031986236572265625, -0.46044921875, -0.1427001953125, -0.1737060546875, 0.212646484375, -0.0025615692138671875, 1.0400390625, 0.642578125, -0.004100799560546875, -0.01390838623046875, -0.779296875, -0.73095703125, 0.08190917968...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k. In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000. Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit). It is guaranteed that the answer exists. Input The only line of the input contains two integer numbers n and k (0 ≀ n ≀ 2 000 000 000, 1 ≀ k ≀ 9). It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros. Output Print w β€” the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0). Examples Input 30020 3 Output 1 Input 100 9 Output 2 Input 10203049 2 Output 3 Note In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. Submitted Solution: ``` n,k=list(map(int,input().split())) ans,c=0,0 while k>0 and n>0: if n % 10 == 0: k -= 1 else: ans += 1 n //= 10 c += 1 print(ans if n>0 else c-1) ``` No
100,828
[ 0.2431640625, 0.1064453125, 0.0292816162109375, -0.0178985595703125, -0.46533203125, -0.1810302734375, -0.1783447265625, 0.18310546875, -0.02410888671875, 1.046875, 0.6279296875, -0.019073486328125, -0.006961822509765625, -0.7900390625, -0.74072265625, 0.09759521484375, -0.6669921875...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k. In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000. Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit). It is guaranteed that the answer exists. Input The only line of the input contains two integer numbers n and k (0 ≀ n ≀ 2 000 000 000, 1 ≀ k ≀ 9). It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros. Output Print w β€” the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0). Examples Input 30020 3 Output 1 Input 100 9 Output 2 Input 10203049 2 Output 3 Note In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. Submitted Solution: ``` n,k=input ().split (); k = int (k); n=n [::-1]; for i in range (0,100) : if n [:i].count ("0")>=k : print (i); break; else : print (str (len (n)-1)) ``` No
100,829
[ 0.2425537109375, 0.1151123046875, 0.014373779296875, -0.0177764892578125, -0.49169921875, -0.1697998046875, -0.1778564453125, 0.189208984375, -0.038330078125, 1.0341796875, 0.6279296875, -0.0533447265625, -0.0202789306640625, -0.76708984375, -0.7177734375, 0.097900390625, -0.69091796...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k. In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000. Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit). It is guaranteed that the answer exists. Input The only line of the input contains two integer numbers n and k (0 ≀ n ≀ 2 000 000 000, 1 ≀ k ≀ 9). It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros. Output Print w β€” the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0). Examples Input 30020 3 Output 1 Input 100 9 Output 2 Input 10203049 2 Output 3 Note In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. Submitted Solution: ``` n,k=map(str,input().strip().split()) k=int(k) num=str(10**k) if(len(n)<len(num)): print(len(n)-1) else: c,z=0,0 for i in range(len(n)-1,-1,-1): if(n[i]!='0'): c+=1 else: z+=1 if(z==k): break print(c) ``` No
100,830
[ 0.2152099609375, 0.1151123046875, 0.038482666015625, -0.0206298828125, -0.475830078125, -0.156982421875, -0.183349609375, 0.16845703125, -0.04522705078125, 1.01953125, 0.630859375, -0.058319091796875, -0.01438140869140625, -0.763671875, -0.73046875, 0.0897216796875, -0.6962890625, ...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is crazy about round numbers. He especially likes the numbers divisible by 10k. In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if k = 3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103 = 1000. Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit). It is guaranteed that the answer exists. Input The only line of the input contains two integer numbers n and k (0 ≀ n ≀ 2 000 000 000, 1 ≀ k ≀ 9). It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros. Output Print w β€” the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0). Examples Input 30020 3 Output 1 Input 100 9 Output 2 Input 10203049 2 Output 3 Note In the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. Submitted Solution: ``` '''input 100 9 ''' n, k = map(int, input().split()) if str(n).count('0') >= k: x = str(n)[::-1] for l in range(1,len(x)): if x[:l].count('0') == k: print(l-k) else: print(len(str(n))-1) ``` No
100,831
[ 0.21875, 0.11126708984375, 0.0266876220703125, -0.0447998046875, -0.4462890625, -0.1746826171875, -0.17138671875, 0.1712646484375, 0.004108428955078125, 1.05859375, 0.6552734375, -0.038482666015625, -0.01232147216796875, -0.7646484375, -0.6982421875, 0.0836181640625, -0.6728515625, ...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β€” coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them. Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 ≀ i ≀ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good. Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set? Input The first line contains a single integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” number of test cases. Then t test cases follow. The first line of each test case contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of segments. This is followed by n lines describing the segments. Each segment is described by two integers l and r (1 ≀ l ≀ r ≀ 10^9) β€” coordinates of the beginning and end of the segment, respectively. It is guaranteed that the sum of n for all test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the minimum number of segments that need to be deleted in order for the set of remaining segments to become good. Example Input 4 3 1 4 2 3 3 6 4 1 2 2 3 3 5 4 5 5 1 2 3 8 4 5 6 7 9 10 5 1 5 2 4 3 5 3 8 4 8 Output 0 1 2 0 Tags: binary search, data structures, greedy Correct Solution: ``` import sys import bisect input = lambda: sys.stdin.readline().rstrip("\r\n") for _ in range(int(input())): n=int(input()) l=[] r=[] a=[] for _ in range(n): L,R=map(int,input().split()) l.append(L) r.append(R) a.append([L,R]) l.sort() r.sort() ans=n for i in a: ans=min(ans,n-bisect.bisect(l,i[1])+bisect.bisect_left(r,i[0])) print(ans) ```
101,416
[ 0.257568359375, 0.2646484375, 0.509765625, 0.46337890625, -0.58544921875, -0.7578125, -0.2467041015625, -0.03106689453125, 0.404541015625, 0.68603515625, 0.9189453125, -0.109375, 0.08172607421875, -0.94091796875, -0.71923828125, -0.001392364501953125, -0.7119140625, -0.6904296875, ...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β€” coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them. Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 ≀ i ≀ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good. Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set? Input The first line contains a single integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” number of test cases. Then t test cases follow. The first line of each test case contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of segments. This is followed by n lines describing the segments. Each segment is described by two integers l and r (1 ≀ l ≀ r ≀ 10^9) β€” coordinates of the beginning and end of the segment, respectively. It is guaranteed that the sum of n for all test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the minimum number of segments that need to be deleted in order for the set of remaining segments to become good. Example Input 4 3 1 4 2 3 3 6 4 1 2 2 3 3 5 4 5 5 1 2 3 8 4 5 6 7 9 10 5 1 5 2 4 3 5 3 8 4 8 Output 0 1 2 0 Tags: binary search, data structures, greedy Correct Solution: ``` import sys import bisect input=sys.stdin.readline t=int(input()) for _ in range(t): n=int(input()) left=[] right=[] l=[] for i in range(n): p=input().split() x=int(p[0]) y=int(p[1]) l.append((x,y)) left.append(x) right.append(y) left.sort() right.sort() mina=10**18 for i in range(n): y=bisect.bisect_right(left,l[i][1]) y=n-y z=bisect.bisect_left(right,l[i][0]) mina=min(mina,z+y) print(mina) ```
101,417
[ 0.250244140625, 0.2384033203125, 0.5087890625, 0.429443359375, -0.58837890625, -0.76611328125, -0.248291015625, -0.0340576171875, 0.401611328125, 0.68798828125, 0.92919921875, -0.11639404296875, 0.11676025390625, -0.935546875, -0.73974609375, 0.003154754638671875, -0.7421875, -0.69...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β€” coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them. Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 ≀ i ≀ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good. Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set? Input The first line contains a single integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” number of test cases. Then t test cases follow. The first line of each test case contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of segments. This is followed by n lines describing the segments. Each segment is described by two integers l and r (1 ≀ l ≀ r ≀ 10^9) β€” coordinates of the beginning and end of the segment, respectively. It is guaranteed that the sum of n for all test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the minimum number of segments that need to be deleted in order for the set of remaining segments to become good. Example Input 4 3 1 4 2 3 3 6 4 1 2 2 3 3 5 4 5 5 1 2 3 8 4 5 6 7 9 10 5 1 5 2 4 3 5 3 8 4 8 Output 0 1 2 0 Tags: binary search, data structures, greedy Correct Solution: ``` from bisect import bisect_left, bisect_right from math import inf from sys import stdin def read_ints(): return map(int, stdin.readline().split()) t_n, = read_ints() for i_t in range(t_n): n, = read_ints() segments = [tuple(read_ints()) for i_segment in range(n)] ls = sorted(l for l, r in segments) rs = sorted(r for l, r in segments) result = +inf for l, r in segments: lower_n = bisect_left(rs, l) higher_n = len(ls) - bisect_right(ls, r) result = min(result, lower_n + higher_n) print(result) ```
101,418
[ 0.26025390625, 0.258544921875, 0.501953125, 0.42529296875, -0.5986328125, -0.7333984375, -0.2320556640625, -0.0645751953125, 0.39013671875, 0.7236328125, 0.94384765625, -0.09429931640625, 0.1435546875, -0.93359375, -0.72021484375, -0.049041748046875, -0.75830078125, -0.70166015625,...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β€” coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them. Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 ≀ i ≀ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good. Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set? Input The first line contains a single integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” number of test cases. Then t test cases follow. The first line of each test case contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of segments. This is followed by n lines describing the segments. Each segment is described by two integers l and r (1 ≀ l ≀ r ≀ 10^9) β€” coordinates of the beginning and end of the segment, respectively. It is guaranteed that the sum of n for all test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the minimum number of segments that need to be deleted in order for the set of remaining segments to become good. Example Input 4 3 1 4 2 3 3 6 4 1 2 2 3 3 5 4 5 5 1 2 3 8 4 5 6 7 9 10 5 1 5 2 4 3 5 3 8 4 8 Output 0 1 2 0 Tags: binary search, data structures, greedy Correct Solution: ``` import sys,math,itertools from collections import Counter,deque,defaultdict from bisect import bisect_left,bisect_right from heapq import heappop,heappush,heapify mod = 10**9+7 INF = float('inf') def inp(): return int(sys.stdin.readline()) def inpl(): return list(map(int, sys.stdin.readline().split())) class BIT: def __init__(self, n): self.n = n self.data = [0]*(n+1) self.el = [0]*(n+1) def sum(self, i): s = 0 while i > 0: s += self.data[i] i -= i & -i return s def add(self, i, x): # assert i > 0 self.el[i] += x while i <= self.n: self.data[i] += x i += i & -i def get(self, i, j=None): if j is None: return self.el[i] return self.sum(j) - self.sum(i) # n = 6 # a = [1,2,3,4,5,6] # bit = BIT(n) # for i,e in enumerate(a): # bit.add(i+1,e) # print(bit.get(2,5)) #12 (3+4+5) for _ in range(inp()): n = inp() lr = [inpl() for _ in range(n)] s = set() for l,r in lr: s.add(l); s.add(r) s = list(s); s.sort() d = {} for i,x in enumerate(s): d[x] = i+1 ln = len(s) lbit = BIT(ln+10) rbit = BIT(ln+10) for i,(l,r) in enumerate(lr): lr[i][0] = d[l]; lbit.add(d[l]+1,1) lr[i][1] = d[r]; rbit.add(d[r]+1,1) res = INF # print(rbit.get(1,2)) for L,R in lr: now = rbit.get(0,L) + lbit.get(R+1,ln+10) res = min(res,now) print(res) ```
101,419
[ 0.2305908203125, 0.2257080078125, 0.447265625, 0.517578125, -0.55029296875, -0.73388671875, -0.226318359375, -0.1610107421875, 0.469970703125, 0.72509765625, 0.91259765625, -0.129150390625, 0.104248046875, -0.95849609375, -0.74560546875, -0.023956298828125, -0.744140625, -0.7338867...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β€” coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them. Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 ≀ i ≀ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good. Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set? Input The first line contains a single integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” number of test cases. Then t test cases follow. The first line of each test case contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of segments. This is followed by n lines describing the segments. Each segment is described by two integers l and r (1 ≀ l ≀ r ≀ 10^9) β€” coordinates of the beginning and end of the segment, respectively. It is guaranteed that the sum of n for all test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the minimum number of segments that need to be deleted in order for the set of remaining segments to become good. Example Input 4 3 1 4 2 3 3 6 4 1 2 2 3 3 5 4 5 5 1 2 3 8 4 5 6 7 9 10 5 1 5 2 4 3 5 3 8 4 8 Output 0 1 2 0 Tags: binary search, data structures, greedy Correct Solution: ``` import os,io from bisect import bisect_left, bisect_right input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline for _ in range (int(input())): n = int(input()) l = [] r = [] a = [] for i in range (n): li,ri = [int(i) for i in input().split()] l.append(li) r.append(ri) a.append([li,ri]) l.sort() r.sort() cnt = n for i in range (n): cnt = min(cnt, n-bisect_right(l,a[i][1])+bisect_left(r,a[i][0])) print(cnt) ```
101,420
[ 0.2353515625, 0.2430419921875, 0.49853515625, 0.44873046875, -0.59619140625, -0.77197265625, -0.221923828125, -0.042236328125, 0.442626953125, 0.7255859375, 0.95947265625, -0.0987548828125, 0.11737060546875, -0.90673828125, -0.73974609375, -0.01727294921875, -0.77490234375, -0.7001...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β€” coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them. Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 ≀ i ≀ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good. Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set? Input The first line contains a single integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” number of test cases. Then t test cases follow. The first line of each test case contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of segments. This is followed by n lines describing the segments. Each segment is described by two integers l and r (1 ≀ l ≀ r ≀ 10^9) β€” coordinates of the beginning and end of the segment, respectively. It is guaranteed that the sum of n for all test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the minimum number of segments that need to be deleted in order for the set of remaining segments to become good. Example Input 4 3 1 4 2 3 3 6 4 1 2 2 3 3 5 4 5 5 1 2 3 8 4 5 6 7 9 10 5 1 5 2 4 3 5 3 8 4 8 Output 0 1 2 0 Tags: binary search, data structures, greedy Correct Solution: ``` # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- from bisect import bisect_left, bisect_right for _ in range (int(input())): n = int(input()) l = [] r = [] a = [] for i in range (n): li,ri = [int(i) for i in input().split()] l.append(li) r.append(ri) a.append([li,ri]) l.sort() r.sort() cnt = n for i in range (n): cnt = min(cnt, n-bisect_right(l,a[i][1])+bisect_left(r,a[i][0])) print(cnt) ```
101,421
[ 0.31298828125, 0.233642578125, 0.44140625, 0.488037109375, -0.53662109375, -0.84228515625, -0.2452392578125, 0.0712890625, 0.461181640625, 0.69580078125, 0.9384765625, -0.050506591796875, 0.1163330078125, -0.93115234375, -0.6484375, -0.0144195556640625, -0.65869140625, -0.666503906...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β€” coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them. Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 ≀ i ≀ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good. Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set? Input The first line contains a single integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” number of test cases. Then t test cases follow. The first line of each test case contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of segments. This is followed by n lines describing the segments. Each segment is described by two integers l and r (1 ≀ l ≀ r ≀ 10^9) β€” coordinates of the beginning and end of the segment, respectively. It is guaranteed that the sum of n for all test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the minimum number of segments that need to be deleted in order for the set of remaining segments to become good. Example Input 4 3 1 4 2 3 3 6 4 1 2 2 3 3 5 4 5 5 1 2 3 8 4 5 6 7 9 10 5 1 5 2 4 3 5 3 8 4 8 Output 0 1 2 0 Tags: binary search, data structures, greedy Correct Solution: ``` import bisect import io, os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline for _ in range(int(input())): n = int(input()) ls = [] lsl = [] lsr = [] for _ in range(n): l, r = map(int, input().split()) ls.append([l, r]) lsl.append(l) lsr.append(r) lsl.sort() lsr.sort() cnt = n for i in range(n): cnt = min(cnt, n - bisect.bisect_right(lsl, ls[i][1]) + bisect.bisect_left(lsr, ls[i][0])) print(cnt) ```
101,422
[ 0.253662109375, 0.240478515625, 0.515625, 0.45556640625, -0.6015625, -0.7548828125, -0.1986083984375, -0.044403076171875, 0.44921875, 0.71142578125, 0.94482421875, -0.11932373046875, 0.11322021484375, -0.92236328125, -0.73876953125, -0.009185791015625, -0.75341796875, -0.6801757812...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β€” coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them. Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 ≀ i ≀ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good. Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set? Input The first line contains a single integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” number of test cases. Then t test cases follow. The first line of each test case contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of segments. This is followed by n lines describing the segments. Each segment is described by two integers l and r (1 ≀ l ≀ r ≀ 10^9) β€” coordinates of the beginning and end of the segment, respectively. It is guaranteed that the sum of n for all test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the minimum number of segments that need to be deleted in order for the set of remaining segments to become good. Example Input 4 3 1 4 2 3 3 6 4 1 2 2 3 3 5 4 5 5 1 2 3 8 4 5 6 7 9 10 5 1 5 2 4 3 5 3 8 4 8 Output 0 1 2 0 Tags: binary search, data structures, greedy Correct Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys #import threading from collections import defaultdict #threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase #sys.setrecursionlimit(300000) 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----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=300006, func=lambda a, b: min(a , b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b:a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] <=key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ class TrieNode: def __init__(self): self.children = [None] * 26 self.isEndOfWord = False class Trie: def __init__(self): self.root = self.getNode() def getNode(self): return TrieNode() def _charToIndex(self, ch): return ord(ch) - ord('a') def insert(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: pCrawl.children[index] = self.getNode() pCrawl = pCrawl.children[index] pCrawl.isEndOfWord = True def search(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: return False pCrawl = pCrawl.children[index] return pCrawl != None and pCrawl.isEndOfWord #-----------------------------------------trie--------------------------------- class Node: def __init__(self, data): self.data = data self.height=0 self.left = None # left node for 0 self.right = None # right node for 1 class BinaryTrie: def __init__(self): self.root = Node(0) def insert(self, pre_xor): self.temp = self.root for i in range(31, -1, -1): val = pre_xor & (1 << i) if val==0: if not self.temp.right: self.temp.right = Node(0) self.temp = self.temp.right elif val>=1: if not self.temp.left: self.temp.left = Node(0) self.temp = self.temp.left def do(self,temp): if not temp: return 0 ter=temp temp.height=self.do(ter.left)+self.do(ter.right) if temp.height==0: temp.height+=1 return temp.height def query(self, xor): self.temp = self.root cur=0 i=31 while(i>-1): val = xor & (1 << i) if not self.temp: return cur if val>=1: self.opp = self.temp.right if self.temp.left: self.temp = self.temp.left else: return cur else: self.opp=self.temp.left if self.temp.right: self.temp = self.temp.right else: return cur if self.temp.height==pow(2,i): cur+=1<<(i) self.temp=self.opp i-=1 return cur #-------------------------bin trie------------------------------------------- def binarySearchCount1(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] <key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count for ik in range(int(input())): n=int(input()) l=[] l1=[] l2=[] for i in range(n): a,b=map(int,input().split()) l.append((a,b)) l1.append(b) l.sort() l1.sort() d=defaultdict(list) inr = defaultdict(int) for i in range(len(l1)): d[l1[i]].append(i) inr[l1[i]]+=1 w=[] e=[0]*n s=SegmentTree(e) for i in range(n): w.append(l[i][0]) w1=n for i in range(n): ind=binarySearchCount1(l1,len(l1),l[i][0]) if ind==n: ans=0 else: ind=d[l1[ind]][0] ans=s.query(ind,n-1) ans+=binarySearchCount(w,len(w),l[i][1])-i-1 s.__setitem__(d[l[i][1]][inr[l[i][1]]-1],1) e[d[l[i][1]][inr[l[i][1]]-1]]=1 inr[l[i][1]]-=1 w1=min(w1,n-1-ans) print(w1) ```
101,423
[ 0.318603515625, 0.240234375, 0.441162109375, 0.5029296875, -0.54248046875, -0.8349609375, -0.23291015625, 0.09283447265625, 0.421630859375, 0.6826171875, 0.96923828125, -0.04052734375, 0.08819580078125, -0.888671875, -0.6611328125, -0.01397705078125, -0.64306640625, -0.63818359375,...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β€” coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them. Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 ≀ i ≀ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good. Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set? Input The first line contains a single integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” number of test cases. Then t test cases follow. The first line of each test case contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of segments. This is followed by n lines describing the segments. Each segment is described by two integers l and r (1 ≀ l ≀ r ≀ 10^9) β€” coordinates of the beginning and end of the segment, respectively. It is guaranteed that the sum of n for all test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the minimum number of segments that need to be deleted in order for the set of remaining segments to become good. Example Input 4 3 1 4 2 3 3 6 4 1 2 2 3 3 5 4 5 5 1 2 3 8 4 5 6 7 9 10 5 1 5 2 4 3 5 3 8 4 8 Output 0 1 2 0 Submitted Solution: ``` import sys import math,bisect,operator inf,mod = float('inf'),10**9+7 sys.setrecursionlimit(10 ** 5) from itertools import groupby,accumulate from heapq import heapify,heappop,heappush from collections import deque,Counter,defaultdict I = lambda : int(sys.stdin.readline()) neo = lambda : map(int, sys.stdin.readline().split()) Neo = lambda : list(map(int, sys.stdin.readline().split())) def overlap(v): x,y = [],[] for i,j in v: x += [i] y += [j] x.sort() y.sort() Ans = 0 for i in range(n): p,q = v[i][0],v[i][1] r = bisect.bisect_right(x,q) l = bisect.bisect_left(y,p) Ans = max(Ans,r-l) return Ans for _ in range(I()): n = I() A = [] for i in range(n): l,r = neo() A += [(l,r)] print(max(n-overlap(A),0)) ``` Yes
101,424
[ 0.273193359375, 0.3466796875, 0.416259765625, 0.4521484375, -0.6728515625, -0.6494140625, -0.295166015625, 0.045562744140625, 0.402099609375, 0.79052734375, 0.92529296875, 0.024566650390625, 0.107421875, -0.970703125, -0.671875, 0.0104217529296875, -0.73486328125, -0.7216796875, ...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β€” coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them. Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 ≀ i ≀ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good. Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set? Input The first line contains a single integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” number of test cases. Then t test cases follow. The first line of each test case contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of segments. This is followed by n lines describing the segments. Each segment is described by two integers l and r (1 ≀ l ≀ r ≀ 10^9) β€” coordinates of the beginning and end of the segment, respectively. It is guaranteed that the sum of n for all test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the minimum number of segments that need to be deleted in order for the set of remaining segments to become good. Example Input 4 3 1 4 2 3 3 6 4 1 2 2 3 3 5 4 5 5 1 2 3 8 4 5 6 7 9 10 5 1 5 2 4 3 5 3 8 4 8 Output 0 1 2 0 Submitted 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") for t in range(int(input())): n=int(input()) lft=[1000000000] rt=[0] a=[] for i in range(n): l,r=map(int,input().split()) a.append([l,r]) lft.append(l) rt.append(r) lft.sort() rt.sort() count=0 mini=9999999999999 for i in range(n): j,k,count=0,n,0 while True: m=(j+k)//2 if(rt[m]>=a[i][0]): k=m else: j=m if(k==j+1): break count+=j j,k=0,n while True: m=(j+k)//2 if(lft[m]>a[i][1]): k=m else: j=m if(k==j+1): break count+=(n-1-j) mini=min(mini,count) print(mini) ``` Yes
101,425
[ 0.354248046875, 0.219970703125, 0.291259765625, 0.498046875, -0.71728515625, -0.7177734375, -0.287841796875, 0.112060546875, 0.479248046875, 0.76220703125, 0.859375, 0.046234130859375, 0.11407470703125, -0.90673828125, -0.7021484375, -0.03448486328125, -0.6953125, -0.7041015625, ...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β€” coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them. Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 ≀ i ≀ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good. Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set? Input The first line contains a single integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” number of test cases. Then t test cases follow. The first line of each test case contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of segments. This is followed by n lines describing the segments. Each segment is described by two integers l and r (1 ≀ l ≀ r ≀ 10^9) β€” coordinates of the beginning and end of the segment, respectively. It is guaranteed that the sum of n for all test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the minimum number of segments that need to be deleted in order for the set of remaining segments to become good. Example Input 4 3 1 4 2 3 3 6 4 1 2 2 3 3 5 4 5 5 1 2 3 8 4 5 6 7 9 10 5 1 5 2 4 3 5 3 8 4 8 Output 0 1 2 0 Submitted Solution: ``` from sys import stdin, stdout from bisect import bisect_left, bisect_right def main(): global dp global add for _ in range(int(stdin.readline())): n = int(stdin.readline()) rangey = [] L = list() R = list() for _ in range(n): l,r = list(map(int, stdin.readline().split())) rangey.append([l,r]) L.append(l) R.append(r) L.sort() R.sort() mn = n + 1 for i in range(n): l,r = rangey[i] left = bisect_left(R, l) right = n - bisect_right(L, r) mn = min(left + right, mn) stdout.write(str(mn)+"\n") main() ``` Yes
101,426
[ 0.2783203125, 0.2763671875, 0.40380859375, 0.4560546875, -0.7490234375, -0.68798828125, -0.372314453125, 0.0194091796875, 0.374267578125, 0.77685546875, 0.8486328125, 0.018157958984375, 0.0704345703125, -0.94287109375, -0.71435546875, -0.0943603515625, -0.7578125, -0.70703125, -0...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β€” coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them. Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 ≀ i ≀ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good. Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set? Input The first line contains a single integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” number of test cases. Then t test cases follow. The first line of each test case contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of segments. This is followed by n lines describing the segments. Each segment is described by two integers l and r (1 ≀ l ≀ r ≀ 10^9) β€” coordinates of the beginning and end of the segment, respectively. It is guaranteed that the sum of n for all test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the minimum number of segments that need to be deleted in order for the set of remaining segments to become good. Example Input 4 3 1 4 2 3 3 6 4 1 2 2 3 3 5 4 5 5 1 2 3 8 4 5 6 7 9 10 5 1 5 2 4 3 5 3 8 4 8 Output 0 1 2 0 Submitted Solution: ``` """ pppppppppppppppppppp ppppp ppppppppppppppppppp ppppppp ppppppppppppppppppppp pppppppp pppppppppppppppppppppp pppppppppppppppppppppppppppppppp pppppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppppp ppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppp pppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppp ppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppppppp ppppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppp ppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppp pppppppppppppppppppppppppppppppp pppppppppppppppppppppp pppppppp ppppppppppppppppppppp ppppppp ppppppppppppppppppp ppppp pppppppppppppppppppp """ import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush, nsmallest from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br, bisect from time import perf_counter from fractions import Fraction from decimal import Decimal # sys.setrecursionlimit(pow(10, 6)) # sys.stdin = open("input.txt", "r") # sys.stdout = open("output.txt", "w") mod = pow(10, 9) + 7 mod2 = 998244353 def data(): return sys.stdin.readline().strip() def out(var): sys.stdout.write(str(var)+"\n") def outa(*var, end="\n"): sys.stdout.write(' '.join(map(str, var)) + end) def l(): return list(sp()) def sl(): return list(ssp()) def sp(): return map(int, data().split()) def ssp(): return map(str, data().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)] def update(index, value): while index <= limit: bit[index] += value index += index & -index def query(index): ret = 0 while index: ret += bit[index] index -= index & -index return ret for _ in range(int(data())): n = int(data()) arr = [l() for _ in range(n)] s = set() for a, b in arr: s.add(a) s.add(b) s = list(s) s.sort() mp = dd(int) for i in range(len(s)): mp[s[i]] = i + 1 for i in range(n): arr[i] = [mp[arr[i][0]], mp[arr[i][1]]] arr.sort() limit = n * 2 + 10 bit = [0] * limit limit -= 1 answer = n for i, [a, b] in enumerate(arr): low, high = i, n - 1 index = i while low <= high: mid = (low + high) >> 1 if arr[mid][0] <= b: index = mid low = mid + 1 else: high = mid - 1 answer = min(answer, n - (index - i + 1 + query(n * 2 + 2) - query(a - 1))) update(b, 1) out(answer) ``` Yes
101,427
[ 0.357666015625, 0.251220703125, 0.3876953125, 0.482421875, -0.689453125, -0.736328125, -0.38134765625, 0.130615234375, 0.39453125, 0.72265625, 0.89599609375, 0.00905609130859375, 0.05426025390625, -0.90185546875, -0.6884765625, -0.03668212890625, -0.72900390625, -0.646484375, -0....
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β€” coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them. Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 ≀ i ≀ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good. Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set? Input The first line contains a single integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” number of test cases. Then t test cases follow. The first line of each test case contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of segments. This is followed by n lines describing the segments. Each segment is described by two integers l and r (1 ≀ l ≀ r ≀ 10^9) β€” coordinates of the beginning and end of the segment, respectively. It is guaranteed that the sum of n for all test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the minimum number of segments that need to be deleted in order for the set of remaining segments to become good. Example Input 4 3 1 4 2 3 3 6 4 1 2 2 3 3 5 4 5 5 1 2 3 8 4 5 6 7 9 10 5 1 5 2 4 3 5 3 8 4 8 Output 0 1 2 0 Submitted Solution: ``` import sys input=sys.stdin.readline def update(inp,add,ar,n): while(inp<n): ar[inp]+=add inp+=(inp&(-inp)) def fun1(inp,ar,n): ans=0 while(inp): ans+=ar[inp] inp-=(inp&(-inp)) return ans for _ in range(int(input())): n=int(input()) ar=[] se=set({}) for i in range(n): l,r=map(int,input().split()) ar.append([l,r]) se.add(l) se.add(r) se=list(se) se.sort() dic={} le=len(se) for i in range(le): dic[se[i]]=i br=[] for i in range(n): br.append([dic[ar[i][0]],dic[ar[i][1]]]) br.sort(key=lambda x:x[0]) le+=1 left=[0]*(le-1) for i in range(n): left[br[i][0]]+=1 for i in range(1,le-1): left[i]+=left[i-1] right=[0]*le ans=0 for i in range(n): xx=left[br[i][1]]-left[br[i][0]] yy=i-fun1(br[i][0],right,le) ans=max(xx+yy+1,ans) update(br[i][1]+1,1,right,le) print(n-ans) ``` No
101,428
[ 0.35546875, 0.256591796875, 0.374267578125, 0.431640625, -0.6943359375, -0.7265625, -0.38330078125, 0.07208251953125, 0.414306640625, 0.73828125, 0.84912109375, -0.00023627281188964844, 0.07916259765625, -0.91162109375, -0.68212890625, -0.0814208984375, -0.712890625, -0.6103515625,...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β€” coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them. Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 ≀ i ≀ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good. Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set? Input The first line contains a single integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” number of test cases. Then t test cases follow. The first line of each test case contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of segments. This is followed by n lines describing the segments. Each segment is described by two integers l and r (1 ≀ l ≀ r ≀ 10^9) β€” coordinates of the beginning and end of the segment, respectively. It is guaranteed that the sum of n for all test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the minimum number of segments that need to be deleted in order for the set of remaining segments to become good. Example Input 4 3 1 4 2 3 3 6 4 1 2 2 3 3 5 4 5 5 1 2 3 8 4 5 6 7 9 10 5 1 5 2 4 3 5 3 8 4 8 Output 0 1 2 0 Submitted Solution: ``` import sys import bisect,string,math,time,functools,random,fractions from heapq import heappush,heappop,heapify from collections import deque,defaultdict,Counter from itertools import permutations,combinations,groupby rep=range;R=range def Golf():n,*t=map(int,open(0).read().split()) def I():return int(input()) def S_():return input() def IS():return input().split() def LS():return [i for i in input().split()] def MI():return map(int,input().split()) def LI():return [int(i) for i in input().split()] def LI_():return [int(i)-1 for i in input().split()] def NI(n):return [int(input()) for i in range(n)] def NI_(n):return [int(input())-1 for i in range(n)] def NLI(n):return [[int(i) for i in input().split()] for i in range(n)] def NLI_(n):return [[int(i)-1 for i in input().split()] for i in range(n)] def StoLI():return [ord(i)-97 for i in input()] def ItoS(n):return chr(n+97) def LtoS(ls):return ''.join([chr(i+97) for i in ls]) def RA():return map(int,open(0).read().split()) def RLI(n=8,a=1,b=10):return [random.randint(a,b)for i in range(n)] def RI(a=1,b=10):return random.randint(a,b) def INP(): N=9 n=random.randint(1,N) m=random.randint(1,n*n) A=[random.randint(1,n) for i in range(m)] B=[random.randint(1,n) for i in range(m)] G=[[]for i in range(n)];RG=[[]for i in range(n)] for i in range(m): a,b=A[i]-1,B[i]-1 if a==b:continue G[a]+=(b,1),;RG[b]+=(a,1), return n,m,G,RG def Rtest(T): case,err=0,0 for i in range(T): inp=INP() a1=naive(*inp) a2=solve(*inp) if a1==a2: print(inp) print('naive',a1) print('solve',a2) err+=1 case+=1 print('Tested',case,'case with',err,'errors') def GI(V,E,ls=None,Directed=False,index=1): org_inp=[];g=[[] for i in range(V)] FromStdin=True if ls==None else False for i in range(E): if FromStdin: inp=LI() org_inp.append(inp) else: inp=ls[i] if len(inp)==2: a,b=inp;c=1 else: a,b,c=inp if index==1:a-=1;b-=1 aa=(a,c);bb=(b,c);g[a].append(bb) if not Directed:g[b].append(aa) return g,org_inp def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1): #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage mp=[boundary]*(w+2);found={} for i in R(h): s=input() for char in search: if char in s: found[char]=((i+1)*(w+2)+s.index(char)+1) mp_def[char]=mp_def[replacement_of_found] mp+=[boundary]+[mp_def[j] for j in s]+[boundary] mp+=[boundary]*(w+2) return h+2,w+2,mp,found def TI(n):return GI(n,n-1) def accum(ls): rt=[0] for i in ls:rt+=[rt[-1]+i] return rt def bit_combination(n,base=2): rt=[] for tb in R(base**n):s=[tb//(base**bt)%base for bt in R(n)];rt+=[s] return rt def gcd(x,y): if y==0:return x if x%y==0:return y while x%y!=0:x,y=y,x%y return y def YN(x):print(['NO','YES'][x]) def Yn(x):print(['No','Yes'][x]) def show(*inp,end='\n'): if show_flg:print(*inp,end=end) mo=10**9+7 #mo=998244353 inf=float('inf') FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb)) l_alp=string.ascii_lowercase #sys.setrecursionlimit(10**9) read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip() show_flg=False show_flg=True class Comb: def __init__(self,n): return def fact(self,n): return self.fac[n] def invf(self,n): return self.inv[n] def comb(self,x,y): if y<0 or y>x: return 0 return x*(x-1)//2 ######################################################################################################################################################################## # Verified by # https://atcoder.jp/contests/arc033/submissions/me # https://atcoder.jp/contests/abc174/tasks/abc174_f # # speed up TIPS: delete update of el. non-use of getitem, setitem. # # Binary Indexed Tree # Bit.add(i,x) :Add x at i-th value, the following gives the same result # Bit[i]+=x # Bit.sum(i) : get sum up to i-th value # Bit.l_bound(w) get bound of index where x1+x2+...+xi<w class Bit: # 1-indexed def __init__(self,n,init=None): self.size=n self.m=len(bin(self.size))-2 self.arr=[0]*(2**self.m+1) self.el=[0]*(2**self.m+1) if init!=None: for i in range(len(init)): self.add(i,init[i]) self.el[i]=init[i] def __str__(self): a=[self.sum(i+1)-self.sum(i) for i in range(self.size)] return str(a) def add(self,i,x): if not 0<i<=self.size:return NotImplemented self.el[i]+=x while i<=self.size: self.arr[i]+=x i+=i&(-i) return def sum(self,i): if not 0<=i<=self.size:return NotImplemented rt=0 while i>0: rt+=self.arr[i] i-=i&(-i) return rt def __getitem__(self,key): return self.el[key] #return self.sum(key+1)-self.sum(key) def __setitem__(self,key,value): self.add(key,value-self.sum(key+1)+self.sum(key)) def l_bound(self,w): if w<=0: return 0 x=0 k=2**self.m while k>0: if x+k<=self.size and self.arr[x+k]<w: w-=self.arr[x+k] x+=k k>>=1 return x+1 def u_bound(self,w): if w<=0: return 0 x=0 k=2**self.m while k>0: if x+k<=self.size and self.arr[x+k]<=w: w-=self.arr[x+k] x+=k k>>=1 return x+1 class Bit0(Bit): # 0-indexed def add(self,j,x): super().add(j+1,x) def l_bound(self,w): return max(super().l_bound(w)-1,0) def u_bound(self,w): return max(super().u_bound(w)-1,0) class Multiset(Bit0): def __init__(self,max_v): super().__init__(max_v) def insert(self,x): super().add(x,1) def find(self,x): return super().l_bound(super().sum(x)) def __str__(self): return str(self.arr) def compress(L): dc={v:i for i,v in enumerate(sorted(set(L)))} return dc ans=0 ## Segment Tree ## ## Test case: ABC 146 F ## https://atcoder.jp/contests/abc146/tasks/abc146_f ## Initializer Template ## # Range Sum: sg=SegTree(n) # Range Minimum: sg=SegTree(n,inf,min,inf) class SegTree: def __init__(self,n,init_val=0,function=lambda a,b:a+b,ide=0): self.size=n self.ide_ele=ide self.num=1<<(self.size-1).bit_length() self.table=[self.ide_ele]*2*self.num self.index=[0]*2*self.num self.lazy=[self.ide_ele]*2*self.num self.func=function #set_val if not hasattr(init_val,"__iter__"): init_val=[init_val]*self.size for i,val in enumerate(init_val): self.table[i+self.num-1]=val self.index[i+self.num-1]=i #build for i in range(self.num-2,-1,-1): self.table[i]=self.func(self.table[2*i+1],self.table[2*i+2]) if self.table[i]==self.table[i*2+1]: self.index[i]=self.index[i*2+1] else: self.index[i]=self.index[i*2+2] def update(self,k,x): k+=self.num-1 self.table[k]=x while k: k=(k-1)//2 res=self.func(self.table[k*2+1],self.table[k*2+2]) self.table[k]=res ## Remove if index is not needed if res==self.table[k*2+1]: self.index[k]=self.index[k*2+1] else: self.index[k]=self.index[k*2+2] ## Remove if index is not needed def evaluate(k,l,r): #遅廢評侑処理 if lazy[k]!=0: node[k]+=lazy[k] if(r-l>1): lazy[2*k+1]+=lazy[k]//2 lazy[2*k+2]+=lazy[k]//2 lazy[k]=0 def __getitem__(self,key): if type(key) is slice: a=None if key.start==None else key.start b=None if key.stop==None else key.stop c=None if key.step==None else key.step return self.table[self.num-1:self.num-1+self.size][slice(a,b,c)] else: if 0<=key<self.size: return self.table[key+self.num-1] elif -self.size<=key<0: return self.table[self.size+key+self.num-1] else: raise IndexError("list index out of range") def __setitem__(self,key,value): if key>=0: self.update(key,value) else: self.update(self.size+key,value) def query(self,p,q): if q<=p: return self.ide_ele p+=self.num-1 q+=self.num-2 res=self.ide_ele while q-p>1: if p&1==0: res=self.func(res,self.table[p]) if q&1==1: res=self.func(res,self.table[q]) q-=1 p=p>>1 q=(q-1)>>1 if p==q: res=self.func(res,self.table[p]) else: res=self.func(self.func(res,self.table[p]),self.table[q]) return res def query_id(self,p,q): if q<=p: return self.ide_ele p+=self.num-1 q+=self.num-2 res=self.ide_ele idx=p while q-p>1: if p&1==0: res=self.func(res,self.table[p]) if res==self.table[p]: idx=self.index[p] if q&1==1: res=self.func(res,self.table[q]) if res==self.table[q]: idx=self.index[q] q-=1 p=p>>1 q=(q-1)>>1 if p==q: res=self.func(res,self.table[p]) if res==self.table[p]: idx=self.index[p] else: res=self.func(self.func(res,self.table[p]),self.table[q]) if res==self.table[p]: idx=self.index[p] elif res==self.table[q]: idx=self.index[q] return idx def __str__(self): # η”Ÿι…εˆ—γ‚’θ‘¨η€Ί rt=self.table[self.num-1:self.num-1+self.size] return str(rt) for _ in range(I()): n=I() p=[] s=set() L=[] R=[] for i in range(n): l,r=LI() p+=(l,r), R+=r, L+=l, L.sort() R.sort() for i in range(n): l,r=p[i] a=bisect.bisect_left(R,l) b=n-bisect.bisect_right(L,r) ans=max(ans,n-1-a-b) #show((a,b),(l,r),p,L,R) print(n-1-ans) ``` No
101,429
[ 0.29296875, 0.2362060546875, 0.330810546875, 0.52001953125, -0.63525390625, -0.64208984375, -0.323486328125, -0.01702880859375, 0.494140625, 0.77685546875, 0.83544921875, -0.053375244140625, 0.044281005859375, -0.94921875, -0.69921875, -0.0330810546875, -0.7109375, -0.67529296875, ...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β€” coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them. Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 ≀ i ≀ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good. Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set? Input The first line contains a single integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” number of test cases. Then t test cases follow. The first line of each test case contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of segments. This is followed by n lines describing the segments. Each segment is described by two integers l and r (1 ≀ l ≀ r ≀ 10^9) β€” coordinates of the beginning and end of the segment, respectively. It is guaranteed that the sum of n for all test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the minimum number of segments that need to be deleted in order for the set of remaining segments to become good. Example Input 4 3 1 4 2 3 3 6 4 1 2 2 3 3 5 4 5 5 1 2 3 8 4 5 6 7 9 10 5 1 5 2 4 3 5 3 8 4 8 Output 0 1 2 0 Submitted Solution: ``` t=int(input()) for _ in range(t): n=int(input()) a=[] b=[] for i in range(n): l,r=map(int,input().split()) a.append([l,r]) b.append([l,r]) a.sort(key=lambda thing: thing[0]) b.sort(key=lambda thing: thing[1]) pointer1=0 pointer2=0 rightborder=0 ans=n-1 for i in range(n): l=a[i][0] r=a[i][1] if r<=rightborder: continue rightborder=r while pointer1+1<n and a[pointer1+1][0]<r: pointer1+=1 while pointer2<n and b[pointer2][1]<l: pointer2+=1 ans=min(ans,pointer2+n-pointer1-1) print(ans) ``` No
101,430
[ 0.32177734375, 0.2381591796875, 0.377197265625, 0.428466796875, -0.666015625, -0.71728515625, -0.362060546875, 0.11602783203125, 0.389404296875, 0.740234375, 0.87255859375, 0.021209716796875, 0.05120849609375, -0.91064453125, -0.68798828125, -0.036163330078125, -0.74169921875, -0.6...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i β€” coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them. Polycarp believes that a set of k segments is good if there is a segment [l_i, r_i] (1 ≀ i ≀ k) from the set, such that it intersects every segment from the set (the intersection must be a point or segment). For example, a set of 3 segments [[1, 4], [2, 3], [3, 6]] is good, since the segment [2, 3] intersects each segment from the set. Set of 4 segments [[1, 2], [2, 3], [3, 5], [4, 5]] is not good. Polycarp wonders, what is the minimum number of segments he has to delete so that the remaining segments form a good set? Input The first line contains a single integer t (1 ≀ t ≀ 2 β‹… 10^5) β€” number of test cases. Then t test cases follow. The first line of each test case contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the number of segments. This is followed by n lines describing the segments. Each segment is described by two integers l and r (1 ≀ l ≀ r ≀ 10^9) β€” coordinates of the beginning and end of the segment, respectively. It is guaranteed that the sum of n for all test cases does not exceed 2 β‹… 10^5. Output For each test case, output a single integer β€” the minimum number of segments that need to be deleted in order for the set of remaining segments to become good. Example Input 4 3 1 4 2 3 3 6 4 1 2 2 3 3 5 4 5 5 1 2 3 8 4 5 6 7 9 10 5 1 5 2 4 3 5 3 8 4 8 Output 0 1 2 0 Submitted Solution: ``` import bisect for _ in range(int(input())): n=int(input()) xx=[0]*n yy=[0]*n arr=[(0,0)]*n for i in range(n): a,b=map(int,input().split()) xx[i]=a yy[i]=b arr[i]=(a,b) ans=999999999 for i in range(n): a=bisect.bisect_left(yy,arr[i][0]) b=bisect.bisect_right(xx,arr[i][1]) b=n-b #print(a,b,arr[i]) ans=min(ans,a+b) #print(ed) print(ans) ``` No
101,431
[ 0.289794921875, 0.28369140625, 0.377685546875, 0.436767578125, -0.7099609375, -0.69970703125, -0.315185546875, 0.0574951171875, 0.37353515625, 0.77734375, 0.88232421875, 0.0224609375, 0.06610107421875, -0.9638671875, -0.72412109375, -0.0316162109375, -0.771484375, -0.6845703125, ...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is in really serious trouble β€” his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β€” the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β‰₯ di, then i-th item cannot be saved. Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β€” in ta + tb seconds after fire started. Input The first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of items in Polycarp's house. Each of the following n lines contains three integers ti, di, pi (1 ≀ ti ≀ 20, 1 ≀ di ≀ 2 000, 1 ≀ pi ≀ 20) β€” the time needed to save the item i, the time after which the item i will burn completely and the value of item i. Output In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β€” the number of items in the desired set. In the third line print m distinct integers β€” numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them. Examples Input 3 3 7 4 2 6 5 3 7 6 Output 11 2 2 3 Input 2 5 6 1 3 3 5 Output 1 1 1 Note In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11. In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. Tags: dp, sortings Correct Solution: ``` from sys import stdin input = stdin.readline n = int(input()) T = 2001 t, d, p, idx = [], [], [], [] ans = [] arr = [] for i in range(n): a, b, c = map(int, input().split()) arr.append([a, b, c, i]) arr.sort(key=lambda x: x[1]) for i in arr: t.append(i[0]); d.append(i[1]); p.append(i[2]); idx.append(i[3]) dp = [[0 for j in range(n)] for i in range(T)] for time in range(1, T): for i in range(n): #dp[time][i] = max(dp[time - 1][i], dp[time][i - 1]) dp[time][i] = dp[time][i - 1] if d[i] > time >= t[i]: if i: dp[time][i] = max(dp[time][i], p[i] + dp[time - t[i]][i - 1]) else: dp[time][i] = p[i] b = [0, [0 ,0]] for i in range(T): for j in range(n): if b[0] < dp[i][j]: b = [dp[i][j], [i, j]] print(b[0]) b = b[1] while dp[b[0]][b[1]] and b[0] > -1: if b[1] and dp[b[0]][b[1]] != dp[b[0]][b[1] - 1]: ans.append(b[1]) b[0] -= t[b[1]] elif b[1] == 0: if dp[b[0]][b[1]]: ans.append(b[1]) break b[1] -= 1 print(len(ans)) for i in ans[::-1]: print(idx[i] + 1, end=' ') ```
102,603
[ 0.41015625, 0.1705322265625, 0.1280517578125, 0.30712890625, -0.373291015625, -0.369140625, -0.31201171875, -0.015594482421875, 0.5302734375, 0.412841796875, 0.86279296875, -0.09783935546875, 0.348388671875, -0.5859375, -0.45068359375, -0.1407470703125, -0.5283203125, -0.3056640625...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is in really serious trouble β€” his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β€” the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β‰₯ di, then i-th item cannot be saved. Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β€” in ta + tb seconds after fire started. Input The first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of items in Polycarp's house. Each of the following n lines contains three integers ti, di, pi (1 ≀ ti ≀ 20, 1 ≀ di ≀ 2 000, 1 ≀ pi ≀ 20) β€” the time needed to save the item i, the time after which the item i will burn completely and the value of item i. Output In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β€” the number of items in the desired set. In the third line print m distinct integers β€” numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them. Examples Input 3 3 7 4 2 6 5 3 7 6 Output 11 2 2 3 Input 2 5 6 1 3 3 5 Output 1 1 1 Note In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11. In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. Tags: dp, sortings Correct Solution: ``` n = int(input()) items = [] max_time = 0 for i in range(1,n+1): t,d,p = map(int,input().split()) max_time = max(max_time, d) items.append((t,d,p,i)) items.sort(key=lambda x: x[1]) dp = [[(0,[]) for _ in range(n+1)] for _ in range(max_time+1)] for time in range(1, max_time+1): for it in range(1, n+1): if time < items[it-1][0] or time >= items[it-1][1]: dp[time][it] = max(dp[time][it-1], dp[time-1][it]) else: pick = dp[time-items[it-1][0]][it-1][0] + items[it-1][2] if dp[time][it-1][0] > pick : dp[time][it] = max(dp[time][it-1], dp[time-1][it]) else: dp[time][it] = (dp[time-items[it-1][0]][it-1][0] + items[it-1][2], list(dp[time-items[it-1][0]][it-1][1])) dp[time][it][1].append(items[it-1][3]) #print(dp) res = max(dp[max_time]) print(res[0]) print(len(res[1])) print(*res[1]) ```
102,604
[ 0.41015625, 0.1705322265625, 0.1280517578125, 0.30712890625, -0.373291015625, -0.369140625, -0.31201171875, -0.015594482421875, 0.5302734375, 0.412841796875, 0.86279296875, -0.09783935546875, 0.348388671875, -0.5859375, -0.45068359375, -0.1407470703125, -0.5283203125, -0.3056640625...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is in really serious trouble β€” his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β€” the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β‰₯ di, then i-th item cannot be saved. Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β€” in ta + tb seconds after fire started. Input The first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of items in Polycarp's house. Each of the following n lines contains three integers ti, di, pi (1 ≀ ti ≀ 20, 1 ≀ di ≀ 2 000, 1 ≀ pi ≀ 20) β€” the time needed to save the item i, the time after which the item i will burn completely and the value of item i. Output In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β€” the number of items in the desired set. In the third line print m distinct integers β€” numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them. Examples Input 3 3 7 4 2 6 5 3 7 6 Output 11 2 2 3 Input 2 5 6 1 3 3 5 Output 1 1 1 Note In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11. In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. Tags: dp, sortings Correct Solution: ``` from functools import lru_cache def readints(): return [int(obj) for obj in input().strip().split()] class Solver: def main(self): n = readints()[0] self.t, self.d, self.p = [], [], [] for i in range(n): t1, d1, p1 = readints() self.t.append(t1) self.d.append(d1) self.p.append(p1) self.backtrack = [] sd = max(self.d) + 1 for i in range(n+1): self.backtrack.append([]) for j in range(sd): self.backtrack[i].append(0) triples = zip(self.t, self.d, self.p, range(1, n+1)) triples = sorted(triples, key=lambda x: x[1]) self.t, self.d, self.p, self.indexes = [0], [0], [0], [] for i in range(n): self.t.append(triples[i][0]) self.d.append(triples[i][1]) self.p.append(triples[i][2]) self.indexes.append(triples[i][3]) self.f = [] for i in range(n+1): self.f.append([]) for j in range(sd): self.f[i].append(0) for i in range(1, n+1): for d in range(sd): if d - self.t[i] >= 0 and d < self.d[i] and self.t[i] < self.d[i]: data = self.f[i - 1][d - self.t[i]] if data + self.p[i] > self.f[i][d]: self.f[i][d] = data + self.p[i] self.backtrack[i][d] = i data = self.f[i - 1][d] if data > self.f[i][d]: self.f[i][d] = data self.backtrack[i][d] = 0 ans = 0 res = [] best = None for i in range(sd): data = self.f[n][i] if data > ans: ans = data best = (n, i) if best is None: print('0\n0\n') return i = best[0] s = best[1] while i > 0: if self.backtrack[i][s] != 0: res.append(self.backtrack[i][s]) s -= self.t[self.backtrack[i][s]] i -= 1 print(ans) print(len(res)) print(' '.join(str(self.indexes[item - 1]) for item in reversed(res))) Solver().main() ```
102,605
[ 0.41015625, 0.1705322265625, 0.1280517578125, 0.30712890625, -0.373291015625, -0.369140625, -0.31201171875, -0.015594482421875, 0.5302734375, 0.412841796875, 0.86279296875, -0.09783935546875, 0.348388671875, -0.5859375, -0.45068359375, -0.1407470703125, -0.5283203125, -0.3056640625...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is in really serious trouble β€” his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β€” the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β‰₯ di, then i-th item cannot be saved. Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β€” in ta + tb seconds after fire started. Input The first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of items in Polycarp's house. Each of the following n lines contains three integers ti, di, pi (1 ≀ ti ≀ 20, 1 ≀ di ≀ 2 000, 1 ≀ pi ≀ 20) β€” the time needed to save the item i, the time after which the item i will burn completely and the value of item i. Output In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β€” the number of items in the desired set. In the third line print m distinct integers β€” numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them. Examples Input 3 3 7 4 2 6 5 3 7 6 Output 11 2 2 3 Input 2 5 6 1 3 3 5 Output 1 1 1 Note In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11. In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. Tags: dp, sortings Correct Solution: ``` import sys input = lambda : sys.stdin.readline().rstrip() sys.setrecursionlimit(2*10**5+10) write = lambda x: sys.stdout.write(x+"\n") debug = lambda x: sys.stderr.write(x+"\n") writef = lambda x: print("{:.12f}".format(x)) n = int(input()) tdp = [list(map(int, input().split())) for _ in range(n)] index = list(range(n)) index.sort(key=lambda i: tdp[i][1]) # tdp.sort(key=lambda item: (item[1])) T = max([item[1] for item in tdp]) dp = [0]*(T+1) ps = [] # for i,(t,d,p) in enumerate(tdp): for ind in range(n): i = index[ind] t,d,p = tdp[i] ndp = dp[:] prv = [(k, -1) for k in range(T+1)] for j in range(T+1): if j+t<d: if ndp[j+t]<dp[j]+p: ndp[j+t] = dp[j]+p prv[j+t] = (j, i) dp = ndp ps.append(prv) # print(dp) ans = max(dp) res = [] for j in range(T+1)[::-1]: if dp[j]==ans: for i in range(n)[::-1]: jj,ii = ps[i][j] if ii>=0: res.append(ii+1) j = jj break res = res[::-1] print(ans) print(len(res)) write(" ".join(map(str, res))) ```
102,606
[ 0.41015625, 0.1705322265625, 0.1280517578125, 0.30712890625, -0.373291015625, -0.369140625, -0.31201171875, -0.015594482421875, 0.5302734375, 0.412841796875, 0.86279296875, -0.09783935546875, 0.348388671875, -0.5859375, -0.45068359375, -0.1407470703125, -0.5283203125, -0.3056640625...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is in really serious trouble β€” his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β€” the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β‰₯ di, then i-th item cannot be saved. Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β€” in ta + tb seconds after fire started. Input The first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of items in Polycarp's house. Each of the following n lines contains three integers ti, di, pi (1 ≀ ti ≀ 20, 1 ≀ di ≀ 2 000, 1 ≀ pi ≀ 20) β€” the time needed to save the item i, the time after which the item i will burn completely and the value of item i. Output In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β€” the number of items in the desired set. In the third line print m distinct integers β€” numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them. Examples Input 3 3 7 4 2 6 5 3 7 6 Output 11 2 2 3 Input 2 5 6 1 3 3 5 Output 1 1 1 Note In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11. In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. Tags: dp, sortings Correct Solution: ``` P = [0] * 2001 S = [[] for i in range(2001)] q = [list(map(int, input().split())) + [str(i + 1)] for i in range(int(input()))] q.sort(key=lambda q: q[1]) for t, d, p, i in q: for x in range(t, d)[::-1]: if P[x] < P[x - t] + p: P[x] = P[x - t] + p S[x] = S[x - t] + [i] k = P.index(max(P)) print('\n'.join([str(P[k]), str(len(S[k])), ' '.join(S[k])])) ```
102,607
[ 0.41015625, 0.1705322265625, 0.1280517578125, 0.30712890625, -0.373291015625, -0.369140625, -0.31201171875, -0.015594482421875, 0.5302734375, 0.412841796875, 0.86279296875, -0.09783935546875, 0.348388671875, -0.5859375, -0.45068359375, -0.1407470703125, -0.5283203125, -0.3056640625...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is in really serious trouble β€” his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β€” the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β‰₯ di, then i-th item cannot be saved. Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β€” in ta + tb seconds after fire started. Input The first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of items in Polycarp's house. Each of the following n lines contains three integers ti, di, pi (1 ≀ ti ≀ 20, 1 ≀ di ≀ 2 000, 1 ≀ pi ≀ 20) β€” the time needed to save the item i, the time after which the item i will burn completely and the value of item i. Output In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β€” the number of items in the desired set. In the third line print m distinct integers β€” numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them. Examples Input 3 3 7 4 2 6 5 3 7 6 Output 11 2 2 3 Input 2 5 6 1 3 3 5 Output 1 1 1 Note In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11. In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. Tags: dp, sortings Correct Solution: ``` from sys import stdin, stdout T = 2001 INF = int(1e9) n = int(stdin.readline()) items = [] for i in range(n): c, d, t = map(int, stdin.readline().split()) items.append((d, c, t, i+1)) items.sort() dp = [[None for i in range(T)] for j in range(n)] def solve(pos, time): if pos >= n or time >= T: return 0 if dp[pos][time] is not None: return dp[pos][time] d, c, t, i = items[pos] ans = solve(pos+1, time) if time + c < d: ans = max(ans, solve(pos+1, time + c) + t) dp[pos][time] = ans return ans ans = [] def recover(pos, time): global ans if pos >= n or time >= T: return d, c, t, i = items[pos] if solve(pos+1, time) == solve(pos, time): recover(pos+1, time) else: ans.append(i) recover(pos+1, time + c) stdout.write(str(solve(0, 0)) + '\n') recover(0, 0) stdout.write(str(len(ans)) + '\n') for i in ans: stdout.write(str(i) + ' ') stdout.write('\n') ```
102,608
[ 0.41015625, 0.1705322265625, 0.1280517578125, 0.30712890625, -0.373291015625, -0.369140625, -0.31201171875, -0.015594482421875, 0.5302734375, 0.412841796875, 0.86279296875, -0.09783935546875, 0.348388671875, -0.5859375, -0.45068359375, -0.1407470703125, -0.5283203125, -0.3056640625...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is in really serious trouble β€” his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β€” the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β‰₯ di, then i-th item cannot be saved. Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β€” in ta + tb seconds after fire started. Input The first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of items in Polycarp's house. Each of the following n lines contains three integers ti, di, pi (1 ≀ ti ≀ 20, 1 ≀ di ≀ 2 000, 1 ≀ pi ≀ 20) β€” the time needed to save the item i, the time after which the item i will burn completely and the value of item i. Output In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β€” the number of items in the desired set. In the third line print m distinct integers β€” numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them. Examples Input 3 3 7 4 2 6 5 3 7 6 Output 11 2 2 3 Input 2 5 6 1 3 3 5 Output 1 1 1 Note In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11. In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. Tags: dp, sortings Correct Solution: ``` n = int(input()) a = [] for i in range(n): t,d,p = map(int,input().split()) a.append([t,d,p,i+1]) a.sort(key = lambda x: x[1]) d = {0: [0,[]]} for i in a: e = {} for j in d: if d[j][0] + i[0] < i[1]: if j + i[2] in d: if d[j][0]+i[0] < d[j+i[2]][0]: e[j+i[2]] = [d[j][0]+i[0],d[j][1]+[i[3]]] else: e[j+i[2]] = [d[j][0]+i[0],d[j][1]+[i[3]]] d.update(e) t = max(d) print(t) k = d[t][1] print(len(k)) k = list(map(str,k)) print(' '.join(k)) ```
102,609
[ 0.41015625, 0.1705322265625, 0.1280517578125, 0.30712890625, -0.373291015625, -0.369140625, -0.31201171875, -0.015594482421875, 0.5302734375, 0.412841796875, 0.86279296875, -0.09783935546875, 0.348388671875, -0.5859375, -0.45068359375, -0.1407470703125, -0.5283203125, -0.3056640625...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp is in really serious trouble β€” his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β€” the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β‰₯ di, then i-th item cannot be saved. Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β€” in ta + tb seconds after fire started. Input The first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of items in Polycarp's house. Each of the following n lines contains three integers ti, di, pi (1 ≀ ti ≀ 20, 1 ≀ di ≀ 2 000, 1 ≀ pi ≀ 20) β€” the time needed to save the item i, the time after which the item i will burn completely and the value of item i. Output In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β€” the number of items in the desired set. In the third line print m distinct integers β€” numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them. Examples Input 3 3 7 4 2 6 5 3 7 6 Output 11 2 2 3 Input 2 5 6 1 3 3 5 Output 1 1 1 Note In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11. In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. Tags: dp, sortings Correct Solution: ``` import os import sys import re from collections import OrderedDict if 'PYCHARM' in os.environ: sys.stdin = open('in', 'r') n = int(input()) things = [] for i in range(n): t, d, p = map(int, input().split()) things.append((d, t, p, i + 1)) things.sort() D = 2001 f = [[0] * D] w = [[False] * D] for i in range(n): thing = things[i] w.append([False] * D) f.append(list(f[i])) for j in range(D): ni = j + thing[1] nv = f[i][j] + thing[2] if ni < thing[0]: if f[i + 1][ni] < nv: f[i + 1][ni] = nv w[i + 1][ni] = True ind = 0 for i in range(D): if f[n][i] > f[n][ind]: ind = i print(f[n][ind]) ans = [] for i in range(n, 0, -1): if w[i][ind]: ind -= things[i - 1][1] ans.append(things[i - 1][3]) print(len(ans)) print(*reversed(ans)) ```
102,610
[ 0.41015625, 0.1705322265625, 0.1280517578125, 0.30712890625, -0.373291015625, -0.369140625, -0.31201171875, -0.015594482421875, 0.5302734375, 0.412841796875, 0.86279296875, -0.09783935546875, 0.348388671875, -0.5859375, -0.45068359375, -0.1407470703125, -0.5283203125, -0.3056640625...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is in really serious trouble β€” his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β€” the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β‰₯ di, then i-th item cannot be saved. Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β€” in ta + tb seconds after fire started. Input The first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of items in Polycarp's house. Each of the following n lines contains three integers ti, di, pi (1 ≀ ti ≀ 20, 1 ≀ di ≀ 2 000, 1 ≀ pi ≀ 20) β€” the time needed to save the item i, the time after which the item i will burn completely and the value of item i. Output In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β€” the number of items in the desired set. In the third line print m distinct integers β€” numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them. Examples Input 3 3 7 4 2 6 5 3 7 6 Output 11 2 2 3 Input 2 5 6 1 3 3 5 Output 1 1 1 Note In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11. In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. Submitted Solution: ``` import copy n = int(input()) arr = [] m = 0 for er in range(n): temp = list(map(int,input().split(" "))) temp.append(er+1) if(temp[0]<temp[1]): arr.append(temp) if(temp[1]>m): m = temp[1] else: n-=1 arr.sort(key = lambda x:x[1]) #print(arr) temp=[] for i in range(n): temp.append([0]) com = [] com.append(temp) total = [0,0] for i in range(1,m+1): temp = [] for j in range(n+1): if(j==0): temp.append([0]) else: p=arr[j-1] if(p[0]>i or p[1]<=i): temp.append(temp[j-1]) else: te = i - p[0] ty = copy.deepcopy(com[te][j-1]) ty[0]+=p[2] ty.append(j) if(total[0]<ty[0]): total = ty if(temp[j-1][0]<ty[0]): temp.append(ty) else: temp.append(temp[j-1]) #print(temp , " temp") com.append(temp) #print(com) print(total[0]) if(total[0]>0): print(len(total)-1) for i in range(1,len(total)): print(arr[total[i]-1][3] , end = " ") else: print("0") ``` Yes
102,611
[ 0.49072265625, 0.25390625, 0.1114501953125, 0.29248046875, -0.43017578125, -0.2357177734375, -0.382568359375, 0.032196044921875, 0.54248046875, 0.402587890625, 0.8125, -0.09027099609375, 0.2802734375, -0.58203125, -0.426513671875, -0.178955078125, -0.46044921875, -0.33349609375, ...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is in really serious trouble β€” his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β€” the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β‰₯ di, then i-th item cannot be saved. Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β€” in ta + tb seconds after fire started. Input The first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of items in Polycarp's house. Each of the following n lines contains three integers ti, di, pi (1 ≀ ti ≀ 20, 1 ≀ di ≀ 2 000, 1 ≀ pi ≀ 20) β€” the time needed to save the item i, the time after which the item i will burn completely and the value of item i. Output In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β€” the number of items in the desired set. In the third line print m distinct integers β€” numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them. Examples Input 3 3 7 4 2 6 5 3 7 6 Output 11 2 2 3 Input 2 5 6 1 3 3 5 Output 1 1 1 Note In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11. In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. Submitted Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys mod = 10 ** 9 + 7 mod1 = 998244353 #setrecursionlimit(300000) # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 sys.setrecursionlimit(300000) 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----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=0, func=lambda a, b: max(a, b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] < key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ n=int(input()) ma=0 l=[] time=[] for i in range(n): s=list(map(int,input().split())) ma=max(ma,s[1]) l.append(s+[i+1]) time.append(s[1]) l=sort_list(l,time) dp=[[[] for i in range(ma+1)]for j in range(n)] dp1=[[0 for i in range(ma+1)]for j in range(n)] for i in range(ma+1): if l[0][0]<i<=l[0][1]: dp1[0][i]=l[0][2] dp[0][i]=[l[0][-1]] for i in range(1,n): for j in range(ma+1): if j-l[i][0]>0 and j<=l[i][1]: dp1[i][j]=max(dp1[i-1][j],dp1[i-1][j-l[i][0]]+l[i][2]) if dp1[i][j]==dp1[i-1][j]: dp[i][j]=dp[i-1][j]+[] else: dp[i][j]=dp[i-1][j-l[i][0]]+[l[i][-1]] else: dp1[i][j]=dp1[i-1][j] dp[i][j]=dp[i-1][j]+[] ans=max(dp1[-1]) print(ans) ind=dp1[-1].index(ans) print(len(dp[-1][ind])) print(*dp[-1][ind]) ``` Yes
102,612
[ 0.49072265625, 0.25390625, 0.1114501953125, 0.29248046875, -0.43017578125, -0.2357177734375, -0.382568359375, 0.032196044921875, 0.54248046875, 0.402587890625, 0.8125, -0.09027099609375, 0.2802734375, -0.58203125, -0.426513671875, -0.178955078125, -0.46044921875, -0.33349609375, ...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is in really serious trouble β€” his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β€” the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β‰₯ di, then i-th item cannot be saved. Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β€” in ta + tb seconds after fire started. Input The first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of items in Polycarp's house. Each of the following n lines contains three integers ti, di, pi (1 ≀ ti ≀ 20, 1 ≀ di ≀ 2 000, 1 ≀ pi ≀ 20) β€” the time needed to save the item i, the time after which the item i will burn completely and the value of item i. Output In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β€” the number of items in the desired set. In the third line print m distinct integers β€” numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them. Examples Input 3 3 7 4 2 6 5 3 7 6 Output 11 2 2 3 Input 2 5 6 1 3 3 5 Output 1 1 1 Note In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11. In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. Submitted Solution: ``` from sys import stdin n = int(stdin.readline()) items = [] for i in range(n): t,d,p = [int(x) for x in stdin.readline().split()] items.append((d,t,p,i)) items.sort() mem = [{} for x in range(n)] mem2 = [{} for x in range(n)] def best(time,x): time += items[x][1] if time in mem[x]: return mem[x][time] if time >= items[x][0]: mem[x][time] = 0 mem2[x][time] = -1 return 0 top = 0 top2 = -1 for i in range(x+1,n): temp = best(time,i) if temp > top: top = temp top2 = i mem[x][time] = top+items[x][2] mem2[x][time] = top2 return mem[x][time] top = -1 l = [] for x in range(n): b = best(0,x) if b > top: top = b #print('new',x,top) l = [] c = x time = 0 while c != -1: time += items[c][1] l.append(items[c][3]) if time in mem2[c]: c = mem2[c][time] else: c = -1 print(top) if top != 0: print(len(l)) print(' '.join([str(x+1) for x in l])) else: print(0) print() ``` Yes
102,613
[ 0.49072265625, 0.25390625, 0.1114501953125, 0.29248046875, -0.43017578125, -0.2357177734375, -0.382568359375, 0.032196044921875, 0.54248046875, 0.402587890625, 0.8125, -0.09027099609375, 0.2802734375, -0.58203125, -0.426513671875, -0.178955078125, -0.46044921875, -0.33349609375, ...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is in really serious trouble β€” his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β€” the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β‰₯ di, then i-th item cannot be saved. Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β€” in ta + tb seconds after fire started. Input The first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of items in Polycarp's house. Each of the following n lines contains three integers ti, di, pi (1 ≀ ti ≀ 20, 1 ≀ di ≀ 2 000, 1 ≀ pi ≀ 20) β€” the time needed to save the item i, the time after which the item i will burn completely and the value of item i. Output In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β€” the number of items in the desired set. In the third line print m distinct integers β€” numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them. Examples Input 3 3 7 4 2 6 5 3 7 6 Output 11 2 2 3 Input 2 5 6 1 3 3 5 Output 1 1 1 Note In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11. In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. Submitted Solution: ``` #Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase import io from fractions import Fraction import collections from itertools import permutations from collections import defaultdict from collections import deque from collections import Counter import threading #sys.setrecursionlimit(300000) #threading.stack_size(10**8) 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----------------------------------------------------- #mod = 9223372036854775807 class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: max(a,b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) class SegmentTree1: def __init__(self, data, default=0, func=lambda a, b: a+b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) MOD=10**9+7 class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD mod=10**9+7 omod=998244353 #------------------------------------------------------------------------- prime = [True for i in range(10001)] prime[0]=prime[1]=False #pp=[0]*10000 def SieveOfEratosthenes(n=10000): p = 2 c=0 while (p <= n): if (prime[p] == True): c+=1 for i in range(p, n+1, p): #pp[i]=1 prime[i] = False p += 1 #-----------------------------------DSU-------------------------------------------------- class DSU: def __init__(self, R, C): #R * C is the source, and isn't a grid square self.par = range(R*C + 1) self.rnk = [0] * (R*C + 1) self.sz = [1] * (R*C + 1) def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): xr, yr = self.find(x), self.find(y) if xr == yr: return if self.rnk[xr] < self.rnk[yr]: xr, yr = yr, xr if self.rnk[xr] == self.rnk[yr]: self.rnk[xr] += 1 self.par[yr] = xr self.sz[xr] += self.sz[yr] def size(self, x): return self.sz[self.find(x)] def top(self): # Size of component at ephemeral "source" node at index R*C, # minus 1 to not count the source itself in the size return self.size(len(self.sz) - 1) - 1 #---------------------------------Lazy Segment Tree-------------------------------------- # https://github.com/atcoder/ac-library/blob/master/atcoder/lazysegtree.hpp class LazySegTree: def __init__(self, _op, _e, _mapping, _composition, _id, v): def set(p, x): assert 0 <= p < _n p += _size for i in range(_log, 0, -1): _push(p >> i) _d[p] = x for i in range(1, _log + 1): _update(p >> i) def get(p): assert 0 <= p < _n p += _size for i in range(_log, 0, -1): _push(p >> i) return _d[p] def prod(l, r): assert 0 <= l <= r <= _n if l == r: return _e l += _size r += _size for i in range(_log, 0, -1): if ((l >> i) << i) != l: _push(l >> i) if ((r >> i) << i) != r: _push(r >> i) sml = _e smr = _e while l < r: if l & 1: sml = _op(sml, _d[l]) l += 1 if r & 1: r -= 1 smr = _op(_d[r], smr) l >>= 1 r >>= 1 return _op(sml, smr) def apply(l, r, f): assert 0 <= l <= r <= _n if l == r: return l += _size r += _size for i in range(_log, 0, -1): if ((l >> i) << i) != l: _push(l >> i) if ((r >> i) << i) != r: _push((r - 1) >> i) l2 = l r2 = r while l < r: if l & 1: _all_apply(l, f) l += 1 if r & 1: r -= 1 _all_apply(r, f) l >>= 1 r >>= 1 l = l2 r = r2 for i in range(1, _log + 1): if ((l >> i) << i) != l: _update(l >> i) if ((r >> i) << i) != r: _update((r - 1) >> i) def _update(k): _d[k] = _op(_d[2 * k], _d[2 * k + 1]) def _all_apply(k, f): _d[k] = _mapping(f, _d[k]) if k < _size: _lz[k] = _composition(f, _lz[k]) def _push(k): _all_apply(2 * k, _lz[k]) _all_apply(2 * k + 1, _lz[k]) _lz[k] = _id _n = len(v) _log = _n.bit_length() _size = 1 << _log _d = [_e] * (2 * _size) _lz = [_id] * _size for i in range(_n): _d[_size + i] = v[i] for i in range(_size - 1, 0, -1): _update(i) self.set = set self.get = get self.prod = prod self.apply = apply MIL = 1 << 20 def makeNode(total, count): # Pack a pair into a float return (total * MIL) + count def getTotal(node): return math.floor(node / MIL) def getCount(node): return node - getTotal(node) * MIL nodeIdentity = makeNode(0.0, 0.0) def nodeOp(node1, node2): return node1 + node2 # Equivalent to the following: return makeNode( getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2) ) identityMapping = -1 def mapping(tag, node): if tag == identityMapping: return node # If assigned, new total is the number assigned times count count = getCount(node) return makeNode(tag * count, count) def composition(mapping1, mapping2): # If assigned multiple times, take first non-identity assignment return mapping1 if mapping1 != identityMapping else mapping2 #---------------------------------Pollard rho-------------------------------------------- def memodict(f): """memoization decorator for a function taking a single argument""" class memodict(dict): def __missing__(self, key): ret = self[key] = f(key) return ret return memodict().__getitem__ def pollard_rho(n): """returns a random factor of n""" if n & 1 == 0: return 2 if n % 3 == 0: return 3 s = ((n - 1) & (1 - n)).bit_length() - 1 d = n >> s for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]: p = pow(a, d, n) if p == 1 or p == n - 1 or a % n == 0: continue for _ in range(s): prev = p p = (p * p) % n if p == 1: return math.gcd(prev - 1, n) if p == n - 1: break else: for i in range(2, n): x, y = i, (i * i + 1) % n f = math.gcd(abs(x - y), n) while f == 1: x, y = (x * x + 1) % n, (y * y + 1) % n y = (y * y + 1) % n f = math.gcd(abs(x - y), n) if f != n: return f return n @memodict def prime_factors(n): """returns a Counter of the prime factorization of n""" if n <= 1: return Counter() f = pollard_rho(n) return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f) def distinct_factors(n): """returns a list of all distinct factors of n""" factors = [1] for p, exp in prime_factors(n).items(): factors += [p**i * factor for factor in factors for i in range(1, exp + 1)] return factors def all_factors(n): """returns a sorted list of all distinct factors of n""" small, large = [], [] for i in range(1, int(n**0.5) + 1, 2 if n & 1 else 1): if not n % i: small.append(i) large.append(n // i) if small[-1] == large[-1]: large.pop() large.reverse() small.extend(large) return small #---------------------------------Binary Search------------------------------------------ def binarySearch(arr, n,i, key): left = 0 right = n-1 mid = 0 res=n while (left <= right): mid = (right + left)//2 if (arr[mid][i] > key): res=mid right = mid-1 else: left = mid + 1 return res def binarySearch1(arr, n,i, key): left = 0 right = n-1 mid = 0 res=-1 while (left <= right): mid = (right + left)//2 if (arr[mid][i] > key): right = mid-1 else: res=mid left = mid + 1 return res #---------------------------------running code------------------------------------------ #Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase import io from fractions import Fraction import collections from itertools import permutations from collections import defaultdict from collections import deque from collections import Counter import threading #sys.setrecursionlimit(300000) #threading.stack_size(10**8) 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----------------------------------------------------- #mod = 9223372036854775807 class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: max(a,b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) class SegmentTree1: def __init__(self, data, default=0, func=lambda a, b: a+b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) MOD=10**9+7 class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD mod=10**9+7 omod=998244353 #------------------------------------------------------------------------- prime = [True for i in range(10001)] prime[0]=prime[1]=False #pp=[0]*10000 def SieveOfEratosthenes(n=10000): p = 2 c=0 while (p <= n): if (prime[p] == True): c+=1 for i in range(p, n+1, p): #pp[i]=1 prime[i] = False p += 1 #-----------------------------------DSU-------------------------------------------------- class DSU: def __init__(self, R, C): #R * C is the source, and isn't a grid square self.par = range(R*C + 1) self.rnk = [0] * (R*C + 1) self.sz = [1] * (R*C + 1) def find(self, x): if self.par[x] != x: self.par[x] = self.find(self.par[x]) return self.par[x] def union(self, x, y): xr, yr = self.find(x), self.find(y) if xr == yr: return if self.rnk[xr] < self.rnk[yr]: xr, yr = yr, xr if self.rnk[xr] == self.rnk[yr]: self.rnk[xr] += 1 self.par[yr] = xr self.sz[xr] += self.sz[yr] def size(self, x): return self.sz[self.find(x)] def top(self): # Size of component at ephemeral "source" node at index R*C, # minus 1 to not count the source itself in the size return self.size(len(self.sz) - 1) - 1 #---------------------------------Lazy Segment Tree-------------------------------------- # https://github.com/atcoder/ac-library/blob/master/atcoder/lazysegtree.hpp class LazySegTree: def __init__(self, _op, _e, _mapping, _composition, _id, v): def set(p, x): assert 0 <= p < _n p += _size for i in range(_log, 0, -1): _push(p >> i) _d[p] = x for i in range(1, _log + 1): _update(p >> i) def get(p): assert 0 <= p < _n p += _size for i in range(_log, 0, -1): _push(p >> i) return _d[p] def prod(l, r): assert 0 <= l <= r <= _n if l == r: return _e l += _size r += _size for i in range(_log, 0, -1): if ((l >> i) << i) != l: _push(l >> i) if ((r >> i) << i) != r: _push(r >> i) sml = _e smr = _e while l < r: if l & 1: sml = _op(sml, _d[l]) l += 1 if r & 1: r -= 1 smr = _op(_d[r], smr) l >>= 1 r >>= 1 return _op(sml, smr) def apply(l, r, f): assert 0 <= l <= r <= _n if l == r: return l += _size r += _size for i in range(_log, 0, -1): if ((l >> i) << i) != l: _push(l >> i) if ((r >> i) << i) != r: _push((r - 1) >> i) l2 = l r2 = r while l < r: if l & 1: _all_apply(l, f) l += 1 if r & 1: r -= 1 _all_apply(r, f) l >>= 1 r >>= 1 l = l2 r = r2 for i in range(1, _log + 1): if ((l >> i) << i) != l: _update(l >> i) if ((r >> i) << i) != r: _update((r - 1) >> i) def _update(k): _d[k] = _op(_d[2 * k], _d[2 * k + 1]) def _all_apply(k, f): _d[k] = _mapping(f, _d[k]) if k < _size: _lz[k] = _composition(f, _lz[k]) def _push(k): _all_apply(2 * k, _lz[k]) _all_apply(2 * k + 1, _lz[k]) _lz[k] = _id _n = len(v) _log = _n.bit_length() _size = 1 << _log _d = [_e] * (2 * _size) _lz = [_id] * _size for i in range(_n): _d[_size + i] = v[i] for i in range(_size - 1, 0, -1): _update(i) self.set = set self.get = get self.prod = prod self.apply = apply MIL = 1 << 20 def makeNode(total, count): # Pack a pair into a float return (total * MIL) + count def getTotal(node): return math.floor(node / MIL) def getCount(node): return node - getTotal(node) * MIL nodeIdentity = makeNode(0.0, 0.0) def nodeOp(node1, node2): return node1 + node2 # Equivalent to the following: return makeNode( getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2) ) identityMapping = -1 def mapping(tag, node): if tag == identityMapping: return node # If assigned, new total is the number assigned times count count = getCount(node) return makeNode(tag * count, count) def composition(mapping1, mapping2): # If assigned multiple times, take first non-identity assignment return mapping1 if mapping1 != identityMapping else mapping2 #---------------------------------Pollard rho-------------------------------------------- def memodict(f): """memoization decorator for a function taking a single argument""" class memodict(dict): def __missing__(self, key): ret = self[key] = f(key) return ret return memodict().__getitem__ def pollard_rho(n): """returns a random factor of n""" if n & 1 == 0: return 2 if n % 3 == 0: return 3 s = ((n - 1) & (1 - n)).bit_length() - 1 d = n >> s for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]: p = pow(a, d, n) if p == 1 or p == n - 1 or a % n == 0: continue for _ in range(s): prev = p p = (p * p) % n if p == 1: return math.gcd(prev - 1, n) if p == n - 1: break else: for i in range(2, n): x, y = i, (i * i + 1) % n f = math.gcd(abs(x - y), n) while f == 1: x, y = (x * x + 1) % n, (y * y + 1) % n y = (y * y + 1) % n f = math.gcd(abs(x - y), n) if f != n: return f return n @memodict def prime_factors(n): """returns a Counter of the prime factorization of n""" if n <= 1: return Counter() f = pollard_rho(n) return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f) def distinct_factors(n): """returns a list of all distinct factors of n""" factors = [1] for p, exp in prime_factors(n).items(): factors += [p**i * factor for factor in factors for i in range(1, exp + 1)] return factors def all_factors(n): """returns a sorted list of all distinct factors of n""" small, large = [], [] for i in range(1, int(n**0.5) + 1, 2 if n & 1 else 1): if not n % i: small.append(i) large.append(n // i) if small[-1] == large[-1]: large.pop() large.reverse() small.extend(large) return small #---------------------------------Binary Search------------------------------------------ def binarySearch(arr, n,i, key): left = 0 right = n-1 mid = 0 res=n while (left <= right): mid = (right + left)//2 if (arr[mid][i] > key): res=mid right = mid-1 else: left = mid + 1 return res def binarySearch1(arr, n,i, key): left = 0 right = n-1 mid = 0 res=-1 while (left <= right): mid = (right + left)//2 if (arr[mid][i] > key): right = mid-1 else: res=mid left = mid + 1 return res #---------------------------------running code------------------------------------------ t=1 #t=int(input()) for _ in range (t): n=int(input()) #n,x=map(int,input().split()) #a=list(map(int,input().split())) #b=list(map(int,input().split())) #s=input() #n=len(s) a=[] m=0 for i in range (n): tm,d,p=map(int,input().split()) a.append([d,tm,p,i+1]) m=max(m,d) a.sort() dp=[0]*(m+1) result=[set()]*(m+1) for i in range (n): for j in range (a[i][0]-1,a[i][1]-1,-1): curr=dp[j-a[i][1]]+a[i][2] if curr>dp[j]: dp[j]=curr result[j]=result[j-a[i][1]].copy() result[j].add(a[i][3]) #print(dp) #print(result) mx=max(dp) ans=None for i in range (m+1): if dp[i]==mx: ans=result[i] print(mx) print(len(ans)) print(*ans) ``` Yes
102,614
[ 0.49072265625, 0.25390625, 0.1114501953125, 0.29248046875, -0.43017578125, -0.2357177734375, -0.382568359375, 0.032196044921875, 0.54248046875, 0.402587890625, 0.8125, -0.09027099609375, 0.2802734375, -0.58203125, -0.426513671875, -0.178955078125, -0.46044921875, -0.33349609375, ...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is in really serious trouble β€” his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β€” the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β‰₯ di, then i-th item cannot be saved. Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β€” in ta + tb seconds after fire started. Input The first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of items in Polycarp's house. Each of the following n lines contains three integers ti, di, pi (1 ≀ ti ≀ 20, 1 ≀ di ≀ 2 000, 1 ≀ pi ≀ 20) β€” the time needed to save the item i, the time after which the item i will burn completely and the value of item i. Output In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β€” the number of items in the desired set. In the third line print m distinct integers β€” numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them. Examples Input 3 3 7 4 2 6 5 3 7 6 Output 11 2 2 3 Input 2 5 6 1 3 3 5 Output 1 1 1 Note In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11. In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. Submitted Solution: ``` import os import sys import re from collections import OrderedDict if 'PYCHARM' in os.environ: sys.stdin = open('in', 'r') n = int(input()) things = [] for i in range(n): t, d, p = map(int, input().split()) things.append((d, t, p, i + 1)) things.sort() D = 2001 f = [0] * D p = [-1] * D pi = [-1] * D for thing in things: for i in reversed(range(D)): ni = i + thing[1] nv = f[i] + thing[2] if ni <= thing[0]: if f[ni] < nv: f[ni] = nv p[ni] = thing[3] pi[ni] = i ind = 0 for i in range(0, D): if f[i] > f[ind]: ind = i print(f[ind]) ans = [] while ind: ans.append(p[ind]) ind = pi[ind] print(len(ans)) print(*reversed(ans)) ``` No
102,615
[ 0.49072265625, 0.25390625, 0.1114501953125, 0.29248046875, -0.43017578125, -0.2357177734375, -0.382568359375, 0.032196044921875, 0.54248046875, 0.402587890625, 0.8125, -0.09027099609375, 0.2802734375, -0.58203125, -0.426513671875, -0.178955078125, -0.46044921875, -0.33349609375, ...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is in really serious trouble β€” his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β€” the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β‰₯ di, then i-th item cannot be saved. Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β€” in ta + tb seconds after fire started. Input The first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of items in Polycarp's house. Each of the following n lines contains three integers ti, di, pi (1 ≀ ti ≀ 20, 1 ≀ di ≀ 2 000, 1 ≀ pi ≀ 20) β€” the time needed to save the item i, the time after which the item i will burn completely and the value of item i. Output In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β€” the number of items in the desired set. In the third line print m distinct integers β€” numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them. Examples Input 3 3 7 4 2 6 5 3 7 6 Output 11 2 2 3 Input 2 5 6 1 3 3 5 Output 1 1 1 Note In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11. In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. Submitted Solution: ``` # -*- coding: utf-8 -*- import math import collections import bisect import heapq import time import random """ created by shhuan at 2017/10/4 21:10 """ N = int(input()) M = [] for i in range(N): M.append([int(x) for x in input().split()]) N = len(M) T = [0] + [x[0] for x in M] D = [0] + [x[1] for x in M] P = [0] + [x[2] for x in M] dmax = max(D) # dp[t][i]即既间tε†…θƒ½ε€Ÿζ‹―ζ•‘ηš„ε‰iδΈͺη‰©ε“ηš„ζœ€ε€§η‰©ε“δ»·ε€Ό dp = [[0 for _ in range(N+1)] for _ in range(dmax)] track = [[0 for _ in range(N+1)] for _ in range(dmax)] for t in range(dmax): for i in range(1, N+1): ti = t-T[i] if T[i] <= t < D[i] and ti >= 0: dp[t][i] = max(dp[t][i-1], dp[ti][i-1] + P[i]) if dp[t][i-1] > dp[ti][i-1]+P[i]: track[t][i] = (t, i-1, -1) else: track[t][i] = (ti, i-1, i) else: dp[t][i] = dp[t][i-1] track[t][i] = (t, i-1, -1) print(dp[dmax-1][N]) t, i, j = dmax-1, N, -1 res = [] while t > 0 and i > 0: t, i, j = track[t][i] if j > 0: res.append(j) print(len(res)) print(' '.join([str(x) for x in reversed(res)])) ``` No
102,616
[ 0.49072265625, 0.25390625, 0.1114501953125, 0.29248046875, -0.43017578125, -0.2357177734375, -0.382568359375, 0.032196044921875, 0.54248046875, 0.402587890625, 0.8125, -0.09027099609375, 0.2802734375, -0.58203125, -0.426513671875, -0.178955078125, -0.46044921875, -0.33349609375, ...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is in really serious trouble β€” his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β€” the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β‰₯ di, then i-th item cannot be saved. Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β€” in ta + tb seconds after fire started. Input The first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of items in Polycarp's house. Each of the following n lines contains three integers ti, di, pi (1 ≀ ti ≀ 20, 1 ≀ di ≀ 2 000, 1 ≀ pi ≀ 20) β€” the time needed to save the item i, the time after which the item i will burn completely and the value of item i. Output In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β€” the number of items in the desired set. In the third line print m distinct integers β€” numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them. Examples Input 3 3 7 4 2 6 5 3 7 6 Output 11 2 2 3 Input 2 5 6 1 3 3 5 Output 1 1 1 Note In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11. In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. Submitted Solution: ``` def count_spaces(l, t, x): # up to ind x. total = prev = 0; n = len(l) for i in range(x + 1): total += l[i][1] - prev prev = l[i][1] + t[l[i][0]] return total def move_blocks(x, dist, l, t): # blocks up to x will move. last = -1 gaps = [] for i in range(x, 0, -1): gap = l[i][1] - (l[i - 1][1] + t[l[i - 1][0]]) gaps.append(gap) if dist > gap: dist -= gap else: if gap > dist: gaps[-1] = dist last = i dist = 0 break if dist > 0: last = 0 gaps.append(dist) #print(gaps, last, x, "ago") pref = 0 for j in range(last, x + 1): # == len(gaps), prob #pref += gaps[j - last] # 0 1 2.. pref += gaps[-(j - last + 1)] # -1 -2 -3.. l[j][1] -= pref def main(): n = int(input()) t = []; d = []; p = []; v = [] nu = 0 for i in range(n): ti, di, pi = map(int, input().split()) if ti >= di: continue di -= 1 t.append(ti); d.append(di); p.append(pi) v.append(nu) nu += 1 v.sort(key = lambda x : [p[x] / d[x], d[x]], reverse = True) l = [] #print(v) for idx in v: #print(l, "hello", idx) placed = False for j in range(len(l) - 1, -1, -1): el = l[j] #print(el, "jumankjo", d, t, idx) if d[idx] >= el[1] + t[el[0]]: # back of new after back of old placed = True front_diff = el[1] + t[el[0]] - (d[idx] - t[idx]) # overlap btwn old back and new front if j == len(l) - 1: back_diff = 0 else: #back_diff = max(0, d[idx] - (l[j + 1][1] + t[l[j + 1][0]])) # overlap btwn back of new and front of next old back_diff = max(0, d[idx] - l[j + 1][1]) if abs(front_diff) >= back_diff: diff = max(0, front_diff) + back_diff else: diff = back_diff + front_diff #print(front_diff, back_diff, diff) if diff == 0: #l.append((idx, d[idx] - t[idx])) l.insert(j + 1, [idx, d[idx] - t[idx]]) else: spaces = count_spaces(l, t, j) #print(spaces) if spaces >= diff: move_blocks(j, diff, l, t) #l.insert(j + 1, [idx, d[idx] - t[idx]]) #l.insert(j + 1, [idx, l[j][1] + t[l[j][0]]]) l.insert(j + 1, [idx, l[j][1] + t[l[j][0]] - back_diff]) break #print("apple", placed) if not placed: if len(l) == 0: l.append([idx, d[idx] - t[idx]]) elif l[0][1] >= t[idx]: #l.append((idx, l[0][1] - t[idx])) l.insert(0, [idx, l[0][1] - t[idx]]) o = []; total = 0 #print(l) for k in range(len(l)): total += p[l[k][0]] o.append(l[k][0] + 1) print(total) print(len(o)) print(*o) main() ''' try: main() except Exception as e: print(e) ''' ``` No
102,617
[ 0.49072265625, 0.25390625, 0.1114501953125, 0.29248046875, -0.43017578125, -0.2357177734375, -0.382568359375, 0.032196044921875, 0.54248046875, 0.402587890625, 0.8125, -0.09027099609375, 0.2802734375, -0.58203125, -0.426513671875, -0.178955078125, -0.46044921875, -0.33349609375, ...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp is in really serious trouble β€” his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di β€” the moment after which the item i will be completely burned and will no longer be valuable for him at all. In particular, if ti β‰₯ di, then i-th item cannot be saved. Given the values pi for each of the items, find a set of items that Polycarp can save such that the total value of this items is maximum possible. Polycarp saves the items one after another. For example, if he takes item a first, and then item b, then the item a will be saved in ta seconds, and the item b β€” in ta + tb seconds after fire started. Input The first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of items in Polycarp's house. Each of the following n lines contains three integers ti, di, pi (1 ≀ ti ≀ 20, 1 ≀ di ≀ 2 000, 1 ≀ pi ≀ 20) β€” the time needed to save the item i, the time after which the item i will burn completely and the value of item i. Output In the first line print the maximum possible total value of the set of saved items. In the second line print one integer m β€” the number of items in the desired set. In the third line print m distinct integers β€” numbers of the saved items in the order Polycarp saves them. Items are 1-indexed in the same order in which they appear in the input. If there are several answers, print any of them. Examples Input 3 3 7 4 2 6 5 3 7 6 Output 11 2 2 3 Input 2 5 6 1 3 3 5 Output 1 1 1 Note In the first example Polycarp will have time to save any two items, but in order to maximize the total value of the saved items, he must save the second and the third item. For example, he can firstly save the third item in 3 seconds, and then save the second item in another 2 seconds. Thus, the total value of the saved items will be 6 + 5 = 11. In the second example Polycarp can save only the first item, since even if he immediately starts saving the second item, he can save it in 3 seconds, but this item will already be completely burned by this time. Submitted Solution: ``` n = int(input()) t, d, p = [], [], [] for _ in range(n): a, b, c = map(int, input().split()) t.append(a); d.append(b); p.append(c) dp = [[0, -1] for i in range(10)] for i in range(1, 10): # dp[i] = dp[i - 1].copy() for j in range(n): if d[j] > i >= t[j] and dp[i][0] < p[j] + dp[i - t[j]][0]: dp[i][0] = p[j] + dp[i - t[j]][0] dp[i][1] = j print(max(dp)[0]) i = dp.index(max(dp)) ans = [] while i > 0 and dp[i][1] != -1: ans.append(dp[i][1] + 1) i = dp[i][1] print(len(ans)) print(*ans[::-1]) ``` No
102,618
[ 0.49072265625, 0.25390625, 0.1114501953125, 0.29248046875, -0.43017578125, -0.2357177734375, -0.382568359375, 0.032196044921875, 0.54248046875, 0.402587890625, 0.8125, -0.09027099609375, 0.2802734375, -0.58203125, -0.426513671875, -0.178955078125, -0.46044921875, -0.33349609375, ...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. Tags: dp Correct Solution: ``` # -*- coding: utf-8 -*- import sys from collections import deque, defaultdict, namedtuple from math import sqrt, factorial, gcd, ceil, atan, pi def input(): return sys.stdin.readline()[:-1] # warning not \n # def input(): return sys.stdin.buffer.readline().strip() # warning bytes # def input(): return sys.stdin.buffer.readline().decode('utf-8') import string import operator # string.ascii_lowercase from bisect import bisect_left, bisect_right from functools import lru_cache, reduce MOD = int(1e9)+7 INF = float('inf') def solve(): a, n, m = [int(x) for x in input().split()] rain = [0] * (a + 1) for _ in range(n): l, r = [int(x) for x in input().split()] for i in range(l + 1, r + 1): rain[i] = 1 umb = [] for _ in range(m): x, p = [int(x) for x in input().split()] umb.append((x, p)) umb.sort() dp = [INF for _ in range(a + 1)] dp[0] = 0 for i in range(1, a + 1): if rain[i]: for x, p in umb: if x >= i: break dp[i] = min(dp[i], dp[x] + p * (i - x)) else: dp[i] = dp[i-1] if dp[a] == INF: print(-1) else: print(dp[a]) t = 1 # t = int(input()) for case in range(1,t+1): ans = solve() """ 1 2 dp[x] = min() """ ```
102,673
[ 0.314697265625, 0.44482421875, 0.461181640625, 0.1304931640625, -0.41064453125, -0.3134765625, -0.3310546875, 0.0159454345703125, 0.420166015625, 0.73486328125, 0.75146484375, 0.0311431884765625, 0.0242156982421875, -0.7080078125, -0.147705078125, 0.1475830078125, -0.7705078125, -0...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. Tags: dp Correct Solution: ``` # Author: S Mahesh Raju # Username: maheshraju2020 # Date: 03/07/2020 from sys import stdin,stdout from math import gcd, ceil, sqrt from collections import Counter ii1 = lambda: int(stdin.readline().strip()) is1 = lambda: stdin.readline().strip() iia = lambda: list(map(int, stdin.readline().strip().split())) isa = lambda: stdin.readline().strip().split() mod = 1000000007 a, n, m = iia() rain = [] for _ in range(n): l, r = iia() for i in range(l, r): rain.append(i) umb = [] for _ in range(m): umb.append(iia()) rain.sort() umb.sort() dp = [0] * (a + 1) for i in range(a + 1): if i not in rain: if i != 0: dp[i] = dp[i - 1] else: for j in umb: if j[0] <= i: temp = (i + 1 - j[0]) * j[1] if j[0] - 1 >= 0: temp += dp[j[0] - 1] if dp[i] > 0: dp[i] = min(dp[i], temp) else: dp[i] = temp else: break # print(dp) if umb[0][0] > rain[0]: print(-1) else: print(dp[-1]) ```
102,674
[ 0.314697265625, 0.44482421875, 0.461181640625, 0.1304931640625, -0.41064453125, -0.3134765625, -0.3310546875, 0.0159454345703125, 0.420166015625, 0.73486328125, 0.75146484375, 0.0311431884765625, 0.0242156982421875, -0.7080078125, -0.147705078125, 0.1475830078125, -0.7705078125, -0...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. Tags: dp Correct Solution: ``` from bisect import bisect_left as bl from bisect import bisect_right as br from heapq import heappush,heappop,heapify import math from collections import * from functools import reduce,cmp_to_key import sys input = sys.stdin.readline from itertools import accumulate from functools import lru_cache M = mod = 998244353 def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))) def inv_mod(n):return pow(n, mod - 2, mod) def li():return [int(i) for i in input().rstrip('\n').split()] def st():return input().rstrip('\n') def val():return int(input().rstrip('\n')) def li2():return [i for i in input().rstrip('\n')] def li3():return [int(i) for i in input().rstrip('\n')] sys.setrecursionlimit(10 ** 6) a, n, m = li() l = [] rain = defaultdict(int) for i in range(n): c, b = li() for j in range(c, b): rain[(j, j + 1)] = 1 # print(rain) umbrellas = [float('inf')] * (a + 5) for i in range(m): c, b = li() umbrellas[c] = min(umbrellas[c], b) # print(umbrellas[:a + 1]) @lru_cache(None) def dp(i = 0, umbon = 0): # print(i, umbon) if i == a: if rain[(i - 1, i)]: if umbon:return umbon return float('inf') else:return umbon else: ans = float('inf') last = umbon if rain[(i - 1, i)]: umbon = min(umbon, umbrellas[i]) if umbon else umbrellas[i] if not last:last = float('inf') ans = min(ans, last + dp(i + 1, umbon)) ans = min(ans, last + dp(i + 1, 0)) else: ans = min(ans, dp(i + 1, 0) + last) umbon = min(umbon, umbrellas[i]) if umbon else umbrellas[i] ans = min(ans, dp(i + 1, umbon) + last) return ans print(dp(0, 0) if dp(0, 0) != float('inf') else -1) ```
102,675
[ 0.314697265625, 0.44482421875, 0.461181640625, 0.1304931640625, -0.41064453125, -0.3134765625, -0.3310546875, 0.0159454345703125, 0.420166015625, 0.73486328125, 0.75146484375, 0.0311431884765625, 0.0242156982421875, -0.7080078125, -0.147705078125, 0.1475830078125, -0.7705078125, -0...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. Tags: dp Correct Solution: ``` import io import os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline INF = 10**15 def dp_min(dp, pos, new_val): if pos not in dp: dp[pos] = new_val else: dp[pos] = min(dp[pos], new_val) def solve(): a, n, m = list(map(int, input().split())) has_rain = [False] * a for _ in range(n): l, r = map(int, input().split()) for i in range(l, r): has_rain[i] = True umbrella = [INF] * a for _ in range(m): x, p = map(int, input().split()) if x == a: continue umbrella[x] = min(umbrella[x], p) # dp: best cost so far if I am currently carrying no umbrella (-1), or some umbrella of certain weight dp = {-1: 0} for i in range(a): new_dp = {} for umbrella_weight, best_cost in dp.items(): if not has_rain[i]: # carry no umbrella dp_min(new_dp, -1, best_cost) # take the new umbrella dp_min(new_dp, umbrella[i], best_cost + umbrella[i]) if umbrella_weight != -1: # continue same umbrella dp_min(new_dp, umbrella_weight, best_cost + umbrella_weight) dp = new_dp best = min(dp.values()) if best >= INF: print(-1) else: print(best) t = 1 for _ in range(t): solve() ```
102,676
[ 0.314697265625, 0.44482421875, 0.461181640625, 0.1304931640625, -0.41064453125, -0.3134765625, -0.3310546875, 0.0159454345703125, 0.420166015625, 0.73486328125, 0.75146484375, 0.0311431884765625, 0.0242156982421875, -0.7080078125, -0.147705078125, 0.1475830078125, -0.7705078125, -0...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. Tags: dp Correct Solution: ``` import sys a, n, m = map(int, input().split(' ')) seg = [] for i in range(n): rained = tuple(map(int, input().split(' '))) for k in range(rained[0], rained[1]): seg.append(k+1) umbrella = [] for j in range(m): u = tuple(map(int, input().split(' '))) umbrella.append(u) memo = [0] * (a+1) umbrella = sorted(umbrella, key=lambda x: x[0]) if umbrella[0][0] > seg[0] - 1: print(-1) sys.exit(0) for index in range(1, len(memo)): if index not in seg: memo[index] = memo[index-1] continue for each in umbrella: if index >= each[0]: cur = (index - each[0]) * each[1] + memo[each[0]] if memo[index] > 0: if cur < memo[index]: memo[index] = cur else: memo[index] = cur print(memo[-1]) ```
102,677
[ 0.314697265625, 0.44482421875, 0.461181640625, 0.1304931640625, -0.41064453125, -0.3134765625, -0.3310546875, 0.0159454345703125, 0.420166015625, 0.73486328125, 0.75146484375, 0.0311431884765625, 0.0242156982421875, -0.7080078125, -0.147705078125, 0.1475830078125, -0.7705078125, -0...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. Tags: dp Correct Solution: ``` # Codeforces Round #486 (Div. 3) from functools import cmp_to_key #key=cmp_to_key(lambda x,y: 1 if x not in y else -1 ) import sys def getIntList(): return list(map(int, input().split())) a,n,m = getIntList() rainend = set() umbr = {} keyPointSet = set([0,a]) for i in range(n): t =tuple(getIntList()) for j in range(t[0] + 1, t[1] + 1): rainend.add(j) keyPointSet.add(t[1]) for i in range(m): t =getIntList() if t[0] not in umbr or t[1]< umbr[t[0]]: umbr[t[0]] = t[1] keyPointSet.add(t[0]) keyPoint = list(keyPointSet) keyPoint.sort() dp = {} dp[0] = {} dp[0] [0] = 0 if 0 in umbr: dp[0][umbr[0]] = 0 for i in range(1, len(keyPoint)): x = keyPoint[i] lx = keyPoint[i-1] ifrain = x in rainend dp[x] = {} nowdp = dp[x] lastdp = dp[lx] for z in lastdp: if z == 0 : if not ifrain: nowdp[0] = lastdp[0] else: nowdp[z] = lastdp[z] + z * (x-lx) if len(nowdp) >0: nowdp[0] = min(nowdp.values()) if x in umbr: if umbr[x] not in nowdp or nowdp[0] < nowdp[umbr[x]]: nowdp[umbr[x]] = nowdp[0] else: print(-1) sys.exit() print( min(dp[a].values()) ) ```
102,678
[ 0.314697265625, 0.44482421875, 0.461181640625, 0.1304931640625, -0.41064453125, -0.3134765625, -0.3310546875, 0.0159454345703125, 0.420166015625, 0.73486328125, 0.75146484375, 0.0311431884765625, 0.0242156982421875, -0.7080078125, -0.147705078125, 0.1475830078125, -0.7705078125, -0...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. Tags: dp Correct Solution: ``` import sys a,m,n=list(map(int,input().split())) aux=[0]*(a+1) inf=10**15 dp=[aux.copy() for i in range(n+1)] m1=10**12 m2=10**12 for i in range(m): l,r=list(map(int,input().split())) if l<m1: m1=l for j in range(l,r): dp[0][j+1]=inf s=[] for i in range(1,n+1): x,w=list(map(int,input().split())) s.append(tuple([x,w])) if x<m2: m2=x if m2>m1: print(-1) sys.exit() s.sort() for i in range(1,n+1): x=s[i-1][0] w=s[i-1][1] for j in range(x+1): dp[i][j]=dp[i-1][j] for j in range(x+1,a+1): if i!=1: dp[i][j]=min(dp[0][j]+dp[i][j-1],dp[i-1][j],w*(j-x)+dp[i][x]) else: dp[i][j]=min(dp[0][j]+dp[i][j-1],w*(j-x)+dp[i][x]) ans=dp[-1][-1] if ans>=inf: print(-1) else: print(ans) ```
102,679
[ 0.314697265625, 0.44482421875, 0.461181640625, 0.1304931640625, -0.41064453125, -0.3134765625, -0.3310546875, 0.0159454345703125, 0.420166015625, 0.73486328125, 0.75146484375, 0.0311431884765625, 0.0242156982421875, -0.7080078125, -0.147705078125, 0.1475830078125, -0.7705078125, -0...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. Tags: dp Correct Solution: ``` import sys def input(): return sys.stdin.readline().strip() def input_l(): return map(int, input().split()) def input_t(): return tuple(input_l()) def main(): a, s, d = input_l() q = [] e = [] z = [0] * (a + 1) for i in range(s): w = input_t() for k in range(w[0], w[1]): q.append(k + 1) for j in range(d): e.append(input_t()) e = sorted(e, key = lambda x: x[0]) if e[0][0] > q[0] - 1: print(-1) sys.exit(0) for i in range(1, len(z)): if i not in q: z[i] = z[i-1] continue for j in e: if i >= j[0]: c = (i - j[0]) * j[1] + z[j[0]] if z[i] > 0: if c < z[i]: z[i] = c else: z[i] = c print(z[-1]) main() ```
102,680
[ 0.314697265625, 0.44482421875, 0.461181640625, 0.1304931640625, -0.41064453125, -0.3134765625, -0.3310546875, 0.0159454345703125, 0.420166015625, 0.73486328125, 0.75146484375, 0.0311431884765625, 0.0242156982421875, -0.7080078125, -0.147705078125, 0.1475830078125, -0.7705078125, -0...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. Submitted Solution: ``` import math def main(): a, n, m = map(int, input().split()) rain = [] u = [] w = [] raining = [False] * (a+1) for i in range(n): l, r = map(int, input().split()) rain.append((l, r)) for j in range(l, r): raining[j] = True for i in range(m): x, y = map(int, input().split()) u.append(x) w.append(y) rain_int = [0] * a for i in range(n): rain_int[rain[i][0]-1] = 1 rain_int[rain[i][1]-1] = -1 umbrellas = [-1 for _ in range(a+1)] for i, x in enumerate(u): if umbrellas[x] == -1 or w[umbrellas[x]] > w[i]: umbrellas[x] = i dp = [[math.inf for _ in range(m+1)] for _ in range(a+1)] dp[0][m] = 0 for i in range(a): for j in range(m+1): if dp[i][j] == math.inf: continue if not raining[i]: dp[i+1][m] = min(dp[i+1][m], dp[i][j]) if j < m: dp[i+1][j] = min(dp[i+1][j], dp[i][j] + w[j]) if umbrellas[i] != -1: dp[i+1][umbrellas[i]] = min(dp[i+1][umbrellas[i]], dp[i][j]+w[umbrellas[i]]) ans = math.inf for i in range(m+1): ans = min(ans, dp[a][i]) print(-1 if ans == math.inf else ans) if __name__ == '__main__': main() ``` Yes
102,681
[ 0.404296875, 0.43896484375, 0.374267578125, 0.08331298828125, -0.388427734375, -0.1744384765625, -0.33251953125, 0.0889892578125, 0.405029296875, 0.7373046875, 0.72119140625, 0.10003662109375, 0.0450439453125, -0.69287109375, -0.185546875, 0.0791015625, -0.71533203125, -0.619140625...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. Submitted Solution: ``` #!/usr/bin/env pypy from __future__ import division, print_function import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip MOD = 10**9 + 7 # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion a, s, d = map(int, input().split()) q = [] e = [] z = [0] * (a + 1) for i in range(s): w = tuple(map(int, input().split())) for k in range(w[0], w[1]): q.append(k + 1) for j in range(d): e.append(tuple(map(int, input().split()))) e = sorted(e, key = lambda x: x[0]) # ~ print(e) if e[0][0] > q[0] - 1: print(-1) exit() for i in range(1, a +1): if i not in q: z[i] = z[i-1] continue for j in e: if i >= j[0]: c = (i - j[0]) * j[1] + z[j[0]] if z[i] > 0: if c < z[i]: z[i] = c else: z[i] = c print(z[-1]) ``` Yes
102,682
[ 0.404296875, 0.43896484375, 0.374267578125, 0.08331298828125, -0.388427734375, -0.1744384765625, -0.33251953125, 0.0889892578125, 0.405029296875, 0.7373046875, 0.72119140625, 0.10003662109375, 0.0450439453125, -0.69287109375, -0.185546875, 0.0791015625, -0.71533203125, -0.619140625...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. Submitted Solution: ``` rd = lambda: map(int, input().split()) a, n, m = rd() s = set() u = {} k = set([0, a]) for _ in range(n): l, r = rd() for x in range(l + 1, r + 1): s.add(x) k.add(r) for _ in range(m): x, p = rd() u[x] = min(p, u.get(x, 1e9)) k.add(x) k = sorted(list(k)) dp = {} dp[0] = {} dp[0][0] = 0 if 0 in u: dp[0][u[0]] = 0 for i in range(1, len(k)): x = k[i] y = k[i - 1] dp[x] = {} for z in dp[y]: if z: dp[x][z] = dp[y][z] + z * (x - y) else: if x not in s: dp[x][0] = dp[y][0] if len(dp[x]): dp[x][0] = min(dp[x].values()) if x in u: if u[x] not in dp[x] or dp[x][0] < dp[x][u[x]]: dp[x][u[x]] = dp[x][0] else: print(-1) exit() print(dp[a][0]) ``` Yes
102,683
[ 0.404296875, 0.43896484375, 0.374267578125, 0.08331298828125, -0.388427734375, -0.1744384765625, -0.33251953125, 0.0889892578125, 0.405029296875, 0.7373046875, 0.72119140625, 0.10003662109375, 0.0450439453125, -0.69287109375, -0.185546875, 0.0791015625, -0.71533203125, -0.619140625...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. Submitted Solution: ``` a,m,n=list(map(int,input().split())) aux=[0]*(a+1) inf=10**15 dp=[aux.copy() for i in range(n+1)] for i in range(m): l,r=list(map(int,input().split())) for j in range(l,r): dp[0][j+1]=inf s=[] for i in range(1,n+1): x,w=list(map(int,input().split())) s.append(tuple([x,w])) s.sort() for i in range(1,n+1): x=s[i-1][0] w=s[i-1][1] for j in range(x+1): dp[i][j]=dp[i-1][j] for j in range(x+1,a+1): if i!=1: dp[i][j]=min(dp[0][j]+dp[i][j-1],dp[i-1][j],w*(j-x)+dp[i][x]) else: dp[i][j]=min(dp[0][j]+dp[i][j-1],w*(j-x)+dp[i][x]) ans=dp[-1][-1] if ans>=inf: print(-1) else: print(ans) ``` No
102,684
[ 0.404296875, 0.43896484375, 0.374267578125, 0.08331298828125, -0.388427734375, -0.1744384765625, -0.33251953125, 0.0889892578125, 0.405029296875, 0.7373046875, 0.72119140625, 0.10003662109375, 0.0450439453125, -0.69287109375, -0.185546875, 0.0791015625, -0.71533203125, -0.619140625...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. Submitted Solution: ``` #!python3 # http://codeforces.com/contest/988/problem/F from bisect import bisect_left as bl a, n, m = [int(i) for i in input().strip().split(' ')] R = [] for i in range(n): l, r = [int(j) for j in input().strip().split(' ')] inx = bl(R, l) R.insert(inx, l) R.insert(inx+1, r) A = [] for i in range(m): A += [tuple(int(j) for j in input().strip().split(' '))] A = sorted(A) class S: # Solution def __init__(self, a, t): self.t = t # tiredness self.a = a # ambrella def __repr__(self): return "({} {})".format(self.a, self.t) O = [S(0,0)] # no ambrellas, not tired x = 0 # starts at 0 x_prev = 0 is_rain = False optimal = None while x <= a: # check if rain: rain_inx = bl(R, x) if rain_inx < len(R): rain_coord = R[rain_inx] if x == rain_coord: is_rain = not is_rain # update tiredness in solutions: distance = x - x_prev optimal = 9*999 for o in O: amb = o.a if amb > 0: p = A[amb-1][1] o.t += p*distance if o.t < optimal: optimal = o.t # pick up new ambrellas: k = bl(A, (x, 0)) # inx of next ambrellas or one at x if k < len(A): # have some here or next while k < len(A) and A[k][0] == x: # every ambrella at x amb = k + 1 O += [S(amb, optimal)] k += 1 assert k >= len(A) or A[k][0] != x, "k should be next amb or none" # drop solution without ambrella if rains: index_list = [i for i, el in enumerate(O) if el.a == 0] s_inx = index_list[0] if len(index_list) > 0 else None if is_rain and s_inx is not None: # can not go without ambrella assert O[s_inx].a == 0 del O[s_inx] elif not is_rain and s_inx is None: # can go without one O.append(S(0, optimal)) if not any(O) and x != a: optimal = -1 break # get next x: next_x = a if rain_inx < len(R): if x < R[rain_inx]: next_x = R[rain_inx] elif rain_inx + 1 < len(R): next_x = R[rain_inx+1] if k < len(A) and A[k][0] < next_x: next_x = A[k][0] if x == next_x: break x_prev = x x = next_x print(optimal) ``` No
102,685
[ 0.404296875, 0.43896484375, 0.374267578125, 0.08331298828125, -0.388427734375, -0.1744384765625, -0.33251953125, 0.0889892578125, 0.405029296875, 0.7373046875, 0.72119140625, 0.10003662109375, 0.0450439453125, -0.69287109375, -0.185546875, 0.0791015625, -0.71533203125, -0.619140625...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. Submitted Solution: ``` def main(): a, n, m = map(int, input().split()) rain = [False] * (a + 1) for _ in range(n): x, y = map(int, input().split()) for i in range(x, y + 1): rain[i] = True umrella = [0] * (a + 1) for _ in range(m): x, y = map(int, input().split()) if umrella[x] == 0: umrella[x] = y else: umrella[x] = min(umrella[x], y) max_value = 10 ** 18 dp = [max_value] * (a + 1) ok = True if not rain[0] or umrella[0] > 0: dp[0] = 0 else: ok = False if ok: for i in range(1, a + 1): if not rain[i]: dp[i] = dp[i - 1] else: for j in range(0, i + 1): if umrella[j] > 0: if j >= 1: dp[i] = min(dp[i], dp[j - 1] + umrella[j] * (i - j)) else: dp[i] = min(dp[i], umrella[j] * (i - j)) if dp[a] == max_value: print(-1) else: print(dp[a]) else: print(-1) if __name__ == "__main__": main() ``` No
102,686
[ 0.404296875, 0.43896484375, 0.374267578125, 0.08331298828125, -0.388427734375, -0.1744384765625, -0.33251953125, 0.0889892578125, 0.405029296875, 0.7373046875, 0.72119140625, 0.10003662109375, 0.0450439453125, -0.69287109375, -0.185546875, 0.0791015625, -0.71533203125, -0.619140625...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second. Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 ≀ l_i < r_i ≀ a). There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 ≀ x_i ≀ a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas. During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i ≀ x and x + 1 ≀ r_i). The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain. Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving. Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Input The first line contains three integers a, n and m (1 ≀ a, m ≀ 2000, 1 ≀ n ≀ ⌈a/2βŒ‰) β€” the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next n lines contains two integers l_i and r_i (0 ≀ l_i < r_i ≀ a) β€” the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i. Each of the next m lines contains two integers x_i and p_i (0 ≀ x_i ≀ a, 1 ≀ p_i ≀ 10^5) β€” the location and the weight of the i-th umbrella. Output Print "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer β€” the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally. Examples Input 10 2 4 3 7 8 10 0 10 3 4 8 1 1 2 Output 14 Input 10 1 1 0 9 0 5 Output 45 Input 10 1 1 0 9 1 5 Output -1 Note In the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. Submitted Solution: ``` s=input()[::-1] m=I=41 f=s.find('5')+1 i=s.find('0')+1 t=len(s) if i: j=min(s.find('0',i)+1or I,f or I) if j<I: m=i+j-3 if j<i:m+=1 if f: j=min(s.find('2')+1or I,s.find('7')+1or I) if j<I: l=f+j-3 if j<f:l+=1 if f==t: i=t-1 while i==j or s[i-1]=='0': if i!=j:l+=1 i-=1 m=min(m,l) print((-1,m)[m<I]) ``` No
102,687
[ 0.404296875, 0.43896484375, 0.374267578125, 0.08331298828125, -0.388427734375, -0.1744384765625, -0.33251953125, 0.0889892578125, 0.405029296875, 0.7373046875, 0.72119140625, 0.10003662109375, 0.0450439453125, -0.69287109375, -0.185546875, 0.0791015625, -0.71533203125, -0.619140625...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Tags: *special, dfs and similar, graphs, implementation Correct Solution: ``` cycle = False def DFS(s): global cycle visited[s] = 1 stack = [s] while len(stack) != 0: u = stack[-1] visited[u] = 1 if len(graph[u]) != 0: v = graph[u].pop() if visited[v] == 1: cycle = True return if visited[v] == 2: continue stack.append(v) else: result.append(u) stack.pop() visited[u] = 2 def TopoSort(graph, result, visited): for i in range (m): if not visited[requiredCourse[i]]: DFS(requiredCourse[i]) return result n, m = map(int, input().split()) requiredCourse = list(map(int, input().split())) visited = [0 for i in range (n + 1)] graph = [[] for i in range (n + 1)] result = [] for i in range (1, n + 1): tmp = list(map(int, input().split())) if tmp[0] == 0: continue for j in range (1, tmp[0] + 1): graph[i].append(tmp[j]) res = TopoSort(graph, result, visited) if cycle: print(-1) else: print(len(res)) for i in res: print(i, end = " ") ```
103,362
[ 0.5400390625, 0.05194091796875, 0.038330078125, 0.1500244140625, -0.28369140625, 0.1053466796875, -0.0635986328125, 0.1451416015625, 0.059326171875, 0.92822265625, 1.0390625, -0.0243072509765625, 0.60888671875, -0.80419921875, -0.5087890625, 0.222900390625, -0.73681640625, -1.15429...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Tags: *special, dfs and similar, graphs, implementation Correct Solution: ``` # https://codeforces.com/problemset/problem/770/C n, k = map(int, input().split()) K = set(list(map(int, input().split()))) g = {} rg = {} deg = {} def push_d(deg, u, val): if u not in deg: deg[u] = 0 deg[u] += val def push_g(g, u, v): if u not in g: g[u] = [] g[u].append(v) for u in range(1, n+1): list_v = list(map(int, input().split()))[1:] deg[u] = 0 for v in list_v: push_d(deg, u, 1) push_g(g, v, u) push_g(rg, u, v) S = [x for x in K] used = [0] * (n+1) i = 0 while i<len(S): u = S[i] if u in rg: for v in rg[u]: if used[v] == 0: used[v] = 1 S.append(v) i+=1 S = {x:1 for x in S} deg0 = [x for x in S if deg[x]==0] ans = [] def process(g, deg, deg0, u): if u in g: for v in g[u]: if v in S: push_d(deg, v, -1) if deg[v] == 0: deg0.append(v) while len(deg0) > 0 and len(K) > 0: u = deg0.pop() ans.append(u) if u in K: K.remove(u) process(g, deg, deg0, u) if len(K) > 0: print(-1) else: print(len(ans)) print(' '.join([str(x) for x in ans])) #6 2 #5 6 #0 #1 1 #1 4 5 #2 2 1 #1 4 #2 5 3 ```
103,363
[ 0.5400390625, 0.05194091796875, 0.038330078125, 0.1500244140625, -0.28369140625, 0.1053466796875, -0.0635986328125, 0.1451416015625, 0.059326171875, 0.92822265625, 1.0390625, -0.0243072509765625, 0.60888671875, -0.80419921875, -0.5087890625, 0.222900390625, -0.73681640625, -1.15429...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Tags: *special, dfs and similar, graphs, implementation Correct Solution: ``` def dfs(start_node, edges, colors, result): stack = [start_node] while stack: current_node = stack[-1] if colors[current_node] == 2: stack.pop() continue colors[current_node] = 1 children = edges[current_node] if not children: colors[current_node] = 2 result.append(stack.pop()) else: child = children.pop() if colors[child] == 1: return False stack.append(child) return True def find_courses_sequence(member_of_node, find_nodes, edges): colors = [0] * member_of_node result = [] for node in find_nodes: if not dfs(node, edges, colors, result): return [] return result if __name__ == '__main__': n, k = map(int, input().split()) main_courses = [int(c)-1 for c in input().split()] courses = dict() for index in range(n): courses[index] = [int(d)-1 for d in input().split()[1:]] result = find_courses_sequence(n, main_courses, courses) if result: print(len(result)) for v in result: print(v+1, end=" ") else: print(-1) ```
103,364
[ 0.5400390625, 0.05194091796875, 0.038330078125, 0.1500244140625, -0.28369140625, 0.1053466796875, -0.0635986328125, 0.1451416015625, 0.059326171875, 0.92822265625, 1.0390625, -0.0243072509765625, 0.60888671875, -0.80419921875, -0.5087890625, 0.222900390625, -0.73681640625, -1.15429...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Tags: *special, dfs and similar, graphs, implementation Correct Solution: ``` n,k=list(map(lambda x: int(x), input().split())) m=list(map(lambda x: int(x), input().split())) from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc class Graph: def __init__(self, V): self.V = V self.adj = [[] for i in range(V)] @bootstrap def DFSUtil(self, temp, v, visited): visited[v] = True for i in self.adj[v]: if visited[i] == False: yield self.DFSUtil(temp, i, visited) temp.append(v) yield temp def addEdge(self, v, w): self.adj[v].append(w) # self.adj[w].append(v) @bootstrap def isCyclicUtil(self, v, visited, recStack): # Mark current node as visited and # adds to recursion stack visited[v] = True recStack[v] = True # Recur for all neighbours # if any neighbour is visited and in # recStack then graph is cyclic for neighbour in self.adj[v]: if visited[neighbour] == False: ans =yield self.isCyclicUtil(neighbour, visited, recStack) if ans == True: yield True elif recStack[neighbour] == True: yield True # The node needs to be poped from # recursion stack before function ends recStack[v] = False yield False # Returns true if graph is cyclic else false def isCyclic(self,nodes): visited = [False] * self.V recStack = [False] * self.V for node in nodes: if visited[node] == False: if self.isCyclicUtil(node, visited, recStack) == True: return True return False G=Graph(n) for i in range(0,n): x=list(map(lambda x: int(x), input().split())) if x[0]==0: continue else: for k in range(1,x[0]+1): G.addEdge(i,x[k]-1) visited=[False for _ in range(n)] path=[] # print(G.adj) for subj in m: temp = [] if visited[subj-1]==False: G.DFSUtil(temp,subj-1,visited) path.extend(temp) if G.isCyclic([x-1 for x in m]): print(-1) else: print(len(path)) for p in path: print(p+1,end=" ") print() ```
103,365
[ 0.5400390625, 0.05194091796875, 0.038330078125, 0.1500244140625, -0.28369140625, 0.1053466796875, -0.0635986328125, 0.1451416015625, 0.059326171875, 0.92822265625, 1.0390625, -0.0243072509765625, 0.60888671875, -0.80419921875, -0.5087890625, 0.222900390625, -0.73681640625, -1.15429...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Tags: *special, dfs and similar, graphs, implementation Correct Solution: ``` import sys def main(): n,k = map(int,sys.stdin.readline().split()) courses = list(map(int,sys.stdin.readline().split())) courses = [x-1 for x in courses] visited = [False]*n used = [False]*n ans = [] t = [] for i in range(n): temp = list(map(int,sys.stdin.readline().split())) temp = [x-1 for x in temp] t.append(temp[1:]) for i in range(k): c = courses[i] if used[c]: continue q = [c] visited[c]=True while len(q)>0: cur = q[-1] if len(t[cur])!=0: s = t[cur].pop() if visited[s] and not used[s]: print(-1) return if used[s]: continue q.append(s) visited[s]=True else: ans.append(cur) q.pop() used[cur] = True ans = [str(x+1) for x in ans] print(len(ans)) print(" ".join(ans)) main() ```
103,366
[ 0.5400390625, 0.05194091796875, 0.038330078125, 0.1500244140625, -0.28369140625, 0.1053466796875, -0.0635986328125, 0.1451416015625, 0.059326171875, 0.92822265625, 1.0390625, -0.0243072509765625, 0.60888671875, -0.80419921875, -0.5087890625, 0.222900390625, -0.73681640625, -1.15429...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Tags: *special, dfs and similar, graphs, implementation Correct Solution: ``` import collections as col import itertools as its import sys import operator from copy import copy, deepcopy class Solver: def __init__(self): pass def solve(self): n, k = map(int, input().split()) q = list(map(lambda x: int(x) - 1, input().split())) used = [False] * n for e in q: used[e] = True edges = [[] for _ in range(n)] redges = [[] for _ in range(n)] for i in range(n): l = list(map(lambda x: int(x) - 1, input().split()))[1:] edges[i] = l for e in l: redges[e].append(i) degs = [len(edges[i]) for i in range(n)] d = 0 while d < len(q): v = q[d] d += 1 for e in edges[v]: if not used[e]: used[e] = True q.append(e) q = q[::-1] nq = [] for v in q: if degs[v] == 0: nq.append(v) d = 0 while d < len(nq): v = nq[d] d += 1 for e in redges[v]: if not used[e]: continue degs[e] -= 1 if degs[e] == 0: nq.append(e) #print(nq) if len(q) != len(nq): print(-1) return print(len(nq)) print(' '.join(map(lambda x: str(x + 1), nq))) if __name__ == '__main__': s = Solver() s.solve() ```
103,367
[ 0.5400390625, 0.05194091796875, 0.038330078125, 0.1500244140625, -0.28369140625, 0.1053466796875, -0.0635986328125, 0.1451416015625, 0.059326171875, 0.92822265625, 1.0390625, -0.0243072509765625, 0.60888671875, -0.80419921875, -0.5087890625, 0.222900390625, -0.73681640625, -1.15429...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Tags: *special, dfs and similar, graphs, implementation Correct Solution: ``` f = lambda: map(int, input().split()) g = lambda: [int(q) - 1 for q in f()] class T: def __init__(s, i): s.i, s.t = i, g()[1:] s.a = s.q = 0 n, k = f() d = g() p = [T(i) for i in range(n)] s = [] while d: x = p[d.pop()] if x.a: continue d.append(x.i) q = 1 for i in x.t: y = p[i] if y.a: continue d.append(y.i) q = 0 if q: s.append(x.i + 1) x.a = 1 elif x.q: print(-1) exit() else: x.q = 1 print(len(s), *s) ```
103,368
[ 0.5400390625, 0.05194091796875, 0.038330078125, 0.1500244140625, -0.28369140625, 0.1053466796875, -0.0635986328125, 0.1451416015625, 0.059326171875, 0.92822265625, 1.0390625, -0.0243072509765625, 0.60888671875, -0.80419921875, -0.5087890625, 0.222900390625, -0.73681640625, -1.15429...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Tags: *special, dfs and similar, graphs, implementation Correct Solution: ``` from sys import * f = lambda: list(map(int, stdin.readline().split())) class T: def __init__(self, i): self.i, self.t = i, f()[1:] self.a = self.q = 0 n, k = f() d = f() p = [None] + [T(i + 1) for i in range(n)] s = [] while d: x = p[d.pop()] if x.a: continue d.append(x.i) q = 1 for i in x.t: y = p[i] if y.a: continue d.append(y.i) q = 0 if q: s.append(x.i) x.a = 1 elif x.q: print(-1) exit() else: x.q = 1 print(len(s), *s) ```
103,369
[ 0.5400390625, 0.05194091796875, 0.038330078125, 0.1500244140625, -0.28369140625, 0.1053466796875, -0.0635986328125, 0.1451416015625, 0.059326171875, 0.92822265625, 1.0390625, -0.0243072509765625, 0.60888671875, -0.80419921875, -0.5087890625, 0.222900390625, -0.73681640625, -1.15429...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Submitted Solution: ``` import sys sys.setrecursionlimit(10 ** 8) cycle = False def DFS(i, graph, result, visited): global cycle stack = [i] while len(stack) != 0: u = stack[-1] visited[u] = 1 if len(graph[u]) != 0: v = graph[u].pop() if visited[v] == 1: cycle = True return if visited[v] == 2: continue stack.append(v) visited[u] = 1 else: result.append(u) stack.pop() visited[u] = 2 def TopoSort(graph, result): for i in range(m): if not visited[requiredCourse[i]]: DFS(requiredCourse[i], graph, result, visited) return result n, m = map(int, input().split()) requiredCourse = list(map(int, input().split())) graph = [[] for i in range(n + 1)] result = [] visited = [False for i in range(n + 1)] for i in range(1, n + 1): tmp = list(map(int, input().split())) if tmp[0] == 0: continue for j in range(1, tmp[0] + 1): graph[i].append(tmp[j]) res = TopoSort(graph, result) if cycle == True: print(-1) else: print(len(res)) for i in res: print(i, end=" ") ``` Yes
103,370
[ 0.5517578125, 0.114990234375, 0.020294189453125, 0.11083984375, -0.3349609375, 0.1529541015625, -0.09344482421875, 0.2010498046875, 0.081298828125, 0.9287109375, 1.046875, 0.0196990966796875, 0.572265625, -0.81494140625, -0.458740234375, 0.164306640625, -0.7314453125, -1.1943359375...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Submitted Solution: ``` '''import sys flag=True sys.setrecursionlimit(2000000) c=[];st=[]; def topo(s):#Traversing the array and storing the vertices global c,st,flag; c[s]=1; #Being Visited for i in adjli[s]:#visiting neighbors if c[i]==0: topo(i) if c[i]==1: flag=False# If Back Edge , Then Not Possible st.append(str(s)) c[s]=2 # Visited try: n,k=map(int,input().split(' '))#Number Of Courses,Dependencies main=list(map(int,input().split(' ')))#Main Dependencies depen=[]#Dependencies List for i in range(n): depen.append(list(map(int,input().split(' ')))[1:]);c.append(0)#Append Input To Dependencies List, Marking Visited as 0(False) c.append(0) adjli=[] adjli.append(main)#Assuming Main Course at index 0 with dependencies as Main Dependency(main) for i in range(len(depen)): adjli.append(depen[i])#Appending Other Dependencies topo(0)#TopoLogical Sort Order st.pop(-1)#popping the assumed Main Couse if flag:# IF possible then print print(len(st)) print(' '.join(st)) else: print(-1) except Exception as e: print(e,"error")''' import sys flag=True sys.setrecursionlimit(2000000000) c=[];st=[]; cur_adj=[] def topo(s):#Traversing the array and storing the vertices global c,st,flag; stack = [s] while(stack): s = stack[-1] c[s]=1; #Being Visited if(cur_adj[s] < len(adjli[s])): cur = adjli[s][cur_adj[s]] if(c[cur]==0): stack.append(cur) if(c[cur]==1): flag=False# If Back Edge , Then Not Possible cur_adj[s]+=1 else: c[s]=2 st.append(str(s)) del stack[-1] try: n,k=map(int,input().split(' ')) main=list(map(int,input().split(' '))) depen=[] for i in range(n): depen.append(list(map(int,input().split(' ')))[1:]);c.append(0) cur_adj.append(0) c.append(0) cur_adj.append(0) adjli=[] adjli.append(main)#Assuming Main Course at index 0 with dependencies as Main Dependency(main) for i in range(len(depen)): adjli.append(depen[i])#Appending Other Dependencies topo(0)#TopoLogical Sort Order st.pop(-1)#popping the assumed Main Couse if flag:# IF possible then print print(len(st)) print(' '.join(st)) else: print(-1) except Exception as e: print(e,"error") ``` Yes
103,371
[ 0.5517578125, 0.114990234375, 0.020294189453125, 0.11083984375, -0.3349609375, 0.1529541015625, -0.09344482421875, 0.2010498046875, 0.081298828125, 0.9287109375, 1.046875, 0.0196990966796875, 0.572265625, -0.81494140625, -0.458740234375, 0.164306640625, -0.7314453125, -1.1943359375...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Submitted Solution: ``` import sys flag=True sys.setrecursionlimit(2000000000) c=[];st=[]; cur_adj=[] def topo(s):#Traversing the array and storing the vertices global c,st,flag; stack = [s] while(stack): s = stack[-1] c[s]=1; #Being Visited if(cur_adj[s] < len(adjli[s])): cur = adjli[s][cur_adj[s]] if(c[cur]==0): stack.append(cur) if(c[cur]==1): flag=False# If Back Edge , Then Not Possible cur_adj[s]+=1 else: c[s]=2 st.append(str(s)) del stack[-1] try: n,k=map(int,input().split(' ')) main=list(map(int,input().split(' '))) depen=[] for i in range(n): depen.append(list(map(int,input().split(' ')))[1:]);c.append(0) cur_adj.append(0) c.append(0) cur_adj.append(0) adjli=[] adjli.append(main)#Assuming Main Course at index 0 with dependencies as Main Dependency(main) for i in range(len(depen)): adjli.append(depen[i])#Appending Other Dependencies topo(0)#TopoLogical Sort Order st.pop(-1)#popping the assumed Main Couse if flag:# IF possible then print print(len(st)) print(' '.join(st)) else: print(-1) except Exception as e: print(e,"error") ``` Yes
103,372
[ 0.5517578125, 0.114990234375, 0.020294189453125, 0.11083984375, -0.3349609375, 0.1529541015625, -0.09344482421875, 0.2010498046875, 0.081298828125, 0.9287109375, 1.046875, 0.0196990966796875, 0.572265625, -0.81494140625, -0.458740234375, 0.164306640625, -0.7314453125, -1.1943359375...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Submitted Solution: ``` #This code is dedicated to Vlada S. class Course: def __init__(self, reqs, number): self.reqs = list(map(int, reqs.split()[1:])) self.available = False self.in_stack = False self.number = number n, k = list(map(int, input().split())) requirements = list(map(int, input().split())) courses = {} answer = "" for i in range(n): courses[i + 1]= Course(input(), i + 1) for i in range(len(requirements)): requirements[i] = courses[requirements[i]] while requirements: data = {} course = requirements.pop() if not course.available: requirements.append(course) done = True for c in course.reqs: c = courses[c] if not c.available: requirements.append(c) done = False if done: answer += " " + str(course.number) course.available = True else: if course.in_stack: print(-1) break course.in_stack = True else: print(answer.count(" ")) print(answer[1:]) # Made By Mostafa_Khaled ``` Yes
103,373
[ 0.5517578125, 0.114990234375, 0.020294189453125, 0.11083984375, -0.3349609375, 0.1529541015625, -0.09344482421875, 0.2010498046875, 0.081298828125, 0.9287109375, 1.046875, 0.0196990966796875, 0.572265625, -0.81494140625, -0.458740234375, 0.164306640625, -0.7314453125, -1.1943359375...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Submitted Solution: ``` putninja=[] courses=[] B=True def mff(A, num): global putninja global courses if A[0]=='0': putninja.append(num) courses[int(num)-1][0]='stop' elif A[0]=='stop': pass else: for j in range(int(A[0])): mff(courses[int(A[j+1])-1],A[j+1]) putninja.append(num) courses[int(num)-1][0]='stop' kn=input().split() k=int(kn[0]) n=int(kn[1]) mk=input().split() for i in range(k): s=input() courses.append(s.split(' ')) for i in range(n): try: mff(courses[int(mk[i])-1],mk[i]) except: B=False break if B: print(len(putninja)) print(' '.join(putninja)) else: print(-1) ``` No
103,374
[ 0.5517578125, 0.114990234375, 0.020294189453125, 0.11083984375, -0.3349609375, 0.1529541015625, -0.09344482421875, 0.2010498046875, 0.081298828125, 0.9287109375, 1.046875, 0.0196990966796875, 0.572265625, -0.81494140625, -0.458740234375, 0.164306640625, -0.7314453125, -1.1943359375...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Submitted Solution: ``` from sys import stdin, stdout n,k = stdin.readline().split() n = int(n) k = int(k) toLearn = [-1] * n kList = input().split() for i in range(len(kList)): kList[i] = int(kList[i]) nList = [] flag = True for i in range(n): nL = stdin.readline().split() nL.pop(0) for j in range(len(nL)): nL[j] = int(nL[j]) if len(nL) == 0: flag = False nList.append(nL) # n = 100000 # k = 1 # kList = [100000] # nList =[[]] # flag = False # for i in range(1, n): # nList.append([i]) res = [] if k == 0: print(0) print("") elif flag: print(-1) else: res = [] notCircle = True current = 0 while len(kList) > 0 and notCircle: temp = [] for i in kList: res.append(i) toLearn[i - 1] = current for j in nList[i - 1]: if toLearn[j - 1] >= 0: notCircle = False break break if toLearn[j - 1] == -1: temp.append(j) kList = temp current += 1 if notCircle: res.reverse() s = "" for i in res: s += str(i) + " " stdout.write(str(len(res)) + '\n') stdout.write(s[: -1] + '\n') else: stdout.write('-1\n') ``` No
103,375
[ 0.5517578125, 0.114990234375, 0.020294189453125, 0.11083984375, -0.3349609375, 0.1529541015625, -0.09344482421875, 0.2010498046875, 0.081298828125, 0.9287109375, 1.046875, 0.0196990966796875, 0.572265625, -0.81494140625, -0.458740234375, 0.164306640625, -0.7314453125, -1.1943359375...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Submitted Solution: ``` itog = '' result = [] iskl = 0 control = 0 maxway = -1 wayStolb = 0 table = [] fs = input() inp = fs.split(' ') nk = [int(i) for i in inp] ss = input() inp = ss.split(' ') maincour = [int(i) for i in inp] for i in range(0,nk[0]): table.append([]) s = input() inp = s.split(' ') t = [int(i) for i in inp] for j in range(0,t[0]+1): table[i].append(t[j]) for i in range (0,len(maincour)): #print(table[maincour[i]-1]) if table[maincour[i]-1][0] > maxway: wayStolb = maincour[i] - 1 maxway = table[maincour[i]-1][0] #print(wayStolb) #print(maxway) e = maxway stolb = wayStolb #4 startStolb = stolb while control != len(maincour) : while table[wayStolb][0] != 0: maxway = -1 e = table[stolb][0] for i in range(1,e+1): if table[table[stolb][i]-1][0] > maxway: wayStolb = table[stolb][i] - 1 maxway = table[table[stolb][i]-1][0] e = maxway if e > 0: stolb = wayStolb iskl = iskl + 1; if iskl > 100000: iskl = -1 break #print('WayStolb = '+str(wayStolb)) #print('Π‘Ρ‹Π» здСсь'+str(stolb)) if iskl == -1: result = '-1' break #print('ΠžΡΡ‚Π°Π½ΠΎΠ²ΠΊΠ° ' +str(wayStolb)) result.append(wayStolb+1) for i in range(0,len(maincour)): if wayStolb == maincour[i] - 1: control = control + 1; if control != len(maincour): table[stolb][0] = table[stolb][0] - 1 try: table[stolb].remove(wayStolb+1) except ValueError: for i in range(0,len(maincour)): if table[maincour[i]-1][0] == 0 and result.count(maincour[i]) == 0: result.append(maincour[i]) control = control + 1 if control != len(maincour): for i in range (0,len(maincour)): #print(table[maincour[i]-1]) if table[maincour[i]-1][0] > maxway: wayStolb = maincour[i] - 1 maxway = table[maincour[i]-1][0] #print(wayStolb) #print(maxway) e = maxway stolb = wayStolb #4 startStolb = stolb #print(table[stolb]) #print(table[stolb][1]) wayStolb = startStolb #print('wayStolb = '+str(wayStolb)) stolb = wayStolb if result != '-1': itog = itog + str(result[0]) for i in range(1,len(result)): itog = itog + ' ' + str(result[i]) print(len(result)) print(itog) else: print(result) ``` No
103,376
[ 0.5517578125, 0.114990234375, 0.020294189453125, 0.11083984375, -0.3349609375, 0.1529541015625, -0.09344482421875, 0.2010498046875, 0.081298828125, 0.9287109375, 1.046875, 0.0196990966796875, 0.572265625, -0.81494140625, -0.458740234375, 0.164306640625, -0.7314453125, -1.1943359375...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation). Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. Input The first line contains n and k (1 ≀ k ≀ n ≀ 105) β€” the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β€” numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0 ≀ ti ≀ n - 1) β€” the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β€” numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. Output Print -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β€” the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β€” numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them. Examples Input 6 2 5 3 0 0 0 2 2 1 1 4 1 5 Output 5 1 2 3 4 5 Input 9 3 3 9 5 0 0 3 9 4 5 0 0 1 8 1 6 1 2 2 1 2 Output 6 1 2 9 4 5 3 Input 3 3 1 2 3 1 2 1 3 1 1 Output -1 Note In the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. Submitted Solution: ``` import collections as col import itertools as its import sys import operator from copy import copy, deepcopy class Solver: def __init__(self): pass def solve(self): n, k = map(int, input().split()) q = list(map(lambda x: int(x) - 1, input().split())) used = [False] * n for e in q: used[e] = True edges = [[] for _ in range(n)] redges = [[] for _ in range(n)] for i in range(n): l = list(map(lambda x: int(x) - 1, input().split()))[1:] edges[i] = l for e in l: redges[e].append(i) degs = [len(edges[i]) for i in range(n)] d = 0 while d < len(q): v = q[d] d += 1 for e in edges[v]: if not used[e]: used[e] = True q.append(e) q = q[::-1] nq = [] for v in q: if degs[v] == 0: nq.append(v) d = 0 while d < len(nq): v = nq[d] d += 1 for e in redges[v]: degs[e] -= 1 if degs[e] == 0: nq.append(e) if len(q) != len(nq): print(-1) return print(len(nq)) print(' '.join(map(lambda x: str(x + 1), nq))) if __name__ == '__main__': s = Solver() s.solve() ``` No
103,377
[ 0.5517578125, 0.114990234375, 0.020294189453125, 0.11083984375, -0.3349609375, 0.1529541015625, -0.09344482421875, 0.2010498046875, 0.081298828125, 0.9287109375, 1.046875, 0.0196990966796875, 0.572265625, -0.81494140625, -0.458740234375, 0.164306640625, -0.7314453125, -1.1943359375...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Tags: dp, math, number theory, sortings Correct Solution: ``` for _ in range(int(input())): length=int(input()) array=list(map(int,input().split())) array.sort() cnt=[0]*(max(array)+1) dp=[0]*(max(array)+1) for x in array: cnt[x]+=1 """ [3, 7, 9, 14, 63] """ for i in range(1,len(dp)): dp[i]+=cnt[i] for j in range(i,len(dp),i): dp[j]=max(dp[j],dp[i]) print(length-max(dp)) ```
103,903
[ 0.3251953125, 0.01552581787109375, 0.498779296875, 0.12744140625, -0.517578125, -0.55712890625, -0.2139892578125, 0.0394287109375, 0.34228515625, 0.6083984375, 0.87841796875, -0.1024169921875, 0.025665283203125, -1.0341796875, -0.65234375, -0.283447265625, -0.3916015625, -0.4079589...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Tags: dp, math, number theory, sortings Correct Solution: ``` # Legends Always Come Up with Solution # Author: Manvir Singh import os from io import BytesIO, IOBase import sys from collections import defaultdict, deque, Counter from math import sqrt, pi, ceil, log, inf, gcd, floor from itertools import combinations, permutations from bisect import * from fractions import Fraction from heapq import * from random import randint def main(): for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) ma=max(a) b=Counter(a) c=sorted(set(a)) d=[0]*(ma+1) d[c[-1]] =b[c[-1]] ans = b[c[-1]] c.pop() c.reverse() for i in range(len(c)): j=2*c[i] zz=0 while j<=ma: zz=max(zz,d[j]) j+=c[i] d[c[i]]=b[c[i]]+zz ans=max(ans,d[c[i]]) print(n-ans) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main() ```
103,904
[ 0.337890625, 0.021636962890625, 0.48291015625, 0.126953125, -0.5224609375, -0.56298828125, -0.22021484375, 0.035064697265625, 0.338623046875, 0.6201171875, 0.8798828125, -0.1417236328125, 0.043060302734375, -1.05078125, -0.64990234375, -0.29296875, -0.397705078125, -0.3828125, -0...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Tags: dp, math, number theory, sortings Correct Solution: ``` import os,io input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from collections import deque for i in range(int(input())): n=int(input()) alist=list(map(int,input().split())) maxN=int(2e5+1) anslist=[0]*maxN blist=[0]*maxN for i,val in enumerate(alist):blist[val]+=1 for i in range(1,maxN): if blist[i]==0: continue anslist[i]+=blist[i] for j in range(2*i,maxN,i): anslist[j]=max(anslist[i],anslist[j]) print(n-max(anslist)) ```
103,905
[ 0.34375, 0.033905029296875, 0.49853515625, 0.1181640625, -0.53076171875, -0.5703125, -0.228759765625, 0.045318603515625, 0.3525390625, 0.63232421875, 0.853515625, -0.1414794921875, 0.044189453125, -1.0419921875, -0.63671875, -0.282470703125, -0.392578125, -0.413330078125, -0.8828...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Tags: dp, math, number theory, sortings Correct Solution: ``` import sys import math def II(): return int(sys.stdin.readline()) def LI(): return list(map(int, sys.stdin.readline().split())) def MI(): return map(int, sys.stdin.readline().split()) def SI(): return sys.stdin.readline().strip() def FACT(n, mod): s = 1 facts = [1] for i in range(1,n+1): s*=i s%=mod facts.append(s) return facts[n] def C(n, k, mod): return (FACT(n,mod) * pow((FACT(k,mod)*FACT(n-k,mod))%mod,mod-2, mod))%mod t = II() for q in range(t): n = II() a = LI() inf = max(a)+1 cnt = [0 for i in range(inf)] for i in a: cnt[i]+=1 dp = [0 for i in range(inf)] for i in range(1,inf): dp[i]+=cnt[i] for j in range(i*2,inf, i): dp[j] = max(dp[j], dp[i]) print(n-max(dp)) ```
103,906
[ 0.32568359375, 0.049835205078125, 0.494873046875, 0.1212158203125, -0.548828125, -0.55029296875, -0.2340087890625, 0.05499267578125, 0.34326171875, 0.63330078125, 0.86767578125, -0.1146240234375, 0.04034423828125, -1.05859375, -0.6376953125, -0.280517578125, -0.3974609375, -0.41674...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Tags: dp, math, number theory, sortings Correct Solution: ``` import sys import copy input=sys.stdin.readline for z in range(int(input())): n=int(input()) a=list(map(int,input().split())) cnt=[0]*(2*10**5+10) cnt2=[0]*(2*10**5+10) a.sort() num10=-1 cnt10=0 a2=[] for i in range(n): if num10!=a[i]: if cnt10!=0: a2.append(num10) cnt[num10]=cnt10 cnt10=1 num10=a[i] else: cnt10+=1 if cnt10!=0: a2.append(num10) cnt[num10]=cnt10 cnt2=copy.copy(cnt) a2.sort() for i in range(len(a2)): b=a2[i] num11=cnt2[b] for j in range(b*2,2*10**5+10,b): cnt2[j]=max(cnt2[j],num11+cnt[j]) ans=n+10 for i in range(len(a2)): ans=min(ans,n-cnt2[a2[i]]) print(ans) ```
103,907
[ 0.343994140625, 0.0302734375, 0.49951171875, 0.1273193359375, -0.53955078125, -0.5576171875, -0.2379150390625, 0.040771484375, 0.33837890625, 0.62353515625, 0.84619140625, -0.1072998046875, 0.04608154296875, -1.056640625, -0.6474609375, -0.28369140625, -0.383056640625, -0.419677734...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Tags: dp, math, number theory, sortings Correct Solution: ``` from sys import stdin from collections import Counter input = stdin.readline for test in range(int(input())): n = int(input()) lst = list(map(int, input().strip().split())) N = max(lst) + 1 po = [0] * N cnt = Counter(lst) for k in range(1, N): po[k] += cnt.get(k, 0) for i in range(2 * k, N, k): po[i] = max(po[i], po[k]) print(n - max(po)) ```
103,908
[ 0.322998046875, 0.037139892578125, 0.50927734375, 0.126220703125, -0.5556640625, -0.55419921875, -0.2376708984375, 0.036224365234375, 0.3369140625, 0.625, 0.84423828125, -0.1171875, 0.047332763671875, -1.068359375, -0.65771484375, -0.29345703125, -0.40869140625, -0.40673828125, -...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Tags: dp, math, number theory, sortings Correct Solution: ``` from bisect import bisect_left for _ in range(int(input())): n = int(input()) l = list(map(int, input().split())) l.sort() m = max(l) z = [0] * (m+1) f = [0] * (m+1) for i in range(n): z[l[i]] += 1 for i in sorted(set(l)): b = i+i f[i] += z[i] while b <= m: f[b] = max(f[b], f[i]) b += i print(n-max(f)) ```
103,909
[ 0.265869140625, 0.062744140625, 0.489013671875, 0.136474609375, -0.59375, -0.5673828125, -0.1788330078125, -0.0245361328125, 0.337158203125, 0.66796875, 0.8837890625, -0.06781005859375, 0.09027099609375, -1.1064453125, -0.67138671875, -0.30908203125, -0.406005859375, -0.45776367187...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Tags: dp, math, number theory, sortings Correct Solution: ``` from collections import Counter #fk this shit def f(arr): cnt=Counter(arr) mxn=max(arr)+100 factor=[0]*(mxn) for i in range(1,len(factor)): factor[i]+=cnt.get(i,0) for j in range(2*i,mxn,i): factor[j]=max(factor[i],factor[j]) return len(arr)-max(factor) for i in range(int(input())): s=input() lst=list(map(int,input().strip().split())) print(f(lst)) ```
103,910
[ 0.3955078125, 0.0115966796875, 0.420166015625, 0.1820068359375, -0.5380859375, -0.57666015625, -0.20947265625, 0.056915283203125, 0.378173828125, 0.6162109375, 0.86083984375, -0.07135009765625, 0.04791259765625, -1.0830078125, -0.650390625, -0.29833984375, -0.387451171875, -0.39453...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` from collections import Counter MX = 200001 def solve(arr): total = len(arr) cnt = [0] * MX for a in arr: cnt[a] += 1 u = sorted(set(arr)) loc = [-1] * MX for i,a in enumerate(u): loc[a] = i N = len(u) dp = [0] * N for i,a in enumerate(u): dp[i] = max(dp[i], cnt[a]) for b in range(2*a,MX,a): j = loc[b] if j >= 0: dp[j] = max(dp[j], dp[i] + cnt[b]) return total - max(dp) for _ in range(int(input())): input() arr = list(map(int,input().split())) print(solve(arr)) ``` Yes
103,911
[ 0.367919921875, 0.06451416015625, 0.364990234375, 0.111572265625, -0.63916015625, -0.5087890625, -0.256103515625, 0.089111328125, 0.285888671875, 0.56494140625, 0.76220703125, -0.045318603515625, 0.02227783203125, -1.0595703125, -0.70654296875, -0.2958984375, -0.34326171875, -0.404...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): def __init__(self, file): self.newlines = 0 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() # -------------------------------------------------------------------- def RL(): return map(int, sys.stdin.readline().split()) def RLL(): return list(map(int, sys.stdin.readline().split())) def N(): return int(input()) def S(): return input().strip() def print_list(l): print(' '.join(map(str, l))) # sys.setrecursionlimit(200000) # import random # from functools import reduce # from functools import lru_cache # from heapq import * # from collections import deque as dq # import math # import bisect as bs from collections import Counter # from collections import defaultdict as dc for t in range(N()): n = N() a = RLL() count = Counter(a) dp = [0] * 200001 for i in range(1, 200001): if count[i] == 0: continue dp[i] += count[i] for j in range(2 * i, 200001, i): dp[j] = max(dp[i], dp[j]) print(n - max(dp)) ``` Yes
103,912
[ 0.3583984375, 0.0275115966796875, 0.369384765625, 0.1343994140625, -0.67431640625, -0.50390625, -0.234375, 0.09619140625, 0.277587890625, 0.60009765625, 0.7666015625, -0.049835205078125, 0.01364898681640625, -1.0400390625, -0.69873046875, -0.28369140625, -0.317138671875, -0.4509277...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` import sys,math def main(): for _ in range(int(sys.stdin.readline().strip())): n=int(sys.stdin.readline().strip()) arr=list(map(int,sys.stdin.readline().strip().split())) table=[0]*(200001) dp=[0]*(200001) for i in range(n): table[arr[i]]+=1 for i in range(1,200001): dp[i]+=table[i] if dp[i]>0: for j in range(2*i,200001,i): dp[j]=max(dp[j],dp[i]) ans=n-max(dp) sys.stdout.write(str(ans)+'\n') main() ``` Yes
103,913
[ 0.340576171875, 0.06109619140625, 0.389404296875, 0.1475830078125, -0.63818359375, -0.4853515625, -0.252197265625, 0.09002685546875, 0.251708984375, 0.5693359375, 0.79052734375, -0.08367919921875, -0.0006961822509765625, -1.078125, -0.71142578125, -0.292236328125, -0.32275390625, -...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` factorsMemo=[-1 for _ in range(200001)] def getAllFactors(x): #returns a sorted list of all the factors or divisors of x (including 1 and x) if factorsMemo[x]==-1: factors=[] for i in range(1,int(x**0.5)+1): if x%i==0: factors.append(i) if x//i!=i: factors.append(x//i) factorsMemo[x]=factors return factorsMemo[x] def main(): t=int(input()) allAns=[] for _ in range(t): n=int(input()) a=readIntArr() a.sort() dp=[-inf for _ in range(200001)] #dp[previous number]max number of elements before and including it to be beautiful} maxSizeOfBeautifulArray=0 for x in a: maxPrevCnts=0 for f in getAllFactors(x): maxPrevCnts=max(maxPrevCnts,dp[f]) dp[x]=1+maxPrevCnts maxSizeOfBeautifulArray=max(maxSizeOfBeautifulArray,dp[x]) allAns.append(n-maxSizeOfBeautifulArray) multiLineArrayPrint(allAns) return import sys input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) #import sys #input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] inf=float('inf') MOD=10**9+7 main() ``` Yes
103,914
[ 0.373779296875, 0.058074951171875, 0.391845703125, 0.133056640625, -0.6298828125, -0.51904296875, -0.266357421875, 0.07781982421875, 0.1917724609375, 0.5517578125, 0.80224609375, -0.06939697265625, 0.034515380859375, -1.0927734375, -0.693359375, -0.2900390625, -0.30517578125, -0.45...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` import sys,math # FASTEST IO from io import BytesIO, IOBase from types import GeneratorType BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os 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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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: self.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) # End of FASTEST IO def main(): for _ in range(int(sys.stdin.readline().strip())): n=int(sys.stdin.readline().strip()) arr=list(map(int,sys.stdin.readline().strip().split())) table=[0]*(200001) dp=[0]*(200001) for i in range(n): table[arr[i]]+=1 for i in range(1,200001): for j in range(2*i,200001,i): dp[j]=max(dp[j],table[i]+dp[i]) ans=n-max(dp) sys.stdout.write(str(ans)+'\n') main() ``` No
103,915
[ 0.36572265625, 0.033905029296875, 0.3564453125, 0.11541748046875, -0.67822265625, -0.5107421875, -0.242431640625, 0.097412109375, 0.274658203125, 0.5908203125, 0.7451171875, -0.075927734375, 0.051727294921875, -1.060546875, -0.69482421875, -0.331298828125, -0.30517578125, -0.424072...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` import heapq __all__ = ['MappedQueue'] class MappedQueue(object): """The MappedQueue class implements an efficient minimum heap. The smallest element can be popped in O(1) time, new elements can be pushed in O(log n) time, and any element can be removed or updated in O(log n) time. The queue cannot contain duplicate elements and an attempt to push an element already in the queue will have no effect. MappedQueue complements the heapq package from the python standard library. While MappedQueue is designed for maximum compatibility with heapq, it has slightly different functionality. Examples -------- A `MappedQueue` can be created empty or optionally given an array of initial elements. Calling `push()` will add an element and calling `pop()` will remove and return the smallest element. >>> q = MappedQueue([916, 50, 4609, 493, 237]) >>> q.push(1310) True >>> x = [q.pop() for i in range(len(q.h))] >>> x [50, 237, 493, 916, 1310, 4609] Elements can also be updated or removed from anywhere in the queue. >>> q = MappedQueue([916, 50, 4609, 493, 237]) >>> q.remove(493) >>> q.update(237, 1117) >>> x = [q.pop() for i in range(len(q.h))] >>> x [50, 916, 1117, 4609] References ---------- .. [1] Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. (2001). Introduction to algorithms second edition. .. [2] Knuth, D. E. (1997). The art of computer programming (Vol. 3). Pearson Education. """ def __init__(self, data=[]): """Priority queue class with updatable priorities. """ self.h = list(data) self.d = dict() self._heapify() def __len__(self): return len(self.h) def _heapify(self): """Restore heap invariant and recalculate map.""" heapq.heapify(self.h) self.d = dict([(elt, pos) for pos, elt in enumerate(self.h)]) if len(self.h) != len(self.d): raise AssertionError("Heap contains duplicate elements") def push(self, elt): """Add an element to the queue.""" # If element is already in queue, do nothing if elt in self.d: return False # Add element to heap and dict pos = len(self.h) self.h.append(elt) self.d[elt] = pos # Restore invariant by sifting down self._siftdown(pos) return True def pop(self): """Remove and return the smallest element in the queue.""" # Remove smallest element elt = self.h[0] del self.d[elt] # If elt is last item, remove and return if len(self.h) == 1: self.h.pop() return elt # Replace root with last element last = self.h.pop() self.h[0] = last self.d[last] = 0 # Restore invariant by sifting up, then down pos = self._siftup(0) self._siftdown(pos) # Return smallest element return elt def update(self, elt, new): """Replace an element in the queue with a new one.""" # Replace pos = self.d[elt] self.h[pos] = new del self.d[elt] self.d[new] = pos # Restore invariant by sifting up, then down pos = self._siftup(pos) self._siftdown(pos) def remove(self, elt): """Remove an element from the queue.""" # Find and remove element try: pos = self.d[elt] del self.d[elt] except KeyError: # Not in queue raise # If elt is last item, remove and return if pos == len(self.h) - 1: self.h.pop() return # Replace elt with last element last = self.h.pop() self.h[pos] = last self.d[last] = pos # Restore invariant by sifting up, then down pos = self._siftup(pos) self._siftdown(pos) def _siftup(self, pos): """Move element at pos down to a leaf by repeatedly moving the smaller child up.""" h, d = self.h, self.d elt = h[pos] # Continue until element is in a leaf end_pos = len(h) left_pos = (pos << 1) + 1 while left_pos < end_pos: # Left child is guaranteed to exist by loop predicate left = h[left_pos] try: right_pos = left_pos + 1 right = h[right_pos] # Out-of-place, swap with left unless right is smaller if right < left: h[pos], h[right_pos] = right, elt pos, right_pos = right_pos, pos d[elt], d[right] = pos, right_pos else: h[pos], h[left_pos] = left, elt pos, left_pos = left_pos, pos d[elt], d[left] = pos, left_pos except IndexError: # Left leaf is the end of the heap, swap h[pos], h[left_pos] = left, elt pos, left_pos = left_pos, pos d[elt], d[left] = pos, left_pos # Update left_pos left_pos = (pos << 1) + 1 return pos def _siftdown(self, pos): """Restore invariant by repeatedly replacing out-of-place element with its parent.""" h, d = self.h, self.d elt = h[pos] # Continue until element is at root while pos > 0: parent_pos = (pos - 1) >> 1 parent = h[parent_pos] if parent > elt: # Swap out-of-place element with parent h[parent_pos], h[pos] = elt, parent parent_pos, pos = pos, parent_pos d[elt] = pos d[parent] = parent_pos else: # Invariant is satisfied break return pos ########################################################## ########################################################## ########################################################## from collections import Counter # from sortedcontainers import SortedList t = int(input()) DEBUG = False for asdasd in range(t): # with open('temp.txt', 'w') as file: # for i in range(1, 200001): # file.write(str(i) + ' ') # break n = int(input()) arr = [int(i) for i in input().split(" ")] # if n==200000: # DEBUG = True # if DEBUG and asdasd == 3: # arr.insert(0,n) # line = str(arr) # n = 400 # x = [line[i:i+n] for i in range(0, len(line), n)] # for asd in x: # print(asd) arr.sort(reverse = True) # print(arr) count = dict(Counter(arr)) edges = {} ########################################## # DOESNT REALLY WORK ########################################## # heads = set() # for x in count: # edges[x] = set() # heads_to_remove = set() # for head in heads: # if head % x == 0: # edges[x].update(edges[head]) # edges[x].add(head) # heads_to_remove.add(head) # heads -= heads_to_remove # heads.add(x) # # print(edges) # edges_copy = edges.copy() # for x, edge_set in edges.items(): # for e in edge_set: # edges_copy[e].add(x) # edges = edges_copy ############################################ print('x1') ########################################## # TRYING N^2 EDGEs ########################################## for x in count: edges[x] = set() count_list = list(count.items()) for i in range(len(count_list)): if i % 10 == 0: print(i/len(count_list)) for j in range(i+1, len(count_list)): if count_list[i][0] % count_list[j][0] == 0 or count_list[j][0] % count_list[i][0] == 0: edges[count_list[i][0]].add(count_list[j][0]) edges[count_list[j][0]].add(count_list[i][0]) ############################################ print('x2') edge_count = {} total_edges = 0 for x, edge_set in edges.items(): edge_count[x] = count[x]-1 for e in edge_set: edge_count[x] += count[e] total_edges += count[x] * edge_count[x] total_edges //= 2 NODE_VALUE = 1 N_EDGES = 0 # queue = SortedList(list(edge_count.items()), key=lambda x: -x[N_EDGES]) # for key, value in edge_count.items(): # edge_count[key] = value * count[key] queue = MappedQueue([(n_edges, node_value) for node_value, n_edges in edge_count.items()]) # print('edges:', edges) # print('edge_count:', edge_count) # print('total_edges', total_edges) # print() # print('queue:', queue) # print() remaining_nodes = n # print('total_edges:', total_edges, 'remaining_nodes:', remaining_nodes) # print() # print(count) while total_edges != remaining_nodes*(remaining_nodes-1)//2: small = queue.pop() # remaining_nodes -= count[small[NODE_VALUE]] remaining_nodes -= 1 # print('popping node:', small[NODE_VALUE], 'edges:', small[N_EDGES]) # print(queue) for e in edges[small[NODE_VALUE]]: # print('updating edge', e) # queue.remove((e, edge_count[e])) queue.remove((edge_count[e], e)) # print('rem2', count[e] * count[small[NODE_VALUE]]) # edge_count[e] -= count[e] * count[small[NODE_VALUE]] # total_edges -= count[e] * count[small[NODE_VALUE]] # print('decreasing edge', e, ' edges by', 1) edge_count[e] -= 1 # print('decreasing total edges by', count[e]) total_edges -= count[e] if count[small[NODE_VALUE]] == 1: edges[e].remove(small[NODE_VALUE]) # queue.add((e, edge_count[e])) queue.push((edge_count[e], e)) # Edges between nodes of same value t = count[small[NODE_VALUE]] # print('rem1', t*(t-1)//2) t2 = t-1 total_edges -= t2 # print(t, '(*) decreasing total edges by', t2) count[small[NODE_VALUE]] -= 1 if count[small[NODE_VALUE]] != 0: queue.push((small[N_EDGES]-1, small[NODE_VALUE])) # print(queue) # print('total_edges:', total_edges, 'remaining_nodes:', remaining_nodes) # print() print(n - remaining_nodes) ``` No
103,916
[ 0.31640625, 0.12176513671875, 0.26416015625, 0.2032470703125, -0.60498046875, -0.455810546875, -0.267822265625, 0.06500244140625, 0.247802734375, 0.63427734375, 0.7265625, -0.018768310546875, 0.049041748046875, -1.0654296875, -0.6943359375, -0.294677734375, -0.317138671875, -0.4838...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` import os import sys from io import BytesIO, IOBase def main(): pass # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") from collections import defaultdict,Counter m=2*10**5+5 t=int(input()) for _ in range(t): n=int(input()) a=list(map(int,input().split())) c=Counter(a) greater_count=defaultdict(lambda: 0) #Stores number of numbers a given number(not necessarily in a) is greater than or equal to the numbers in a. greater_count[0]=c[0] for i in range(1,m+1): greater_count[i]=greater_count[i-1]+c[i] dp=[float('inf') for i in range(m+1)] for i in range(m,0,-1): dp[i]=n-greater_count[i-1] #number of numbers in a, strictly greater than i (this is worst case answer for the sublist consisting of all numbers in a >=i) for j in range(2*i,m,i): dp[i]=min(dp[i],dp[j]+greater_count[j-1]-greater_count[i]) #number of numbers in a, between (i,j) print(dp[1]) ``` No
103,917
[ 0.351806640625, 0.03912353515625, 0.341796875, 0.12225341796875, -0.6611328125, -0.51416015625, -0.2440185546875, 0.08929443359375, 0.2939453125, 0.5947265625, 0.744140625, -0.036285400390625, 0.0164642333984375, -1.041015625, -0.70361328125, -0.31201171875, -0.327880859375, -0.467...
24
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Polycarp found on the street an array a of n elements. Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i β‰  j: * a_i is divisible by a_j; * or a_j is divisible by a_i. For example, if: * n=5 and a=[7, 9, 3, 14, 63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met); * n=3 and a=[2, 14, 42], then the a array is beautiful; * n=4 and a=[45, 9, 3, 18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met); Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful. Input The first line contains one integer t (1 ≀ t ≀ 10) β€” the number of test cases. Then t test cases follow. The first line of each test case contains one integer n (1 ≀ n ≀ 2 β‹… 10^5) β€” the length of the array a. The second line of each test case contains n numbers a_1, a_2, …, a_n (1 ≀ a_i ≀ 2 β‹… 10^5) β€” elements of the array a. Output For each test case output one integer β€” the minimum number of elements that must be removed to make the array a beautiful. Example Input 4 5 7 9 3 14 63 3 2 14 42 4 45 9 3 18 3 2 2 8 Output 2 0 1 0 Note In the first test case, removing 7 and 14 will make array a beautiful. In the second test case, the array a is already beautiful. In the third test case, removing one of the elements 45 or 18 will make the array a beautiful. In the fourth test case, the array a is beautiful. Submitted Solution: ``` # Legends Always Come Up with Solution # Author: Manvir Singh import os from io import BytesIO, IOBase import sys from collections import defaultdict, deque, Counter from math import sqrt, pi, ceil, log, inf, gcd, floor from itertools import combinations, permutations from bisect import * from fractions import Fraction from heapq import * from random import randint def main(): for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) ma=max(a) b=[0]*(ma+1) for i in a: b[i]+=1 c=[] for i in range(1,ma+1): if b[i]: c.append(i) d = [0] * (ma + 1) d[c[-1]] =b[c[-1]] c.pop() c.reverse() ans=1 for i in range(len(c)): j=2*c[i] zz=0 while j<=ma: zz=max(zz,d[j]) j+=c[i] d[c[i]]=b[c[i]]+zz ans=max(ans,d[c[i]]) print(n-ans) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main() ``` No
103,918
[ 0.361328125, 0.03729248046875, 0.353759765625, 0.1251220703125, -0.63818359375, -0.51806640625, -0.241943359375, 0.09027099609375, 0.253662109375, 0.58349609375, 0.7744140625, -0.060150146484375, 0.00506591796875, -1.0341796875, -0.70703125, -0.323974609375, -0.32421875, -0.4003906...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip. Tags: implementation, math Correct Solution: ``` a,b,c=map(int,input().split()) fu=0 fu=min(a//3,b//2,c//2) a-=3*fu b-=2*fu c-=2*fu x=[1,2,3,1,3,2,1] k=0 m=0 for i in range(len(x)): d=0 f=0 j=i a1=a b1=b c1=c z=1 while z==1: k=x[j] if (k==1)&(a1>0): a1-=1 d+=1 if (k==2)&(b1>0): b1-=1 d+=1 if (k==3)&(c1>0): c1-=1 d+=1 if d==f: z=0 else: f=d j+=1 j=j%7 if d>m: m=d print(7*fu+m) ```
105,305
[ 0.488525390625, 0.026641845703125, 0.1583251953125, 0.05682373046875, -0.58740234375, -0.0675048828125, -0.3359375, 0.5205078125, 0.05413818359375, 0.84521484375, 0.55908203125, -0.2039794921875, 0.304931640625, -0.69287109375, -0.6806640625, 0.0122833251953125, -0.57763671875, -0....
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip. Tags: implementation, math Correct Solution: ``` def dfs(day_l,day_r,a,b,c): global span if day_l<1 or day_r>14: return if a<0 or b<0 or c<0: return #print(day_l,day_r,a,b,c) span=max(span,day_r-day_l+1) if day_l-1 in [1,4,7,8,11,14]: dfs(day_l-1,day_r,a-1,b,c) elif day_l-1 in [2,6,9,13]: dfs(day_l-1,day_r,a,b-1,c) elif day_l-1 in [3,5,10,12]: dfs(day_l-1,day_r,a,b,c-1) if day_r+1 in [1,4,7,8,11,14]: dfs(day_l,day_r+1,a-1,b,c) elif day_r+1 in [2,6,9,13]: dfs(day_l,day_r+1,a,b-1,c) elif day_r+1 in [3,5,10,12]: dfs(day_l,day_r+1,a,b,c-1) a,b,c=list(map(int,input().split())) weeks=min([a//3,b//2,c//2]) a-=weeks*3 b-=weeks*2 c-=weeks*2 if weeks>0: span=0 if a>0: day_min,day_max=7,7 dfs(7,7,a-1,b,c) ans1=7*weeks+span span=0 day_min,day_max=7,7 dfs(7,7,a-1+3,b+2,c+2) ans2=7*(weeks-1)+span print(max(ans1,ans2)) else: span=0 for i in [4,5,6,7]: day_min,day_max=i,i if i in [4,7]: dfs(i,i,a-1,b,c) elif i==6: dfs(i,i,a,b-1,c) else: dfs(i,i,a,b,c-1) print(span) ```
105,306
[ 0.46826171875, 0.007076263427734375, 0.2012939453125, 0.09881591796875, -0.55810546875, -0.0200042724609375, -0.3193359375, 0.52978515625, 0.053558349609375, 0.83740234375, 0.56103515625, -0.254150390625, 0.304931640625, -0.64111328125, -0.67919921875, 0.0208587646484375, -0.59912109...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip. Tags: implementation, math Correct Solution: ``` a, b, c = map(int, input().split()) x = min(a//3, b//2, c//2) a,b,c = a-3*x, b-2*x, c-2*x z = [1,1,2,3,1,3,2] m = 0 for i in range(7): lis = [0,a,b,c] j = i cnt = 0 while(lis[1]>=0 and lis[2]>=0 and lis[3]>=0): lis[z[j]] -= 1 j = (j+1)%7 cnt += 1 m = max(m,cnt-1) print(x*7+m) ```
105,307
[ 0.473876953125, 0.03607177734375, 0.14697265625, 0.06829833984375, -0.568359375, -0.056243896484375, -0.3388671875, 0.52294921875, 0.05780029296875, 0.849609375, 0.5517578125, -0.2105712890625, 0.290771484375, -0.7041015625, -0.6767578125, 0.019683837890625, -0.583984375, -0.624511...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip. Tags: implementation, math Correct Solution: ``` a = [int(i) for i in input().split()] days = [0, 1, 2, 0, 2, 1, 0] week = min(a[0] // 3, a[1] // 2, a[2] // 2) a[0], a[1], a[2] = a[0] - week * 3, a[1] - week * 2, a[2] - week * 2 m = 0 for day in range(7): b = a.copy() c = 0 for this_day in range(7): if b[days[(day + this_day) % 7]] > 0: b[days[(day + this_day) % 7]] -= 1 c += 1 else: break if c > m: m = c print(m + week * 7) ```
105,308
[ 0.4990234375, 0.03656005859375, 0.156982421875, 0.0379638671875, -0.59521484375, -0.040618896484375, -0.3134765625, 0.5146484375, 0.07281494140625, 0.8466796875, 0.55224609375, -0.2156982421875, 0.28271484375, -0.705078125, -0.6884765625, 0.0151519775390625, -0.57763671875, -0.6284...
24
Provide tags and a correct Python 3 solution for this coding contest problem. Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food: * on Mondays, Thursdays and Sundays he eats fish food; * on Tuesdays and Saturdays he eats rabbit stew; * on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains: * a daily rations of fish food; * b daily rations of rabbit stew; * c daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Input The first line of the input contains three positive integers a, b and c (1 ≀ a, b, c ≀ 7β‹…10^8) β€” the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly. Output Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally. Examples Input 2 1 1 Output 4 Input 3 2 2 Output 7 Input 1 100 1 Output 3 Input 30 20 10 Output 39 Note In the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday β€” rabbit stew and during Wednesday β€” chicken stake. So, after four days of the trip all food will be eaten. In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack. In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be 99 portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip. Tags: implementation, math Correct Solution: ``` a,b,c = map(int,input().strip().split()) ans = 0 basi = min(c//2,min(b//2,a//3)) #print(basi) aa = a- 3*basi bb = b - 2*basi cc = c - 2*basi mp = {0:'aa',1:'aa',2:'bb',3:'cc',4:'aa',5:'cc',6:'bb'} #print(aa,bb,cc) for i in range(7): aaa = aa bbb = bb ccc = cc an = 0 for j in range(i,i+15): if mp[j%7]=='aa': aaa-=1 if mp[j%7]=='bb': bbb-=1 if mp[j%7]=='cc': ccc-=1 if aaa<0 or bbb<0 or ccc<0: break else: an+=1 ans = max(ans,basi*7+an) print(ans) ```
105,309
[ 0.488037109375, 0.0313720703125, 0.153564453125, 0.036224365234375, -0.56787109375, -0.05145263671875, -0.36474609375, 0.513671875, 0.0682373046875, 0.82666015625, 0.5361328125, -0.2208251953125, 0.292236328125, -0.68896484375, -0.6689453125, -0.007472991943359375, -0.58349609375, ...
24