text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:
1. Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.
2. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 β€ i β€ n).
3. Take a piece of paper and write out the qi-th array element. That is, the element aqi.
Help Sereja, complete all his operations.
Input
The first line contains integers n, m (1 β€ n, m β€ 105). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β the original array.
Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 β€ ti β€ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 β€ vi β€ n, 1 β€ xi β€ 109). If ti = 2, then it is followed by integer yi (1 β€ yi β€ 104). And if ti = 3, then it is followed by integer qi (1 β€ qi β€ n).
Output
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
Examples
Input
10 11
1 2 3 4 5 6 7 8 9 10
3 2
3 9
2 10
3 1
3 10
1 1 10
2 10
2 10
3 1
3 10
3 9
Output
2
9
11
20
30
40
39
Tags: implementation
Correct Solution:
```
n,m=input().split()
a=input().split()
soma=0
dic ={}
total=0
for x in range(int(m)):
b=input().split()
v=int(b[1])
if(b[0]=="1"):
b[2]=int(b[2])
a[v-1]=b[2]
dic[v] = soma
elif(b[0]=="2"):
soma=soma+v
elif(b[0]=="3"):
if v in dic:
total =soma-dic[v]
print(int(a[v-1])+ total)
else:
print(int(a[v-1]) + soma)
```
| 13,600 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:
1. Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.
2. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 β€ i β€ n).
3. Take a piece of paper and write out the qi-th array element. That is, the element aqi.
Help Sereja, complete all his operations.
Input
The first line contains integers n, m (1 β€ n, m β€ 105). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β the original array.
Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 β€ ti β€ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 β€ vi β€ n, 1 β€ xi β€ 109). If ti = 2, then it is followed by integer yi (1 β€ yi β€ 104). And if ti = 3, then it is followed by integer qi (1 β€ qi β€ n).
Output
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
Examples
Input
10 11
1 2 3 4 5 6 7 8 9 10
3 2
3 9
2 10
3 1
3 10
1 1 10
2 10
2 10
3 1
3 10
3 9
Output
2
9
11
20
30
40
39
Tags: implementation
Correct Solution:
```
import sys
import itertools
import collections
def rs(x=''): return sys.stdin.readline().strip() if len(x) == 0 else input(x).strip()
def ri(x=''): return int(rs(x))
def rm(x=''): return map(str, rs(x).split())
def rl(x=''): return rs(x).split()
def rmi(x=''): return map(int, rs(x).split())
def rli(x=''): return [int(x) for x in rs(x).split()]
def println(val): sys.stdout.write(str(val) + '\n')
def solve(testCase):
n, m = rmi()
a = rli()
queries = [tuple(rmi()) for _ in range(m)]
add = 0
mark = [0] * n
inc = 0
for t, *operation in queries:
if t == 1:
vi, x = operation
vi -= 1
a[vi] = x
mark[vi] = -add
elif t == 2:
y = operation[0]
add += y
inc += 1
elif t == 3:
idx = operation[0]
idx -= 1
# print('!', add, a[idx], mark[idx])
print(add + a[idx] + mark[idx])
for _ in range(ri() if 0 else 1):
solve(_ + 1)
```
| 13,601 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:
1. Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.
2. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 β€ i β€ n).
3. Take a piece of paper and write out the qi-th array element. That is, the element aqi.
Help Sereja, complete all his operations.
Input
The first line contains integers n, m (1 β€ n, m β€ 105). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β the original array.
Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 β€ ti β€ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 β€ vi β€ n, 1 β€ xi β€ 109). If ti = 2, then it is followed by integer yi (1 β€ yi β€ 104). And if ti = 3, then it is followed by integer qi (1 β€ qi β€ n).
Output
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
Examples
Input
10 11
1 2 3 4 5 6 7 8 9 10
3 2
3 9
2 10
3 1
3 10
1 1 10
2 10
2 10
3 1
3 10
3 9
Output
2
9
11
20
30
40
39
Tags: implementation
Correct Solution:
```
n,m=map(int,input().split())
l=[int(x) for x in input().split()]
curr=0
for _ in range(m):
temp=input().split()
if temp[0]=="1":
x=int(temp[1])
y=int(temp[2])
l[x-1]=y
l[x-1]=l[x-1]-curr
elif temp[0]=="2":
curr+=int(temp[1])
else:
x=int(temp[1])
print(l[x-1]+curr)
```
| 13,602 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:
1. Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.
2. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 β€ i β€ n).
3. Take a piece of paper and write out the qi-th array element. That is, the element aqi.
Help Sereja, complete all his operations.
Input
The first line contains integers n, m (1 β€ n, m β€ 105). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β the original array.
Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 β€ ti β€ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 β€ vi β€ n, 1 β€ xi β€ 109). If ti = 2, then it is followed by integer yi (1 β€ yi β€ 104). And if ti = 3, then it is followed by integer qi (1 β€ qi β€ n).
Output
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
Examples
Input
10 11
1 2 3 4 5 6 7 8 9 10
3 2
3 9
2 10
3 1
3 10
1 1 10
2 10
2 10
3 1
3 10
3 9
Output
2
9
11
20
30
40
39
Tags: implementation
Correct Solution:
```
n, m = map(int, input().split())
arr = [int(i) for i in input().split()]
res, s = 0, ""
for i in range(m):
b = [int(x) for x in input().split()]
if b[0] == 1:
arr[b[1] - 1] = b[2] - res
elif b[0] == 2:
res += b[1]
else:
s += str(arr[b[1] - 1] + res) + '\n'
print(s)
```
| 13,603 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:
1. Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.
2. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 β€ i β€ n).
3. Take a piece of paper and write out the qi-th array element. That is, the element aqi.
Help Sereja, complete all his operations.
Input
The first line contains integers n, m (1 β€ n, m β€ 105). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β the original array.
Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 β€ ti β€ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 β€ vi β€ n, 1 β€ xi β€ 109). If ti = 2, then it is followed by integer yi (1 β€ yi β€ 104). And if ti = 3, then it is followed by integer qi (1 β€ qi β€ n).
Output
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
Examples
Input
10 11
1 2 3 4 5 6 7 8 9 10
3 2
3 9
2 10
3 1
3 10
1 1 10
2 10
2 10
3 1
3 10
3 9
Output
2
9
11
20
30
40
39
Tags: implementation
Correct Solution:
```
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
#from bisect import bisect_left as bl #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br #c++ upperbound br(array,element)
def main():
n,m=map(int,input().split(" "))
a=list(map(int,input().split(" ")))
op=[0 for x in range(n)]
cur=0
for x in range(m):
temp=list(map(int,input().split(" ")))
if temp[0]==1:
a[temp[1]-1]=temp[2]
op[temp[1]-1]=-cur
elif temp[0]==2:
cur+=temp[1]
else:
print(a[temp[1]-1]+op[temp[1]-1]+cur)
#-----------------------------BOSS-------------------------------------!
# 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()
```
| 13,604 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:
1. Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.
2. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 β€ i β€ n).
3. Take a piece of paper and write out the qi-th array element. That is, the element aqi.
Help Sereja, complete all his operations.
Input
The first line contains integers n, m (1 β€ n, m β€ 105). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β the original array.
Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 β€ ti β€ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 β€ vi β€ n, 1 β€ xi β€ 109). If ti = 2, then it is followed by integer yi (1 β€ yi β€ 104). And if ti = 3, then it is followed by integer qi (1 β€ qi β€ n).
Output
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
Examples
Input
10 11
1 2 3 4 5 6 7 8 9 10
3 2
3 9
2 10
3 1
3 10
1 1 10
2 10
2 10
3 1
3 10
3 9
Output
2
9
11
20
30
40
39
Tags: implementation
Correct Solution:
```
"""
n=int(z())
for _ in range(int(z())):
x=int(z())
l=list(map(int,z().split()))
n=int(z())
l=sorted(list(map(int,z().split())))[::-1]
a,b=map(int,z().split())
l=set(map(int,z().split()))
led=(6,2,5,5,4,5,6,3,7,6)
vowel={'a':0,'e':0,'i':0,'o':0,'u':0}
color4=["G", "GB", "YGB", "YGBI", "OYGBI" ,"OYGBIV",'ROYGBIV' ]
"""
#!/usr/bin/env python
#pyrival orz
import os
import sys
from io import BytesIO, IOBase
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
def main():
try:
n, m = invr()
a = inlt()
s = 0
for _ in range(m):
t = inlt()
if t[0] == 1:
a[t[1]-1] = t[2] - s
elif t[0] == 2:
s += t[1]
else:
print(a[t[1]-1] + s)
except Exception as e:
print(e)
# 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()
```
| 13,605 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:
1. Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.
2. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 β€ i β€ n).
3. Take a piece of paper and write out the qi-th array element. That is, the element aqi.
Help Sereja, complete all his operations.
Input
The first line contains integers n, m (1 β€ n, m β€ 105). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β the original array.
Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 β€ ti β€ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 β€ vi β€ n, 1 β€ xi β€ 109). If ti = 2, then it is followed by integer yi (1 β€ yi β€ 104). And if ti = 3, then it is followed by integer qi (1 β€ qi β€ n).
Output
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
Examples
Input
10 11
1 2 3 4 5 6 7 8 9 10
3 2
3 9
2 10
3 1
3 10
1 1 10
2 10
2 10
3 1
3 10
3 9
Output
2
9
11
20
30
40
39
Tags: implementation
Correct Solution:
```
from sys import stdin, stdout
m=int(input().split()[1])
a=[int(x) for x in stdin.readline().split()]
s,o=0,''
for i in range(m):
x=[int(x) for x in stdin.readline().split()]
if x[0]==1:
a[x[1]-1]=x[2]-s
elif x[0]==2:
s+=x[1]
else:
o+=str(a[x[1]-1]+s)+'\n'
stdout.write(o)
```
| 13,606 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:
1. Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.
2. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 β€ i β€ n).
3. Take a piece of paper and write out the qi-th array element. That is, the element aqi.
Help Sereja, complete all his operations.
Input
The first line contains integers n, m (1 β€ n, m β€ 105). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β the original array.
Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 β€ ti β€ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 β€ vi β€ n, 1 β€ xi β€ 109). If ti = 2, then it is followed by integer yi (1 β€ yi β€ 104). And if ti = 3, then it is followed by integer qi (1 β€ qi β€ n).
Output
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
Examples
Input
10 11
1 2 3 4 5 6 7 8 9 10
3 2
3 9
2 10
3 1
3 10
1 1 10
2 10
2 10
3 1
3 10
3 9
Output
2
9
11
20
30
40
39
Submitted Solution:
```
n,m = [int(x) for x in input().split()]
arr = [int(x) for x in input().split()]
query = []
for _ in range(m):
query.append([int(x) for x in input().split()])
add = [0 for i in range(n)]
netadd = 0
for q in query:
t = q[0]
v = q[1]
x = 0
if len(q) == 3:
x = q[2]
if t == 3:
print(arr[v -1]+netadd - add[v-1])
elif t == 2:
netadd += v
else:
arr[v-1] = x
add[v-1] = netadd
```
Yes
| 13,607 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:
1. Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.
2. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 β€ i β€ n).
3. Take a piece of paper and write out the qi-th array element. That is, the element aqi.
Help Sereja, complete all his operations.
Input
The first line contains integers n, m (1 β€ n, m β€ 105). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β the original array.
Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 β€ ti β€ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 β€ vi β€ n, 1 β€ xi β€ 109). If ti = 2, then it is followed by integer yi (1 β€ yi β€ 104). And if ti = 3, then it is followed by integer qi (1 β€ qi β€ n).
Output
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
Examples
Input
10 11
1 2 3 4 5 6 7 8 9 10
3 2
3 9
2 10
3 1
3 10
1 1 10
2 10
2 10
3 1
3 10
3 9
Output
2
9
11
20
30
40
39
Submitted Solution:
```
#python3
import sys, threading, os.path
import collections, heapq, math,bisect
import string
from platform import python_version
import itertools
sys.setrecursionlimit(10**6)
threading.stack_size(2**27)
def main():
if os.path.exists('input.txt'):
input = open('input.txt', 'r')
else:
input = sys.stdin
#--------------------------------INPUT---------------------------------
n,m = list(map(int, input.readline().split()))
lis = list(map(int, input.readline().split()))
sumall = 0
sol=[]
for i in range(m):
temlis = list(map(int, input.readline().split()))
#print(temlis)
if temlis[0]==1:
lis[temlis[1]-1]=temlis[2]-sumall
elif temlis[0]==2:
sumall+=temlis[1]
elif temlis[0]==3:
sol.append(lis[temlis[1]-1]+sumall)
#print(lis,sumall)
output = '\n'.join(map(str, sol))
#-------------------------------OUTPUT----------------------------------
if os.path.exists('output.txt'):
open('output.txt', 'w').writelines(str(output))
else:
sys.stdout.write(str(output))
if __name__ == '__main__':
main()
#threading.Thread(target=main).start()
```
Yes
| 13,608 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:
1. Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.
2. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 β€ i β€ n).
3. Take a piece of paper and write out the qi-th array element. That is, the element aqi.
Help Sereja, complete all his operations.
Input
The first line contains integers n, m (1 β€ n, m β€ 105). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β the original array.
Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 β€ ti β€ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 β€ vi β€ n, 1 β€ xi β€ 109). If ti = 2, then it is followed by integer yi (1 β€ yi β€ 104). And if ti = 3, then it is followed by integer qi (1 β€ qi β€ n).
Output
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
Examples
Input
10 11
1 2 3 4 5 6 7 8 9 10
3 2
3 9
2 10
3 1
3 10
1 1 10
2 10
2 10
3 1
3 10
3 9
Output
2
9
11
20
30
40
39
Submitted Solution:
```
n , m = map(int, input().split())
l = list(map(int, input().split()))
tmp,s = 0,""
for i in range(m):
op = list(map(int, input().split()))
if op[0] == 1:
l[op[1]-1] = op[-1] - tmp
elif op[0] == 2 :
tmp += op[-1]
else:
s+=f"{l[op[-1]-1]+tmp}\n"
print(s)
```
Yes
| 13,609 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:
1. Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.
2. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 β€ i β€ n).
3. Take a piece of paper and write out the qi-th array element. That is, the element aqi.
Help Sereja, complete all his operations.
Input
The first line contains integers n, m (1 β€ n, m β€ 105). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β the original array.
Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 β€ ti β€ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 β€ vi β€ n, 1 β€ xi β€ 109). If ti = 2, then it is followed by integer yi (1 β€ yi β€ 104). And if ti = 3, then it is followed by integer qi (1 β€ qi β€ n).
Output
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
Examples
Input
10 11
1 2 3 4 5 6 7 8 9 10
3 2
3 9
2 10
3 1
3 10
1 1 10
2 10
2 10
3 1
3 10
3 9
Output
2
9
11
20
30
40
39
Submitted Solution:
```
n, m = [int(x) for x in input().split()]
lista = [int(x) for x in input().split()]
soma = 0
dic = {}
for i in range(m):
entrada = input().split()
a = entrada[0]
b = int(entrada[1])
if a == "1":
lista[b-1] = int(entrada[2])
dic[b] = soma
elif a == "2":
soma += b
elif a == "3":
if b in dic:
total = soma - dic[b]
print(lista[b-1] + total)
else:
print(lista[b-1] + soma)
```
Yes
| 13,610 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:
1. Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.
2. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 β€ i β€ n).
3. Take a piece of paper and write out the qi-th array element. That is, the element aqi.
Help Sereja, complete all his operations.
Input
The first line contains integers n, m (1 β€ n, m β€ 105). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β the original array.
Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 β€ ti β€ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 β€ vi β€ n, 1 β€ xi β€ 109). If ti = 2, then it is followed by integer yi (1 β€ yi β€ 104). And if ti = 3, then it is followed by integer qi (1 β€ qi β€ n).
Output
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
Examples
Input
10 11
1 2 3 4 5 6 7 8 9 10
3 2
3 9
2 10
3 1
3 10
1 1 10
2 10
2 10
3 1
3 10
3 9
Output
2
9
11
20
30
40
39
Submitted Solution:
```
n,m = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
soma = 0
for mm in range(m):
entrada = [int(x) for x in input().split()]
op = entrada[0]
b = int(entrada[1])
if op == "1":
a[b-1] = int(entrada[2]) - soma
elif op == "2":
soma += b
else:
print(a[b-1] + soma)
```
No
| 13,611 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:
1. Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.
2. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 β€ i β€ n).
3. Take a piece of paper and write out the qi-th array element. That is, the element aqi.
Help Sereja, complete all his operations.
Input
The first line contains integers n, m (1 β€ n, m β€ 105). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β the original array.
Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 β€ ti β€ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 β€ vi β€ n, 1 β€ xi β€ 109). If ti = 2, then it is followed by integer yi (1 β€ yi β€ 104). And if ti = 3, then it is followed by integer qi (1 β€ qi β€ n).
Output
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
Examples
Input
10 11
1 2 3 4 5 6 7 8 9 10
3 2
3 9
2 10
3 1
3 10
1 1 10
2 10
2 10
3 1
3 10
3 9
Output
2
9
11
20
30
40
39
Submitted Solution:
```
n, m = map(int, input().split())
a = [0] + list(map(int, input().split()))
S = 0
for i in range(m):
q = list(map(int, input().split()))
if q[0] == 3: print(a[q[1]] + S)
if q[0] == 2: S += q[1]
if q[0] == 1: a[q[1]] += q[2]
```
No
| 13,612 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:
1. Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.
2. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 β€ i β€ n).
3. Take a piece of paper and write out the qi-th array element. That is, the element aqi.
Help Sereja, complete all his operations.
Input
The first line contains integers n, m (1 β€ n, m β€ 105). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β the original array.
Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 β€ ti β€ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 β€ vi β€ n, 1 β€ xi β€ 109). If ti = 2, then it is followed by integer yi (1 β€ yi β€ 104). And if ti = 3, then it is followed by integer qi (1 β€ qi β€ n).
Output
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
Examples
Input
10 11
1 2 3 4 5 6 7 8 9 10
3 2
3 9
2 10
3 1
3 10
1 1 10
2 10
2 10
3 1
3 10
3 9
Output
2
9
11
20
30
40
39
Submitted Solution:
```
n, m = map(int, input().split())
numbers = list(map(int, input().split()))
copy = [0] * n
results = []
accumulator = 0
for i in range(m):
inputs = input().split()
if inputs[0] == "3":
results.append(numbers[int(inputs[1])-1] + accumulator + copy[int(inputs[1])-1])
elif inputs[0] == "2":
accumulator += int(inputs[1])
else:
copy[int(inputs[1]) - 1] -= accumulator
numbers[int(inputs[1]) - 1] = int(inputs[2])
print(*results, sep="\n")
```
No
| 13,613 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:
1. Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.
2. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 β€ i β€ n).
3. Take a piece of paper and write out the qi-th array element. That is, the element aqi.
Help Sereja, complete all his operations.
Input
The first line contains integers n, m (1 β€ n, m β€ 105). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β the original array.
Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 β€ ti β€ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 β€ vi β€ n, 1 β€ xi β€ 109). If ti = 2, then it is followed by integer yi (1 β€ yi β€ 104). And if ti = 3, then it is followed by integer qi (1 β€ qi β€ n).
Output
For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.
Examples
Input
10 11
1 2 3 4 5 6 7 8 9 10
3 2
3 9
2 10
3 1
3 10
1 1 10
2 10
2 10
3 1
3 10
3 9
Output
2
9
11
20
30
40
39
Submitted Solution:
```
x,k = input().split()
x = int(x)
k = int(k)
a = list(map(int,input().split()))
for i in range(k):
y = list(map(int,input().split()))
if(y[0] == 1):
a[y[1]] = y[2]
elif(y[0] == 2):
for j in range(x):
a[j] += y[1]
else:
print(a[y[1]-1])
```
No
| 13,614 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Paladin Manao caught the trail of the ancient Book of Evil in a swampy area. This area contains n settlements numbered from 1 to n. Moving through the swamp is very difficult, so people tramped exactly n - 1 paths. Each of these paths connects some pair of settlements and is bidirectional. Moreover, it is possible to reach any settlement from any other one by traversing one or several paths.
The distance between two settlements is the minimum number of paths that have to be crossed to get from one settlement to the other one. Manao knows that the Book of Evil has got a damage range d. This means that if the Book of Evil is located in some settlement, its damage (for example, emergence of ghosts and werewolves) affects other settlements at distance d or less from the settlement where the Book resides.
Manao has heard of m settlements affected by the Book of Evil. Their numbers are p1, p2, ..., pm. Note that the Book may be affecting other settlements as well, but this has not been detected yet. Manao wants to determine which settlements may contain the Book. Help him with this difficult task.
Input
The first line contains three space-separated integers n, m and d (1 β€ m β€ n β€ 100000; 0 β€ d β€ n - 1). The second line contains m distinct space-separated integers p1, p2, ..., pm (1 β€ pi β€ n). Then n - 1 lines follow, each line describes a path made in the area. A path is described by a pair of space-separated integers ai and bi representing the ends of this path.
Output
Print a single number β the number of settlements that may contain the Book of Evil. It is possible that Manao received some controversial information and there is no settlement that may contain the Book. In such case, print 0.
Examples
Input
6 2 3
1 2
1 5
2 3
3 4
4 5
5 6
Output
3
Note
Sample 1. The damage range of the Book of Evil equals 3 and its effects have been noticed in settlements 1 and 2. Thus, it can be in settlements 3, 4 or 5.
<image>
Tags: dfs and similar, divide and conquer, dp, trees
Correct Solution:
```
from collections import defaultdict
import sys
input=sys.stdin.readline
class graph:
def __init__(self,n,mark):
self.d=defaultdict(list)
self.n=n
self.mark=mark
def add(self,s,d):
self.d[s].append(d)
self.d[d].append(s)
def bfs(self,s,dis):
marked=s
visited=[False]*self.n
visited[s]=True
q=[s]
while q:
s=q.pop(0)
if(s in mark):
marked=s
for i in self.d[s]:
if(visited[i]==False):
q.append(i)
visited[i]=True
dis[i]+=dis[s]+1
return marked
n,m,k=map(int,input().split())
mrk=[int(x) for x in input().split()]
mark={}
for i in mrk:
mark[i-1]=1
g=graph(n,mark)
for i in range(n-1):
a,b=map(int,input().split())
g.add(a-1,b-1)
dis=[0]*n
u=g.bfs(0,dis)
dis=[0]*n
d=g.bfs(u,dis)
#print(dis)
temp=[0]*n
x=g.bfs(d,temp)
#print(temp)
count=0
for i in range(n):
if(temp[i]<=k and dis[i]<=k):
count+=1
print(count)
```
| 13,615 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Paladin Manao caught the trail of the ancient Book of Evil in a swampy area. This area contains n settlements numbered from 1 to n. Moving through the swamp is very difficult, so people tramped exactly n - 1 paths. Each of these paths connects some pair of settlements and is bidirectional. Moreover, it is possible to reach any settlement from any other one by traversing one or several paths.
The distance between two settlements is the minimum number of paths that have to be crossed to get from one settlement to the other one. Manao knows that the Book of Evil has got a damage range d. This means that if the Book of Evil is located in some settlement, its damage (for example, emergence of ghosts and werewolves) affects other settlements at distance d or less from the settlement where the Book resides.
Manao has heard of m settlements affected by the Book of Evil. Their numbers are p1, p2, ..., pm. Note that the Book may be affecting other settlements as well, but this has not been detected yet. Manao wants to determine which settlements may contain the Book. Help him with this difficult task.
Input
The first line contains three space-separated integers n, m and d (1 β€ m β€ n β€ 100000; 0 β€ d β€ n - 1). The second line contains m distinct space-separated integers p1, p2, ..., pm (1 β€ pi β€ n). Then n - 1 lines follow, each line describes a path made in the area. A path is described by a pair of space-separated integers ai and bi representing the ends of this path.
Output
Print a single number β the number of settlements that may contain the Book of Evil. It is possible that Manao received some controversial information and there is no settlement that may contain the Book. In such case, print 0.
Examples
Input
6 2 3
1 2
1 5
2 3
3 4
4 5
5 6
Output
3
Note
Sample 1. The damage range of the Book of Evil equals 3 and its effects have been noticed in settlements 1 and 2. Thus, it can be in settlements 3, 4 or 5.
<image>
Tags: dfs and similar, divide and conquer, dp, trees
Correct Solution:
```
import heapq
def dfs(graph, start):
n = len(graph)
dist = [-0 for i in range(n + 1)]
visited = [False for i in range(n + 1)]
visited[start] = True
stack = []
dist[start] = 0
heapq.heappush(stack, start)
while stack:
u = heapq.heappop(stack)
for v in graph[u]:
if not visited[v]:
visited[v] = True
dist[v] = dist[u] + 1
heapq.heappush(stack, v)
return dist
def solution():
n, m, d = map(int, input().strip().split())
p = list(map(int, input().strip().split()))
graph = [[] for i in range(n + 1)]
for i in range(n - 1):
a, b = map(int, input().strip().split())
graph[a].append(b)
graph[b].append(a)
dist = dfs(graph, 1)
max_distance = -1
u = -1
v = -1
for i in p:
if dist[i] > max_distance:
max_distance = dist[i]
u = i
distu = dfs(graph, u)
max_distance = -1
for i in p:
if distu[i] > max_distance:
max_distance = distu[i]
v = i
distv = dfs(graph, v)
affected = 0
for i in range(1, n + 1):
if 0 <= distu[i] <= d and 0 <= distv[i] <= d:
affected += 1
print(affected)
solution()
```
| 13,616 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Levko loves array a1, a2, ... , an, consisting of integers, very much. That is why Levko is playing with array a, performing all sorts of operations with it. Each operation Levko performs is of one of two types:
1. Increase all elements from li to ri by di. In other words, perform assignments aj = aj + di for all j that meet the inequation li β€ j β€ ri.
2. Find the maximum of elements from li to ri. That is, calculate the value <image>.
Sadly, Levko has recently lost his array. Fortunately, Levko has records of all operations he has performed on array a. Help Levko, given the operation records, find at least one suitable array. The results of all operations for the given array must coincide with the record results. Levko clearly remembers that all numbers in his array didn't exceed 109 in their absolute value, so he asks you to find such an array.
Input
The first line contains two integers n and m (1 β€ n, m β€ 5000) β the size of the array and the number of operations in Levko's records, correspondingly.
Next m lines describe the operations, the i-th line describes the i-th operation. The first integer in the i-th line is integer ti (1 β€ ti β€ 2) that describes the operation type. If ti = 1, then it is followed by three integers li, ri and di (1 β€ li β€ ri β€ n, - 104 β€ di β€ 104) β the description of the operation of the first type. If ti = 2, then it is followed by three integers li, ri and mi (1 β€ li β€ ri β€ n, - 5Β·107 β€ mi β€ 5Β·107) β the description of the operation of the second type.
The operations are given in the order Levko performed them on his array.
Output
In the first line print "YES" (without the quotes), if the solution exists and "NO" (without the quotes) otherwise.
If the solution exists, then on the second line print n integers a1, a2, ... , an (|ai| β€ 109) β the recovered array.
Examples
Input
4 5
1 2 3 1
2 1 2 8
2 3 4 7
1 1 3 3
2 3 4 8
Output
YES
4 7 4 7
Input
4 5
1 2 3 1
2 1 2 8
2 3 4 7
1 1 3 3
2 3 4 13
Output
NO
Tags: greedy, implementation
Correct Solution:
```
n, m = map(int, input().split())
a = [int(1e9)] * n
extra = [0] * n
query = list()
for _ in range(m):
t, l, r, x = map(int, input().split())
l -= 1
r -= 1
query.append((t, l, r, x))
if t == 1:
for j in range(l, r+1):
extra[j] += x
else:
for j in range(l, r+1):
a[j] = min(a[j], x - extra[j])
extra = a[:]
for t, l, r, x in query:
if t == 1:
for j in range(l, r+1):
a[j] += x
else:
val = -10**9
for j in range(l, r+1):
val = max(val, a[j])
if not val == x:
print('NO')
exit()
print('YES')
print(*extra)
```
| 13,617 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Levko loves array a1, a2, ... , an, consisting of integers, very much. That is why Levko is playing with array a, performing all sorts of operations with it. Each operation Levko performs is of one of two types:
1. Increase all elements from li to ri by di. In other words, perform assignments aj = aj + di for all j that meet the inequation li β€ j β€ ri.
2. Find the maximum of elements from li to ri. That is, calculate the value <image>.
Sadly, Levko has recently lost his array. Fortunately, Levko has records of all operations he has performed on array a. Help Levko, given the operation records, find at least one suitable array. The results of all operations for the given array must coincide with the record results. Levko clearly remembers that all numbers in his array didn't exceed 109 in their absolute value, so he asks you to find such an array.
Input
The first line contains two integers n and m (1 β€ n, m β€ 5000) β the size of the array and the number of operations in Levko's records, correspondingly.
Next m lines describe the operations, the i-th line describes the i-th operation. The first integer in the i-th line is integer ti (1 β€ ti β€ 2) that describes the operation type. If ti = 1, then it is followed by three integers li, ri and di (1 β€ li β€ ri β€ n, - 104 β€ di β€ 104) β the description of the operation of the first type. If ti = 2, then it is followed by three integers li, ri and mi (1 β€ li β€ ri β€ n, - 5Β·107 β€ mi β€ 5Β·107) β the description of the operation of the second type.
The operations are given in the order Levko performed them on his array.
Output
In the first line print "YES" (without the quotes), if the solution exists and "NO" (without the quotes) otherwise.
If the solution exists, then on the second line print n integers a1, a2, ... , an (|ai| β€ 109) β the recovered array.
Examples
Input
4 5
1 2 3 1
2 1 2 8
2 3 4 7
1 1 3 3
2 3 4 8
Output
YES
4 7 4 7
Input
4 5
1 2 3 1
2 1 2 8
2 3 4 7
1 1 3 3
2 3 4 13
Output
NO
Tags: greedy, implementation
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 18
MOD = 10**9+7
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
n,m = Ri()
lis = []
for i in range(m):
lis.append(Ri())
ans = [10**9]*n
for i in range(m-1,-1,-1):
if lis[i][0] == 2:
for j in range(lis[i][1]-1,lis[i][2]):
ans[j] = min(ans[j], lis[i][3])
else:
for j in range(lis[i][1]-1,lis[i][2]):
if ans[j] != 10**9:
ans[j]-=lis[i][3]
for i in range(n):
if ans[i] == 10**9:
ans[i] = -10**9
temp = ans[:]
# print(temp)
flag = True
for i in range(m):
if lis[i][0] == 2:
t= -10**9
for j in range(lis[i][1]-1,lis[i][2]):
t = max(t, temp[j])
if t != lis[i][3]:
flag = False
break
else:
for j in range(lis[i][1]-1,lis[i][2]):
temp[j]+=lis[i][3]
# print(temp, ans)
if flag :
YES()
print(*ans)
else:
NO()
# print(-1)
```
| 13,618 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Levko loves array a1, a2, ... , an, consisting of integers, very much. That is why Levko is playing with array a, performing all sorts of operations with it. Each operation Levko performs is of one of two types:
1. Increase all elements from li to ri by di. In other words, perform assignments aj = aj + di for all j that meet the inequation li β€ j β€ ri.
2. Find the maximum of elements from li to ri. That is, calculate the value <image>.
Sadly, Levko has recently lost his array. Fortunately, Levko has records of all operations he has performed on array a. Help Levko, given the operation records, find at least one suitable array. The results of all operations for the given array must coincide with the record results. Levko clearly remembers that all numbers in his array didn't exceed 109 in their absolute value, so he asks you to find such an array.
Input
The first line contains two integers n and m (1 β€ n, m β€ 5000) β the size of the array and the number of operations in Levko's records, correspondingly.
Next m lines describe the operations, the i-th line describes the i-th operation. The first integer in the i-th line is integer ti (1 β€ ti β€ 2) that describes the operation type. If ti = 1, then it is followed by three integers li, ri and di (1 β€ li β€ ri β€ n, - 104 β€ di β€ 104) β the description of the operation of the first type. If ti = 2, then it is followed by three integers li, ri and mi (1 β€ li β€ ri β€ n, - 5Β·107 β€ mi β€ 5Β·107) β the description of the operation of the second type.
The operations are given in the order Levko performed them on his array.
Output
In the first line print "YES" (without the quotes), if the solution exists and "NO" (without the quotes) otherwise.
If the solution exists, then on the second line print n integers a1, a2, ... , an (|ai| β€ 109) β the recovered array.
Examples
Input
4 5
1 2 3 1
2 1 2 8
2 3 4 7
1 1 3 3
2 3 4 8
Output
YES
4 7 4 7
Input
4 5
1 2 3 1
2 1 2 8
2 3 4 7
1 1 3 3
2 3 4 13
Output
NO
Tags: greedy, implementation
Correct Solution:
```
n, m = map(int, input().split())
a = [10**9 for _ in range(n)]
extra = [0 for _ in range(n)]
query = list()
for _ in range(m):
t, l, r, x = map(int, input().split())
l -= 1
r -= 1
query.append((t, l, r, x))
if t == 1:
for j in range(l, r + 1):
extra[j] += x
else:
for j in range(l, r + 1):
a[j] = min(a[j], x - extra[j])
extra = a.copy()
for t, l, r, x in query:
if t == 1:
for j in range(l, r + 1):
a[j] += x
else:
val = -10**9
for j in range(l, r + 1):
val = max(val, a[j])
if not val == x:
print('NO')
exit(0)
print('YES')
for x in extra:
print(x, end=' ')
```
| 13,619 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Levko loves array a1, a2, ... , an, consisting of integers, very much. That is why Levko is playing with array a, performing all sorts of operations with it. Each operation Levko performs is of one of two types:
1. Increase all elements from li to ri by di. In other words, perform assignments aj = aj + di for all j that meet the inequation li β€ j β€ ri.
2. Find the maximum of elements from li to ri. That is, calculate the value <image>.
Sadly, Levko has recently lost his array. Fortunately, Levko has records of all operations he has performed on array a. Help Levko, given the operation records, find at least one suitable array. The results of all operations for the given array must coincide with the record results. Levko clearly remembers that all numbers in his array didn't exceed 109 in their absolute value, so he asks you to find such an array.
Input
The first line contains two integers n and m (1 β€ n, m β€ 5000) β the size of the array and the number of operations in Levko's records, correspondingly.
Next m lines describe the operations, the i-th line describes the i-th operation. The first integer in the i-th line is integer ti (1 β€ ti β€ 2) that describes the operation type. If ti = 1, then it is followed by three integers li, ri and di (1 β€ li β€ ri β€ n, - 104 β€ di β€ 104) β the description of the operation of the first type. If ti = 2, then it is followed by three integers li, ri and mi (1 β€ li β€ ri β€ n, - 5Β·107 β€ mi β€ 5Β·107) β the description of the operation of the second type.
The operations are given in the order Levko performed them on his array.
Output
In the first line print "YES" (without the quotes), if the solution exists and "NO" (without the quotes) otherwise.
If the solution exists, then on the second line print n integers a1, a2, ... , an (|ai| β€ 109) β the recovered array.
Examples
Input
4 5
1 2 3 1
2 1 2 8
2 3 4 7
1 1 3 3
2 3 4 8
Output
YES
4 7 4 7
Input
4 5
1 2 3 1
2 1 2 8
2 3 4 7
1 1 3 3
2 3 4 13
Output
NO
Submitted Solution:
```
n, m = map(int, input().split())
a = [1e9] * n
extra = [0] * n
query = list()
for _ in range(m):
t, l, r, x = map(int, input().split())
l -= 1
r -= 1
query.append((t, l, r, x))
if t == 1:
for j in range(l, r+1):
extra[j] += x
else:
for j in range(l, r+1):
a[j] = min(a[j], x - extra[j])
extra = a.copy()
for t, l, r, x in query:
if t == 1:
for j in range(l, r+1):
a[j] += x
else:
val = -10**9
for j in range(l, r+1):
val = max(val, a[j])
if not val == x:
print('NO')
exit()
print('YES')
print(*extra)
```
No
| 13,620 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub accidentally discovered a secret lab. He found there n devices ordered in a line, numbered from 1 to n from left to right. Each device i (1 β€ i β€ n) can create either ai units of matter or ai units of antimatter.
Iahub wants to choose some contiguous subarray of devices in the lab, specify the production mode for each of them (produce matter or antimatter) and finally take a photo of it. However he will be successful only if the amounts of matter and antimatter produced in the selected subarray will be the same (otherwise there would be overflowing matter or antimatter in the photo).
You are requested to compute the number of different ways Iahub can successful take a photo. A photo is different than another if it represents another subarray, or if at least one device of the subarray is set to produce matter in one of the photos and antimatter in the other one.
Input
The first line contains an integer n (1 β€ n β€ 1000). The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 1000).
The sum a1 + a2 + ... + an will be less than or equal to 10000.
Output
Output a single integer, the number of ways Iahub can take a photo, modulo 1000000007 (109 + 7).
Examples
Input
4
1 1 1 1
Output
12
Note
The possible photos are [1+, 2-], [1-, 2+], [2+, 3-], [2-, 3+], [3+, 4-], [3-, 4+], [1+, 2+, 3-, 4-], [1+, 2-, 3+, 4-], [1+, 2-, 3-, 4+], [1-, 2+, 3+, 4-], [1-, 2+, 3-, 4+] and [1-, 2-, 3+, 4+], where "i+" means that the i-th element produces matter, and "i-" means that the i-th element produces antimatter.
Tags: dp
Correct Solution:
```
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(2*10**5+10)
write = lambda x: sys.stdout.write(x+"\n")
debug = lambda x: sys.stderr.write(x+"\n")
writef = lambda x: print("{:.12f}".format(x))
n = int(input())
a = list(map(int, input().split()))
m = sum(a)
M = 10**9+7
dp = [0]*(2*m+1)
ans = 0
dp[m] = 1
val = 0
for i in range(n):
v = a[i]
ndp = [0]*(2*m+1)
for j in range(2*m+1):
if j-v>=0:
ndp[j-v] += dp[j]
if ndp[j-v]>M:
ndp[j-v] -= M
if j+v<=2*m:
ndp[j+v] += dp[j]
if ndp[j+v]>M:
ndp[j+v] -= M
dp = ndp
ans += dp[m]
ans %= M
dp[m] += 1
val += v
print(ans%M)
```
| 13,621 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub accidentally discovered a secret lab. He found there n devices ordered in a line, numbered from 1 to n from left to right. Each device i (1 β€ i β€ n) can create either ai units of matter or ai units of antimatter.
Iahub wants to choose some contiguous subarray of devices in the lab, specify the production mode for each of them (produce matter or antimatter) and finally take a photo of it. However he will be successful only if the amounts of matter and antimatter produced in the selected subarray will be the same (otherwise there would be overflowing matter or antimatter in the photo).
You are requested to compute the number of different ways Iahub can successful take a photo. A photo is different than another if it represents another subarray, or if at least one device of the subarray is set to produce matter in one of the photos and antimatter in the other one.
Input
The first line contains an integer n (1 β€ n β€ 1000). The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 1000).
The sum a1 + a2 + ... + an will be less than or equal to 10000.
Output
Output a single integer, the number of ways Iahub can take a photo, modulo 1000000007 (109 + 7).
Examples
Input
4
1 1 1 1
Output
12
Note
The possible photos are [1+, 2-], [1-, 2+], [2+, 3-], [2-, 3+], [3+, 4-], [3-, 4+], [1+, 2+, 3-, 4-], [1+, 2-, 3+, 4-], [1+, 2-, 3-, 4+], [1-, 2+, 3+, 4-], [1-, 2+, 3-, 4+] and [1-, 2-, 3+, 4+], where "i+" means that the i-th element produces matter, and "i-" means that the i-th element produces antimatter.
Tags: dp
Correct Solution:
```
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(2*10**5+10)
write = lambda x: sys.stdout.write(x+"\n")
debug = lambda x: sys.stderr.write(x+"\n")
writef = lambda x: print("{:.12f}".format(x))
n = int(input())
a = list(map(int, input().split()))
m = sum(a)
M = 10**9+7
dp = [0]*(2*m+1)
ans = 0
dp[m] = 1
val = 0
for i in range(n):
v = a[i]
ndp = [0]*(2*m+1)
for j in range(m-val, m+val+1):
if j-v>=0:
ndp[j-v] += dp[j]
if ndp[j-v]>M:
ndp[j-v] -= M
if j+v<=2*m:
ndp[j+v] += dp[j]
if ndp[j+v]>M:
ndp[j+v] -= M
dp = ndp
ans += dp[m]
ans %= M
dp[m] += 1
val += v
print(ans%M)
```
| 13,622 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Iahub accidentally discovered a secret lab. He found there n devices ordered in a line, numbered from 1 to n from left to right. Each device i (1 β€ i β€ n) can create either ai units of matter or ai units of antimatter.
Iahub wants to choose some contiguous subarray of devices in the lab, specify the production mode for each of them (produce matter or antimatter) and finally take a photo of it. However he will be successful only if the amounts of matter and antimatter produced in the selected subarray will be the same (otherwise there would be overflowing matter or antimatter in the photo).
You are requested to compute the number of different ways Iahub can successful take a photo. A photo is different than another if it represents another subarray, or if at least one device of the subarray is set to produce matter in one of the photos and antimatter in the other one.
Input
The first line contains an integer n (1 β€ n β€ 1000). The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 1000).
The sum a1 + a2 + ... + an will be less than or equal to 10000.
Output
Output a single integer, the number of ways Iahub can take a photo, modulo 1000000007 (109 + 7).
Examples
Input
4
1 1 1 1
Output
12
Note
The possible photos are [1+, 2-], [1-, 2+], [2+, 3-], [2-, 3+], [3+, 4-], [3-, 4+], [1+, 2+, 3-, 4-], [1+, 2-, 3+, 4-], [1+, 2-, 3-, 4+], [1-, 2+, 3+, 4-], [1-, 2+, 3-, 4+] and [1-, 2-, 3+, 4+], where "i+" means that the i-th element produces matter, and "i-" means that the i-th element produces antimatter.
Submitted Solution:
```
__author__ = 'Pavel Mavrin'
n = int(input())
a = [int(x) for x in input().split()]
d = [0] * 10001
dd = [0] * 10001
res = 0
s = 1
for i in range(n):
for j in range(s):
dd[j] = 0
s += a[i]
dd[0] += 1
for j in range(s):
kk = j + a[i]
dd[kk] += d[j]
dd[kk] %= 1000000007
kk = abs(j - a[i])
dd[kk] += d[j]
dd[kk] %= 1000000007
t = d
d = dd
dd = t
res += d[0]
res %= 1000000007
print(res - n)
```
No
| 13,623 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Iahub accidentally discovered a secret lab. He found there n devices ordered in a line, numbered from 1 to n from left to right. Each device i (1 β€ i β€ n) can create either ai units of matter or ai units of antimatter.
Iahub wants to choose some contiguous subarray of devices in the lab, specify the production mode for each of them (produce matter or antimatter) and finally take a photo of it. However he will be successful only if the amounts of matter and antimatter produced in the selected subarray will be the same (otherwise there would be overflowing matter or antimatter in the photo).
You are requested to compute the number of different ways Iahub can successful take a photo. A photo is different than another if it represents another subarray, or if at least one device of the subarray is set to produce matter in one of the photos and antimatter in the other one.
Input
The first line contains an integer n (1 β€ n β€ 1000). The second line contains n integers a1, a2, ..., an (1 β€ ai β€ 1000).
The sum a1 + a2 + ... + an will be less than or equal to 10000.
Output
Output a single integer, the number of ways Iahub can take a photo, modulo 1000000007 (109 + 7).
Examples
Input
4
1 1 1 1
Output
12
Note
The possible photos are [1+, 2-], [1-, 2+], [2+, 3-], [2-, 3+], [3+, 4-], [3-, 4+], [1+, 2+, 3-, 4-], [1+, 2-, 3+, 4-], [1+, 2-, 3-, 4+], [1-, 2+, 3+, 4-], [1-, 2+, 3-, 4+] and [1-, 2-, 3+, 4+], where "i+" means that the i-th element produces matter, and "i-" means that the i-th element produces antimatter.
Submitted Solution:
```
__author__ = 'Pavel Mavrin'
n = int(input())
a = [int(x) for x in input().split()]
d = [1]
res = 0
for i in range(n):
dd = [0] * (len(d) + a[i])
dd[0] += 1
for j in range(len(d)):
kk = j + a[i]
dd[kk] += d[j]
kk = abs(j - a[i])
dd[kk] += d[j]
d = dd
res += d[0]
print(res - n)
```
No
| 13,624 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 β€ k < n β€ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 β€ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 β€ m β€ 106) β the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 β€ ai, bi β€ n; ai β bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
import sys
import itertools as it
import math as mt
import collections as cc
import bisect as bi
input=sys.stdin.readline
I=lambda:list(map(int,input().split()))
n,k=I()
l=I()
ar=[]
f=cc.defaultdict(list)
ch=cc.defaultdict(int)
for i in range(n):
ar.append([l[i],i])
f[l[i]].append(i)
ar.sort(key=lambda x:x[0])
if l.count(0)>1:
print(-1)
elif 0 not in l:
print(-1)
else:
d=max(l)
ed=[]
now=0;
prev=[l.index(0)]
tf=1
while now+1<=d:
cur=set()
if len(f[now+1])==0:
tf=0
break
ii=0
ll=len(prev)
if ll*k<len(f[now+1]):
tf=0
break
else:
for j in f[now+1]:
if ch[prev[ii]]<k:
#print(1,ch,prev[ii])
ch[prev[ii]]+=1
ch[j]+=1
cur.add(j)
ed.append([prev[ii]+1,j+1])
ii+=1
ii%=ll
else:
tf=0
break
#print(2,ch)
prev=list(cur)
now+=1
if not tf:
print(-1)
else:
print(len(ed))
for i in ed:
print(*i)
```
| 13,625 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 β€ k < n β€ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 β€ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 β€ m β€ 106) β the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 β€ ai, bi β€ n; ai β bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
n, k = map(int, input().split())
d = zip(list(map(int, input().split())), range(1, n + 1))
d = sorted(d)
if d[0][0] != 0:
print(-1)
else:
u = 0
m = 0
check = True
graph = []
deg = [0]*(n + 1)
for v in range(1, n):
while u < v and (d[v][0] != d[u][0] + 1 or deg[d[u][1]] == k):
u += 1
if u == v:
print(-1)
check = False
break
graph.append([d[u][1], d[v][1]])
deg[d[u][1]] += 1
deg[d[v][1]] += 1
m += 1
if check:
print(m)
for i in range(0, m):
print(graph[i][0], graph[i][1])
```
| 13,626 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 β€ k < n β€ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 β€ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 β€ m β€ 106) β the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 β€ ai, bi β€ n; ai β bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
class RestoreGraph():
def __init__(self,n, k, dis_values):
self.dis_values = dis_values
self.n = n
self.k = k
def generate_graph(self):
dis_pairs = [(self.dis_values[i],i) for i in range(len(self.dis_values))]
dis_pairs = sorted(dis_pairs)
if dis_pairs[0][0] != 0:
print(-1)
return
count = [0]*self.n
parent = [-1]*self.n
ind = 0
for i in range(1, self.n):
if dis_pairs[ind][0] != dis_pairs[i][0]-1 or count[ind] == self.k:
ind = ind+1
while(ind < i and (dis_pairs[ind][0] < dis_pairs[i][0]-1 or count[ind] == self.k)):
ind += 1
if dis_pairs[ind][0] != dis_pairs[i][0]-1 or count[ind] == self.k:
print(-1)
return
parent[i] = ind
count[i] += 1
count[ind] += 1
print(self.n-1)
for i in range(1,n):
print(dis_pairs[i][1]+1, dis_pairs[parent[i]][1]+1)
n, k = list(map(int,input().strip(' ').split(' ')))
arr = list(map(int,input().strip(' ').split(' ')))
graph = RestoreGraph(n,k,arr)
graph.generate_graph()
```
| 13,627 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 β€ k < n β€ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 β€ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 β€ m β€ 106) β the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 β€ ai, bi β€ n; ai β bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
n, k = map(int, input().split())
d = zip(list(map(int, input().split())), range(1, n + 1))
d = sorted(d)
if d[0][0] != 0:
print(-1)
else:
u = 0
check = True
graph = []
deg = [0]*(n + 1)
for v in range(1, n):
if deg[d[u][1]] >= k:
u += 1
while u < v and d[v][0] != d[u][0] + 1:
u += 1
if u == v or deg[d[u][1]] >= k or deg[d[v][1]] >= k:
print(-1)
check = False
break
graph.append([d[u][1], d[v][1]])
deg[d[u][1]] += 1
deg[d[v][1]] += 1
if check:
m = len(graph)
print(m)
for i in range(0, m):
print(graph[i][0], graph[i][1])
```
| 13,628 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 β€ k < n β€ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 β€ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 β€ m β€ 106) β the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 β€ ai, bi β€ n; ai β bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
n, k = map(int, input().split())
t = list(map(int, input().split()))
s, p = [], [[] for i in range(max(t) + 1)]
for i, j in enumerate(t, 1): p[j].append(str(i))
if len(p[0]) - 1: print('-1')
else:
for i in range(1, len(p)):
if k * len(p[i - 1]) < len(p[i]):
print('-1')
exit(0)
j, u, v = 0, len(p[i]) // k, len(p[i]) % k
for x in range(u):
s += [p[i - 1][x] + ' ' + p[i][y] for y in range(j, j + k)]
j += k
s += [p[i - 1][u] + ' ' + p[i][y] for y in range(j, j + v)]
if i == 1: k -= 1
print(len(s))
print('\n'.join(s))
```
| 13,629 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 β€ k < n β€ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 β€ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 β€ m β€ 106) β the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 β€ ai, bi β€ n; ai β bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def main():
n,k = map(int,input().split())
d = list(map(int,input().split()))
cou = [[] for _ in range(n)]
for i in range(n):
cou[d[i]].append(i+1)
if len(cou[0]) != 1:
print(-1)
return
ans = []
for i in range(max(d)):
if len(cou[i])*(k-1)+(i==0) < len(cou[i+1]):
print(-1)
return
x,y = 0,0
for j in cou[i+1]:
if x == k-1+(i==0):
x,y = 0,y+1
x += 1
ans.append((cou[i][y],j))
print(len(ans))
for i in ans:
print(*i)
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
```
| 13,630 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 β€ k < n β€ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 β€ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 β€ m β€ 106) β the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 β€ ai, bi β€ n; ai β bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
import sys
n, k = map(int, input().split())
a = [int(i) for i in input().split()]
g = [k] * n
maxi = max(a)
ans = []
if a.count(0) != 1:
print(-1)
sys.exit()
i = 1
f = a.index(0)
pref_t = [f]
x = [[] for y in range(maxi + 1)]
for v in range(n):
x[a[v]].append(v)
while i <= maxi:
t = x[i]
w = len(t)
z = 0
for o in pref_t:
z += g[o]
if z < w:
print(-1)
sys.exit()
u = 0
for l in pref_t:
while w > 0 and g[l] > 0:
g[l] -= 1
g[t[u]] -= 1
w -= 1
ans.append([l, t[u]])
u += 1
pref_t = t
i += 1
print(len(ans))
for row in ans:
print(row[0] + 1, row[1] + 1)
```
| 13,631 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 β€ k < n β€ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 β€ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 β€ m β€ 106) β the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 β€ ai, bi β€ n; ai β bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Tags: dfs and similar, graphs, sortings
Correct Solution:
```
from math import ceil
def mkgr(n, srs, k):
res = [str(n-1)]
for d in srs[1]:
res.append("%i %i" % (srs[0][0]+1, d+1))
for i in range(2, len(srs)):
h, hs= 0, 0
for j in range(len(srs[i])):
res.append("%i %i" % (srs[i][j]+1, srs[i-1][h]+1))
hs += 1
if hs == k-1:
h += 1
hs = 0
return res
def test(n,k,dists):
m = max(dists)
srs = [[] for i in range(m+1)]
for i in range(n):
srs[dists[i]].append(i)
if [] in srs:
return ["-1"]
if len(srs[0]) != 1:
return ["-1"]
if len(srs[1]) > k:
return ["-1"]
for i in range(1, m):
if ceil(len(srs[i+1])/len(srs[i])) + 1 > k:
return ["-1"]
return mkgr(n, srs, k)
n, k = map(int, input().split())
dists = list(map(int, input().split()))
res = test(n,k,dists)
print("\n".join(res))
```
| 13,632 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 β€ k < n β€ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 β€ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 β€ m β€ 106) β the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 β€ ai, bi β€ n; ai β bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Submitted Solution:
```
from sys import exit
n, k = map(int, input().split())
nodes = [[] for _ in range(n+1)]
edges = []
for node, dist in enumerate(map(int, input().split())):
nodes[dist].append(node)
if len(nodes[0]) != 1 or len(nodes[1]) > k:
print(-1)
else:
for i in range(1, n):
if len(nodes[i])*(k-1) < len(nodes[i+1]):
print(-1)
exit(0)
for i in range(n):
next = 0
if len(nodes[i+1]) > 0:
for j, node in enumerate(nodes[i]):
current = 0
while current < (k if i == 0 else k-1) and next < len(nodes[i+1]):
edges.append((node+1, nodes[i+1][next]+1))
next += 1
current += 1
print(len(edges))
print('\n'.join(map(lambda x: ' '.join([str(x[0]), str(x[1])]), edges)))
```
Yes
| 13,633 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 β€ k < n β€ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 β€ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 β€ m β€ 106) β the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 β€ ai, bi β€ n; ai β bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Submitted Solution:
```
n, k = map(int, input().split())
d = list(map(int, input().split()))
dmax = max(d)
nv = [[] for i in range(dmax+1)]
v = [0] * (dmax+1)
for i, dist in enumerate(d):
nv[dist].append(i)
v[dist] += 1
flag = True
if v[0] != 1 or v[1] > k:
flag = False
else:
for i in range(2, dmax+1):
if v[i] > (k-1) * v[i-1] or v[i] == 0:
flag = False
break
if flag:
print(n-1)
for vrtx in nv[1]:
print(nv[0][0] + 1, vrtx + 1)
for i, vs in enumerate(nv[1:-1]):
for j, vrtx in enumerate(vs):
m = 0
while m < (k-1):
if (j*(k-1) + m) < len(nv[i+2]):
print(vrtx + 1, nv[i+2][j*(k-1) + m] + 1)
m += 1
else:
break
else:
print(-1)
```
Yes
| 13,634 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 β€ k < n β€ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 β€ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 β€ m β€ 106) β the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 β€ ai, bi β€ n; ai β bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Submitted Solution:
```
import sys
input=sys.stdin.readline
n,k=map(int,input().split())
d=list(map(int,input().split()))
r=[[d[i],i] for i in range(n)]
r.sort()
if r[0][0]!=0 or r[1][0]==0:
print(-1)
exit()
v=[[] for i in range(n+1)]
cnt=[0]*n
v[0].append(r[0][1])
edges=[]
for rank,ver in r[1:]:
if len(v[rank-1])==0:
print(-1)
exit()
edges.append([v[rank-1][-1]+1,ver+1])
v[rank].append(ver)
cnt[v[rank-1][-1]]+=1
cnt[ver]+=1
if cnt[v[rank-1][-1]]==k:
v[rank-1].pop()
if cnt[ver]==k:
v[rank].pop()
print(len(edges))
for x in edges:
print(*x)
```
Yes
| 13,635 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 β€ k < n β€ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 β€ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 β€ m β€ 106) β the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 β€ ai, bi β€ n; ai β bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Submitted Solution:
```
import sys
n, k = map(int, input().split())
a = [int(i) for i in input().split()]
g = [k] * n
maxi = max(a)
ans = []
if a.count(0) != 1:
print(-1)
sys.exit()
i = 1
f = a.index(0)
pref_t = [f]
x = [[] for y in range(maxi + 1)]
for v in range(n):
x[a[v]].append(v)
while i <= maxi:
t = x[i]
w = len(t)
z = 0
for o in pref_t:
z += g[o]
if z < w:
print(-1)
sys.exit()
u = 0
for l in pref_t:
while w > 0 and g[l] > 0:
g[l] -= 1
g[t[u]] -= 1
w -= 1
ans.append([l, t[u]])
u += 1
pref_t = t
i += 1
print(len(ans))
for row in ans:
print(row[0] + 1, row[1] + 1)
# Fri Oct 16 2020 18:10:22 GMT+0300 (ΠΠΎΡΠΊΠ²Π°, ΡΡΠ°Π½Π΄Π°ΡΡΠ½ΠΎΠ΅ Π²ΡΠ΅ΠΌΡ)
```
Yes
| 13,636 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 β€ k < n β€ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 β€ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 β€ m β€ 106) β the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 β€ ai, bi β€ n; ai β bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Submitted Solution:
```
n,k = map(int,input().split())
a = list(map(int,input().split()))
import collections
d = collections.defaultdict(list)
cnt,cnt1 = 0,0
freq = [0]*(n+10)
ans = 0
temp = []
for i in range(n):
if(a[i]==0):
cnt+=1
freq[a[i]]+=1
if(a[i]>0):
ans+=1
temp.append([i+1,a[i]])
if(cnt!=1):
print(-1)
exit(0)
for i in range(1,n):
if(freq[i+1]>0):
if(freq[i]*(k-1)<freq[i+1]):
print(-1)
exit(0)
else:
break
temp.sort(key = lambda x:x[1])
print(ans)
cnt = 0
x = temp[0][0]
y = 1
abc = []
cntr = [0]*(n+1)
for i in range(1,n):
if(cnt<k):
if(temp[i][1]==y):
freq[temp[i][1]]-=1
abc.append(temp[i][0])
cntr[x]+=1
if(cntr[x]>k):
print(-1)
exit(0)
print(x,temp[i][0])
cnt+=1
else:
y+=1
x = abc.pop()
print(x,temp[i][0])
abc.append(temp[i][0])
freq[temp[i][1]]-=1
cnt = 2
else:
if(freq[temp[i-1][1]]>0):
x = abc.pop(0)
print(x,temp[i][0])
abc.append(temp[i][0])
freq[temp[i-1][1]]-=1
cnt = 2
else:
y+=1
x = abc.pop()
print(x,temp[i][0])
abc.append(temp[i][0])
freq[temp[i][1]]-=1
cnt = 2
```
No
| 13,637 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 β€ k < n β€ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 β€ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 β€ m β€ 106) β the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 β€ ai, bi β€ n; ai β bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Submitted Solution:
```
import sys
input=sys.stdin.readline
n,k=map(int,input().split())
d=list(map(int,input().split()))
r=[[d[i],i] for i in range(n)]
r.sort()
if r[0][0]!=0 or r[1][0]==0:
print(-1)
exit()
v=[[] for i in range(n+1)]
cnt=[0]*n
v[0].append(r[0][1])
edges=[]
for rank,ver in r[1:]:
if len(v[rank-1])==0:
print(-1)
exit()
edges.append([v[rank-1][-1]+1,ver+1])
v[rank].append(ver)
cnt[v[rank-1][-1]]+=1
if cnt[v[rank-1][-1]]==k:
v[rank-1].pop()
print(len(edges))
for x in edges:
print(*x)
```
No
| 13,638 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 β€ k < n β€ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 β€ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 β€ m β€ 106) β the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 β€ ai, bi β€ n; ai β bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Submitted Solution:
```
n, k = map(int, input().split())
d = zip(list(map(int, input().split())), range(1, n + 1))
d = sorted(d)
if d[0][0] != 0:
print(-1)
else:
u = 0
check = True
graph = []
deg = [0]*(n + 1)
for v in range(1, n):
if deg[d[u][1]] >= k:
u += 1
while u < v and d[v][0] != d[u][0] + 1:
u += 1
if u == v or deg[d[v][1]] >= k:
print(-1)
check = False
break
graph.append([d[u][1], d[v][1]])
deg[d[u][1]] += 1
deg[d[v][1]] += 1
if check:
m = len(graph)
print(m)
for i in range(0, m):
print(graph[i][0], graph[i][1])
```
No
| 13,639 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.
Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.
Input
The first line contains two space-separated integers n and k (1 β€ k < n β€ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph.
The second line contains space-separated integers d[1], d[2], ..., d[n] (0 β€ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.
Output
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 β€ m β€ 106) β the number of edges in the found graph.
In each of the next m lines print two space-separated integers ai and bi (1 β€ ai, bi β€ n; ai β bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
Examples
Input
3 2
0 1 1
Output
3
1 2
1 3
3 2
Input
4 2
2 0 1 3
Output
3
1 3
1 4
2 3
Input
3 1
0 0 0
Output
-1
Submitted Solution:
```
n,k=map(int,input().split())
d=zip( list(map(int,input().split())),range(0,n) )
d=sorted(d)
last=0
du=[0]*n
fa=[0]*n
flag=1
for j in range(1,n):
while last<j and ( du[last]==k or d[last][0]+1<d[j][0] ):
last+=1
if last==j or d[last][0]+1!=d[j][0]:
print(-1)
break
fa[j]=last
du[j]+=1
du[last]+=1
else:
print(n-1)
for j in range(1,n):
print(d[fa[j]][1]+1,d[j][1]+1)
```
No
| 13,640 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1, n + 2, ..., 2Β·n there are exactly m numbers which binary representation contains exactly k digits one".
The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018.
Input
The first line contains two space-separated integers, m and k (0 β€ m β€ 1018; 1 β€ k β€ 64).
Output
Print the required number n (1 β€ n β€ 1018). If there are multiple answers, print any of them.
Examples
Input
1 1
Output
1
Input
3 2
Output
5
Tags: binary search, bitmasks, combinatorics, dp, math
Correct Solution:
```
import sys
def b(n):
c = 0
while n:
if n & 1:
c += 1
n //= 2
return c
c = {}
def f(n, k):
if (n, k) in c.keys():
return c[(n, k)]
if n == 1:
return 1 if k == 1 else 0
c[(n, k)] = f(n // 2, k) + f(n // 2, k - 1) + int(n & 1 and b(n // 2) == k - 1)
return c[(n, k)]
m, k = map(int, input().split())
hi = int(1e18)
lo = 1
while (hi - lo >= 0):
mid = (lo + hi) // 2
val = f(mid, k)
if val == m:
print(mid)
sys.exit()
elif val < m:
lo = mid + 1
else:
hi = mid - 1
```
| 13,641 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1, n + 2, ..., 2Β·n there are exactly m numbers which binary representation contains exactly k digits one".
The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018.
Input
The first line contains two space-separated integers, m and k (0 β€ m β€ 1018; 1 β€ k β€ 64).
Output
Print the required number n (1 β€ n β€ 1018). If there are multiple answers, print any of them.
Examples
Input
1 1
Output
1
Input
3 2
Output
5
Tags: binary search, bitmasks, combinatorics, dp, math
Correct Solution:
```
MX_BIT = 64
C = [[int(0) for i in range(MX_BIT)] for j in range(MX_BIT)]
def ck(x, i):
return (x>>i) & 1
def tot_bits(x):
x = bin(x)[2:]
return len(x)
def mkt():
C[0][0] = 1
for i in range (1, MX_BIT):
for j in range (i+1):
C[i][j] = C[i-1][j] + (C[i-1][j-1] if j else 0)
def solve(x, k):
a = 0
for i in reversed(range(MX_BIT)):
if ck(x, i) != 0:
a += C[i][k]
k -= 1
if k == 0:
break
return a
mkt()
m, k = list(input().split())
m = int(m)
k = int(k)
l = 1
r = 1e18
if not m:
l = 1
else:
while l < r:
mid = int((l + r) // 2)
if (solve(2*mid, k) - solve(mid, k)) < m :
l = mid + 1
else:
r = mid
print(l)
```
| 13,642 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1, n + 2, ..., 2Β·n there are exactly m numbers which binary representation contains exactly k digits one".
The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018.
Input
The first line contains two space-separated integers, m and k (0 β€ m β€ 1018; 1 β€ k β€ 64).
Output
Print the required number n (1 β€ n β€ 1018). If there are multiple answers, print any of them.
Examples
Input
1 1
Output
1
Input
3 2
Output
5
Tags: binary search, bitmasks, combinatorics, dp, math
Correct Solution:
```
def dfs(n, k, cache = {}):
# if number of bits is bigger than the number's bits of the number's bits is less than 0
if k > n or k < 0: return 0
# if num bits is 0 or num bits is equivalent to the number's bits
if k == 0 or k == n: return 1
#
# if k*2 > n: k = n-k
# Check is already calculated
if (n, k) in cache: return cache[(n, k)]
# Use dfs addition for case where certain bit is 1 or certain bit is 0
z = cache[(n, k)] = dfs(n-1, k-1) + dfs(n-1, k)
return z
def bits(n):
b = 0
while n:
if n&1: b += 1
n >>= 1
return b
def count(n, k):
z, b, c = 0, 63, 0
for b in reversed(range(64)):
# Taking n and checking if bit is 1 or not
if (n>>b)&1:
z += dfs(b, k-c)
c += 1
if not k: break
return z + (bits(n) == k)
def solve(m, k):
# Binary Search for number 1-10^18
low, high = 1, 10**18
while low < high:
mid = (low+high)//2
if count(2*mid, k) - count(mid, k) < m:
low = mid+1
else:
high = mid
return high
m, k = [int(x) for x in input().split()]
print(solve(m, k))
```
| 13,643 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1, n + 2, ..., 2Β·n there are exactly m numbers which binary representation contains exactly k digits one".
The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018.
Input
The first line contains two space-separated integers, m and k (0 β€ m β€ 1018; 1 β€ k β€ 64).
Output
Print the required number n (1 β€ n β€ 1018). If there are multiple answers, print any of them.
Examples
Input
1 1
Output
1
Input
3 2
Output
5
Tags: binary search, bitmasks, combinatorics, dp, math
Correct Solution:
```
N = 70
C = [[0 for _ in range(N)] for _ in range(N)]
for i in range(N):
C[i][0] = C[i][i] = 1
for j in range(1, i):
C[i][j] = C[i - 1][j - 1] + C[i - 1][j]
l, r = 1, int(1e19)
m, k = [int(x) for x in input().split(' ')]
k -= 1
def ok(x: int):
s = bin(x)[2:]
s = s[::-1]
t = k
ans = 0
for i in range(len(s) - 1, -1, -1):
if s[i] == "1":
ans += C[i][t]
t -= 1
if t < 0:
break
return ans >= m
while l < r:
mid = (l + r) >> 1
if ok(mid):
r = mid
else:
l = mid + 1
print(l)
```
| 13,644 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1, n + 2, ..., 2Β·n there are exactly m numbers which binary representation contains exactly k digits one".
The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018.
Input
The first line contains two space-separated integers, m and k (0 β€ m β€ 1018; 1 β€ k β€ 64).
Output
Print the required number n (1 β€ n β€ 1018). If there are multiple answers, print any of them.
Examples
Input
1 1
Output
1
Input
3 2
Output
5
Tags: binary search, bitmasks, combinatorics, dp, math
Correct Solution:
```
comb = [[0 for i in range(67)] for j in range(67)]
for i in range(67):
comb[i][0], comb[i][i] = 1, 1
for j in range(1, i):
comb[i][j] = comb[i - 1][j - 1] + comb[i - 1][j]
def calc(x):
cnt = 0
digit = []
while (x > 0):
digit.append(x % 2)
x //= 2
cnt += 1
ans, one = 0, 0
for i in reversed(range(cnt)):
if (digit[i] == 1):
if (k - one >= 0):
ans += comb[i][k - one]
one += 1
return ans
m, k = map(int, input().split())
lcur, rcur = 0, 2 ** 64
while (lcur + 2 <= rcur):
mid = (lcur + rcur) // 2
if (calc(mid * 2) - calc(mid) < m):
lcur = mid
else:
rcur = mid
print(rcur)
```
| 13,645 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1, n + 2, ..., 2Β·n there are exactly m numbers which binary representation contains exactly k digits one".
The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018.
Input
The first line contains two space-separated integers, m and k (0 β€ m β€ 1018; 1 β€ k β€ 64).
Output
Print the required number n (1 β€ n β€ 1018). If there are multiple answers, print any of them.
Examples
Input
1 1
Output
1
Input
3 2
Output
5
Tags: binary search, bitmasks, combinatorics, dp, math
Correct Solution:
```
def dfs(n, k, cache = {}):
# if number of bits is bigger than the number's bits of the number's bits is less than 0
if k > n or k < 0: return 0
# if num bits is 0 or num bits is equivalent to the number's bits
if k == 0 or k == n: return 1
if k*2 > n: k = n-k
# Check is already calculated
if (n, k) in cache: return cache[(n, k)]
# Use dfs addition for case where certain bit is 1 or certain bit is 0
z = cache[(n, k)] = dfs(n-1, k-1) + dfs(n-1, k)
return z
def bits(n):
b = 0
while n:
if n&1: b += 1
n >>= 1
return b
def count(n, k):
z, b, c = 0, 63, 0
for b in reversed(range(64)):
# Taking n and checking if bit is 1 or not
if (n>>b)&1:
z += dfs(b, k-c)
c += 1
if not k: break
return z + (bits(n) == k)
def solve(m, k):
# Binary Search for number 1-10^18
low, high = 1, 10**18
while low < high:
mid = (low+high)//2
if count(2*mid, k) - count(mid, k) < m:
low = mid+1
else:
high = mid
return high
m, k = [int(x) for x in input().split()]
print(solve(m, k))
```
| 13,646 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1, n + 2, ..., 2Β·n there are exactly m numbers which binary representation contains exactly k digits one".
The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018.
Input
The first line contains two space-separated integers, m and k (0 β€ m β€ 1018; 1 β€ k β€ 64).
Output
Print the required number n (1 β€ n β€ 1018). If there are multiple answers, print any of them.
Examples
Input
1 1
Output
1
Input
3 2
Output
5
Tags: binary search, bitmasks, combinatorics, dp, math
Correct Solution:
```
def dfs(n, k, cache = {}):
# if number of bits is bigger than the number's bits of the number's bits is less than 0
if k > n or k < 0: return 0
# if num bits is 0 or num bits is equivalent to the number's bits
if k == 0 or k == n: return 1
# This optimization is not necessary but flips the 0s and the 1s
# if k*2 > n: k = n-k
# Check is already calculated
if (n, k) in cache: return cache[(n, k)]
# Use dfs addition for case where certain bit is 1 or certain bit is 0
z = cache[(n, k)] = dfs(n-1, k-1) + dfs(n-1, k)
return z
def bits(n):
b = 0
while n:
if n&1: b += 1
n >>= 1
return b
def count(n, k):
z, b, c = 0, 63, 0
for b in reversed(range(64)):
# Taking n and checking if certain bit is 1 or not
# This sums for every mod power of 2 that exists to account for every case
if (n>>b)&1:
# calculates by subtracting for bits not accounted for
z += dfs(b, k-c)
c += 1
# if not k: break
return z + (bits(n) == k)
def solve(m, k):
# Binary Search for number 1-10^18
low, high = 1, 10**18
while low < high:
mid = (low+high)//2
if count(2*mid, k) - count(mid, k) < m:
low = mid+1
else:
high = mid
return high
m, k = [int(x) for x in input().split()]
print(solve(m, k))
```
| 13,647 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1, n + 2, ..., 2Β·n there are exactly m numbers which binary representation contains exactly k digits one".
The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018.
Input
The first line contains two space-separated integers, m and k (0 β€ m β€ 1018; 1 β€ k β€ 64).
Output
Print the required number n (1 β€ n β€ 1018). If there are multiple answers, print any of them.
Examples
Input
1 1
Output
1
Input
3 2
Output
5
Tags: binary search, bitmasks, combinatorics, dp, math
Correct Solution:
```
def nck(n, k, cache = {}):
if k > n or k < 0: return 0
if k == 0 or k == n: return 1
if k*2 > n: k = n-k
if (n, k) in cache: return cache[(n, k)]
z = cache[(n, k)] = nck(n-1, k-1) + nck(n-1, k)
return z
def bits(n):
b = 0
while n:
if n&1: b += 1
n >>= 1
return b
def count(n, k):
z, b, c = 0, 63, 0
for b in reversed(range(64)):
if (n>>b)&1:
z += nck(b, k-c)
c += 1
if not k: break
return z + (bits(n) == k)
def solve(m, k):
lo, hi = 1, 10**18
while lo < hi:
mi = (lo+hi)//2
if count(2*mi, k) - count(mi, k) < m:
lo = mi+1
else:
hi = mi
return hi
m, k = [int(x) for x in input().split()]
print(solve(m, k))
```
| 13,648 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1, n + 2, ..., 2Β·n there are exactly m numbers which binary representation contains exactly k digits one".
The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018.
Input
The first line contains two space-separated integers, m and k (0 β€ m β€ 1018; 1 β€ k β€ 64).
Output
Print the required number n (1 β€ n β€ 1018). If there are multiple answers, print any of them.
Examples
Input
1 1
Output
1
Input
3 2
Output
5
Submitted Solution:
```
from math import factorial as f
def C(n, m):
if n < m: return 0
return f(n) // ( f(n - m ) * f(m) )
m, k = map(int, input().split())
ans = 1
for bit in reversed(range(65)):
if k == 0:
break
if C(bit, k - 1) < m:
ans += ( 1 << bit )
m -= C(bit, k - 1)
k -= 1
print(ans)
```
Yes
| 13,649 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1, n + 2, ..., 2Β·n there are exactly m numbers which binary representation contains exactly k digits one".
The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018.
Input
The first line contains two space-separated integers, m and k (0 β€ m β€ 1018; 1 β€ k β€ 64).
Output
Print the required number n (1 β€ n β€ 1018). If there are multiple answers, print any of them.
Examples
Input
1 1
Output
1
Input
3 2
Output
5
Submitted Solution:
```
def dfs(n, k, cache = {}):
# if number of bits is bigger than the number's bits of the number's bits is less than 0
if k > n or k < 0: return 0
# if num bits is 0 or num bits is equivalent to the number's bits
if k == 0 or k == n: return 1
# This optimization is not necessary but flips the 0s and the 1s
# if k*2 > n: k = n-k
# Check is already calculated
if (n, k) in cache: return cache[(n, k)]
# Use dfs addition for case where certain bit is 1 or certain bit is 0
z = cache[(n, k)] = dfs(n-1, k-1) + dfs(n-1, k)
return z
def bits(n):
# counts number of 1s in the number
b = 0
while n:
if n & 1: b += 1
n >>= 1
return b
def count(n, k):
z, b, c = 0, 63, 0
for b in reversed(range(64)):
# Taking n and checking if certain bit is 1 or not
# This sums for every mod power of 2 that exists to account for every case
if (n>>b)&1:
# calculates by subtracting for bits not accounted for
z += dfs(b, k-c)
c += 1
# Unnecessary code
# if not k: break
# if original number has same number of 1s as digits required, add 1
return z + (bits(n) == k)
def solve(m, k):
# Binary Search for number 1-10^18
low, high = 1, 10**18
while low < high:
mid = (low+high)//2
if count(2*mid, k) - count(mid, k) < m:
low = mid+1
else:
high = mid
return high
m, k = [int(x) for x in input().split()]
print(solve(m, k))
```
Yes
| 13,650 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1, n + 2, ..., 2Β·n there are exactly m numbers which binary representation contains exactly k digits one".
The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018.
Input
The first line contains two space-separated integers, m and k (0 β€ m β€ 1018; 1 β€ k β€ 64).
Output
Print the required number n (1 β€ n β€ 1018). If there are multiple answers, print any of them.
Examples
Input
1 1
Output
1
Input
3 2
Output
5
Submitted Solution:
```
dp = dict()
def cnt(n, k):
if k < 0:
return 0
if n == 0:
if k == 0:
return 1
else:
return 0
else:
if (n, k) in dp.keys():
return dp[(n, k)]
else:
dp[(n, k)] = cnt(n//2, k) + cnt(n//2, k-1)
return dp[(n, k)]
m, k = map(int, input().split())
lo = 1
hi = 10**18
ans = -1
while lo <= hi:
mid = (lo+hi)//2
if cnt(2 * mid, k) - cnt(mid, k) > m:
hi = mid - 1
elif cnt(2 * mid, k) - cnt(mid, k) == m:
ans = mid
break
else:
lo = mid + 1
print(ans)
```
No
| 13,651 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1, n + 2, ..., 2Β·n there are exactly m numbers which binary representation contains exactly k digits one".
The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018.
Input
The first line contains two space-separated integers, m and k (0 β€ m β€ 1018; 1 β€ k β€ 64).
Output
Print the required number n (1 β€ n β€ 1018). If there are multiple answers, print any of them.
Examples
Input
1 1
Output
1
Input
3 2
Output
5
Submitted Solution:
```
#!/usr/bin/python
import math
m, k = map(int, input().strip(' ').split(' '))
def solve(x):
ans = 0
tot = 0
for i in reversed(range(1, int(math.log2(x)+1))):
if x & (1 << i):
ans += math.comb(i, k-tot)
tot += 1
if tot > k:
return ans
return ans
def judge(x):
return solve(x*2)-solve(x) >= m
l, r = 1, 2
while not judge(r):
l, r = r, r*2
ans = -1
while l <= r:
mid = (l+r) >> 1
if judge(mid):
ans, r = mid, mid-1
else:
l = mid+1
print(ans)
```
No
| 13,652 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1, n + 2, ..., 2Β·n there are exactly m numbers which binary representation contains exactly k digits one".
The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018.
Input
The first line contains two space-separated integers, m and k (0 β€ m β€ 1018; 1 β€ k β€ 64).
Output
Print the required number n (1 β€ n β€ 1018). If there are multiple answers, print any of them.
Examples
Input
1 1
Output
1
Input
3 2
Output
5
Submitted Solution:
```
import math
n = input()
n = n.split(" ")
t = [int(i) for i in n]
m = t[0]
k = t[1]
l = m
r = 2*m+1
def check(inp):
s = bin(int(inp))
s = s[2:]
num = int(s)
ans = 0
while num >= 1 :
ans = ans + num%10
num = num / 10
return int(ans)
while l < r:
mid = (l+r)/2;
if check(mid) == int(k):
print(int(mid))
break
elif check(mid) < k:
l = mid + 1
else:
r = mid - 1
```
No
| 13,653 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1, n + 2, ..., 2Β·n there are exactly m numbers which binary representation contains exactly k digits one".
The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018.
Input
The first line contains two space-separated integers, m and k (0 β€ m β€ 1018; 1 β€ k β€ 64).
Output
Print the required number n (1 β€ n β€ 1018). If there are multiple answers, print any of them.
Examples
Input
1 1
Output
1
Input
3 2
Output
5
Submitted Solution:
```
#!/usr/bin/python
import math
m, k = map(int, input().strip(' ').split(' '))
def solve(x):
ans = 0
tot = 0
for i in reversed(range(1, int(math.log2(x)+1))):
if x & (1 << i):
ans += math.comb(i, k-tot)
tot += 1
if tot == k:
return ans
return ans
l, r = 1, 2**(k+2)
ans = -1
while l <= r:
mid = (l+r) >> 1
if solve(mid*2)-solve(mid) >= m:
ans = mid
r = mid-1
else:
l = mid+1
print(ans)
```
No
| 13,654 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n Γ n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matrix should be represented by character "*". Look at the examples to understand what you need to draw.
Input
The only line contains an integer n (3 β€ n β€ 101; n is odd).
Output
Output a crystal of size n.
Examples
Input
3
Output
*D*
DDD
*D*
Input
5
Output
**D**
*DDD*
DDDDD
*DDD*
**D**
Input
7
Output
***D***
**DDD**
*DDDDD*
DDDDDDD
*DDDDD*
**DDD**
***D***
Tags: implementation
Correct Solution:
```
n=int(input())
d=0
for i in range(n):
if i<n//2:
print("*"*(n//2-i)+"D"*(2*i+1)+"*"*(n//2-i))
elif i==n//2:
print("D"*n)
elif i>n//2:
print("*"*(i-n//2)+"D"*(n-2-2*d)+"*"*(n//2-(n-i-1)))
d+=1
```
| 13,655 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n Γ n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matrix should be represented by character "*". Look at the examples to understand what you need to draw.
Input
The only line contains an integer n (3 β€ n β€ 101; n is odd).
Output
Output a crystal of size n.
Examples
Input
3
Output
*D*
DDD
*D*
Input
5
Output
**D**
*DDD*
DDDDD
*DDD*
**D**
Input
7
Output
***D***
**DDD**
*DDDDD*
DDDDDDD
*DDDDD*
**DDD**
***D***
Tags: implementation
Correct Solution:
```
import math, os, sys
import string, re
import itertools, functools, operator
from collections import Counter
def inputint():
return int(input())
def inputarray(func=int):
return map(func, input().split())
n = inputint()
for i in range(n):
x = abs(n//2 - i)
print('*'*x + 'D'*(n - 2*x) + '*'*x)
```
| 13,656 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n Γ n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matrix should be represented by character "*". Look at the examples to understand what you need to draw.
Input
The only line contains an integer n (3 β€ n β€ 101; n is odd).
Output
Output a crystal of size n.
Examples
Input
3
Output
*D*
DDD
*D*
Input
5
Output
**D**
*DDD*
DDDDD
*DDD*
**D**
Input
7
Output
***D***
**DDD**
*DDDDD*
DDDDDDD
*DDDDD*
**DDD**
***D***
Tags: implementation
Correct Solution:
```
n = int(input())
k = n // 2
ans = [['*']*n for i in range(n)]
i = 0
while k >= 0:
for j in range(k,n-k):
ans[i][j] = 'D'
k -= 1
i += 1
k = 1
while k <=n // 2:
for j in range(k,n-k):
ans[i][j] = 'D'
k += 1
i += 1
for i in range(n):
for j in range(n):
print(ans[i][j], end = '')
print('')
```
| 13,657 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n Γ n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matrix should be represented by character "*". Look at the examples to understand what you need to draw.
Input
The only line contains an integer n (3 β€ n β€ 101; n is odd).
Output
Output a crystal of size n.
Examples
Input
3
Output
*D*
DDD
*D*
Input
5
Output
**D**
*DDD*
DDDDD
*DDD*
**D**
Input
7
Output
***D***
**DDD**
*DDDDD*
DDDDDDD
*DDDDD*
**DDD**
***D***
Tags: implementation
Correct Solution:
```
n=int(input())
x=''
for a in range(1,int((n+3)/2)):
b=(n+1-2*a)/2
x+=int(b)*'*'
x+=(2*a-1)*'D'
x+=int(b)*'*'
print(x)
x=''
for a in range(1,int((n+1)/2)):
b=n-2*a
x+=a*'*'
x+=b*'D'
x+=a*'*'
print(x)
x=''
```
| 13,658 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n Γ n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matrix should be represented by character "*". Look at the examples to understand what you need to draw.
Input
The only line contains an integer n (3 β€ n β€ 101; n is odd).
Output
Output a crystal of size n.
Examples
Input
3
Output
*D*
DDD
*D*
Input
5
Output
**D**
*DDD*
DDDDD
*DDD*
**D**
Input
7
Output
***D***
**DDD**
*DDDDD*
DDDDDDD
*DDDDD*
**DDD**
***D***
Tags: implementation
Correct Solution:
```
n = int(input()); m = n//2; k = 1
for i in range(n):
if k<n:
print('*'*m + 'D'*k + '*'*m)
m-=1; k+=2
k=n
for i in range(n):
print('*'*m + 'D'*k + '*'*m)
m+=1; k-=2
if m>n//2: break
```
| 13,659 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n Γ n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matrix should be represented by character "*". Look at the examples to understand what you need to draw.
Input
The only line contains an integer n (3 β€ n β€ 101; n is odd).
Output
Output a crystal of size n.
Examples
Input
3
Output
*D*
DDD
*D*
Input
5
Output
**D**
*DDD*
DDDDD
*DDD*
**D**
Input
7
Output
***D***
**DDD**
*DDDDD*
DDDDDDD
*DDDDD*
**DDD**
***D***
Tags: implementation
Correct Solution:
```
a = int(input())
mat=[]
sat=[]
fat=[]
rat=[]
for i in range(a//2+1):
for j in range(a):
if i+j>=a//2 and i+j<=((a//2)+2*i):
sat.append('D')
else:
sat.append('*')
mat.append(sat)
sat=[]
for i in mat:
for j in i:
print(j,end='')
print()
for i in range(1,a//2+1):
for j in range(a):
print(mat[a//2-i][j],end='')
print()
```
| 13,660 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n Γ n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matrix should be represented by character "*". Look at the examples to understand what you need to draw.
Input
The only line contains an integer n (3 β€ n β€ 101; n is odd).
Output
Output a crystal of size n.
Examples
Input
3
Output
*D*
DDD
*D*
Input
5
Output
**D**
*DDD*
DDDDD
*DDD*
**D**
Input
7
Output
***D***
**DDD**
*DDDDD*
DDDDDDD
*DDDDD*
**DDD**
***D***
Tags: implementation
Correct Solution:
```
n=int(input())
a=n//2
c=0
for i in range((n//2)+1):
for j in range(0,a):
print("*",end="")
for k in range(0,c+1):
print("D",end="")
c=c+2
for j in range(0,a):
print("*",end="")
print()
a=a-1
c=n-2
b=1
for i in range(n//2):
for j in range(0,b):
print("*",end="")
for k in range(0,c):
print("D",end="")
c=c-2
for j in range(0,b):
print("*",end="")
print()
b=b+1
```
| 13,661 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n Γ n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matrix should be represented by character "*". Look at the examples to understand what you need to draw.
Input
The only line contains an integer n (3 β€ n β€ 101; n is odd).
Output
Output a crystal of size n.
Examples
Input
3
Output
*D*
DDD
*D*
Input
5
Output
**D**
*DDD*
DDDDD
*DDD*
**D**
Input
7
Output
***D***
**DDD**
*DDDDD*
DDDDDDD
*DDDDD*
**DDD**
***D***
Tags: implementation
Correct Solution:
```
n = int(input())
add = -1
a = n // 2
for i in range(n):
if a == -1:
a = 1
add *= -1
print("*" * a + "D" * (n - a * 2) + "*" * a)
a += add
```
| 13,662 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n Γ n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matrix should be represented by character "*". Look at the examples to understand what you need to draw.
Input
The only line contains an integer n (3 β€ n β€ 101; n is odd).
Output
Output a crystal of size n.
Examples
Input
3
Output
*D*
DDD
*D*
Input
5
Output
**D**
*DDD*
DDDDD
*DDD*
**D**
Input
7
Output
***D***
**DDD**
*DDDDD*
DDDDDDD
*DDDDD*
**DDD**
***D***
Submitted Solution:
```
n = int(input())
for i in range(n):
buf = abs((n-1)//2-i)
other = n-2*buf
print('*'*buf+'D'*other+'*'*buf)
```
Yes
| 13,663 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n Γ n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matrix should be represented by character "*". Look at the examples to understand what you need to draw.
Input
The only line contains an integer n (3 β€ n β€ 101; n is odd).
Output
Output a crystal of size n.
Examples
Input
3
Output
*D*
DDD
*D*
Input
5
Output
**D**
*DDD*
DDDDD
*DDD*
**D**
Input
7
Output
***D***
**DDD**
*DDDDD*
DDDDDDD
*DDDDD*
**DDD**
***D***
Submitted Solution:
```
height = int(input())
diamonds_on_line=1
while diamonds_on_line!=height:
print(((height-diamonds_on_line)//2)*'*'+diamonds_on_line*'D'+((height-diamonds_on_line)//2)*'*')
diamonds_on_line+=2
print(diamonds_on_line*'D')
while diamonds_on_line!=1:
diamonds_on_line-=2
print(((height-diamonds_on_line)//2)*'*'+diamonds_on_line*'D'+((height-diamonds_on_line)//2)*'*')
```
Yes
| 13,664 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n Γ n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matrix should be represented by character "*". Look at the examples to understand what you need to draw.
Input
The only line contains an integer n (3 β€ n β€ 101; n is odd).
Output
Output a crystal of size n.
Examples
Input
3
Output
*D*
DDD
*D*
Input
5
Output
**D**
*DDD*
DDDDD
*DDD*
**D**
Input
7
Output
***D***
**DDD**
*DDDDD*
DDDDDDD
*DDDDD*
**DDD**
***D***
Submitted Solution:
```
n=int(input())
k=[]
s=''
a=n-1
a=a//2
b=1
p=(n//2)+1
for i in range(p):
for j in range(a):
s+='*'
for j in range(b):
s+='D'
for j in range(a):
s+='*'
k.append(s)
s=''
b=b+2
a=a-1
s=''
a=1
b=n-2
for i in range(p-1):
for j in range(a):
s+='*'
for j in range(b):
s+='D'
for j in range(a):
s+='*'
k.append(s)
s=''
b=b-2
a=a+1
for i in k:
print(i)
```
Yes
| 13,665 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n Γ n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matrix should be represented by character "*". Look at the examples to understand what you need to draw.
Input
The only line contains an integer n (3 β€ n β€ 101; n is odd).
Output
Output a crystal of size n.
Examples
Input
3
Output
*D*
DDD
*D*
Input
5
Output
**D**
*DDD*
DDDDD
*DDD*
**D**
Input
7
Output
***D***
**DDD**
*DDDDD*
DDDDDDD
*DDDDD*
**DDD**
***D***
Submitted Solution:
```
#####--------------Template Begin-------------------####
import math
import sys
import string
#input = sys.stdin.readline
def ri(): #Regular input
return input()
def ii(): #integer input
return int(input())
def li(): #list input
return input().split()
def mi(): #map input
return list(map(int, input().split()))
#####---------------Template Ends-------------------######
n=ii()
for i in range(1, n-1, 2):
print(("D"*i).center(n, "*"))
print("D"*n)
for i in range(n-2,0,-2):
print(("D"*i).center(n, "*"))
```
Yes
| 13,666 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n Γ n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matrix should be represented by character "*". Look at the examples to understand what you need to draw.
Input
The only line contains an integer n (3 β€ n β€ 101; n is odd).
Output
Output a crystal of size n.
Examples
Input
3
Output
*D*
DDD
*D*
Input
5
Output
**D**
*DDD*
DDDDD
*DDD*
**D**
Input
7
Output
***D***
**DDD**
*DDDDD*
DDDDDDD
*DDDDD*
**DDD**
***D***
Submitted Solution:
```
def solve():
n = int(input())
score = n // 2
lst = []
for i in range(score, -1, -1):
string = "*" * i + "D" * (n - 2*i) + "*" * i
lst.append(string)
for j in lst:
print(j)
for k in lst[1::-1]:
print(k)
solve()
```
No
| 13,667 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n Γ n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matrix should be represented by character "*". Look at the examples to understand what you need to draw.
Input
The only line contains an integer n (3 β€ n β€ 101; n is odd).
Output
Output a crystal of size n.
Examples
Input
3
Output
*D*
DDD
*D*
Input
5
Output
**D**
*DDD*
DDDDD
*DDD*
**D**
Input
7
Output
***D***
**DDD**
*DDDDD*
DDDDDDD
*DDDDD*
**DDD**
***D***
Submitted Solution:
```
n = int(input())
c = "*" *n
x = 1
mid = False
for i in range(n):
if i == (n-1)/2:
mid = True
a = c[:int((n-x)/2)+1]
b = "D"*x
print(a+b+a)
if mid == True:
x -= 2
else:
x += 2
```
No
| 13,668 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n Γ n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matrix should be represented by character "*". Look at the examples to understand what you need to draw.
Input
The only line contains an integer n (3 β€ n β€ 101; n is odd).
Output
Output a crystal of size n.
Examples
Input
3
Output
*D*
DDD
*D*
Input
5
Output
**D**
*DDD*
DDDDD
*DDD*
**D**
Input
7
Output
***D***
**DDD**
*DDDDD*
DDDDDDD
*DDDDD*
**DDD**
***D***
Submitted Solution:
```
from __future__ import print_function
print ("self")
y= input("please enter number:")
x=int(y)
count = 1
side = True
for i in range(x):
for j in range(int((x-count)/2)):
print('*',end='')
for j in range(count):
print('D',end='')
for j in range(int((x-count)/2)):
print('*',end='')
if(i!=x-1):
print("")
if(count>=x):
side =False
if(side):
count+=2
else:
count-=2
```
No
| 13,669 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n Γ n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matrix should be represented by character "*". Look at the examples to understand what you need to draw.
Input
The only line contains an integer n (3 β€ n β€ 101; n is odd).
Output
Output a crystal of size n.
Examples
Input
3
Output
*D*
DDD
*D*
Input
5
Output
**D**
*DDD*
DDDDD
*DDD*
**D**
Input
7
Output
***D***
**DDD**
*DDDDD*
DDDDDDD
*DDDDD*
**DDD**
***D***
Submitted Solution:
```
print("ok")
```
No
| 13,670 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dreamoon likes to play with sets, integers and <image>. <image> is defined as the largest positive integer that divides both a and b.
Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, <image>.
Given k and n, Dreamoon wants to make up n sets of rank k using integers from 1 to m such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum m that makes it possible and print one possible solution.
Input
The single line of the input contains two space separated integers n, k (1 β€ n β€ 10 000, 1 β€ k β€ 100).
Output
On the first line print a single integer β the minimal possible m.
On each of the next n lines print four space separated integers representing the i-th set.
Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal m, print any one of them.
Examples
Input
1 1
Output
5
1 2 3 5
Input
2 2
Output
22
2 4 6 22
14 18 10 16
Note
For the first example it's easy to see that set {1, 2, 3, 4} isn't a valid set of rank 1 since <image>.
Tags: constructive algorithms, greedy, math
Correct Solution:
```
n, k = map(int, input().split())
print(k * (6 * n - 1))
for i in range(1, n + 1):
x = (i - 1) * 6 + 1
print(k * x, end = ' ')
print(k * (x + 1), end = ' ')
print(k * (x + 2), end = ' ')
print(k * (x + 4))
```
| 13,671 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dreamoon likes to play with sets, integers and <image>. <image> is defined as the largest positive integer that divides both a and b.
Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, <image>.
Given k and n, Dreamoon wants to make up n sets of rank k using integers from 1 to m such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum m that makes it possible and print one possible solution.
Input
The single line of the input contains two space separated integers n, k (1 β€ n β€ 10 000, 1 β€ k β€ 100).
Output
On the first line print a single integer β the minimal possible m.
On each of the next n lines print four space separated integers representing the i-th set.
Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal m, print any one of them.
Examples
Input
1 1
Output
5
1 2 3 5
Input
2 2
Output
22
2 4 6 22
14 18 10 16
Note
For the first example it's easy to see that set {1, 2, 3, 4} isn't a valid set of rank 1 since <image>.
Tags: constructive algorithms, greedy, math
Correct Solution:
```
n,k=map(int,input().split())
print((6*n-1)*k)
for i in range(0,6*n,6):
print((i+1)*k,(i+2)*k,(i+3)*k,(i+5)*k)
```
| 13,672 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dreamoon likes to play with sets, integers and <image>. <image> is defined as the largest positive integer that divides both a and b.
Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, <image>.
Given k and n, Dreamoon wants to make up n sets of rank k using integers from 1 to m such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum m that makes it possible and print one possible solution.
Input
The single line of the input contains two space separated integers n, k (1 β€ n β€ 10 000, 1 β€ k β€ 100).
Output
On the first line print a single integer β the minimal possible m.
On each of the next n lines print four space separated integers representing the i-th set.
Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal m, print any one of them.
Examples
Input
1 1
Output
5
1 2 3 5
Input
2 2
Output
22
2 4 6 22
14 18 10 16
Note
For the first example it's easy to see that set {1, 2, 3, 4} isn't a valid set of rank 1 since <image>.
Tags: constructive algorithms, greedy, math
Correct Solution:
```
n,k=map(int,input().split())
print((6*n-1)*k)
maxx=-1
for i in range(0,n):
a,b,c,d=k*(6*i+1),k*(6*i+2),k*(6*i+3),k*(6*i+5)
print(a,b,c,d)
```
| 13,673 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dreamoon likes to play with sets, integers and <image>. <image> is defined as the largest positive integer that divides both a and b.
Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, <image>.
Given k and n, Dreamoon wants to make up n sets of rank k using integers from 1 to m such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum m that makes it possible and print one possible solution.
Input
The single line of the input contains two space separated integers n, k (1 β€ n β€ 10 000, 1 β€ k β€ 100).
Output
On the first line print a single integer β the minimal possible m.
On each of the next n lines print four space separated integers representing the i-th set.
Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal m, print any one of them.
Examples
Input
1 1
Output
5
1 2 3 5
Input
2 2
Output
22
2 4 6 22
14 18 10 16
Note
For the first example it's easy to see that set {1, 2, 3, 4} isn't a valid set of rank 1 since <image>.
Tags: constructive algorithms, greedy, math
Correct Solution:
```
n, k = map(int, input().split())
l = [1, 2, 3, 5]
print((6 * n - 1) * k)
for i in range(n):
for j in l:
print((6 * i + j) * k, end=' ')
print()
```
| 13,674 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dreamoon likes to play with sets, integers and <image>. <image> is defined as the largest positive integer that divides both a and b.
Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, <image>.
Given k and n, Dreamoon wants to make up n sets of rank k using integers from 1 to m such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum m that makes it possible and print one possible solution.
Input
The single line of the input contains two space separated integers n, k (1 β€ n β€ 10 000, 1 β€ k β€ 100).
Output
On the first line print a single integer β the minimal possible m.
On each of the next n lines print four space separated integers representing the i-th set.
Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal m, print any one of them.
Examples
Input
1 1
Output
5
1 2 3 5
Input
2 2
Output
22
2 4 6 22
14 18 10 16
Note
For the first example it's easy to see that set {1, 2, 3, 4} isn't a valid set of rank 1 since <image>.
Tags: constructive algorithms, greedy, math
Correct Solution:
```
a, b = map(int, input().split(' '))
print((6*a-1)*b)
for i in range(a):
print((6*i+1)*b, (6*i+2)*b, (6*i+3)*b, (6*i+5)*b)
```
| 13,675 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dreamoon likes to play with sets, integers and <image>. <image> is defined as the largest positive integer that divides both a and b.
Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, <image>.
Given k and n, Dreamoon wants to make up n sets of rank k using integers from 1 to m such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum m that makes it possible and print one possible solution.
Input
The single line of the input contains two space separated integers n, k (1 β€ n β€ 10 000, 1 β€ k β€ 100).
Output
On the first line print a single integer β the minimal possible m.
On each of the next n lines print four space separated integers representing the i-th set.
Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal m, print any one of them.
Examples
Input
1 1
Output
5
1 2 3 5
Input
2 2
Output
22
2 4 6 22
14 18 10 16
Note
For the first example it's easy to see that set {1, 2, 3, 4} isn't a valid set of rank 1 since <image>.
Tags: constructive algorithms, greedy, math
Correct Solution:
```
n, k = map(int, input().split())
print(k*(6*n-1))
for i in range (n):
print(k*(6*i+1), k * (6*i+3), k*(6*i+4), k * (6*i+5))
```
| 13,676 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dreamoon likes to play with sets, integers and <image>. <image> is defined as the largest positive integer that divides both a and b.
Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, <image>.
Given k and n, Dreamoon wants to make up n sets of rank k using integers from 1 to m such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum m that makes it possible and print one possible solution.
Input
The single line of the input contains two space separated integers n, k (1 β€ n β€ 10 000, 1 β€ k β€ 100).
Output
On the first line print a single integer β the minimal possible m.
On each of the next n lines print four space separated integers representing the i-th set.
Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal m, print any one of them.
Examples
Input
1 1
Output
5
1 2 3 5
Input
2 2
Output
22
2 4 6 22
14 18 10 16
Note
For the first example it's easy to see that set {1, 2, 3, 4} isn't a valid set of rank 1 since <image>.
Tags: constructive algorithms, greedy, math
Correct Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz/'
M=998244353
EPS=1e-6
def Ceil(a,b): return a//b+int(a%b>0)
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
n,k=value()
ans=[]
for i in range(1,2*n*4,6):
ans.append(i)
ans.append(i+1)
ans.append(i+2)
ans.append(i+4)
print(k*max(ans[:4*n]))
for i in range(n):
for j in range(4):
print(k*ans[4*i+j],end=" ")
print()
```
| 13,677 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dreamoon likes to play with sets, integers and <image>. <image> is defined as the largest positive integer that divides both a and b.
Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, <image>.
Given k and n, Dreamoon wants to make up n sets of rank k using integers from 1 to m such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum m that makes it possible and print one possible solution.
Input
The single line of the input contains two space separated integers n, k (1 β€ n β€ 10 000, 1 β€ k β€ 100).
Output
On the first line print a single integer β the minimal possible m.
On each of the next n lines print four space separated integers representing the i-th set.
Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal m, print any one of them.
Examples
Input
1 1
Output
5
1 2 3 5
Input
2 2
Output
22
2 4 6 22
14 18 10 16
Note
For the first example it's easy to see that set {1, 2, 3, 4} isn't a valid set of rank 1 since <image>.
Tags: constructive algorithms, greedy, math
Correct Solution:
```
n, k = list(map(int,input().split()))
print((6*n-1)*k)
for i in range(0, n): print((6*i+1)*k,(6*i+2)*k,(6*i+3)*k,(6*i+5)*k)
```
| 13,678 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dreamoon likes to play with sets, integers and <image>. <image> is defined as the largest positive integer that divides both a and b.
Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, <image>.
Given k and n, Dreamoon wants to make up n sets of rank k using integers from 1 to m such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum m that makes it possible and print one possible solution.
Input
The single line of the input contains two space separated integers n, k (1 β€ n β€ 10 000, 1 β€ k β€ 100).
Output
On the first line print a single integer β the minimal possible m.
On each of the next n lines print four space separated integers representing the i-th set.
Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal m, print any one of them.
Examples
Input
1 1
Output
5
1 2 3 5
Input
2 2
Output
22
2 4 6 22
14 18 10 16
Note
For the first example it's easy to see that set {1, 2, 3, 4} isn't a valid set of rank 1 since <image>.
Submitted Solution:
```
import sys
INF = 10**20
MOD = 10**9 + 7
I = lambda:list(map(int,input().split()))
from math import gcd
from math import ceil
from collections import defaultdict as dd, Counter
from bisect import bisect_left as bl, bisect_right as br
"""
Facts and Data representation
Constructive? Top bottom up down
"""
n, k = I()
ans = [[1, 2, 3, 5]]
cur = 4
add = 7
for i in range(1, n):
ok = [add, add + 2, add + 4]
while True:
r = True
for i in ok:
if gcd(i, cur) > 1:
r = False
if r:
break
cur += 2
ok.append(cur)
add += 6
cur += 2
ans.append(ok)
print((add - 2) * k)
for i in ans:
print(*[j * k for j in i])
```
Yes
| 13,679 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dreamoon likes to play with sets, integers and <image>. <image> is defined as the largest positive integer that divides both a and b.
Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, <image>.
Given k and n, Dreamoon wants to make up n sets of rank k using integers from 1 to m such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum m that makes it possible and print one possible solution.
Input
The single line of the input contains two space separated integers n, k (1 β€ n β€ 10 000, 1 β€ k β€ 100).
Output
On the first line print a single integer β the minimal possible m.
On each of the next n lines print four space separated integers representing the i-th set.
Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal m, print any one of them.
Examples
Input
1 1
Output
5
1 2 3 5
Input
2 2
Output
22
2 4 6 22
14 18 10 16
Note
For the first example it's easy to see that set {1, 2, 3, 4} isn't a valid set of rank 1 since <image>.
Submitted Solution:
```
n, k = [int(x) for x in input().split()]
print(k*((n-1)*6+5))
for i in range(n):
print(k*(6*i+1),k*(6*i+3),k*(6*i+5),k*(6*i+2))
```
Yes
| 13,680 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dreamoon likes to play with sets, integers and <image>. <image> is defined as the largest positive integer that divides both a and b.
Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, <image>.
Given k and n, Dreamoon wants to make up n sets of rank k using integers from 1 to m such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum m that makes it possible and print one possible solution.
Input
The single line of the input contains two space separated integers n, k (1 β€ n β€ 10 000, 1 β€ k β€ 100).
Output
On the first line print a single integer β the minimal possible m.
On each of the next n lines print four space separated integers representing the i-th set.
Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal m, print any one of them.
Examples
Input
1 1
Output
5
1 2 3 5
Input
2 2
Output
22
2 4 6 22
14 18 10 16
Note
For the first example it's easy to see that set {1, 2, 3, 4} isn't a valid set of rank 1 since <image>.
Submitted Solution:
```
l = input().split(" ")
n = int(l[0])
k = int(l[1])
print((6*n-1)*k)
for i in range(n):
print(str((6*i+1)*k)+" "+str((6*i+2)*k)+" "+str((6*i+3)*k)+" "+str((6*i+5)*k))
```
Yes
| 13,681 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dreamoon likes to play with sets, integers and <image>. <image> is defined as the largest positive integer that divides both a and b.
Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, <image>.
Given k and n, Dreamoon wants to make up n sets of rank k using integers from 1 to m such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum m that makes it possible and print one possible solution.
Input
The single line of the input contains two space separated integers n, k (1 β€ n β€ 10 000, 1 β€ k β€ 100).
Output
On the first line print a single integer β the minimal possible m.
On each of the next n lines print four space separated integers representing the i-th set.
Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal m, print any one of them.
Examples
Input
1 1
Output
5
1 2 3 5
Input
2 2
Output
22
2 4 6 22
14 18 10 16
Note
For the first example it's easy to see that set {1, 2, 3, 4} isn't a valid set of rank 1 since <image>.
Submitted Solution:
```
inp = input().split(' ')
def result(sets,maximum_divisor):
output = list()
output.append(str(int(maximum_divisor) * (6 * int(sets) - 1)))
for i in range(int(sets)):
output.append(str(int(maximum_divisor)* (6 * int(i) + 1)) + ' ' + str(int(maximum_divisor) * (6 * int(i) + 3)) + ' ' + str(int(maximum_divisor) * (6 * int(i) + 4)) + ' ' + str(int(maximum_divisor) * (6 * int(i) + 5)))
return output
for i in result(inp[0],inp[1]):
print(i)
```
Yes
| 13,682 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dreamoon likes to play with sets, integers and <image>. <image> is defined as the largest positive integer that divides both a and b.
Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, <image>.
Given k and n, Dreamoon wants to make up n sets of rank k using integers from 1 to m such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum m that makes it possible and print one possible solution.
Input
The single line of the input contains two space separated integers n, k (1 β€ n β€ 10 000, 1 β€ k β€ 100).
Output
On the first line print a single integer β the minimal possible m.
On each of the next n lines print four space separated integers representing the i-th set.
Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal m, print any one of them.
Examples
Input
1 1
Output
5
1 2 3 5
Input
2 2
Output
22
2 4 6 22
14 18 10 16
Note
For the first example it's easy to see that set {1, 2, 3, 4} isn't a valid set of rank 1 since <image>.
Submitted Solution:
```
import sys
INF = 10**20
MOD = 10**9 + 7
I = lambda:list(map(int,input().split()))
from math import gcd
from math import ceil
from collections import defaultdict as dd, Counter
from bisect import bisect_left as bl, bisect_right as br
"""
Facts and Data representation
Constructive? Top bottom up down
"""
n, k = I()
ans = [[1, 2, 3, 5]]
cur = 2
add = 7
for i in range(1, n):
ok = [cur, add, add + 2, add + 4]
add += 6
cur += 2
ans.append(ok)
print((add - 2) * k)
for i in ans:
print(*[j * k for j in i])
```
No
| 13,683 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dreamoon likes to play with sets, integers and <image>. <image> is defined as the largest positive integer that divides both a and b.
Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, <image>.
Given k and n, Dreamoon wants to make up n sets of rank k using integers from 1 to m such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum m that makes it possible and print one possible solution.
Input
The single line of the input contains two space separated integers n, k (1 β€ n β€ 10 000, 1 β€ k β€ 100).
Output
On the first line print a single integer β the minimal possible m.
On each of the next n lines print four space separated integers representing the i-th set.
Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal m, print any one of them.
Examples
Input
1 1
Output
5
1 2 3 5
Input
2 2
Output
22
2 4 6 22
14 18 10 16
Note
For the first example it's easy to see that set {1, 2, 3, 4} isn't a valid set of rank 1 since <image>.
Submitted Solution:
```
inp = input().split(' ')
def result(sets, maximum_divisor):
maximum_divisor = 7
sets = 9
output = list()
output.append(str(int(maximum_divisor) * (6 * int(sets) - 1)))
for i in range(int(sets)):
output.append(str(int(maximum_divisor) * (6 * int(i) + 1)) + ' ' + str(int(maximum_divisor) * (6 * int(i) + 3)) +
' ' + str(int(maximum_divisor) * (6 * int(i) + 4)) + ' ' + str(int(maximum_divisor) * (6 * int(i) + 5)))
return output
for i in result(inp[0], inp[1]):
print(i)
```
No
| 13,684 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dreamoon likes to play with sets, integers and <image>. <image> is defined as the largest positive integer that divides both a and b.
Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, <image>.
Given k and n, Dreamoon wants to make up n sets of rank k using integers from 1 to m such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum m that makes it possible and print one possible solution.
Input
The single line of the input contains two space separated integers n, k (1 β€ n β€ 10 000, 1 β€ k β€ 100).
Output
On the first line print a single integer β the minimal possible m.
On each of the next n lines print four space separated integers representing the i-th set.
Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal m, print any one of them.
Examples
Input
1 1
Output
5
1 2 3 5
Input
2 2
Output
22
2 4 6 22
14 18 10 16
Note
For the first example it's easy to see that set {1, 2, 3, 4} isn't a valid set of rank 1 since <image>.
Submitted Solution:
```
__author__ = 'neki'
import sys
import math
#sys.stdin = open("sets.in", "r")
global primes, primeDiv
def primality(limit):
global primes, primeDiv
primes = [2, 3]
primeDiv = [[], [], [], []] #according to an abstraction made: 0, 1, 2, 3 have no prime divisors
i = 4
k = 3 #we can use 1, 2 and 3, we need limit prime numbers to be absolutely sure we cannot fail
while k < limit:
primeDiv.append([])
for j in primes:
if 2*j > i:
break
if i % j == 0:
primeDiv[i].append(j)
if not primeDiv[i]:
primes.append(i)
k += 1
i += 1
def gcdPrime(a, b):
if b==0 or a==0:
return 0 #not prime
if b==1 or a==1:
return 1 #prime
if b>a:
return gcdPrime(a, b%a)
return gcdPrime(b, a%b)
def gcdPrimeSet(set, a):
result = []
if len(set) >= 4: #full set
return [x for x in set]
for i in set:
if gcdPrime(i, a) == 0:
result.append(i)
return result
words = str(input()).split()
n = int(words[0])
k = int(words[1])
primality(4*n)
#print(primes)
#print(primeDiv)
#print(gcdPrime(8, 12))
sets = []
for i in range(n):
sets.append(set())
m = 0
nEl = 0
iniSet = 0
stack = [2]
last = 2
stPointer = 0
while nEl < 4*n-1:
m = stack[stPointer]
#print(m, sets)
sw = 0
setProblems = [[] for x in sets]
for j in range(iniSet, iniSet + len(sets)):
i = j % len(sets)
setProblems[i] = gcdPrimeSet(sets[i], m)
if len(setProblems[i]) == 0:
sets[i].add(m)
last += 1
stack.append(last)
iniSet += 1
nEl += 1
sw = 1
break
if sw == 0:
for i in range(len(setProblems)):
if len(setProblems[i]) == 1 and len(primeDiv[m]) < len(primeDiv[setProblems[i][0]]):
sets[i].remove(setProblems[i][0])
sets[i].add(m)
stack.append(setProblems[i][0])
break
else:
last += 1
stack.append(last)
stPointer += 1
print(k*m)
for s in sets:
if len(s) < 4:
s.add(1)
for s in sets:
for i in range(4):
print(k*s.pop(), end=" ")
print()
```
No
| 13,685 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dreamoon likes to play with sets, integers and <image>. <image> is defined as the largest positive integer that divides both a and b.
Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, <image>.
Given k and n, Dreamoon wants to make up n sets of rank k using integers from 1 to m such that no integer is used in two different sets (of course you can leave some integers without use). Calculate the minimum m that makes it possible and print one possible solution.
Input
The single line of the input contains two space separated integers n, k (1 β€ n β€ 10 000, 1 β€ k β€ 100).
Output
On the first line print a single integer β the minimal possible m.
On each of the next n lines print four space separated integers representing the i-th set.
Neither the order of the sets nor the order of integers within a set is important. If there are multiple possible solutions with minimal m, print any one of them.
Examples
Input
1 1
Output
5
1 2 3 5
Input
2 2
Output
22
2 4 6 22
14 18 10 16
Note
For the first example it's easy to see that set {1, 2, 3, 4} isn't a valid set of rank 1 since <image>.
Submitted Solution:
```
n, k = map(int, input().split())
print(2 * (3 * n) - 1)
now = 1
for i in range(n):
print(k * 2 * (i + 1), end = ' ')
for j in range(3):
print(k * now, end = ' ')
now += 2
print()
```
No
| 13,686 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The DNA sequence for every living creature in Berland can be represented as a non-empty line consisting of lowercase Latin letters. Berland scientists found out that all the creatures evolve by stages. During one stage exactly one symbol of the DNA line is replaced by exactly two other ones. At that overall there are n permissible substitutions. The substitution ai->bici means that any one symbol ai can be replaced with two symbols bici. Every substitution could happen an unlimited number of times.
They say that two creatures with DNA sequences s1 and s2 can have a common ancestor if there exists such a DNA sequence s3 that throughout evolution it can result in s1 and s2, perhaps after a different number of stages. Your task is to find out by the given s1 and s2 whether the creatures possessing such DNA sequences can have a common ancestor. If the answer is positive, you have to find the length of the shortest sequence of the common ancestorβs DNA.
Input
The first line contains a non-empty DNA sequence s1, the second line contains a non-empty DNA sequence s2. The lengths of these lines do not exceed 50, the lines contain only lowercase Latin letters. The third line contains an integer n (0 β€ n β€ 50) β the number of permissible substitutions. Then follow n lines each of which describes a substitution in the format ai->bici. The characters ai, bi, and ci are lowercase Latin letters. Lines s1 and s2 can coincide, the list of substitutions can contain similar substitutions.
Output
If s1 and s2 cannot have a common ancestor, print -1. Otherwise print the length of the shortest sequence s3, from which s1 and s2 could have evolved.
Examples
Input
ababa
aba
2
c->ba
c->cc
Output
2
Input
ababa
aba
7
c->ba
c->cc
e->ab
z->ea
b->ba
d->dd
d->ab
Output
1
Input
ababa
aba
1
c->ba
Output
-1
Tags: dp
Correct Solution:
```
#!/usr/bin/env python3
import itertools
import collections
# Read input strings
s1 = input()
s2 = input()
# Read evolution rules, use a mapping from the 2 target characters to the source character
rules = collections.defaultdict(set)
n = int(input())
for i in range(n):
rule = input()
target = rule[-2:]
source = rule[0]
rules[target].add(source)
def substrings_of_precise_length(s, l):
# Generator for all substrings of s that are of length l
for start_pos in range(len(s)-l+1):
yield s[start_pos:start_pos+l]
def substrings_of_minimum_length(s, minlen):
# Generator for all substrings of s that are of length l or larger, in order from short to long length
return itertools.chain.from_iterable(substrings_of_precise_length(s,l) for l in range(minlen, len(s)+1))
def partitions_of_string(s):
# Generator for all possible pairs (a,b) such that a+b = c where a and b are not empty strings
for l1 in range(1, len(s)):
yield (s[:l1], s[l1:])
# Dictionary mapping strings onto the set of single characters from which those strings could evolve
ancestors = collections.defaultdict(set)
def update_ancestors(ancestors, rules, s):
# Update the ancestor dictionary for string s
# O(len(s)**3 * len(rules))
# All single characters can "evolve" from a single character
for c in s:
ancestors[c].add(c)
# Examine all substrings of s, in order of increasing length
for sub in substrings_of_minimum_length(s, 2):
# Examine any way the substring can be created from two seperate, smaller strings
for (sub1, sub2) in partitions_of_string(sub):
# Check all rules to see if the two substrings can evolve from a single character by using that rule
for target, sources in rules.items():
if (target[0] in ancestors[sub1]) and (target[1] in ancestors[sub2]):
ancestors[sub].update(sources)
# Update the ancestors based on s1 and s2
update_ancestors(ancestors, rules, s1)
update_ancestors(ancestors, rules, s2)
def prefixes(s):
# Generator for all non-empty prefixes of s, in order of increasing length
for l in range(1, len(s)+1):
yield s[:l]
def determine_shortest_common_ancestor(ancestors, s1, s2):
# Returns the length of the shortest common ancestor of string s1 and s2, or float('inf') if there is no common ancestor.
# The ancestors is a dictionary that contains for every substring of s1 and s2 the set of single characters from which that substring can evolve
# O(len(s1)**2 * len(s2)**2 * 26 )
# Dictionary mapping pairs of strings onto the length of their shortest common ancestor
shortest_common_ancestor = collections.defaultdict(lambda:float('inf'))
# Check every possible combinations of prefixes of s1 and s2
for (pre1,pre2) in itertools.product(prefixes(s1), prefixes(s2)):
# If both prefixes have an overlap in the single character from which they can evolve, then the shortest common ancestor is 1 letter
if not ancestors[pre1].isdisjoint(ancestors[pre2]):
shortest_common_ancestor[(pre1,pre2)] = 1
# Check all possible combinations of partitions of pre1 and pre2
temp = shortest_common_ancestor[(pre1, pre2)]
for ((sub1a,sub1b),(sub2a,sub2b)) in itertools.product(partitions_of_string(pre1), partitions_of_string(pre2)):
if not ancestors[sub1b].isdisjoint(ancestors[sub2b]):
# sub1b and sub2b can evolve from the same character, so the shortest common ancestor of sub1a+sub1b and sub2a+sub2b is
# never longer than the shortest common ancestor of sub1a and sub2a plus the one letter from which sub1b and sub2b can evolve
temp = min(temp, shortest_common_ancestor[(sub1a, sub2a)] + 1)
shortest_common_ancestor[(pre1, pre2)] = temp
return shortest_common_ancestor[(s1, s2)]
answer = determine_shortest_common_ancestor(ancestors, s1, s2)
if (answer == float('inf')):
print(-1)
else:
print(answer)
```
| 13,687 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The DNA sequence for every living creature in Berland can be represented as a non-empty line consisting of lowercase Latin letters. Berland scientists found out that all the creatures evolve by stages. During one stage exactly one symbol of the DNA line is replaced by exactly two other ones. At that overall there are n permissible substitutions. The substitution ai->bici means that any one symbol ai can be replaced with two symbols bici. Every substitution could happen an unlimited number of times.
They say that two creatures with DNA sequences s1 and s2 can have a common ancestor if there exists such a DNA sequence s3 that throughout evolution it can result in s1 and s2, perhaps after a different number of stages. Your task is to find out by the given s1 and s2 whether the creatures possessing such DNA sequences can have a common ancestor. If the answer is positive, you have to find the length of the shortest sequence of the common ancestorβs DNA.
Input
The first line contains a non-empty DNA sequence s1, the second line contains a non-empty DNA sequence s2. The lengths of these lines do not exceed 50, the lines contain only lowercase Latin letters. The third line contains an integer n (0 β€ n β€ 50) β the number of permissible substitutions. Then follow n lines each of which describes a substitution in the format ai->bici. The characters ai, bi, and ci are lowercase Latin letters. Lines s1 and s2 can coincide, the list of substitutions can contain similar substitutions.
Output
If s1 and s2 cannot have a common ancestor, print -1. Otherwise print the length of the shortest sequence s3, from which s1 and s2 could have evolved.
Examples
Input
ababa
aba
2
c->ba
c->cc
Output
2
Input
ababa
aba
7
c->ba
c->cc
e->ab
z->ea
b->ba
d->dd
d->ab
Output
1
Input
ababa
aba
1
c->ba
Output
-1
Submitted Solution:
```
#!/usr/bin/env python3
import itertools
import collections
s1 = input().strip()
s2 = input().strip()
n = int(input())
rules = collections.defaultdict(set)
for i in range(n):
rule = input().strip()
target = rule[-2:]
source = rule[0]
rules[target].add(source)
def get_shortest_ancestors(rules, s):
# Create tables for the shortest possible ancestors. Indices are based on, respectively, substring length and starting position in the original string s
ancestor_length = [[l for start_pos in range(len(s)-l+1)] for l in range(len(s)+1)]
ancestor_set = [[set([s[start_pos:start_pos+l]]) for start_pos in range(len(s)-l+1)] for l in range(len(s)+1)]
# Fill in the tables for substrings of length 2 and higher
for l in range(2,len(s)+1):
for start_pos in range(len(s)-l+1):
# Check all possible ways in which the substring s[start_pos:start_pos+l] can be made from two shorter substrings
for l1 in range(1, l):
# Combine shortest possible ancestors of the two substrings s[start_pos:start_pos+l1] and ss[start_pos+l1:start_pos+l] to get the ancestors of s[start_pos:start_pos+l]
ancestors = set()
for (a,b) in itertools.product(ancestor_set[l1][start_pos], ancestor_set[l-l1][start_pos+l1]):
if (a[-1]+b[0]) in rules.keys():
# The end of one ancestor and the start of the other ancestor can be created from one or more rules
for source in rules[a[-1]+b[0]]:
# Add all ancestors that can be created by using the available rules, note: these will always be shorter than simply combining ancestors
ancestors.add(a[:-1]+source+b[1:])
else:
# Simply combine the two ancestors
ancestors.add(a+b)
# Use the new set of ancestors to update te table
ancestor_length[l][start_pos] = min(min(len(a) for a in ancestors), ancestor_length[l][start_pos])
ancestor_set[l][start_pos] = set(a for a in ancestors.union(ancestor_set[l][start_pos]) if len(a) == ancestor_length[l][start_pos])
return ancestor_set[len(s)][0]
shortest_ancestors_s1 = get_shortest_ancestors(rules, s1)
shortest_ancestors_s2 = get_shortest_ancestors(rules, s2)
if (shortest_ancestors_s1.isdisjoint(shortest_ancestors_s2)):
print(-1)
else:
print(len(list(shortest_ancestors_s1)[0]))
```
No
| 13,688 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i Γ j. The rows and columns are numbered starting from 1.
You are given a positive integer x. Your task is to count the number of cells in a table that contain number x.
Input
The single line contains numbers n and x (1 β€ n β€ 105, 1 β€ x β€ 109) β the size of the table and the number that we are looking for in the table.
Output
Print a single number: the number of times x occurs in the table.
Examples
Input
10 5
Output
2
Input
6 12
Output
4
Input
5 13
Output
0
Note
A table for the second sample test is given below. The occurrences of number 12 are marked bold.
<image>
Tags: implementation, number theory
Correct Solution:
```
size,n=map(int,input().split())
count=0
for i in range(1, size+1):
if n%i==0 and n<=size*i:
count=count+1
print(count)
```
| 13,689 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i Γ j. The rows and columns are numbered starting from 1.
You are given a positive integer x. Your task is to count the number of cells in a table that contain number x.
Input
The single line contains numbers n and x (1 β€ n β€ 105, 1 β€ x β€ 109) β the size of the table and the number that we are looking for in the table.
Output
Print a single number: the number of times x occurs in the table.
Examples
Input
10 5
Output
2
Input
6 12
Output
4
Input
5 13
Output
0
Note
A table for the second sample test is given below. The occurrences of number 12 are marked bold.
<image>
Tags: implementation, number theory
Correct Solution:
```
import sys
import itertools
import math
import collections
from collections import Counter
#########################
# imgur.com/Pkt7iIf.png #
#########################
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 * 2, n + 1, p):
prime[i] = False
p += 1
prime[0] = prime[1] = False
r = [p for p in range(n + 1) if prime[p]]
return r
def divs(n, start=1):
r = []
for i in range(start, int(math.sqrt(n) + 1)):
if (n % i == 0):
if (n / i == i):
r.append(i)
else:
r.extend([i, n // i])
return r
def ceil(n, k): return n // k + (n % k != 0)
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return list(map(int, input().split()))
def lcm(a, b): return abs(a * b) // math.gcd(a, b)
def prr(a, sep=' '): print(sep.join(map(str, a)))
def dd(): return collections.defaultdict(int)
n, x = mi()
print(len([i for i in divs(x) if i <= n and x // i <= n]))
```
| 13,690 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i Γ j. The rows and columns are numbered starting from 1.
You are given a positive integer x. Your task is to count the number of cells in a table that contain number x.
Input
The single line contains numbers n and x (1 β€ n β€ 105, 1 β€ x β€ 109) β the size of the table and the number that we are looking for in the table.
Output
Print a single number: the number of times x occurs in the table.
Examples
Input
10 5
Output
2
Input
6 12
Output
4
Input
5 13
Output
0
Note
A table for the second sample test is given below. The occurrences of number 12 are marked bold.
<image>
Tags: implementation, number theory
Correct Solution:
```
n,x=input().split(" ")
n=int(n)
x=int(x)
count = 0
for i in range(1,n+1):
if x%i==0 and x/i<=n:
count = count+1
print(count)
```
| 13,691 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i Γ j. The rows and columns are numbered starting from 1.
You are given a positive integer x. Your task is to count the number of cells in a table that contain number x.
Input
The single line contains numbers n and x (1 β€ n β€ 105, 1 β€ x β€ 109) β the size of the table and the number that we are looking for in the table.
Output
Print a single number: the number of times x occurs in the table.
Examples
Input
10 5
Output
2
Input
6 12
Output
4
Input
5 13
Output
0
Note
A table for the second sample test is given below. The occurrences of number 12 are marked bold.
<image>
Tags: implementation, number theory
Correct Solution:
```
n, x = (int(y) for y in input().split())
count = 0
for i in range(1, n + 1):
div = x / i
if div == int(div) and div >= 1 and div <= n:
count += 1
print(count)
```
| 13,692 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i Γ j. The rows and columns are numbered starting from 1.
You are given a positive integer x. Your task is to count the number of cells in a table that contain number x.
Input
The single line contains numbers n and x (1 β€ n β€ 105, 1 β€ x β€ 109) β the size of the table and the number that we are looking for in the table.
Output
Print a single number: the number of times x occurs in the table.
Examples
Input
10 5
Output
2
Input
6 12
Output
4
Input
5 13
Output
0
Note
A table for the second sample test is given below. The occurrences of number 12 are marked bold.
<image>
Tags: implementation, number theory
Correct Solution:
```
from math import sqrt
n,x=map(int,input().split())
c=0
y=sqrt(x)
for i in range(1,int(y)+1):
if x%i==0 and x//i<=n:
if i!=y:
c+=2
else:
c+=1
print(c)
```
| 13,693 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i Γ j. The rows and columns are numbered starting from 1.
You are given a positive integer x. Your task is to count the number of cells in a table that contain number x.
Input
The single line contains numbers n and x (1 β€ n β€ 105, 1 β€ x β€ 109) β the size of the table and the number that we are looking for in the table.
Output
Print a single number: the number of times x occurs in the table.
Examples
Input
10 5
Output
2
Input
6 12
Output
4
Input
5 13
Output
0
Note
A table for the second sample test is given below. The occurrences of number 12 are marked bold.
<image>
Tags: implementation, number theory
Correct Solution:
```
n,x=map(int,input().split())
a=0
for i in range(1,n+1):
if x/i==x//i and x//i<=n:
a=a+1
print(a)
```
| 13,694 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i Γ j. The rows and columns are numbered starting from 1.
You are given a positive integer x. Your task is to count the number of cells in a table that contain number x.
Input
The single line contains numbers n and x (1 β€ n β€ 105, 1 β€ x β€ 109) β the size of the table and the number that we are looking for in the table.
Output
Print a single number: the number of times x occurs in the table.
Examples
Input
10 5
Output
2
Input
6 12
Output
4
Input
5 13
Output
0
Note
A table for the second sample test is given below. The occurrences of number 12 are marked bold.
<image>
Tags: implementation, number theory
Correct Solution:
```
a,b=map(int,input().split())
ans=0
for i in range(1,a+1):
if b%i==0:
if b//i<=a:
ans+=1
print(ans)
```
| 13,695 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i Γ j. The rows and columns are numbered starting from 1.
You are given a positive integer x. Your task is to count the number of cells in a table that contain number x.
Input
The single line contains numbers n and x (1 β€ n β€ 105, 1 β€ x β€ 109) β the size of the table and the number that we are looking for in the table.
Output
Print a single number: the number of times x occurs in the table.
Examples
Input
10 5
Output
2
Input
6 12
Output
4
Input
5 13
Output
0
Note
A table for the second sample test is given below. The occurrences of number 12 are marked bold.
<image>
Tags: implementation, number theory
Correct Solution:
```
n, x = map(int, input().split())
print(sum(x % i == 0 and x<=n*i for i in range(1, n + 1)))
```
| 13,696 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i Γ j. The rows and columns are numbered starting from 1.
You are given a positive integer x. Your task is to count the number of cells in a table that contain number x.
Input
The single line contains numbers n and x (1 β€ n β€ 105, 1 β€ x β€ 109) β the size of the table and the number that we are looking for in the table.
Output
Print a single number: the number of times x occurs in the table.
Examples
Input
10 5
Output
2
Input
6 12
Output
4
Input
5 13
Output
0
Note
A table for the second sample test is given below. The occurrences of number 12 are marked bold.
<image>
Submitted Solution:
```
data = [int(n) for n in input().split()]
n = data[0]
x = data[1]
ans = 0
for i in range(2, n + 1):
if x % i == 0 and x <= i * n:
ans += 1
if (n >= x):
ans += 1
print(ans)
```
Yes
| 13,697 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i Γ j. The rows and columns are numbered starting from 1.
You are given a positive integer x. Your task is to count the number of cells in a table that contain number x.
Input
The single line contains numbers n and x (1 β€ n β€ 105, 1 β€ x β€ 109) β the size of the table and the number that we are looking for in the table.
Output
Print a single number: the number of times x occurs in the table.
Examples
Input
10 5
Output
2
Input
6 12
Output
4
Input
5 13
Output
0
Note
A table for the second sample test is given below. The occurrences of number 12 are marked bold.
<image>
Submitted Solution:
```
if __name__ == '__main__':
n, x = [int(__) for __ in input().strip().split()]
ans = 0
for i in range(1, n + 1):
if x % i == 0 and i * n >= x:
ans += 1
print(ans)
```
Yes
| 13,698 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i Γ j. The rows and columns are numbered starting from 1.
You are given a positive integer x. Your task is to count the number of cells in a table that contain number x.
Input
The single line contains numbers n and x (1 β€ n β€ 105, 1 β€ x β€ 109) β the size of the table and the number that we are looking for in the table.
Output
Print a single number: the number of times x occurs in the table.
Examples
Input
10 5
Output
2
Input
6 12
Output
4
Input
5 13
Output
0
Note
A table for the second sample test is given below. The occurrences of number 12 are marked bold.
<image>
Submitted Solution:
```
# Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number iβΓβj. The rows and columns are numbered starting from 1.
# You are given a positive integer x. Your task is to count the number of cells in a table that contain number x.
# Input
# The single line contains numbers n and x (1ββ€βnββ€β105, 1ββ€βxββ€β109) β the size of the table and the number that we are looking for in the table.
# Output
# Print a single number: the number of times x occurs in the table.
# Examples
# inputCopy
# 10 5
# outputCopy
# 2
# inputCopy
# 6 12
# outputCopy
# 4
# inputCopy
# 5 13
# outputCopy
# 0
# Note
# A table for the second sample test is given below. The occurrences of number 12 are marked bold.
n,x = [int(i) for i in input().split()]
# n = 5
# x = 13
res = 0
for i in range(1,n+1):
if x%i==0 and x//i<n+1:
res+=1
print(res)
```
Yes
| 13,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.