text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree of size n is an undirected connected graph consisting of n vertices without cycles.
Consider some tree with n vertices. We call a tree invariant relative to permutation p = p1p2... pn, if for any two vertices of the tree u and v the condition holds: "vertices u and v are connected by an edge if and only if vertices pu and pv are connected by an edge".
You are given permutation p of size n. Find some tree size n, invariant relative to the given permutation.
Input
The first line contains number n (1 β€ n β€ 105) β the size of the permutation (also equal to the size of the sought tree).
The second line contains permutation pi (1 β€ pi β€ n).
Output
If the sought tree does not exist, print "NO" (without the quotes).
Otherwise, print "YES", and then print n - 1 lines, each of which contains two integers β the numbers of vertices connected by an edge of the tree you found. The vertices are numbered from 1, the order of the edges and the order of the vertices within the edges does not matter.
If there are multiple solutions, output any of them.
Examples
Input
4
4 3 2 1
Output
YES
4 1
4 2
1 3
Input
3
3 1 2
Output
NO
Note
In the first sample test a permutation transforms edge (4, 1) into edge (1, 4), edge (4, 2) into edge (1, 3) and edge (1, 3) into edge (4, 2). These edges all appear in the resulting tree.
It can be shown that in the second sample test no tree satisfies the given condition.
Submitted Solution:
```
n = int(input())
permu = list(map(int,input().split()))
Type = 0
det = 0
Ind = -1
for i in range(n):
if(permu[i]-1==i):
det+=1
Ind=i
if(det==1):
Type=1
if(Type==0):
for i in range(n):
if(permu[permu[i]-1]-1==i):
Ind=i
Type=2
if(Type==0):
print("NO")
elif(Type==1):
print("YES")
for i in range(n):
if(i!=Ind):
print(str(i+1)+' '+str(Ind+1))
elif(n%2==1):
print("NO")
else:
print("YES")
a,b=Ind,permu[Ind]-1
t=1
for i in range(n):
if(i!=a and i!=b):
if(t>0):
print(str(i+1)+' '+str(a+1))
t=-t
else:
print(str(i+1)+' '+str(b+1))
t=-t
print(str(a+1)+' '+str(b+1))
```
No
| 107,400 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Given simple (without self-intersections) n-gon. It is not necessary convex. Also you are given m lines. For each line find the length of common part of the line and the n-gon.
The boundary of n-gon belongs to polygon. It is possible that n-gon contains 180-degree angles.
Input
The first line contains integers n and m (3 β€ n β€ 1000;1 β€ m β€ 100). The following n lines contain coordinates of polygon vertices (in clockwise or counterclockwise direction). All vertices are distinct.
The following m lines contain line descriptions. Each of them contains two distict points of a line by their coordinates.
All given in the input coordinates are real numbers, given with at most two digits after decimal point. They do not exceed 105 by absolute values.
Output
Print m lines, the i-th line should contain the length of common part of the given n-gon and the i-th line. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
Examples
Input
4 3
0 0
1 0
1 1
0 1
0 0 1 1
0 0 0 1
0 0 1 -1
Output
1.41421356237309514547
1.00000000000000000000
0.00000000000000000000
Tags: geometry
Correct Solution:
```
def main():
from math import hypot
n, m = map(int, input().split())
vertices = list(tuple(map(float, input().split())) for _ in range(n))
ax, ay = vertices[-1]
for i, (bx, by) in enumerate(vertices):
vertices[i], ax, ay = (bx, by, bx - ax, by - ay), bx, by
for _ in range(m):
x0, y0, x1, y1 = map(float, input().split())
x1 -= x0
y1 -= y0
bx, by = vertices[-1][:2]
tmp = (bx - x0) * y1 - (by - y0) * x1
t = -1 if tmp < 0 else 1 if tmp > 0 else 0
res = []
for bx, by, abx, aby in vertices:
s, tmp = t, (bx - x0) * y1 - (by - y0) * x1
t = -1 if tmp < 0 else 1 if tmp > 0 else 0
if s != t:
res.append((((bx - x0) * aby - (by - y0) * abx) / (x1 * aby - y1 * abx), s - t))
res.sort()
t, w = 0, 0.
for i, (tmp, s) in enumerate(res, -1):
if t:
w += tmp - res[i][0]
t += s
print(w * hypot(x1, y1))
if __name__ == '__main__':
main()
```
| 107,401 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Given simple (without self-intersections) n-gon. It is not necessary convex. Also you are given m lines. For each line find the length of common part of the line and the n-gon.
The boundary of n-gon belongs to polygon. It is possible that n-gon contains 180-degree angles.
Input
The first line contains integers n and m (3 β€ n β€ 1000;1 β€ m β€ 100). The following n lines contain coordinates of polygon vertices (in clockwise or counterclockwise direction). All vertices are distinct.
The following m lines contain line descriptions. Each of them contains two distict points of a line by their coordinates.
All given in the input coordinates are real numbers, given with at most two digits after decimal point. They do not exceed 105 by absolute values.
Output
Print m lines, the i-th line should contain the length of common part of the given n-gon and the i-th line. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
Examples
Input
4 3
0 0
1 0
1 1
0 1
0 0 1 1
0 0 0 1
0 0 1 -1
Output
1.41421356237309514547
1.00000000000000000000
0.00000000000000000000
Tags: geometry
Correct Solution:
```
import math
eps = 1e-9
def sign(n):
if n > eps: return 1
if n < -eps: return -1
return 0
def cross(a, b):
return a.x * b.y - a.y * b.x
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, v):
return Vector(self.x + v.x, self.y + v.y)
def __sub__(self, v):
return Vector(self.x - v.x, self.y - v.y)
def length(self):
return math.hypot(self.x, self.y)
def solve(polygon, p, q):
intersections = []
for (a, b) in zip(polygon, polygon[1:] + polygon[:1]):
ss = sign(cross(a - p, q - p))
es = sign(cross(b - p, q - p))
if ss == es: continue
t = cross(a - p, a - b) / cross(q - p, a - b)
intersections.append((t, es - ss))
intersections = sorted(intersections)
total_t, previous_t, count = [0] * 3
for t, order in intersections:
if (count > 0): total_t += t - previous_t
previous_t = t
count += order
# print(total_t)
print(total_t * (q - p).length())
n, m = map(int, input().split())
polygon = []
for i in range(n):
x, y = map(float, input().split())
polygon.append(Vector(x, y))
area = sum(map(lambda x: cross(x[0], x[1]), zip(polygon, polygon[1:] + polygon[:1])))
if (area < 0): polygon.reverse()
for i in range(m):
x1, y1, x2, y2 = map(float, input().split())
solve(polygon, Vector(x1, y1), Vector(x2, y2))
```
| 107,402 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given simple (without self-intersections) n-gon. It is not necessary convex. Also you are given m lines. For each line find the length of common part of the line and the n-gon.
The boundary of n-gon belongs to polygon. It is possible that n-gon contains 180-degree angles.
Input
The first line contains integers n and m (3 β€ n β€ 1000;1 β€ m β€ 100). The following n lines contain coordinates of polygon vertices (in clockwise or counterclockwise direction). All vertices are distinct.
The following m lines contain line descriptions. Each of them contains two distict points of a line by their coordinates.
All given in the input coordinates are real numbers, given with at most two digits after decimal point. They do not exceed 105 by absolute values.
Output
Print m lines, the i-th line should contain the length of common part of the given n-gon and the i-th line. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
Examples
Input
4 3
0 0
1 0
1 1
0 1
0 0 1 1
0 0 0 1
0 0 1 -1
Output
1.41421356237309514547
1.00000000000000000000
0.00000000000000000000
Submitted Solution:
```
from math import fsum, hypot
def main():
n, m = map(int, input().split())
ax = ay = 0
segments = []
myint = lambda s: int(float(s) * 1e2 + .1)
for _ in range(n):
bx, by = map(myint, input().split())
segments.append((ax, ay, bx, by))
ax, ay = bx, by
_, _, bx, by = segments[0]
segments[0] = (ax, ay, bx, by)
for _ in range(m):
l = []
cx, cy, dx, dy = map(myint, input().split())
linex, liney = dx - cx, dy - cy
for ax, ay, bx, by in segments:
segx, segy = bx - ax, by - ay
den = liney * segx - linex * segy
if den:
nom = (ay - cy) * linex - (ax - cx) * liney
t = nom / den
u, v = ax + segx * t, ay + segy * t
if ax <= u <= bx and ay <= v <= by or bx <= u <= ax and by <= v <= bx:
l.append((u, v))
else:
if segx * (cy - ay) == segy * (cx - ax):
l.append((ax, ay))
l.append((bx, by))
res = []
for (bx, by), (ax, ay) in zip(l[::2], l[1::2]):
res.append(hypot(bx - ax, by - ay))
print(fsum(res) * .01)
print()
if __name__ == '__main__':
main()
```
No
| 107,403 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given simple (without self-intersections) n-gon. It is not necessary convex. Also you are given m lines. For each line find the length of common part of the line and the n-gon.
The boundary of n-gon belongs to polygon. It is possible that n-gon contains 180-degree angles.
Input
The first line contains integers n and m (3 β€ n β€ 1000;1 β€ m β€ 100). The following n lines contain coordinates of polygon vertices (in clockwise or counterclockwise direction). All vertices are distinct.
The following m lines contain line descriptions. Each of them contains two distict points of a line by their coordinates.
All given in the input coordinates are real numbers, given with at most two digits after decimal point. They do not exceed 105 by absolute values.
Output
Print m lines, the i-th line should contain the length of common part of the given n-gon and the i-th line. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
Examples
Input
4 3
0 0
1 0
1 1
0 1
0 0 1 1
0 0 0 1
0 0 1 -1
Output
1.41421356237309514547
1.00000000000000000000
0.00000000000000000000
Submitted Solution:
```
import sys
# sys.stdin = open('ivo.in')
EPSYLON = 1e-9
def sign(x):
if x > EPSYLON:
return 1
if x < -EPSYLON:
return -1
return 0
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def dist2(self, point):
return (self.x - point.x) * (self.x - point.x) + (self.y - point.y) * (self.y - point.y)
def dist(self, point):
return self.dist2(point) ** 0.5
def area(a, b, c):
return a.x * b.y + b.x * c.y + c.x * a.y - a.y * b.x - b.y * c.x - c.y * a.x
class Line:
def __init__(self, A, B, C):
self.A = A
self.B = B
self.C = C
def __init__(self, a, b):
self.A = a.y - b.y
self.B = b.x - a.x
self.C = a.x * b.y - a.y * b.x
def has(self, p):
return sign(self.A * p.x + self.B * p.y + self.C) == 0
def intersect(a, b):
denom = b.A * a.B - a.A * b.B
if sign(denom) == 0:
return False
x = (a.C * b.B - b.C * a.B) / denom
y = (b.C * a.A - a.C * b.A) / denom
return Point(x, y)
class Segment:
def __init__(self, a, b):
self.a = a
self.b = b
def get(self, p):
if sign(self.a.x - self.b.x) == 0:
return (p.y - self.b.y) / (self.a.y - self.b.y)
else:
return (p.x - self.b.x) / (self.a.x - self.b.x)
n, m = map(int, sys.stdin.readline().split())
poly = []
for i in range(n):
x, y = map(float, sys.stdin.readline().split())
if i > 2 and sign(area(poly[-2], poly[-1], Point(x, y))) == 0:
continue
poly.append(Point(x, y))
lines = []
for i in range(m):
x1, y1, x2, y2 = map(float, sys.stdin.readline().split())
lines.append(Line(Point(x1, y1), Point(x2, y2)))
n = len(poly)
for l in lines:
intersections = []
for i in range(n):
if l.has(poly[i]) and l.has(poly[(i + 1) % n]):
intersections.append(poly[i])
continue
s = Segment(poly[i], poly[(i + 1) % n])
line = Line(s.a, s.b)
p = intersect(line, l)
if not p:
continue
r = s.get(p)
if sign(r) <= 0 or sign(r - 1) > 0:
continue
intersections.append(p)
intersections.sort(key=lambda x:(x.x, x.y))
sum = 0.0
for i in range(0, len(intersections) - 1, 2):
if i + 1 < len(intersections):
sum += intersections[i].dist(intersections[i + 1])
print(sum)
```
No
| 107,404 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given simple (without self-intersections) n-gon. It is not necessary convex. Also you are given m lines. For each line find the length of common part of the line and the n-gon.
The boundary of n-gon belongs to polygon. It is possible that n-gon contains 180-degree angles.
Input
The first line contains integers n and m (3 β€ n β€ 1000;1 β€ m β€ 100). The following n lines contain coordinates of polygon vertices (in clockwise or counterclockwise direction). All vertices are distinct.
The following m lines contain line descriptions. Each of them contains two distict points of a line by their coordinates.
All given in the input coordinates are real numbers, given with at most two digits after decimal point. They do not exceed 105 by absolute values.
Output
Print m lines, the i-th line should contain the length of common part of the given n-gon and the i-th line. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
Examples
Input
4 3
0 0
1 0
1 1
0 1
0 0 1 1
0 0 0 1
0 0 1 -1
Output
1.41421356237309514547
1.00000000000000000000
0.00000000000000000000
Submitted Solution:
```
from math import *
class pvs:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return pvs(self.x + other.x, self.y + other.y)
def __iadd__(self, other):
self.x += other.x
self.y += other.y
return self
def __sub__(self, other):
return pvs(self.x - other.x, self.y - other.y)
def __isub__(self, other):
self.x -= other.x
self.y -= other.y
return self
def __neg__(self):
return pvs(-self.x, -self.y)
def __abs__(self):
return sqrt(self.x * self.x + self.y * self.y)
def __mul__(self, other):
return pvs(self.x * other, self.y * other)
def __rmul__(self, other):
return self * other
def __imul__(self, other):
self.x *= other
self.y *= other
return self
def __truediv__(self, other):
return pvs(self.x / other, self.y / other)
def __idiv__(self, other):
self.x /= other
self.y /= other
return self
def __pow__(self, other):
""" cos """
return self.x * other.x + self.y * other.y
def __xor__(self, other):
""" sin """
return self.x * other.y - other.x * self.y
def __eq__(self, other):
if type(self) is type(other):
return self.x == other.x \
and self.y == other.y
return False
def __str__(self):
return '{}:{}'.format(self.x, self.y)
def copy(self):
return pvs(self.x, self.y)
class line:
def __init__(self, *args):
if len(args) == 0:
self.point = pvs(0, 0)
self.vector = pvs(1, 0)
return
if len(args) == 1 and type(args[0]) is line:
self.point = args[0].point.copy()
self.vector = args[0].vector.copy()
return
if len(args) == 2 and all(type(arg) is pvs for arg in args):
self.point = args[0].copy()
self.vector = args[1].copy()
return
if len(args) == 3:
a, b, c = args
if a != 0 and b != 0:
self.point = pvs(-c / a, 0)
self.vector = pvs(c / a, -c / b)
elif a == 0:
self.point = pvs(0, -c / b)
self.vector = pvs(1, 0)
else:
self.point = pvs(-c / a, 0)
self.vector = pvs(0, 1)
return
exit('line.__init__:\n\tline not constructed!\n\targs : {}'.format(' '.join(*map(str, args))))
def rand(self):
self.point -= self.vector * (2**(1/2))
def __str__(self):
return '{} {}'.format(self.point, self.vector)
def side(self, p):
return self.vector ^ (p - self.point)
def include_(self, p: pvs):
return (p - self.point) ^ self.vector == 0
def copy(self):
return line(self.point.copy(), self.vector.copy())
class segment:
def __init__(self, a: pvs, b: pvs):
self.a = a
self.b = b
def __len__(self):
return abs(self.b - self.a)
def copy(self):
return segment(self.a.copy(), self.b.copy())
def angle_test(m):
ans = 0
MOD = 2*pi
for i in range(len(m)):
ans += (
atan2(m[i - 1].y - m[i - 2].y, m[i - 1].x - m[i - 2].x) -
atan2(m[i].y - m[i - 1].y, m[i].x - m[i - 1].x) + MOD
) % MOD
return ans
class rectangle:
def __init__(self, m):
if not all(type(el) is pvs for el in m):
exit("rectangle.__init__:\n\tValueError")
self.m = []
for i in range(len(m)):
if (m[i - 2] - m[i - 1]) ^ (m[i - 1] - m[i]):
self.m.append(m[i - 1])
if angle_test(self.m) < 0:
self.m.reverse()
def line_key(vect: pvs):
def take_x(self):
return self.x
def take_y(self):
return self.y
return take_x if abs(vect.y) < abs(vect.x) else take_y
class __intersectoin:
def __init__(self, rect: rectangle, ln: line):
last_V = rect.m[-2]
q_Int = rect.m[-1] if ln.include_(rect.m[-1]) else None
ans = []
for i in range(len(rect.m)):
it = intersectoin(ln, segment(rect.m[i - 1], rect.m[i]))
if it is not None:
# (m[i - 2] - m[i - 1]) ^ (m[i - 1] - m[i])
if it == "||":
continue
if q_Int is None:
if ln.include_(rect.m[i]):
q_Int = rect.m[i]
else:
ans.append(it)
else:
if q_Int == rect.m[i-1]:
if ln.side(rect.m[i]) * ln.side(last_V) < 0:
ans.append(it)
else:
if (q_Int - last_V) ^ (rect.m[i - 1] - q_Int) > 0:
ans.append(q_Int)
if (rect.m[i-1] - q_Int) ^ (rect.m[i] - rect.m[i-1]) > 0:
ans.append(rect.m[i-1])
q_Int = None
last_V = rect.m[i - 1]
ans.sort(key=line_key(ln.vector))
self.ans = ans
def size(self):
print(*self.ans)
ans = 0
for p1, p2 in zip(self.ans[::2], self.ans[1::2]):
ans += abs(p1 - p2)
return ans
def intersectoin(a, b):
if type(a) is line and type(b) is line:
p = b.point - a.point
k2 = (a.vector ^ p) / (a.vector ^ b.vector)
return b.point - (k2 * b.vector)
if type(a) is segment and type(b) is line:
a, b = b, a
if type(a) is line and type(b) is segment:
ans = (a.vector ^ (b.a - a.point)), (a.vector ^ (b.b - a.point))
if ans[0] == 0 and ans[1] == 0:
return "||"
ans = ans[0]*ans[1]
if ans <= 0:
return intersectoin(a, line(b.a, b.a - b.b))
else:
return None
if type(a) is rectangle and type(b) is line:
return __intersectoin(a, b)
exit("cant intersect {} and {}".format(type(a), type(b)))
def main():
n, t = map(int, input().split())
rect = rectangle([pvs(*map(float, input().split())) for i in range(n)])
for i in range(t):
x1, y1, x2, y2 = map(float, input().split())
p1, p2 = pvs(x1, y1), pvs(x2, y2)
ln = line(p1, p2 - p1)
ln.rand()
print(intersectoin(rect, ln).size())
if __name__ == '__main__':
main()
```
No
| 107,405 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given simple (without self-intersections) n-gon. It is not necessary convex. Also you are given m lines. For each line find the length of common part of the line and the n-gon.
The boundary of n-gon belongs to polygon. It is possible that n-gon contains 180-degree angles.
Input
The first line contains integers n and m (3 β€ n β€ 1000;1 β€ m β€ 100). The following n lines contain coordinates of polygon vertices (in clockwise or counterclockwise direction). All vertices are distinct.
The following m lines contain line descriptions. Each of them contains two distict points of a line by their coordinates.
All given in the input coordinates are real numbers, given with at most two digits after decimal point. They do not exceed 105 by absolute values.
Output
Print m lines, the i-th line should contain the length of common part of the given n-gon and the i-th line. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
Examples
Input
4 3
0 0
1 0
1 1
0 1
0 0 1 1
0 0 0 1
0 0 1 -1
Output
1.41421356237309514547
1.00000000000000000000
0.00000000000000000000
Submitted Solution:
```
from collections import deque
from itertools import combinations
from math import fsum, hypot
def myint(s):
return int(float(s) * 100. + 1e-6)
def main():
n, m = map(int, input().split())
vertices = list(tuple(map(myint, input().split())) for _ in range(n))
area, (x1, y1) = 0, vertices[-1]
for x2, y2 in vertices:
area += x2 * y1 - x1 * y2
x1, y1 = x2, y2
if area < 0:
vertices.reverse()
x0, y0 = vertices.pop()
x1, y1 = vertices.pop()
vertices, triangles, area = deque(vertices), [], 0
try:
while True:
x2, y2 = vertices.pop()
if (x1 - x0) * (y2 - y1) - (x2 - x1) * (y1 - y0) > 0:
triangles.append(((x0, y0), (x1, y1), (x2, y2)))
area += (x1 - x0) * (y2 - y1) - (x2 - x1) * (y1 - y0)
else:
vertices.appendleft((x0, y0))
x0, y0 = x1, y1
x1, y1 = x2, y2
except IndexError:
res = []
for _ in range(m):
tmp, edges = [], set()
x0, y0, x1, y1 = map(myint, input().split())
dx, dy = x1 - x0, y1 - y0
for t in triangles:
seg = []
for e in combinations(t, 2):
edge = [(x - x0, y - y0) for x, y in e]
if all(dx * y == dy * x for x, y in edge):
edges.add(tuple(sorted(e)))
break
(x2, y2), (x3, y3) = edge
dz, dt = x2 - x3, y2 - y3
nom, den = y3 * dz - x3 * dt, dy * dz - dx * dt
if den < 0:
nom *= -1
den *= -1
if 0 <= nom <= den:
seg.append((dx * nom / den, dy * nom / den))
else:
if len(seg) > 1:
(x2, y2), (x3, y3) = min(seg), max(seg)
tmp.append(hypot(x2 - x3, y2 - y3))
for (x2, y2), (x3, y3) in edges:
tmp.append(hypot(x2 - x3, y2 - y3))
res.append(str(fsum(tmp) / 1e2))
print('\n'.join(res))
if __name__ == '__main__':
main()
```
No
| 107,406 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!
He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these n cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities.
All cities are numbered 1 to n. Shapur is currently in the city 1 and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city.
Help Shapur find how much He should travel.
Input
First line contains a single natural number n (1 β€ n β€ 105) β the amount of cities.
Next n - 1 lines contain 3 integer numbers each xi, yi and wi (1 β€ xi, yi β€ n, 0 β€ wi β€ 2 Γ 104). xi and yi are two ends of a road and wi is the length of that road.
Output
A single integer number, the minimal length of Shapur's travel.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
3
1 2 3
2 3 4
Output
7
Input
3
1 2 3
1 3 3
Output
9
Tags: dfs and similar, graphs, greedy, shortest paths, trees
Correct Solution:
```
n = int(input())
g = [[] for _ in range(n)]
s = 0
for i in range(1,n):
u,v,w = map(int,input().split())
u -= 1
v -= 1
g[u].append([v,w])
g[v].append([u,w])
s += w
def dfs (u,f,x):
ret = x
for v,w in g[u]:
if f != v:
ret = max(ret,dfs(v,u,w+x))
return ret
print(2*s-dfs(0,-1,0))
```
| 107,407 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!
He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these n cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities.
All cities are numbered 1 to n. Shapur is currently in the city 1 and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city.
Help Shapur find how much He should travel.
Input
First line contains a single natural number n (1 β€ n β€ 105) β the amount of cities.
Next n - 1 lines contain 3 integer numbers each xi, yi and wi (1 β€ xi, yi β€ n, 0 β€ wi β€ 2 Γ 104). xi and yi are two ends of a road and wi is the length of that road.
Output
A single integer number, the minimal length of Shapur's travel.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
3
1 2 3
2 3 4
Output
7
Input
3
1 2 3
1 3 3
Output
9
Tags: dfs and similar, graphs, greedy, shortest paths, trees
Correct Solution:
```
n = int(input())
matrix = [[] * n for i in range(n)]
conn = dict()
def dfs(el, el2):
suma = 0
for element in matrix[el]:
if element[0] != el2:
suma = max(suma, element[1]+dfs(element[0],el))
return suma
suma=0
for i in range(n-1):
line = input()
line = line.split(' ')
matrix[int(line[0])-1].append((int(line[1])-1,int(line[2])))
matrix[int(line[1])-1].append((int(line[0])-1,int(line[2])))
suma += 2*int(line[2])
print(suma-dfs(0,-1))
```
| 107,408 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!
He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these n cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities.
All cities are numbered 1 to n. Shapur is currently in the city 1 and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city.
Help Shapur find how much He should travel.
Input
First line contains a single natural number n (1 β€ n β€ 105) β the amount of cities.
Next n - 1 lines contain 3 integer numbers each xi, yi and wi (1 β€ xi, yi β€ n, 0 β€ wi β€ 2 Γ 104). xi and yi are two ends of a road and wi is the length of that road.
Output
A single integer number, the minimal length of Shapur's travel.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
3
1 2 3
2 3 4
Output
7
Input
3
1 2 3
1 3 3
Output
9
Tags: dfs and similar, graphs, greedy, shortest paths, trees
Correct Solution:
```
import sys
def mainFunction():
n, = rv()
edges = [list() for _ in range(n+1)]
for i in range(n - 1):
x, y, w, = rv()
edges[x].append((y, w))
edges[y].append((x, w))
res = dfs(1, -1, edges)
print(res[0] * 2 - res[1])
def dfs(cur, prev, edges):
total, single = 0, 0
for nxt, weight in edges[cur]:
if nxt != prev:
temp = dfs(nxt, cur, edges)
total += temp[0] + weight
single = max(single, temp[1] + weight)
return (total, single)
def prt(l): return print(' '.join(l))
def rv(): return map(int, input().split())
def rl(n): return [list(map(int, input().split())) for _ in range(n)]
#-----------------main method------------------------------------------
mainFunction()
```
| 107,409 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!
He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these n cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities.
All cities are numbered 1 to n. Shapur is currently in the city 1 and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city.
Help Shapur find how much He should travel.
Input
First line contains a single natural number n (1 β€ n β€ 105) β the amount of cities.
Next n - 1 lines contain 3 integer numbers each xi, yi and wi (1 β€ xi, yi β€ n, 0 β€ wi β€ 2 Γ 104). xi and yi are two ends of a road and wi is the length of that road.
Output
A single integer number, the minimal length of Shapur's travel.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
3
1 2 3
2 3 4
Output
7
Input
3
1 2 3
1 3 3
Output
9
Tags: dfs and similar, graphs, greedy, shortest paths, trees
Correct Solution:
```
from os import sys
num = int(input())
vertices=[]
[vertices.append([]) for c in range(num+1)]
weightUnder=[-1]*(num+1)
visited = [-1]*(num+1)
sys.setrecursionlimit(100000)
def calculateWeight(i):
totalWeightUnder=0
visited[i]=1
for (vert,weight) in vertices[i]:
if visited[vert]==-1:
totalWeightUnder+=weight+calculateWeight(vert)
weightUnder[i]= totalWeightUnder
return totalWeightUnder
def getSolution(i):
visited[i]=1
minValue = 20000000000
for (vert,weight) in vertices[i]:
if (visited[vert]==-1):
newValue = weight+getSolution(vert)
minValue = min((weightUnder[i]-weight-weightUnder[vert])*2+newValue,minValue)
if minValue == 20000000000:
return 0
return minValue
def solve():
global num
for x in range(num-1):
x,y,w = list(map(int, input().split()))
vertices[x].append((y,w))
vertices[y].append((x,w))
calculateWeight(1)
for i in range(num+1):
visited[i]=-1
currentNode = 1
print (getSolution(currentNode))
try:
solve()
except Exception as e:
print (e)
```
| 107,410 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!
He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these n cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities.
All cities are numbered 1 to n. Shapur is currently in the city 1 and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city.
Help Shapur find how much He should travel.
Input
First line contains a single natural number n (1 β€ n β€ 105) β the amount of cities.
Next n - 1 lines contain 3 integer numbers each xi, yi and wi (1 β€ xi, yi β€ n, 0 β€ wi β€ 2 Γ 104). xi and yi are two ends of a road and wi is the length of that road.
Output
A single integer number, the minimal length of Shapur's travel.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
3
1 2 3
2 3 4
Output
7
Input
3
1 2 3
1 3 3
Output
9
Tags: dfs and similar, graphs, greedy, shortest paths, trees
Correct Solution:
```
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n = int(input())
adj = [[] for _ in range(n)]
deg = [100] + [0] * n
for u, v, w in (map(int, input().split()) for _ in range(n - 1)):
adj[u - 1].append((v - 1, w))
adj[v - 1].append((u - 1, w))
deg[u - 1] += 1
deg[v - 1] += 1
total_w = [0] * n
max_w = [0] * n
stack = [i for i in range(1, n) if deg[i] == 1]
while stack:
v = stack.pop()
deg[v] = 0
for dest, w in adj[v]:
if deg[dest] == 0:
continue
total_w[dest] += total_w[v] + w
max_w[dest] = max(max_w[dest], max_w[v] + w)
deg[dest] -= 1
if deg[dest] == 1:
stack.append(dest)
print(total_w[0] * 2 - max_w[0])
```
| 107,411 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!
He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these n cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities.
All cities are numbered 1 to n. Shapur is currently in the city 1 and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city.
Help Shapur find how much He should travel.
Input
First line contains a single natural number n (1 β€ n β€ 105) β the amount of cities.
Next n - 1 lines contain 3 integer numbers each xi, yi and wi (1 β€ xi, yi β€ n, 0 β€ wi β€ 2 Γ 104). xi and yi are two ends of a road and wi is the length of that road.
Output
A single integer number, the minimal length of Shapur's travel.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
3
1 2 3
2 3 4
Output
7
Input
3
1 2 3
1 3 3
Output
9
Tags: dfs and similar, graphs, greedy, shortest paths, trees
Correct Solution:
```
import sys
sys.setrecursionlimit(1000*1000)
n = int(input())
g = [[] for i in range(n+1)]
dist = [0] * (10**5+1)
r = 10**32
#print(dist)
def init(i,p):
for j in g[i]:
#print(j)
if j[0] == p:
continue
else :
s = 2*j[1]+init(j[0],i)
dist[i] += s
#print(i)
return dist[i]
def dfs(i,p,c):
global r
for j in g[i]:
if j[0] == p:
continue
dfs(j[0],i,c+dist[i]-dist[j[0]]-j[1])
if len(g[i]) == 1 and i != 1:
r = min(r,c)
for i in range(n-1):
x,y,w = map(int,input().split(' '))
g[x].append((y,w))
g[y].append((x,w))
init(1,0)
dfs(1,0,0)
if n == 1 :
print(0)
else :
print(r)
```
| 107,412 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!
He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these n cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities.
All cities are numbered 1 to n. Shapur is currently in the city 1 and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city.
Help Shapur find how much He should travel.
Input
First line contains a single natural number n (1 β€ n β€ 105) β the amount of cities.
Next n - 1 lines contain 3 integer numbers each xi, yi and wi (1 β€ xi, yi β€ n, 0 β€ wi β€ 2 Γ 104). xi and yi are two ends of a road and wi is the length of that road.
Output
A single integer number, the minimal length of Shapur's travel.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
3
1 2 3
2 3 4
Output
7
Input
3
1 2 3
1 3 3
Output
9
Tags: dfs and similar, graphs, greedy, shortest paths, trees
Correct Solution:
```
n = int(input())
g = [[] for _ in range(n)]
s = 0
for _ in range(n-1):
u, v, w = map(int, input().split())
u -= 1
v -= 1
g[u].append((v, w))
g[v].append((u, w))
s += w
def dfs(u, f,x):
ret = x
for v, w in g[u]:
if f!= v:
ret = max(ret, dfs(v, u, w+x))
return ret
# test
print(2*s - dfs(0, -1, 0))
```
| 107,413 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!
He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these n cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities.
All cities are numbered 1 to n. Shapur is currently in the city 1 and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city.
Help Shapur find how much He should travel.
Input
First line contains a single natural number n (1 β€ n β€ 105) β the amount of cities.
Next n - 1 lines contain 3 integer numbers each xi, yi and wi (1 β€ xi, yi β€ n, 0 β€ wi β€ 2 Γ 104). xi and yi are two ends of a road and wi is the length of that road.
Output
A single integer number, the minimal length of Shapur's travel.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
3
1 2 3
2 3 4
Output
7
Input
3
1 2 3
1 3 3
Output
9
Tags: dfs and similar, graphs, greedy, shortest paths, trees
Correct Solution:
```
from collections import defaultdict
class EternalVictory():
def __init__(self, n, edges):
self.n = n
self.edge_list = defaultdict(list)
self.edge_sum = 0
for u,v,w in edges:
self.edge_list[u-1].append((v-1, w))
self.edge_list[v-1].append((u-1, w))
self.edge_sum += w
self.distances = [0]*self.n
def populate(self, u, par, dis):
self.distances[u] = dis
for v,w in self.edge_list[u]:
if v != par:
self.populate(v, u, dis+w)
def min_sum(self):
self.populate(0, -1, 0)
max_dis = max(self.distances)
return (2*self.edge_sum)-max_dis
n = int(input())
edges = []
for i in range(n-1):
u,v,w = list(map(int,input().strip(' ').split(' ')))
edges.append((u,v,w))
ev = EternalVictory(n, edges)
print(ev.min_sum())
```
| 107,414 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!
He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these n cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities.
All cities are numbered 1 to n. Shapur is currently in the city 1 and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city.
Help Shapur find how much He should travel.
Input
First line contains a single natural number n (1 β€ n β€ 105) β the amount of cities.
Next n - 1 lines contain 3 integer numbers each xi, yi and wi (1 β€ xi, yi β€ n, 0 β€ wi β€ 2 Γ 104). xi and yi are two ends of a road and wi is the length of that road.
Output
A single integer number, the minimal length of Shapur's travel.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
3
1 2 3
2 3 4
Output
7
Input
3
1 2 3
1 3 3
Output
9
Submitted Solution:
```
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
import sys
from io import BytesIO, IOBase
from heapq import *
from math import inf
def main():
n=int(input())
tree,su=[[] for _ in range(n+1)],0
for i in range(n-1):
x,y,w=map(int,input().split())
tree[x].append((y,w))
tree[y].append((x,w))
su+=w
d,b=[inf]*(n+1),[]
d[1]=0
heappush(b,(0,1))
while b:
c,ch=heappop(b)
if d[ch]<c:
continue
for i in tree[ch]:
if d[i[0]]>c+i[1]:
d[i[0]]=c+i[1]
heappush(b,(c+i[1],i[0]))
print(2*su-max(d[1:]))
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
```
Yes
| 107,415 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!
He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these n cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities.
All cities are numbered 1 to n. Shapur is currently in the city 1 and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city.
Help Shapur find how much He should travel.
Input
First line contains a single natural number n (1 β€ n β€ 105) β the amount of cities.
Next n - 1 lines contain 3 integer numbers each xi, yi and wi (1 β€ xi, yi β€ n, 0 β€ wi β€ 2 Γ 104). xi and yi are two ends of a road and wi is the length of that road.
Output
A single integer number, the minimal length of Shapur's travel.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
3
1 2 3
2 3 4
Output
7
Input
3
1 2 3
1 3 3
Output
9
Submitted Solution:
```
from sys import stdin, stdout
n = int(stdin.readline())
visit = [0 for i in range(n + 1)]
counting = [[] for i in range(n + 1)]
vertices = [[] for i in range(n + 1)]
for i in range(n - 1):
a, b, w = map(int, stdin.readline().split())
vertices[a].append((b, w))
vertices[b].append((a, w))
def dfs(v, weight, d):
global cnt, depth
depth = max(depth, d)
visit[v] = 1
for u, w in vertices[v]:
if not visit[u]:
cnt[-1] += w
dfs(u, w, d + w)
cnt[-1] += w
cnt = []
ans = 0
visit[1] = 1
depth = 0
for i in range(len(vertices[1])):
cnt.append(0)
dfs(vertices[1][i][0], 0, vertices[1][i][1])
cnt[-1] += vertices[1][i][1] * 2
ans += sum(cnt) - depth
stdout.write(str(ans))
```
Yes
| 107,416 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!
He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these n cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities.
All cities are numbered 1 to n. Shapur is currently in the city 1 and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city.
Help Shapur find how much He should travel.
Input
First line contains a single natural number n (1 β€ n β€ 105) β the amount of cities.
Next n - 1 lines contain 3 integer numbers each xi, yi and wi (1 β€ xi, yi β€ n, 0 β€ wi β€ 2 Γ 104). xi and yi are two ends of a road and wi is the length of that road.
Output
A single integer number, the minimal length of Shapur's travel.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
3
1 2 3
2 3 4
Output
7
Input
3
1 2 3
1 3 3
Output
9
Submitted Solution:
```
from collections import defaultdict
edges=defaultdict(list)
def solve():
sum=0
for _ in range(int(input())-1):
v,u,w=map(int,input().split())
edges[v].append((u,w))
edges[u].append((v,w))
sum+=w
def dfs(cur,per,x):
ret=x
for i,w in edges[cur]:
if i!=per:
ret=max(ret,dfs(i,cur,x+w))
return ret
print(2*sum-dfs(1,-1,0))
solve()
```
Yes
| 107,417 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!
He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these n cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities.
All cities are numbered 1 to n. Shapur is currently in the city 1 and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city.
Help Shapur find how much He should travel.
Input
First line contains a single natural number n (1 β€ n β€ 105) β the amount of cities.
Next n - 1 lines contain 3 integer numbers each xi, yi and wi (1 β€ xi, yi β€ n, 0 β€ wi β€ 2 Γ 104). xi and yi are two ends of a road and wi is the length of that road.
Output
A single integer number, the minimal length of Shapur's travel.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
3
1 2 3
2 3 4
Output
7
Input
3
1 2 3
1 3 3
Output
9
Submitted Solution:
```
s, n = 0, int(input())
p, r = [[] for i in range(n + 1)], [0] * (n + 1)
for i in range(n - 1):
x, y, d = map(int, input().split())
p[x].append((y, d))
p[y].append((x, d))
s += d
t = [x for x in range(1, n + 1) if len(p[x]) == 1]
while t:
y = t.pop()
if y == 1: continue
x, d = p[y][0]
r[x] = max(r[x], d + r[y])
p[x].remove((y, d))
if len(p[x]) == 1: t.append(x)
print(2 * s - r[1])
```
Yes
| 107,418 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!
He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these n cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities.
All cities are numbered 1 to n. Shapur is currently in the city 1 and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city.
Help Shapur find how much He should travel.
Input
First line contains a single natural number n (1 β€ n β€ 105) β the amount of cities.
Next n - 1 lines contain 3 integer numbers each xi, yi and wi (1 β€ xi, yi β€ n, 0 β€ wi β€ 2 Γ 104). xi and yi are two ends of a road and wi is the length of that road.
Output
A single integer number, the minimal length of Shapur's travel.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
3
1 2 3
2 3 4
Output
7
Input
3
1 2 3
1 3 3
Output
9
Submitted Solution:
```
n = int(input())
tree = [[] for _ in range(n+1)]
ans = 10 ** 18
tot = 0
for _ in range(n-1):
u,v,w = map(int, input().split())
tree[u].append((v,w))
tree[v].append((u,w))
tot += 2 * w
def dfs(node, par, curr_val):
global ans
global tot
ans = min(ans, tot - curr_val)
for child in tree[node]:
if child[0] != par:
dfs(child[0], node, curr_val + child[1])
for edge in tree[1]:
dfs(edge[0], 1, edge[1])
print(ans)
```
No
| 107,419 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!
He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these n cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities.
All cities are numbered 1 to n. Shapur is currently in the city 1 and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city.
Help Shapur find how much He should travel.
Input
First line contains a single natural number n (1 β€ n β€ 105) β the amount of cities.
Next n - 1 lines contain 3 integer numbers each xi, yi and wi (1 β€ xi, yi β€ n, 0 β€ wi β€ 2 Γ 104). xi and yi are two ends of a road and wi is the length of that road.
Output
A single integer number, the minimal length of Shapur's travel.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
3
1 2 3
2 3 4
Output
7
Input
3
1 2 3
1 3 3
Output
9
Submitted Solution:
```
from sys import stdin, stdout
n = int(stdin.readline())
visit = [0 for i in range(n + 1)]
counting = [[] for i in range(n + 1)]
vertices = [[] for i in range(n + 1)]
for i in range(n - 1):
a, b, w = map(int, stdin.readline().split())
vertices[a].append((b, w))
vertices[b].append((a, w))
def dfs(v, weight):
visit[v] = 1
for u, w in vertices[v]:
if not visit[u]:
value = dfs(u, w)
counting[v].append(value)
return weight + sum(counting[v])
dfs(1, 0)
ans = sorted(counting[1])
stdout.write(str(sum(ans[:-1]) * 2 + ans[-1]))
```
No
| 107,420 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!
He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these n cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities.
All cities are numbered 1 to n. Shapur is currently in the city 1 and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city.
Help Shapur find how much He should travel.
Input
First line contains a single natural number n (1 β€ n β€ 105) β the amount of cities.
Next n - 1 lines contain 3 integer numbers each xi, yi and wi (1 β€ xi, yi β€ n, 0 β€ wi β€ 2 Γ 104). xi and yi are two ends of a road and wi is the length of that road.
Output
A single integer number, the minimal length of Shapur's travel.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
3
1 2 3
2 3 4
Output
7
Input
3
1 2 3
1 3 3
Output
9
Submitted Solution:
```
def main():
n = lie()
g = []
for i in range(n - 1):
g.append(list(liee()))
temp = cs(n, g)
print(temp.find())
class cs():
def __init__(self, n, g):
self.n = n
self.edge = defaultdict(list)
self.sum = 0
self.dp = vector(n + 1)
for u, v, w in g:
self.edge[u].append([v, w])
self.edge[v].append([u, w])
self.sum += w
def dfs(self, ch, par, dis):
self.dp[ch] = dis
for v, w in self.edge[ch]:
if v != par:
self.dfs(v, ch, dis + w)
def find(self):
self.dfs(1, 0, 0)
dis = max(self.dp)
return 2 * self.sum - dis
from sys import *
import inspect
import re
from math import *
import threading
from collections import *
from pprint import pprint as pp
mod = 998244353
MAX = 10**5
def lie():
return int(input())
def liee():
return map(int, input().split())
def array():
return list(map(int, input().split()))
def deb(p):
for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]:
m = re.search(r'\bdeb\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line)
print('%s %s' % (m.group(1), str(p)))
def vec(size, val=0):
vec = [val for i in range(size)]
return vec
def mat(rowNum, colNum, val=0):
mat = []
for i in range(rowNum):
collumn = [val for j in range(colNum)]
mat.append(collumn)
return mat
def dmain():
setrecursionlimit(100000000)
threading.stack_size(40960000)
thread = threading.Thread(target=main)
thread.start()
if __name__ == '__main__':
# main()
dmain()
```
No
| 107,421 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!
He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these n cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities.
All cities are numbered 1 to n. Shapur is currently in the city 1 and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city.
Help Shapur find how much He should travel.
Input
First line contains a single natural number n (1 β€ n β€ 105) β the amount of cities.
Next n - 1 lines contain 3 integer numbers each xi, yi and wi (1 β€ xi, yi β€ n, 0 β€ wi β€ 2 Γ 104). xi and yi are two ends of a road and wi is the length of that road.
Output
A single integer number, the minimal length of Shapur's travel.
Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
Examples
Input
3
1 2 3
2 3 4
Output
7
Input
3
1 2 3
1 3 3
Output
9
Submitted Solution:
```
from sys import stdin, stdout
n = int(stdin.readline())
visit = [0 for i in range(n + 1)]
counting = [[] for i in range(n + 1)]
vertices = [[] for i in range(n + 1)]
for i in range(n - 1):
a, b, w = map(int, stdin.readline().split())
vertices[a].append((b, w))
vertices[b].append((a, w))
def dfs(v, weight):
global cnt
visit[v] = 1
for u, w in vertices[v]:
if not visit[u]:
cnt[-1][0] += w
cnt[-1][1] = 0
dfs(u, w)
cnt[-1][0] += w
cnt[-1][1] += weight
cnt = []
ans = 0
visit[1] = 1
for i in range(len(vertices[1])):
cnt.append([0, 0])
dfs(vertices[1][i][0], 0)
cnt[-1][0] -= cnt[-1][1]
cnt[-1][0] += vertices[1][i][1]
cnt[-1][1] += vertices[1][i][1]
ans += cnt[-1][0]
cnt[-1] = cnt[-1][::-1]
cnt.sort()
for i in range(len(cnt) - 1):
ans += cnt[i][0]
stdout.write(str(ans))
```
No
| 107,422 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it.
The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all it's digits should be different. The guesser tries to guess the number. He makes a series of guesses, trying experimental numbers and receives answers from the first person in the format "x bulls y cows". x represents the number of digits in the experimental number that occupy the same positions as in the sought number. y represents the number of digits of the experimental number that present in the sought number, but occupy different positions. Naturally, the experimental numbers, as well as the sought number, are represented by four-digit numbers where all digits are different and a leading zero can be present.
For example, let's suppose that the thinker thought of the number 0123. Then the guessers' experimental number 1263 will receive a reply "1 bull 2 cows" (3 occupies the same positions in both numbers and 1 and 2 are present in both numbers but they occupy different positions). Also, the answer to number 8103 will be "2 bulls 1 cow" (analogically, 1 and 3 occupy the same positions and 0 occupies a different one).
When the guesser is answered "4 bulls 0 cows", the game is over.
Now the guesser has already made several guesses and wants to know whether his next guess can possibly be the last one.
Input
The first input line contains an integer n (1 β€ n β€ 10) which represents the number of already made guesses. Then follow n lines in the form of "ai bi ci", where ai is the i-th experimental number, bi is the number of bulls, ci is the number of cows (1 β€ i β€ n, 0 β€ bi, ci, bi + ci β€ 4). The experimental numbers are correct, i.e., each of them contains exactly four digits, in each of them all the four digits are different, and there can be a leading zero. All the experimental numbers are different. As the guesser hasn't guessed the number yet, the answer "4 bulls 0 cows" is not present.
Output
If the input data is enough to determine the sought number, print the number with four digits on a single line. If it has less than four digits, add leading zero. If the data is not enough, print "Need more data" without the quotes. If the thinker happens to have made a mistake in his replies, print "Incorrect data" without the quotes.
Examples
Input
2
1263 1 2
8103 2 1
Output
Need more data
Input
2
1234 2 2
1256 0 2
Output
2134
Input
2
0123 1 1
4567 1 2
Output
Incorrect data
Tags: brute force, implementation
Correct Solution:
```
import sys
def solve():
n, = rv()
works = 0
lastworks = -1
guesses = list()
for i in range(n):
a, b, c, = rv()
acopy = a
charcount = [0] * 10
for x in range(4):
charcount[acopy % 10] += 1
acopy //= 10
guesses.append((tolist(a), b, c, charcount))
for i in range(1, 10000):
if different(i):
l = tolist(i)
icopy = i
charcount = [0] * 10
for x in range(4):
charcount[icopy % 10] += 1
icopy //= 10
count = 0
for guess in guesses:
bulls, cows = 0, 0
for j in range(4):
if l[j] == guess[0][j]: bulls += 1
for j in range(10):
if charcount[j] > 0 and guess[3][j] > 0: cows+=1
cows -= bulls
if bulls == guess[1] and cows == guess[2]:
count += 1
if count == n:
works += 1
lastworks = l
if works == 0:
print("Incorrect data")
elif works == 1:
print(''.join(map(str, lastworks)))
else:
print("Need more data")
def tolist(i):
il = list()
while i > 0:
il.append(i % 10)
i //= 10
while len(il) < 4: il.append(0)
return il[::-1]
def different(i):
count = [0] * 10
for x in range(4):
count[i % 10] += 1
i //= 10
for val in count:
if val > 1: return False
return True
def prt(l): return print(''.join(l))
def rv(): return map(int, input().split())
def rl(n): return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve()
# Made By Mostafa_Khaled
```
| 107,423 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it.
The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all it's digits should be different. The guesser tries to guess the number. He makes a series of guesses, trying experimental numbers and receives answers from the first person in the format "x bulls y cows". x represents the number of digits in the experimental number that occupy the same positions as in the sought number. y represents the number of digits of the experimental number that present in the sought number, but occupy different positions. Naturally, the experimental numbers, as well as the sought number, are represented by four-digit numbers where all digits are different and a leading zero can be present.
For example, let's suppose that the thinker thought of the number 0123. Then the guessers' experimental number 1263 will receive a reply "1 bull 2 cows" (3 occupies the same positions in both numbers and 1 and 2 are present in both numbers but they occupy different positions). Also, the answer to number 8103 will be "2 bulls 1 cow" (analogically, 1 and 3 occupy the same positions and 0 occupies a different one).
When the guesser is answered "4 bulls 0 cows", the game is over.
Now the guesser has already made several guesses and wants to know whether his next guess can possibly be the last one.
Input
The first input line contains an integer n (1 β€ n β€ 10) which represents the number of already made guesses. Then follow n lines in the form of "ai bi ci", where ai is the i-th experimental number, bi is the number of bulls, ci is the number of cows (1 β€ i β€ n, 0 β€ bi, ci, bi + ci β€ 4). The experimental numbers are correct, i.e., each of them contains exactly four digits, in each of them all the four digits are different, and there can be a leading zero. All the experimental numbers are different. As the guesser hasn't guessed the number yet, the answer "4 bulls 0 cows" is not present.
Output
If the input data is enough to determine the sought number, print the number with four digits on a single line. If it has less than four digits, add leading zero. If the data is not enough, print "Need more data" without the quotes. If the thinker happens to have made a mistake in his replies, print "Incorrect data" without the quotes.
Examples
Input
2
1263 1 2
8103 2 1
Output
Need more data
Input
2
1234 2 2
1256 0 2
Output
2134
Input
2
0123 1 1
4567 1 2
Output
Incorrect data
Tags: brute force, implementation
Correct Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq 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'
MOD=1000000007
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()
numbers=set()
for i in range(10):
for j in range(10):
for k in range(10):
for l in range(10):
if(i!=j and i!=k and i!=l and j!=k and j!=l and k!=l):
numbers.add(str(i)+str(j)+str(k)+str(l))
def count():
possible=set()
for num in numbers:
cow=0
bulls=0
for i in range(4):
for j in range(4):
if(num[i]==n[j]):
bulls+=1
break
if(num[i]==n[i]): cow+=1
if(cow==x and bulls-cow==y):
possible.add(num)
return possible
for _ in range(Int()):
n,x,y=input().split()
x=int(x)
y=int(y)
numbers=count()
# print(numbers)
if(len(numbers)==1): print(list(numbers)[0])
elif(len(numbers)>1): print('Need more data')
else: print('Incorrect data')
```
| 107,424 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it.
The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all it's digits should be different. The guesser tries to guess the number. He makes a series of guesses, trying experimental numbers and receives answers from the first person in the format "x bulls y cows". x represents the number of digits in the experimental number that occupy the same positions as in the sought number. y represents the number of digits of the experimental number that present in the sought number, but occupy different positions. Naturally, the experimental numbers, as well as the sought number, are represented by four-digit numbers where all digits are different and a leading zero can be present.
For example, let's suppose that the thinker thought of the number 0123. Then the guessers' experimental number 1263 will receive a reply "1 bull 2 cows" (3 occupies the same positions in both numbers and 1 and 2 are present in both numbers but they occupy different positions). Also, the answer to number 8103 will be "2 bulls 1 cow" (analogically, 1 and 3 occupy the same positions and 0 occupies a different one).
When the guesser is answered "4 bulls 0 cows", the game is over.
Now the guesser has already made several guesses and wants to know whether his next guess can possibly be the last one.
Input
The first input line contains an integer n (1 β€ n β€ 10) which represents the number of already made guesses. Then follow n lines in the form of "ai bi ci", where ai is the i-th experimental number, bi is the number of bulls, ci is the number of cows (1 β€ i β€ n, 0 β€ bi, ci, bi + ci β€ 4). The experimental numbers are correct, i.e., each of them contains exactly four digits, in each of them all the four digits are different, and there can be a leading zero. All the experimental numbers are different. As the guesser hasn't guessed the number yet, the answer "4 bulls 0 cows" is not present.
Output
If the input data is enough to determine the sought number, print the number with four digits on a single line. If it has less than four digits, add leading zero. If the data is not enough, print "Need more data" without the quotes. If the thinker happens to have made a mistake in his replies, print "Incorrect data" without the quotes.
Examples
Input
2
1263 1 2
8103 2 1
Output
Need more data
Input
2
1234 2 2
1256 0 2
Output
2134
Input
2
0123 1 1
4567 1 2
Output
Incorrect data
Tags: brute force, implementation
Correct Solution:
```
import sys
def tolist(i):
listx = list()
while i > 0:
listx.append(i % 10)
i //= 10
while len(listx) < 4: listx.append(0)
return listx[::-1]
def diff(i):
count = [0] * 10
for x in range(4):
count[i % 10] += 1
i //= 10
for val in count:
if val > 1: return False
return True
n, = map(int, input().split())
works = 0
lastworks = -1
guesses = list()
for i in range(n):
a, b, c, = map(int, input().split())
acopy = a
charcount = [0] * 10
for x in range(4):
charcount[acopy % 10] += 1
acopy //= 10
guesses.append((tolist(a), b, c, charcount))
for i in range(1, 10000):
if diff(i):
l = tolist(i)
icopy = i
charcount = [0] * 10
for x in range(4):
charcount[icopy % 10] += 1
icopy //= 10
count = 0
for guess in guesses:
bulls, cows = 0, 0
for j in range(4):
if l[j] == guess[0][j]: bulls += 1
for j in range(10):
if charcount[j] > 0 and guess[3][j] > 0: cows+=1
cows -= bulls
if bulls == guess[1] and cows == guess[2]:
count += 1
if count == n:
works += 1
lastworks = l
if works == 0:
print("Incorrect data")
elif works == 1:
print(''.join(map(str, lastworks)))
else:
print("Need more data")
```
| 107,425 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it.
The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all it's digits should be different. The guesser tries to guess the number. He makes a series of guesses, trying experimental numbers and receives answers from the first person in the format "x bulls y cows". x represents the number of digits in the experimental number that occupy the same positions as in the sought number. y represents the number of digits of the experimental number that present in the sought number, but occupy different positions. Naturally, the experimental numbers, as well as the sought number, are represented by four-digit numbers where all digits are different and a leading zero can be present.
For example, let's suppose that the thinker thought of the number 0123. Then the guessers' experimental number 1263 will receive a reply "1 bull 2 cows" (3 occupies the same positions in both numbers and 1 and 2 are present in both numbers but they occupy different positions). Also, the answer to number 8103 will be "2 bulls 1 cow" (analogically, 1 and 3 occupy the same positions and 0 occupies a different one).
When the guesser is answered "4 bulls 0 cows", the game is over.
Now the guesser has already made several guesses and wants to know whether his next guess can possibly be the last one.
Input
The first input line contains an integer n (1 β€ n β€ 10) which represents the number of already made guesses. Then follow n lines in the form of "ai bi ci", where ai is the i-th experimental number, bi is the number of bulls, ci is the number of cows (1 β€ i β€ n, 0 β€ bi, ci, bi + ci β€ 4). The experimental numbers are correct, i.e., each of them contains exactly four digits, in each of them all the four digits are different, and there can be a leading zero. All the experimental numbers are different. As the guesser hasn't guessed the number yet, the answer "4 bulls 0 cows" is not present.
Output
If the input data is enough to determine the sought number, print the number with four digits on a single line. If it has less than four digits, add leading zero. If the data is not enough, print "Need more data" without the quotes. If the thinker happens to have made a mistake in his replies, print "Incorrect data" without the quotes.
Examples
Input
2
1263 1 2
8103 2 1
Output
Need more data
Input
2
1234 2 2
1256 0 2
Output
2134
Input
2
0123 1 1
4567 1 2
Output
Incorrect data
Tags: brute force, implementation
Correct Solution:
```
import sys
def solve():
n, = rv()
works = 0
lastworks = -1
guesses = list()
for i in range(n):
a, b, c, = rv()
acopy = a
charcount = [0] * 10
for x in range(4):
charcount[acopy % 10] += 1
acopy //= 10
guesses.append((tolist(a), b, c, charcount))
for i in range(1, 10000):
if different(i):
l = tolist(i)
icopy = i
charcount = [0] * 10
for x in range(4):
charcount[icopy % 10] += 1
icopy //= 10
count = 0
for guess in guesses:
bulls, cows = 0, 0
for j in range(4):
if l[j] == guess[0][j]: bulls += 1
for j in range(10):
if charcount[j] > 0 and guess[3][j] > 0: cows+=1
cows -= bulls
if bulls == guess[1] and cows == guess[2]:
count += 1
if count == n:
works += 1
lastworks = l
if works == 0:
print("Incorrect data")
elif works == 1:
print(''.join(map(str, lastworks)))
else:
print("Need more data")
def tolist(i):
il = list()
while i > 0:
il.append(i % 10)
i //= 10
while len(il) < 4: il.append(0)
return il[::-1]
def different(i):
count = [0] * 10
for x in range(4):
count[i % 10] += 1
i //= 10
for val in count:
if val > 1: return False
return True
def prt(l): return print(''.join(l))
def rv(): return map(int, input().split())
def rl(n): return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve()
```
| 107,426 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it.
The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all it's digits should be different. The guesser tries to guess the number. He makes a series of guesses, trying experimental numbers and receives answers from the first person in the format "x bulls y cows". x represents the number of digits in the experimental number that occupy the same positions as in the sought number. y represents the number of digits of the experimental number that present in the sought number, but occupy different positions. Naturally, the experimental numbers, as well as the sought number, are represented by four-digit numbers where all digits are different and a leading zero can be present.
For example, let's suppose that the thinker thought of the number 0123. Then the guessers' experimental number 1263 will receive a reply "1 bull 2 cows" (3 occupies the same positions in both numbers and 1 and 2 are present in both numbers but they occupy different positions). Also, the answer to number 8103 will be "2 bulls 1 cow" (analogically, 1 and 3 occupy the same positions and 0 occupies a different one).
When the guesser is answered "4 bulls 0 cows", the game is over.
Now the guesser has already made several guesses and wants to know whether his next guess can possibly be the last one.
Input
The first input line contains an integer n (1 β€ n β€ 10) which represents the number of already made guesses. Then follow n lines in the form of "ai bi ci", where ai is the i-th experimental number, bi is the number of bulls, ci is the number of cows (1 β€ i β€ n, 0 β€ bi, ci, bi + ci β€ 4). The experimental numbers are correct, i.e., each of them contains exactly four digits, in each of them all the four digits are different, and there can be a leading zero. All the experimental numbers are different. As the guesser hasn't guessed the number yet, the answer "4 bulls 0 cows" is not present.
Output
If the input data is enough to determine the sought number, print the number with four digits on a single line. If it has less than four digits, add leading zero. If the data is not enough, print "Need more data" without the quotes. If the thinker happens to have made a mistake in his replies, print "Incorrect data" without the quotes.
Examples
Input
2
1263 1 2
8103 2 1
Output
Need more data
Input
2
1234 2 2
1256 0 2
Output
2134
Input
2
0123 1 1
4567 1 2
Output
Incorrect data
Tags: brute force, implementation
Correct Solution:
```
# cook your dish here
import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
import copy
import time
starttime = time.time()
mod = int(pow(10, 9) + 7)
mod2 = 998244353
# from sys import stdin
# input = stdin.readline
def data(): return sys.stdin.readline().strip()
def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end)
def L(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]
try:
# sys.setrecursionlimit(int(pow(10,7)))
sys.stdin = open("input.txt", "r")
# sys.stdout = open("../output.txt", "w")
except:
pass
def pmat(A):
for ele in A:
print(*ele,end="\n")
def seive():
prime=[1 for i in range(10**6+1)]
prime[0]=0
prime[1]=0
for i in range(10**6+1):
if(prime[i]):
for j in range(2*i,10**6+1,i):
prime[j]=0
return prime
# exit()
S=set()
for term in range(L()[0]):
a,b,c=sl()
curr=set()
b=int(b)
c=int(c)
for i in range(10):
for j in range(10):
for k in range(10):
for l in range(10):
A=[i,j,k,l]
if len(set(A))!=4:
continue
tb,tc=0,0
for pos in range(4):
# print(A,a)
if A[pos]==int(a[pos]):
tb+=1
elif str(A[pos]) in a:
tc+=1
if tb==b and tc==c:
A=[str(ele) for ele in A]
curr.add("".join(A))
if term==0:
# print(curr)
S=curr
else:
# print(curr)
S&=curr
# print(S)
if len(S)==1:
for ele in S:
for x in ele:
print(x,end="")
print()
elif len(S)==0:
print("Incorrect data")
else:
print("Need more data")
endtime = time.time()
# print(f"Runtime of the program is {endtime - starttime}")
```
| 107,427 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it.
The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all it's digits should be different. The guesser tries to guess the number. He makes a series of guesses, trying experimental numbers and receives answers from the first person in the format "x bulls y cows". x represents the number of digits in the experimental number that occupy the same positions as in the sought number. y represents the number of digits of the experimental number that present in the sought number, but occupy different positions. Naturally, the experimental numbers, as well as the sought number, are represented by four-digit numbers where all digits are different and a leading zero can be present.
For example, let's suppose that the thinker thought of the number 0123. Then the guessers' experimental number 1263 will receive a reply "1 bull 2 cows" (3 occupies the same positions in both numbers and 1 and 2 are present in both numbers but they occupy different positions). Also, the answer to number 8103 will be "2 bulls 1 cow" (analogically, 1 and 3 occupy the same positions and 0 occupies a different one).
When the guesser is answered "4 bulls 0 cows", the game is over.
Now the guesser has already made several guesses and wants to know whether his next guess can possibly be the last one.
Input
The first input line contains an integer n (1 β€ n β€ 10) which represents the number of already made guesses. Then follow n lines in the form of "ai bi ci", where ai is the i-th experimental number, bi is the number of bulls, ci is the number of cows (1 β€ i β€ n, 0 β€ bi, ci, bi + ci β€ 4). The experimental numbers are correct, i.e., each of them contains exactly four digits, in each of them all the four digits are different, and there can be a leading zero. All the experimental numbers are different. As the guesser hasn't guessed the number yet, the answer "4 bulls 0 cows" is not present.
Output
If the input data is enough to determine the sought number, print the number with four digits on a single line. If it has less than four digits, add leading zero. If the data is not enough, print "Need more data" without the quotes. If the thinker happens to have made a mistake in his replies, print "Incorrect data" without the quotes.
Examples
Input
2
1263 1 2
8103 2 1
Output
Need more data
Input
2
1234 2 2
1256 0 2
Output
2134
Input
2
0123 1 1
4567 1 2
Output
Incorrect data
Tags: brute force, implementation
Correct Solution:
```
import sys
lines = sys.stdin.readlines()
n = int(lines[0].strip())
query = []
for i in range(1, n+1):
(a, b, c) = lines[i].strip().split(" ")
query.append((a, int(b), int(c)))
def compare(i):
digits = str(i)
digits = "0" *(4-len(digits)) + digits
if len(set(list(digits))) != 4: return False
for q in query:
(a, b, c) = q
m, n = 0, 0
for i in range(4):
if a[i] == digits[i]: m += 1
for l in a:
if l in digits: n += 1
n -= m
if m != b or n != c:
return False
return True
res = 0
count = 0
for i in range(123, 9877):
if compare(i): count += 1; res = i
if count >= 2: break
if count == 0: print("Incorrect data")
elif count == 1:
digits = str(res)
digits = "0" *(4-len(digits)) + digits
print(digits)
else: print("Need more data")
```
| 107,428 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it.
The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all it's digits should be different. The guesser tries to guess the number. He makes a series of guesses, trying experimental numbers and receives answers from the first person in the format "x bulls y cows". x represents the number of digits in the experimental number that occupy the same positions as in the sought number. y represents the number of digits of the experimental number that present in the sought number, but occupy different positions. Naturally, the experimental numbers, as well as the sought number, are represented by four-digit numbers where all digits are different and a leading zero can be present.
For example, let's suppose that the thinker thought of the number 0123. Then the guessers' experimental number 1263 will receive a reply "1 bull 2 cows" (3 occupies the same positions in both numbers and 1 and 2 are present in both numbers but they occupy different positions). Also, the answer to number 8103 will be "2 bulls 1 cow" (analogically, 1 and 3 occupy the same positions and 0 occupies a different one).
When the guesser is answered "4 bulls 0 cows", the game is over.
Now the guesser has already made several guesses and wants to know whether his next guess can possibly be the last one.
Input
The first input line contains an integer n (1 β€ n β€ 10) which represents the number of already made guesses. Then follow n lines in the form of "ai bi ci", where ai is the i-th experimental number, bi is the number of bulls, ci is the number of cows (1 β€ i β€ n, 0 β€ bi, ci, bi + ci β€ 4). The experimental numbers are correct, i.e., each of them contains exactly four digits, in each of them all the four digits are different, and there can be a leading zero. All the experimental numbers are different. As the guesser hasn't guessed the number yet, the answer "4 bulls 0 cows" is not present.
Output
If the input data is enough to determine the sought number, print the number with four digits on a single line. If it has less than four digits, add leading zero. If the data is not enough, print "Need more data" without the quotes. If the thinker happens to have made a mistake in his replies, print "Incorrect data" without the quotes.
Examples
Input
2
1263 1 2
8103 2 1
Output
Need more data
Input
2
1234 2 2
1256 0 2
Output
2134
Input
2
0123 1 1
4567 1 2
Output
Incorrect data
Tags: brute force, implementation
Correct Solution:
```
def filter(candidates, num, rp, wp):
ans = []
for cand in candidates:
crp = cwp = 0
for a, b in zip(cand, num):
if a == b:
crp += 1
elif a in num:
cwp += 1
if crp == rp and cwp == wp:
ans.append(cand)
return ans
def main():
n = int(input())
candidates = []
for i in range(123, 9877):
num = str(i).zfill(4)
if len(set(num)) == 4:
candidates.append(num)
for _ in range(n):
a, b, c = input().split()
candidates = filter(candidates, a, int(b), int(c))
if not candidates:
print('Incorrect data')
return
print(candidates[0] if len(candidates) == 1 else 'Need more data')
if __name__ == "__main__":
main()
```
| 107,429 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it.
The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all it's digits should be different. The guesser tries to guess the number. He makes a series of guesses, trying experimental numbers and receives answers from the first person in the format "x bulls y cows". x represents the number of digits in the experimental number that occupy the same positions as in the sought number. y represents the number of digits of the experimental number that present in the sought number, but occupy different positions. Naturally, the experimental numbers, as well as the sought number, are represented by four-digit numbers where all digits are different and a leading zero can be present.
For example, let's suppose that the thinker thought of the number 0123. Then the guessers' experimental number 1263 will receive a reply "1 bull 2 cows" (3 occupies the same positions in both numbers and 1 and 2 are present in both numbers but they occupy different positions). Also, the answer to number 8103 will be "2 bulls 1 cow" (analogically, 1 and 3 occupy the same positions and 0 occupies a different one).
When the guesser is answered "4 bulls 0 cows", the game is over.
Now the guesser has already made several guesses and wants to know whether his next guess can possibly be the last one.
Input
The first input line contains an integer n (1 β€ n β€ 10) which represents the number of already made guesses. Then follow n lines in the form of "ai bi ci", where ai is the i-th experimental number, bi is the number of bulls, ci is the number of cows (1 β€ i β€ n, 0 β€ bi, ci, bi + ci β€ 4). The experimental numbers are correct, i.e., each of them contains exactly four digits, in each of them all the four digits are different, and there can be a leading zero. All the experimental numbers are different. As the guesser hasn't guessed the number yet, the answer "4 bulls 0 cows" is not present.
Output
If the input data is enough to determine the sought number, print the number with four digits on a single line. If it has less than four digits, add leading zero. If the data is not enough, print "Need more data" without the quotes. If the thinker happens to have made a mistake in his replies, print "Incorrect data" without the quotes.
Examples
Input
2
1263 1 2
8103 2 1
Output
Need more data
Input
2
1234 2 2
1256 0 2
Output
2134
Input
2
0123 1 1
4567 1 2
Output
Incorrect data
Tags: brute force, implementation
Correct Solution:
```
n=int(input())
array=[str(t).zfill(4) for t in range(10000) if len(set(str(t).zfill(4)))==4]
# print (array)
for _ in range(n):
a,b,c=input().split()
b=int(b)
c=int(c)
# for u in array:
# print (u, set(u).intersection(set(a)))
array=[u for u in array if len(set(u).intersection(set(a)))==b+c and sum(u[i]==a[i] for i in range(4))==b]
# print (array)
if len(array)>1:print("Need more data")
elif len(array)==1:print(array[0])
else:print("Incorrect data")
```
| 107,430 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it.
The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all it's digits should be different. The guesser tries to guess the number. He makes a series of guesses, trying experimental numbers and receives answers from the first person in the format "x bulls y cows". x represents the number of digits in the experimental number that occupy the same positions as in the sought number. y represents the number of digits of the experimental number that present in the sought number, but occupy different positions. Naturally, the experimental numbers, as well as the sought number, are represented by four-digit numbers where all digits are different and a leading zero can be present.
For example, let's suppose that the thinker thought of the number 0123. Then the guessers' experimental number 1263 will receive a reply "1 bull 2 cows" (3 occupies the same positions in both numbers and 1 and 2 are present in both numbers but they occupy different positions). Also, the answer to number 8103 will be "2 bulls 1 cow" (analogically, 1 and 3 occupy the same positions and 0 occupies a different one).
When the guesser is answered "4 bulls 0 cows", the game is over.
Now the guesser has already made several guesses and wants to know whether his next guess can possibly be the last one.
Input
The first input line contains an integer n (1 β€ n β€ 10) which represents the number of already made guesses. Then follow n lines in the form of "ai bi ci", where ai is the i-th experimental number, bi is the number of bulls, ci is the number of cows (1 β€ i β€ n, 0 β€ bi, ci, bi + ci β€ 4). The experimental numbers are correct, i.e., each of them contains exactly four digits, in each of them all the four digits are different, and there can be a leading zero. All the experimental numbers are different. As the guesser hasn't guessed the number yet, the answer "4 bulls 0 cows" is not present.
Output
If the input data is enough to determine the sought number, print the number with four digits on a single line. If it has less than four digits, add leading zero. If the data is not enough, print "Need more data" without the quotes. If the thinker happens to have made a mistake in his replies, print "Incorrect data" without the quotes.
Examples
Input
2
1263 1 2
8103 2 1
Output
Need more data
Input
2
1234 2 2
1256 0 2
Output
2134
Input
2
0123 1 1
4567 1 2
Output
Incorrect data
Submitted Solution:
```
import sys
from array import array # noqa: F401
from itertools import product
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n = int(input())
cand = set()
for i, (a, b, c) in enumerate(input().split() for _ in range(n)):
a = list(map(int, a))
b, c = int(b), int(c)
s = set()
for p in product(range(10), repeat=4):
if len(set(p)) < 4:
continue
b_, c_ = 0, 0
for j in range(4):
if p[j] == a[j]:
b_ += 1
elif p[j] in a:
c_ += 1
if b == b_ and c == c_:
s.add(''.join(map(str, p)))
if i == 0:
cand = s
else:
cand &= s
if len(cand) == 1:
print(cand.pop())
elif len(cand) > 1:
print('Need more data')
elif not cand:
print('Incorrect data')
else:
assert False
```
Yes
| 107,431 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it.
The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all it's digits should be different. The guesser tries to guess the number. He makes a series of guesses, trying experimental numbers and receives answers from the first person in the format "x bulls y cows". x represents the number of digits in the experimental number that occupy the same positions as in the sought number. y represents the number of digits of the experimental number that present in the sought number, but occupy different positions. Naturally, the experimental numbers, as well as the sought number, are represented by four-digit numbers where all digits are different and a leading zero can be present.
For example, let's suppose that the thinker thought of the number 0123. Then the guessers' experimental number 1263 will receive a reply "1 bull 2 cows" (3 occupies the same positions in both numbers and 1 and 2 are present in both numbers but they occupy different positions). Also, the answer to number 8103 will be "2 bulls 1 cow" (analogically, 1 and 3 occupy the same positions and 0 occupies a different one).
When the guesser is answered "4 bulls 0 cows", the game is over.
Now the guesser has already made several guesses and wants to know whether his next guess can possibly be the last one.
Input
The first input line contains an integer n (1 β€ n β€ 10) which represents the number of already made guesses. Then follow n lines in the form of "ai bi ci", where ai is the i-th experimental number, bi is the number of bulls, ci is the number of cows (1 β€ i β€ n, 0 β€ bi, ci, bi + ci β€ 4). The experimental numbers are correct, i.e., each of them contains exactly four digits, in each of them all the four digits are different, and there can be a leading zero. All the experimental numbers are different. As the guesser hasn't guessed the number yet, the answer "4 bulls 0 cows" is not present.
Output
If the input data is enough to determine the sought number, print the number with four digits on a single line. If it has less than four digits, add leading zero. If the data is not enough, print "Need more data" without the quotes. If the thinker happens to have made a mistake in his replies, print "Incorrect data" without the quotes.
Examples
Input
2
1263 1 2
8103 2 1
Output
Need more data
Input
2
1234 2 2
1256 0 2
Output
2134
Input
2
0123 1 1
4567 1 2
Output
Incorrect data
Submitted Solution:
```
'''input
8
7954 0 1
5638 0 1
8204 0 2
8293 1 1
3598 0 1
0894 0 1
6324 1 2
0572 0 1
'''
from sys import stdin, setrecursionlimit
import math
from collections import defaultdict, deque
import time
from itertools import combinations, permutations
from copy import deepcopy
setrecursionlimit(15000)
def take_intersection():
pass
def discover_digits(guess):
myset = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}
flag = 0
count = 0
final = []
comb = permutations(myset, 4)
for i in comb:
ans = get_answer(guess, list(i))
if len(ans) == 4:
count += 1
final.append(ans)
flag = 1
if count == 1:
for i in final[0]:
print(i, end = '')
elif count > 1:
print("Need more data")
if flag == 0:
print("Incorrect data")
def check(arr, guess, index):
first = 0
total = 0
second = 0
for i in range(4):
if arr[i] == int(guess[index][0][i]):
first += 1
if str(arr[i]) in guess[index][0]:
total += 1
second = total - first
if first == int(guess[index][1]) and second == int(guess[index][2]):
return True
else:
return False
def get_answer(guess, answer):
flag = 0
ans = []
for j in range(len(guess)):
num = guess[j][0]
if check(answer, guess, j):
pass
else:
break
else:
ans = answer
return ans
# main starts
n = int(stdin.readline().strip())
guess = []
for _ in range(n):
guess.append(list(map(str, stdin.readline().split())))
# getting ready final list
final = []
base = set()
discover_digits(guess)
```
Yes
| 107,432 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it.
The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all it's digits should be different. The guesser tries to guess the number. He makes a series of guesses, trying experimental numbers and receives answers from the first person in the format "x bulls y cows". x represents the number of digits in the experimental number that occupy the same positions as in the sought number. y represents the number of digits of the experimental number that present in the sought number, but occupy different positions. Naturally, the experimental numbers, as well as the sought number, are represented by four-digit numbers where all digits are different and a leading zero can be present.
For example, let's suppose that the thinker thought of the number 0123. Then the guessers' experimental number 1263 will receive a reply "1 bull 2 cows" (3 occupies the same positions in both numbers and 1 and 2 are present in both numbers but they occupy different positions). Also, the answer to number 8103 will be "2 bulls 1 cow" (analogically, 1 and 3 occupy the same positions and 0 occupies a different one).
When the guesser is answered "4 bulls 0 cows", the game is over.
Now the guesser has already made several guesses and wants to know whether his next guess can possibly be the last one.
Input
The first input line contains an integer n (1 β€ n β€ 10) which represents the number of already made guesses. Then follow n lines in the form of "ai bi ci", where ai is the i-th experimental number, bi is the number of bulls, ci is the number of cows (1 β€ i β€ n, 0 β€ bi, ci, bi + ci β€ 4). The experimental numbers are correct, i.e., each of them contains exactly four digits, in each of them all the four digits are different, and there can be a leading zero. All the experimental numbers are different. As the guesser hasn't guessed the number yet, the answer "4 bulls 0 cows" is not present.
Output
If the input data is enough to determine the sought number, print the number with four digits on a single line. If it has less than four digits, add leading zero. If the data is not enough, print "Need more data" without the quotes. If the thinker happens to have made a mistake in his replies, print "Incorrect data" without the quotes.
Examples
Input
2
1263 1 2
8103 2 1
Output
Need more data
Input
2
1234 2 2
1256 0 2
Output
2134
Input
2
0123 1 1
4567 1 2
Output
Incorrect data
Submitted Solution:
```
import sys
import math
MAXNUM = math.inf
MINNUM = -1 * math.inf
ASCIILOWER = 97
ASCIIUPPER = 65
def getInt():
return int(sys.stdin.readline().rstrip())
def getInts():
return map(int, sys.stdin.readline().rstrip().split(" "))
def getString():
return sys.stdin.readline().rstrip()
def printOutput(ans):
sys.stdout.write()
pass
def numChecker(num, genNum, b, c):
"""checks number for bulls and cows against guess"""
# order check:
bullCheck = sum([1 if a == b else 0 for (a, b) in zip(num, genNum)])
# number check, this works because all digits must be different
cowCheck = sum([1 if a in num else 0 for a in genNum]) - bullCheck
return bullCheck == b and cowCheck == c
def padLeft(s):
while len(s) < 4:
s = "0" + s
return s
def isLegal(s):
for i in range(0, len(s)):
for j in range(0, len(s)):
if i != j and s[i] == s[j]:
return False
return True
def solve(o):
initialSet = set()
for i in range(1, 10000):
num = padLeft(str(i))
if isLegal(num):
initialSet.add(num)
# print(initialSet)
for op in o:
guess, b, c = op
newSet = set()
for num in initialSet:
if numChecker(guess, num, b, c):
newSet.add(num)
initialSet = set.intersection(initialSet, newSet)
if len(initialSet) == 1:
return initialSet.pop()
elif len(initialSet) > 1:
return "Need more data"
return "Incorrect data"
def readinput():
ops = getInt()
o = []
for _ in range(ops):
num, b, c = getString().split(" ")
o.append((num, int(b), int(c)))
print(solve(o))
readinput()
```
Yes
| 107,433 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it.
The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all it's digits should be different. The guesser tries to guess the number. He makes a series of guesses, trying experimental numbers and receives answers from the first person in the format "x bulls y cows". x represents the number of digits in the experimental number that occupy the same positions as in the sought number. y represents the number of digits of the experimental number that present in the sought number, but occupy different positions. Naturally, the experimental numbers, as well as the sought number, are represented by four-digit numbers where all digits are different and a leading zero can be present.
For example, let's suppose that the thinker thought of the number 0123. Then the guessers' experimental number 1263 will receive a reply "1 bull 2 cows" (3 occupies the same positions in both numbers and 1 and 2 are present in both numbers but they occupy different positions). Also, the answer to number 8103 will be "2 bulls 1 cow" (analogically, 1 and 3 occupy the same positions and 0 occupies a different one).
When the guesser is answered "4 bulls 0 cows", the game is over.
Now the guesser has already made several guesses and wants to know whether his next guess can possibly be the last one.
Input
The first input line contains an integer n (1 β€ n β€ 10) which represents the number of already made guesses. Then follow n lines in the form of "ai bi ci", where ai is the i-th experimental number, bi is the number of bulls, ci is the number of cows (1 β€ i β€ n, 0 β€ bi, ci, bi + ci β€ 4). The experimental numbers are correct, i.e., each of them contains exactly four digits, in each of them all the four digits are different, and there can be a leading zero. All the experimental numbers are different. As the guesser hasn't guessed the number yet, the answer "4 bulls 0 cows" is not present.
Output
If the input data is enough to determine the sought number, print the number with four digits on a single line. If it has less than four digits, add leading zero. If the data is not enough, print "Need more data" without the quotes. If the thinker happens to have made a mistake in his replies, print "Incorrect data" without the quotes.
Examples
Input
2
1263 1 2
8103 2 1
Output
Need more data
Input
2
1234 2 2
1256 0 2
Output
2134
Input
2
0123 1 1
4567 1 2
Output
Incorrect data
Submitted Solution:
```
def is_valid_cand(a, b, c, cand):
a = str(a)
cand = str(cand)
#if cand == '3210':
# print(len(set(str(cand)).intersection(set(str(a)))), a, cand)
if len(set(str(cand)).intersection(set(str(a)))) != b + c:
return False
total_b = 0
total_c = 0
for x, y in zip(str(cand), str(a)):
if x == y:
total_b += 1
elif x in a:
total_c += 1
# print(total_b, total_c)
if total_b == b and total_c == c:
return True
return False
cands = ['0'* (4-len(str(i)))+str(i) for i in range(10000) if len(set('0'* (4-len(str(i)))+str(i))) == 4]
n = int(input())
for i in range(n):
a, b, c = list(map(str, input().split()))
b = int(b)
c = int(c)
to_del = set()
for i in range(len(cands)):
valid = is_valid_cand(a, b, c, cands[i])
if not valid:
to_del.add(cands[i])
cands = [x for x in cands if x not in to_del]
#print(cands)
if len(cands) == 0:
print('Incorrect data')
elif len(cands) > 1:
print('Need more data')
elif len(cands) == 1:
print(cands[0])
```
Yes
| 107,434 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it.
The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all it's digits should be different. The guesser tries to guess the number. He makes a series of guesses, trying experimental numbers and receives answers from the first person in the format "x bulls y cows". x represents the number of digits in the experimental number that occupy the same positions as in the sought number. y represents the number of digits of the experimental number that present in the sought number, but occupy different positions. Naturally, the experimental numbers, as well as the sought number, are represented by four-digit numbers where all digits are different and a leading zero can be present.
For example, let's suppose that the thinker thought of the number 0123. Then the guessers' experimental number 1263 will receive a reply "1 bull 2 cows" (3 occupies the same positions in both numbers and 1 and 2 are present in both numbers but they occupy different positions). Also, the answer to number 8103 will be "2 bulls 1 cow" (analogically, 1 and 3 occupy the same positions and 0 occupies a different one).
When the guesser is answered "4 bulls 0 cows", the game is over.
Now the guesser has already made several guesses and wants to know whether his next guess can possibly be the last one.
Input
The first input line contains an integer n (1 β€ n β€ 10) which represents the number of already made guesses. Then follow n lines in the form of "ai bi ci", where ai is the i-th experimental number, bi is the number of bulls, ci is the number of cows (1 β€ i β€ n, 0 β€ bi, ci, bi + ci β€ 4). The experimental numbers are correct, i.e., each of them contains exactly four digits, in each of them all the four digits are different, and there can be a leading zero. All the experimental numbers are different. As the guesser hasn't guessed the number yet, the answer "4 bulls 0 cows" is not present.
Output
If the input data is enough to determine the sought number, print the number with four digits on a single line. If it has less than four digits, add leading zero. If the data is not enough, print "Need more data" without the quotes. If the thinker happens to have made a mistake in his replies, print "Incorrect data" without the quotes.
Examples
Input
2
1263 1 2
8103 2 1
Output
Need more data
Input
2
1234 2 2
1256 0 2
Output
2134
Input
2
0123 1 1
4567 1 2
Output
Incorrect data
Submitted Solution:
```
n=int(input())
array=[str(t).zfill(4) for t in range(10000) if len(set(str(t).zfill(4)))==4]
print (array)
for _ in range(n):
a,b,c=input().split()
b=int(b)
c=int(c)
# for u in array:
# print (u, set(u).intersection(set(a)))
array=[u for u in array if len(set(u).intersection(set(a)))==b+c and sum(u[i]==a[i] for i in range(4))==b]
# print (array)
if len(array)>1:print("Need more data")
elif len(array)==1:print(array[0])
else:print("Incorrect data")
```
No
| 107,435 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it.
The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all it's digits should be different. The guesser tries to guess the number. He makes a series of guesses, trying experimental numbers and receives answers from the first person in the format "x bulls y cows". x represents the number of digits in the experimental number that occupy the same positions as in the sought number. y represents the number of digits of the experimental number that present in the sought number, but occupy different positions. Naturally, the experimental numbers, as well as the sought number, are represented by four-digit numbers where all digits are different and a leading zero can be present.
For example, let's suppose that the thinker thought of the number 0123. Then the guessers' experimental number 1263 will receive a reply "1 bull 2 cows" (3 occupies the same positions in both numbers and 1 and 2 are present in both numbers but they occupy different positions). Also, the answer to number 8103 will be "2 bulls 1 cow" (analogically, 1 and 3 occupy the same positions and 0 occupies a different one).
When the guesser is answered "4 bulls 0 cows", the game is over.
Now the guesser has already made several guesses and wants to know whether his next guess can possibly be the last one.
Input
The first input line contains an integer n (1 β€ n β€ 10) which represents the number of already made guesses. Then follow n lines in the form of "ai bi ci", where ai is the i-th experimental number, bi is the number of bulls, ci is the number of cows (1 β€ i β€ n, 0 β€ bi, ci, bi + ci β€ 4). The experimental numbers are correct, i.e., each of them contains exactly four digits, in each of them all the four digits are different, and there can be a leading zero. All the experimental numbers are different. As the guesser hasn't guessed the number yet, the answer "4 bulls 0 cows" is not present.
Output
If the input data is enough to determine the sought number, print the number with four digits on a single line. If it has less than four digits, add leading zero. If the data is not enough, print "Need more data" without the quotes. If the thinker happens to have made a mistake in his replies, print "Incorrect data" without the quotes.
Examples
Input
2
1263 1 2
8103 2 1
Output
Need more data
Input
2
1234 2 2
1256 0 2
Output
2134
Input
2
0123 1 1
4567 1 2
Output
Incorrect data
Submitted Solution:
```
'''input
2
0123 1 1
4567 1 2
'''
from sys import stdin, setrecursionlimit
import math
from collections import defaultdict, deque
import time
from itertools import combinations, permutations
from copy import deepcopy
setrecursionlimit(15000)
def take_intersection():
pass
def discover_digits(guess):
myset = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}
flag = 0
count = 0
final = []
comb = combinations(myset, 4)
for i in comb:
ans = get_answer(guess, list(i))
if len(ans) == 4:
count += 1
final = ans
flag = 1
if count == 1:
for i in final:
print(i, end = '')
elif count > 1:
print("Need more data")
if flag == 0:
print("Incorrect data")
def check(arr, guess, index):
first = 0
total = 0
second = 0
for i in range(4):
if arr[i] == int(guess[index][0][i]):
first += 1
if str(arr[i]) in guess[index][0]:
total += 1
second = total - first
if first == int(guess[index][1]) and second == int(guess[index][2]):
return True
else:
return False
def get_answer(guess, answer):
while len(answer) < 4:
answer.append(-1)
perm = permutations(answer)
flag = 0
ans = []
for i in perm:
if flag == 1:
return ans
i = list(i)
for j in range(len(guess)):
num = guess[j][0]
if check(i, guess, j):
pass
else:
flag = 0
break
else:
flag = 1
ans = i
return ans
def check_invalid(final):
count = 0
tans = []
for element in final:
if len(element) != 4:
ans = get_answer(guess, element)
if len(ans) > 0:
return False
return True
if count == 1:
for i in tans:
print(i, end = '')
return True
else:
return False
def check_unique(final):
count = 0
tans = []
for element in final:
if len(element) == 4:
ans = get_answer(guess, element)
if len(ans) == 4:
tans = ans
count += 1
if count >= 1:
for i in tans:
print(i, end = '')
return True
else:
return False
# main starts
n = int(stdin.readline().strip())
guess = []
for _ in range(n):
guess.append(list(map(str, stdin.readline().split())))
# getting ready final list
final = []
base = set()
discover_digits(guess)
```
No
| 107,436 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it.
The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all it's digits should be different. The guesser tries to guess the number. He makes a series of guesses, trying experimental numbers and receives answers from the first person in the format "x bulls y cows". x represents the number of digits in the experimental number that occupy the same positions as in the sought number. y represents the number of digits of the experimental number that present in the sought number, but occupy different positions. Naturally, the experimental numbers, as well as the sought number, are represented by four-digit numbers where all digits are different and a leading zero can be present.
For example, let's suppose that the thinker thought of the number 0123. Then the guessers' experimental number 1263 will receive a reply "1 bull 2 cows" (3 occupies the same positions in both numbers and 1 and 2 are present in both numbers but they occupy different positions). Also, the answer to number 8103 will be "2 bulls 1 cow" (analogically, 1 and 3 occupy the same positions and 0 occupies a different one).
When the guesser is answered "4 bulls 0 cows", the game is over.
Now the guesser has already made several guesses and wants to know whether his next guess can possibly be the last one.
Input
The first input line contains an integer n (1 β€ n β€ 10) which represents the number of already made guesses. Then follow n lines in the form of "ai bi ci", where ai is the i-th experimental number, bi is the number of bulls, ci is the number of cows (1 β€ i β€ n, 0 β€ bi, ci, bi + ci β€ 4). The experimental numbers are correct, i.e., each of them contains exactly four digits, in each of them all the four digits are different, and there can be a leading zero. All the experimental numbers are different. As the guesser hasn't guessed the number yet, the answer "4 bulls 0 cows" is not present.
Output
If the input data is enough to determine the sought number, print the number with four digits on a single line. If it has less than four digits, add leading zero. If the data is not enough, print "Need more data" without the quotes. If the thinker happens to have made a mistake in his replies, print "Incorrect data" without the quotes.
Examples
Input
2
1263 1 2
8103 2 1
Output
Need more data
Input
2
1234 2 2
1256 0 2
Output
2134
Input
2
0123 1 1
4567 1 2
Output
Incorrect data
Submitted Solution:
```
import math
from os import startfile
import random
from queue import Queue
import time
import heapq
import sys
def u(a):
freq={}
for e in a:
if e not in freq:
freq[e]=0
freq[e]+=1
for e in freq:
if freq[e]>1:
return False
return True
def main(q):
ans=[]
for i in range(1,10000):
s=[c for c in str(i)]
if len(s)!=4:
s=[0]*(4-len(s))+s
if u(s):
w=True
for e in q:
s2,b,c=e
s2=[c for c in str(s2)]
if len(s2)!=4:
s2=[0]*(4-len(s2))+s2
for k in range(len(s)):
if s[k]==s2[k]:
b-=1
else:
if s[k] in s2:
c-=1
if c!=0 or b!=0:
w=False
break
if w:
ans.append(s)
if len(ans)==1:
print("".join(ans[0]))
elif len(ans)==0:
print('Incorrect data')
else:
print("Need more data")
return
n=int(input())
arr=[]
for i in range(n):
arr.append(list(map(int,input().split())))
main(arr)
```
No
| 107,437 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it.
The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all it's digits should be different. The guesser tries to guess the number. He makes a series of guesses, trying experimental numbers and receives answers from the first person in the format "x bulls y cows". x represents the number of digits in the experimental number that occupy the same positions as in the sought number. y represents the number of digits of the experimental number that present in the sought number, but occupy different positions. Naturally, the experimental numbers, as well as the sought number, are represented by four-digit numbers where all digits are different and a leading zero can be present.
For example, let's suppose that the thinker thought of the number 0123. Then the guessers' experimental number 1263 will receive a reply "1 bull 2 cows" (3 occupies the same positions in both numbers and 1 and 2 are present in both numbers but they occupy different positions). Also, the answer to number 8103 will be "2 bulls 1 cow" (analogically, 1 and 3 occupy the same positions and 0 occupies a different one).
When the guesser is answered "4 bulls 0 cows", the game is over.
Now the guesser has already made several guesses and wants to know whether his next guess can possibly be the last one.
Input
The first input line contains an integer n (1 β€ n β€ 10) which represents the number of already made guesses. Then follow n lines in the form of "ai bi ci", where ai is the i-th experimental number, bi is the number of bulls, ci is the number of cows (1 β€ i β€ n, 0 β€ bi, ci, bi + ci β€ 4). The experimental numbers are correct, i.e., each of them contains exactly four digits, in each of them all the four digits are different, and there can be a leading zero. All the experimental numbers are different. As the guesser hasn't guessed the number yet, the answer "4 bulls 0 cows" is not present.
Output
If the input data is enough to determine the sought number, print the number with four digits on a single line. If it has less than four digits, add leading zero. If the data is not enough, print "Need more data" without the quotes. If the thinker happens to have made a mistake in his replies, print "Incorrect data" without the quotes.
Examples
Input
2
1263 1 2
8103 2 1
Output
Need more data
Input
2
1234 2 2
1256 0 2
Output
2134
Input
2
0123 1 1
4567 1 2
Output
Incorrect data
Submitted Solution:
```
def is_valid_cand(a, b, c, cand):
a = str(a)
cand = str(cand)
if len(set(str(cand)).intersection(set(str(a)))) != b + c:
return False
total_b = 0
total_c = 0
for x, y in zip(str(cand), str(a)):
if x == y:
total_b += 1
elif x in a:
total_c += 1
# print(total_b, total_c)
if total_b == b and total_c == c:
return True
return False
cands = ['0'* (4-len(str(i)))+str(i) for i in range(10000) if len(set('0'* (4-len(str(i)))+str(i))) == 4]
n = int(input())
for i in range(n):
a, b, c = list(map(int, input().split()))
to_del = set()
for i in range(len(cands)):
valid = is_valid_cand(a, b, c, cands[i])
if not valid:
to_del.add(cands[i])
cands = [x for x in cands if x not in to_del]
if len(cands) == 0:
print('Incorrect data')
break
if len(cands) > 1 and i == n - 1:
print('Need more data')
break
elif len(cands) == 1:
print(cands[0])
```
No
| 107,438 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem can't give her the same number of stones twice in a row. For example, he can give her 3 stones, then 1 stone, then again 3 stones, but he can't give her 3 stones and then again 3 stones right after that.
How many times can Artem give presents to Masha?
Input
The only line of the input contains a single integer n (1 β€ n β€ 109) β number of stones Artem received on his birthday.
Output
Print the maximum possible number of times Artem can give presents to Masha.
Examples
Input
1
Output
1
Input
2
Output
1
Input
3
Output
2
Input
4
Output
3
Note
In the first sample, Artem can only give 1 stone to Masha.
In the second sample, Atrem can give Masha 1 or 2 stones, though he can't give her 1 stone two times.
In the third sample, Atrem can first give Masha 2 stones, a then 1 more stone.
In the fourth sample, Atrem can first give Masha 1 stone, then 2 stones, and finally 1 stone again.
Tags: math
Correct Solution:
```
n=int(input())
m=n%3
z=n//3
if m==0:
print(z*2)
else:
print(z*2+1)
```
| 107,439 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem can't give her the same number of stones twice in a row. For example, he can give her 3 stones, then 1 stone, then again 3 stones, but he can't give her 3 stones and then again 3 stones right after that.
How many times can Artem give presents to Masha?
Input
The only line of the input contains a single integer n (1 β€ n β€ 109) β number of stones Artem received on his birthday.
Output
Print the maximum possible number of times Artem can give presents to Masha.
Examples
Input
1
Output
1
Input
2
Output
1
Input
3
Output
2
Input
4
Output
3
Note
In the first sample, Artem can only give 1 stone to Masha.
In the second sample, Atrem can give Masha 1 or 2 stones, though he can't give her 1 stone two times.
In the third sample, Atrem can first give Masha 2 stones, a then 1 more stone.
In the fourth sample, Atrem can first give Masha 1 stone, then 2 stones, and finally 1 stone again.
Tags: math
Correct Solution:
```
n=int(input())
c=n//3
c*=2
if n%3!=0:
c+=1
print(c)
```
| 107,440 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem can't give her the same number of stones twice in a row. For example, he can give her 3 stones, then 1 stone, then again 3 stones, but he can't give her 3 stones and then again 3 stones right after that.
How many times can Artem give presents to Masha?
Input
The only line of the input contains a single integer n (1 β€ n β€ 109) β number of stones Artem received on his birthday.
Output
Print the maximum possible number of times Artem can give presents to Masha.
Examples
Input
1
Output
1
Input
2
Output
1
Input
3
Output
2
Input
4
Output
3
Note
In the first sample, Artem can only give 1 stone to Masha.
In the second sample, Atrem can give Masha 1 or 2 stones, though he can't give her 1 stone two times.
In the third sample, Atrem can first give Masha 2 stones, a then 1 more stone.
In the fourth sample, Atrem can first give Masha 1 stone, then 2 stones, and finally 1 stone again.
Tags: math
Correct Solution:
```
n=int(input())
if n%3==0:
print(2*n//3)
else:
print(2*(n//3+1)-1)
```
| 107,441 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem can't give her the same number of stones twice in a row. For example, he can give her 3 stones, then 1 stone, then again 3 stones, but he can't give her 3 stones and then again 3 stones right after that.
How many times can Artem give presents to Masha?
Input
The only line of the input contains a single integer n (1 β€ n β€ 109) β number of stones Artem received on his birthday.
Output
Print the maximum possible number of times Artem can give presents to Masha.
Examples
Input
1
Output
1
Input
2
Output
1
Input
3
Output
2
Input
4
Output
3
Note
In the first sample, Artem can only give 1 stone to Masha.
In the second sample, Atrem can give Masha 1 or 2 stones, though he can't give her 1 stone two times.
In the third sample, Atrem can first give Masha 2 stones, a then 1 more stone.
In the fourth sample, Atrem can first give Masha 1 stone, then 2 stones, and finally 1 stone again.
Tags: math
Correct Solution:
```
n = int(input())
result = 2 * (n // 3)
if n % 3 != 0:
result += 1
print(result)
```
| 107,442 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem can't give her the same number of stones twice in a row. For example, he can give her 3 stones, then 1 stone, then again 3 stones, but he can't give her 3 stones and then again 3 stones right after that.
How many times can Artem give presents to Masha?
Input
The only line of the input contains a single integer n (1 β€ n β€ 109) β number of stones Artem received on his birthday.
Output
Print the maximum possible number of times Artem can give presents to Masha.
Examples
Input
1
Output
1
Input
2
Output
1
Input
3
Output
2
Input
4
Output
3
Note
In the first sample, Artem can only give 1 stone to Masha.
In the second sample, Atrem can give Masha 1 or 2 stones, though he can't give her 1 stone two times.
In the third sample, Atrem can first give Masha 2 stones, a then 1 more stone.
In the fourth sample, Atrem can first give Masha 1 stone, then 2 stones, and finally 1 stone again.
Tags: math
Correct Solution:
```
n=int(input())
print(n//3*2+(n%3>0))
```
| 107,443 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem can't give her the same number of stones twice in a row. For example, he can give her 3 stones, then 1 stone, then again 3 stones, but he can't give her 3 stones and then again 3 stones right after that.
How many times can Artem give presents to Masha?
Input
The only line of the input contains a single integer n (1 β€ n β€ 109) β number of stones Artem received on his birthday.
Output
Print the maximum possible number of times Artem can give presents to Masha.
Examples
Input
1
Output
1
Input
2
Output
1
Input
3
Output
2
Input
4
Output
3
Note
In the first sample, Artem can only give 1 stone to Masha.
In the second sample, Atrem can give Masha 1 or 2 stones, though he can't give her 1 stone two times.
In the third sample, Atrem can first give Masha 2 stones, a then 1 more stone.
In the fourth sample, Atrem can first give Masha 1 stone, then 2 stones, and finally 1 stone again.
Tags: math
Correct Solution:
```
n = int(input())
print(2 * (n // 3) + int(n % 3 != 0))
```
| 107,444 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem can't give her the same number of stones twice in a row. For example, he can give her 3 stones, then 1 stone, then again 3 stones, but he can't give her 3 stones and then again 3 stones right after that.
How many times can Artem give presents to Masha?
Input
The only line of the input contains a single integer n (1 β€ n β€ 109) β number of stones Artem received on his birthday.
Output
Print the maximum possible number of times Artem can give presents to Masha.
Examples
Input
1
Output
1
Input
2
Output
1
Input
3
Output
2
Input
4
Output
3
Note
In the first sample, Artem can only give 1 stone to Masha.
In the second sample, Atrem can give Masha 1 or 2 stones, though he can't give her 1 stone two times.
In the third sample, Atrem can first give Masha 2 stones, a then 1 more stone.
In the fourth sample, Atrem can first give Masha 1 stone, then 2 stones, and finally 1 stone again.
Tags: math
Correct Solution:
```
#rOkY
#FuCk
################################## kOpAl #####################################
t=int(input())
g=0
g=t//3
g=g*2
if(t%3>0):
g+=1
print(g)
```
| 107,445 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem can't give her the same number of stones twice in a row. For example, he can give her 3 stones, then 1 stone, then again 3 stones, but he can't give her 3 stones and then again 3 stones right after that.
How many times can Artem give presents to Masha?
Input
The only line of the input contains a single integer n (1 β€ n β€ 109) β number of stones Artem received on his birthday.
Output
Print the maximum possible number of times Artem can give presents to Masha.
Examples
Input
1
Output
1
Input
2
Output
1
Input
3
Output
2
Input
4
Output
3
Note
In the first sample, Artem can only give 1 stone to Masha.
In the second sample, Atrem can give Masha 1 or 2 stones, though he can't give her 1 stone two times.
In the third sample, Atrem can first give Masha 2 stones, a then 1 more stone.
In the fourth sample, Atrem can first give Masha 1 stone, then 2 stones, and finally 1 stone again.
Tags: math
Correct Solution:
```
n=int(input())
ans=(n//3)*2
if n%3 !=0:
ans += 1
print(ans)
```
| 107,446 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem can't give her the same number of stones twice in a row. For example, he can give her 3 stones, then 1 stone, then again 3 stones, but he can't give her 3 stones and then again 3 stones right after that.
How many times can Artem give presents to Masha?
Input
The only line of the input contains a single integer n (1 β€ n β€ 109) β number of stones Artem received on his birthday.
Output
Print the maximum possible number of times Artem can give presents to Masha.
Examples
Input
1
Output
1
Input
2
Output
1
Input
3
Output
2
Input
4
Output
3
Note
In the first sample, Artem can only give 1 stone to Masha.
In the second sample, Atrem can give Masha 1 or 2 stones, though he can't give her 1 stone two times.
In the third sample, Atrem can first give Masha 2 stones, a then 1 more stone.
In the fourth sample, Atrem can first give Masha 1 stone, then 2 stones, and finally 1 stone again.
Submitted Solution:
```
n=int(input())
count=0
if n=="1" or n=='2':
print("1")
exit(0)
else:
while n>0:
n=n-1
count+=1
if n>=2:
n=n-2
count+=1
else:
print(count)
exit(0)
print(count)
```
Yes
| 107,447 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem can't give her the same number of stones twice in a row. For example, he can give her 3 stones, then 1 stone, then again 3 stones, but he can't give her 3 stones and then again 3 stones right after that.
How many times can Artem give presents to Masha?
Input
The only line of the input contains a single integer n (1 β€ n β€ 109) β number of stones Artem received on his birthday.
Output
Print the maximum possible number of times Artem can give presents to Masha.
Examples
Input
1
Output
1
Input
2
Output
1
Input
3
Output
2
Input
4
Output
3
Note
In the first sample, Artem can only give 1 stone to Masha.
In the second sample, Atrem can give Masha 1 or 2 stones, though he can't give her 1 stone two times.
In the third sample, Atrem can first give Masha 2 stones, a then 1 more stone.
In the fourth sample, Atrem can first give Masha 1 stone, then 2 stones, and finally 1 stone again.
Submitted Solution:
```
n = int(input())
if n % 3 == 2:
n -= 1
print(((n // 3) * 2) + (n % 3))
```
Yes
| 107,448 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem can't give her the same number of stones twice in a row. For example, he can give her 3 stones, then 1 stone, then again 3 stones, but he can't give her 3 stones and then again 3 stones right after that.
How many times can Artem give presents to Masha?
Input
The only line of the input contains a single integer n (1 β€ n β€ 109) β number of stones Artem received on his birthday.
Output
Print the maximum possible number of times Artem can give presents to Masha.
Examples
Input
1
Output
1
Input
2
Output
1
Input
3
Output
2
Input
4
Output
3
Note
In the first sample, Artem can only give 1 stone to Masha.
In the second sample, Atrem can give Masha 1 or 2 stones, though he can't give her 1 stone two times.
In the third sample, Atrem can first give Masha 2 stones, a then 1 more stone.
In the fourth sample, Atrem can first give Masha 1 stone, then 2 stones, and finally 1 stone again.
Submitted Solution:
```
n=int(input())
if(n==1 or n==2):
print(1)
else:
if(n%3==0):
print(2*(n//3))
else:
print(2*(n//3)+1)
```
Yes
| 107,449 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem can't give her the same number of stones twice in a row. For example, he can give her 3 stones, then 1 stone, then again 3 stones, but he can't give her 3 stones and then again 3 stones right after that.
How many times can Artem give presents to Masha?
Input
The only line of the input contains a single integer n (1 β€ n β€ 109) β number of stones Artem received on his birthday.
Output
Print the maximum possible number of times Artem can give presents to Masha.
Examples
Input
1
Output
1
Input
2
Output
1
Input
3
Output
2
Input
4
Output
3
Note
In the first sample, Artem can only give 1 stone to Masha.
In the second sample, Atrem can give Masha 1 or 2 stones, though he can't give her 1 stone two times.
In the third sample, Atrem can first give Masha 2 stones, a then 1 more stone.
In the fourth sample, Atrem can first give Masha 1 stone, then 2 stones, and finally 1 stone again.
Submitted Solution:
```
n = int(input())
r = n/1.5
if(r-int(r)>0.5):
r=int(r)+1
else:
r=int(r)
print(r)
```
Yes
| 107,450 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem can't give her the same number of stones twice in a row. For example, he can give her 3 stones, then 1 stone, then again 3 stones, but he can't give her 3 stones and then again 3 stones right after that.
How many times can Artem give presents to Masha?
Input
The only line of the input contains a single integer n (1 β€ n β€ 109) β number of stones Artem received on his birthday.
Output
Print the maximum possible number of times Artem can give presents to Masha.
Examples
Input
1
Output
1
Input
2
Output
1
Input
3
Output
2
Input
4
Output
3
Note
In the first sample, Artem can only give 1 stone to Masha.
In the second sample, Atrem can give Masha 1 or 2 stones, though he can't give her 1 stone two times.
In the third sample, Atrem can first give Masha 2 stones, a then 1 more stone.
In the fourth sample, Atrem can first give Masha 1 stone, then 2 stones, and finally 1 stone again.
Submitted Solution:
```
import math
stones = int(input())
if stones >= 3: print(math.floor(stones/3)*2 + stones%3)
else: print("1")
```
No
| 107,451 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem can't give her the same number of stones twice in a row. For example, he can give her 3 stones, then 1 stone, then again 3 stones, but he can't give her 3 stones and then again 3 stones right after that.
How many times can Artem give presents to Masha?
Input
The only line of the input contains a single integer n (1 β€ n β€ 109) β number of stones Artem received on his birthday.
Output
Print the maximum possible number of times Artem can give presents to Masha.
Examples
Input
1
Output
1
Input
2
Output
1
Input
3
Output
2
Input
4
Output
3
Note
In the first sample, Artem can only give 1 stone to Masha.
In the second sample, Atrem can give Masha 1 or 2 stones, though he can't give her 1 stone two times.
In the third sample, Atrem can first give Masha 2 stones, a then 1 more stone.
In the fourth sample, Atrem can first give Masha 1 stone, then 2 stones, and finally 1 stone again.
Submitted Solution:
```
n = int(input())
if n == 1 or n == 2: print(1)
elif n == 4 or n == 5: print(3)
elif n % 3 == 0: print((n//3)*2)
else: print((n//3)-1)
```
No
| 107,452 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem can't give her the same number of stones twice in a row. For example, he can give her 3 stones, then 1 stone, then again 3 stones, but he can't give her 3 stones and then again 3 stones right after that.
How many times can Artem give presents to Masha?
Input
The only line of the input contains a single integer n (1 β€ n β€ 109) β number of stones Artem received on his birthday.
Output
Print the maximum possible number of times Artem can give presents to Masha.
Examples
Input
1
Output
1
Input
2
Output
1
Input
3
Output
2
Input
4
Output
3
Note
In the first sample, Artem can only give 1 stone to Masha.
In the second sample, Atrem can give Masha 1 or 2 stones, though he can't give her 1 stone two times.
In the third sample, Atrem can first give Masha 2 stones, a then 1 more stone.
In the fourth sample, Atrem can first give Masha 1 stone, then 2 stones, and finally 1 stone again.
Submitted Solution:
```
def main():
n = int(input())
m = n/3
r = n%3
if r == 0:
print(2*m)
else:
print(2*m + 1)
main()
```
No
| 107,453 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem can't give her the same number of stones twice in a row. For example, he can give her 3 stones, then 1 stone, then again 3 stones, but he can't give her 3 stones and then again 3 stones right after that.
How many times can Artem give presents to Masha?
Input
The only line of the input contains a single integer n (1 β€ n β€ 109) β number of stones Artem received on his birthday.
Output
Print the maximum possible number of times Artem can give presents to Masha.
Examples
Input
1
Output
1
Input
2
Output
1
Input
3
Output
2
Input
4
Output
3
Note
In the first sample, Artem can only give 1 stone to Masha.
In the second sample, Atrem can give Masha 1 or 2 stones, though he can't give her 1 stone two times.
In the third sample, Atrem can first give Masha 2 stones, a then 1 more stone.
In the fourth sample, Atrem can first give Masha 1 stone, then 2 stones, and finally 1 stone again.
Submitted Solution:
```
num = int(input())
if num%3 == 0:
print(num/3)
else:
print(num//3 + 1)
```
No
| 107,454 |
Provide a correct Python 3 solution for this coding contest problem.
"The zombies are lurking outside. Waiting. Moaning. And when they come..."
"When they come?"
"I hope the Wall is high enough."
Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.
The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
Input
The first line of the input consists of two space-separated integers R and C, 1 β€ R, C β€ 100. The next R lines provide a description of the columns as follows:
* each of the R lines contains a string of length C,
* the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.
The input will contain at least one character B and it will be valid.
Output
The number of wall segments in the input configuration.
Examples
Input
3 7
.......
.......
.BB.B..
Output
2
Input
4 5
..B..
..B..
B.B.B
BBB.B
Output
2
Input
4 6
..B...
B.B.BB
BBB.BB
BBBBBB
Output
1
Input
1 1
B
Output
1
Input
10 7
.......
.......
.......
.......
.......
.......
.......
.......
...B...
B.BB.B.
Output
3
Input
8 8
........
........
........
........
.B......
.B.....B
.B.....B
.BB...BB
Output
2
Note
In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
"Correct Solution:
```
n,m = map(int,input().split())
c = []
for i in range(n):
a = list(input())
l = 0
for i in range(len(a)-1):
if(a[i]=='B' and a[i+1]=='.'):
l+=1
if(a[-1]=='B'):
l+=1
print(l)
```
| 107,455 |
Provide a correct Python 3 solution for this coding contest problem.
"The zombies are lurking outside. Waiting. Moaning. And when they come..."
"When they come?"
"I hope the Wall is high enough."
Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.
The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
Input
The first line of the input consists of two space-separated integers R and C, 1 β€ R, C β€ 100. The next R lines provide a description of the columns as follows:
* each of the R lines contains a string of length C,
* the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.
The input will contain at least one character B and it will be valid.
Output
The number of wall segments in the input configuration.
Examples
Input
3 7
.......
.......
.BB.B..
Output
2
Input
4 5
..B..
..B..
B.B.B
BBB.B
Output
2
Input
4 6
..B...
B.B.BB
BBB.BB
BBBBBB
Output
1
Input
1 1
B
Output
1
Input
10 7
.......
.......
.......
.......
.......
.......
.......
.......
...B...
B.BB.B.
Output
3
Input
8 8
........
........
........
........
.B......
.B.....B
.B.....B
.BB...BB
Output
2
Note
In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
"Correct Solution:
```
n, m = map(int, input().split())
a = ''
for _ in range(n):
a = input()
ans = 0
i = 0
while i < m:
if 'B' == a[i]:
ans += 1
while i < m and 'B' == a[i]:
i += 1
else:
i += 1
print(ans)
```
| 107,456 |
Provide a correct Python 3 solution for this coding contest problem.
"The zombies are lurking outside. Waiting. Moaning. And when they come..."
"When they come?"
"I hope the Wall is high enough."
Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.
The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
Input
The first line of the input consists of two space-separated integers R and C, 1 β€ R, C β€ 100. The next R lines provide a description of the columns as follows:
* each of the R lines contains a string of length C,
* the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.
The input will contain at least one character B and it will be valid.
Output
The number of wall segments in the input configuration.
Examples
Input
3 7
.......
.......
.BB.B..
Output
2
Input
4 5
..B..
..B..
B.B.B
BBB.B
Output
2
Input
4 6
..B...
B.B.BB
BBB.BB
BBBBBB
Output
1
Input
1 1
B
Output
1
Input
10 7
.......
.......
.......
.......
.......
.......
.......
.......
...B...
B.BB.B.
Output
3
Input
8 8
........
........
........
........
.B......
.B.....B
.B.....B
.BB...BB
Output
2
Note
In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
"Correct Solution:
```
R, C = map(int, input().split())
line = '.' * (C+2)
wall = [line]
for _ in range(R):
wall.append('.' + input() + '.')
wall.append(line)
vs = set()
ans = 0
def visit(r, c):
q = [(r, c)]
while q:
r, c = q.pop()
if (r, c) in vs:
continue
vs.add((r, c))
if wall[r-1][c] == 'B':
q.append((r-1, c))
if wall[r+1][c] == 'B':
q.append((r+1, c))
if wall[r][c-1] == 'B':
q.append((r, c-1))
if wall[r][c+1] == 'B':
q.append((r, c+1))
for r in range(1, R+1):
for c in range(1, C+1):
if wall[r][c] == 'B' and (r, c) not in vs:
ans += 1
visit(r, c)
print(ans)
```
| 107,457 |
Provide a correct Python 3 solution for this coding contest problem.
"The zombies are lurking outside. Waiting. Moaning. And when they come..."
"When they come?"
"I hope the Wall is high enough."
Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.
The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
Input
The first line of the input consists of two space-separated integers R and C, 1 β€ R, C β€ 100. The next R lines provide a description of the columns as follows:
* each of the R lines contains a string of length C,
* the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.
The input will contain at least one character B and it will be valid.
Output
The number of wall segments in the input configuration.
Examples
Input
3 7
.......
.......
.BB.B..
Output
2
Input
4 5
..B..
..B..
B.B.B
BBB.B
Output
2
Input
4 6
..B...
B.B.BB
BBB.BB
BBBBBB
Output
1
Input
1 1
B
Output
1
Input
10 7
.......
.......
.......
.......
.......
.......
.......
.......
...B...
B.BB.B.
Output
3
Input
8 8
........
........
........
........
.B......
.B.....B
.B.....B
.BB...BB
Output
2
Note
In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
"Correct Solution:
```
r,c = [int(s) for s in input().split()]
w =[]
for i in range(r):
w.append(input())
count = 0
def isEmpty(i):
for j in range(r):
if(w[j][i] == 'B'):
return False
return True
started = False
for i in range(c):
if not (isEmpty(i) or started):
started = True
count += 1
if isEmpty(i):
started = False
print(count)
```
| 107,458 |
Provide a correct Python 3 solution for this coding contest problem.
"The zombies are lurking outside. Waiting. Moaning. And when they come..."
"When they come?"
"I hope the Wall is high enough."
Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.
The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
Input
The first line of the input consists of two space-separated integers R and C, 1 β€ R, C β€ 100. The next R lines provide a description of the columns as follows:
* each of the R lines contains a string of length C,
* the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.
The input will contain at least one character B and it will be valid.
Output
The number of wall segments in the input configuration.
Examples
Input
3 7
.......
.......
.BB.B..
Output
2
Input
4 5
..B..
..B..
B.B.B
BBB.B
Output
2
Input
4 6
..B...
B.B.BB
BBB.BB
BBBBBB
Output
1
Input
1 1
B
Output
1
Input
10 7
.......
.......
.......
.......
.......
.......
.......
.......
...B...
B.BB.B.
Output
3
Input
8 8
........
........
........
........
.B......
.B.....B
.B.....B
.BB...BB
Output
2
Note
In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
"Correct Solution:
```
n, k = map(int, input().split())
rows = []
for row in range(n):
rows.append(input())
seg = []
ind = []
for i in range(n):
for j in range(k):
if rows[i][j] == 'B':
ind.append(j)
for i in range(min(ind), max(ind)+1):
c = 0
for j in rows:
if j[i] == ".":
c += 1
c -= 1
if c == 0:
seg.append(i)
seg.sort()
fin = 1
if len(seg) > 0:
fin += 1
for i in range(1, len(seg)):
if seg[i] - 1 == seg[i-1]:
continue
else:
fin += 1
print(fin)
```
| 107,459 |
Provide a correct Python 3 solution for this coding contest problem.
"The zombies are lurking outside. Waiting. Moaning. And when they come..."
"When they come?"
"I hope the Wall is high enough."
Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.
The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
Input
The first line of the input consists of two space-separated integers R and C, 1 β€ R, C β€ 100. The next R lines provide a description of the columns as follows:
* each of the R lines contains a string of length C,
* the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.
The input will contain at least one character B and it will be valid.
Output
The number of wall segments in the input configuration.
Examples
Input
3 7
.......
.......
.BB.B..
Output
2
Input
4 5
..B..
..B..
B.B.B
BBB.B
Output
2
Input
4 6
..B...
B.B.BB
BBB.BB
BBBBBB
Output
1
Input
1 1
B
Output
1
Input
10 7
.......
.......
.......
.......
.......
.......
.......
.......
...B...
B.BB.B.
Output
3
Input
8 8
........
........
........
........
.B......
.B.....B
.B.....B
.BB...BB
Output
2
Note
In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
"Correct Solution:
```
read = lambda: map(int, input().split())
n, m = read()
a = [input() for i in range(n)]
s = a[n - 1].split('.')
cnt = len(s) - s.count('')
print(cnt)
```
| 107,460 |
Provide a correct Python 3 solution for this coding contest problem.
"The zombies are lurking outside. Waiting. Moaning. And when they come..."
"When they come?"
"I hope the Wall is high enough."
Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.
The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
Input
The first line of the input consists of two space-separated integers R and C, 1 β€ R, C β€ 100. The next R lines provide a description of the columns as follows:
* each of the R lines contains a string of length C,
* the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.
The input will contain at least one character B and it will be valid.
Output
The number of wall segments in the input configuration.
Examples
Input
3 7
.......
.......
.BB.B..
Output
2
Input
4 5
..B..
..B..
B.B.B
BBB.B
Output
2
Input
4 6
..B...
B.B.BB
BBB.BB
BBBBBB
Output
1
Input
1 1
B
Output
1
Input
10 7
.......
.......
.......
.......
.......
.......
.......
.......
...B...
B.BB.B.
Output
3
Input
8 8
........
........
........
........
.B......
.B.....B
.B.....B
.BB...BB
Output
2
Note
In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
"Correct Solution:
```
r, c = input().split()
for q in range(int(r)):
s = input() + "."
print(s.count("B."))
```
| 107,461 |
Provide a correct Python 3 solution for this coding contest problem.
"The zombies are lurking outside. Waiting. Moaning. And when they come..."
"When they come?"
"I hope the Wall is high enough."
Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.
The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
Input
The first line of the input consists of two space-separated integers R and C, 1 β€ R, C β€ 100. The next R lines provide a description of the columns as follows:
* each of the R lines contains a string of length C,
* the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.
The input will contain at least one character B and it will be valid.
Output
The number of wall segments in the input configuration.
Examples
Input
3 7
.......
.......
.BB.B..
Output
2
Input
4 5
..B..
..B..
B.B.B
BBB.B
Output
2
Input
4 6
..B...
B.B.BB
BBB.BB
BBBBBB
Output
1
Input
1 1
B
Output
1
Input
10 7
.......
.......
.......
.......
.......
.......
.......
.......
...B...
B.BB.B.
Output
3
Input
8 8
........
........
........
........
.B......
.B.....B
.B.....B
.BB...BB
Output
2
Note
In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
"Correct Solution:
```
r,c=list(map(int,input().split()))
a=[]
for i in range(r):
a.append(input())
b=[]
for i in range(c):
e=0
for j in range(r):
if a[j][i]=="B":
e=1
b.append(e)
d=0
e=0
for i in range(c):
if b[i]==1:
d+=1
if b[i]==0 and d!=0:
d=0
e+=1
if d!=0:
print(e+1)
else:
print(e)
```
| 107,462 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
"The zombies are lurking outside. Waiting. Moaning. And when they come..."
"When they come?"
"I hope the Wall is high enough."
Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.
The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
Input
The first line of the input consists of two space-separated integers R and C, 1 β€ R, C β€ 100. The next R lines provide a description of the columns as follows:
* each of the R lines contains a string of length C,
* the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.
The input will contain at least one character B and it will be valid.
Output
The number of wall segments in the input configuration.
Examples
Input
3 7
.......
.......
.BB.B..
Output
2
Input
4 5
..B..
..B..
B.B.B
BBB.B
Output
2
Input
4 6
..B...
B.B.BB
BBB.BB
BBBBBB
Output
1
Input
1 1
B
Output
1
Input
10 7
.......
.......
.......
.......
.......
.......
.......
.......
...B...
B.BB.B.
Output
3
Input
8 8
........
........
........
........
.B......
.B.....B
.B.....B
.BB...BB
Output
2
Note
In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
Submitted Solution:
```
inc=input().split(' ')
for i in range(int(inc[0])):
foundation = input()
bl=True
block=0
for i in range(int(inc[1])):
if bl and foundation[i] == 'B':
bl=False
block+=1
elif (not bl) and foundation[i] == '.':
bl=True
print (block)
```
Yes
| 107,463 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
"The zombies are lurking outside. Waiting. Moaning. And when they come..."
"When they come?"
"I hope the Wall is high enough."
Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.
The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
Input
The first line of the input consists of two space-separated integers R and C, 1 β€ R, C β€ 100. The next R lines provide a description of the columns as follows:
* each of the R lines contains a string of length C,
* the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.
The input will contain at least one character B and it will be valid.
Output
The number of wall segments in the input configuration.
Examples
Input
3 7
.......
.......
.BB.B..
Output
2
Input
4 5
..B..
..B..
B.B.B
BBB.B
Output
2
Input
4 6
..B...
B.B.BB
BBB.BB
BBBBBB
Output
1
Input
1 1
B
Output
1
Input
10 7
.......
.......
.......
.......
.......
.......
.......
.......
...B...
B.BB.B.
Output
3
Input
8 8
........
........
........
........
.B......
.B.....B
.B.....B
.BB...BB
Output
2
Note
In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
Submitted Solution:
```
n, m = map(int, input().split())
a = [input() for _ in range(n)]
used = [[False] * m for _ in range(n)]
ans = 0
for i in range(n):
for j in range(m):
if not used[i][j] and a[i][j] == "B":
ans += 1
q = [(i, j)]
used[i][j] = True
head = 0
while head < len(q):
x, y = q[head]
head += 1
for d in range(4):
xx = x + (1 if d == 0 else -1 if d == 1 else 0)
yy = y + (1 if d == 2 else -1 if d == 3 else 0)
if 0 <= xx < n and 0 <= yy < m and not used[xx][yy] and a[xx][yy] == "B":
used[xx][yy] = True
q.append((xx, yy))
print(ans)
```
Yes
| 107,464 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
"The zombies are lurking outside. Waiting. Moaning. And when they come..."
"When they come?"
"I hope the Wall is high enough."
Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.
The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
Input
The first line of the input consists of two space-separated integers R and C, 1 β€ R, C β€ 100. The next R lines provide a description of the columns as follows:
* each of the R lines contains a string of length C,
* the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.
The input will contain at least one character B and it will be valid.
Output
The number of wall segments in the input configuration.
Examples
Input
3 7
.......
.......
.BB.B..
Output
2
Input
4 5
..B..
..B..
B.B.B
BBB.B
Output
2
Input
4 6
..B...
B.B.BB
BBB.BB
BBBBBB
Output
1
Input
1 1
B
Output
1
Input
10 7
.......
.......
.......
.......
.......
.......
.......
.......
...B...
B.BB.B.
Output
3
Input
8 8
........
........
........
........
.B......
.B.....B
.B.....B
.BB...BB
Output
2
Note
In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
Submitted Solution:
```
n, m = map(int, input().split())
a = [input() for i in range(n)]
ans = 0
i = 0
while i < m:
if a[n-1][i] == "B":
ans += 1
while i < m and a[n-1][i] == "B":
i += 1
i += 1
print(ans)
```
Yes
| 107,465 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
"The zombies are lurking outside. Waiting. Moaning. And when they come..."
"When they come?"
"I hope the Wall is high enough."
Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.
The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
Input
The first line of the input consists of two space-separated integers R and C, 1 β€ R, C β€ 100. The next R lines provide a description of the columns as follows:
* each of the R lines contains a string of length C,
* the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.
The input will contain at least one character B and it will be valid.
Output
The number of wall segments in the input configuration.
Examples
Input
3 7
.......
.......
.BB.B..
Output
2
Input
4 5
..B..
..B..
B.B.B
BBB.B
Output
2
Input
4 6
..B...
B.B.BB
BBB.BB
BBBBBB
Output
1
Input
1 1
B
Output
1
Input
10 7
.......
.......
.......
.......
.......
.......
.......
.......
...B...
B.BB.B.
Output
3
Input
8 8
........
........
........
........
.B......
.B.....B
.B.....B
.BB...BB
Output
2
Note
In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
Submitted Solution:
```
r = int(input().split()[0])
for i in range(r-1):
trash = input()
print((input().strip('.')+'.').count('B.'))
```
Yes
| 107,466 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
"The zombies are lurking outside. Waiting. Moaning. And when they come..."
"When they come?"
"I hope the Wall is high enough."
Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.
The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
Input
The first line of the input consists of two space-separated integers R and C, 1 β€ R, C β€ 100. The next R lines provide a description of the columns as follows:
* each of the R lines contains a string of length C,
* the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.
The input will contain at least one character B and it will be valid.
Output
The number of wall segments in the input configuration.
Examples
Input
3 7
.......
.......
.BB.B..
Output
2
Input
4 5
..B..
..B..
B.B.B
BBB.B
Output
2
Input
4 6
..B...
B.B.BB
BBB.BB
BBBBBB
Output
1
Input
1 1
B
Output
1
Input
10 7
.......
.......
.......
.......
.......
.......
.......
.......
...B...
B.BB.B.
Output
3
Input
8 8
........
........
........
........
.B......
.B.....B
.B.....B
.BB...BB
Output
2
Note
In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
Submitted Solution:
```
from sys import *
print((stdin.readlines()[-1] + '.').count('B.'))
```
No
| 107,467 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
"The zombies are lurking outside. Waiting. Moaning. And when they come..."
"When they come?"
"I hope the Wall is high enough."
Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.
The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
Input
The first line of the input consists of two space-separated integers R and C, 1 β€ R, C β€ 100. The next R lines provide a description of the columns as follows:
* each of the R lines contains a string of length C,
* the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.
The input will contain at least one character B and it will be valid.
Output
The number of wall segments in the input configuration.
Examples
Input
3 7
.......
.......
.BB.B..
Output
2
Input
4 5
..B..
..B..
B.B.B
BBB.B
Output
2
Input
4 6
..B...
B.B.BB
BBB.BB
BBBBBB
Output
1
Input
1 1
B
Output
1
Input
10 7
.......
.......
.......
.......
.......
.......
.......
.......
...B...
B.BB.B.
Output
3
Input
8 8
........
........
........
........
.B......
.B.....B
.B.....B
.BB...BB
Output
2
Note
In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
Submitted Solution:
```
import sys
#with open(filename, 'r') as f:
with sys.stdin as f:
input_list = list(f)
for i, line in enumerate(input_list):
if i == 0:
R = int(line.split(" ")[0])
else:
if i == R:
nb_walls = len(list(filter(lambda x: len(x) > 0, line.split('.'))))
print(line.split('.'), nb_walls)
```
No
| 107,468 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
"The zombies are lurking outside. Waiting. Moaning. And when they come..."
"When they come?"
"I hope the Wall is high enough."
Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.
The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
Input
The first line of the input consists of two space-separated integers R and C, 1 β€ R, C β€ 100. The next R lines provide a description of the columns as follows:
* each of the R lines contains a string of length C,
* the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.
The input will contain at least one character B and it will be valid.
Output
The number of wall segments in the input configuration.
Examples
Input
3 7
.......
.......
.BB.B..
Output
2
Input
4 5
..B..
..B..
B.B.B
BBB.B
Output
2
Input
4 6
..B...
B.B.BB
BBB.BB
BBBBBB
Output
1
Input
1 1
B
Output
1
Input
10 7
.......
.......
.......
.......
.......
.......
.......
.......
...B...
B.BB.B.
Output
3
Input
8 8
........
........
........
........
.B......
.B.....B
.B.....B
.BB...BB
Output
2
Note
In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
Submitted Solution:
```
import sys
#with open(filename, 'r') as f:
with sys.stdin as f:
input_list = list(f)
for i, line in enumerate(input_list):
if i == 0:
R = int(line.split(" ")[0])
else:
if i == R:
print(len(list(filter(lambda x: len(x) > 0, line.split('.')))))
```
No
| 107,469 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
"The zombies are lurking outside. Waiting. Moaning. And when they come..."
"When they come?"
"I hope the Wall is high enough."
Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.
The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.
Input
The first line of the input consists of two space-separated integers R and C, 1 β€ R, C β€ 100. The next R lines provide a description of the columns as follows:
* each of the R lines contains a string of length C,
* the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.
The input will contain at least one character B and it will be valid.
Output
The number of wall segments in the input configuration.
Examples
Input
3 7
.......
.......
.BB.B..
Output
2
Input
4 5
..B..
..B..
B.B.B
BBB.B
Output
2
Input
4 6
..B...
B.B.BB
BBB.BB
BBBBBB
Output
1
Input
1 1
B
Output
1
Input
10 7
.......
.......
.......
.......
.......
.......
.......
.......
...B...
B.BB.B.
Output
3
Input
8 8
........
........
........
........
.B......
.B.....B
.B.....B
.BB...BB
Output
2
Note
In the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.
Submitted Solution:
```
r,c=list(map(int,input().split()))
a=[]
for i in range(r):
a.append(input())
b=[]
for i in range(c):
e=0
for j in range(r):
if a[j][i]=="B":
e=1
b.append(e)
d=0
e=0
for i in range(c):
if b[i]==1:
d+=1
if b[i]==0 and d!=0:
d=0
e+=1
print(e)
```
No
| 107,470 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:
1. + ai β add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.
2. - ai β delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset.
3. ? s β count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left.
For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
Input
The first line of the input contains an integer t (1 β€ t β€ 100 000) β the number of operation Sonya has to perform.
Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci β the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 β€ ai < 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18.
It's guaranteed that there will be at least one query of type '?'.
It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
Output
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
Examples
Input
12
+ 1
+ 241
? 1
+ 361
- 241
? 0101
+ 101
? 101
- 101
? 101
+ 4000
? 0
Output
2
1
2
1
1
Input
4
+ 200
+ 200
- 200
? 0
Output
1
Note
Consider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input.
1. 1 and 241.
2. 361.
3. 101 and 361.
4. 361.
5. 4000.
Tags: data structures, implementation
Correct Solution:
```
#!/usr/local/env python3
# -*- encoding: utf-8 -*-
import sys
import re
def mask2(s):
m = int("0", 2)
while len(s) > 0:
m *= 2
m += int(s[0]) % 2
s = s[1:]
return m
def mask(s):
return int(re.sub("[02468]", "0", re.sub("[13579]", "1", s)), 2)
def solve():
d = dict()
n = int(sys.stdin.readline().strip())
ans = ""
for line in sys.stdin:
op, i = line.strip().split(' ')
m = mask(i)
if op == '+':
d.setdefault(m, 0)
d[m] += 1
if op == '-':
d[m] -= 1
if op == '?':
ans += "{:d}\n".format(d.get(m, 0))
return ans
if __name__ == "__main__":
ans = solve()
print(ans)
```
| 107,471 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:
1. + ai β add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.
2. - ai β delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset.
3. ? s β count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left.
For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
Input
The first line of the input contains an integer t (1 β€ t β€ 100 000) β the number of operation Sonya has to perform.
Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci β the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 β€ ai < 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18.
It's guaranteed that there will be at least one query of type '?'.
It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
Output
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
Examples
Input
12
+ 1
+ 241
? 1
+ 361
- 241
? 0101
+ 101
? 101
- 101
? 101
+ 4000
? 0
Output
2
1
2
1
1
Input
4
+ 200
+ 200
- 200
? 0
Output
1
Note
Consider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input.
1. 1 and 241.
2. 361.
3. 101 and 361.
4. 361.
5. 4000.
Tags: data structures, implementation
Correct Solution:
```
from sys import stdin, stdout
quests = int(stdin.readline().rstrip())
multi_set = {}
p = str.maketrans('0123456789', '0101010101')
for i in range(quests):
quest, core = stdin.readline().rstrip().split()
pattern = int(core.translate(p))
if quest == '+':
if pattern in multi_set.keys(): multi_set[pattern] += 1
else: multi_set[pattern] = 1
elif quest == '-': multi_set[pattern] -= 1
else:
if pattern in multi_set: stdout.write(str(multi_set[pattern])+'\n')
else: stdout.write('0\n')
```
| 107,472 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:
1. + ai β add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.
2. - ai β delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset.
3. ? s β count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left.
For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
Input
The first line of the input contains an integer t (1 β€ t β€ 100 000) β the number of operation Sonya has to perform.
Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci β the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 β€ ai < 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18.
It's guaranteed that there will be at least one query of type '?'.
It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
Output
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
Examples
Input
12
+ 1
+ 241
? 1
+ 361
- 241
? 0101
+ 101
? 101
- 101
? 101
+ 4000
? 0
Output
2
1
2
1
1
Input
4
+ 200
+ 200
- 200
? 0
Output
1
Note
Consider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input.
1. 1 and 241.
2. 361.
3. 101 and 361.
4. 361.
5. 4000.
Tags: data structures, implementation
Correct Solution:
```
t = int(input())
trantab = str.maketrans('0123456789', '0101010101')
a = {}
for i in range(t):
string = input()
oper, number = string.split()
pattern = int(number.translate(trantab))
if oper == '+':
a[pattern] = a.get(pattern, 0) + 1
elif oper == '-':
a[pattern] -= 1
if not a[pattern]:
del a[pattern]
else:
if pattern in a:
print(a[pattern])
else:
print(0)
```
| 107,473 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:
1. + ai β add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.
2. - ai β delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset.
3. ? s β count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left.
For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
Input
The first line of the input contains an integer t (1 β€ t β€ 100 000) β the number of operation Sonya has to perform.
Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci β the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 β€ ai < 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18.
It's guaranteed that there will be at least one query of type '?'.
It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
Output
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
Examples
Input
12
+ 1
+ 241
? 1
+ 361
- 241
? 0101
+ 101
? 101
- 101
? 101
+ 4000
? 0
Output
2
1
2
1
1
Input
4
+ 200
+ 200
- 200
? 0
Output
1
Note
Consider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input.
1. 1 and 241.
2. 361.
3. 101 and 361.
4. 361.
5. 4000.
Tags: data structures, implementation
Correct Solution:
```
# Description of the problem can be found at http://codeforces.com/problemset/problem/713/A
from collections import defaultdict
from sys import stdin
from sys import stdout
n = int(stdin.readline())
d = defaultdict(int)
for _ in range(n):
s, x = stdin.readline().split()
y = "".join(["1" if c in ["1", "3", "5", "7", "9"] else "0" for c in x]).zfill(18)
if s == "+":
d[y] += 1
elif s == "-":
d[y] -= 1
else:
stdout.write(str(d[y]) + '\n')
```
| 107,474 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:
1. + ai β add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.
2. - ai β delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset.
3. ? s β count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left.
For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
Input
The first line of the input contains an integer t (1 β€ t β€ 100 000) β the number of operation Sonya has to perform.
Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci β the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 β€ ai < 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18.
It's guaranteed that there will be at least one query of type '?'.
It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
Output
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
Examples
Input
12
+ 1
+ 241
? 1
+ 361
- 241
? 0101
+ 101
? 101
- 101
? 101
+ 4000
? 0
Output
2
1
2
1
1
Input
4
+ 200
+ 200
- 200
? 0
Output
1
Note
Consider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input.
1. 1 and 241.
2. 361.
3. 101 and 361.
4. 361.
5. 4000.
Tags: data structures, implementation
Correct Solution:
```
num = int(input())
multiset = [0] * 2 ** 18
t = str.maketrans('0123456789', '0101010101')
while num:
opr = input().split()
if opr[0] == '+':
multiset[int(opr[1].translate(t), 2)] += 1
elif opr[0] == '-':
multiset[int(opr[1].translate(t), 2)] -= 1
elif opr[0] == '?':
print(multiset[int(opr[1], 2)])
num -= 1
```
| 107,475 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:
1. + ai β add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.
2. - ai β delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset.
3. ? s β count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left.
For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
Input
The first line of the input contains an integer t (1 β€ t β€ 100 000) β the number of operation Sonya has to perform.
Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci β the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 β€ ai < 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18.
It's guaranteed that there will be at least one query of type '?'.
It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
Output
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
Examples
Input
12
+ 1
+ 241
? 1
+ 361
- 241
? 0101
+ 101
? 101
- 101
? 101
+ 4000
? 0
Output
2
1
2
1
1
Input
4
+ 200
+ 200
- 200
? 0
Output
1
Note
Consider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input.
1. 1 and 241.
2. 361.
3. 101 and 361.
4. 361.
5. 4000.
Tags: data structures, implementation
Correct Solution:
```
n = int(input())
ans = [0] * 2 ** 18
trantab = str.maketrans('0123456789', '0101010101')
for i in range(n):
ch, s = map(str, input().split())
if ch == '+':
ans[int(s.translate(trantab), 2)] += 1
elif ch == '-':
ans[int(s.translate(trantab), 2)] -= 1
else:
print(ans[int(s.translate(trantab), 2)])
```
| 107,476 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:
1. + ai β add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.
2. - ai β delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset.
3. ? s β count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left.
For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
Input
The first line of the input contains an integer t (1 β€ t β€ 100 000) β the number of operation Sonya has to perform.
Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci β the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 β€ ai < 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18.
It's guaranteed that there will be at least one query of type '?'.
It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
Output
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
Examples
Input
12
+ 1
+ 241
? 1
+ 361
- 241
? 0101
+ 101
? 101
- 101
? 101
+ 4000
? 0
Output
2
1
2
1
1
Input
4
+ 200
+ 200
- 200
? 0
Output
1
Note
Consider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input.
1. 1 and 241.
2. 361.
3. 101 and 361.
4. 361.
5. 4000.
Tags: data structures, implementation
Correct Solution:
```
# Problem : C. Sonya and Queries
# Contest : Codeforces Round #371 (Div. 2)
# URL : https://codeforces.com/contest/714/problem/C
# Memory Limit : 256 MB
# Time Limit : 1000 ms
# Powered by CP Editor (https://github.com/cpeditor/cpeditor)
"""
// Author : snape_here - Susanta Mukherjee
"""
from __future__ import division, print_function
import os,sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def ii(): return int(input())
def si(): return input()
def mi(): return map(str,input().split())
def li(): return list(mi())
def read():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
def gcd(x, y):
while y:
x, y = y, x % y
return x
mod=1000000007
import math
def main():
t=ii()
di={}
for _ in range(t):
c,a=mi()
s=""
for i in range(len(a)):
s+=str(int(a[i])%2)
d=18-len(a)
s=d*'0'+s
if c=='+':
if s in di:
di[s]+=1
else:
di[s]=1
elif c=='-':
di[s]-=1
else:
d=18-len(a)
a=d*'0'+a
if a in di:
print(di[a])
else:
print(0)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
#read()
main()
```
| 107,477 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:
1. + ai β add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.
2. - ai β delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset.
3. ? s β count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left.
For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
Input
The first line of the input contains an integer t (1 β€ t β€ 100 000) β the number of operation Sonya has to perform.
Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci β the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 β€ ai < 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18.
It's guaranteed that there will be at least one query of type '?'.
It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
Output
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
Examples
Input
12
+ 1
+ 241
? 1
+ 361
- 241
? 0101
+ 101
? 101
- 101
? 101
+ 4000
? 0
Output
2
1
2
1
1
Input
4
+ 200
+ 200
- 200
? 0
Output
1
Note
Consider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input.
1. 1 and 241.
2. 361.
3. 101 and 361.
4. 361.
5. 4000.
Tags: data structures, implementation
Correct Solution:
```
import sys
import math
import collections
import heapq
input=sys.stdin.readline
d={}
t=int(input())
for w in range(t):
x,y=(i for i in input().split())
y=list(y)
k=len(y)
for i in range(k):
if(int(y[i])%2==0):
y[i]='0'
else:
y[i]='1'
y=''.join(y)
if(k<30):
y='0'*(30-k)+y
if(x=='+'):
if(y in d):
d[y]+=1
else:
d[y]=1
elif(x=='-'):
d[y]-=1
else:
if(y in d):
print(d[y])
else:
print(0)
```
| 107,478 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:
1. + ai β add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.
2. - ai β delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset.
3. ? s β count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left.
For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
Input
The first line of the input contains an integer t (1 β€ t β€ 100 000) β the number of operation Sonya has to perform.
Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci β the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 β€ ai < 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18.
It's guaranteed that there will be at least one query of type '?'.
It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
Output
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
Examples
Input
12
+ 1
+ 241
? 1
+ 361
- 241
? 0101
+ 101
? 101
- 101
? 101
+ 4000
? 0
Output
2
1
2
1
1
Input
4
+ 200
+ 200
- 200
? 0
Output
1
Note
Consider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input.
1. 1 and 241.
2. 361.
3. 101 and 361.
4. 361.
5. 4000.
Submitted Solution:
```
from collections import defaultdict
from sys import stdin
from sys import stdout
def main():
n = int(stdin.readline())
d = defaultdict(int)
for i in range(n):
s, x = stdin.readline().split()
y = ''.join(['1' if c in ['1', '3', '5', '7', '9'] else '0' for c in x]).zfill(18)
if s == '+': d[y] += 1
elif s == '-': d[y] -= 1
else: stdout.write(str(d[y]) + '\n')
if __name__ == '__main__':
main()
```
Yes
| 107,479 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:
1. + ai β add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.
2. - ai β delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset.
3. ? s β count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left.
For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
Input
The first line of the input contains an integer t (1 β€ t β€ 100 000) β the number of operation Sonya has to perform.
Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci β the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 β€ ai < 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18.
It's guaranteed that there will be at least one query of type '?'.
It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
Output
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
Examples
Input
12
+ 1
+ 241
? 1
+ 361
- 241
? 0101
+ 101
? 101
- 101
? 101
+ 4000
? 0
Output
2
1
2
1
1
Input
4
+ 200
+ 200
- 200
? 0
Output
1
Note
Consider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input.
1. 1 and 241.
2. 361.
3. 101 and 361.
4. 361.
5. 4000.
Submitted Solution:
```
from sys import stdin
input()
cnt=[0]*2**18
t=str.maketrans("0123456789","0101010101")
for ch,s in map(str.split,stdin):
if ch=='?' :
print(cnt[int(s,2)])
else :
cnt[int(s.translate(t),2)]+= (1 if ch=='+' else -1 )
# Made By Mostafa_Khaled
```
Yes
| 107,480 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:
1. + ai β add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.
2. - ai β delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset.
3. ? s β count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left.
For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
Input
The first line of the input contains an integer t (1 β€ t β€ 100 000) β the number of operation Sonya has to perform.
Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci β the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 β€ ai < 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18.
It's guaranteed that there will be at least one query of type '?'.
It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
Output
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
Examples
Input
12
+ 1
+ 241
? 1
+ 361
- 241
? 0101
+ 101
? 101
- 101
? 101
+ 4000
? 0
Output
2
1
2
1
1
Input
4
+ 200
+ 200
- 200
? 0
Output
1
Note
Consider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input.
1. 1 and 241.
2. 361.
3. 101 and 361.
4. 361.
5. 4000.
Submitted Solution:
```
import sys
from collections import Counter
from sys import stdin
input()
c = [0]*2**18
deg = [0]*18
for i in range(18):
deg[i] = 2**i
t=str.maketrans("0123456789","0101010101")
for ch,n in map(str.split,stdin):
if ch == '?':
print(c[int(n, 2)])
n = n.translate(t)
if ch == '+':
c[int(n,2)] += 1
if ch == '-':
c[int(n,2)] -= 1
```
Yes
| 107,481 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:
1. + ai β add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.
2. - ai β delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset.
3. ? s β count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left.
For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
Input
The first line of the input contains an integer t (1 β€ t β€ 100 000) β the number of operation Sonya has to perform.
Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci β the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 β€ ai < 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18.
It's guaranteed that there will be at least one query of type '?'.
It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
Output
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
Examples
Input
12
+ 1
+ 241
? 1
+ 361
- 241
? 0101
+ 101
? 101
- 101
? 101
+ 4000
? 0
Output
2
1
2
1
1
Input
4
+ 200
+ 200
- 200
? 0
Output
1
Note
Consider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input.
1. 1 and 241.
2. 361.
3. 101 and 361.
4. 361.
5. 4000.
Submitted Solution:
```
from __future__ import division, print_function
import sys
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
import os, sys, bisect, copy
from collections import defaultdict, Counter, deque
#from functools import lru_cache #use @lru_cache(None)
if os.path.exists('in.txt'): sys.stdin=open('in.txt','r')
if os.path.exists('out.txt'): sys.stdout=open('out.txt', 'w')
#
def input(): return sys.stdin.readline()
def mapi(arg=0): return map(int if arg==0 else str,input().split())
#------------------------------------------------------------------
mp = defaultdict(int)
def key(x):
res = 0
for i in range(len(x)):
res = 2*res+int(x[i])%2
return res
for _ in range(int(input())):
a = input().strip().split()
#print(*a)
if a[0]=="+":
mp[key(a[1])]+=1
#print(mp[a[1]])
elif a[0]=="-":
mp[key(a[1])]-=1
pass
else:
print(mp[key(a[1])])
```
Yes
| 107,482 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:
1. + ai β add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.
2. - ai β delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset.
3. ? s β count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left.
For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
Input
The first line of the input contains an integer t (1 β€ t β€ 100 000) β the number of operation Sonya has to perform.
Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci β the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 β€ ai < 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18.
It's guaranteed that there will be at least one query of type '?'.
It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
Output
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
Examples
Input
12
+ 1
+ 241
? 1
+ 361
- 241
? 0101
+ 101
? 101
- 101
? 101
+ 4000
? 0
Output
2
1
2
1
1
Input
4
+ 200
+ 200
- 200
? 0
Output
1
Note
Consider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input.
1. 1 and 241.
2. 361.
3. 101 and 361.
4. 361.
5. 4000.
Submitted Solution:
```
from sys import stdin, stdout
quests = int(stdin.readline().rstrip())
multi_set = {}
for i in range(quests):
quest, core = stdin.readline().rstrip().split()
pattern = ''
for i in core: pattern += str(int(i)%2)
if quest == '+':
if pattern in multi_set: multi_set[pattern] += 1
else: multi_set[pattern] = 1
elif quest == '-': multi_set[pattern] -= 1
else:
if pattern in multi_set: stdout.write(str(multi_set[pattern])+'\n')
else: stdout.write('0\n')
```
No
| 107,483 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:
1. + ai β add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.
2. - ai β delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset.
3. ? s β count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left.
For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
Input
The first line of the input contains an integer t (1 β€ t β€ 100 000) β the number of operation Sonya has to perform.
Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci β the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 β€ ai < 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18.
It's guaranteed that there will be at least one query of type '?'.
It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
Output
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
Examples
Input
12
+ 1
+ 241
? 1
+ 361
- 241
? 0101
+ 101
? 101
- 101
? 101
+ 4000
? 0
Output
2
1
2
1
1
Input
4
+ 200
+ 200
- 200
? 0
Output
1
Note
Consider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input.
1. 1 and 241.
2. 361.
3. 101 and 361.
4. 361.
5. 4000.
Submitted Solution:
```
t = int(input())
trantab = str.maketrans('0123456789', '0101010101')
a = {}
for i in range(t):
string = input()
oper = string[0]
number = string[2:]
if oper == '+':
a[number] = a.get(number, 0) + 1
elif oper == '-':
a[number] -= 1
else:
count = 0
for a_i in a:
max_length = max(len(number), len(a_i))
if a_i.translate(trantab).rjust(max_length, '0') == number.rjust(max_length, '0'):
count += 1
print(count)
```
No
| 107,484 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:
1. + ai β add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.
2. - ai β delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset.
3. ? s β count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left.
For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
Input
The first line of the input contains an integer t (1 β€ t β€ 100 000) β the number of operation Sonya has to perform.
Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci β the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 β€ ai < 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18.
It's guaranteed that there will be at least one query of type '?'.
It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
Output
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
Examples
Input
12
+ 1
+ 241
? 1
+ 361
- 241
? 0101
+ 101
? 101
- 101
? 101
+ 4000
? 0
Output
2
1
2
1
1
Input
4
+ 200
+ 200
- 200
? 0
Output
1
Note
Consider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input.
1. 1 and 241.
2. 361.
3. 101 and 361.
4. 361.
5. 4000.
Submitted Solution:
```
t = int(input())
a = []
for i in range(t):
string = input()
number = string[2:]
if string[0] == '+':
a.append(number)
elif string[0] == '-':
a.remove(number)
else:
count = 0
for a_i in a:
for i, j in zip(a_i[::-1], number[::-1]):
if not int(i) % 2 == int(j) % 2:
break
count += 1
print(count)
```
No
| 107,485 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:
1. + ai β add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer.
2. - ai β delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset.
3. ? s β count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left.
For example, if the pattern is s = 010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.
Input
The first line of the input contains an integer t (1 β€ t β€ 100 000) β the number of operation Sonya has to perform.
Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ci β the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0 β€ ai < 1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18.
It's guaranteed that there will be at least one query of type '?'.
It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.
Output
For each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.
Examples
Input
12
+ 1
+ 241
? 1
+ 361
- 241
? 0101
+ 101
? 101
- 101
? 101
+ 4000
? 0
Output
2
1
2
1
1
Input
4
+ 200
+ 200
- 200
? 0
Output
1
Note
Consider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input.
1. 1 and 241.
2. 361.
3. 101 and 361.
4. 361.
5. 4000.
Submitted Solution:
```
import sys
from collections import Counter
t = int(input())
c = Counter()
for i in range(t):
ch, n = sys.stdin.readline().split()
n = list(n)
n.reverse()
val = 0
for i in range(len(n)):
if (ord(n[i])-ord('0')) % 2 == 0:
val = val * 2
else:
val = val * 2 + 1
if ch == '?':
print(c[val])
if ch == '+':
c[val] += 1
if ch == '-':
c[val] -= 1
```
No
| 107,486 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anton goes to school, his favorite lessons are arraystudying. He usually solves all the tasks pretty fast, but this time the teacher gave him a complicated one: given two arrays b and c of length n, find array a, such that:
<image>
where a and b means bitwise AND, while a or b means bitwise OR.
Usually Anton is good in arraystudying, but this problem is too hard, so Anton asks you to help.
Input
The first line of the input contains a single integers n (1 β€ n β€ 200 000) β the size of arrays b and c.
The second line contains n integers bi (0 β€ bi β€ 109) β elements of the array b.
Third line contains n integers ci (0 β€ ci β€ 109) β elements of the array c.
Output
If there is no solution, print - 1.
Otherwise, the only line of the output should contain n non-negative integers ai β elements of the array a. If there are multiple possible solutions, you may print any of them.
Examples
Input
4
6 8 4 4
16 22 10 10
Output
3 5 1 1
Input
5
8 25 14 7 16
19 6 9 4 25
Output
-1
Submitted Solution:
```
n = int(input())
b = list(map(int, input().split()))
c = list(map(int, input().split()))
a = [0]*n
def fun():
sumb,sumc = sum(b),sum(c)
if(sumb+sumc)%(2*n): return False
suma = (sumb+sumc)//(2*n)
for i in range(n):
tmp = (c[i]+b[i]-suma)
if c[i]<b[i]: return False
if tmp<0: return False
if tmp%n: return False
a[i] = tmp//n
if suma != sum(a): return False
if n == 1 and b[0]!=c[0]: return False
return True
ok = fun()
if not ok:
print(-1)
else:
print(' '.join([str(x) for x in a]))
```
No
| 107,487 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anton goes to school, his favorite lessons are arraystudying. He usually solves all the tasks pretty fast, but this time the teacher gave him a complicated one: given two arrays b and c of length n, find array a, such that:
<image>
where a and b means bitwise AND, while a or b means bitwise OR.
Usually Anton is good in arraystudying, but this problem is too hard, so Anton asks you to help.
Input
The first line of the input contains a single integers n (1 β€ n β€ 200 000) β the size of arrays b and c.
The second line contains n integers bi (0 β€ bi β€ 109) β elements of the array b.
Third line contains n integers ci (0 β€ ci β€ 109) β elements of the array c.
Output
If there is no solution, print - 1.
Otherwise, the only line of the output should contain n non-negative integers ai β elements of the array a. If there are multiple possible solutions, you may print any of them.
Examples
Input
4
6 8 4 4
16 22 10 10
Output
3 5 1 1
Input
5
8 25 14 7 16
19 6 9 4 25
Output
-1
Submitted Solution:
```
n = int(input())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
sum1 = sum([x+y for x,y in zip(a,b)])
if sum1 %(2*n) != 0 :
print(-1)
exit()
sumAi = sum1 // (2*n)
ans = [-1 if (x+y-sumAi) % n != 0 else (x+y-sumAi)//n for x,y in zip(a,b)]
if len(list(filter(lambda x : x<0,ans))) != 0 :
print(-1)
else :
print(' '.join(map(str,ans)))
```
No
| 107,488 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anton goes to school, his favorite lessons are arraystudying. He usually solves all the tasks pretty fast, but this time the teacher gave him a complicated one: given two arrays b and c of length n, find array a, such that:
<image>
where a and b means bitwise AND, while a or b means bitwise OR.
Usually Anton is good in arraystudying, but this problem is too hard, so Anton asks you to help.
Input
The first line of the input contains a single integers n (1 β€ n β€ 200 000) β the size of arrays b and c.
The second line contains n integers bi (0 β€ bi β€ 109) β elements of the array b.
Third line contains n integers ci (0 β€ ci β€ 109) β elements of the array c.
Output
If there is no solution, print - 1.
Otherwise, the only line of the output should contain n non-negative integers ai β elements of the array a. If there are multiple possible solutions, you may print any of them.
Examples
Input
4
6 8 4 4
16 22 10 10
Output
3 5 1 1
Input
5
8 25 14 7 16
19 6 9 4 25
Output
-1
Submitted Solution:
```
n,b,c = int(input()), input().split(), input().split()
a = [-1 for i in range(n)]
for i in range(n):
b[i] = int(b[i])
c[i] = int(c[i])
if c[i] < b[i]:
print(-1)
exit(0)
if n==1:
if b[0] != c[0]:
print(-1)
exit(0)
else:
print(b[0])
exit(0)
s1 = sum([b[i] + c[i] for i in range(n)])
if s1 % 2*n != 0:
print(-1)
exit(0)
s1 //= 2*n
for i in range(n):
x = b[i] + c[i] - s1
if x % n != 0:
print(-1)
exit(0)
else:
a[i] = x // n
for i in range(n):
if i == n-1:
end = '\n'
else:
end = ' '
print(a[i], end = end)
```
No
| 107,489 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anton goes to school, his favorite lessons are arraystudying. He usually solves all the tasks pretty fast, but this time the teacher gave him a complicated one: given two arrays b and c of length n, find array a, such that:
<image>
where a and b means bitwise AND, while a or b means bitwise OR.
Usually Anton is good in arraystudying, but this problem is too hard, so Anton asks you to help.
Input
The first line of the input contains a single integers n (1 β€ n β€ 200 000) β the size of arrays b and c.
The second line contains n integers bi (0 β€ bi β€ 109) β elements of the array b.
Third line contains n integers ci (0 β€ ci β€ 109) β elements of the array c.
Output
If there is no solution, print - 1.
Otherwise, the only line of the output should contain n non-negative integers ai β elements of the array a. If there are multiple possible solutions, you may print any of them.
Examples
Input
4
6 8 4 4
16 22 10 10
Output
3 5 1 1
Input
5
8 25 14 7 16
19 6 9 4 25
Output
-1
Submitted Solution:
```
n=int(input())
b=list(map(int, input().split()))
c=list(map(int, input().split()))
if n==1:
print(b[0] if b==c else -1)
exit()
s=sum(b+c)
if s%(n<<1)!=0:
print(-1)
exit()
s//=(n<<1)
a=[b[i]+c[i]-s for i in range(n)]
if any(x<0 or x%n!=0 for x in a):
print(-1)
exit()
print(*[x//n for x in a])
```
No
| 107,490 |
Provide tags and a correct Python 3 solution for this coding contest problem.
For given n, l and r find the number of distinct geometrical progression, each of which contains n distinct integers not less than l and not greater than r. In other words, for each progression the following must hold: l β€ ai β€ r and ai β aj , where a1, a2, ..., an is the geometrical progression, 1 β€ i, j β€ n and i β j.
Geometrical progression is a sequence of numbers a1, a2, ..., an where each term after first is found by multiplying the previous one by a fixed non-zero number d called the common ratio. Note that in our task d may be non-integer. For example in progression 4, 6, 9, common ratio is <image>.
Two progressions a1, a2, ..., an and b1, b2, ..., bn are considered different, if there is such i (1 β€ i β€ n) that ai β bi.
Input
The first and the only line cotains three integers n, l and r (1 β€ n β€ 107, 1 β€ l β€ r β€ 107).
Output
Print the integer K β is the answer to the problem.
Examples
Input
1 1 10
Output
10
Input
2 6 9
Output
12
Input
3 1 10
Output
8
Input
3 3 10
Output
2
Note
These are possible progressions for the first test of examples:
* 1;
* 2;
* 3;
* 4;
* 5;
* 6;
* 7;
* 8;
* 9;
* 10.
These are possible progressions for the second test of examples:
* 6, 7;
* 6, 8;
* 6, 9;
* 7, 6;
* 7, 8;
* 7, 9;
* 8, 6;
* 8, 7;
* 8, 9;
* 9, 6;
* 9, 7;
* 9, 8.
These are possible progressions for the third test of examples:
* 1, 2, 4;
* 1, 3, 9;
* 2, 4, 8;
* 4, 2, 1;
* 4, 6, 9;
* 8, 4, 2;
* 9, 3, 1;
* 9, 6, 4.
These are possible progressions for the fourth test of examples:
* 4, 6, 9;
* 9, 6, 4.
Tags: brute force, math, number theory
Correct Solution:
```
Primes = [2, 3, 5, 7]
def check (a, b) :
for pr in Primes :
if a % pr == 0 and b % pr == 0 :
return False
while (b) :
a %= b
a ^= b
b ^= a
a ^= b
return a == 1
n, l, r = map(int, input().split())
if n == 1 :
ans = r - l + 1
elif n == 2 :
ans = (r - l + 1) * (r - l)
else :
n -= 1
l -= 1
ans = 0
for q in range (2, 100000) :
upper = r // q**n
if (upper == 0) :
break
for p in range (1, q) :
if check(q, p) :
ans += max(0, upper - l // p**n)
ans *= 2
print(ans)
```
| 107,491 |
Provide tags and a correct Python 3 solution for this coding contest problem.
For given n, l and r find the number of distinct geometrical progression, each of which contains n distinct integers not less than l and not greater than r. In other words, for each progression the following must hold: l β€ ai β€ r and ai β aj , where a1, a2, ..., an is the geometrical progression, 1 β€ i, j β€ n and i β j.
Geometrical progression is a sequence of numbers a1, a2, ..., an where each term after first is found by multiplying the previous one by a fixed non-zero number d called the common ratio. Note that in our task d may be non-integer. For example in progression 4, 6, 9, common ratio is <image>.
Two progressions a1, a2, ..., an and b1, b2, ..., bn are considered different, if there is such i (1 β€ i β€ n) that ai β bi.
Input
The first and the only line cotains three integers n, l and r (1 β€ n β€ 107, 1 β€ l β€ r β€ 107).
Output
Print the integer K β is the answer to the problem.
Examples
Input
1 1 10
Output
10
Input
2 6 9
Output
12
Input
3 1 10
Output
8
Input
3 3 10
Output
2
Note
These are possible progressions for the first test of examples:
* 1;
* 2;
* 3;
* 4;
* 5;
* 6;
* 7;
* 8;
* 9;
* 10.
These are possible progressions for the second test of examples:
* 6, 7;
* 6, 8;
* 6, 9;
* 7, 6;
* 7, 8;
* 7, 9;
* 8, 6;
* 8, 7;
* 8, 9;
* 9, 6;
* 9, 7;
* 9, 8.
These are possible progressions for the third test of examples:
* 1, 2, 4;
* 1, 3, 9;
* 2, 4, 8;
* 4, 2, 1;
* 4, 6, 9;
* 8, 4, 2;
* 9, 3, 1;
* 9, 6, 4.
These are possible progressions for the fourth test of examples:
* 4, 6, 9;
* 9, 6, 4.
Tags: brute force, math, number theory
Correct Solution:
```
import math
small=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523]
smallest=[0 for i in range(4001)]
smallest[0]=1
smallest[1]=1
for i in range(2,len(smallest)):
if smallest[i]==0:
for j in range(2*i,len(smallest),i):
smallest[j]=i
smallest[i]=i
def listfactor(N):
if N==2:
return [2]
elif N==3:
return [3]
else:
temp=[]
while(N>1):
t=smallest[N]
temp+=[t]
N=N//t
temp=temp[::-1]
ANS=[temp[0]]
cur=temp[0]
for i in range(len(temp)):
if temp[i]>cur:
cur=temp[i]
ANS+=[cur]
return ANS
def check(a,b):
for x in small:
if (a%x==0 and b%x==0)==True:
return 0
if x>max(a,b)**0.5:
return 1
return 1
def ceil(x):
if x!=int(x):
return int(x)+1
else:
return int(x)
def gcd(a,b):
a,b=min(a,b),max(a,b)
if b%a==0:
return a
else:
return gcd(a,b%a)
def find(n,l,r):
if r-l+1<n:
return 0
elif n==1:
return r-l+1
elif n==2:
return (r-l+1)*(r-l)
elif n>=30:
ans=0
temp=0
for d in range(2,10**10):
temp=max(r//(d**(n-1))-l+1,0)
ans+=temp
if temp==0:
break
return 2*ans
else:
ans=0
for d in range(2,10**10):
temp=max(r//(d**(n-1))-l+1,0)
ans+=temp
if temp==0:
break
#print(ans,'ans')
bound=int(r**(1/(n-1)))
#print(bound,'bound')
#q<=bound
ANS=0
for q in range(2,bound+1):
CUR=listfactor(q)
for p in range(q+1,bound+2):
check=1
for cc in CUR:
if p%cc==0:
check=0
if check==1:
ANS+=max(r//(p**(n-1))-ceil(l/(q**(n-1)))+1,0)
return 2*(ans+ANS)
n,l,r=list(map(int,input().strip().split(' ')))
print(find(n,l,r))
```
| 107,492 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given n, l and r find the number of distinct geometrical progression, each of which contains n distinct integers not less than l and not greater than r. In other words, for each progression the following must hold: l β€ ai β€ r and ai β aj , where a1, a2, ..., an is the geometrical progression, 1 β€ i, j β€ n and i β j.
Geometrical progression is a sequence of numbers a1, a2, ..., an where each term after first is found by multiplying the previous one by a fixed non-zero number d called the common ratio. Note that in our task d may be non-integer. For example in progression 4, 6, 9, common ratio is <image>.
Two progressions a1, a2, ..., an and b1, b2, ..., bn are considered different, if there is such i (1 β€ i β€ n) that ai β bi.
Input
The first and the only line cotains three integers n, l and r (1 β€ n β€ 107, 1 β€ l β€ r β€ 107).
Output
Print the integer K β is the answer to the problem.
Examples
Input
1 1 10
Output
10
Input
2 6 9
Output
12
Input
3 1 10
Output
8
Input
3 3 10
Output
2
Note
These are possible progressions for the first test of examples:
* 1;
* 2;
* 3;
* 4;
* 5;
* 6;
* 7;
* 8;
* 9;
* 10.
These are possible progressions for the second test of examples:
* 6, 7;
* 6, 8;
* 6, 9;
* 7, 6;
* 7, 8;
* 7, 9;
* 8, 6;
* 8, 7;
* 8, 9;
* 9, 6;
* 9, 7;
* 9, 8.
These are possible progressions for the third test of examples:
* 1, 2, 4;
* 1, 3, 9;
* 2, 4, 8;
* 4, 2, 1;
* 4, 6, 9;
* 8, 4, 2;
* 9, 3, 1;
* 9, 6, 4.
These are possible progressions for the fourth test of examples:
* 4, 6, 9;
* 9, 6, 4.
Submitted Solution:
```
n, l, r = map(int, input().split())
m = r-l+1
if n == 1: print(m)
elif n == 2: print(m*(m-1))
else:
cnt = 0
for i in range(2, r):
v = i**(n-1)
if v > r: break
kmax = r // v
for j in range(1,i):
u = j**(n-1)
kmin = l // u + (l % u > 0)
if kmin <= kmax:
cnt += 2*(kmax-kmin+1)
print(cnt)
```
No
| 107,493 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given n, l and r find the number of distinct geometrical progression, each of which contains n distinct integers not less than l and not greater than r. In other words, for each progression the following must hold: l β€ ai β€ r and ai β aj , where a1, a2, ..., an is the geometrical progression, 1 β€ i, j β€ n and i β j.
Geometrical progression is a sequence of numbers a1, a2, ..., an where each term after first is found by multiplying the previous one by a fixed non-zero number d called the common ratio. Note that in our task d may be non-integer. For example in progression 4, 6, 9, common ratio is <image>.
Two progressions a1, a2, ..., an and b1, b2, ..., bn are considered different, if there is such i (1 β€ i β€ n) that ai β bi.
Input
The first and the only line cotains three integers n, l and r (1 β€ n β€ 107, 1 β€ l β€ r β€ 107).
Output
Print the integer K β is the answer to the problem.
Examples
Input
1 1 10
Output
10
Input
2 6 9
Output
12
Input
3 1 10
Output
8
Input
3 3 10
Output
2
Note
These are possible progressions for the first test of examples:
* 1;
* 2;
* 3;
* 4;
* 5;
* 6;
* 7;
* 8;
* 9;
* 10.
These are possible progressions for the second test of examples:
* 6, 7;
* 6, 8;
* 6, 9;
* 7, 6;
* 7, 8;
* 7, 9;
* 8, 6;
* 8, 7;
* 8, 9;
* 9, 6;
* 9, 7;
* 9, 8.
These are possible progressions for the third test of examples:
* 1, 2, 4;
* 1, 3, 9;
* 2, 4, 8;
* 4, 2, 1;
* 4, 6, 9;
* 8, 4, 2;
* 9, 3, 1;
* 9, 6, 4.
These are possible progressions for the fourth test of examples:
* 4, 6, 9;
* 9, 6, 4.
Submitted Solution:
```
def pow(a,n):
if(n==0): return 1
if(n==1): return a
P = pow(a,n//2)
Q=1
if(n%2==1): Q=a
return P*P*Q
def uf(x,y):
if(x>(x//y)*y): return (x//y)+1
return x//y
n, l, r = map(int,input().split(' '))
ans = 0
if(n>24): print(0)
elif(n==1): print(r-l+1)
else:
acc_l = 1; acc_r=1;
while(pow(acc_l,n-1)<l):
acc_l=acc_l+1
while(pow(acc_r,n-1)<=r):
acc_r=acc_r+1
acc_r = acc_r-1
if(acc_l==1 or acc_r==1): print(0)
else:
for i in range(acc_l,acc_r+1):
ans+=max(0,((r//(pow(i,n-1)))-l+1))
for i in range(acc_l,acc_r+1):
for j in range(i+1,acc_r+1):
ans += max(0,(r//pow(j,n-1))-uf(l,pow(i,n-1))+1);
print(ans*2)
```
No
| 107,494 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given n, l and r find the number of distinct geometrical progression, each of which contains n distinct integers not less than l and not greater than r. In other words, for each progression the following must hold: l β€ ai β€ r and ai β aj , where a1, a2, ..., an is the geometrical progression, 1 β€ i, j β€ n and i β j.
Geometrical progression is a sequence of numbers a1, a2, ..., an where each term after first is found by multiplying the previous one by a fixed non-zero number d called the common ratio. Note that in our task d may be non-integer. For example in progression 4, 6, 9, common ratio is <image>.
Two progressions a1, a2, ..., an and b1, b2, ..., bn are considered different, if there is such i (1 β€ i β€ n) that ai β bi.
Input
The first and the only line cotains three integers n, l and r (1 β€ n β€ 107, 1 β€ l β€ r β€ 107).
Output
Print the integer K β is the answer to the problem.
Examples
Input
1 1 10
Output
10
Input
2 6 9
Output
12
Input
3 1 10
Output
8
Input
3 3 10
Output
2
Note
These are possible progressions for the first test of examples:
* 1;
* 2;
* 3;
* 4;
* 5;
* 6;
* 7;
* 8;
* 9;
* 10.
These are possible progressions for the second test of examples:
* 6, 7;
* 6, 8;
* 6, 9;
* 7, 6;
* 7, 8;
* 7, 9;
* 8, 6;
* 8, 7;
* 8, 9;
* 9, 6;
* 9, 7;
* 9, 8.
These are possible progressions for the third test of examples:
* 1, 2, 4;
* 1, 3, 9;
* 2, 4, 8;
* 4, 2, 1;
* 4, 6, 9;
* 8, 4, 2;
* 9, 3, 1;
* 9, 6, 4.
These are possible progressions for the fourth test of examples:
* 4, 6, 9;
* 9, 6, 4.
Submitted Solution:
```
n, l, r = map(int, input().split())
m = r-l+1
if n == 1: print(m)
elif n == 2: print(m*(m-1))
else:
cnt = 0
drop = []
for i in range(2,r):
v = i**(n-1)
if v > r: break
for vv in range(v,r+1,v):
drop.append(vv)
for i in range(2, r):
v = i**(n-1)
if v > r: break
kmax = r // v
for j in range(1,i):
u = j**(n-1)
kmin = l // u + (l % u > 0)
if kmin <= kmax:
cnt += 2*(kmax-kmin+1-sum(map(lambda x: x >= kmin and x <= kmax, drop)))
#print(kmax, kmin, sum(map(lambda x: x >= kmin and x <= kmax, drop)), list(map(lambda x: x >= kmin and x <= kmax, drop)), drop)
print(cnt)
```
No
| 107,495 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given n, l and r find the number of distinct geometrical progression, each of which contains n distinct integers not less than l and not greater than r. In other words, for each progression the following must hold: l β€ ai β€ r and ai β aj , where a1, a2, ..., an is the geometrical progression, 1 β€ i, j β€ n and i β j.
Geometrical progression is a sequence of numbers a1, a2, ..., an where each term after first is found by multiplying the previous one by a fixed non-zero number d called the common ratio. Note that in our task d may be non-integer. For example in progression 4, 6, 9, common ratio is <image>.
Two progressions a1, a2, ..., an and b1, b2, ..., bn are considered different, if there is such i (1 β€ i β€ n) that ai β bi.
Input
The first and the only line cotains three integers n, l and r (1 β€ n β€ 107, 1 β€ l β€ r β€ 107).
Output
Print the integer K β is the answer to the problem.
Examples
Input
1 1 10
Output
10
Input
2 6 9
Output
12
Input
3 1 10
Output
8
Input
3 3 10
Output
2
Note
These are possible progressions for the first test of examples:
* 1;
* 2;
* 3;
* 4;
* 5;
* 6;
* 7;
* 8;
* 9;
* 10.
These are possible progressions for the second test of examples:
* 6, 7;
* 6, 8;
* 6, 9;
* 7, 6;
* 7, 8;
* 7, 9;
* 8, 6;
* 8, 7;
* 8, 9;
* 9, 6;
* 9, 7;
* 9, 8.
These are possible progressions for the third test of examples:
* 1, 2, 4;
* 1, 3, 9;
* 2, 4, 8;
* 4, 2, 1;
* 4, 6, 9;
* 8, 4, 2;
* 9, 3, 1;
* 9, 6, 4.
These are possible progressions for the fourth test of examples:
* 4, 6, 9;
* 9, 6, 4.
Submitted Solution:
```
#!/usr/bin/env python3
def read_string():
return input()
def read_strings(return_type = iter, split = None, skip = 0):
return return_type(input().split(split)[skip:])
def read_lines(height, return_type = iter):
return return_type(read_string() for i in range(height))
def read_number():
return int(input())
def read_numbers(return_type = iter, skip = 0):
return return_type(int(i) for i in input().split()[skip:])
def read_values(*types, array = None):
line = input().split()
result = []
for return_type, i in zip(types, range(len(types))):
result.append(return_type(line[i]))
if array != None:
array_type, array_contained = array
result.append(array_type(array_contained(i) for i in line[len(types):]))
return result
def read_array(item_type = int, return_type = iter, skip = 0):
return return_type(item_type(i) for i in input().split()[skip:])
def read_martix(height, **args):
return_type = args["return_type"] if "return_type" in args else iter
return_type_inner = args["return_type_inner"] if "return_type_inner" in args else return_type
return_type_outer = args["return_type_outer"] if "return_type_outer" in args else return_type
item_type = args["item_type"] if "item_type" in args else int
return return_type_outer(read_array(item_type = item_type, return_type = return_type_inner) for i in range(height))
def read_martix_linear(width, skip = 0, item_type = int, skiped = None):
num = read_array(item_type = item_type, skip = skip)
height = len(num) / width
return [num[i * width: (i + 1) * width] for i in range(height)]
# (q > p)
# a
# ...
# a * q ^ (n-1)
def solve(n, amin, amax, r):
if amin > amax: return 0;
qn = q ** (n-1)
amax = min(amax, r // qn)
if amin > amax: return 0;
return amax - amin + 1
def gcd(x, y):
if x == 0: return y
return gcd (y % x, x)
def main():
n, l, r = read_numbers()
if n == 1:
ans = r - l + 1
elif n == 2:
ans = (r - l + 1) * (r - l)
else:
ans = 0
for p in range(1, r + 1):
pn = p ** (n - 1)
if pn > r: break
for q in range(p + 1, r + 1):
if gcd(p, q) == 1:
qn = q ** (n - 1)
if qn > r: break
if (r + qn - 1) // qn >= l // pn:
ans += r // qn - (l + pn - 1) // pn + 1
ans *= 2
print(ans)
if __name__ == '__main__':
main()
```
No
| 107,496 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given positive integer number n. You should create such strictly increasing sequence of k positive numbers a1, a2, ..., ak, that their sum is equal to n and greatest common divisor is maximal.
Greatest common divisor of sequence is maximum of such numbers that every element of sequence is divisible by them.
If there is no possible sequence then output -1.
Input
The first line consists of two numbers n and k (1 β€ n, k β€ 1010).
Output
If the answer exists then output k numbers β resulting sequence. Otherwise output -1. If there are multiple answers, print any of them.
Examples
Input
6 3
Output
1 2 3
Input
8 2
Output
2 6
Input
5 3
Output
-1
Tags: constructive algorithms, greedy, math
Correct Solution:
```
from math import sqrt
n,k = map(int,input().split())
d = 10000000000000
if n < k*(k+1)//2:
print(-1)
else:
for i in range(1,int(sqrt(n))+1):
if n%i==0:
if i >= k*(k+1)//2:
d = i
break
if n//i >= (k*(k+1))//2:
d = min(d,n//i)
for i in range(1,k):
print(i*n//d,end=" ")
print((n//d * (k+d-(k*(k+1)//2))),end=" ")
```
| 107,497 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given positive integer number n. You should create such strictly increasing sequence of k positive numbers a1, a2, ..., ak, that their sum is equal to n and greatest common divisor is maximal.
Greatest common divisor of sequence is maximum of such numbers that every element of sequence is divisible by them.
If there is no possible sequence then output -1.
Input
The first line consists of two numbers n and k (1 β€ n, k β€ 1010).
Output
If the answer exists then output k numbers β resulting sequence. Otherwise output -1. If there are multiple answers, print any of them.
Examples
Input
6 3
Output
1 2 3
Input
8 2
Output
2 6
Input
5 3
Output
-1
Tags: constructive algorithms, greedy, math
Correct Solution:
```
'''
Hey why peeping here -_'_- ?
I believe on myself and I will achieve
this->author = Fuad Ashraful Mehmet, CSE ,University of Asia Pacific
Todo:
'''
import sys,math
input=sys.stdin.readline
def getSum(k):
return k*(k-1)//2
def HalfDead():
n,k=map(int,input().split())
ans=-1
for i in range(1,int(math.sqrt(n))+1):
if not n%i:
x=i
y=n//i
sum=x*getSum(k)
rem=n-sum
if rem>x*(k-1):
if x>ans:
ans=x
sum=y*getSum(k)
rem=n-sum
if rem>y*(k-1):
if y>ans:
ans=y
if ans==-1:
print(ans)
else:
ar=[]
for i in range(1,k):
ar.append(ans*i)
ar.append(n-ans*getSum(k))
print(*ar)
if __name__=='__main__':
HalfDead()
```
| 107,498 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given positive integer number n. You should create such strictly increasing sequence of k positive numbers a1, a2, ..., ak, that their sum is equal to n and greatest common divisor is maximal.
Greatest common divisor of sequence is maximum of such numbers that every element of sequence is divisible by them.
If there is no possible sequence then output -1.
Input
The first line consists of two numbers n and k (1 β€ n, k β€ 1010).
Output
If the answer exists then output k numbers β resulting sequence. Otherwise output -1. If there are multiple answers, print any of them.
Examples
Input
6 3
Output
1 2 3
Input
8 2
Output
2 6
Input
5 3
Output
-1
Tags: constructive algorithms, greedy, math
Correct Solution:
```
n,k = map(int,input().split())
if 2*n<k*(k+1):
print(-1)
exit(0)
mx = 0
def ok(d):
sm = k*(k-1)//2
sm *= d
if sm+k>n:
return False
if (n-sm>((k-1)*d)):
return True
else:
return False
i = 1
while i*i<=n:
if n%i==0:
if ok(i): mx = max(mx,i)
if ok(n//i): mx = max(mx,n//i)
i+= 1
ans = ''
for i in range(1,k):
ans += str(i*mx)+' '
ans += str(n-((k*(k-1))//2)*mx)
print(ans)
```
| 107,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.