message stringlengths 2 57.2k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 61 108k | cluster float64 22 22 | __index_level_0__ int64 122 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n integers a1, a2, ..., an. Find the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2 (i. e. some integer x exists so that ai + aj = 2x).
Input
The first line contains the single positive integer n (1 β€ n β€ 105) β the number of integers.
The second line contains n positive integers a1, a2, ..., an (1 β€ ai β€ 109).
Output
Print the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2.
Examples
Input
4
7 3 2 1
Output
2
Input
3
1 1 1
Output
3
Note
In the first example the following pairs of indexes include in answer: (1, 4) and (2, 4).
In the second example all pairs of indexes (i, j) (where i < j) include in answer. | instruction | 0 | 11,250 | 22 | 22,500 |
Tags: brute force, data structures, implementation, math
Correct Solution:
```
from collections import Counter,defaultdict,deque
#import heapq as hq
#import itertools
from operator import itemgetter
#from itertools import count, islice
#from functools import reduce
#alph = 'abcdefghijklmnopqrstuvwxyz'
#from math import factorial as fact
#a,b = [int(x) for x in input().split()]
#sarr = [x for x in input().strip().split()]
import math
import sys
input=sys.stdin.readline
def solve():
n = int(input())
arr = [int(x) for x in input().split()]
d = defaultdict(int)
res = 0
for el in arr:
for p in range(32):
res+=d[(1<<p)-el]
d[el]+=1
print(res)
tt = 1#int(input())
for test in range(tt):
solve()
#
``` | output | 1 | 11,250 | 22 | 22,501 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given several queries. Each query consists of three integers p, q and b. You need to answer whether the result of p/q in notation with base b is a finite fraction.
A fraction in notation with base b is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of queries.
Next n lines contain queries, one per line. Each line contains three integers p, q, and b (0 β€ p β€ 10^{18}, 1 β€ q β€ 10^{18}, 2 β€ b β€ 10^{18}). All numbers are given in notation with base 10.
Output
For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.
Examples
Input
2
6 12 10
4 3 10
Output
Finite
Infinite
Input
4
1 1 2
9 36 2
4 12 3
3 5 4
Output
Finite
Finite
Finite
Infinite
Note
6/12 = 1/2 = 0,5_{10}
4/3 = 1,(3)_{10}
9/36 = 1/4 = 0,01_2
4/12 = 1/3 = 0,1_3 | instruction | 0 | 11,382 | 22 | 22,764 |
Tags: implementation, math
Correct Solution:
```
def mod(b, q): #computes b^k mod q for large k
for i in range(6):
b = (b * b) % q
return b
n = int(input())
s = ''
for i in range(n - 1):
p, q, b = list(map(int, input().split()))
if (p * mod(b, q))%q: #checks if p * b^k is not divisible by q for large k
s += 'Infinite\n'
else:
s += 'Finite\n'
p, q, b = list(map(int, input().split()))
if (p * mod(b, q))%q: #checks if p * b^k is not divisible by q for large k
s += 'Infinite'
else:
s += 'Finite'
print(s)
``` | output | 1 | 11,382 | 22 | 22,765 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given several queries. Each query consists of three integers p, q and b. You need to answer whether the result of p/q in notation with base b is a finite fraction.
A fraction in notation with base b is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of queries.
Next n lines contain queries, one per line. Each line contains three integers p, q, and b (0 β€ p β€ 10^{18}, 1 β€ q β€ 10^{18}, 2 β€ b β€ 10^{18}). All numbers are given in notation with base 10.
Output
For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.
Examples
Input
2
6 12 10
4 3 10
Output
Finite
Infinite
Input
4
1 1 2
9 36 2
4 12 3
3 5 4
Output
Finite
Finite
Finite
Infinite
Note
6/12 = 1/2 = 0,5_{10}
4/3 = 1,(3)_{10}
9/36 = 1/4 = 0,01_2
4/12 = 1/3 = 0,1_3 | instruction | 0 | 11,383 | 22 | 22,766 |
Tags: implementation, math
Correct Solution:
```
n = int(input())
s = ''
for i in range(n):
p, q, b = map(int, input().split())
for i in range(6):
b = (b * b) % q
if ((p * b) % q):
s += 'Infinite\n'
else:
s += 'Finite\n'
print(s)
``` | output | 1 | 11,383 | 22 | 22,767 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given several queries. Each query consists of three integers p, q and b. You need to answer whether the result of p/q in notation with base b is a finite fraction.
A fraction in notation with base b is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of queries.
Next n lines contain queries, one per line. Each line contains three integers p, q, and b (0 β€ p β€ 10^{18}, 1 β€ q β€ 10^{18}, 2 β€ b β€ 10^{18}). All numbers are given in notation with base 10.
Output
For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.
Examples
Input
2
6 12 10
4 3 10
Output
Finite
Infinite
Input
4
1 1 2
9 36 2
4 12 3
3 5 4
Output
Finite
Finite
Finite
Infinite
Note
6/12 = 1/2 = 0,5_{10}
4/3 = 1,(3)_{10}
9/36 = 1/4 = 0,01_2
4/12 = 1/3 = 0,1_3 | instruction | 0 | 11,384 | 22 | 22,768 |
Tags: implementation, math
Correct Solution:
```
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n = int(input())
import math
for i in range(n):
p, q, b = map(int, input().split())
g = math.gcd(p, q)
p //= g
q //= g
if p == 0 or q == 1:
print('Finite')
continue
g = math.gcd(q, b)
while g != 1:
q //= g
b = g
g = math.gcd(q, b)
if q != 1:
print('Infinite')
else:
print('Finite')
``` | output | 1 | 11,384 | 22 | 22,769 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given several queries. Each query consists of three integers p, q and b. You need to answer whether the result of p/q in notation with base b is a finite fraction.
A fraction in notation with base b is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of queries.
Next n lines contain queries, one per line. Each line contains three integers p, q, and b (0 β€ p β€ 10^{18}, 1 β€ q β€ 10^{18}, 2 β€ b β€ 10^{18}). All numbers are given in notation with base 10.
Output
For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.
Examples
Input
2
6 12 10
4 3 10
Output
Finite
Infinite
Input
4
1 1 2
9 36 2
4 12 3
3 5 4
Output
Finite
Finite
Finite
Infinite
Note
6/12 = 1/2 = 0,5_{10}
4/3 = 1,(3)_{10}
9/36 = 1/4 = 0,01_2
4/12 = 1/3 = 0,1_3 | instruction | 0 | 11,385 | 22 | 22,770 |
Tags: implementation, math
Correct Solution:
```
print('\n'.join([(lambda p, q, b: 'Infinite' if p * pow(b, 99, q) % q else 'Finite')(*map(int, input().split())) for _ in range(int(input()))]))
``` | output | 1 | 11,385 | 22 | 22,771 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given several queries. Each query consists of three integers p, q and b. You need to answer whether the result of p/q in notation with base b is a finite fraction.
A fraction in notation with base b is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of queries.
Next n lines contain queries, one per line. Each line contains three integers p, q, and b (0 β€ p β€ 10^{18}, 1 β€ q β€ 10^{18}, 2 β€ b β€ 10^{18}). All numbers are given in notation with base 10.
Output
For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.
Examples
Input
2
6 12 10
4 3 10
Output
Finite
Infinite
Input
4
1 1 2
9 36 2
4 12 3
3 5 4
Output
Finite
Finite
Finite
Infinite
Note
6/12 = 1/2 = 0,5_{10}
4/3 = 1,(3)_{10}
9/36 = 1/4 = 0,01_2
4/12 = 1/3 = 0,1_3 | instruction | 0 | 11,386 | 22 | 22,772 |
Tags: implementation, math
Correct Solution:
```
print('\n'.join(('F','Inf')[pow(b,64,q)*p%q>0]+'inite'for p,q,b
in(map(int,input().split())for _ in[0]*int(input()))))
``` | output | 1 | 11,386 | 22 | 22,773 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given several queries. Each query consists of three integers p, q and b. You need to answer whether the result of p/q in notation with base b is a finite fraction.
A fraction in notation with base b is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of queries.
Next n lines contain queries, one per line. Each line contains three integers p, q, and b (0 β€ p β€ 10^{18}, 1 β€ q β€ 10^{18}, 2 β€ b β€ 10^{18}). All numbers are given in notation with base 10.
Output
For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.
Examples
Input
2
6 12 10
4 3 10
Output
Finite
Infinite
Input
4
1 1 2
9 36 2
4 12 3
3 5 4
Output
Finite
Finite
Finite
Infinite
Note
6/12 = 1/2 = 0,5_{10}
4/3 = 1,(3)_{10}
9/36 = 1/4 = 0,01_2
4/12 = 1/3 = 0,1_3 | instruction | 0 | 11,387 | 22 | 22,774 |
Tags: implementation, math
Correct Solution:
```
from sys import stdin, stdout
n=int(stdin.readline())
s=''
for i in range(n):
p,q,b=map(int,input().split())
for i in range(6):
b=(b*b)%q
if((p*b)%q):
s+='Infinite\n'
else:
s+='Finite\n'
print(s)
``` | output | 1 | 11,387 | 22 | 22,775 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given several queries. Each query consists of three integers p, q and b. You need to answer whether the result of p/q in notation with base b is a finite fraction.
A fraction in notation with base b is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of queries.
Next n lines contain queries, one per line. Each line contains three integers p, q, and b (0 β€ p β€ 10^{18}, 1 β€ q β€ 10^{18}, 2 β€ b β€ 10^{18}). All numbers are given in notation with base 10.
Output
For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.
Examples
Input
2
6 12 10
4 3 10
Output
Finite
Infinite
Input
4
1 1 2
9 36 2
4 12 3
3 5 4
Output
Finite
Finite
Finite
Infinite
Note
6/12 = 1/2 = 0,5_{10}
4/3 = 1,(3)_{10}
9/36 = 1/4 = 0,01_2
4/12 = 1/3 = 0,1_3
Submitted Solution:
```
def mod(b, q): #computes b^k mod q for large k
for i in range(6):
b = (b * b) % q
return b
n = int(input())
s = ''
for i in range(n):
p, q, b = list(map(int, input().split()))
if (p * mod(b, q))%q: #checks if p * b^k is not divisible by q for large k
s += 'Infinite\n'
else:
s += 'Fininte\n'
print(s)
``` | instruction | 0 | 11,388 | 22 | 22,776 |
No | output | 1 | 11,388 | 22 | 22,777 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given several queries. Each query consists of three integers p, q and b. You need to answer whether the result of p/q in notation with base b is a finite fraction.
A fraction in notation with base b is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of queries.
Next n lines contain queries, one per line. Each line contains three integers p, q, and b (0 β€ p β€ 10^{18}, 1 β€ q β€ 10^{18}, 2 β€ b β€ 10^{18}). All numbers are given in notation with base 10.
Output
For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.
Examples
Input
2
6 12 10
4 3 10
Output
Finite
Infinite
Input
4
1 1 2
9 36 2
4 12 3
3 5 4
Output
Finite
Finite
Finite
Infinite
Note
6/12 = 1/2 = 0,5_{10}
4/3 = 1,(3)_{10}
9/36 = 1/4 = 0,01_2
4/12 = 1/3 = 0,1_3
Submitted Solution:
```
def gcd(a, b):
if a > b:
a, b = b, a
if b % a == 0:
return a
return gcd(b, b % a)
n = int(input())
for i in range(n):
p, q, b = list(map(int, input().split()))
if p == 0:
print("Finite")
else:
q = q // gcd(p, q)
if pow(b, 64, q):
print("Infinite")
else:
print("Finite")
``` | instruction | 0 | 11,389 | 22 | 22,778 |
No | output | 1 | 11,389 | 22 | 22,779 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given several queries. Each query consists of three integers p, q and b. You need to answer whether the result of p/q in notation with base b is a finite fraction.
A fraction in notation with base b is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of queries.
Next n lines contain queries, one per line. Each line contains three integers p, q, and b (0 β€ p β€ 10^{18}, 1 β€ q β€ 10^{18}, 2 β€ b β€ 10^{18}). All numbers are given in notation with base 10.
Output
For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.
Examples
Input
2
6 12 10
4 3 10
Output
Finite
Infinite
Input
4
1 1 2
9 36 2
4 12 3
3 5 4
Output
Finite
Finite
Finite
Infinite
Note
6/12 = 1/2 = 0,5_{10}
4/3 = 1,(3)_{10}
9/36 = 1/4 = 0,01_2
4/12 = 1/3 = 0,1_3
Submitted Solution:
```
def mod(b, q): #computes b^k mod q for large k
for i in range(6):
b = (b * b) % q
return b
n = int(input())
s = ''
for i in range(n - 1):
p, q, b = list(map(int, input().split()))
if (p * mod(b, q))%q: #checks if p * b^k is not divisible by q for large k
s += 'Infinite\n'
else:
s += 'Fininte\n'
p, q, b = list(map(int, input().split()))
if (p * mod(b, q))%q: #checks if p * b^k is not divisible by q for large k
s += 'Infinite'
else:
s += 'Fininte'
print(s)
``` | instruction | 0 | 11,390 | 22 | 22,780 |
No | output | 1 | 11,390 | 22 | 22,781 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given several queries. Each query consists of three integers p, q and b. You need to answer whether the result of p/q in notation with base b is a finite fraction.
A fraction in notation with base b is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.
Input
The first line contains a single integer n (1 β€ n β€ 10^5) β the number of queries.
Next n lines contain queries, one per line. Each line contains three integers p, q, and b (0 β€ p β€ 10^{18}, 1 β€ q β€ 10^{18}, 2 β€ b β€ 10^{18}). All numbers are given in notation with base 10.
Output
For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.
Examples
Input
2
6 12 10
4 3 10
Output
Finite
Infinite
Input
4
1 1 2
9 36 2
4 12 3
3 5 4
Output
Finite
Finite
Finite
Infinite
Note
6/12 = 1/2 = 0,5_{10}
4/3 = 1,(3)_{10}
9/36 = 1/4 = 0,01_2
4/12 = 1/3 = 0,1_3
Submitted Solution:
```
def gcd(a, b):
if a > b:
a, b = b, a
if b % a == 0:
return a
return gcd(a, b % a)
def satisfy(b, q):
for i in range(7):
b = (b * b) % q
return b == 0
n = int(input())
for i in range(n):
p, q, b = list(map(int, input().split()))
if p == 0:
print("Finite")
else:
q = q // gcd(p, q)
if pow(b, q):
print("Infinite")
else:
print("Finite")
``` | instruction | 0 | 11,391 | 22 | 22,782 |
No | output | 1 | 11,391 | 22 | 22,783 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's assume that we have a pair of numbers (a, b). We can get a new pair (a + b, b) or (a, a + b) from the given pair in a single step.
Let the initial pair of numbers be (1,1). Your task is to find number k, that is, the least number of steps needed to transform (1,1) into the pair where at least one number equals n.
Input
The input contains the only integer n (1 β€ n β€ 106).
Output
Print the only integer k.
Examples
Input
5
Output
3
Input
1
Output
0
Note
The pair (1,1) can be transformed into a pair containing 5 in three moves: (1,1) β (1,2) β (3,2) β (5,2). | instruction | 0 | 11,764 | 22 | 23,528 |
Tags: brute force, dfs and similar, math, number theory
Correct Solution:
```
def gc(a,b,rs):
if b==1:
return [1,rs+a-1]
if b==0:
return [a,rs]
rs+=(a//b)
return gc(b,a%b,rs)
x=int(input())
res=10**9
for n in range(1,x):
u=gc(x,n,0)
if u[0]==1:
res=min(res,u[1])
if res==10**9:
res=0
print(res)
``` | output | 1 | 11,764 | 22 | 23,529 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's assume that we have a pair of numbers (a, b). We can get a new pair (a + b, b) or (a, a + b) from the given pair in a single step.
Let the initial pair of numbers be (1,1). Your task is to find number k, that is, the least number of steps needed to transform (1,1) into the pair where at least one number equals n.
Input
The input contains the only integer n (1 β€ n β€ 106).
Output
Print the only integer k.
Examples
Input
5
Output
3
Input
1
Output
0
Note
The pair (1,1) can be transformed into a pair containing 5 in three moves: (1,1) β (1,2) β (3,2) β (5,2). | instruction | 0 | 11,765 | 22 | 23,530 |
Tags: brute force, dfs and similar, math, number theory
Correct Solution:
```
def solve(N, M):
ans = 0
while M > 1:
ans += N // M
N, M = M, N % M
if M == 0: return 1000000
return N - 1 + ans
N = int(input())
ans = 1000000
for M in range(1, N + 1):
ans = min([ans, solve(N, M)])
print(ans)
``` | output | 1 | 11,765 | 22 | 23,531 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's assume that we have a pair of numbers (a, b). We can get a new pair (a + b, b) or (a, a + b) from the given pair in a single step.
Let the initial pair of numbers be (1,1). Your task is to find number k, that is, the least number of steps needed to transform (1,1) into the pair where at least one number equals n.
Input
The input contains the only integer n (1 β€ n β€ 106).
Output
Print the only integer k.
Examples
Input
5
Output
3
Input
1
Output
0
Note
The pair (1,1) can be transformed into a pair containing 5 in three moves: (1,1) β (1,2) β (3,2) β (5,2). | instruction | 0 | 11,768 | 22 | 23,536 |
Tags: brute force, dfs and similar, math, number theory
Correct Solution:
```
def calc(n,m):
ans=0
while(m>1):
ans+=n//m
n,m=m,n%m
if m==0:
return float("inf")
return ans+n-1
n=int(input())
ans=n-1
for i in range(1,n+1):
ans=min(ans,calc(n,i))
print(ans)
``` | output | 1 | 11,768 | 22 | 23,537 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's assume that we have a pair of numbers (a, b). We can get a new pair (a + b, b) or (a, a + b) from the given pair in a single step.
Let the initial pair of numbers be (1,1). Your task is to find number k, that is, the least number of steps needed to transform (1,1) into the pair where at least one number equals n.
Input
The input contains the only integer n (1 β€ n β€ 106).
Output
Print the only integer k.
Examples
Input
5
Output
3
Input
1
Output
0
Note
The pair (1,1) can be transformed into a pair containing 5 in three moves: (1,1) β (1,2) β (3,2) β (5,2). | instruction | 0 | 11,771 | 22 | 23,542 |
Tags: brute force, dfs and similar, math, number theory
Correct Solution:
```
TMP = 0
def dfs(a, b, n):
global TMP
if not b:
TMP = n
return None
if b == 1:
TMP += a - 1
return None
TMP += a // b
dfs(b, a % b, n)
class CodeforcesTask134BSolution:
def __init__(self):
self.result = ''
self.n = 0
def read_input(self):
self.n = int(input())
def process_task(self):
ans = self.n - 1
for i in range(1, self.n):
global TMP
TMP = 0
dfs(self.n, i, self.n)
ans = min(ans, TMP)
self.result = str(ans)
def get_result(self):
return self.result
if __name__ == "__main__":
Solution = CodeforcesTask134BSolution()
Solution.read_input()
Solution.process_task()
print(Solution.get_result())
``` | output | 1 | 11,771 | 22 | 23,543 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have two positive integers a and b.
You can perform two kinds of operations:
* a = β a/b β (replace a with the integer part of the division between a and b)
* b=b+1 (increase b by 1)
Find the minimum number of operations required to make a=0.
Input
The first line contains a single integer t (1 β€ t β€ 100) β the number of test cases.
The only line of the description of each test case contains two integers a, b (1 β€ a,b β€ 10^9).
Output
For each test case, print a single integer: the minimum number of operations required to make a=0.
Example
Input
6
9 2
1337 1
1 1
50000000 4
991026972 997
1234 5678
Output
4
9
2
12
3
1
Note
In the first test case, one of the optimal solutions is:
1. Divide a by b. After this operation a = 4 and b = 2.
2. Divide a by b. After this operation a = 2 and b = 2.
3. Increase b. After this operation a = 2 and b = 3.
4. Divide a by b. After this operation a = 0 and b = 3. | instruction | 0 | 11,844 | 22 | 23,688 |
Tags: brute force, greedy, math, number theory
Correct Solution:
```
import sys
input=sys.stdin.buffer.readline
for t in range(int(input())):
A,B=map(int,input().split())
X=0
C,D=A,B
if B==1:
X=1
D=2
while C>0:
C//=D
X+=1
ANS=X
for i in range(1,X):
C,D=A,B+i
while C>0:
C//=D
i+=1
ANS=min(ANS,i)
print(ANS)
``` | output | 1 | 11,844 | 22 | 23,689 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have two positive integers a and b.
You can perform two kinds of operations:
* a = β a/b β (replace a with the integer part of the division between a and b)
* b=b+1 (increase b by 1)
Find the minimum number of operations required to make a=0.
Input
The first line contains a single integer t (1 β€ t β€ 100) β the number of test cases.
The only line of the description of each test case contains two integers a, b (1 β€ a,b β€ 10^9).
Output
For each test case, print a single integer: the minimum number of operations required to make a=0.
Example
Input
6
9 2
1337 1
1 1
50000000 4
991026972 997
1234 5678
Output
4
9
2
12
3
1
Note
In the first test case, one of the optimal solutions is:
1. Divide a by b. After this operation a = 4 and b = 2.
2. Divide a by b. After this operation a = 2 and b = 2.
3. Increase b. After this operation a = 2 and b = 3.
4. Divide a by b. After this operation a = 0 and b = 3. | instruction | 0 | 11,845 | 22 | 23,690 |
Tags: brute force, greedy, math, number theory
Correct Solution:
```
import sys
from collections import defaultdict as dd
from collections import Counter as cc
from queue import Queue
import math
from math import sqrt
import itertools
try:
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
except:
pass
input = lambda: sys.stdin.readline().rstrip()
for _ in range(int(input())):
a,b=map(int,input().split())
q=2e9
if b!=1:
w=0
e=a
while e:
e//=b
w+=1
q=min(q,w)
w=a
if a<b:
print(1)
else:
for i in range(b+1,a+101):
w=i-b
e=a
while e>0:
e//=i
w+=1
if w<=q:
q=w
else:
break
print(q)
``` | output | 1 | 11,845 | 22 | 23,691 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have two positive integers a and b.
You can perform two kinds of operations:
* a = β a/b β (replace a with the integer part of the division between a and b)
* b=b+1 (increase b by 1)
Find the minimum number of operations required to make a=0.
Input
The first line contains a single integer t (1 β€ t β€ 100) β the number of test cases.
The only line of the description of each test case contains two integers a, b (1 β€ a,b β€ 10^9).
Output
For each test case, print a single integer: the minimum number of operations required to make a=0.
Example
Input
6
9 2
1337 1
1 1
50000000 4
991026972 997
1234 5678
Output
4
9
2
12
3
1
Note
In the first test case, one of the optimal solutions is:
1. Divide a by b. After this operation a = 4 and b = 2.
2. Divide a by b. After this operation a = 2 and b = 2.
3. Increase b. After this operation a = 2 and b = 3.
4. Divide a by b. After this operation a = 0 and b = 3. | instruction | 0 | 11,846 | 22 | 23,692 |
Tags: brute force, greedy, math, number theory
Correct Solution:
```
def do(cnt,a,b):
while a>=1:
cnt+=1
a=a//b
return cnt
for _ in range(int(input())):
a,b=[int(x) for x in input().split()]
cnt=0
if b==1:
b+=1;cnt+=1
print(min([do(cnt+i,a,b+i) for i in range(10)]))
``` | output | 1 | 11,846 | 22 | 23,693 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have two positive integers a and b.
You can perform two kinds of operations:
* a = β a/b β (replace a with the integer part of the division between a and b)
* b=b+1 (increase b by 1)
Find the minimum number of operations required to make a=0.
Input
The first line contains a single integer t (1 β€ t β€ 100) β the number of test cases.
The only line of the description of each test case contains two integers a, b (1 β€ a,b β€ 10^9).
Output
For each test case, print a single integer: the minimum number of operations required to make a=0.
Example
Input
6
9 2
1337 1
1 1
50000000 4
991026972 997
1234 5678
Output
4
9
2
12
3
1
Note
In the first test case, one of the optimal solutions is:
1. Divide a by b. After this operation a = 4 and b = 2.
2. Divide a by b. After this operation a = 2 and b = 2.
3. Increase b. After this operation a = 2 and b = 3.
4. Divide a by b. After this operation a = 0 and b = 3. | instruction | 0 | 11,847 | 22 | 23,694 |
Tags: brute force, greedy, math, number theory
Correct Solution:
```
import math
for _ in range(int(input())):
s=0
min = 9999
a, b = input().split()
a, b = int(a), int(b)
for i in range(b, b+20):
if i == 1:
continue
s1 = math.ceil(math.log(a, i)) + (i-b)
if a // pow(i,math.ceil(math.log(a, i))) != 0:
s1+=1
if s1<min:
min = s1
print(min)
``` | output | 1 | 11,847 | 22 | 23,695 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have two positive integers a and b.
You can perform two kinds of operations:
* a = β a/b β (replace a with the integer part of the division between a and b)
* b=b+1 (increase b by 1)
Find the minimum number of operations required to make a=0.
Input
The first line contains a single integer t (1 β€ t β€ 100) β the number of test cases.
The only line of the description of each test case contains two integers a, b (1 β€ a,b β€ 10^9).
Output
For each test case, print a single integer: the minimum number of operations required to make a=0.
Example
Input
6
9 2
1337 1
1 1
50000000 4
991026972 997
1234 5678
Output
4
9
2
12
3
1
Note
In the first test case, one of the optimal solutions is:
1. Divide a by b. After this operation a = 4 and b = 2.
2. Divide a by b. After this operation a = 2 and b = 2.
3. Increase b. After this operation a = 2 and b = 3.
4. Divide a by b. After this operation a = 0 and b = 3. | instruction | 0 | 11,848 | 22 | 23,696 |
Tags: brute force, greedy, math, number theory
Correct Solution:
```
import sys
input = sys.stdin.readline
import math
t = int(input())
for f in range(t):
a,b = map(int,input().split())
ans = 1000000000
for i in range(10000):
temp = i
check = b
comp = a
check += i
if check == 1:
continue
while comp != 0:
comp //= check
temp += 1
ans = min(ans,temp)
print(ans)
``` | output | 1 | 11,848 | 22 | 23,697 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have two positive integers a and b.
You can perform two kinds of operations:
* a = β a/b β (replace a with the integer part of the division between a and b)
* b=b+1 (increase b by 1)
Find the minimum number of operations required to make a=0.
Input
The first line contains a single integer t (1 β€ t β€ 100) β the number of test cases.
The only line of the description of each test case contains two integers a, b (1 β€ a,b β€ 10^9).
Output
For each test case, print a single integer: the minimum number of operations required to make a=0.
Example
Input
6
9 2
1337 1
1 1
50000000 4
991026972 997
1234 5678
Output
4
9
2
12
3
1
Note
In the first test case, one of the optimal solutions is:
1. Divide a by b. After this operation a = 4 and b = 2.
2. Divide a by b. After this operation a = 2 and b = 2.
3. Increase b. After this operation a = 2 and b = 3.
4. Divide a by b. After this operation a = 0 and b = 3. | instruction | 0 | 11,849 | 22 | 23,698 |
Tags: brute force, greedy, math, number theory
Correct Solution:
```
for _ in range(int(input())):
a, b = map(int, input().split())
ans = float("inf")
i = 0
while i*i <= a:
if b == 1 and i == 0:
i += 1
continue
c = a
count = i
while c:
c = c//(b+i)
count += 1
ans = min(ans, count)
i += 1
print(ans)
``` | output | 1 | 11,849 | 22 | 23,699 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have two positive integers a and b.
You can perform two kinds of operations:
* a = β a/b β (replace a with the integer part of the division between a and b)
* b=b+1 (increase b by 1)
Find the minimum number of operations required to make a=0.
Input
The first line contains a single integer t (1 β€ t β€ 100) β the number of test cases.
The only line of the description of each test case contains two integers a, b (1 β€ a,b β€ 10^9).
Output
For each test case, print a single integer: the minimum number of operations required to make a=0.
Example
Input
6
9 2
1337 1
1 1
50000000 4
991026972 997
1234 5678
Output
4
9
2
12
3
1
Note
In the first test case, one of the optimal solutions is:
1. Divide a by b. After this operation a = 4 and b = 2.
2. Divide a by b. After this operation a = 2 and b = 2.
3. Increase b. After this operation a = 2 and b = 3.
4. Divide a by b. After this operation a = 0 and b = 3. | instruction | 0 | 11,850 | 22 | 23,700 |
Tags: brute force, greedy, math, number theory
Correct Solution:
```
import math
def f(a, b):
cnt = 0
while a != 0:
a //= b
cnt += 1
return cnt
t = int(input())
for _ in range(t):
a, b = map(int, input().split())
ans = 32
if b < 10:
for i in range(max(2, b), 10):
cur = i - b + f(a, i)
ans = min(ans, cur)
else:
ans = f(a, b)
print(ans)
``` | output | 1 | 11,850 | 22 | 23,701 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have two positive integers a and b.
You can perform two kinds of operations:
* a = β a/b β (replace a with the integer part of the division between a and b)
* b=b+1 (increase b by 1)
Find the minimum number of operations required to make a=0.
Input
The first line contains a single integer t (1 β€ t β€ 100) β the number of test cases.
The only line of the description of each test case contains two integers a, b (1 β€ a,b β€ 10^9).
Output
For each test case, print a single integer: the minimum number of operations required to make a=0.
Example
Input
6
9 2
1337 1
1 1
50000000 4
991026972 997
1234 5678
Output
4
9
2
12
3
1
Note
In the first test case, one of the optimal solutions is:
1. Divide a by b. After this operation a = 4 and b = 2.
2. Divide a by b. After this operation a = 2 and b = 2.
3. Increase b. After this operation a = 2 and b = 3.
4. Divide a by b. After this operation a = 0 and b = 3. | instruction | 0 | 11,851 | 22 | 23,702 |
Tags: brute force, greedy, math, number theory
Correct Solution:
```
import sys
def get_array(): return list(map(int , sys.stdin.readline().strip().split()))
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def input(): return sys.stdin.readline().strip()
import math
for _ in range(int(input())):
a,b = get_ints()
count = 0
mi = 10**10
if(a==b and b==1):
print(2)
continue
if (a == b):
print(2)
continue
if(a==1):
print(1)
continue
if (b>a):
print(1)
continue
while(True):
if(b == 1):
b+=1
count+=1
continue
else:
if (b==0):
continue
t = a-(a%b)
# print(a,b,t,mi)
if(b>t):
break
k = round(math.log(t,b),12)
# print("k = " ,round(k,2) )
if( k == math.ceil(k)):
k-=1
k+=2
if(k + count <= mi):
mi = k + count
# b += 1
b += 1
count += 1
continue
else:
break
else:
k = math.ceil(k)
# print("k = ",k,count)
# break
if ( k + count <= mi):
mi = k + count
b+=1
count+=1
else:
break
print(int(mi))
``` | output | 1 | 11,851 | 22 | 23,703 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, but will ask them to create a new set to replenish his beautiful collection of sets.
Dr. Evil has his favorite evil integer x. He asks Mahmoud and Ehab to find a set of n distinct non-negative integers such the bitwise-xor sum of the integers in it is exactly x. Dr. Evil doesn't like big numbers, so any number in the set shouldn't be greater than 106.
Input
The only line contains two integers n and x (1 β€ n β€ 105, 0 β€ x β€ 105) β the number of elements in the set and the desired bitwise-xor, respectively.
Output
If there is no such set, print "NO" (without quotes).
Otherwise, on the first line print "YES" (without quotes) and on the second line print n distinct integers, denoting the elements in the set is any order. If there are multiple solutions you can print any of them.
Examples
Input
5 5
Output
YES
1 2 4 5 7
Input
3 6
Output
YES
1 2 5
Note
You can read more about the bitwise-xor operation here: <https://en.wikipedia.org/wiki/Bitwise_operation#XOR>
For the first sample <image>.
For the second sample <image>. | instruction | 0 | 12,210 | 22 | 24,420 |
Tags: constructive algorithms
Correct Solution:
```
n, x = map(int, input().split())
if n == 1:
print("YES")
print(x)
exit()
elif n == 2:
if x == 0:
print("NO")
else:
print("YES")
print(0, x)
exit()
l = [i for i in range(1, n-2)]
v = 0
for i in range(1,n-2):
v = v^i
r1 = x^v
r1 ^= 2**17 + 2**18
r2 = 2**17 + 2**19
r3 = 2**18 + 2**19
l.extend([r1,r2,r3])
print("YES")
print(*l)
``` | output | 1 | 12,210 | 22 | 24,421 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, but will ask them to create a new set to replenish his beautiful collection of sets.
Dr. Evil has his favorite evil integer x. He asks Mahmoud and Ehab to find a set of n distinct non-negative integers such the bitwise-xor sum of the integers in it is exactly x. Dr. Evil doesn't like big numbers, so any number in the set shouldn't be greater than 106.
Input
The only line contains two integers n and x (1 β€ n β€ 105, 0 β€ x β€ 105) β the number of elements in the set and the desired bitwise-xor, respectively.
Output
If there is no such set, print "NO" (without quotes).
Otherwise, on the first line print "YES" (without quotes) and on the second line print n distinct integers, denoting the elements in the set is any order. If there are multiple solutions you can print any of them.
Examples
Input
5 5
Output
YES
1 2 4 5 7
Input
3 6
Output
YES
1 2 5
Note
You can read more about the bitwise-xor operation here: <https://en.wikipedia.org/wiki/Bitwise_operation#XOR>
For the first sample <image>.
For the second sample <image>. | instruction | 0 | 12,211 | 22 | 24,422 |
Tags: constructive algorithms
Correct Solution:
```
n, x = map(int, input().split())
if n == 2 and x == 0:
print('NO')
exit()
if n == 1:
print('YES')
print(x)
exit()
a = [i for i in range(1, n-2)]
xr = 0
for i in a:
xr ^= i
if xr == x:
a += [2**17, 2**18, 2**17 ^ 2**18]
else:
if n >=3:
a += [0, 2**17, 2**17^xr^x]
else:
a += [2**17, 2**17^xr^x]
print('YES')
print(' '.join([str(i) for i in a]))
``` | output | 1 | 12,211 | 22 | 24,423 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, but will ask them to create a new set to replenish his beautiful collection of sets.
Dr. Evil has his favorite evil integer x. He asks Mahmoud and Ehab to find a set of n distinct non-negative integers such the bitwise-xor sum of the integers in it is exactly x. Dr. Evil doesn't like big numbers, so any number in the set shouldn't be greater than 106.
Input
The only line contains two integers n and x (1 β€ n β€ 105, 0 β€ x β€ 105) β the number of elements in the set and the desired bitwise-xor, respectively.
Output
If there is no such set, print "NO" (without quotes).
Otherwise, on the first line print "YES" (without quotes) and on the second line print n distinct integers, denoting the elements in the set is any order. If there are multiple solutions you can print any of them.
Examples
Input
5 5
Output
YES
1 2 4 5 7
Input
3 6
Output
YES
1 2 5
Note
You can read more about the bitwise-xor operation here: <https://en.wikipedia.org/wiki/Bitwise_operation#XOR>
For the first sample <image>.
For the second sample <image>. | instruction | 0 | 12,212 | 22 | 24,424 |
Tags: constructive algorithms
Correct Solution:
```
n, x = map(int, input().split())
if n == 2 and x == 0:
print("NO")
else:
print("YES")
if n > 1:
temp = x
for i in range(n-1):
temp ^= i
if temp:
for i in range(1, n-1): print(i, end = ' ')
print(2**17, 2**17 + temp)
else:
for i in range(n-2): print(i, end = ' ')
print(2**17, 2**17 + n-2)
else:
print(x)
``` | output | 1 | 12,212 | 22 | 24,425 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, but will ask them to create a new set to replenish his beautiful collection of sets.
Dr. Evil has his favorite evil integer x. He asks Mahmoud and Ehab to find a set of n distinct non-negative integers such the bitwise-xor sum of the integers in it is exactly x. Dr. Evil doesn't like big numbers, so any number in the set shouldn't be greater than 106.
Input
The only line contains two integers n and x (1 β€ n β€ 105, 0 β€ x β€ 105) β the number of elements in the set and the desired bitwise-xor, respectively.
Output
If there is no such set, print "NO" (without quotes).
Otherwise, on the first line print "YES" (without quotes) and on the second line print n distinct integers, denoting the elements in the set is any order. If there are multiple solutions you can print any of them.
Examples
Input
5 5
Output
YES
1 2 4 5 7
Input
3 6
Output
YES
1 2 5
Note
You can read more about the bitwise-xor operation here: <https://en.wikipedia.org/wiki/Bitwise_operation#XOR>
For the first sample <image>.
For the second sample <image>. | instruction | 0 | 12,213 | 22 | 24,426 |
Tags: constructive algorithms
Correct Solution:
```
def main():
n, x = map(int, input().split())
if n == 1:
print('YES')
print(x)
return
if n == 2:
if x == 0:
print('NO')
else:
print('YES')
print(0, x)
return
o = 0
for i in range(n - 1):
o ^= i
print('YES')
q = o ^ x
if q >= n - 1:
print(*([i for i in range(n - 1)]), q)
else:
if n - 2 != q:
print(*([i for i in range(n - 2)]), n - 2 + 262144, q + 262144)
else:
print(*([i for i in range(n - 3)]), n - 3 + 262144, n - 2, q + 262144)
main()
``` | output | 1 | 12,213 | 22 | 24,427 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, but will ask them to create a new set to replenish his beautiful collection of sets.
Dr. Evil has his favorite evil integer x. He asks Mahmoud and Ehab to find a set of n distinct non-negative integers such the bitwise-xor sum of the integers in it is exactly x. Dr. Evil doesn't like big numbers, so any number in the set shouldn't be greater than 106.
Input
The only line contains two integers n and x (1 β€ n β€ 105, 0 β€ x β€ 105) β the number of elements in the set and the desired bitwise-xor, respectively.
Output
If there is no such set, print "NO" (without quotes).
Otherwise, on the first line print "YES" (without quotes) and on the second line print n distinct integers, denoting the elements in the set is any order. If there are multiple solutions you can print any of them.
Examples
Input
5 5
Output
YES
1 2 4 5 7
Input
3 6
Output
YES
1 2 5
Note
You can read more about the bitwise-xor operation here: <https://en.wikipedia.org/wiki/Bitwise_operation#XOR>
For the first sample <image>.
For the second sample <image>. | instruction | 0 | 12,214 | 22 | 24,428 |
Tags: constructive algorithms
Correct Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 26 14:24:58 2017
"""
def xor(a,b):
a=bin(a)[2:]
b=bin(b)[2:]
while(len(a)>len(b)):
b='0' + b
while(len(b)>len(a)):
a='0' + a
c=['0']*len(a)
for i in range(len(a)):
if(a[i]!=b[i]):
c[i]='1'
a=''
for i in c:
a+=i
return(int(a,2))
n,x=input().split()
n=int(n)
x=int(x)
a=[]
ans=0
flag=False
if(n%4!=0):
for i in range(n-n%4):
a.append(100002+i)
if(n%4==1):
a.append(x)
elif(n%4==2):
if(x==0):
if(n==2):
flag=True
else:
for i in range(4):
del a[-1]
a.append(500001)
a.append(500002)
a.append(500007)
a.append(300046)
a.append(210218)
a.append(0)
else:
a.append(0)
a.append(x)
else:
if(x==0):
a.append(4)
a.append(7)
a.append(3)
elif(x==1):
a.append(8)
a.append(9)
a.append(0)
elif(x==2):
a.append(1)
a.append(4)
a.append(7)
else:
a.append(0)
a.append(1)
if(x%2==0):
a.append(x+1)
else:
a.append(x-1)
else:
for i in range(n-4):
a.append(100002+i)
a.append(500001)
a.append(200002)
a.append(306275)
a.append(x)
if(flag):
print("NO")
else:
print("YES")
temp=''
for i in a:
temp+=str(i)
temp+=' '
print(temp)
``` | output | 1 | 12,214 | 22 | 24,429 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, but will ask them to create a new set to replenish his beautiful collection of sets.
Dr. Evil has his favorite evil integer x. He asks Mahmoud and Ehab to find a set of n distinct non-negative integers such the bitwise-xor sum of the integers in it is exactly x. Dr. Evil doesn't like big numbers, so any number in the set shouldn't be greater than 106.
Input
The only line contains two integers n and x (1 β€ n β€ 105, 0 β€ x β€ 105) β the number of elements in the set and the desired bitwise-xor, respectively.
Output
If there is no such set, print "NO" (without quotes).
Otherwise, on the first line print "YES" (without quotes) and on the second line print n distinct integers, denoting the elements in the set is any order. If there are multiple solutions you can print any of them.
Examples
Input
5 5
Output
YES
1 2 4 5 7
Input
3 6
Output
YES
1 2 5
Note
You can read more about the bitwise-xor operation here: <https://en.wikipedia.org/wiki/Bitwise_operation#XOR>
For the first sample <image>.
For the second sample <image>. | instruction | 0 | 12,215 | 22 | 24,430 |
Tags: constructive algorithms
Correct Solution:
```
def comp(n) :
if n % 4 == 0 :
return n
if n % 4 == 1 :
return 1
if n % 4 == 2 :
return n + 1
return 0
n , x = map(int,input().split())
a=1<<17
if n==2:
if x==0:
print("NO")
else:
print("YES")
print(0,x)
elif n==1:
print("YES")
print(x)
else:
ans=[i for i in range(1,n-2)]
if comp(n-3)==x:
ans.append((a*2)^a)
ans.append(a)
ans.append(a*2)
else:
ans.append(0)
ans.append(a)
ans.append(a^x^comp(n-3))
print("YES")
print(*ans)
``` | output | 1 | 12,215 | 22 | 24,431 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, but will ask them to create a new set to replenish his beautiful collection of sets.
Dr. Evil has his favorite evil integer x. He asks Mahmoud and Ehab to find a set of n distinct non-negative integers such the bitwise-xor sum of the integers in it is exactly x. Dr. Evil doesn't like big numbers, so any number in the set shouldn't be greater than 106.
Input
The only line contains two integers n and x (1 β€ n β€ 105, 0 β€ x β€ 105) β the number of elements in the set and the desired bitwise-xor, respectively.
Output
If there is no such set, print "NO" (without quotes).
Otherwise, on the first line print "YES" (without quotes) and on the second line print n distinct integers, denoting the elements in the set is any order. If there are multiple solutions you can print any of them.
Examples
Input
5 5
Output
YES
1 2 4 5 7
Input
3 6
Output
YES
1 2 5
Note
You can read more about the bitwise-xor operation here: <https://en.wikipedia.org/wiki/Bitwise_operation#XOR>
For the first sample <image>.
For the second sample <image>. | instruction | 0 | 12,216 | 22 | 24,432 |
Tags: constructive algorithms
Correct Solution:
```
from sys import stdin, stdout
class Solve:
def __init__(self):
R = stdin.readline
W = stdout.write
n, x = map(int, R().split())
ans = []
if n == 2 and x == 0:
W('NO\n')
return
elif n == 1:
W('YES\n%d' % x)
return
elif n == 2:
W('YES\n%d %d' % (0,x))
return
ans = ['YES\n']
xor = 0
for i in range(1,n-2):
xor ^= i
ans.append(str(i) + ' ')
if xor == x:
ans += [str(2**17)+' ', str(2**18)+' ',str((2**17)^(2**18))]
else:
ans += ['0 ', str(2**17)+' ', str((2**17)^xor^x)]
W(''.join(ans))
def main():
s = Solve()
main()
``` | output | 1 | 12,216 | 22 | 24,433 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems.
The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced.
Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7.
Input
Input consists of multiple test cases. The first line contains one integer t (1 β€ t β€ 10^5) β the number of test cases. Each test case is described as follows:
The first line contains two integers n and p (1 β€ n, p β€ 10^6). The second line contains n integers k_i (0 β€ k_i β€ 10^6).
The sum of n over all test cases doesn't exceed 10^6.
Output
Output one integer β the reminder of division the answer by 1 000 000 007.
Example
Input
4
5 2
2 3 4 4 3
3 1
2 10 1000
4 5
0 1 1 100
1 8
89
Output
4
1
146981438
747093407
Note
You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1.
In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. | instruction | 0 | 12,602 | 22 | 25,204 |
Tags: greedy, implementation, math, sortings
Correct Solution:
```
#!/usr/bin/env python
#pyrival orz
import os
import sys
from io import BytesIO, IOBase
"""
for _ in range(int(input())):
n,m=map(int,input().split())
n=int(input())
a = [int(x) for x in input().split()]
"""
def main():
mod=10**9+7
def po(a,n):
ans=1
while n:
if n&1:
ans=(ans*a)%mod
a=(a*a)%mod
n//=2
return ans
for _ in range(int(input())):
n,p=map(int,input().split())
a = [int(x) for x in input().split()]
if p==1:
print(n%2)
continue
a.sort(reverse=True)
# print(a)
from collections import defaultdict
d=defaultdict(int)
for x in a:
# print(x,d)
if len(d)==0:
d[x]+=1
else:
d[x]-=1
while len(d) and d[x]%p==0:
if d[x]==0:
del d[x]
break
d[x+1]+=d[x]//p
del d[x]
x+=1
# print(d)
ans=0
for x in d.items():
ans+=x[1]*po(p,x[0])%mod
print(ans%mod)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
``` | output | 1 | 12,602 | 22 | 25,205 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems.
The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced.
Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7.
Input
Input consists of multiple test cases. The first line contains one integer t (1 β€ t β€ 10^5) β the number of test cases. Each test case is described as follows:
The first line contains two integers n and p (1 β€ n, p β€ 10^6). The second line contains n integers k_i (0 β€ k_i β€ 10^6).
The sum of n over all test cases doesn't exceed 10^6.
Output
Output one integer β the reminder of division the answer by 1 000 000 007.
Example
Input
4
5 2
2 3 4 4 3
3 1
2 10 1000
4 5
0 1 1 100
1 8
89
Output
4
1
146981438
747093407
Note
You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1.
In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. | instruction | 0 | 12,603 | 22 | 25,206 |
Tags: greedy, implementation, math, sortings
Correct Solution:
```
import sys
readline = sys.stdin.readline
T = int(readline())
Ans = [None]*T
MOD = 10**9+7
mod = 10**9+9
for qu in range(T):
N, P = map(int, readline().split())
A = list(map(int, readline().split()))
if P == 1:
if N&1:
Ans[qu] = 1
else:
Ans[qu] = 0
continue
if N == 1:
Ans[qu] = pow(P, A[0], MOD)
continue
A.sort(reverse = True)
cans = 0
carry = 0
res = 0
ra = 0
for a in A:
if carry == 0:
carry = pow(P, a, mod)
cans = pow(P, a, MOD)
continue
res = (res + pow(P, a, mod))%mod
ra = (ra + pow(P, a, MOD))%MOD
if res == carry and ra == cans:
carry = 0
cans = 0
ra = 0
res = 0
Ans[qu] = (cans-ra)%MOD
print('\n'.join(map(str, Ans)))
``` | output | 1 | 12,603 | 22 | 25,207 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems.
The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced.
Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7.
Input
Input consists of multiple test cases. The first line contains one integer t (1 β€ t β€ 10^5) β the number of test cases. Each test case is described as follows:
The first line contains two integers n and p (1 β€ n, p β€ 10^6). The second line contains n integers k_i (0 β€ k_i β€ 10^6).
The sum of n over all test cases doesn't exceed 10^6.
Output
Output one integer β the reminder of division the answer by 1 000 000 007.
Example
Input
4
5 2
2 3 4 4 3
3 1
2 10 1000
4 5
0 1 1 100
1 8
89
Output
4
1
146981438
747093407
Note
You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1.
In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. | instruction | 0 | 12,604 | 22 | 25,208 |
Tags: greedy, implementation, math, sortings
Correct Solution:
```
#created by nit1n
import sys
input = sys.stdin.readline
m = 1000000007
for T in range(int(input())) :
n, p = list(map(int ,input().split()))
arr = list(map(int, input().split()))
if p ==1 :
if n&1 :
print(1)
else :
print(0)
continue
if n ==1 :
print(pow(p,arr[0] ,m))
continue
arr.sort(reverse = True)
curr = 0
c = -1
for i in range(n ):
if c == - 1 :
req =1
curr = i
c = arr[i]
prev = arr[i]
#print(c,curr)
else :
d = prev -arr[i]
if d > 20 :
break
req *= p**d
prev = arr[i]
req -=1
#print(req)
if req > n :
break
if req == 0 :
c = -1
if c != -1 :
ans = pow(p ,c , m)
for i in range(curr+1 ,n ) :
ans -= pow(p ,arr[i] , m )
print(ans%(m))
else :
print(0)
``` | output | 1 | 12,604 | 22 | 25,209 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems.
The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced.
Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7.
Input
Input consists of multiple test cases. The first line contains one integer t (1 β€ t β€ 10^5) β the number of test cases. Each test case is described as follows:
The first line contains two integers n and p (1 β€ n, p β€ 10^6). The second line contains n integers k_i (0 β€ k_i β€ 10^6).
The sum of n over all test cases doesn't exceed 10^6.
Output
Output one integer β the reminder of division the answer by 1 000 000 007.
Example
Input
4
5 2
2 3 4 4 3
3 1
2 10 1000
4 5
0 1 1 100
1 8
89
Output
4
1
146981438
747093407
Note
You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1.
In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. | instruction | 0 | 12,605 | 22 | 25,210 |
Tags: greedy, implementation, math, sortings
Correct Solution:
```
from sys import stdin,stderr
def rl():
return [int(w) for w in stdin.readline().split()]
M = 1000000007
def pow(p, x):
r = 1
p2k = p
while x > 0:
if x & 1:
r = r * p2k % M
x >>= 1
p2k = p2k * p2k % M
return r
t, = rl()
for _ in range(t):
n, p = rl()
k = rl()
if p == 1:
print(n % 2)
continue
else:
k.sort(reverse=True)
multiplier = 1
i = 0
while i < n - 1:
if multiplier == 0:
multiplier = 1
elif multiplier > n:
break
else:
dk = k[i] - k[i+1]
if multiplier > 0 and dk >= 20: # p**20 > len(k)
break
multiplier = abs(multiplier * p ** dk - 1)
i += 1
r = multiplier * pow(p, k[i]) % M
for x in k[i+1:]:
r = (r - pow(p, x)) % M
print(r)
``` | output | 1 | 12,605 | 22 | 25,211 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems.
The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced.
Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7.
Input
Input consists of multiple test cases. The first line contains one integer t (1 β€ t β€ 10^5) β the number of test cases. Each test case is described as follows:
The first line contains two integers n and p (1 β€ n, p β€ 10^6). The second line contains n integers k_i (0 β€ k_i β€ 10^6).
The sum of n over all test cases doesn't exceed 10^6.
Output
Output one integer β the reminder of division the answer by 1 000 000 007.
Example
Input
4
5 2
2 3 4 4 3
3 1
2 10 1000
4 5
0 1 1 100
1 8
89
Output
4
1
146981438
747093407
Note
You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1.
In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. | instruction | 0 | 12,606 | 22 | 25,212 |
Tags: greedy, implementation, math, sortings
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default='z', func=lambda a, b: min(a, b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] <= key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
for ik in range(int(input())):
n,k=map(int,input().split())
l=list(map(int,input().split()))
l.sort()
#print(l)
ans1=pow(k,l[-1],mod1)
ans=pow(k,l[-1],1000000007)
ans2=pow(k,l[-1],17)
#print(ans)
for i in range(n-2,-1,-1):
if ans==0 and ans1==0 and ans2==0:
#print(111111111111111111111111111111111111111,i)
ans=pow(k,l[i],1000000007)
ans1 = pow(k, l[i], mod1)
ans2 = pow(k, l[i], 17)
else:
ans-=pow(k,l[i],1000000007)
ans%=10**9+7
ans2 -= pow(k, l[i], 17)
ans2 %= 17
ans1-= pow(k,l[i],mod1)
ans1%=mod1
print(ans)
``` | output | 1 | 12,606 | 22 | 25,213 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems.
The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced.
Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7.
Input
Input consists of multiple test cases. The first line contains one integer t (1 β€ t β€ 10^5) β the number of test cases. Each test case is described as follows:
The first line contains two integers n and p (1 β€ n, p β€ 10^6). The second line contains n integers k_i (0 β€ k_i β€ 10^6).
The sum of n over all test cases doesn't exceed 10^6.
Output
Output one integer β the reminder of division the answer by 1 000 000 007.
Example
Input
4
5 2
2 3 4 4 3
3 1
2 10 1000
4 5
0 1 1 100
1 8
89
Output
4
1
146981438
747093407
Note
You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1.
In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. | instruction | 0 | 12,607 | 22 | 25,214 |
Tags: greedy, implementation, math, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
for _ in range(int(input())):
n, p = map(int, input().split())
s = list(map(int, input().split()))
s.sort(reverse=True)
if p == 1:
print(n % 2)
continue
c = -1
ci = 0
for i, si in enumerate(s):
if c == -1:
c = si
ls = si
f = 1
ci = i
else:
d = ls - si
if d > 20: # 2 ** 20 > 1000000
break
elif d:
f *= p ** d
ls = si
f -= 1
if f > n:
break
if f == 0:
c = -1
if c != -1:
ans = pow(p, c, 1000000007)
for si in s[ci+1:]:
ans -= pow(p, si, 1000000007)
ans %= 1000000007
ans += 1000000007
else:
ans = 0
print(ans % 1000000007)
'''
1
6 2
0 4 4 4 4 6
'''
``` | output | 1 | 12,607 | 22 | 25,215 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems.
The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced.
Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7.
Input
Input consists of multiple test cases. The first line contains one integer t (1 β€ t β€ 10^5) β the number of test cases. Each test case is described as follows:
The first line contains two integers n and p (1 β€ n, p β€ 10^6). The second line contains n integers k_i (0 β€ k_i β€ 10^6).
The sum of n over all test cases doesn't exceed 10^6.
Output
Output one integer β the reminder of division the answer by 1 000 000 007.
Example
Input
4
5 2
2 3 4 4 3
3 1
2 10 1000
4 5
0 1 1 100
1 8
89
Output
4
1
146981438
747093407
Note
You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1.
In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. | instruction | 0 | 12,608 | 22 | 25,216 |
Tags: greedy, implementation, math, sortings
Correct Solution:
```
from sys import stdin, gettrace, stdout
from collections import defaultdict
if gettrace():
inputi = input
else:
def input():
return next(stdin)[:-1]
def inputi():
return stdin.buffer.readline()
def modInt(mod):
class ModInt:
def __init__(self, value):
self.value = value % mod
def __int__(self):
return self.value
def __eq__(self, other):
return self.value == other.value
def __hash__(self):
return hash(self.value)
def __add__(self, other):
return ModInt(self.value + int(other))
def __sub__(self, other):
return ModInt(self.value - int(other))
def __mul__(self, other):
return ModInt(self.value * int(other))
def __floordiv__(self, other):
return ModInt(self.value // int(other))
def __truediv__(self, other):
return ModInt(self.value * pow(int(other), mod - 2, mod))
def __pow__(self, exp):
return pow(self.value, int(exp), mod)
def __str__(self):
return str(self.value)
return ModInt
MOD = 1000000007
def main():
ModInt = modInt(MOD)
def solve():
n,p = map(int, inputi().split())
kk = [int(a) for a in inputi().split()]
if p == 1:
print(n%2)
return
kk.sort(reverse=True)
res = ModInt(0)
mp = ModInt(p)
v = 0
lk = kk[0]+1
mxe = 0
mxp = 1
while mxp < n:
mxp *= p
mxe += 1
i = len(kk)
for i in range(len(kk)):
k = kk[i]
if lk > k:
v *= p**(min(lk-k, mxe))
if v > n:
for k in kk[i:]:
res -= mp ** k
break
lk = k
if v == 0:
res += mp**k
v = 1
else:
res -= mp**k
if v <= n:
v -= 1
print(res)
q = int(inputi())
for _ in range(q):
solve()
if __name__ == "__main__":
main()
``` | output | 1 | 12,608 | 22 | 25,217 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems.
The boy has found an online judge with tasks divided by topics they cover. He has picked p^{k_i} problems from i-th category (p is his favorite number). He wants to solve them in two weeks (the patience condition is too hard for Johnny, so for simplicity, he looks only at easy tasks, which can be solved in such a period). Now our future grandmaster has to decide which topics to cover first and which the second week. Help him assign topics in such a way, that workload is balanced.
Formally, given n numbers p^{k_i}, the boy wants to divide them into two disjoint sets, minimizing the absolute difference between sums of numbers in each set. Find the minimal absolute difference. Output the result modulo 10^{9}+7.
Input
Input consists of multiple test cases. The first line contains one integer t (1 β€ t β€ 10^5) β the number of test cases. Each test case is described as follows:
The first line contains two integers n and p (1 β€ n, p β€ 10^6). The second line contains n integers k_i (0 β€ k_i β€ 10^6).
The sum of n over all test cases doesn't exceed 10^6.
Output
Output one integer β the reminder of division the answer by 1 000 000 007.
Example
Input
4
5 2
2 3 4 4 3
3 1
2 10 1000
4 5
0 1 1 100
1 8
89
Output
4
1
146981438
747093407
Note
You have to minimize the difference, not it's remainder. For example, if the minimum difference is equal to 2, but there is also a distribution where the difference is 10^9 + 8, then the answer is 2, not 1.
In the first test case of the example, there're the following numbers: 4, 8, 16, 16, and 8. We can divide them into such two sets: {4, 8, 16} and {8, 16}. Then the difference between the sums of numbers in sets would be 4. | instruction | 0 | 12,609 | 22 | 25,218 |
Tags: greedy, implementation, math, sortings
Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
T = int(input())
P = 10 ** 9 + 7
for _ in range(T):
N, b = map(int, input().split())
A = sorted([int(a) for a in input().split()])
if b == 1:
print(N % 2)
continue
a = A.pop()
pre = a
s = 1
ans = pow(b, a, P)
while A:
a = A.pop()
s *= b ** min(pre - a, 30)
if s >= len(A) + 5:
ans -= pow(b, a, P)
if ans < 0: ans += P
while A:
a = A.pop()
ans -= pow(b, a, P)
if ans < 0: ans += P
print(ans)
break
if s:
s -= 1
ans -= pow(b, a, P)
if ans < 0: ans += P
pre = a
else:
s = 1
ans = -ans
if ans < 0: ans += P
ans += pow(b, a, P)
if ans >= P: ans -= P
pre = a
else:
print(ans)
``` | output | 1 | 12,609 | 22 | 25,219 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a polyline going through points (0, 0) β (x, x) β (2x, 0) β (3x, x) β (4x, 0) β ... - (2kx, 0) β (2kx + x, x) β ....
We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x.
Input
Only one line containing two positive integers a and b (1 β€ a, b β€ 109).
Output
Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output - 1 as the answer.
Examples
Input
3 1
Output
1.000000000000
Input
1 3
Output
-1
Input
4 1
Output
1.250000000000
Note
You can see following graphs for sample 1 and sample 3.
<image> <image> | instruction | 0 | 12,891 | 22 | 25,782 |
Tags: geometry, math
Correct Solution:
```
import sys
a, b = list(map(int, sys.stdin.readline().split()))
if b > a :
print(-1)
elif b == a:
print(a)
else:
t = (a+b)/(2*int((a+b)/b/2))
print(t)
``` | output | 1 | 12,891 | 22 | 25,783 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a polyline going through points (0, 0) β (x, x) β (2x, 0) β (3x, x) β (4x, 0) β ... - (2kx, 0) β (2kx + x, x) β ....
We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x.
Input
Only one line containing two positive integers a and b (1 β€ a, b β€ 109).
Output
Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output - 1 as the answer.
Examples
Input
3 1
Output
1.000000000000
Input
1 3
Output
-1
Input
4 1
Output
1.250000000000
Note
You can see following graphs for sample 1 and sample 3.
<image> <image> | instruction | 0 | 12,892 | 22 | 25,784 |
Tags: geometry, math
Correct Solution:
```
a, b = map(int, input().split())
if a < b:
print(-1)
else:
print((a + b) / (2 * ((a + b) // (2 * b))))
``` | output | 1 | 12,892 | 22 | 25,785 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a polyline going through points (0, 0) β (x, x) β (2x, 0) β (3x, x) β (4x, 0) β ... - (2kx, 0) β (2kx + x, x) β ....
We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x.
Input
Only one line containing two positive integers a and b (1 β€ a, b β€ 109).
Output
Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output - 1 as the answer.
Examples
Input
3 1
Output
1.000000000000
Input
1 3
Output
-1
Input
4 1
Output
1.250000000000
Note
You can see following graphs for sample 1 and sample 3.
<image> <image> | instruction | 0 | 12,894 | 22 | 25,788 |
Tags: geometry, math
Correct Solution:
```
a,b = map(float,input().split(" "))
if a==b:
print(b)
elif a<b:
print(-1)
else:
n=(a-b)//b+1
if n%2==0:n-=1
if n>1:
x1=(a-b)/(n-1)
else: x1=999999999999999999
n=(a+b)//b-1
if n%2==0:n-=1
x2=(a+b)/(n+1)
print(min(x1,x2))
``` | output | 1 | 12,894 | 22 | 25,789 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a polyline going through points (0, 0) β (x, x) β (2x, 0) β (3x, x) β (4x, 0) β ... - (2kx, 0) β (2kx + x, x) β ....
We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x.
Input
Only one line containing two positive integers a and b (1 β€ a, b β€ 109).
Output
Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output - 1 as the answer.
Examples
Input
3 1
Output
1.000000000000
Input
1 3
Output
-1
Input
4 1
Output
1.250000000000
Note
You can see following graphs for sample 1 and sample 3.
<image> <image> | instruction | 0 | 12,895 | 22 | 25,790 |
Tags: geometry, math
Correct Solution:
```
from fractions import Fraction
def solve(a, b):
x = Fraction(b)
n = a // (x*2)
a_ = a % (x*2)
if b > a:
return -1
if a_ == x:
return float(x)
if a_ < x:
return float((a+b)/(2*n))
if a_ > x:
return float((a+b)/(2*n+2))
a, b = map(Fraction, input().split())
print(solve(a, b))
``` | output | 1 | 12,895 | 22 | 25,791 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a polyline going through points (0, 0) β (x, x) β (2x, 0) β (3x, x) β (4x, 0) β ... - (2kx, 0) β (2kx + x, x) β ....
We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x.
Input
Only one line containing two positive integers a and b (1 β€ a, b β€ 109).
Output
Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output - 1 as the answer.
Examples
Input
3 1
Output
1.000000000000
Input
1 3
Output
-1
Input
4 1
Output
1.250000000000
Note
You can see following graphs for sample 1 and sample 3.
<image> <image> | instruction | 0 | 12,896 | 22 | 25,792 |
Tags: geometry, math
Correct Solution:
```
def find(x,b):
if x/2//b>0: return x/2/(x/2//b)
else: return 10000000000
a,b=map(int,input().split())
if a==b: print("%.9f"%a)
elif b>a: print(-1)
else: print("%.9f"%min(find(a-b,b),find(a+b,b)))
``` | output | 1 | 12,896 | 22 | 25,793 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a polyline going through points (0, 0) β (x, x) β (2x, 0) β (3x, x) β (4x, 0) β ... - (2kx, 0) β (2kx + x, x) β ....
We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x.
Input
Only one line containing two positive integers a and b (1 β€ a, b β€ 109).
Output
Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output - 1 as the answer.
Examples
Input
3 1
Output
1.000000000000
Input
1 3
Output
-1
Input
4 1
Output
1.250000000000
Note
You can see following graphs for sample 1 and sample 3.
<image> <image> | instruction | 0 | 12,897 | 22 | 25,794 |
Tags: geometry, math
Correct Solution:
```
from math import floor
a, b = map(int, input().split())
if a < b:
print(-1)
else:
if floor((a-b)/(2*b)) == 0:
print((a+b)/(2*floor((a+b)/(2*b))))
else:
print(min((a-b)/(2*floor((a-b)/(2*b))), (a+b)/(2*floor((a+b)/(2*b)))))
``` | output | 1 | 12,897 | 22 | 25,795 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a polyline going through points (0, 0) β (x, x) β (2x, 0) β (3x, x) β (4x, 0) β ... - (2kx, 0) β (2kx + x, x) β ....
We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x.
Input
Only one line containing two positive integers a and b (1 β€ a, b β€ 109).
Output
Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output - 1 as the answer.
Examples
Input
3 1
Output
1.000000000000
Input
1 3
Output
-1
Input
4 1
Output
1.250000000000
Note
You can see following graphs for sample 1 and sample 3.
<image> <image> | instruction | 0 | 12,898 | 22 | 25,796 |
Tags: geometry, math
Correct Solution:
```
def main(a,b):
if b > a:
return(-1)
# ver1
k1 = (a - b) // (2*b)
if k1 > 0:
x1 = (a - b) / (2 * k1)
else:
x1 = 10**9
k2 = (a + b) // (2*b)
x2 = (a + b) / (2*k2)
return min(x1, x2)
a,b = list(map(int, input().split()))
print(main(a,b))
``` | output | 1 | 12,898 | 22 | 25,797 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.
Input
The first line contains two integers n, m (1 β€ n, m β€ 2Β·105) β the sizes of arrays a and b.
The second line contains n integers β the elements of array a ( - 109 β€ ai β€ 109).
The third line contains m integers β the elements of array b ( - 109 β€ bj β€ 109).
Output
Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.
Examples
Input
5 4
1 3 5 7 9
6 4 2 8
Output
3 2 1 4
Input
5 5
1 2 1 2 5
3 1 4 1 5
Output
4 2 4 2 5 | instruction | 0 | 12,910 | 22 | 25,820 |
Tags: binary search, data structures, sortings, two pointers
Correct Solution:
```
## necessary imports
import sys
import random
from math import log2, log, ceil
input = sys.stdin.readline
# swap_array function
def swaparr(arr, a,b):
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp
## gcd function
def gcd(a,b):
if a == 0:
return b
return gcd(b%a, a)
## prime factorization
def primefs(n):
## if n == 1 ## calculating primes
primes = {}
while(n%2 == 0):
primes[2] = primes.get(2, 0) + 1
n = n//2
for i in range(3, int(n**0.5)+2, 2):
while(n%i == 0):
primes[i] = primes.get(i, 0) + 1
n = n//i
if n > 2:
primes[n] = primes.get(n, 0) + 1
## prime factoriazation of n is stored in dictionary
## primes and can be accesed. O(sqrt n)
return primes
## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
temp = a
a = b
b = temp
return a,b
# find function
def find(x, link):
while(x != link[x]):
x = link[x]
return x
# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, size, link):
x = find(x, link)
y = find(y, link)
if size[x] < size[y]:
x,y = swap(x,y)
if x != y:
size[x] += size[y]
link[y] = x
## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e6 + 5)
def spf_sieve():
spf[1] = 1;
for i in range(2, MAXN):
spf[i] = i;
for i in range(4, MAXN, 2):
spf[i] = 2;
for i in range(3, ceil(MAXN ** 0.5), 2):
if spf[i] == i:
for j in range(i*i, MAXN, i):
if spf[j] == j:
spf[j] = i;
## function for storing smallest prime factors (spf) in the array
################## un-comment below 2 lines when using factorization #################
# spf = [0 for i in range(MAXN)]
# spf_sieve()
def factoriazation(x):
ret = {};
while x != 1:
ret[spf[x]] = ret.get(spf[x], 0) + 1;
x = x//spf[x]
return ret
## this function is useful for multiple queries only, o/w use
## primefs function above. complexity O(log n)
## taking integer array input
def int_array():
return list(map(int, input().split()))
#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');
################# ---------------- TEMPLATE ENDS HERE ---------------- #################
n, m = int_array(); a = int_array(); b = int_array();
for i in range(m):
b[i] = (b[i], i);
a.sort(); b.sort();
i = j = 0; ans = [];
while(i < n and j < m):
if a[i] <= b[j][0]:
i +=1;
else:
ans.append((b[j][1], i));
j += 1;
while (len(ans) < m):
ans.append((b[j][1], i));
j += 1;
ans.sort(); answer = [ans[i][1] for i in range(m)];
print(*answer)
``` | output | 1 | 12,910 | 22 | 25,821 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.
Input
The first line contains two integers n, m (1 β€ n, m β€ 2Β·105) β the sizes of arrays a and b.
The second line contains n integers β the elements of array a ( - 109 β€ ai β€ 109).
The third line contains m integers β the elements of array b ( - 109 β€ bj β€ 109).
Output
Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.
Examples
Input
5 4
1 3 5 7 9
6 4 2 8
Output
3 2 1 4
Input
5 5
1 2 1 2 5
3 1 4 1 5
Output
4 2 4 2 5
Submitted Solution:
```
## necessary imports
import sys
import random
from math import log2, log, ceil
input = sys.stdin.readline
# swap_array function
def swaparr(arr, a,b):
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp
## gcd function
def gcd(a,b):
if a == 0:
return b
return gcd(b%a, a)
## prime factorization
def primefs(n):
## if n == 1 ## calculating primes
primes = {}
while(n%2 == 0):
primes[2] = primes.get(2, 0) + 1
n = n//2
for i in range(3, int(n**0.5)+2, 2):
while(n%i == 0):
primes[i] = primes.get(i, 0) + 1
n = n//i
if n > 2:
primes[n] = primes.get(n, 0) + 1
## prime factoriazation of n is stored in dictionary
## primes and can be accesed. O(sqrt n)
return primes
## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
temp = a
a = b
b = temp
return a,b
# find function
def find(x, link):
while(x != link[x]):
x = link[x]
return x
# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, size, link):
x = find(x, link)
y = find(y, link)
if size[x] < size[y]:
x,y = swap(x,y)
if x != y:
size[x] += size[y]
link[y] = x
## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e6 + 5)
def spf_sieve():
spf[1] = 1;
for i in range(2, MAXN):
spf[i] = i;
for i in range(4, MAXN, 2):
spf[i] = 2;
for i in range(3, ceil(MAXN ** 0.5), 2):
if spf[i] == i:
for j in range(i*i, MAXN, i):
if spf[j] == j:
spf[j] = i;
## function for storing smallest prime factors (spf) in the array
################## un-comment below 2 lines when using factorization #################
# spf = [0 for i in range(MAXN)]
# spf_sieve()
def factoriazation(x):
ret = {};
while x != 1:
ret[spf[x]] = ret.get(spf[x], 0) + 1;
x = x//spf[x]
return ret
## this function is useful for multiple queries only, o/w use
## primefs function above. complexity O(log n)
## taking integer array input
def int_array():
return list(map(int, input().split()))
#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');
################# ---------------- TEMPLATE ENDS HERE ---------------- #################
n, m = int_array(); a = int_array(); b = int_array();
for i in range(m):
b[i] = (b[i], i);
a.sort(); b.sort();
i = j = 0; ans = [];
while(i < n and j < m):
if a[i] <= b[j][0]:
i +=1;
else:
ans.append((b[j][1], i));
j += 1;
while (len(ans) < m):
ans.append((b[j][1], i));
j = j+ 1;
ans.sort(); answer = [ans[i][1] for i in range(m)];
print(*answer)
``` | instruction | 0 | 12,915 | 22 | 25,830 |
Yes | output | 1 | 12,915 | 22 | 25,831 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Imp is watching a documentary about cave painting.
<image>
Some numbers, carved in chaotic order, immediately attracted his attention. Imp rapidly proposed a guess that they are the remainders of division of a number n by all integers i from 1 to k. Unfortunately, there are too many integers to analyze for Imp.
Imp wants you to check whether all these remainders are distinct. Formally, he wants to check, if all <image>, 1 β€ i β€ k, are distinct, i. e. there is no such pair (i, j) that:
* 1 β€ i < j β€ k,
* <image>, where <image> is the remainder of division x by y.
Input
The only line contains two integers n, k (1 β€ n, k β€ 1018).
Output
Print "Yes", if all the remainders are distinct, and "No" otherwise.
You can print each letter in arbitrary case (lower or upper).
Examples
Input
4 4
Output
No
Input
5 3
Output
Yes
Note
In the first sample remainders modulo 1 and 4 coincide. | instruction | 0 | 13,059 | 22 | 26,118 |
Tags: brute force, number theory
Correct Solution:
```
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
n, k = map(int, input().split())
cur = 1
if k >= 1e6:
print("NO")
exit()
for i in range(1, k+ 1):
cur = cur // gcd(cur, i) * i
if cur > n + 1:
print("No")
exit()
if (n + 1) % cur == 0:
print("Yes")
else:
print("No")
``` | output | 1 | 13,059 | 22 | 26,119 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Imp is watching a documentary about cave painting.
<image>
Some numbers, carved in chaotic order, immediately attracted his attention. Imp rapidly proposed a guess that they are the remainders of division of a number n by all integers i from 1 to k. Unfortunately, there are too many integers to analyze for Imp.
Imp wants you to check whether all these remainders are distinct. Formally, he wants to check, if all <image>, 1 β€ i β€ k, are distinct, i. e. there is no such pair (i, j) that:
* 1 β€ i < j β€ k,
* <image>, where <image> is the remainder of division x by y.
Input
The only line contains two integers n, k (1 β€ n, k β€ 1018).
Output
Print "Yes", if all the remainders are distinct, and "No" otherwise.
You can print each letter in arbitrary case (lower or upper).
Examples
Input
4 4
Output
No
Input
5 3
Output
Yes
Note
In the first sample remainders modulo 1 and 4 coincide. | instruction | 0 | 13,060 | 22 | 26,120 |
Tags: brute force, number theory
Correct Solution:
```
n, k = [int(x) for x in input().split()]
ost = set()
i = 1
f = True
while i <= k:
if n % i not in ost:
ost.add(n % i)
i += 1
else:
f = False
break
if f:
print("Yes")
else:
print("No")
``` | output | 1 | 13,060 | 22 | 26,121 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Imp is watching a documentary about cave painting.
<image>
Some numbers, carved in chaotic order, immediately attracted his attention. Imp rapidly proposed a guess that they are the remainders of division of a number n by all integers i from 1 to k. Unfortunately, there are too many integers to analyze for Imp.
Imp wants you to check whether all these remainders are distinct. Formally, he wants to check, if all <image>, 1 β€ i β€ k, are distinct, i. e. there is no such pair (i, j) that:
* 1 β€ i < j β€ k,
* <image>, where <image> is the remainder of division x by y.
Input
The only line contains two integers n, k (1 β€ n, k β€ 1018).
Output
Print "Yes", if all the remainders are distinct, and "No" otherwise.
You can print each letter in arbitrary case (lower or upper).
Examples
Input
4 4
Output
No
Input
5 3
Output
Yes
Note
In the first sample remainders modulo 1 and 4 coincide. | instruction | 0 | 13,061 | 22 | 26,122 |
Tags: brute force, number theory
Correct Solution:
```
# IAWT
n, k = list(map(int, input().split()))
ps = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]
def LCM():
lcm = 1
for p in ps:
max_p = 0
while p ** max_p <= k: max_p += 1
max_p -= 1
lcm *= p ** max_p
if lcm > 10**18: return -1
return lcm
def f():
if k > 200: return False
for i in range(2, k+1):
if n % i != i-1: return False
return True
if f(): print('Yes')
else: print('No')
``` | output | 1 | 13,061 | 22 | 26,123 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.