message stringlengths 2 59.7k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 37 108k | cluster float64 20 20 | __index_level_0__ int64 74 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied:
* a12 + a22 + ... + an2 β₯ x
* a1 + a2 + ... + an β€ y
Input
The first line contains three space-separated integers n, x and y (1 β€ n β€ 105, 1 β€ x β€ 1012, 1 β€ y β€ 106).
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is recommended to use cin, cout streams or the %I64d specificator.
Output
Print n positive integers that satisfy the conditions, one integer per line. If such numbers do not exist, print a single number "-1". If there are several solutions, print any of them.
Examples
Input
5 15 15
Output
4
4
1
1
2
Input
2 3 2
Output
-1
Input
1 99 11
Output
11 | instruction | 0 | 106,169 | 20 | 212,338 |
Tags: greedy
Correct Solution:
```
n, x, y = map(int, input().split(' '))
if (y < n):
print(-1)
quit()
ones = n - 1
left = (y-n+1)**2 + ones
if left < x:
print(-1)
else:
for i in range(n-1):
print(1)
print(y-n+1)
``` | output | 1 | 106,169 | 20 | 212,339 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied:
* a12 + a22 + ... + an2 β₯ x
* a1 + a2 + ... + an β€ y
Input
The first line contains three space-separated integers n, x and y (1 β€ n β€ 105, 1 β€ x β€ 1012, 1 β€ y β€ 106).
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is recommended to use cin, cout streams or the %I64d specificator.
Output
Print n positive integers that satisfy the conditions, one integer per line. If such numbers do not exist, print a single number "-1". If there are several solutions, print any of them.
Examples
Input
5 15 15
Output
4
4
1
1
2
Input
2 3 2
Output
-1
Input
1 99 11
Output
11 | instruction | 0 | 106,170 | 20 | 212,340 |
Tags: greedy
Correct Solution:
```
import sys
n,x,y=map(int,sys.stdin.readline().split())
if (y-n+1<1) or (y-n+1)**2+(n-1)<x:
print(-1)
else:
print(y-n+1)
for i in range(n-1):
print(1)
``` | output | 1 | 106,170 | 20 | 212,341 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied:
* a12 + a22 + ... + an2 β₯ x
* a1 + a2 + ... + an β€ y
Input
The first line contains three space-separated integers n, x and y (1 β€ n β€ 105, 1 β€ x β€ 1012, 1 β€ y β€ 106).
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is recommended to use cin, cout streams or the %I64d specificator.
Output
Print n positive integers that satisfy the conditions, one integer per line. If such numbers do not exist, print a single number "-1". If there are several solutions, print any of them.
Examples
Input
5 15 15
Output
4
4
1
1
2
Input
2 3 2
Output
-1
Input
1 99 11
Output
11 | instruction | 0 | 106,171 | 20 | 212,342 |
Tags: greedy
Correct Solution:
```
n, x, y = map(int, input().split(' '))
if(y < n):
print(-1)
else:
val = (y - n + 1)**2 + (n-1)
if(val < x):
print(-1)
else:
for i in range(n-1):
print(1)
print(y - n + 1)
``` | output | 1 | 106,171 | 20 | 212,343 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied:
* a12 + a22 + ... + an2 β₯ x
* a1 + a2 + ... + an β€ y
Input
The first line contains three space-separated integers n, x and y (1 β€ n β€ 105, 1 β€ x β€ 1012, 1 β€ y β€ 106).
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is recommended to use cin, cout streams or the %I64d specificator.
Output
Print n positive integers that satisfy the conditions, one integer per line. If such numbers do not exist, print a single number "-1". If there are several solutions, print any of them.
Examples
Input
5 15 15
Output
4
4
1
1
2
Input
2 3 2
Output
-1
Input
1 99 11
Output
11 | instruction | 0 | 106,172 | 20 | 212,344 |
Tags: greedy
Correct Solution:
```
from math import ceil, sqrt
x,y,z = map(int, input().split())
t = x-1
if x > z:
print(-1)
elif y >= z and t + (ceil(sqrt(y -t)) ** 2) >= y and t + ceil(sqrt(y -t)) <= z:
k = ceil(sqrt(y-t))
for c in range(x-1):
print(1)
print(k)
elif z >= y and t + (ceil(sqrt(z - t)) ** 2) >= y and t + ceil(sqrt(z - t)) <= z:
k = ceil(sqrt(z-t))
for c in range(x-1):
print(1)
print(k)
else:
print(-1)
#
``` | output | 1 | 106,172 | 20 | 212,345 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied:
* a12 + a22 + ... + an2 β₯ x
* a1 + a2 + ... + an β€ y
Input
The first line contains three space-separated integers n, x and y (1 β€ n β€ 105, 1 β€ x β€ 1012, 1 β€ y β€ 106).
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is recommended to use cin, cout streams or the %I64d specificator.
Output
Print n positive integers that satisfy the conditions, one integer per line. If such numbers do not exist, print a single number "-1". If there are several solutions, print any of them.
Examples
Input
5 15 15
Output
4
4
1
1
2
Input
2 3 2
Output
-1
Input
1 99 11
Output
11 | instruction | 0 | 106,173 | 20 | 212,346 |
Tags: greedy
Correct Solution:
```
n, x, y = map(int, input().split())
if n > y:
print(-1)
else:
left = y - n
left += 1
if left ** 2 + n - 1 >= x:
print(left)
for _ in range(n - 1):
print(1)
else:
print(-1)
``` | output | 1 | 106,173 | 20 | 212,347 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied:
* a12 + a22 + ... + an2 β₯ x
* a1 + a2 + ... + an β€ y
Input
The first line contains three space-separated integers n, x and y (1 β€ n β€ 105, 1 β€ x β€ 1012, 1 β€ y β€ 106).
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is recommended to use cin, cout streams or the %I64d specificator.
Output
Print n positive integers that satisfy the conditions, one integer per line. If such numbers do not exist, print a single number "-1". If there are several solutions, print any of them.
Examples
Input
5 15 15
Output
4
4
1
1
2
Input
2 3 2
Output
-1
Input
1 99 11
Output
11 | instruction | 0 | 106,174 | 20 | 212,348 |
Tags: greedy
Correct Solution:
```
n,x,y=map(int,input().split())
n-=1
t=y-n
print(['1\n'*n+str(t),-1][t<1 or t*t+n<x])
# Made By Mostafa_Khaled
``` | output | 1 | 106,174 | 20 | 212,349 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied:
* a12 + a22 + ... + an2 β₯ x
* a1 + a2 + ... + an β€ y
Input
The first line contains three space-separated integers n, x and y (1 β€ n β€ 105, 1 β€ x β€ 1012, 1 β€ y β€ 106).
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is recommended to use cin, cout streams or the %I64d specificator.
Output
Print n positive integers that satisfy the conditions, one integer per line. If such numbers do not exist, print a single number "-1". If there are several solutions, print any of them.
Examples
Input
5 15 15
Output
4
4
1
1
2
Input
2 3 2
Output
-1
Input
1 99 11
Output
11 | instruction | 0 | 106,175 | 20 | 212,350 |
Tags: greedy
Correct Solution:
```
n, x, y = map(int, input().split())
curr = y - n + 1
if curr <= 0:
print(-1)
else:
if curr ** 2 + (n - 1) < x:
print(-1)
else:
for i in range(n-1):
print(1)
print(y - n + 1)
``` | output | 1 | 106,175 | 20 | 212,351 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Input
The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.
Output
Output a single integer.
Examples
Input
A278832
Output
0
Input
A089956
Output
0
Input
A089957
Output
1
Input
A144045
Output
1 | instruction | 0 | 106,273 | 20 | 212,546 |
Tags: *special, implementation
Correct Solution:
```
k=input().lower()
h=int(k,16)
print(h%2)
``` | output | 1 | 106,273 | 20 | 212,547 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Input
The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.
Output
Output a single integer.
Examples
Input
A278832
Output
0
Input
A089956
Output
0
Input
A089957
Output
1
Input
A144045
Output
1 | instruction | 0 | 106,274 | 20 | 212,548 |
Tags: *special, implementation
Correct Solution:
```
# d = {'0':0, '1': 1, '2':1, '3':2, '4':1,'5':2, '6':2,'7':3,'8':1,'9':2,'A':2}
s = input()
# count = 0
# for i in s:
# count+=d[i]
count = int(s[-1])
if(count%2==0):
print('0')
else:
print('1')
``` | output | 1 | 106,274 | 20 | 212,549 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Input
The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.
Output
Output a single integer.
Examples
Input
A278832
Output
0
Input
A089956
Output
0
Input
A089957
Output
1
Input
A144045
Output
1 | instruction | 0 | 106,275 | 20 | 212,550 |
Tags: *special, implementation
Correct Solution:
```
if int(input(),16)%2==0:
print(0)
else:
print(1)
``` | output | 1 | 106,275 | 20 | 212,551 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Input
The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.
Output
Output a single integer.
Examples
Input
A278832
Output
0
Input
A089956
Output
0
Input
A089957
Output
1
Input
A144045
Output
1 | instruction | 0 | 106,276 | 20 | 212,552 |
Tags: *special, implementation
Correct Solution:
```
n=input()
if(int(n[len(n)-1])%2==0):
print("0")
else:
print("1")
``` | output | 1 | 106,276 | 20 | 212,553 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Input
The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.
Output
Output a single integer.
Examples
Input
A278832
Output
0
Input
A089956
Output
0
Input
A089957
Output
1
Input
A144045
Output
1 | instruction | 0 | 106,277 | 20 | 212,554 |
Tags: *special, implementation
Correct Solution:
```
N = int(input()[-1])
print(N%2)
``` | output | 1 | 106,277 | 20 | 212,555 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Input
The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.
Output
Output a single integer.
Examples
Input
A278832
Output
0
Input
A089956
Output
0
Input
A089957
Output
1
Input
A144045
Output
1 | instruction | 0 | 106,278 | 20 | 212,556 |
Tags: *special, implementation
Correct Solution:
```
ans = int(input(), 16)
if ans%2 == 0:
print(0)
else:
print(1)
``` | output | 1 | 106,278 | 20 | 212,557 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Input
The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.
Output
Output a single integer.
Examples
Input
A278832
Output
0
Input
A089956
Output
0
Input
A089957
Output
1
Input
A144045
Output
1 | instruction | 0 | 106,279 | 20 | 212,558 |
Tags: *special, implementation
Correct Solution:
```
import math
# Initialising hex string
ini_string = input()
# Code to convert hex to binary
n = int(ini_string, 16)
bStr = ''
while n > 0:
bStr = str(n % 2) + bStr
n = n >> 1
res = bStr
# Print the resultant string
print(res[len(res) - 1])
``` | output | 1 | 106,279 | 20 | 212,559 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Input
The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.
Output
Output a single integer.
Examples
Input
A278832
Output
0
Input
A089956
Output
0
Input
A089957
Output
1
Input
A144045
Output
1 | instruction | 0 | 106,280 | 20 | 212,560 |
Tags: *special, implementation
Correct Solution:
```
str = input()
res = int(str, 16)
if res & 1 == 0:
print(0)
else:
print(1)
``` | output | 1 | 106,280 | 20 | 212,561 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Input
The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.
Output
Output a single integer.
Examples
Input
A278832
Output
0
Input
A089956
Output
0
Input
A089957
Output
1
Input
A144045
Output
1
Submitted Solution:
```
# your code goes here
a=input()
if int(a[6])%2==0:
print('0')
else:
print('1')
``` | instruction | 0 | 106,281 | 20 | 212,562 |
Yes | output | 1 | 106,281 | 20 | 212,563 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Input
The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.
Output
Output a single integer.
Examples
Input
A278832
Output
0
Input
A089956
Output
0
Input
A089957
Output
1
Input
A144045
Output
1
Submitted Solution:
```
s=str(input())
t=0
if(int(s[len(s)-1])%2==0):
print(0)
else:
print(1)
``` | instruction | 0 | 106,282 | 20 | 212,564 |
Yes | output | 1 | 106,282 | 20 | 212,565 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Input
The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.
Output
Output a single integer.
Examples
Input
A278832
Output
0
Input
A089956
Output
0
Input
A089957
Output
1
Input
A144045
Output
1
Submitted Solution:
```
s = str(input())
a = int(s[-1])
if a % 2 == 0:
print("0")
else:
print("1")
``` | instruction | 0 | 106,283 | 20 | 212,566 |
Yes | output | 1 | 106,283 | 20 | 212,567 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Input
The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.
Output
Output a single integer.
Examples
Input
A278832
Output
0
Input
A089956
Output
0
Input
A089957
Output
1
Input
A144045
Output
1
Submitted Solution:
```
x = input()
x = int(x,16)
print(x % 2)
``` | instruction | 0 | 106,284 | 20 | 212,568 |
Yes | output | 1 | 106,284 | 20 | 212,569 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Input
The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.
Output
Output a single integer.
Examples
Input
A278832
Output
0
Input
A089956
Output
0
Input
A089957
Output
1
Input
A144045
Output
1
Submitted Solution:
```
import random
a=input()
print(random.randrange(0,2,1))
``` | instruction | 0 | 106,285 | 20 | 212,570 |
No | output | 1 | 106,285 | 20 | 212,571 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Input
The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.
Output
Output a single integer.
Examples
Input
A278832
Output
0
Input
A089956
Output
0
Input
A089957
Output
1
Input
A144045
Output
1
Submitted Solution:
```
print("1")
``` | instruction | 0 | 106,286 | 20 | 212,572 |
No | output | 1 | 106,286 | 20 | 212,573 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Input
The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.
Output
Output a single integer.
Examples
Input
A278832
Output
0
Input
A089956
Output
0
Input
A089957
Output
1
Input
A144045
Output
1
Submitted Solution:
```
inp = input()
import random
random.seed(inp)
print(random.randint(0, 1))
``` | instruction | 0 | 106,288 | 20 | 212,576 |
No | output | 1 | 106,288 | 20 | 212,577 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them.
Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her.
Input
The first line contains the integers n and d (1β€ nβ€ 10^5, 0β€ dβ€ 9). The second line contains n integers a_i (1β€ a_iβ€ 1000).
Output
On the first line, print the number of chosen cards k (1β€ kβ€ n). On the next line, print the numbers written on the chosen cards in any order.
If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1.
Examples
Input
6 4
4 11 8 2 1 13
Output
5
1 2 4 11 13
Input
3 1
2 4 6
Output
-1
Input
5 7
1 3 1 5 3
Output
-1
Input
6 3
8 9 4 17 11 5
Output
3
9 11 17
Input
5 6
2 2 2 2 2
Output
4
2 2 2 2
Note
In the first example, 1 Γ 2 Γ 4 Γ 11 Γ 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144.
In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1.
In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7.
In the fourth example, 9 Γ 11 Γ 17 = 1683, which ends with the digit 3.
In the fifth example, 2 Γ 2 Γ 2 Γ 2 = 16, which ends with the digit 6. | instruction | 0 | 106,388 | 20 | 212,776 |
Tags: dp, math, number theory
Correct Solution:
```
# your code goes here
import math
import sys
import argparse
def main():
input = sys.stdin.readline
n, d = list(map(int,input().split()))
a = list(map(float,input().split()))
b = []
for i in range(0,n):
b.append(int(a[i]))
a[i] = math.log(a[i])
mlog = sum(a)
f = [[0.0 for j in range(0,11)] for i in range(0,n)]
c = [[[0,0] for j in range(0,11)] for i in range(0,n)]
ans = []
for i in range(n):
if (i != 0) :
for j in range(10):
f[i][j] = f[i-1][j]
c[i][j][0] = c[i-1][j][0]
c[i][j][1] = c[i-1][j][1]
for j in range(10):
if f[i-1][j]+a[i] > f[i][(j*b[i])%10]:
f[i][(j*b[i])%10] = f[i-1][j]+a[i]
c[i][(j*b[i])%10][0] = i
c[i][(j*b[i])%10][1] = j
if f[i][b[i]%10] < a[i]:
f[i][b[i]%10] = a[i]
c[i][b[i]%10][0] = i
c[i][b[i]%10][1] = -1
continue
if (i == 0) :
for j in range(10):
f[i][j] = math.log(0.0001)-mlog
c[i][j][0] = -1
c[i][j][1] = -1
f[i][b[0]%10] = a[0]
c[i][b[0]%10][0] = 0
c[i][b[0]%10][1] = -1
continue
if(f[n-1][d] <= 0):
print(-1)
return 0
x,y = c[n-1][d][0],c[n-1][d][1]
while y != -1:
ans.append(b[x])
u = x-1
if u < 0:
break
x = c[u][y][0]
y = c[u][y][1]
if x >= 0:
ans.append(b[x])
print(len(ans))
print(" ".join(list(map(str,ans))))
if __name__ == "__main__":
if 0:
print("test2")
main()
``` | output | 1 | 106,388 | 20 | 212,777 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them.
Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her.
Input
The first line contains the integers n and d (1β€ nβ€ 10^5, 0β€ dβ€ 9). The second line contains n integers a_i (1β€ a_iβ€ 1000).
Output
On the first line, print the number of chosen cards k (1β€ kβ€ n). On the next line, print the numbers written on the chosen cards in any order.
If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1.
Examples
Input
6 4
4 11 8 2 1 13
Output
5
1 2 4 11 13
Input
3 1
2 4 6
Output
-1
Input
5 7
1 3 1 5 3
Output
-1
Input
6 3
8 9 4 17 11 5
Output
3
9 11 17
Input
5 6
2 2 2 2 2
Output
4
2 2 2 2
Note
In the first example, 1 Γ 2 Γ 4 Γ 11 Γ 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144.
In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1.
In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7.
In the fourth example, 9 Γ 11 Γ 17 = 1683, which ends with the digit 3.
In the fifth example, 2 Γ 2 Γ 2 Γ 2 = 16, which ends with the digit 6. | instruction | 0 | 106,389 | 20 | 212,778 |
Tags: dp, math, number theory
Correct Solution:
```
import math
n, d = map(int, input().split())
a = [int(_) for _ in input().split()]
dp = [[-1e10] * 10 for _ in range(n + 1)]
come = [[(0, 0, 0) for i in range(10)] for j in range(n + 1)]
dp[0][1] = 0
for i in range(n):
for j in range(10):
val = dp[i][j] + math.log(a[i])
if dp[i + 1][(j * a[i]) % 10] <= val:
dp[i + 1][(j * a[i]) % 10] = val
come[i + 1][(j * a[i]) % 10] = (i, j, 1)
val = dp[i][j]
if dp[i + 1][j] <= val:
dp[i + 1][j] = val
come[i + 1][j] = (i, j, 0)
now = n
dig = d
soln = []
while now > 0:
if come[now][dig][2] == 1:
soln.append(a[now - 1])
now, dig = come[now][dig][:2]
prod = 1
for i in soln: prod = (prod * i) % 10
if prod == d and len(soln) > 0:
print(len(soln))
print(' '.join(map(str, soln)))
else:
print(-1)
``` | output | 1 | 106,389 | 20 | 212,779 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them.
Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her.
Input
The first line contains the integers n and d (1β€ nβ€ 10^5, 0β€ dβ€ 9). The second line contains n integers a_i (1β€ a_iβ€ 1000).
Output
On the first line, print the number of chosen cards k (1β€ kβ€ n). On the next line, print the numbers written on the chosen cards in any order.
If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1.
Examples
Input
6 4
4 11 8 2 1 13
Output
5
1 2 4 11 13
Input
3 1
2 4 6
Output
-1
Input
5 7
1 3 1 5 3
Output
-1
Input
6 3
8 9 4 17 11 5
Output
3
9 11 17
Input
5 6
2 2 2 2 2
Output
4
2 2 2 2
Note
In the first example, 1 Γ 2 Γ 4 Γ 11 Γ 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144.
In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1.
In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7.
In the fourth example, 9 Γ 11 Γ 17 = 1683, which ends with the digit 3.
In the fifth example, 2 Γ 2 Γ 2 Γ 2 = 16, which ends with the digit 6. | instruction | 0 | 106,390 | 20 | 212,780 |
Tags: dp, math, number theory
Correct Solution:
```
# your code goes here
import math
import sys
import argparse
def main():
input = sys.stdin.readline
n, d = list(map(int,input().split()))
a = list(map(float,input().split()))
b = []
for i in range(0,n):
b.append(int(a[i]))
a[i] = math.log(a[i])
mlog = sum(a)
f = [[0.0 for j in range(0,11)] for i in range(0,n)]
c = [[[0,0] for j in range(0,11)] for i in range(0,n)]
ans = []
for i in range(n):
if (i != 0) :
for j in range(10):
f[i][j] = f[i-1][j]
c[i][j][0] = c[i-1][j][0]
c[i][j][1] = c[i-1][j][1]
for j in range(10):
if f[i-1][j]+a[i] > f[i][(j*b[i])%10]:
f[i][(j*b[i])%10] = f[i-1][j]+a[i]
c[i][(j*b[i])%10][0] = i
c[i][(j*b[i])%10][1] = j
if f[i][b[i]%10] < a[i]:
f[i][b[i]%10] = a[i]
c[i][b[i]%10][0] = i
c[i][b[i]%10][1] = -1
continue
if (i == 0) :
for j in range(10):
f[i][j] = math.log(0.0001)-mlog
c[i][j][0] = -1
c[i][j][1] = -1
f[i][b[0]%10] = a[0]
c[i][b[0]%10][0] = 0
c[i][b[0]%10][1] = -1
continue
if(f[n-1][d] <= 0):
print(-1)
return 0
x,y = c[n-1][d][0],c[n-1][d][1]
while y != -1:
ans.append(b[x])
u = x-1
if u < 0:
break
x = c[u][y][0]
y = c[u][y][1]
if x >= 0:
ans.append(b[x])
print(len(ans))
print(" ".join(list(map(str,ans))))
if __name__ == "__main__":
if 0:
print("hello")
main()
``` | output | 1 | 106,390 | 20 | 212,781 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them.
Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her.
Input
The first line contains the integers n and d (1β€ nβ€ 10^5, 0β€ dβ€ 9). The second line contains n integers a_i (1β€ a_iβ€ 1000).
Output
On the first line, print the number of chosen cards k (1β€ kβ€ n). On the next line, print the numbers written on the chosen cards in any order.
If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1.
Examples
Input
6 4
4 11 8 2 1 13
Output
5
1 2 4 11 13
Input
3 1
2 4 6
Output
-1
Input
5 7
1 3 1 5 3
Output
-1
Input
6 3
8 9 4 17 11 5
Output
3
9 11 17
Input
5 6
2 2 2 2 2
Output
4
2 2 2 2
Note
In the first example, 1 Γ 2 Γ 4 Γ 11 Γ 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144.
In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1.
In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7.
In the fourth example, 9 Γ 11 Γ 17 = 1683, which ends with the digit 3.
In the fifth example, 2 Γ 2 Γ 2 Γ 2 = 16, which ends with the digit 6. | instruction | 0 | 106,391 | 20 | 212,782 |
Tags: dp, math, number theory
Correct Solution:
```
import math
import random
import sys
import time
seed = int(time.time())
random.seed(seed)
def equalsf(a, b): return abs(a - b) < 1e-6
def solve(N, D, A):
lgA = [math.log(a) for a in A]
dp = [[None for _ in range(10)] for _ in range(N)]
parents = [[-1 for _ in range(10)] for _ in range(N)]
for i in range(N):
#if i > 0:
# print(i - 1, dp[i - 1], file=sys.stderr)
# print(i - 1, parents[i - 1], file=sys.stderr)
d = A[i] % 10
dp[i][d] = lgA[i]
if i == 0:
continue
# propagate
for prev_d in range(10):
if dp[i][prev_d] is None or (dp[i - 1][prev_d] is not None and
dp[i][prev_d] < dp[i - 1][prev_d]):
dp[i][prev_d] = dp[i - 1][prev_d]
parents[i][prev_d] = prev_d
for prev_d in range(10):
if dp[i - 1][prev_d] is None:
continue
prod_d = (d * prev_d) % 10
cand = dp[i - 1][prev_d] + lgA[i]
if dp[i][prod_d] is None or dp[i][prod_d] < cand:
dp[i][prod_d] = cand
parents[i][prod_d] = prev_d
#print(N - 1, dp[N - 1], file=sys.stderr)
#print(N - 1, parents[N - 1], file=sys.stderr)
#if dp[N - 1][D] is not None:
# print("found solution:", round(math.exp(dp[N - 1][d])), file=sys.stderr)
#else:
# print("no solution", file=sys.stderr)
# reconstruct answer
ans = []
parent = D
for i in range(N - 1, -1, -1):
if dp[i][parent] is None:
break
prev_p = parents[i][parent]
if i > 0 and prev_p >= 0:
print(i, "cur:", parent, "prev:", prev_p, file=sys.stderr)
if dp[i - 1][prev_p] is not None and equalsf(dp[i - 1][prev_p] + lgA[i], dp[i][parent]):
ans.append(A[i])
parent = prev_p
else:
ans.append(A[i])
break
return ans
def main():
N, D = [int(x) for x in input().strip().split()]
A = [int(x) for x in input().strip().split()]
ans = solve(N, D, A)
if len(ans) == 0:
print(-1)
else:
print(len(ans))
print(' '.join([str(x) for x in ans]))
if '__main__'==__name__:
main()
``` | output | 1 | 106,391 | 20 | 212,783 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them.
Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her.
Input
The first line contains the integers n and d (1β€ nβ€ 10^5, 0β€ dβ€ 9). The second line contains n integers a_i (1β€ a_iβ€ 1000).
Output
On the first line, print the number of chosen cards k (1β€ kβ€ n). On the next line, print the numbers written on the chosen cards in any order.
If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1.
Examples
Input
6 4
4 11 8 2 1 13
Output
5
1 2 4 11 13
Input
3 1
2 4 6
Output
-1
Input
5 7
1 3 1 5 3
Output
-1
Input
6 3
8 9 4 17 11 5
Output
3
9 11 17
Input
5 6
2 2 2 2 2
Output
4
2 2 2 2
Note
In the first example, 1 Γ 2 Γ 4 Γ 11 Γ 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144.
In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1.
In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7.
In the fourth example, 9 Γ 11 Γ 17 = 1683, which ends with the digit 3.
In the fifth example, 2 Γ 2 Γ 2 Γ 2 = 16, which ends with the digit 6. | instruction | 0 | 106,392 | 20 | 212,784 |
Tags: dp, math, number theory
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
from math import log10
def main():
log = [0]+[log10(i) for i in range(1,1001)]
unit = [i%10 for i in range(1001)]
n,d = map(int,input().split())
a = list(map(int,input().split()))
dp = [[0]*10 for _ in range(n+1)]
# unit digit ; index
ne = [[i for i in range(10)] for _ in range(n+1)]
take = [[0]*10 for _ in range(n+1)]
for i in range(n):
dp[i+1],uni = dp[i][:],unit[a[i]]
for j in range(10):
if not dp[i][j]:
continue
xx,un = dp[i][j]+log[a[i]],unit[j*uni]
if xx > dp[i+1][un]:
dp[i+1][un],ne[i+1][un],take[i+1][un] = xx,j,1
if log[a[i]] > dp[i+1][uni]:
dp[i+1][uni],take[i+1][uni],ne[i+1][uni] = log[a[i]],1,-1
ind,ans = d,[]
for i in range(n,0,-1):
if take[i][ind]:
ans.append(a[i-1])
ind = ne[i][ind]
if ind == -1:
break
if len(ans):
print(len(ans))
print(*ans)
elif d == 1 and a.count(1):
print(1)
print(1)
else:
print(-1)
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | output | 1 | 106,392 | 20 | 212,785 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them.
Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her.
Input
The first line contains the integers n and d (1β€ nβ€ 10^5, 0β€ dβ€ 9). The second line contains n integers a_i (1β€ a_iβ€ 1000).
Output
On the first line, print the number of chosen cards k (1β€ kβ€ n). On the next line, print the numbers written on the chosen cards in any order.
If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1.
Examples
Input
6 4
4 11 8 2 1 13
Output
5
1 2 4 11 13
Input
3 1
2 4 6
Output
-1
Input
5 7
1 3 1 5 3
Output
-1
Input
6 3
8 9 4 17 11 5
Output
3
9 11 17
Input
5 6
2 2 2 2 2
Output
4
2 2 2 2
Note
In the first example, 1 Γ 2 Γ 4 Γ 11 Γ 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144.
In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1.
In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7.
In the fourth example, 9 Γ 11 Γ 17 = 1683, which ends with the digit 3.
In the fifth example, 2 Γ 2 Γ 2 Γ 2 = 16, which ends with the digit 6. | instruction | 0 | 106,393 | 20 | 212,786 |
Tags: dp, math, number theory
Correct Solution:
```
import math
def main():
n, d = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
if d!=5 and d!=0:
a = list(filter(lambda x: x%5!=0 ,a))
if d&1:
a = list(filter(lambda x: x%2, a))
n = len(a)
dp = [[-1e6 for _ in range(10)] for _ in range(n + 1)]
path = [[(0, 0, 0) for _ in range(10)] for _ in range(n + 1)]
dp[0][1] = 0
for i in range(n):
for j in range(10):
val = dp[i][j] + math.log(a[i])
if dp[i + 1][(j * a[i])%10] <= val:
dp[i + 1][(j * a[i])%10] = val
path[i + 1][(j * a[i])%10] = (i, j, 1)
val = dp[i][j]
if dp[i + 1][j] <= val:
dp[i + 1][j] = val
path[i + 1][j] = (i, j , 0)
ans = []
test, pd = 1, d
while n > 0 :
if path[n][d][2] == 1:
ans.append(a[n - 1])
test = (test * a[n - 1])%10
n,d = path[n][d][:2]
if test == pd and len(ans) > 0:
print(len(ans))
print(' '.join(map(str, ans)))
else:
print(-1)
if __name__=='__main__':
main()
``` | output | 1 | 106,393 | 20 | 212,787 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them.
Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her.
Input
The first line contains the integers n and d (1β€ nβ€ 10^5, 0β€ dβ€ 9). The second line contains n integers a_i (1β€ a_iβ€ 1000).
Output
On the first line, print the number of chosen cards k (1β€ kβ€ n). On the next line, print the numbers written on the chosen cards in any order.
If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1.
Examples
Input
6 4
4 11 8 2 1 13
Output
5
1 2 4 11 13
Input
3 1
2 4 6
Output
-1
Input
5 7
1 3 1 5 3
Output
-1
Input
6 3
8 9 4 17 11 5
Output
3
9 11 17
Input
5 6
2 2 2 2 2
Output
4
2 2 2 2
Note
In the first example, 1 Γ 2 Γ 4 Γ 11 Γ 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144.
In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1.
In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7.
In the fourth example, 9 Γ 11 Γ 17 = 1683, which ends with the digit 3.
In the fifth example, 2 Γ 2 Γ 2 Γ 2 = 16, which ends with the digit 6. | instruction | 0 | 106,394 | 20 | 212,788 |
Tags: dp, math, number theory
Correct Solution:
```
import collections
import string
import math
import copy
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)
def input(): return sys.stdin.readline().rstrip("\r\n")
# n = 0
# m = 0
# n = int(input())
# li = [int(i) for i in input().split()]
# s = sorted(li)
"""
from dataclasses import dataclass
@dataclass
class point:
x: float
y: float
@dataclass
class line:
A: float
B: float
C: float
def gety(self, x):
return (self.A*x+self.C)/-self.B
def getx(self, y):
return (self.B*y+self.C)/-self.A
def k(self):
return -self.A/self.B
def b(self):
return -self.C/self.B
def dist(self, p: point):
return abs((self.A*p.x+self.B*p.y+self.C)/(self.A**2+self.B**2)**0.5)
def calc_line(u: point, v: point):
return line(A=u.y-v.y, B=v.x-u.x, C=u.y*(u.x-v.x)-u.x*(u.y-v.y))
def is_parallel(u: line, v: line) -> bool:
f1 = False
f2 = False
try:
k1 = u.k()
except:
f1 = True
try:
k2 = v.k()
except:
f2 = True
if f1 != f2:
return False
return f1 or k1 == k2
def seg_len(_from: point, _to: point):
return ((_from.x - _to.x)**2 + (_from.y - _to.y)**2) ** 0.5
def in_range(_from: point, _to: point, _point: point) -> bool:
if _from.x < _to.x:
if _from.y < _to.y:
return _from.x <= _point.x <= _to.x and _from.y <= _point.y <= _to.y
else:
return _from.x <= _point.x <= _to.x and _from.y >= _point.y >= _to.y
else:
if _from.y < _to.y:
return _from.x >= _point.x >= _to.x and _from.y <= _point.y <= _to.y
else:
return _from.x >= _point.x >= _to.x and _from.y >= _point.y >= _to.y
def intersect(u: line, v: line) -> point:
tx = (u.B*v.C-v.B*u.C)/(v.B*u.A-u.B*v.A)
if u.B!=0.0:
ty = -u.A*tx/u.B - u.C/u.B
else:
ty = -v.A*tx/v.B - v.C/v.B
return point(x=tx, y=ty)
def in_direction(_from: point, _to: point, _point: point) -> bool:
if _from.x < _to.x:
if _from.y < _to.y:
return _to.x < _point.x and _to.y < _point.y
else:
return _to.x < _point.x and _point.y <= _to.y
else:
if _from.y < _to.y:
return _to.x >= _point.x and _to.y < _point.y
else:
return _to.x >= _point.x and _point.y <= _to.y
"""
mo = int(1e9+7)
def exgcd(a, b):
if not b:
return 1, 0
y, x = exgcd(b, a % b)
y -= a//b * x
return x, y
def getinv(a, m):
x, y = exgcd(a, m)
return -1 if x == 1 else x % m
def comb(n, b):
res = 1
b = min(b, n-b)
for i in range(b):
res = res*(n-i)*getinv(i+1, mo) % mo
# res %= mo
return res % mo
def quickpower(a, n):
res = 1
while n:
if n & 1:
res = res * a % mo
n >>= 1
a = a*a % mo
return res
def dis(a, b):
return abs(a[0]-b[0]) + abs(a[1]-b[1])
def getpref(x):
if x > 1:
return (x)*(x-1) >> 1
else:
return 0
def orafli(upp):
primes = []
marked = [False for i in range(upp+3)]
prvs = [i for i in range(upp+3)]
for i in range(2, upp):
if not marked[i]:
primes.append(i)
for j in primes:
if i*j >= upp:
break
marked[i*j] = True
prvs[i*j] = j
if i % j == 0:
break
return primes, prvs
def lower_ord(c: str) -> int:
return ord(c)-97
def upper_ord(c: str) -> int:
return ord(c) - 65
def read_list():
return [int(i) for i in input().split()]
def read_int():
s = input().split()
if len(s) == 1:
return int(s[0])
else:
return map(int, s)
def ask(s):
print(f"? {s}", flush=True)
def answer(s):
print(f"{s}", flush=True)
import random
def solve():
n, d = read_int()
l = read_list()
# dp = [[0 for i in range(10)] for i in range(n)]
dp = {}
pv = []
for i in l:
cd = copy.deepcopy(dp)
cp = {}
for k, v in dp.items():
lg = math.log(i,2)
if v+lg >cd.get(k*i%10,0):
# prvcd = cd[k*i%10]
cp[v+lg] = v
cd[k*i%10] = v+lg
# cd[k*i%10] = max(cd.get(k*i%10, 1), v+math.log(i,2))
lg = math.log(i,2)
if lg > cd.get(i%10, 0):
cp[lg]=0
cd[i%10] = lg
pv.append(cp)
# cd[i%10] = max(cd.get(i%10, 1), math.log(i,2))
dp = cd
sel = []
if d not in dp:
print(-1)
else:
# print(dp[d])
# c = int(round(2**dp[d]))
# print(pv)
c = dp[d]
# rc = round(c,14)
while pv:
fac = pv.pop()
curfac = l.pop()
if c in fac:
sel.append(curfac)
c = fac[c]
# for i in l:
# if c%i==0:
# sel.append(i)
# c//=i
print(len(sel))
print(*sel)
# print(dp.get(d, -1))
# fi = open('C:\\cppHeaders\\CF2020.12.17\\test.data', 'r')
# def input(): return fi.readline().rstrip("\r\n")
# primes, prv = orafli(10001)
solve()
# t = int(input())
# for ti in range(t):
# print(f"Case #{ti+1}: ", end='')
# solve()
``` | output | 1 | 106,394 | 20 | 212,789 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them.
Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her.
Input
The first line contains the integers n and d (1β€ nβ€ 10^5, 0β€ dβ€ 9). The second line contains n integers a_i (1β€ a_iβ€ 1000).
Output
On the first line, print the number of chosen cards k (1β€ kβ€ n). On the next line, print the numbers written on the chosen cards in any order.
If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1.
Examples
Input
6 4
4 11 8 2 1 13
Output
5
1 2 4 11 13
Input
3 1
2 4 6
Output
-1
Input
5 7
1 3 1 5 3
Output
-1
Input
6 3
8 9 4 17 11 5
Output
3
9 11 17
Input
5 6
2 2 2 2 2
Output
4
2 2 2 2
Note
In the first example, 1 Γ 2 Γ 4 Γ 11 Γ 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144.
In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1.
In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7.
In the fourth example, 9 Γ 11 Γ 17 = 1683, which ends with the digit 3.
In the fifth example, 2 Γ 2 Γ 2 Γ 2 = 16, which ends with the digit 6. | instruction | 0 | 106,395 | 20 | 212,790 |
Tags: dp, math, number theory
Correct Solution:
```
#------------------Important Modules------------------#
from sys import stdin,stdout
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import *
from random import *
input=stdin.readline
prin=stdout.write
from random import sample
from collections import Counter,deque
from fractions import *
from math import sqrt,ceil,log2,gcd
#dist=[0]*(n+1)
mod=10**9+7
"""
class DisjSet:
def __init__(self, n):
self.rank = [1] * n
self.parent = [i for i in range(n)]
def find(self, x):
if (self.parent[x] != x):
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
xset = self.find(x)
yset = self.find(y)
if xset == yset:
return
if self.rank[xset] < self.rank[yset]:
self.parent[xset] = yset
elif self.rank[xset] > self.rank[yset]:
self.parent[yset] = xset
else:
self.parent[yset] = xset
self.rank[xset] = self.rank[xset] + 1
"""
def f(arr,i,j,d,dist):
if i==j:
return
nn=max(arr[i:j])
for tl in range(i,j):
if arr[tl]==nn:
dist[tl]=d
#print(tl,dist[tl])
f(arr,i,tl,d+1,dist)
f(arr,tl+1,j,d+1,dist)
#return dist
def ps(n):
cp=0;lk=0;arr={}
#print(n)
#cc=0;
while n%2==0:
n=n//2
#arr.append(n);arr.append(2**(lk+1))
lk+=1
for ps in range(3,ceil(sqrt(n))+1,2):
lk=0
cc=0
while n%ps==0:
n=n//ps
#cc=1
#arr.append(n);arr.append(ps**(lk+1))
lk+=1
if n!=1:
#lk+=1
#arr[n]=1
#ans*=n;
lk+=1
return False
#return arr
#print(arr)
return True
#count=0
#dp=[[0 for i in range(m)] for j in range(n)]
#[int(x) for x in input().strip().split()]
def gcd(x, y):
while(y):
x, y = y, x % y
return x
# Driver Code
def factorials(n,r):
#This calculates ncr mod 10**9+7
slr=n;dpr=r
qlr=1;qs=1
mod=10**9+7
for ip in range(n-r+1,n+1):
qlr=(qlr*ip)%mod
for ij in range(1,r+1):
qs=(qs*ij)%mod
#print(qlr,qs)
ans=(qlr*modInverse(qs))%mod
return ans
def modInverse(b):
qr=10**9+7
return pow(b, qr - 2,qr)
#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
def power(arr):
listrep = arr
subsets = []
for i in range(2**len(listrep)):
subset = []
for k in range(len(listrep)):
if i & 1<<k:
subset.append(listrep[k])
subsets.append(subset)
return subsets
def pda(n) :
list = []
for i in range(1, int(sqrt(n) + 1)) :
if (n % i == 0) :
if (n // i == i) :
list.append(i)
else :
list.append(n//i);list.append(i)
# The list will be printed in reverse
return list
def dis(xa,ya,xb,yb):
return sqrt((xa-xb)**2+(ya-yb)**2)
#### END ITERATE RECURSION ####
#===============================================================================================
#----------Input functions--------------------#
def ii():
return int(input())
def ilist():
return [int(x) for x in input().strip().split()]
def islist():
return list(map(str,input().split().rstrip()))
def inp():
return input().strip()
def google(test,ans):
return "Case #"+str(test)+": "+str(ans);
def overlap(x1,y1,x2,y2):
if x2>y1:
return y1-x2
if y1>y2:
return y2-x2
return y1-x2;
###-------------------------CODE STARTS HERE--------------------------------###########
def pal(s):
k=len(s)
n=len(s)//2
for i in range(n):
if s[i]==s[k-1-i]:
continue
else:
return 0
return 1
#########################################################################################
#t=int(input())
t=1
for p in range(t):
n,kll=ilist()
arr=[-1]
arr.extend(ilist())
dp=[[0 for i in range(10)] for j in range(n+1)]
pointer=[[[-1 for k in range(3)] for i in range(10)] for j in range(n+1)]
pp=[]
for i in range(1,n+1):
for j in range(10):
#dp[i][j]=dp[i-1][j]
last=arr[i]%10
for k in range(10):
#print(k*last,j)
#fs=dp[i-1][k]%10
fs=1 if dp[i-1][k]==0 else k
if (fs*last)%10==j:
if dp[i][j]<dp[i-1][k]+log2(arr[i]+0.01):
pointer[i][j][0]=0
pointer[i][j][1]=i-1
pointer[i][j][2]=k
dp[i][j]=max(dp[i-1][k]+log2(arr[i]+0.01),dp[i][j])
#print("dp[i-1][k] ",dp[i-1][k],"dp[i][j] ",dp[i][j],"j ",j,"i ",i,"k ",k)
if dp[i][j]<dp[i-1][j]:
pointer[i][j][0]=1
pointer[i][j][1]=i-1
pointer[i][j][2]=j
dp[i][j]=max(dp[i-1][j],dp[i][j])
ans=dp[n][kll]
if ans==0:
print(-1)
continue
#print(ans)
ap=n;jp=kll
count=0
while True:
up=ap
if pointer[ap][jp][0]!=0:
ap=pointer[up][jp][1]
jp=pointer[up][jp][2]
elif pointer[ap][jp][0]==0:
pp.append(arr[ap])
count+=1
ap=pointer[up][jp][1]
jp=pointer[up][jp][2]
if ap<=0:
break
print(count)
print(*pp)
#byevye
``` | output | 1 | 106,395 | 20 | 212,791 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them.
Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her.
Input
The first line contains the integers n and d (1β€ nβ€ 10^5, 0β€ dβ€ 9). The second line contains n integers a_i (1β€ a_iβ€ 1000).
Output
On the first line, print the number of chosen cards k (1β€ kβ€ n). On the next line, print the numbers written on the chosen cards in any order.
If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1.
Examples
Input
6 4
4 11 8 2 1 13
Output
5
1 2 4 11 13
Input
3 1
2 4 6
Output
-1
Input
5 7
1 3 1 5 3
Output
-1
Input
6 3
8 9 4 17 11 5
Output
3
9 11 17
Input
5 6
2 2 2 2 2
Output
4
2 2 2 2
Note
In the first example, 1 Γ 2 Γ 4 Γ 11 Γ 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144.
In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1.
In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7.
In the fourth example, 9 Γ 11 Γ 17 = 1683, which ends with the digit 3.
In the fifth example, 2 Γ 2 Γ 2 Γ 2 = 16, which ends with the digit 6.
Submitted Solution:
```
# your code goes here
import math
import sys
import argparse
def main():
input = sys.stdin.readline
n, d = list(map(int,input().split()))
a = list(map(float,input().split()))
b = []
for i in range(0,n):
b.append(int(a[i]))
a[i] = math.log(a[i])
mlog = sum(a)
f = [[0.0 for j in range(0,11)] for i in range(0,n)]
c = [[[0,0] for j in range(0,11)] for i in range(0,n)]
ans = []
for i in range(n):
if (i != 0) :
for j in range(10):
f[i][j] = f[i-1][j]
c[i][j][0] = c[i-1][j][0]
c[i][j][1] = c[i-1][j][1]
for j in range(10):
if f[i-1][j]+a[i] > f[i][(j*b[i])%10]:
f[i][(j*b[i])%10] = f[i-1][j]+a[i]
c[i][(j*b[i])%10][0] = i
c[i][(j*b[i])%10][1] = j
if f[i][b[i]%10] < a[i]:
f[i][b[i]%10] = a[i]
c[i][b[i]%10][0] = i
c[i][b[i]%10][1] = -1
continue
if (i == 0) :
for j in range(10):
f[i][j] = math.log(0.0001)-mlog
c[i][j][0] = -1
c[i][j][1] = -1
f[i][b[0]%10] = a[0]
c[i][b[0]%10][0] = 0
c[i][b[0]%10][1] = -1
continue
if(f[n-1][d] <= 0):
print(-1)
return 0
x,y = c[n-1][d][0],c[n-1][d][1]
while y != -1:
ans.append(b[x])
u = x-1
if u < 0:
break
x = c[u][y][0]
y = c[u][y][1]
if x >= 0:
ans.append(b[x])
print(len(ans))
print(" ".join(list(map(str,ans))))
if __name__ == "__main__":
if 0:
print("test1000")
main()
``` | instruction | 0 | 106,396 | 20 | 212,792 |
Yes | output | 1 | 106,396 | 20 | 212,793 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them.
Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her.
Input
The first line contains the integers n and d (1β€ nβ€ 10^5, 0β€ dβ€ 9). The second line contains n integers a_i (1β€ a_iβ€ 1000).
Output
On the first line, print the number of chosen cards k (1β€ kβ€ n). On the next line, print the numbers written on the chosen cards in any order.
If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1.
Examples
Input
6 4
4 11 8 2 1 13
Output
5
1 2 4 11 13
Input
3 1
2 4 6
Output
-1
Input
5 7
1 3 1 5 3
Output
-1
Input
6 3
8 9 4 17 11 5
Output
3
9 11 17
Input
5 6
2 2 2 2 2
Output
4
2 2 2 2
Note
In the first example, 1 Γ 2 Γ 4 Γ 11 Γ 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144.
In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1.
In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7.
In the fourth example, 9 Γ 11 Γ 17 = 1683, which ends with the digit 3.
In the fifth example, 2 Γ 2 Γ 2 Γ 2 = 16, which ends with the digit 6.
Submitted Solution:
```
from sys import stdin, stdout
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353
def inp(): return stdin.readline().strip()
def iinp(): return int(inp())
def out(var, end="\n"): stdout.write(str(var)+"\n")
def outa(*var, end="\n"): stdout.write(' '.join(map(str, var)) + end)
def lmp(): return list(mp())
def mp(): return map(int, inp().split())
def smp(): return map(str, inp().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(m, val) for j in range(n)]
def remadd(x, y): return 1 if x%y else 0
def ceil(a,b): return (a+b-1)//b
def isprime(x):
if x<=1: return False
if x in (2, 3): return True
if x%2 == 0: return False
for i in range(3, int(sqrt(x))+1, 2):
if x%i == 0: return False
return True
n, k = mp()
arr = lmp()
dp = l2d(n+1, 10, -1)
for i in range(1, n+1):
for j in range(10):
dp[i][j] = max(dp[i][j], dp[i-1][j])
if j == arr[i-1]%10:
dp[i][j] = max(dp[i][j], round(log(arr[i-1]), 6))
if dp[i-1][j]!=-1:
dp[i][(j*arr[i-1])%10] = max(dp[i][(j*arr[i-1])%10], round(dp[i-1][j]+log(arr[i-1]), 6))
ansl = []
j = k
flg = True
for i in range(n, 0, -1):
if dp[i][j] == -1:
flg = False
print(-1)
break
if dp[i][j]==dp[i-1][j]:
continue
elif dp[i][j]==round(log(arr[i-1]), 6):
ansl.append(arr[i-1])
break
else:
ansl.append(arr[i-1])
j = dp[i-1].index(round(dp[i][j]-log(arr[i-1]), 6))
if flg:
print(len(ansl))
print(*ansl)
``` | instruction | 0 | 106,397 | 20 | 212,794 |
Yes | output | 1 | 106,397 | 20 | 212,795 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them.
Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her.
Input
The first line contains the integers n and d (1β€ nβ€ 10^5, 0β€ dβ€ 9). The second line contains n integers a_i (1β€ a_iβ€ 1000).
Output
On the first line, print the number of chosen cards k (1β€ kβ€ n). On the next line, print the numbers written on the chosen cards in any order.
If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1.
Examples
Input
6 4
4 11 8 2 1 13
Output
5
1 2 4 11 13
Input
3 1
2 4 6
Output
-1
Input
5 7
1 3 1 5 3
Output
-1
Input
6 3
8 9 4 17 11 5
Output
3
9 11 17
Input
5 6
2 2 2 2 2
Output
4
2 2 2 2
Note
In the first example, 1 Γ 2 Γ 4 Γ 11 Γ 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144.
In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1.
In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7.
In the fourth example, 9 Γ 11 Γ 17 = 1683, which ends with the digit 3.
In the fifth example, 2 Γ 2 Γ 2 Γ 2 = 16, which ends with the digit 6.
Submitted Solution:
```
import time
#start_time = time.time()
#def TIME_(): print(time.time()-start_time)
import os, sys
from io import BytesIO, IOBase
from types import GeneratorType
from bisect import bisect_left, bisect_right
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string, heapq as h
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)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def getInt(): return int(input())
def getStrs(): return input().split()
def getInts(): return list(map(int,input().split()))
def getStr(): return input()
def listStr(): return list(input())
def getMat(n): return [getInts() for _ in range(n)]
def getBin(): return list(map(int,list(input())))
def isInt(s): return '0' <= s[0] <= '9'
def ceil_(a,b): return a//b + (a%b > 0)
MOD = 10**9 + 7
"""
1: {(1,1) (3,7) (9,9)}
2: {(1,2) (2,6) (3,4) (4,8) (6,7) (8,9)}
3: {(1,3) (7,9)}
4: {(1,4) (2,2) (2,7) (3,8) (4,6) (6,9) (8,8)}
5: {(1,5) (3,5) (5,5) (5,7) (5,9)}
6: {(1,6) (2,3) (2,8) (4,4) (4,9) (6,6) (7,8)}
7: {(1,7) (3,9)}
8: {(1,8) (2,4) (2,9) (3,6) (4,7) (6,8)}
9: {(1,9) (3,3) (7,7)}
Include all numbers ending in 1
Numbers ending in 3 go in cycles 3 -> 9 -> 7 -> 1
Let's pairwise multiply the 9s, fourwise multiply the 3s and 7s
We either include all 5s or no 5s
We definitely include:
all 1s
all but 3 to 6 of the 3s
all but 3 to 6 of the 7s
all but 1 to 2 of the 9s
all the 5s or none of them
2 4 8 6
4 6 4 6
6 6 6 6
8 4 2 6
19 5
37 6 40 50 27 2 9 45 10 8 40 1 37 14 14 30 29 8 9
"""
from random import randint as ri
def solve():
N, D = getInts()
A = getInts()
#N = ri(1,20)
#D = ri(1,9)
#A = [ri(1,50) for _ in range(N)]
#print(N,D)
#print(*A)
dec = [[] for _ in range(10)]
for a in A:
dec[a%10].append(a)
for i in range(10):
dec[i].sort()
if D == 0:
if not dec[0] and not (dec[2] and dec[5]):
print(-1)
return
else:
print(N)
print(*A)
return
else:
dec[0] = []
if D == 5:
if not dec[5]:
print(-1)
return
else:
ans = []
for a in A:
if a % 2:
ans.append(a)
print(len(ans))
print(*ans)
return
else:
dec[5] = []
ans = []
while dec[1]:
ans.append(dec[1].pop())
while len(dec[3]) > 6:
for _ in range(4):
ans.append(dec[3].pop())
while len(dec[7]) > 6:
for _ in range(4):
ans.append(dec[7].pop())
while len(dec[9]) > 2:
for _ in range(2):
ans.append(dec[9].pop())
#print(ans)
if D % 2:
A = []
for i in range(1,10,2):
while dec[i]:
A.append(dec[i].pop())
best = -1
best_mask = -1
for x in range(1,pow(2,len(A))):
mask = bin(x)[2:].zfill(len(A))
tmp = 1
for j in range(len(A)):
if mask[j] == '1':
tmp *= A[j]
if tmp % 10 == D and tmp > best:
best = tmp
best_mask = mask
if best != -1:
for j in range(len(A)):
if best_mask[j] == '1':
ans.append(A[j])
print(len(ans))
print(*ans)
return
elif (D == 1) and ans:
print(len(ans))
print(*ans)
return
else:
print(-1)
return
while dec[6]:
ans.append(dec[6].pop())
while len(dec[2]) > 6:
for _ in range(4):
ans.append(dec[2].pop())
while len(dec[8]) > 6:
for _ in range(4):
ans.append(dec[8].pop())
while len(dec[4]) > 2:
for _ in range(2):
ans.append(dec[4].pop())
#now I need the best mask for digit
A_odd = []
A_even = []
for i in range(0,10,2):
while dec[i]:
A_even.append(dec[i].pop())
while dec[i+1]:
A_odd.append(dec[i+1].pop())
best = [-1]*10
best_mask = [-1]*10
if ans:
best[1] = 1
best_mask[1] = 0
for x in range(1,pow(2,len(A_odd))):
mask = bin(x)[2:].zfill(len(A_odd))
tmp = 1
for j in range(len(A_odd)):
if mask[j] == '1':
tmp *= A_odd[j]
if tmp > best[tmp%10]:
best[tmp%10] = tmp
best_mask[tmp%10] = x
for x in range(1,pow(2,len(A_even))):
mask = bin(x)[2:].zfill(len(A_even))
tmp = 1
for j in range(len(A_even)):
if mask[j] == '1':
tmp *= A_even[j]
if tmp > best[tmp%10]:
best[tmp%10] = tmp
best_mask[tmp%10] = x
best_combo = -1
best_pair = [-1,-1]
for i in range(0,10,2):
for j in range(1,10,2):
if best[i] != -1 and best[j] != -1:
curr = best[i]*best[j]
if curr % 10 == D and curr > best_combo:
best_combo = curr
best_pair = [i,j]
if best[D] > best_combo:
x = best_mask[D]
mask = bin(x)[2:].zfill(len(A_even))
for j in range(len(A_even)):
if mask[j] == '1':
ans.append(A_even[j])
print(len(ans))
print(*ans)
return
#print(best_combo,best_pair)
#print(A_even,A_odd)
#print(best_mask[2],best_mask[9])
if best_pair == [-1,-1]:
print(-1)
return
k,i = best_pair
x = best_mask[i]
mask = bin(x)[2:].zfill(len(A_odd))
for j in range(len(A_odd)):
if mask[j] == '1':
ans.append(A_odd[j])
x = best_mask[k]
mask = bin(x)[2:].zfill(len(A_even))
for j in range(len(A_even)):
if mask[j] == '1':
ans.append(A_even[j])
print(len(ans))
print(*ans)
return
#for _ in range(getInt()):
#print(solve())
solve()
#TIME_()
``` | instruction | 0 | 106,398 | 20 | 212,796 |
Yes | output | 1 | 106,398 | 20 | 212,797 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them.
Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her.
Input
The first line contains the integers n and d (1β€ nβ€ 10^5, 0β€ dβ€ 9). The second line contains n integers a_i (1β€ a_iβ€ 1000).
Output
On the first line, print the number of chosen cards k (1β€ kβ€ n). On the next line, print the numbers written on the chosen cards in any order.
If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1.
Examples
Input
6 4
4 11 8 2 1 13
Output
5
1 2 4 11 13
Input
3 1
2 4 6
Output
-1
Input
5 7
1 3 1 5 3
Output
-1
Input
6 3
8 9 4 17 11 5
Output
3
9 11 17
Input
5 6
2 2 2 2 2
Output
4
2 2 2 2
Note
In the first example, 1 Γ 2 Γ 4 Γ 11 Γ 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144.
In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1.
In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7.
In the fourth example, 9 Γ 11 Γ 17 = 1683, which ends with the digit 3.
In the fifth example, 2 Γ 2 Γ 2 Γ 2 = 16, which ends with the digit 6.
Submitted Solution:
```
# your code goes here
import math
import sys
import argparse
def main():
input = sys.stdin.readline
n, d = list(map(int,input().split()))
a = list(map(float,input().split()))
b = []
for i in range(0,n):
b.append(int(a[i]))
a[i] = math.log(a[i])
mlog = sum(a)
f = [[0.0 for j in range(0,11)] for i in range(0,n)]
c = [[[0,0] for j in range(0,11)] for i in range(0,n)]
ans = []
for i in range(n):
if (i != 0) :
for j in range(10):
f[i][j] = f[i-1][j]
c[i][j][0] = c[i-1][j][0]
c[i][j][1] = c[i-1][j][1]
for j in range(10):
if f[i-1][j]+a[i] > f[i][(j*b[i])%10]:
f[i][(j*b[i])%10] = f[i-1][j]+a[i]
c[i][(j*b[i])%10][0] = i
c[i][(j*b[i])%10][1] = j
if f[i][b[i]%10] < a[i]:
f[i][b[i]%10] = a[i]
c[i][b[i]%10][0] = i
c[i][b[i]%10][1] = -1
continue
if (i == 0) :
for j in range(10):
f[i][j] = math.log(0.0001)-mlog
c[i][j][0] = -1
c[i][j][1] = -1
f[i][b[0]%10] = a[0]
c[i][b[0]%10][0] = 0
c[i][b[0]%10][1] = -1
continue
if(f[n-1][d] <= 0):
print(-1)
return 0
x,y = c[n-1][d][0],c[n-1][d][1]
while y != -1:
ans.append(b[x])
u = x-1
if u < 0:
break
x = c[u][y][0]
y = c[u][y][1]
if x >= 0:
ans.append(b[x])
print(len(ans))
print(" ".join(list(map(str,ans))))
if __name__ == "__main__":
main()
``` | instruction | 0 | 106,399 | 20 | 212,798 |
Yes | output | 1 | 106,399 | 20 | 212,799 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them.
Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her.
Input
The first line contains the integers n and d (1β€ nβ€ 10^5, 0β€ dβ€ 9). The second line contains n integers a_i (1β€ a_iβ€ 1000).
Output
On the first line, print the number of chosen cards k (1β€ kβ€ n). On the next line, print the numbers written on the chosen cards in any order.
If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1.
Examples
Input
6 4
4 11 8 2 1 13
Output
5
1 2 4 11 13
Input
3 1
2 4 6
Output
-1
Input
5 7
1 3 1 5 3
Output
-1
Input
6 3
8 9 4 17 11 5
Output
3
9 11 17
Input
5 6
2 2 2 2 2
Output
4
2 2 2 2
Note
In the first example, 1 Γ 2 Γ 4 Γ 11 Γ 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144.
In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1.
In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7.
In the fourth example, 9 Γ 11 Γ 17 = 1683, which ends with the digit 3.
In the fifth example, 2 Γ 2 Γ 2 Γ 2 = 16, which ends with the digit 6.
Submitted Solution:
```
#coding:utf-8
'''
Created on 2021εΉ΄4ζ6ζ₯
@author: lzh
'''
import math
n, d = map(int, input().split())
arr = [int(_) for _ in input().split()]
dp = [[0 for _ in range(0, 10)] for _ in range(n + 1)]
path = [[(0, 0, 0) for _ in range(0, 10)] for _ in range(n + 1)]
for i in range(n):
dp[i + 1][arr[i]%10] = math.log(arr[i])
path[i + 1][arr[i]%10] = (i, arr[i]%10, 1)
for i in range(n) :
for j in range(10):
val = dp[i][j] + math.log(arr[i])
if dp[i + 1][(j * arr[i])%10] < val:
dp[i + 1][(j * arr[i])%10] = val
path[i + 1][(j * arr[i])%10] = (i, j, 1)
val = dp[i][j]
if dp[i + 1][j] < val:
dp[i + 1][j] = val
path[i + 1][j] = (i, j , 0)
ans = []
while n > 0 :
if path[n][d][2] == 1:
ans.append(arr[n - 1])
n,d = path[n][d][:2]
if len(ans) > 0:
print(len(ans))
print(' '.join(map(str, ans)))
else:
print(-1)
``` | instruction | 0 | 106,400 | 20 | 212,800 |
No | output | 1 | 106,400 | 20 | 212,801 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them.
Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her.
Input
The first line contains the integers n and d (1β€ nβ€ 10^5, 0β€ dβ€ 9). The second line contains n integers a_i (1β€ a_iβ€ 1000).
Output
On the first line, print the number of chosen cards k (1β€ kβ€ n). On the next line, print the numbers written on the chosen cards in any order.
If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1.
Examples
Input
6 4
4 11 8 2 1 13
Output
5
1 2 4 11 13
Input
3 1
2 4 6
Output
-1
Input
5 7
1 3 1 5 3
Output
-1
Input
6 3
8 9 4 17 11 5
Output
3
9 11 17
Input
5 6
2 2 2 2 2
Output
4
2 2 2 2
Note
In the first example, 1 Γ 2 Γ 4 Γ 11 Γ 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144.
In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1.
In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7.
In the fourth example, 9 Γ 11 Γ 17 = 1683, which ends with the digit 3.
In the fifth example, 2 Γ 2 Γ 2 Γ 2 = 16, which ends with the digit 6.
Submitted Solution:
```
from math import prod
from itertools import combinations
from operator import itemgetter
def main():
n,d = list(map(int,input().split()))
a = list(map(int,input().split()))
if d%2==1:
a = [m for m in a if m%2==1]
p = [m%10 for m in a]
ind = [m for m in range(len(a))]
else:
p = [m%10 for m in a]
ind = [m for m in range(len(a))]
a.sort()
a.reverse()
for k in range(n,1,-1):
combi = list(combinations(ind,k))
for i in combi:
if prod(itemgetter(*i)(p)) % 10 == d:
return itemgetter(*i)(a)
return 0
l = main()
if l:
print(len(l))
print(*l)
else:
print(-1)
``` | instruction | 0 | 106,401 | 20 | 212,802 |
No | output | 1 | 106,401 | 20 | 212,803 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them.
Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her.
Input
The first line contains the integers n and d (1β€ nβ€ 10^5, 0β€ dβ€ 9). The second line contains n integers a_i (1β€ a_iβ€ 1000).
Output
On the first line, print the number of chosen cards k (1β€ kβ€ n). On the next line, print the numbers written on the chosen cards in any order.
If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1.
Examples
Input
6 4
4 11 8 2 1 13
Output
5
1 2 4 11 13
Input
3 1
2 4 6
Output
-1
Input
5 7
1 3 1 5 3
Output
-1
Input
6 3
8 9 4 17 11 5
Output
3
9 11 17
Input
5 6
2 2 2 2 2
Output
4
2 2 2 2
Note
In the first example, 1 Γ 2 Γ 4 Γ 11 Γ 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144.
In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1.
In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7.
In the fourth example, 9 Γ 11 Γ 17 = 1683, which ends with the digit 3.
In the fifth example, 2 Γ 2 Γ 2 Γ 2 = 16, which ends with the digit 6.
Submitted Solution:
```
import collections
import string
import math
import copy
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)
def input(): return sys.stdin.readline().rstrip("\r\n")
# n = 0
# m = 0
# n = int(input())
# li = [int(i) for i in input().split()]
# s = sorted(li)
"""
from dataclasses import dataclass
@dataclass
class point:
x: float
y: float
@dataclass
class line:
A: float
B: float
C: float
def gety(self, x):
return (self.A*x+self.C)/-self.B
def getx(self, y):
return (self.B*y+self.C)/-self.A
def k(self):
return -self.A/self.B
def b(self):
return -self.C/self.B
def dist(self, p: point):
return abs((self.A*p.x+self.B*p.y+self.C)/(self.A**2+self.B**2)**0.5)
def calc_line(u: point, v: point):
return line(A=u.y-v.y, B=v.x-u.x, C=u.y*(u.x-v.x)-u.x*(u.y-v.y))
def is_parallel(u: line, v: line) -> bool:
f1 = False
f2 = False
try:
k1 = u.k()
except:
f1 = True
try:
k2 = v.k()
except:
f2 = True
if f1 != f2:
return False
return f1 or k1 == k2
def seg_len(_from: point, _to: point):
return ((_from.x - _to.x)**2 + (_from.y - _to.y)**2) ** 0.5
def in_range(_from: point, _to: point, _point: point) -> bool:
if _from.x < _to.x:
if _from.y < _to.y:
return _from.x <= _point.x <= _to.x and _from.y <= _point.y <= _to.y
else:
return _from.x <= _point.x <= _to.x and _from.y >= _point.y >= _to.y
else:
if _from.y < _to.y:
return _from.x >= _point.x >= _to.x and _from.y <= _point.y <= _to.y
else:
return _from.x >= _point.x >= _to.x and _from.y >= _point.y >= _to.y
def intersect(u: line, v: line) -> point:
tx = (u.B*v.C-v.B*u.C)/(v.B*u.A-u.B*v.A)
if u.B!=0.0:
ty = -u.A*tx/u.B - u.C/u.B
else:
ty = -v.A*tx/v.B - v.C/v.B
return point(x=tx, y=ty)
def in_direction(_from: point, _to: point, _point: point) -> bool:
if _from.x < _to.x:
if _from.y < _to.y:
return _to.x < _point.x and _to.y < _point.y
else:
return _to.x < _point.x and _point.y <= _to.y
else:
if _from.y < _to.y:
return _to.x >= _point.x and _to.y < _point.y
else:
return _to.x >= _point.x and _point.y <= _to.y
"""
mo = int(1e9+7)
def exgcd(a, b):
if not b:
return 1, 0
y, x = exgcd(b, a % b)
y -= a//b * x
return x, y
def getinv(a, m):
x, y = exgcd(a, m)
return -1 if x == 1 else x % m
def comb(n, b):
res = 1
b = min(b, n-b)
for i in range(b):
res = res*(n-i)*getinv(i+1, mo) % mo
# res %= mo
return res % mo
def quickpower(a, n):
res = 1
while n:
if n & 1:
res = res * a % mo
n >>= 1
a = a*a % mo
return res
def dis(a, b):
return abs(a[0]-b[0]) + abs(a[1]-b[1])
def getpref(x):
if x > 1:
return (x)*(x-1) >> 1
else:
return 0
def orafli(upp):
primes = []
marked = [False for i in range(upp+3)]
prvs = [i for i in range(upp+3)]
for i in range(2, upp):
if not marked[i]:
primes.append(i)
for j in primes:
if i*j >= upp:
break
marked[i*j] = True
prvs[i*j] = j
if i % j == 0:
break
return primes, prvs
def lower_ord(c: str) -> int:
return ord(c)-97
def upper_ord(c: str) -> int:
return ord(c) - 65
def read_list():
return [int(i) for i in input().split()]
def read_int():
s = input().split()
if len(s) == 1:
return int(s[0])
else:
return map(int, s)
def ask(s):
print(f"? {s}", flush=True)
def answer(s):
print(f"{s}", flush=True)
import random
def solve():
n, d = read_int()
l = read_list()
# dp = [[0 for i in range(10)] for i in range(n)]
dp = {}
pv = []
for i in l:
cd = copy.deepcopy(dp)
cp = {}
for k, v in dp.items():
lg = math.log(i,2)
if v+lg >cd.get(k*i%10,1):
# prvcd = cd[k*i%10]
cp[v+lg] = v
cd[k*i%10] = v+lg
# cd[k*i%10] = max(cd.get(k*i%10, 1), v+math.log(i,2))
lg = math.log(i,2)
if lg > cd.get(i%10, 1):
cp[lg]=cd.get(i%10,1)
cd[i%10] = lg
pv.append(cp)
# cd[i%10] = max(cd.get(i%10, 1), math.log(i,2))
dp = cd
sel = []
if d not in dp:
print(-1)
else:
# print(dp[d])
# c = int(round(2**dp[d]))
# print(pv)
c = dp[d]
# rc = round(c,14)
while pv:
fac = pv.pop()
curfac = l.pop()
if c in fac:
sel.append(curfac)
c = fac[c]
# for i in l:
# if c%i==0:
# sel.append(i)
# c//=i
print(len(sel))
print(*sel)
# print(dp.get(d, -1))
# fi = open('C:\\cppHeaders\\CF2020.12.17\\test.data', 'r')
# def input(): return fi.readline().rstrip("\r\n")
# primes, prv = orafli(10001)
solve()
# t = int(input())
# for ti in range(t):
# print(f"Case #{ti+1}: ", end='')
# solve()
``` | instruction | 0 | 106,402 | 20 | 212,804 |
No | output | 1 | 106,402 | 20 | 212,805 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them.
Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her.
Input
The first line contains the integers n and d (1β€ nβ€ 10^5, 0β€ dβ€ 9). The second line contains n integers a_i (1β€ a_iβ€ 1000).
Output
On the first line, print the number of chosen cards k (1β€ kβ€ n). On the next line, print the numbers written on the chosen cards in any order.
If it is impossible to choose a subset of cards with the product that ends with the digit d, print the single line with -1.
Examples
Input
6 4
4 11 8 2 1 13
Output
5
1 2 4 11 13
Input
3 1
2 4 6
Output
-1
Input
5 7
1 3 1 5 3
Output
-1
Input
6 3
8 9 4 17 11 5
Output
3
9 11 17
Input
5 6
2 2 2 2 2
Output
4
2 2 2 2
Note
In the first example, 1 Γ 2 Γ 4 Γ 11 Γ 13 = 1144, which is the largest product that ends with the digit 4. The same set of cards without the number 1 is also a valid answer, as well as a set of 8, 11, and 13 with or without 1 that also has the product of 1144.
In the second example, all the numbers on the cards are even and their product cannot end with an odd digit 1.
In the third example, the only possible products are 1, 3, 5, 9, 15, and 45, none of which end with the digit 7.
In the fourth example, 9 Γ 11 Γ 17 = 1683, which ends with the digit 3.
In the fifth example, 2 Γ 2 Γ 2 Γ 2 = 16, which ends with the digit 6.
Submitted Solution:
```
n, d = [int(s) for s in input().split(' ')]
a = [int(s) for s in input().split(' ')]
aDig = [[] for _ in range(10)]
for x in a:
aDig[x % 10].append(x)
for ad in aDig:
ad.sort()
c0 = len(aDig[0])
c5 = len(aDig[5])
c1379 = len(aDig[1]) + len(aDig[3]) + len(aDig[7]) + len(aDig[9])
c2468 = len(aDig[2]) + len(aDig[4]) + len(aDig[6]) + len(aDig[8])
def solveMod5(r3, r7, r9, m5):
prod, prodList = 0, []
for a in range(len(r3) + 1):
for b in range(len(r7) + 1):
for c in range(len(r9) + 1):
currList = []
if a:
currList += r3[-a:]
if b:
currList += r7[-b:]
if c:
currList += r9[-c:]
r = 1
for t in currList:
r *= t
if r % 5 == m5 and r > prod:
prod = r
prodList = currList
return prod, prodList
if d == 0:
if c0 or (c2468 and c5):
print(n)
print(*a)
else:
print(-1)
elif d == 5:
if c5:
print(c5 + c1379)
print(*[x for x in a if x & 1])
else:
print(-1)
else:
usedSurely = aDig[1]
if d % 2 == 0 and (len(aDig[2]) >= 7 or len(aDig[4]) >= 3 or len(aDig[6]) >= 1 or len(aDig[8]) >= 7):
for ev in [2, 4, 6, 8]:
aDig[(ev + 5) % 10] += aDig[ev]
d = (d + 5) % 10
# ---------------------------------------
for t in [3, 7]:
while len(aDig[t]) >= 7:
usedSurely += aDig[t][-4:]
for _ in range(4):
aDig[t].pop()
while len(aDig[9]) >= 3:
usedSurely += aDig[t][-2:]
for _ in range(2):
aDig[9].pop()
# ---------------------------------------
if d & 1:
d5 = d % 5
prod, prodList = solveMod5(aDig[3], aDig[7], aDig[9], d5)
if prod and len(prodList) + len(usedSurely):
print(len(prodList) + len(usedSurely))
print(*prodList, *usedSurely)
else:
print(-1)
else:
d5 = d % 5
prod, prodList = 0, []
for ev in [2, 4, 6, 8]:
if not len(aDig[ev]):
continue
save = aDig[ev][-1]
aDig[ev].pop()
dd5 = (d5 * pow(save, -1, 5)) % 5
currProd, currProdList = solveMod5(sorted(aDig[3] + aDig[8]), sorted(aDig[7] + aDig[2]),
sorted(aDig[9] + aDig[4]), dd5)
currProd *= save
currProdList.append(save)
if currProd > prod:
prod = currProd
prodList = currProdList
aDig[ev].append(save)
if prod and len(prodList) + len(usedSurely):
print(len(prodList) + len(usedSurely))
print(*prodList, *usedSurely)
else:
print(-1)
``` | instruction | 0 | 106,403 | 20 | 212,806 |
No | output | 1 | 106,403 | 20 | 212,807 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!
One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.
Limak assumes three things:
* Years are listed in the strictly increasing order;
* Every year is a positive integer number;
* There are no leading zeros.
Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7.
Input
The first line of the input contains a single integer n (1 β€ n β€ 5000) β the number of digits.
The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'.
Output
Print the number of ways to correctly split the given sequence modulo 109 + 7.
Examples
Input
6
123434
Output
8
Input
8
20152016
Output
4
Note
In the first sample there are 8 ways to split the sequence:
* "123434" = "123434" (maybe the given sequence is just one big number)
* "123434" = "1" + "23434"
* "123434" = "12" + "3434"
* "123434" = "123" + "434"
* "123434" = "1" + "23" + "434"
* "123434" = "1" + "2" + "3434"
* "123434" = "1" + "2" + "3" + "434"
* "123434" = "1" + "2" + "3" + "4" + "34"
Note that we don't count a split "123434" = "12" + "34" + "34" because numbers have to be strictly increasing.
In the second sample there are 4 ways:
* "20152016" = "20152016"
* "20152016" = "20" + "152016"
* "20152016" = "201" + "52016"
* "20152016" = "2015" + "2016"
Submitted Solution:
```
from collections import OrderedDict
from collections import deque
import time
import random
import sys
import re
def sizeof(t):
return sys.getsizeof(t)
def pr(x):
print(x)
def ti():
return time.time()
#Function profiler. Sorting options: 0-by call number, 1-by function inner time, 2-by function cumulative time.
def profile(s,sort=1):
import cProfile
cProfile.run(s,sort=sort)
#Use @initializer wrapper. Checks for defaults existence. Why do we need to go in reverse direction?
#How much slower it is than usual init?
from functools import wraps
import inspect
def inize(fun):
names, varargs, keywords, defaults = inspect.getargspec(fun)
@wraps(fun)
def wrapper(self, *args, **kargs):
self.inited=False
for name, arg in list(zip(names[1:], args)) + list(kargs.items()):
setattr(self, name, arg)
if defaults:
for i in range(len(defaults)):
index = -(i + 1)
if not hasattr(self, names[index]):
setattr(self, names[index], defaults[index])
fun(self, *args, **kargs)
self.inited=True
return wrapper
#To avoid problems with default empty lists.
def denone(fun):
def wrap(*args,**kws):
largs=inspect.getargspec(fun)[0]
if largs[-1] not in kws and len(args)<len(largs): kws[largs[-1]]=[]
return fun(*args, **kws)
return wrap
def fread(s):
return open(s,'r').read()
def hardread(s):
return open(s,'r',encoding="utf8").read()
def fwrite(f,s):
return open(f,'w',encoding="utf8").write(s)
#Helper functions zone.
def tel(n=5):
return [i+1 for i in range(n)]
def tel2(n=4,m=None):
if m==None: m=n
return [[i*m+j+1 for j in range(m)] for i in range(n)]
def tels(n=5):
return 'abcde'*2
def abc(n):
return list(map(chr, range(97, 123)))[n]
'''Operations'''
def lflat2(l):
if ist(l[0], list): return [x for y in l for x in y]
else: return l
def lflat(l):
return lflat2(l)
def lflat(l):
nl=[]
for x in l:
if (isiter(x)):
nl+=lflat(x)
else:
nl.append(x)
return nl
def ist(o,t):
return isinstance(o,t)
def antinone(l):
if l==None: return []
else: return l
def getl(f):
return f().split()
def getint(f):
return int(f())
def getints(s):
return lm(int, s.split())
def stoints(s):
return lm(int, s.split())
def enum(l):
return enumerate(l)
def sign(x):
if x>0: return 1
if x<0: return -1
return 0
global la
la={
'^': lambda x,y:x**y,
'**':lambda x,y:x**y,
'+': lambda x,y:x+y,
'-': lambda x,y:x-y,
'*': lambda x,y:x*y,
'/': lambda x,y:x/y,
'//': lambda x,y:x//y,
'%': lambda x,y:x%y,
'1': lambda x,y:x,
'2': lambda x,y:y,
'>': lambda x,y:x>y,
'=>':lambda x,y:x>=y,
'<': lambda x,y:x<y,
'<=': lambda x,y:x<=y,
'!=': lambda x,y:x!=y,
'==': lambda x,y:x==y,
'in': lambda x,y:x in y,
'nin': lambda x,y:x not in y,
'and': lambda x,y:x and y,
'or': lambda x,y:x or y,
}
#Shortcut-functions processor. Allow fixing of the second arg.
def tof(f,a2=None):
if ist(f,str): f=la[f]
return f if not a2 else lambda x:f(x,a2)
def isiter(o):
try:
iterator = iter(o)
except TypeError:
return 0
else:
return 1
def isarray(o):
if isiter(o) and not ist(o,str): return 1
else: return 0
def lm(f,*l):
f=tof(f)
return list(map(f,*l))
#Multifunction
def mf(f,*l):
return lm(f,l)
def fitem(i=0):
return lambda x:x[i]
fself=lambda x:x
def lf(l,f):
return [x for x in l if f(x)]
def lzip(*l):
return list(zip(*l))
#fzip('+', [1,2,3])=6. Problem: list doesn't change? You shouldn't copy it, choose indeces instead.
#Note! It takes list of arguments, not tuple!
def fzip(f,l):
f=tof(f)
for i in range(1,len(l)):
l[i]=f(l[i-1],l[i])
return l[-1]
def allwith(s,l):
return [x for x in l if s in x]
class Op:
def __init__ (self,l=None):
self.l=l
def __add__(self,s):
return self.act('+',s)
def __sub__(self,s):
return self.act('-',s)
def __mul__(self,s):
return self.act('*',s)
def __truediv__(self,s):
return self.act('/',s)
def __pow__(self,s):
return self.act('**',s)
def __lt__(self,s):
return self.act('<',s)
def __gt__(self,s):
return self.act('>',s)
def __le__(self,s):
return self.act('<=',s)
def __ge__(self,s):
return self.act('>=',s)
def __eq__(self,s):
op='in' if isiter(s) else '=='
return self.act(op,s)
def __ne__(self,s):
op='nin' if isiter(s) else '!='
return self.act(op,s)
class oneof(Op):
def act(self,op,s):
l=[tof(op)(x,s) for x in self.l]
return fzip('or',l)
class allof(Op):
def act(self,op,s):
l=[tof(op)(x,s) for x in self.l]
return fzip('and',l)
class lif(Op):
@inize
def __init__(c,l,key=fself): pass
#key acts on values before filtering.
def act(self,op,y):
return lf(self.l, lambda x:tof(op)(self.key(x),y))
#Super lambda. But what if there are several variables? No complex statements lik X**2+10?
class X(Op):
def act(c,op,y):
return tof(op,y)
X=X()
#Eg lop(l)*3
class lop(Op):
def act(self,op,y):
f=tof(op)
return [f(x,y) for x in self.l]
'''Dicts and lists'''
#Transpose table.
def ltrans(l):
return [[x[k] for x in l] for k in range(0,len(l[0]))]
class D(dict):
def __init__(c,d):
dict.__init__(c,d)
for x in d:
setattr(c,x,d[x])
def __setattr__(c,x,v):
c.__dict__[x]=v
c[x]=v
#New array with specific dimensions.
def lnew(*n,fill=0):
l=[]
for i in range(n[0]):
if len(n)>1: l.append(lnew(*n[1:],fill=fill))
else: l.append(fill)
return l
#Fast dict from list. Works for words list to, cause maintains unique keys.
#Problem with empty list, binded to function.
def dnew(l, fill=0):
d={}
for x in l: d[x]=fill
return d
def dlnew(l):
d={}
for x in l: d[x]=[]
return d
def odnew(l=None, fill=0):
d=OrderedDict()
if not l: return d
for x in l: d[x]=fill
return d
def odlnew(l=None):
d=OrderedDict()
if not l: return d
for x in l: d[x]=[]
return d
def dfill(d,fill):
for x in d: d[x]=fill
return d
def combzip(l1,l2):
return [(x,y) for x in l1 for y in l2]
#Place numbers in ascending order. Maybe better to use yield?
def comb(state,k,n,l):
p=len(state)
if p==k: l.append(lm(int,state))
else:
prev=int(state[-1]) if state!=[] else -1
for x in range(prev+1,n-k+p+1):
comb(state+[x],k,n,l)
def combs(k,n):
l=[]
comb([],k,n,l)
return l
def lcomb(state,k,l,lbase):
p=len(state)
if p==k: l.append(lm(int,state))
else:
for x in lbase: lcomb(state+[x],k,l,lbase)
def lcombs(lbase,k):
l=[]
lcomb([],k,l,lbase)
return l
from itertools import product
def lcombs(l,k):
return product(l,repeat=k)
def clad(c):
return c.__dict__
def saferec(x):
return 1/x if x!=0 else float('inf')
def safef(f,*x):
try:
return f(*x)
except: return x
#Isn't possible!
def safev(x):
try: return x
except: return 'Hey!'
return
#Real copy of dict to avoid iterating over changing structure
def dits(d):
return list(d.items())
def fastd(l):
return {x[0]:x[1:] for x in l}
def bifind(l,v,key=fself):
#Note that assignemt to var makes it innermost local.
def f(k,n):
#Take the closest lower item.
if k>=n:
if key(l[k])>v and k!=0:k-=1
return k
i=(k+n)//2; x=key(l[i])
if x==v: return i
if v<x: return f(k,i-1)
else: return f(i+1,n)
n=len(l); k=0
return l[f(k,n-1)]
def idict(l):
return {x[0]:[i]+x[1:] for i,x in enum(l)}
#Table indexer. Takes table and column number. Returns sorted and indexed list based on this column.
def lindex(l,k):
l.sort(key=lambda x:x[k],reverse=True)
#Adds index column. list(x) operation handles one-dimensional table.
for i,x in enumerate(l): l[i]=[i+1]+list(x)
return l
def fitem(i):
return lambda x:x[i]
def tabsort(l,k=0,rev=1):
return sorted(l,key=fitem(k),reverse=rev)
def safedit(d,k,safe=0):
return d[k] if k in d else safe
def antific(s):
s=s.replace('β',"'")
s=s.replace('β',"'")
s=s.replace('β¦','...')
return s
def lfy(f):
def wrap(*a):
return list(f(*a))
return wrap
'''Classes'''
#Needs new to initialize str or int children
class Str(str):
def __new__(c,s,**kw):
obj = str.__new__(c, s)
for k in kw:
obj.__dict__[k]=kw[k]
return obj
class L(list):
@inize
def __init__(c,l=None,*a,**kw):
if l==None: l=[]
init(c,l)
def getpar(c):
return c.__class__.__bases__[0]
#Would be problem with grandfather class in vertical chain of calls.
#That's why we create spec variable to track class in this multi-level process.
def autoclass(f):
def wrap(c,*args):
#Note that _par is class, not instance, that's why getpar doesn't work there.
par=c._par.__bases__[0] if '_par' in c.__dict__ else getpar(c)
c._par=par
f(c,*args)
#Don't forget to kill variable at the end.
if '_par' in c.__dict__: del(c._par)
return wrap
@autoclass
def init(c,*args):
c._par.__init__(c,*args)
@autoclass
def parcall(c,*args):
return c._par.__call__(c,*args)
@autoclass
def parset(c,*args):
return c._par.__setattr__(c,*args)
def revbool(b):
if b: b=False
else: b=True
return b
def fa(p,s):
return re.findall(p,str(s),re.DOTALL)
#Doesn't take last part.
def spliton(s,chars):
return fa('.*?[{}]'.format(chars),s)
def skick(s,sub):
return ''.join(s.split(sub))
def strip(s):
return s.strip()
def sentsplit(s):
s=skick(s,'\n')
l=spliton(s,'.?!')
l=lif(l)!=''
l=lm(strip,l)
return l
from inspect import getsource
def pr(x):
return print(x)
def row(s):
return s+'\n'
def coderows(s,gap):
return ''.join([gap+row(x) for x in s.split(';')])
#Look at module where function is defined. Take space of this module.
def fspace(f):
mod=f.__module__
if mod=='__main__': dglob=globals()
else: dglob=globals()[mod].__dict__
return dglob
def split(s,c):
return s.split(c)
import sys
def sizeof(t):
return sys.getsizeof(t)
n=input()
s=input()
print(sizeof(s))
``` | instruction | 0 | 106,622 | 20 | 213,244 |
No | output | 1 | 106,622 | 20 | 213,245 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!
One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.
Limak assumes three things:
* Years are listed in the strictly increasing order;
* Every year is a positive integer number;
* There are no leading zeros.
Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7.
Input
The first line of the input contains a single integer n (1 β€ n β€ 5000) β the number of digits.
The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'.
Output
Print the number of ways to correctly split the given sequence modulo 109 + 7.
Examples
Input
6
123434
Output
8
Input
8
20152016
Output
4
Note
In the first sample there are 8 ways to split the sequence:
* "123434" = "123434" (maybe the given sequence is just one big number)
* "123434" = "1" + "23434"
* "123434" = "12" + "3434"
* "123434" = "123" + "434"
* "123434" = "1" + "23" + "434"
* "123434" = "1" + "2" + "3434"
* "123434" = "1" + "2" + "3" + "434"
* "123434" = "1" + "2" + "3" + "4" + "34"
Note that we don't count a split "123434" = "12" + "34" + "34" because numbers have to be strictly increasing.
In the second sample there are 4 ways:
* "20152016" = "20152016"
* "20152016" = "20" + "152016"
* "20152016" = "201" + "52016"
* "20152016" = "2015" + "2016"
Submitted Solution:
```
import sys
sys.setrecursionlimit(10**8)
mod = 10**9 + 7
def recurse(curr_start,curr_pos,prev,num):
global memo
my_tuple = (curr_start,curr_pos,prev)
if my_tuple in memo:
return memo[my_tuple]
if curr_pos >= len(num):
if prev < int(num[curr_start:curr_pos]):
return 1
else:
return 0
option1 = recurse(curr_start,curr_pos+1,prev,num)
if curr_start != curr_pos and prev < int(num[curr_start:curr_pos]):
option2 = recurse(curr_pos,curr_pos+1,int(num[curr_start:curr_pos]),num)
else:
option2 = 0
ans = option1 + option2
memo[my_tuple] = ans
return ans
n = int(input())
num = str(input())
memo = {}
ans = recurse(0,0,-float('inf'),num)
print(ans % mod)
``` | instruction | 0 | 106,623 | 20 | 213,246 |
No | output | 1 | 106,623 | 20 | 213,247 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!
One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.
Limak assumes three things:
* Years are listed in the strictly increasing order;
* Every year is a positive integer number;
* There are no leading zeros.
Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7.
Input
The first line of the input contains a single integer n (1 β€ n β€ 5000) β the number of digits.
The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'.
Output
Print the number of ways to correctly split the given sequence modulo 109 + 7.
Examples
Input
6
123434
Output
8
Input
8
20152016
Output
4
Note
In the first sample there are 8 ways to split the sequence:
* "123434" = "123434" (maybe the given sequence is just one big number)
* "123434" = "1" + "23434"
* "123434" = "12" + "3434"
* "123434" = "123" + "434"
* "123434" = "1" + "23" + "434"
* "123434" = "1" + "2" + "3434"
* "123434" = "1" + "2" + "3" + "434"
* "123434" = "1" + "2" + "3" + "4" + "34"
Note that we don't count a split "123434" = "12" + "34" + "34" because numbers have to be strictly increasing.
In the second sample there are 4 ways:
* "20152016" = "20152016"
* "20152016" = "20" + "152016"
* "20152016" = "201" + "52016"
* "20152016" = "2015" + "2016"
Submitted Solution:
```
from inspect import getsource
def f():
return 10
n=input()
s=input()
print(getsource(f))
``` | instruction | 0 | 106,624 | 20 | 213,248 |
No | output | 1 | 106,624 | 20 | 213,249 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!
One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.
Limak assumes three things:
* Years are listed in the strictly increasing order;
* Every year is a positive integer number;
* There are no leading zeros.
Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7.
Input
The first line of the input contains a single integer n (1 β€ n β€ 5000) β the number of digits.
The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'.
Output
Print the number of ways to correctly split the given sequence modulo 109 + 7.
Examples
Input
6
123434
Output
8
Input
8
20152016
Output
4
Note
In the first sample there are 8 ways to split the sequence:
* "123434" = "123434" (maybe the given sequence is just one big number)
* "123434" = "1" + "23434"
* "123434" = "12" + "3434"
* "123434" = "123" + "434"
* "123434" = "1" + "23" + "434"
* "123434" = "1" + "2" + "3434"
* "123434" = "1" + "2" + "3" + "434"
* "123434" = "1" + "2" + "3" + "4" + "34"
Note that we don't count a split "123434" = "12" + "34" + "34" because numbers have to be strictly increasing.
In the second sample there are 4 ways:
* "20152016" = "20152016"
* "20152016" = "20" + "152016"
* "20152016" = "201" + "52016"
* "20152016" = "2015" + "2016"
Submitted Solution:
```
from collections import OrderedDict
from collections import deque
import time
import random
import sys
import re
def sizeof(t):
return sys.getsizeof(t)
def pr(x):
print(x)
def ti():
return time.time()
#Function profiler. Sorting options: 0-by call number, 1-by function inner time, 2-by function cumulative time.
def profile(s,sort=1):
import cProfile
cProfile.run(s,sort=sort)
#Use @initializer wrapper. Checks for defaults existence. Why do we need to go in reverse direction?
#How much slower it is than usual init?
from functools import wraps
import inspect
def inize(fun):
names, varargs, keywords, defaults = inspect.getargspec(fun)
@wraps(fun)
def wrapper(self, *args, **kargs):
self.inited=False
for name, arg in list(zip(names[1:], args)) + list(kargs.items()):
setattr(self, name, arg)
if defaults:
for i in range(len(defaults)):
index = -(i + 1)
if not hasattr(self, names[index]):
setattr(self, names[index], defaults[index])
fun(self, *args, **kargs)
self.inited=True
return wrapper
#To avoid problems with default empty lists.
def denone(fun):
def wrap(*args,**kws):
largs=inspect.getargspec(fun)[0]
if largs[-1] not in kws and len(args)<len(largs): kws[largs[-1]]=[]
return fun(*args, **kws)
return wrap
def fread(s):
return open(s,'r').read()
def hardread(s):
return open(s,'r',encoding="utf8").read()
def fwrite(f,s):
return open(f,'w',encoding="utf8").write(s)
#Helper functions zone.
def tel(n=5):
return [i+1 for i in range(n)]
def tel2(n=4,m=None):
if m==None: m=n
return [[i*m+j+1 for j in range(m)] for i in range(n)]
def tels(n=5):
return 'abcde'*2
def abc(n):
return list(map(chr, range(97, 123)))[n]
'''Operations'''
def lflat2(l):
if ist(l[0], list): return [x for y in l for x in y]
else: return l
def lflat(l):
return lflat2(l)
def lflat(l):
nl=[]
for x in l:
if (isiter(x)):
nl+=lflat(x)
else:
nl.append(x)
return nl
def ist(o,t):
return isinstance(o,t)
def antinone(l):
if l==None: return []
else: return l
def getl(f):
return f().split()
def getint(f):
return int(f())
def getints(s):
return lm(int, s.split())
def stoints(s):
return lm(int, s.split())
def enum(l):
return enumerate(l)
def sign(x):
if x>0: return 1
if x<0: return -1
return 0
global la
la={
'^': lambda x,y:x**y,
'**':lambda x,y:x**y,
'+': lambda x,y:x+y,
'-': lambda x,y:x-y,
'*': lambda x,y:x*y,
'/': lambda x,y:x/y,
'//': lambda x,y:x//y,
'%': lambda x,y:x%y,
'1': lambda x,y:x,
'2': lambda x,y:y,
'>': lambda x,y:x>y,
'=>':lambda x,y:x>=y,
'<': lambda x,y:x<y,
'<=': lambda x,y:x<=y,
'!=': lambda x,y:x!=y,
'==': lambda x,y:x==y,
'in': lambda x,y:x in y,
'nin': lambda x,y:x not in y,
'and': lambda x,y:x and y,
'or': lambda x,y:x or y,
}
#Shortcut-functions processor. Allow fixing of the second arg.
def tof(f,a2=None):
if ist(f,str): f=la[f]
return f if not a2 else lambda x:f(x,a2)
def isiter(o):
try:
iterator = iter(o)
except TypeError:
return 0
else:
return 1
def isarray(o):
if isiter(o) and not ist(o,str): return 1
else: return 0
def lm(f,*l):
f=tof(f)
return list(map(f,*l))
#Multifunction
def mf(f,*l):
return lm(f,l)
def fitem(i=0):
return lambda x:x[i]
fself=lambda x:x
def lf(l,f):
return [x for x in l if f(x)]
def lzip(*l):
return list(zip(*l))
#fzip('+', [1,2,3])=6. Problem: list doesn't change? You shouldn't copy it, choose indeces instead.
#Note! It takes list of arguments, not tuple!
def fzip(f,l):
f=tof(f)
for i in range(1,len(l)):
l[i]=f(l[i-1],l[i])
return l[-1]
def allwith(s,l):
return [x for x in l if s in x]
class Op:
def __init__ (self,l=None):
self.l=l
def __add__(self,s):
return self.act('+',s)
def __sub__(self,s):
return self.act('-',s)
def __mul__(self,s):
return self.act('*',s)
def __truediv__(self,s):
return self.act('/',s)
def __pow__(self,s):
return self.act('**',s)
def __lt__(self,s):
return self.act('<',s)
def __gt__(self,s):
return self.act('>',s)
def __le__(self,s):
return self.act('<=',s)
def __ge__(self,s):
return self.act('>=',s)
def __eq__(self,s):
op='in' if isiter(s) else '=='
return self.act(op,s)
def __ne__(self,s):
op='nin' if isiter(s) else '!='
return self.act(op,s)
class oneof(Op):
def act(self,op,s):
l=[tof(op)(x,s) for x in self.l]
return fzip('or',l)
class allof(Op):
def act(self,op,s):
l=[tof(op)(x,s) for x in self.l]
return fzip('and',l)
class lif(Op):
@inize
def __init__(c,l,key=fself): pass
#key acts on values before filtering.
def act(self,op,y):
return lf(self.l, lambda x:tof(op)(self.key(x),y))
#Super lambda. But what if there are several variables? No complex statements lik X**2+10?
class X(Op):
def act(c,op,y):
return tof(op,y)
X=X()
#Eg lop(l)*3
class lop(Op):
def act(self,op,y):
f=tof(op)
return [f(x,y) for x in self.l]
'''Dicts and lists'''
#Transpose table.
def ltrans(l):
return [[x[k] for x in l] for k in range(0,len(l[0]))]
class D(dict):
def __init__(c,d):
dict.__init__(c,d)
for x in d:
setattr(c,x,d[x])
def __setattr__(c,x,v):
c.__dict__[x]=v
c[x]=v
#New array with specific dimensions.
def lnew(*n,fill=0):
l=[]
for i in range(n[0]):
if len(n)>1: l.append(lnew(*n[1:],fill=fill))
else: l.append(fill)
return l
#Fast dict from list. Works for words list to, cause maintains unique keys.
#Problem with empty list, binded to function.
def dnew(l, fill=0):
d={}
for x in l: d[x]=fill
return d
def dlnew(l):
d={}
for x in l: d[x]=[]
return d
def odnew(l=None, fill=0):
d=OrderedDict()
if not l: return d
for x in l: d[x]=fill
return d
def odlnew(l=None):
d=OrderedDict()
if not l: return d
for x in l: d[x]=[]
return d
def dfill(d,fill):
for x in d: d[x]=fill
return d
def combzip(l1,l2):
return [(x,y) for x in l1 for y in l2]
#Place numbers in ascending order. Maybe better to use yield?
def comb(state,k,n,l):
p=len(state)
if p==k: l.append(lm(int,state))
else:
prev=int(state[-1]) if state!=[] else -1
for x in range(prev+1,n-k+p+1):
comb(state+[x],k,n,l)
def combs(k,n):
l=[]
comb([],k,n,l)
return l
def lcomb(state,k,l,lbase):
p=len(state)
if p==k: l.append(lm(int,state))
else:
for x in lbase: lcomb(state+[x],k,l,lbase)
def lcombs(lbase,k):
l=[]
lcomb([],k,l,lbase)
return l
from itertools import product
def lcombs(l,k):
return product(l,repeat=k)
def clad(c):
return c.__dict__
def saferec(x):
return 1/x if x!=0 else float('inf')
def safef(f,*x):
try:
return f(*x)
except: return x
#Isn't possible!
def safev(x):
try: return x
except: return 'Hey!'
return
#Real copy of dict to avoid iterating over changing structure
def dits(d):
return list(d.items())
def fastd(l):
return {x[0]:x[1:] for x in l}
def bifind(l,v,key=fself):
#Note that assignemt to var makes it innermost local.
def f(k,n):
#Take the closest lower item.
if k>=n:
if key(l[k])>v and k!=0:k-=1
return k
i=(k+n)//2; x=key(l[i])
if x==v: return i
if v<x: return f(k,i-1)
else: return f(i+1,n)
n=len(l); k=0
return l[f(k,n-1)]
def idict(l):
return {x[0]:[i]+x[1:] for i,x in enum(l)}
#Table indexer. Takes table and column number. Returns sorted and indexed list based on this column.
def lindex(l,k):
l.sort(key=lambda x:x[k],reverse=True)
#Adds index column. list(x) operation handles one-dimensional table.
for i,x in enumerate(l): l[i]=[i+1]+list(x)
return l
def fitem(i):
return lambda x:x[i]
def tabsort(l,k=0,rev=1):
return sorted(l,key=fitem(k),reverse=rev)
def safedit(d,k,safe=0):
return d[k] if k in d else safe
def antific(s):
s=s.replace('β',"'")
s=s.replace('β',"'")
s=s.replace('β¦','...')
return s
def lfy(f):
def wrap(*a):
return list(f(*a))
return wrap
'''Classes'''
#Needs new to initialize str or int children
class Str(str):
def __new__(c,s,**kw):
obj = str.__new__(c, s)
for k in kw:
obj.__dict__[k]=kw[k]
return obj
class L(list):
@inize
def __init__(c,l=None,*a,**kw):
if l==None: l=[]
init(c,l)
def getpar(c):
return c.__class__.__bases__[0]
#Would be problem with grandfather class in vertical chain of calls.
#That's why we create spec variable to track class in this multi-level process.
def autoclass(f):
def wrap(c,*args):
#Note that _par is class, not instance, that's why getpar doesn't work there.
par=c._par.__bases__[0] if '_par' in c.__dict__ else getpar(c)
c._par=par
f(c,*args)
#Don't forget to kill variable at the end.
if '_par' in c.__dict__: del(c._par)
return wrap
@autoclass
def init(c,*args):
c._par.__init__(c,*args)
@autoclass
def parcall(c,*args):
return c._par.__call__(c,*args)
@autoclass
def parset(c,*args):
return c._par.__setattr__(c,*args)
def revbool(b):
if b: b=False
else: b=True
return b
def fa(p,s):
return re.findall(p,str(s),re.DOTALL)
#Doesn't take last part.
def spliton(s,chars):
return fa('.*?[{}]'.format(chars),s)
def skick(s,sub):
return ''.join(s.split(sub))
def strip(s):
return s.strip()
def sentsplit(s):
s=skick(s,'\n')
l=spliton(s,'.?!')
l=lif(l)!=''
l=lm(strip,l)
return l
from inspect import getsource
def pr(x):
return print(x)
def row(s):
return s+'\n'
def coderows(s,gap):
return ''.join([gap+row(x) for x in s.split(';')])
#Look at module where function is defined. Take space of this module.
def fspace(f):
mod=f.__module__
if mod=='__main__': dglob=globals()
else: dglob=globals()[mod].__dict__
return dglob
def split(s,c):
return s.split(c)
def intjoin(l):
return int(''.join(lm(str,l)))
def count(start=0,d=1):
v=start
while True:
yield v
v+=d
#Actually you don't need variable k2, that's artifact of a mistake: forgetting about gluing prohibition in S calc.
#Leave it for demonstration purposes.
#Maybe it can auto-detect types based on your inputs? Or explicit types easier to read?
def checkS(n,*k,t):
p=lnew(3)
#Pos of values.
p[0]=n-k[0]+1
for i in range(1,3): p[i]=p[i-1]+k[i-1]
#Values of all active elements in checking.
v=[intjoin(V[p[i]:p[i]+k[i]]) for i in range(3)]
#Anti-leadzero.
if V[p[1]]==0: return 0
#Type 1:..llk. Type 2: l(l-k)k.
if t==1 and v[1]>v[0]: return 0
#Problem: you need not sum values, but join them? Don't confuse string addition with integer one.
#So maybe intjoin was bad idea?
if t==2 and intjoin((v[1],v[2]))<=v[0]: return 0
return fS(n,k[0])
#Main function for processing combs of different classes.
#For first two types k2=1.
def sumS(n,k2,t):
#Case of ..kk1. Start from 1. Use S to count combs.
if t==1:
#Can we make spec-function for these types of tasks? Unlimited for?
su=0
for k0 in count(1):
#If this configuration exceeds substring size.
if 2*k0+1>n: break
su+=checkS(n-k0-1,k0,k0,1,t=1)
return su
#Case of ..k(k-1)1. Start from 2.
if t==2:
su=0
for k0 in count(2):
if 2*k0>n: break
su+=checkS(n-k0,k0,k0-1,1,t=2)
return su
#Case of ..lk with l<=k. Look with caution at ..kk case.
if t==3:
#Problem: Case with n==k. Add spec condition.
if n==k2: return 1
if V[n-k2+1]==0: return 0
su=0
for k1 in range(1,k2+1):
if k1+k2>n: break
if k1==k2:
#Problem: didn't work when k+k>n. Note that l+k can be >n too. That's why we added break before.
#v1,v2=mf(intjoin, V[n-2*k2+1:n-k2+1], V[n-k2+1:n+1])
#Don't forget that arrays start from zero. Substract 1 from everybody.
#Actually you don't have square table. Second index works like length.
v1,v2=I[n-2*k2][k2-1], I[n-k2][k2-1]
if v1>=v2: break
su+=fS(n-k2,k1)
return su
from inspect import currentframe, getframeinfo, getouterframes, stack, getargvalues
#Print sum pieces.
def talksum(*x,nodeb=0):
#print(getframeinfo(currentframe()))
#print(getouterframes(currentframe())[1])
#Stack getter is too slow, use only in debug.
if nodeb: return sum(x)
prevframe=stack()[1]
#Give it a frame object.
prevargs=getargvalues(prevframe[0])
print('Function:',stack()[1][3], prevargs.locals,'Elements:', x, 'Res:', sum(x))
return sum(x)
def fN(n):
if N[n]!=-1: return N[n]
#Check not-glued case
noglue=all([V[i+1]>V[i] for i in range(1,n)])
#N[n]=N[n-1]+int(noglue)+sumS(n,1,1)+sumS(n,1,2)
#Note that we give it fN to launch recursion, not N.
N[n]=talksum(fN(n-1),int(noglue),sumS(n,1,1),sumS(n,1,2),nodeb=1)
return N[n]
def fN(n):
return sum(fS(n,i) for i in range(1,n+1))
def fS(n,k):
if S[n][k]!=-1: return S[n][k]
S[n][k]=sumS(n,k,3)
return S[n][k]
def Nnumstairs(s):
if len(s)==1: return 1
#Init empty functions cells and recursion seeds.
global N,S,V,I
V=[None]+lm(int,s)
n=len(s); N=lnew(n+1,fill=-1); S=lnew(n+1,n+1,fill=-1)
N[1]=1; S[1][1]=1
I=[[s[i-1:j] for j in range(i,n+1)] for i in range(1,n+1)]
return fN(n)
def fS(n,k):
if S[n][k]!=-1: return S[n][k]
S[n][k]=sumS(n,k,3)
return S[n][k]
def Nnumstairs(s):
if len(s)==1: return 1
#Init empty functions cells and recursion seeds.
global N,S,V
V=[None]+lm(int,s)
n=len(s); N=lnew(n+1,fill=-1); S=lnew(n+1,n+1,fill=-1)
N[1]=1; S[1][1]=1
try:
return fN(n)
except:
print(-1)
n=input()
s=input()
#ddeb(Nnumstairs,'23',f=checkS)#('123434')
print(Nnumstairs(s))
``` | instruction | 0 | 106,625 | 20 | 213,250 |
No | output | 1 | 106,625 | 20 | 213,251 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a function f written in some basic language. The function accepts an integer value, which is immediately written into some variable x. x is an integer variable and can be assigned values from 0 to 2^{32}-1. The function contains three types of commands:
* for n β for loop;
* end β every command between "for n" and corresponding "end" is executed n times;
* add β adds 1 to x.
After the execution of these commands, value of x is returned.
Every "for n" is matched with "end", thus the function is guaranteed to be valid. "for n" can be immediately followed by "end"."add" command can be outside of any for loops.
Notice that "add" commands might overflow the value of x! It means that the value of x becomes greater than 2^{32}-1 after some "add" command.
Now you run f(0) and wonder if the resulting value of x is correct or some overflow made it incorrect.
If overflow happened then output "OVERFLOW!!!", otherwise print the resulting value of x.
Input
The first line contains a single integer l (1 β€ l β€ 10^5) β the number of lines in the function.
Each of the next l lines contains a single command of one of three types:
* for n (1 β€ n β€ 100) β for loop;
* end β every command between "for n" and corresponding "end" is executed n times;
* add β adds 1 to x.
Output
If overflow happened during execution of f(0), then output "OVERFLOW!!!", otherwise print the resulting value of x.
Examples
Input
9
add
for 43
end
for 10
for 15
add
end
add
end
Output
161
Input
2
for 62
end
Output
0
Input
11
for 100
for 100
for 100
for 100
for 100
add
end
end
end
end
end
Output
OVERFLOW!!!
Note
In the first example the first "add" is executed 1 time, the second "add" is executed 150 times and the last "add" is executed 10 times. Note that "for n" can be immediately followed by "end" and that "add" can be outside of any for loops.
In the second example there are no commands "add", thus the returning value is 0.
In the third example "add" command is executed too many times, which causes x to go over 2^{32}-1. | instruction | 0 | 107,095 | 20 | 214,190 |
Tags: data structures, expression parsing, implementation
Correct Solution:
```
from sys import stdin, stdout
def read():
return stdin.readline().rstrip()
def write(s):
stdout.write(s + "\n")
def solve():
l = int(read())
st = []
lim = 2*2147483647+ 1
cur = 1
x = 0
for i in range(l):
s = read().split()
if s[0] == 'for':
y = int(s[1])
cur = cur*y if (cur * y <= lim) else lim+1
st.append(cur)
elif s[0] == 'end':
st.pop()
cur = 1 if not st else st[-1]
else:
x += cur
#if x > lim: #2**32-1:
if x > 2**32-1:
write("OVERFLOW!!!")
break
else:
write(str(x))
solve()
``` | output | 1 | 107,095 | 20 | 214,191 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a function f written in some basic language. The function accepts an integer value, which is immediately written into some variable x. x is an integer variable and can be assigned values from 0 to 2^{32}-1. The function contains three types of commands:
* for n β for loop;
* end β every command between "for n" and corresponding "end" is executed n times;
* add β adds 1 to x.
After the execution of these commands, value of x is returned.
Every "for n" is matched with "end", thus the function is guaranteed to be valid. "for n" can be immediately followed by "end"."add" command can be outside of any for loops.
Notice that "add" commands might overflow the value of x! It means that the value of x becomes greater than 2^{32}-1 after some "add" command.
Now you run f(0) and wonder if the resulting value of x is correct or some overflow made it incorrect.
If overflow happened then output "OVERFLOW!!!", otherwise print the resulting value of x.
Input
The first line contains a single integer l (1 β€ l β€ 10^5) β the number of lines in the function.
Each of the next l lines contains a single command of one of three types:
* for n (1 β€ n β€ 100) β for loop;
* end β every command between "for n" and corresponding "end" is executed n times;
* add β adds 1 to x.
Output
If overflow happened during execution of f(0), then output "OVERFLOW!!!", otherwise print the resulting value of x.
Examples
Input
9
add
for 43
end
for 10
for 15
add
end
add
end
Output
161
Input
2
for 62
end
Output
0
Input
11
for 100
for 100
for 100
for 100
for 100
add
end
end
end
end
end
Output
OVERFLOW!!!
Note
In the first example the first "add" is executed 1 time, the second "add" is executed 150 times and the last "add" is executed 10 times. Note that "for n" can be immediately followed by "end" and that "add" can be outside of any for loops.
In the second example there are no commands "add", thus the returning value is 0.
In the third example "add" command is executed too many times, which causes x to go over 2^{32}-1. | instruction | 0 | 107,096 | 20 | 214,192 |
Tags: data structures, expression parsing, implementation
Correct Solution:
```
t = int(input())
r = 0
s = [0] * 10**5
ss = 0
for _ in range(t):
x = input().split()
if x[0] == 'add':
r += 1
elif x[0] == 'for':
s[ss] = (r, int(x[1]))
ss += 1
r = 0
elif x[0] == 'end':
ss -= 1
r_old, k = s[ss]
r = r_old + r * k
if r >= 2**32:
print("OVERFLOW!!!")
break
else:
print(r if r < 2**32 else "OVERFLOW!!!")
``` | output | 1 | 107,096 | 20 | 214,193 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a function f written in some basic language. The function accepts an integer value, which is immediately written into some variable x. x is an integer variable and can be assigned values from 0 to 2^{32}-1. The function contains three types of commands:
* for n β for loop;
* end β every command between "for n" and corresponding "end" is executed n times;
* add β adds 1 to x.
After the execution of these commands, value of x is returned.
Every "for n" is matched with "end", thus the function is guaranteed to be valid. "for n" can be immediately followed by "end"."add" command can be outside of any for loops.
Notice that "add" commands might overflow the value of x! It means that the value of x becomes greater than 2^{32}-1 after some "add" command.
Now you run f(0) and wonder if the resulting value of x is correct or some overflow made it incorrect.
If overflow happened then output "OVERFLOW!!!", otherwise print the resulting value of x.
Input
The first line contains a single integer l (1 β€ l β€ 10^5) β the number of lines in the function.
Each of the next l lines contains a single command of one of three types:
* for n (1 β€ n β€ 100) β for loop;
* end β every command between "for n" and corresponding "end" is executed n times;
* add β adds 1 to x.
Output
If overflow happened during execution of f(0), then output "OVERFLOW!!!", otherwise print the resulting value of x.
Examples
Input
9
add
for 43
end
for 10
for 15
add
end
add
end
Output
161
Input
2
for 62
end
Output
0
Input
11
for 100
for 100
for 100
for 100
for 100
add
end
end
end
end
end
Output
OVERFLOW!!!
Note
In the first example the first "add" is executed 1 time, the second "add" is executed 150 times and the last "add" is executed 10 times. Note that "for n" can be immediately followed by "end" and that "add" can be outside of any for loops.
In the second example there are no commands "add", thus the returning value is 0.
In the third example "add" command is executed too many times, which causes x to go over 2^{32}-1. | instruction | 0 | 107,097 | 20 | 214,194 |
Tags: data structures, expression parsing, implementation
Correct Solution:
```
def catch_overflow(o):
stack = [1]
output = 0
for i in range(o):
n = input()
if n[:3] == 'for':
stack.append(min(2**32,stack[-1]*int(n[4:])))
elif n == 'end':
stack.pop()
else:
output += stack[-1]
if output >= 2**32:
print('OVERFLOW!!!')
else:
print(output)
n = int(input())
catch_overflow(n)
``` | output | 1 | 107,097 | 20 | 214,195 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a function f written in some basic language. The function accepts an integer value, which is immediately written into some variable x. x is an integer variable and can be assigned values from 0 to 2^{32}-1. The function contains three types of commands:
* for n β for loop;
* end β every command between "for n" and corresponding "end" is executed n times;
* add β adds 1 to x.
After the execution of these commands, value of x is returned.
Every "for n" is matched with "end", thus the function is guaranteed to be valid. "for n" can be immediately followed by "end"."add" command can be outside of any for loops.
Notice that "add" commands might overflow the value of x! It means that the value of x becomes greater than 2^{32}-1 after some "add" command.
Now you run f(0) and wonder if the resulting value of x is correct or some overflow made it incorrect.
If overflow happened then output "OVERFLOW!!!", otherwise print the resulting value of x.
Input
The first line contains a single integer l (1 β€ l β€ 10^5) β the number of lines in the function.
Each of the next l lines contains a single command of one of three types:
* for n (1 β€ n β€ 100) β for loop;
* end β every command between "for n" and corresponding "end" is executed n times;
* add β adds 1 to x.
Output
If overflow happened during execution of f(0), then output "OVERFLOW!!!", otherwise print the resulting value of x.
Examples
Input
9
add
for 43
end
for 10
for 15
add
end
add
end
Output
161
Input
2
for 62
end
Output
0
Input
11
for 100
for 100
for 100
for 100
for 100
add
end
end
end
end
end
Output
OVERFLOW!!!
Note
In the first example the first "add" is executed 1 time, the second "add" is executed 150 times and the last "add" is executed 10 times. Note that "for n" can be immediately followed by "end" and that "add" can be outside of any for loops.
In the second example there are no commands "add", thus the returning value is 0.
In the third example "add" command is executed too many times, which causes x to go over 2^{32}-1. | instruction | 0 | 107,098 | 20 | 214,196 |
Tags: data structures, expression parsing, implementation
Correct Solution:
```
from array import array
n = int(input())
stack = array('Q', list(1 for _ in range(n // 2 + 1)))
stack_top = 1
overflow = 2**32 - 1
s = 0
flag = True
for _ in range(n):
command = input()
if command == "end":
stack_top -= 1
elif command == "add":
s += stack[stack_top - 1]
if s > overflow:
print("OVERFLOW!!!")
flag = False
break
else:
res = stack[stack_top - 1] * int(command[4 : len(command)])
stack[stack_top] = min(res, overflow + 1)
stack_top += 1
if flag:
print(s)
``` | output | 1 | 107,098 | 20 | 214,197 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a function f written in some basic language. The function accepts an integer value, which is immediately written into some variable x. x is an integer variable and can be assigned values from 0 to 2^{32}-1. The function contains three types of commands:
* for n β for loop;
* end β every command between "for n" and corresponding "end" is executed n times;
* add β adds 1 to x.
After the execution of these commands, value of x is returned.
Every "for n" is matched with "end", thus the function is guaranteed to be valid. "for n" can be immediately followed by "end"."add" command can be outside of any for loops.
Notice that "add" commands might overflow the value of x! It means that the value of x becomes greater than 2^{32}-1 after some "add" command.
Now you run f(0) and wonder if the resulting value of x is correct or some overflow made it incorrect.
If overflow happened then output "OVERFLOW!!!", otherwise print the resulting value of x.
Input
The first line contains a single integer l (1 β€ l β€ 10^5) β the number of lines in the function.
Each of the next l lines contains a single command of one of three types:
* for n (1 β€ n β€ 100) β for loop;
* end β every command between "for n" and corresponding "end" is executed n times;
* add β adds 1 to x.
Output
If overflow happened during execution of f(0), then output "OVERFLOW!!!", otherwise print the resulting value of x.
Examples
Input
9
add
for 43
end
for 10
for 15
add
end
add
end
Output
161
Input
2
for 62
end
Output
0
Input
11
for 100
for 100
for 100
for 100
for 100
add
end
end
end
end
end
Output
OVERFLOW!!!
Note
In the first example the first "add" is executed 1 time, the second "add" is executed 150 times and the last "add" is executed 10 times. Note that "for n" can be immediately followed by "end" and that "add" can be outside of any for loops.
In the second example there are no commands "add", thus the returning value is 0.
In the third example "add" command is executed too many times, which causes x to go over 2^{32}-1. | instruction | 0 | 107,099 | 20 | 214,198 |
Tags: data structures, expression parsing, implementation
Correct Solution:
```
n=int(input())
stack_for = [[1,0]]
overflow=int(0xffffffff)
ans=0
for i in range(n) :
c = input()
if c[0] == 'f' :
f_str=c.split()
stack_for.append([int(f_str[1]),0])
elif c[0] == 'a' :
L=stack_for.pop()
a=L[1]
a+=1
L[1] = a
stack_for.append(L)
else :
L = stack_for.pop()
f= L[0]
a=L[1]
stack_for[len(stack_for)-1][1]+=(f*a)
if stack_for[len(stack_for)-1][1] > overflow :
print("OVERFLOW!!!")
exit(0)
ans=stack_for.pop()[1]
if ans <= overflow :
print(ans)
else :
print("OVERFLOW!!!")
``` | output | 1 | 107,099 | 20 | 214,199 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a function f written in some basic language. The function accepts an integer value, which is immediately written into some variable x. x is an integer variable and can be assigned values from 0 to 2^{32}-1. The function contains three types of commands:
* for n β for loop;
* end β every command between "for n" and corresponding "end" is executed n times;
* add β adds 1 to x.
After the execution of these commands, value of x is returned.
Every "for n" is matched with "end", thus the function is guaranteed to be valid. "for n" can be immediately followed by "end"."add" command can be outside of any for loops.
Notice that "add" commands might overflow the value of x! It means that the value of x becomes greater than 2^{32}-1 after some "add" command.
Now you run f(0) and wonder if the resulting value of x is correct or some overflow made it incorrect.
If overflow happened then output "OVERFLOW!!!", otherwise print the resulting value of x.
Input
The first line contains a single integer l (1 β€ l β€ 10^5) β the number of lines in the function.
Each of the next l lines contains a single command of one of three types:
* for n (1 β€ n β€ 100) β for loop;
* end β every command between "for n" and corresponding "end" is executed n times;
* add β adds 1 to x.
Output
If overflow happened during execution of f(0), then output "OVERFLOW!!!", otherwise print the resulting value of x.
Examples
Input
9
add
for 43
end
for 10
for 15
add
end
add
end
Output
161
Input
2
for 62
end
Output
0
Input
11
for 100
for 100
for 100
for 100
for 100
add
end
end
end
end
end
Output
OVERFLOW!!!
Note
In the first example the first "add" is executed 1 time, the second "add" is executed 150 times and the last "add" is executed 10 times. Note that "for n" can be immediately followed by "end" and that "add" can be outside of any for loops.
In the second example there are no commands "add", thus the returning value is 0.
In the third example "add" command is executed too many times, which causes x to go over 2^{32}-1. | instruction | 0 | 107,100 | 20 | 214,200 |
Tags: data structures, expression parsing, implementation
Correct Solution:
```
# -*- coding: utf-8 -*-
# @Date : 2019-06-06 09:13:44
# @Author : raj lath (oorja.halt@gmail.com)
# @Link : link
# @Version : 1.0.0
import sys
sys.setrecursionlimit(10**5+1)
inf = int(10 ** 20)
max_val = inf
min_val = -inf
RW = lambda : sys.stdin.readline().strip()
RI = lambda : int(RW())
RMI = lambda : [int(x) for x in sys.stdin.readline().strip().split()]
RWI = lambda : [x for x in sys.stdin.readline().strip().split()]
overflow = 2 ** 32
ans = 0
nb_test = RI()
calc = [1]
for _ in range(nb_test):
mods, *vals = RWI()
if mods == "add":
ans += calc[-1]
elif mods == "for":
val = int(vals[0])
calc.append(min((calc[-1] * val),overflow))
#print(calc)
else:calc.pop()
ans = "OVERFLOW!!!" if ans >=overflow else ans
print(ans)
``` | output | 1 | 107,100 | 20 | 214,201 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a function f written in some basic language. The function accepts an integer value, which is immediately written into some variable x. x is an integer variable and can be assigned values from 0 to 2^{32}-1. The function contains three types of commands:
* for n β for loop;
* end β every command between "for n" and corresponding "end" is executed n times;
* add β adds 1 to x.
After the execution of these commands, value of x is returned.
Every "for n" is matched with "end", thus the function is guaranteed to be valid. "for n" can be immediately followed by "end"."add" command can be outside of any for loops.
Notice that "add" commands might overflow the value of x! It means that the value of x becomes greater than 2^{32}-1 after some "add" command.
Now you run f(0) and wonder if the resulting value of x is correct or some overflow made it incorrect.
If overflow happened then output "OVERFLOW!!!", otherwise print the resulting value of x.
Input
The first line contains a single integer l (1 β€ l β€ 10^5) β the number of lines in the function.
Each of the next l lines contains a single command of one of three types:
* for n (1 β€ n β€ 100) β for loop;
* end β every command between "for n" and corresponding "end" is executed n times;
* add β adds 1 to x.
Output
If overflow happened during execution of f(0), then output "OVERFLOW!!!", otherwise print the resulting value of x.
Examples
Input
9
add
for 43
end
for 10
for 15
add
end
add
end
Output
161
Input
2
for 62
end
Output
0
Input
11
for 100
for 100
for 100
for 100
for 100
add
end
end
end
end
end
Output
OVERFLOW!!!
Note
In the first example the first "add" is executed 1 time, the second "add" is executed 150 times and the last "add" is executed 10 times. Note that "for n" can be immediately followed by "end" and that "add" can be outside of any for loops.
In the second example there are no commands "add", thus the returning value is 0.
In the third example "add" command is executed too many times, which causes x to go over 2^{32}-1. | instruction | 0 | 107,101 | 20 | 214,202 |
Tags: data structures, expression parsing, implementation
Correct Solution:
```
inf=10**12
val=2**32
import sys
n=int(input())
m=1
st=[]
st1=[]
st2=[1]
ans=0
for i in range(n):
a=list(map(str,sys.stdin.readline().split()))
if len(a)==2:
m=int(a[1])
st1.append(m)
if st1[-1]*st2[-1]<=val:
st2.append(st1[-1]*st2[-1])
else:
st2.append(inf)
x=a[0]
m=st2[-1]
if x=="add":
ans+=m
elif x=="end":
st1.pop()
st2.pop()
# m//=int(k)
if ans>=2**32:
exit(print("OVERFLOW!!!"))
print(ans)
``` | output | 1 | 107,101 | 20 | 214,203 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a function f written in some basic language. The function accepts an integer value, which is immediately written into some variable x. x is an integer variable and can be assigned values from 0 to 2^{32}-1. The function contains three types of commands:
* for n β for loop;
* end β every command between "for n" and corresponding "end" is executed n times;
* add β adds 1 to x.
After the execution of these commands, value of x is returned.
Every "for n" is matched with "end", thus the function is guaranteed to be valid. "for n" can be immediately followed by "end"."add" command can be outside of any for loops.
Notice that "add" commands might overflow the value of x! It means that the value of x becomes greater than 2^{32}-1 after some "add" command.
Now you run f(0) and wonder if the resulting value of x is correct or some overflow made it incorrect.
If overflow happened then output "OVERFLOW!!!", otherwise print the resulting value of x.
Input
The first line contains a single integer l (1 β€ l β€ 10^5) β the number of lines in the function.
Each of the next l lines contains a single command of one of three types:
* for n (1 β€ n β€ 100) β for loop;
* end β every command between "for n" and corresponding "end" is executed n times;
* add β adds 1 to x.
Output
If overflow happened during execution of f(0), then output "OVERFLOW!!!", otherwise print the resulting value of x.
Examples
Input
9
add
for 43
end
for 10
for 15
add
end
add
end
Output
161
Input
2
for 62
end
Output
0
Input
11
for 100
for 100
for 100
for 100
for 100
add
end
end
end
end
end
Output
OVERFLOW!!!
Note
In the first example the first "add" is executed 1 time, the second "add" is executed 150 times and the last "add" is executed 10 times. Note that "for n" can be immediately followed by "end" and that "add" can be outside of any for loops.
In the second example there are no commands "add", thus the returning value is 0.
In the third example "add" command is executed too many times, which causes x to go over 2^{32}-1. | instruction | 0 | 107,102 | 20 | 214,204 |
Tags: data structures, expression parsing, implementation
Correct Solution:
```
import sys
L = int(sys.stdin.readline().strip())
x = 0
i = 1
m = []
v = True
l = 0
y = 0
while l < L:
w = sys.stdin.readline().strip()
if v == True and y == 0:
if w == "add":
x = x + i
elif w == "end":
i = i // m.pop()
else:
m.append(int(w.split()[1]))
i = i * m[-1]
if x > 2 ** 32 - 1:
v = False
if i > 2 ** 32 - 1:
y = y + 1
elif v == True and y > 0:
if w == "add":
v = False
elif w == "end":
y = y - 1
if y == 0:
i = i // m.pop()
else:
y = y + 1
l = l + 1
if v == True:
print(x)
else:
print("OVERFLOW!!!")
``` | output | 1 | 107,102 | 20 | 214,205 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.