text
stringlengths
198
433k
conversation_id
int64
0
109k
Provide a correct Python 3 solution for this coding contest problem. For a given polygon g and target points t, print "2" if g contains t, "1" if t is on a segment of g, "0" otherwise. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≀ i ≀ n-1) are sides of the polygon. The line segment connecting pn and p1 is also a side of the polygon. Note that the polygon is not necessarily convex. Constraints * 3 ≀ n ≀ 100 * 1 ≀ q ≀ 1000 * -10000 ≀ xi, yi ≀ 10000 * No point of the polygon will occur more than once. * Two sides of the polygon can intersect only at a common endpoint. Input The entire input looks like: g (the sequence of the points of the polygon) q (the number of queris = the number of target points) 1st query 2nd query : qth query g is given by coordinates of the points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of a point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Each query consists of the coordinate of a target point t. The coordinate is given by two intgers x and y. Output For each query, print "2", "1" or "0". Example Input 4 0 0 3 1 2 3 0 3 3 2 1 0 2 3 2 Output 2 1 0 "Correct Solution: ``` import sys from operator import itemgetter, attrgetter from itertools import starmap import cmath from math import isinf, sqrt, acos, atan2 readline = sys.stdin.readline EPS = 1e-9 ONLINE_FRONT = -2 CLOCKWISE = -1 ON_SEGMENT = 0 COUNTER_CLOCKWISE = 1 ONLINE_BACK = 2 class Circle(object): __slots__ = ('c', 'r') def __init__(self, c, r): self.c = c self.r = r class Segment(object): __slots__ = ('fi', 'se') def __init__(self, fi, se): self.fi = fi self.se = se Line = Segment def cross(a, b): return a.real * b.imag - a.imag * b.real def dot(a, b): return a.real * b.real + a.imag * b.imag def norm(base): return abs(base) ** 2 def project(s, p2): base = s.fi - s.se r = dot(p2 - s.fi, base) / norm(base) return s.fi + base * r def reflect(s, p): return p + (project(s, p) - p) * 2.0 def ccw(p1, p2, p3): a = p2 - p1 b = p3 - p1 if cross(a, b) > EPS: return 1 if cross(a, b) < -EPS: return -1 if dot(a, b) < -EPS: return 2 if norm(a) < norm(b): return -2 return 0 def intersect4(p1, p2, p3, p4): return (ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0 and ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0) def intersect2(s1, s2): return intersect4(s1.fi, s1.se, s2.fi, s2.se) def getDistance(a, b): return abs(a - b) def getDistanceLP(l, p): return abs(cross(l.se - l.fi, p - l.fi) / abs(l.se - l.fi)) def getDistanceSP(s, p): if dot(s.se - s.fi, p - s.fi) < 0.0: return abs(p - s.fi) if dot(s.fi - s.se, p - s.se) < 0.0: return abs(p - s.se) return getDistanceLP(s, p) def getDistances(s1, s2): if intersect2(s1, s2): return 0.0 return min(getDistanceSP(s1, s2.fi), getDistanceSP(s1, s2.se), getDistanceSP(s2, s1.fi), getDistanceSP(s2, s1.se)) def getCrossPoint(s1, s2): base = s2.se - s2.fi d1 = abs(cross(base, s1.fi - s2.fi)) d2 = abs(cross(base, s1.se - s2.fi)) t = d1 / (d1 + d2) return s1.fi + (s1.se - s1.fi) * t def getCrossPointsCL(c, l): pr = project(l, c.c) e = (l.se - l.fi) / abs(l.se - l.fi) base = sqrt(c.r * c.r - norm(pr - c.c)) return Segment(*sorted((pr + e * base, pr - e * base)), key=attrgetter('real', 'imag')) def getCrossPointsCC(c1, c2): d = abs(c1.c - c2.c) a = acos((c1.r * c1.r + d * d - c2.r * c2.r) / (2.0 * c1.r * d)) t = cmath.phase(c2.c - c1.c) return Segment(*sorted((c1.c + cmath.rect(c1.r, t + a), c1.c + cmath.rect(c1.r, t - a)), key=attrgetter('real', 'imag'))) def contains(g, p): n = len(g) x = False for i in range(n): a = g[i] - p b = g[(i + 1) % n] - p if abs(cross(a, b)) < EPS and dot(a, b) < EPS: return 1 if a.imag > b.imag: a, b = b, a if a.imag < EPS and EPS < b.imag and cross(a, b) > EPS: x = not x return 2 if x else 0 n = int(readline()) pg = tuple(complex(*map(int, readline().split())) for _ in [0] * n) q = int(readline()) for _ in [0] * q: print(contains(pg, complex(*map(int, readline().split())))) ```
3,300
Provide a correct Python 3 solution for this coding contest problem. For a given polygon g and target points t, print "2" if g contains t, "1" if t is on a segment of g, "0" otherwise. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≀ i ≀ n-1) are sides of the polygon. The line segment connecting pn and p1 is also a side of the polygon. Note that the polygon is not necessarily convex. Constraints * 3 ≀ n ≀ 100 * 1 ≀ q ≀ 1000 * -10000 ≀ xi, yi ≀ 10000 * No point of the polygon will occur more than once. * Two sides of the polygon can intersect only at a common endpoint. Input The entire input looks like: g (the sequence of the points of the polygon) q (the number of queris = the number of target points) 1st query 2nd query : qth query g is given by coordinates of the points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of a point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Each query consists of the coordinate of a target point t. The coordinate is given by two intgers x and y. Output For each query, print "2", "1" or "0". Example Input 4 0 0 3 1 2 3 0 3 3 2 1 0 2 3 2 Output 2 1 0 "Correct Solution: ``` # Aizu Problem CGL_3_C: Polygon-Point-Containment # import sys, math, os # read input: PYDEV = os.environ.get('PYDEV') if PYDEV=="True": sys.stdin = open("sample-input.txt", "rt") def cross_product_test(A, B, C): if A[1] == B[1] == C[1]: if B[0] <= A[0] <= C[0] or C[0] <= A[0] <= B[0]: return 0 else: return 1 if B[1] > C[1]: B, C = C[:], B[:] if A[1] == B[1] and A[0] == B[0]: return 0 if A[1] <= B[1] or A[1] > C[1]: return 1 delta = (B[0] - A[0]) * (C[1] - A[1]) - (B[1] - A[1]) * (C[0] - A[0]) if delta > 0: return -1 elif delta < 0: return 1 else: return 0 def point_in_polygon(polygon, point): t = -1 polygon.append(polygon[0]) for i in range(len(polygon) - 1): t *= cross_product_test(point, polygon[i], polygon[i+1]) return t N = int(input()) P = [[int(_) for _ in input().split()] for __ in range(N)] Q = int(input()) for q in range(Q): x, y = [int(_) for _ in input().split()] print(point_in_polygon(P, [x, y]) + 1) ```
3,301
Provide a correct Python 3 solution for this coding contest problem. For a given polygon g and target points t, print "2" if g contains t, "1" if t is on a segment of g, "0" otherwise. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≀ i ≀ n-1) are sides of the polygon. The line segment connecting pn and p1 is also a side of the polygon. Note that the polygon is not necessarily convex. Constraints * 3 ≀ n ≀ 100 * 1 ≀ q ≀ 1000 * -10000 ≀ xi, yi ≀ 10000 * No point of the polygon will occur more than once. * Two sides of the polygon can intersect only at a common endpoint. Input The entire input looks like: g (the sequence of the points of the polygon) q (the number of queris = the number of target points) 1st query 2nd query : qth query g is given by coordinates of the points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of a point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Each query consists of the coordinate of a target point t. The coordinate is given by two intgers x and y. Output For each query, print "2", "1" or "0". Example Input 4 0 0 3 1 2 3 0 3 3 2 1 0 2 3 2 Output 2 1 0 "Correct Solution: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- """ input: 4 0 0 3 1 2 3 0 3 3 2 1 0 2 3 2 output: 2 1 0 """ import sys EPS = 1e-9 def cross(a, b): return a.real * b.imag - a.imag * b.real def dot(a, b): return a.real * b.real + a.imag * b.imag def check_contains(g, p): flag = False for j in range(edges): a, b = g[j] - p, g[(j + 1) % edges] - p if abs(cross(a, b)) < EPS and dot(a, b) < EPS: return 1 elif a.imag > b.imag: a, b = b, a if a.imag < EPS < b.imag and cross(a, b) > EPS: flag = not flag return 2 if flag else 0 def solve(_p_info): for point in _p_info: px, py = map(float, point) p = px + py * 1j print(check_contains(polygon, p)) return None if __name__ == '__main__': _input = sys.stdin.readlines() edges = int(_input[0]) e_info = map(lambda x: x.split(), _input[1:edges + 1]) points = int(_input[edges + 1]) p_info = map(lambda x: x.split(), _input[edges + 2:]) polygon = [float(x) + float(y) * 1j for x, y in e_info] solve(p_info) ```
3,302
Provide a correct Python 3 solution for this coding contest problem. For a given polygon g and target points t, print "2" if g contains t, "1" if t is on a segment of g, "0" otherwise. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≀ i ≀ n-1) are sides of the polygon. The line segment connecting pn and p1 is also a side of the polygon. Note that the polygon is not necessarily convex. Constraints * 3 ≀ n ≀ 100 * 1 ≀ q ≀ 1000 * -10000 ≀ xi, yi ≀ 10000 * No point of the polygon will occur more than once. * Two sides of the polygon can intersect only at a common endpoint. Input The entire input looks like: g (the sequence of the points of the polygon) q (the number of queris = the number of target points) 1st query 2nd query : qth query g is given by coordinates of the points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of a point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Each query consists of the coordinate of a target point t. The coordinate is given by two intgers x and y. Output For each query, print "2", "1" or "0". Example Input 4 0 0 3 1 2 3 0 3 3 2 1 0 2 3 2 Output 2 1 0 "Correct Solution: ``` #!/usr/bin/env python3 # CGL_3_C: Polygon - Polygon-Point Containment from enum import Enum class Position(Enum): OUTSIDE = 0 BORDER = 1 INSIDE = 2 class Polygon: def __init__(self, ps): self.ps = ps self.convex_poligons = divide(ps) def position(self, p): if p in self.ps: return Position.BORDER pos = [position(*c, p) for c in self.convex_poligons] if all([x == Position.OUTSIDE for x in pos]): return Position.OUTSIDE elif any([x == Position.INSIDE for x in pos]): return Position.INSIDE elif len([x for x in pos if x == Position.BORDER]) > 1: return Position.INSIDE else: return Position.BORDER def divide(ps): if len(ps) < 3: return [] p0, p1, p2, *ps = ps if not ccw(p0, p1, p2): return divide([p1, p2] + ps + [p0]) for p in ps: if position(p0, p1, p2, p) != Position.OUTSIDE: return divide([p1, p2] + ps + [p0]) return [(p0, p1, p2)] + divide([p0, p2] + ps) def ccw(p0, p1, p2): x0, y0 = p0 x1, y1 = p1 x2, y2 = p2 v1 = (x1-x0, y1-y0) v2 = (x2-x1, y2-y1) return dot(orthogonal(v1), v2) > 0 def dot(v1, v2): x1, y1 = v1 x2, y2 = v2 return x1 * x2 + y1 * y2 def cross(v1, v2): x1, y1 = v1 x2, y2 = v2 return x1 * y2 - y1 * x2 def orthogonal(v): x, y = v return -y, x def position(p0, p1, p2, p): x, y = p ps = [p0, p1, p2] online = False for i in range(3): pa = ps[i] pb = ps[(i+1) % 3] pc = ps[(i+2) % 3] xa, ya = pa xb, yb = pb xc, yc = pc vab = (xb-xa, yb-ya) vac = (xc-xa, yc-ya) vp = (x-xa, y-ya) c = cross(vab, vp) * cross(vp, vac) if c == 0: online = True elif c < 0: return Position.OUTSIDE if online: return Position.BORDER else: return Position.INSIDE def run(): g = int(input()) ps = [] for _ in range(g): x, y = [int(i) for i in input().split()] ps.append((x, y)) poly = Polygon(ps) n = int(input()) for _ in range(n): qx, qy = [int(i) for i in input().split()] pos = poly.position((qx, qy)) print(pos.value) if __name__ == '__main__': run() ```
3,303
Provide a correct Python 3 solution for this coding contest problem. For a given polygon g and target points t, print "2" if g contains t, "1" if t is on a segment of g, "0" otherwise. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≀ i ≀ n-1) are sides of the polygon. The line segment connecting pn and p1 is also a side of the polygon. Note that the polygon is not necessarily convex. Constraints * 3 ≀ n ≀ 100 * 1 ≀ q ≀ 1000 * -10000 ≀ xi, yi ≀ 10000 * No point of the polygon will occur more than once. * Two sides of the polygon can intersect only at a common endpoint. Input The entire input looks like: g (the sequence of the points of the polygon) q (the number of queris = the number of target points) 1st query 2nd query : qth query g is given by coordinates of the points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of a point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Each query consists of the coordinate of a target point t. The coordinate is given by two intgers x and y. Output For each query, print "2", "1" or "0". Example Input 4 0 0 3 1 2 3 0 3 3 2 1 0 2 3 2 Output 2 1 0 "Correct Solution: ``` n = int(input()) vec = [] for i in range(n): vec += [list(map(int, input().split()))] vec += [vec[0]] def cross(a, b): return a[0]*b[1]-a[1]*b[0] def ab(a, b): c = (b[0]-a[0],b[1]-a[1]) return c def dot(a, b): n = len(a) if n != len(b): return None ans = 0 for i, j in zip(a, b): ans += i*j return ans def check(a, b): if abs(cross(a, b)) < pow(10,-8) and dot(a,b)<pow(10,-8): return 1 else: return 0 def contain(): x = 0 p = list(map(int, input().split())) for a,b in zip(vec[:-1],vec[1:]): a = ab(p,a) b = ab(p,b) if check(a, b) == 1: print(1) return if a[1] > b[1]: a, b = b, a if a[1] < pow(10,-8) and b[1] > pow(10,-8) and cross(a, b) > 0: x += 1 if x%2==1:print(2) else:print(0) k = int(input()) for i in range(k): contain() ```
3,304
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given polygon g and target points t, print "2" if g contains t, "1" if t is on a segment of g, "0" otherwise. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≀ i ≀ n-1) are sides of the polygon. The line segment connecting pn and p1 is also a side of the polygon. Note that the polygon is not necessarily convex. Constraints * 3 ≀ n ≀ 100 * 1 ≀ q ≀ 1000 * -10000 ≀ xi, yi ≀ 10000 * No point of the polygon will occur more than once. * Two sides of the polygon can intersect only at a common endpoint. Input The entire input looks like: g (the sequence of the points of the polygon) q (the number of queris = the number of target points) 1st query 2nd query : qth query g is given by coordinates of the points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of a point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Each query consists of the coordinate of a target point t. The coordinate is given by two intgers x and y. Output For each query, print "2", "1" or "0". Example Input 4 0 0 3 1 2 3 0 3 3 2 1 0 2 3 2 Output 2 1 0 Submitted Solution: ``` def dot(a, b): return a.real * b.real + a.imag * b.imag def cross(a, b): return a.real * b.imag - a.imag * b.real n = int(input()) vertices = [complex(*map(int, input().split())) for _ in range(n)] edges = [(p0, p1, p1 - p0) for p0, p1 in zip(vertices, vertices[1:] + [vertices[0]])] q = int(input()) while q: q -= 1 p = complex(*map(int, input().split())) counter = 0 for p0, p1, edge in edges: a, b = p0 - p, p1 - p if a.imag > b.imag: a, b = b, a crs = cross(a, b) if a.imag <= 0 and 0 < b.imag and crs < 0: counter += 1 if crs == 0 and dot(a, b) <= 0: print(1) break else: print(2 if counter % 2 else 0) ``` Yes
3,305
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given polygon g and target points t, print "2" if g contains t, "1" if t is on a segment of g, "0" otherwise. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≀ i ≀ n-1) are sides of the polygon. The line segment connecting pn and p1 is also a side of the polygon. Note that the polygon is not necessarily convex. Constraints * 3 ≀ n ≀ 100 * 1 ≀ q ≀ 1000 * -10000 ≀ xi, yi ≀ 10000 * No point of the polygon will occur more than once. * Two sides of the polygon can intersect only at a common endpoint. Input The entire input looks like: g (the sequence of the points of the polygon) q (the number of queris = the number of target points) 1st query 2nd query : qth query g is given by coordinates of the points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of a point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Each query consists of the coordinate of a target point t. The coordinate is given by two intgers x and y. Output For each query, print "2", "1" or "0". Example Input 4 0 0 3 1 2 3 0 3 3 2 1 0 2 3 2 Output 2 1 0 Submitted Solution: ``` def dot(c1, c2): return c1.real * c2.real + c1.imag * c2.imag def cross(c1, c2): return c1.real * c2.imag - c1.imag * c2.real def string_to_complex(s): x, y = map(int, s.split()) return x + y * 1j def contains(polygon, point): flag = False for v1, v2 in zip(polygon[0:], polygon[1:]): a = v1 - point b = v2 - point if a.imag > b.imag: a, b = b, a cross_ab = cross(a, b) if a.imag <= 0 and b.imag > 0 and cross_ab > 0: flag = not flag if cross_ab == 0 and dot(a, b) <= 0: return 1 if flag: return 2 else: return 0 import sys file_input = sys.stdin n = int(file_input.readline()) polygon = [string_to_complex(file_input.readline()) for i in range(n)] polygon.append(polygon[0]) q = int(file_input.readline()) for line in file_input: t = string_to_complex(line) print(contains(polygon, t)) ``` Yes
3,306
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given polygon g and target points t, print "2" if g contains t, "1" if t is on a segment of g, "0" otherwise. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≀ i ≀ n-1) are sides of the polygon. The line segment connecting pn and p1 is also a side of the polygon. Note that the polygon is not necessarily convex. Constraints * 3 ≀ n ≀ 100 * 1 ≀ q ≀ 1000 * -10000 ≀ xi, yi ≀ 10000 * No point of the polygon will occur more than once. * Two sides of the polygon can intersect only at a common endpoint. Input The entire input looks like: g (the sequence of the points of the polygon) q (the number of queris = the number of target points) 1st query 2nd query : qth query g is given by coordinates of the points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of a point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Each query consists of the coordinate of a target point t. The coordinate is given by two intgers x and y. Output For each query, print "2", "1" or "0". Example Input 4 0 0 3 1 2 3 0 3 3 2 1 0 2 3 2 Output 2 1 0 Submitted Solution: ``` def dot(c1, c2): return c1.real * c2.real + c1.imag * c2.imag def cross(c1, c2): return c1.real * c2.imag - c1.imag * c2.real def string_to_complex(s): x, y = map(int, s.split()) return x + y * 1j def contains(polygon, point): flag = False for v1, v2 in zip(polygon[0:], polygon[1:]): a = v1 - point b = v2 - point if a.imag > b.imag: a, b = b, a cross_ab = cross(a, b) if cross_ab == 0 and dot(a, b) <= 0: return 1 if a.imag <= 0 and b.imag > 0 and cross_ab > 0: flag = not flag if flag: return 2 else: return 0 import sys file_input = sys.stdin n = int(file_input.readline()) polygon = [string_to_complex(file_input.readline()) for i in range(n)] polygon.append(polygon[0]) q = int(file_input.readline()) for line in file_input: t = string_to_complex(line) print(contains(polygon, t)) ``` Yes
3,307
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given polygon g and target points t, print "2" if g contains t, "1" if t is on a segment of g, "0" otherwise. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≀ i ≀ n-1) are sides of the polygon. The line segment connecting pn and p1 is also a side of the polygon. Note that the polygon is not necessarily convex. Constraints * 3 ≀ n ≀ 100 * 1 ≀ q ≀ 1000 * -10000 ≀ xi, yi ≀ 10000 * No point of the polygon will occur more than once. * Two sides of the polygon can intersect only at a common endpoint. Input The entire input looks like: g (the sequence of the points of the polygon) q (the number of queris = the number of target points) 1st query 2nd query : qth query g is given by coordinates of the points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of a point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Each query consists of the coordinate of a target point t. The coordinate is given by two intgers x and y. Output For each query, print "2", "1" or "0". Example Input 4 0 0 3 1 2 3 0 3 3 2 1 0 2 3 2 Output 2 1 0 Submitted Solution: ``` n = int(input()) g = [] for i in range(n): g.append([int(i) for i in input().split()]) q = int(input()) EPS = 0.001 def dot(a, b): return sum([i * j for i,j in zip(a, b)]) def sub(a, b): return [a[0] - b[0],a[1] - b[1]] def cross(a, b): return a[0] * b[1] - a[1] * b[0] def contains(g, p): x = False for i in range(n): a = sub(g[i], p) b = sub(g[(i+1)%n], p) if abs(cross(a, b)) < EPS and dot(a, b) < EPS: return 1 if a[1] > b[1]: a,b=b,a if a[1] < EPS and EPS < b[1] and cross(a,b) > EPS: x = not x return 2 if x else 0 for i in range(q): x,y = map(int, input().split()) print(contains(g, [x,y])) ``` Yes
3,308
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given polygon g and target points t, print "2" if g contains t, "1" if t is on a segment of g, "0" otherwise. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≀ i ≀ n-1) are sides of the polygon. The line segment connecting pn and p1 is also a side of the polygon. Note that the polygon is not necessarily convex. Constraints * 3 ≀ n ≀ 100 * 1 ≀ q ≀ 1000 * -10000 ≀ xi, yi ≀ 10000 * No point of the polygon will occur more than once. * Two sides of the polygon can intersect only at a common endpoint. Input The entire input looks like: g (the sequence of the points of the polygon) q (the number of queris = the number of target points) 1st query 2nd query : qth query g is given by coordinates of the points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of a point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Each query consists of the coordinate of a target point t. The coordinate is given by two intgers x and y. Output For each query, print "2", "1" or "0". Example Input 4 0 0 3 1 2 3 0 3 3 2 1 0 2 3 2 Output 2 1 0 Submitted Solution: ``` def point_in_poly(x,y,poly): # check if point is a vertex if (x,y) in poly: return 1 # check if point is on a boundary for i in range(len(poly)): p1 = None p2 = None if i==0: p1 = poly[0] p2 = poly[1] else: p1 = poly[i-1] p2 = poly[i] if p1[1] == p2[1] and p1[1] == y and x > min(p1[0], p2[0]) and x < max(p1[0], p2[0]): return 1 n = len(poly) inside = False p1x,p1y = poly[0] for i in range(n+1): p2x,p2y = poly[i % n] if y > min(p1y,p2y): if y <= max(p1y,p2y): if x <= max(p1x,p2x): if p1y != p2y: xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x if p1x == p2x or x <= xints: inside = not inside p1x,p1y = p2x,p2y if inside: return 2 else: return 0 n=int(input()) g=[] for i in range(0,n): s= [int(x) for x in input().split()] #p0=Point(s[0],s[1]) g.append((s[0],s[1])) q=int(input()) for i in range(0,q): s= [int(x) for x in input().split()] #pa=Point(s[0],s[1]) rt=point_in_poly(s[0],s[1],g) print(rt) ``` No
3,309
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given polygon g and target points t, print "2" if g contains t, "1" if t is on a segment of g, "0" otherwise. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≀ i ≀ n-1) are sides of the polygon. The line segment connecting pn and p1 is also a side of the polygon. Note that the polygon is not necessarily convex. Constraints * 3 ≀ n ≀ 100 * 1 ≀ q ≀ 1000 * -10000 ≀ xi, yi ≀ 10000 * No point of the polygon will occur more than once. * Two sides of the polygon can intersect only at a common endpoint. Input The entire input looks like: g (the sequence of the points of the polygon) q (the number of queris = the number of target points) 1st query 2nd query : qth query g is given by coordinates of the points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of a point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Each query consists of the coordinate of a target point t. The coordinate is given by two intgers x and y. Output For each query, print "2", "1" or "0". Example Input 4 0 0 3 1 2 3 0 3 3 2 1 0 2 3 2 Output 2 1 0 Submitted Solution: ``` import math def dot(ux, uy, vx, vy): return ux*vx + uy*vy def cross(ux, uy, vx, vy): return ux*vy - uy*vx def dist_to_segment(x, y, ax, ay, bx, by): if dot(x - ax, y - ay, bx - ax, by - ay) < 0: return math.hypot(x - ax, y - ay) if dot(x - bx, y - by, ax - bx, ay - by) < 0: return math.hypot(x - bx, y - by) c = abs(cross(bx - ax, by - ay, x - ax, y - ay)) return c / math.hypot(bx - ax, by - ay) n = int(input()) g = [list(map(int, input().split())) for _ in range(n)] g.append(g[0]) q = int(input()) for _ in range(q): x, y = map(int, input().split()) i_min, d_min = 0, 1e7 for i in range(n): x1, y1 = g[i] x2, y2 = g[i + 1] d = dist_to_segment(x, y, x1, y1, x2, y2) if d < d_min: i_min, d_min = i, d x1, y1 = g[i_min] x2, y2 = g[i_min + 1] if cross(x1 - x, y1 - y, x2 - x, y2 - y) > 0: print(2) elif dist_to_segment(x, y, x1, y1, x2, y2) > 0: print(0) else: print(1) ``` No
3,310
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given polygon g and target points t, print "2" if g contains t, "1" if t is on a segment of g, "0" otherwise. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≀ i ≀ n-1) are sides of the polygon. The line segment connecting pn and p1 is also a side of the polygon. Note that the polygon is not necessarily convex. Constraints * 3 ≀ n ≀ 100 * 1 ≀ q ≀ 1000 * -10000 ≀ xi, yi ≀ 10000 * No point of the polygon will occur more than once. * Two sides of the polygon can intersect only at a common endpoint. Input The entire input looks like: g (the sequence of the points of the polygon) q (the number of queris = the number of target points) 1st query 2nd query : qth query g is given by coordinates of the points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of a point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Each query consists of the coordinate of a target point t. The coordinate is given by two intgers x and y. Output For each query, print "2", "1" or "0". Example Input 4 0 0 3 1 2 3 0 3 3 2 1 0 2 3 2 Output 2 1 0 Submitted Solution: ``` from sys import stdin readline = stdin.readline def cross(a, b): return a.real * b.imag - a.imag * b.real def dot(a, b): return a.real * b.real + a.imag * b.imag def eq(a, b): return abs(a - b) < 1e-10 def on_line(p, s, e): d = dot(p - s, e - s) c = cross(p - s, e - s) if c == 0 and 0 <= d <= abs(e - s) ** 2: return True return False def on_polygon_line(xy, p): for i in range(len(p)): j = i - 1 if on_line(xy, p[i], p[j]): return True return False def in_polygon(xy, p): wn = 0 for i in range(len(p)): j = i - 1 if 0 == (p[i] - p[j]).imag: continue vt = (xy - p[j]).imag / (p[i] - p[j]).imag tmp = p[i] + vt * (p[i] - p[j]) if xy.real < tmp.real: wn += 1 if p[j].imag < xy.imag <= p[i].imag else\ -1 if p[i].imag < xy.imag <= p[j].imag else 0 return wn n = int(readline()) p = [map(int, readline().split()) for _ in range(n)] p = [x + y * 1j for x, y in p] q = int(readline()) for _ in range(q): x, y = map(int, readline().split()) xy = x + y * 1j print(1 if on_polygon_line(xy, p) else 2 if in_polygon(xy, p) else 0) ``` No
3,311
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a given polygon g and target points t, print "2" if g contains t, "1" if t is on a segment of g, "0" otherwise. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≀ i ≀ n-1) are sides of the polygon. The line segment connecting pn and p1 is also a side of the polygon. Note that the polygon is not necessarily convex. Constraints * 3 ≀ n ≀ 100 * 1 ≀ q ≀ 1000 * -10000 ≀ xi, yi ≀ 10000 * No point of the polygon will occur more than once. * Two sides of the polygon can intersect only at a common endpoint. Input The entire input looks like: g (the sequence of the points of the polygon) q (the number of queris = the number of target points) 1st query 2nd query : qth query g is given by coordinates of the points p1,..., pn in the following format: n x1 y1 x2 y2 : xn yn The first integer n is the number of points. The coordinate of a point pi is given by two integers xi and yi. The coordinates of points are given in the order of counter-clockwise visit of them. Each query consists of the coordinate of a target point t. The coordinate is given by two intgers x and y. Output For each query, print "2", "1" or "0". Example Input 4 0 0 3 1 2 3 0 3 3 2 1 0 2 3 2 Output 2 1 0 Submitted Solution: ``` import math class Point(): def __init__(self, x, y): self.x = x self.y = y def __eq__(self, pnt): if self.x == pnt.x and self.y == pnt.y: return True return False class Vector(): def __init__(self, x, y): self.x = x self.y = y def inner_product(self, vec): return self.x*vec.x + self.y*vec.y def outer_product(self, vec): return self.x*vec.y - self.y*vec.x def norm(self): return math.sqrt(self.x**2 + self.y**2) def polar(self): r = self.norm() theta = math.atan2(self.y, self.x) return r, theta class Segment(): def __init__(self, p1=None, p2=None): self.p1 = p1 self.p2 = p2 def is_intersect(self, seg): a = (seg.p1.x - seg.p2.x) * (self.p1.y - seg.p1.y) + (seg.p1.y - seg.p2.y) * (seg.p1.x - self.p1.x) b = (seg.p1.x - seg.p2.x) * (self.p2.y - seg.p1.y) + (seg.p1.y - seg.p2.y) * (seg.p1.x - self.p2.x) c = (self.p1.x - self.p2.x) * (seg.p1.y - self.p1.y) + (self.p1.y - self.p2.y) * (self.p1.x - seg.p1.x) d = (self.p1.x - self.p2.x) * (seg.p2.y - self.p1.y) + (self.p1.y - self.p2.y) * (self.p1.x - seg.p2.x) e = (self.p1.x - seg.p1.x)*(self.p2.x - seg.p2.x) f = (self.p1.x - seg.p2.x)*(self.p2.x - seg.p1.x) g = (self.p1.y - seg.p1.y)*(self.p2.y - seg.p2.y) h = (self.p1.y - seg.p2.y)*(self.p2.y - seg.p1.y) return a*b <= 0 and c*d <= 0 and (e <= 0 or f <= 0) and (g <= 0 or h <= 0) def on_segment(self, pnt): if self.p1 == pnt or self.p2 == pnt: return True a, b = Vector(self.p2.x - self.p1.x, self.p2.y - self.p1.y), Vector(pnt.x - self.p1.x, pnt.y - self.p1.y) a_r, a_theta = a.polar() b_r, b_theta = b.polar() if a_theta == b_theta: if 0 < b_r/a_r and b_r/a_r < 1: return True return False n = int(input()) points = [] for i in range(n): x, y = list(map(int, input().split(' '))) points.append(Point(x, y)) points.append(points[0]) segments = [Segment(points[i], points[i+1]) for i in range(n)] q = int(input()) for i in range(q): x, y = list(map(int, input().split(' '))) right, left = Segment(Point(x, y), Point(10001, y)), Segment(Point(x, y), Point(-10001, y)) up, down = Segment(Point(x, y), Point(x, 10001)), Segment(Point(x, y), Point(x, -10001)) r_int, l_int, u_int, d_int = 0, 0, 0, 0 on_segment = False for seg in segments: if seg.on_segment(Point(x, y)): on_segment = True break if seg.is_intersect(right): r_int += 1 if seg.is_intersect(left): l_int += 1 if seg.is_intersect(up): u_int += 1 if seg.is_intersect(down): d_int += 1 if on_segment: print(1) elif (r_int%2 == 1 or l_int%2 == 1) and (u_int%2 == 1 or d_int%2 == 1): print(2) else: print(0) ``` No
3,312
Provide a correct Python 3 solution for this coding contest problem. For a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ which is sorted by ascending order, eliminate all equivalent elements. Constraints * $1 \leq n \leq 100,000$ * $-1000,000,000 \leq a_i \leq 1,000,000,000$ * $a_0 \leq a_1 \leq ... \leq a_{n-1}$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ,..., \; a_{n-1}$ Output Print the sequence after eliminating equivalent elements in a line. Separate adjacency elements by a space character. Example Input 4 1 2 2 4 Output 1 2 4 "Correct Solution: ``` n=int(input()) S=set(map(int, input().split())) print(*sorted(list(S))) ```
3,313
Provide a correct Python 3 solution for this coding contest problem. For a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ which is sorted by ascending order, eliminate all equivalent elements. Constraints * $1 \leq n \leq 100,000$ * $-1000,000,000 \leq a_i \leq 1,000,000,000$ * $a_0 \leq a_1 \leq ... \leq a_{n-1}$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ,..., \; a_{n-1}$ Output Print the sequence after eliminating equivalent elements in a line. Separate adjacency elements by a space character. Example Input 4 1 2 2 4 Output 1 2 4 "Correct Solution: ``` n = input() li = set([int(i) for i in input().split()]) li = sorted(li) print(" ".join(map(str, li))) ```
3,314
Provide a correct Python 3 solution for this coding contest problem. For a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ which is sorted by ascending order, eliminate all equivalent elements. Constraints * $1 \leq n \leq 100,000$ * $-1000,000,000 \leq a_i \leq 1,000,000,000$ * $a_0 \leq a_1 \leq ... \leq a_{n-1}$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ,..., \; a_{n-1}$ Output Print the sequence after eliminating equivalent elements in a line. Separate adjacency elements by a space character. Example Input 4 1 2 2 4 Output 1 2 4 "Correct Solution: ``` def main(): n = input() s = sorted(set(map(int, input().split(" ")))) print(*s) main() ```
3,315
Provide a correct Python 3 solution for this coding contest problem. For a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ which is sorted by ascending order, eliminate all equivalent elements. Constraints * $1 \leq n \leq 100,000$ * $-1000,000,000 \leq a_i \leq 1,000,000,000$ * $a_0 \leq a_1 \leq ... \leq a_{n-1}$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ,..., \; a_{n-1}$ Output Print the sequence after eliminating equivalent elements in a line. Separate adjacency elements by a space character. Example Input 4 1 2 2 4 Output 1 2 4 "Correct Solution: ``` n = int(input()) b = list(map(int,input().split())) a = list() pre = 100100100 for bb in b: if bb != pre: a.append(bb) pre = bb print(a[0],end="") for aa in a[1:]: print(" {}".format(aa),end="") print() ```
3,316
Provide a correct Python 3 solution for this coding contest problem. For a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ which is sorted by ascending order, eliminate all equivalent elements. Constraints * $1 \leq n \leq 100,000$ * $-1000,000,000 \leq a_i \leq 1,000,000,000$ * $a_0 \leq a_1 \leq ... \leq a_{n-1}$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ,..., \; a_{n-1}$ Output Print the sequence after eliminating equivalent elements in a line. Separate adjacency elements by a space character. Example Input 4 1 2 2 4 Output 1 2 4 "Correct Solution: ``` n = int(input()) a = sorted(list(set((map(int, input().split()))))) print(*a) ```
3,317
Provide a correct Python 3 solution for this coding contest problem. For a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ which is sorted by ascending order, eliminate all equivalent elements. Constraints * $1 \leq n \leq 100,000$ * $-1000,000,000 \leq a_i \leq 1,000,000,000$ * $a_0 \leq a_1 \leq ... \leq a_{n-1}$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ,..., \; a_{n-1}$ Output Print the sequence after eliminating equivalent elements in a line. Separate adjacency elements by a space character. Example Input 4 1 2 2 4 Output 1 2 4 "Correct Solution: ``` n = int(input()) a = list(map(int, input().split())) a = sorted(set(a)) print(" ".join(map(str, a))) ```
3,318
Provide a correct Python 3 solution for this coding contest problem. For a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ which is sorted by ascending order, eliminate all equivalent elements. Constraints * $1 \leq n \leq 100,000$ * $-1000,000,000 \leq a_i \leq 1,000,000,000$ * $a_0 \leq a_1 \leq ... \leq a_{n-1}$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ,..., \; a_{n-1}$ Output Print the sequence after eliminating equivalent elements in a line. Separate adjacency elements by a space character. Example Input 4 1 2 2 4 Output 1 2 4 "Correct Solution: ``` from sys import stdin n = int(stdin.readline()) l = list(stdin.readline().split()) l = list(dict.fromkeys(l)) print(' '.join(l)) ```
3,319
Provide a correct Python 3 solution for this coding contest problem. For a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ which is sorted by ascending order, eliminate all equivalent elements. Constraints * $1 \leq n \leq 100,000$ * $-1000,000,000 \leq a_i \leq 1,000,000,000$ * $a_0 \leq a_1 \leq ... \leq a_{n-1}$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ,..., \; a_{n-1}$ Output Print the sequence after eliminating equivalent elements in a line. Separate adjacency elements by a space character. Example Input 4 1 2 2 4 Output 1 2 4 "Correct Solution: ``` def unique(li): """Returns a list of unique elements in ordered list li >>> unique([1, 1]) [1] >>> unique([1, 2]) [1, 2] """ return [li[i] for i in range(len(li)) if i == 0 or li[i] > li[i-1]] def run(): n = int(input()) li = [int(x) for x in input().split()] assert(n == len(li)) print(" ".join([str(x) for x in unique(li)])) if __name__ == '__main__': run() ```
3,320
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ which is sorted by ascending order, eliminate all equivalent elements. Constraints * $1 \leq n \leq 100,000$ * $-1000,000,000 \leq a_i \leq 1,000,000,000$ * $a_0 \leq a_1 \leq ... \leq a_{n-1}$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ,..., \; a_{n-1}$ Output Print the sequence after eliminating equivalent elements in a line. Separate adjacency elements by a space character. Example Input 4 1 2 2 4 Output 1 2 4 Submitted Solution: ``` n=int(input()) A=list(map(int,input().split())) A=sorted(list(set(A))) print(' '.join(map(str,A))) ``` Yes
3,321
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ which is sorted by ascending order, eliminate all equivalent elements. Constraints * $1 \leq n \leq 100,000$ * $-1000,000,000 \leq a_i \leq 1,000,000,000$ * $a_0 \leq a_1 \leq ... \leq a_{n-1}$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ,..., \; a_{n-1}$ Output Print the sequence after eliminating equivalent elements in a line. Separate adjacency elements by a space character. Example Input 4 1 2 2 4 Output 1 2 4 Submitted Solution: ``` n = int(input()) a = sorted(list(set(list(map(int,input().split()))))) print (' '.join(map(str,a))) ``` Yes
3,322
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ which is sorted by ascending order, eliminate all equivalent elements. Constraints * $1 \leq n \leq 100,000$ * $-1000,000,000 \leq a_i \leq 1,000,000,000$ * $a_0 \leq a_1 \leq ... \leq a_{n-1}$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ,..., \; a_{n-1}$ Output Print the sequence after eliminating equivalent elements in a line. Separate adjacency elements by a space character. Example Input 4 1 2 2 4 Output 1 2 4 Submitted Solution: ``` n = int(input()) A = list(map(int, input().split())) B = [A[0]] for i in A: if B[-1] < i: B.append(i) print(*B) ``` Yes
3,323
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ which is sorted by ascending order, eliminate all equivalent elements. Constraints * $1 \leq n \leq 100,000$ * $-1000,000,000 \leq a_i \leq 1,000,000,000$ * $a_0 \leq a_1 \leq ... \leq a_{n-1}$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ,..., \; a_{n-1}$ Output Print the sequence after eliminating equivalent elements in a line. Separate adjacency elements by a space character. Example Input 4 1 2 2 4 Output 1 2 4 Submitted Solution: ``` N = int(input()) A = list(map(int,input().split())) print(*sorted(set(A))) ``` Yes
3,324
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ which is sorted by ascending order, eliminate all equivalent elements. Constraints * $1 \leq n \leq 100,000$ * $-1000,000,000 \leq a_i \leq 1,000,000,000$ * $a_0 \leq a_1 \leq ... \leq a_{n-1}$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ,..., \; a_{n-1}$ Output Print the sequence after eliminating equivalent elements in a line. Separate adjacency elements by a space character. Example Input 4 1 2 2 4 Output 1 2 4 Submitted Solution: ``` # coding=utf-8 N = int(input()) A = list(map(int, input().split())) print(' '.join(map(str, set(A)))) ``` No
3,325
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. For a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ which is sorted by ascending order, eliminate all equivalent elements. Constraints * $1 \leq n \leq 100,000$ * $-1000,000,000 \leq a_i \leq 1,000,000,000$ * $a_0 \leq a_1 \leq ... \leq a_{n-1}$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ,..., \; a_{n-1}$ Output Print the sequence after eliminating equivalent elements in a line. Separate adjacency elements by a space character. Example Input 4 1 2 2 4 Output 1 2 4 Submitted Solution: ``` n = int(input()) a = list(map(int, input().split(' '))) a = list(set(a)) print(' '.join(list(map(str, a)))) ``` No
3,326
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 ≀ i < n) such that s_i β‰  s_{i + 1}. It is guaranteed that the answer always exists. For example, for the string "01010" there are four indices i such that 1 ≀ i < n and s_i β‰  s_{i + 1} (i = 1, 2, 3, 4). For the string "111001" there are two such indices i (i = 3, 5). Recall that binary string is a non-empty sequence of characters where each character is either 0 or 1. Input The first line of the input contains three integers a, b and x (1 ≀ a, b ≀ 100, 1 ≀ x < a + b). Output Print only one string s, where s is any binary string satisfying conditions described above. It is guaranteed that the answer always exists. Examples Input 2 2 1 Output 1100 Input 3 3 3 Output 101100 Input 5 3 6 Output 01010100 Note All possible answers for the first example: * 1100; * 0011. All possible answers for the second example: * 110100; * 101100; * 110010; * 100110; * 011001; * 001101; * 010011; * 001011. Tags: constructive algorithms Correct Solution: ``` def binary_string(a, b, x): s1 = '01' s2 = '10' if x % 2 == 0 and a > b: return s1 * (x // 2) + '1' * (b - x // 2) + '0' * (a - x // 2) elif x % 2 == 0 and a <= b: return s2 * (x // 2) + '0' * (a - x // 2) + '1' * (b - x // 2) elif x % 2 != 0 and a > b: return s1 * (x // 2) + '0' * (a - x // 2) + '1' * (b - x // 2) elif x % 2 != 0 and a <= b: return s2 * (x // 2) + '1' * (b - x // 2) + '0' * (a - x // 2) A, B, X = [int(j) for j in input().split()] print(binary_string(A, B, X)) ```
3,327
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 ≀ i < n) such that s_i β‰  s_{i + 1}. It is guaranteed that the answer always exists. For example, for the string "01010" there are four indices i such that 1 ≀ i < n and s_i β‰  s_{i + 1} (i = 1, 2, 3, 4). For the string "111001" there are two such indices i (i = 3, 5). Recall that binary string is a non-empty sequence of characters where each character is either 0 or 1. Input The first line of the input contains three integers a, b and x (1 ≀ a, b ≀ 100, 1 ≀ x < a + b). Output Print only one string s, where s is any binary string satisfying conditions described above. It is guaranteed that the answer always exists. Examples Input 2 2 1 Output 1100 Input 3 3 3 Output 101100 Input 5 3 6 Output 01010100 Note All possible answers for the first example: * 1100; * 0011. All possible answers for the second example: * 110100; * 101100; * 110010; * 100110; * 011001; * 001101; * 010011; * 001011. Tags: constructive algorithms Correct Solution: ``` a,b,x = map(int,input().split(' ')) if b>a: if x%2!=0: s = '10'*(x-x//2) s = '1'*(b-(x//2)-1)+s+'0'*(a-(x//2)-1) else: s = '10'*((x-1)-(x-1)//2) s = s+'0'*(a-(x//2))+'1'*(b-(x//2)) else: if x%2!=0: s = '01'*(x-x//2) s = '0'*(a-(x//2)-1)+s+'1'*(b-(x//2)-1) else: s = '01'*((x-1)-(x-1)//2) s = s+'1'*(b-(x//2))+'0'*(a-(x//2)) print(s) ```
3,328
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 ≀ i < n) such that s_i β‰  s_{i + 1}. It is guaranteed that the answer always exists. For example, for the string "01010" there are four indices i such that 1 ≀ i < n and s_i β‰  s_{i + 1} (i = 1, 2, 3, 4). For the string "111001" there are two such indices i (i = 3, 5). Recall that binary string is a non-empty sequence of characters where each character is either 0 or 1. Input The first line of the input contains three integers a, b and x (1 ≀ a, b ≀ 100, 1 ≀ x < a + b). Output Print only one string s, where s is any binary string satisfying conditions described above. It is guaranteed that the answer always exists. Examples Input 2 2 1 Output 1100 Input 3 3 3 Output 101100 Input 5 3 6 Output 01010100 Note All possible answers for the first example: * 1100; * 0011. All possible answers for the second example: * 110100; * 101100; * 110010; * 100110; * 011001; * 001101; * 010011; * 001011. Tags: constructive algorithms Correct Solution: ``` a, b, x = [int(i) for i in input().split()] odd = "" if x % 2 == 0: for i in range(x//2): odd += "01" a -= 1 b -= 1 if b > 0: print("1" * b + "0" * a + odd) elif b == 0: print(odd + "0" * a) else: for i in range((x+1)//2): odd += "01" a -= 1 b -= 1 print("0" * a + odd + "1" * b) ```
3,329
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 ≀ i < n) such that s_i β‰  s_{i + 1}. It is guaranteed that the answer always exists. For example, for the string "01010" there are four indices i such that 1 ≀ i < n and s_i β‰  s_{i + 1} (i = 1, 2, 3, 4). For the string "111001" there are two such indices i (i = 3, 5). Recall that binary string is a non-empty sequence of characters where each character is either 0 or 1. Input The first line of the input contains three integers a, b and x (1 ≀ a, b ≀ 100, 1 ≀ x < a + b). Output Print only one string s, where s is any binary string satisfying conditions described above. It is guaranteed that the answer always exists. Examples Input 2 2 1 Output 1100 Input 3 3 3 Output 101100 Input 5 3 6 Output 01010100 Note All possible answers for the first example: * 1100; * 0011. All possible answers for the second example: * 110100; * 101100; * 110010; * 100110; * 011001; * 001101; * 010011; * 001011. Tags: constructive algorithms Correct Solution: ``` def sol(z,o,k): c = 1 idx = 1 if z>o: s = ['0']*z+['1']*o else: s = ['1']*o+['0']*z while (c<k): key = s.pop(-1) s.insert(idx, key) c+=2 idx+=2 if c>k: for _ in range(2): key = s.pop(idx-2) s.append(key) return ''.join(s) z,o,k = map(int, input().split()) print(sol(z,o,k)) ```
3,330
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 ≀ i < n) such that s_i β‰  s_{i + 1}. It is guaranteed that the answer always exists. For example, for the string "01010" there are four indices i such that 1 ≀ i < n and s_i β‰  s_{i + 1} (i = 1, 2, 3, 4). For the string "111001" there are two such indices i (i = 3, 5). Recall that binary string is a non-empty sequence of characters where each character is either 0 or 1. Input The first line of the input contains three integers a, b and x (1 ≀ a, b ≀ 100, 1 ≀ x < a + b). Output Print only one string s, where s is any binary string satisfying conditions described above. It is guaranteed that the answer always exists. Examples Input 2 2 1 Output 1100 Input 3 3 3 Output 101100 Input 5 3 6 Output 01010100 Note All possible answers for the first example: * 1100; * 0011. All possible answers for the second example: * 110100; * 101100; * 110010; * 100110; * 011001; * 001101; * 010011; * 001011. Tags: constructive algorithms Correct Solution: ``` L = list(map(int, input().split())) zero=L[0] one=L[1] x=L[2] s='' if x%2==0: if one>zero : for i in range (x//2): s=s+'10' s+='1' one=one-(x//2)-1 zero=zero-(x//2) else: for i in range (x//2): s=s+'01' s+='0' one=one-(x//2) zero=zero-(x//2)-1 else: z=int(x/2)+1 if one>zero : for i in range (z): s=s+'10' one=one-z zero=zero-z else: for i in range (z): s=s+'01' one=one-z zero=zero-z leftone='' for i in range(one): leftone+='1' leftzero='' for i in range(zero): leftzero+='0' if s[0]=='1': s=s[0]+leftzero+s[1:] s=leftone+s else: s=s[0]+leftone+s[1:] s=leftzero+s print(s) ```
3,331
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 ≀ i < n) such that s_i β‰  s_{i + 1}. It is guaranteed that the answer always exists. For example, for the string "01010" there are four indices i such that 1 ≀ i < n and s_i β‰  s_{i + 1} (i = 1, 2, 3, 4). For the string "111001" there are two such indices i (i = 3, 5). Recall that binary string is a non-empty sequence of characters where each character is either 0 or 1. Input The first line of the input contains three integers a, b and x (1 ≀ a, b ≀ 100, 1 ≀ x < a + b). Output Print only one string s, where s is any binary string satisfying conditions described above. It is guaranteed that the answer always exists. Examples Input 2 2 1 Output 1100 Input 3 3 3 Output 101100 Input 5 3 6 Output 01010100 Note All possible answers for the first example: * 1100; * 0011. All possible answers for the second example: * 110100; * 101100; * 110010; * 100110; * 011001; * 001101; * 010011; * 001011. Tags: constructive algorithms Correct Solution: ``` s=input() s=s.split() x='' for i in range(len(s)): s[i]=int(s[i]) if s[0]>=s[1]: for j in range(s[2]): if j%2==0: x=x+'0' else: x=x+'1' if s[2]%2==0: s1=s[2]//2 s2=s[2]//2 else: s1=s[2]//2 s2=s[2]//2+1 else: for j in range(s[2]): if j%2==0: x=x+'1' else: x=x+'0' if s[2]%2==0: s1=s[2]//2 s2=s[2]//2 else: s1=s[2]//2+1 s2=s[2]//2 if len(x)==0: for i in range(s[0]): x=x+'0' for i in range(s[1]): x=x+'1' elif x[len(x)-1]=='0': for i in range(s[0]-s2): x=x+'0' for i in range(s[1]-s1): x=x+'1' elif x[len(x)-1]=='1': for i in range(s[1]-s1): x=x+'1' for i in range(s[0]-s2): x=x+'0' print(x) ```
3,332
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 ≀ i < n) such that s_i β‰  s_{i + 1}. It is guaranteed that the answer always exists. For example, for the string "01010" there are four indices i such that 1 ≀ i < n and s_i β‰  s_{i + 1} (i = 1, 2, 3, 4). For the string "111001" there are two such indices i (i = 3, 5). Recall that binary string is a non-empty sequence of characters where each character is either 0 or 1. Input The first line of the input contains three integers a, b and x (1 ≀ a, b ≀ 100, 1 ≀ x < a + b). Output Print only one string s, where s is any binary string satisfying conditions described above. It is guaranteed that the answer always exists. Examples Input 2 2 1 Output 1100 Input 3 3 3 Output 101100 Input 5 3 6 Output 01010100 Note All possible answers for the first example: * 1100; * 0011. All possible answers for the second example: * 110100; * 101100; * 110010; * 100110; * 011001; * 001101; * 010011; * 001011. Tags: constructive algorithms Correct Solution: ``` ### PREYANSH RASTOGI ### 2017176 if __name__=="__main__": a,b,x = [int(x) for x in input().split()] s= "" c=1 if b >a: c=-1 x+=1 while(x!=0) : if (c==1): s+="0" a-=1 else: s+="1" b-=1 c*=-1 x-=1 # print(s,a,b) if (a>0): q = s.rfind("0") if (q!=len(s)-1): s = s[:q] + "0"*a + s[q:] else: s+="0"*a if (b > 0): q= s.rfind("1") if (q!=len(s)-1): s = s[:q] + "1"*b + s[q:] else: s+="1"*b print(s) ```
3,333
Provide tags and a correct Python 3 solution for this coding contest problem. You are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 ≀ i < n) such that s_i β‰  s_{i + 1}. It is guaranteed that the answer always exists. For example, for the string "01010" there are four indices i such that 1 ≀ i < n and s_i β‰  s_{i + 1} (i = 1, 2, 3, 4). For the string "111001" there are two such indices i (i = 3, 5). Recall that binary string is a non-empty sequence of characters where each character is either 0 or 1. Input The first line of the input contains three integers a, b and x (1 ≀ a, b ≀ 100, 1 ≀ x < a + b). Output Print only one string s, where s is any binary string satisfying conditions described above. It is guaranteed that the answer always exists. Examples Input 2 2 1 Output 1100 Input 3 3 3 Output 101100 Input 5 3 6 Output 01010100 Note All possible answers for the first example: * 1100; * 0011. All possible answers for the second example: * 110100; * 101100; * 110010; * 100110; * 011001; * 001101; * 010011; * 001011. Tags: constructive algorithms Correct Solution: ``` from math import * a,b,x=(int(i) for i in input().split()) ans='' a1,b1=a,b mx=ceil((a+b)/(x+1)) af=True xx=0 for i in range(x-1): if (af): ans+='0' a-=1 af=not(af) else: ans+='1' b-=1 af=not(af) if (af): ans+='0'*a ans+='1'*b else: ans+='1'*b ans+='0'*a for i in range(len(ans)-1): if (ans[i]!=ans[i+1]): xx+=1 if xx!=x: af=False ans='' a,b=a1,b1 for i in range(x-1): if (af): ans+='0' a-=1 af=not(af) else: ans+='1' b-=1 af=not(af) if (af): ans+='0'*a ans+='1'*b else: ans+='1'*b ans+='0'*a print(ans) ```
3,334
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 ≀ i < n) such that s_i β‰  s_{i + 1}. It is guaranteed that the answer always exists. For example, for the string "01010" there are four indices i such that 1 ≀ i < n and s_i β‰  s_{i + 1} (i = 1, 2, 3, 4). For the string "111001" there are two such indices i (i = 3, 5). Recall that binary string is a non-empty sequence of characters where each character is either 0 or 1. Input The first line of the input contains three integers a, b and x (1 ≀ a, b ≀ 100, 1 ≀ x < a + b). Output Print only one string s, where s is any binary string satisfying conditions described above. It is guaranteed that the answer always exists. Examples Input 2 2 1 Output 1100 Input 3 3 3 Output 101100 Input 5 3 6 Output 01010100 Note All possible answers for the first example: * 1100; * 0011. All possible answers for the second example: * 110100; * 101100; * 110010; * 100110; * 011001; * 001101; * 010011; * 001011. Submitted Solution: ``` [a,b,x]=list(map(int,input().split())) n=int(x/2) s='' if x%2: if b>a: s+='10'*n s+='1'*(b-n) s+='0'*(a-n) else: s+='01'*n s+='0'*(a-n) s+='1'*(b-n) else: if b>a: s+='10'*n s+='0'*(a-n) s+='1'*(b-n) else: s+='01'*n s+='1'*(b-n) s+='0'*(a-n) print(s) ``` Yes
3,335
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 ≀ i < n) such that s_i β‰  s_{i + 1}. It is guaranteed that the answer always exists. For example, for the string "01010" there are four indices i such that 1 ≀ i < n and s_i β‰  s_{i + 1} (i = 1, 2, 3, 4). For the string "111001" there are two such indices i (i = 3, 5). Recall that binary string is a non-empty sequence of characters where each character is either 0 or 1. Input The first line of the input contains three integers a, b and x (1 ≀ a, b ≀ 100, 1 ≀ x < a + b). Output Print only one string s, where s is any binary string satisfying conditions described above. It is guaranteed that the answer always exists. Examples Input 2 2 1 Output 1100 Input 3 3 3 Output 101100 Input 5 3 6 Output 01010100 Note All possible answers for the first example: * 1100; * 0011. All possible answers for the second example: * 110100; * 101100; * 110010; * 100110; * 011001; * 001101; * 010011; * 001011. Submitted Solution: ``` a, b, x = input().split() a = int(a) b = int(b) x = int(x) s = "" y = 0 flag = 0 if x % 2 == 0: flag = 1 y = int(x/2) else: y = int((x+1)/2) # if y == b: # a = a - 1 # for i in range(y): # s = s + "10" # for i in range(b-y): # s = "1" + s # for i in range(a-y): # s = s + "0" # s = "0" + s # elif y == a: # b = b - 1 # for i in range(y): # s = s + "10" # for i in range(b-y): # s = "1" + s # for i in range(a-y): # s = s + "0" # s = s + "1" # else: b = b - y a = a - y for i in range(y): s = s + "10" for i in range(b): s = "1" + s for i in range(a): s = s + "0" if flag == 1: if a > 0: s = "0" + s s = s[0:-1] elif b > 0: s = s + "1" s = s[1:] print(s) ``` Yes
3,336
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 ≀ i < n) such that s_i β‰  s_{i + 1}. It is guaranteed that the answer always exists. For example, for the string "01010" there are four indices i such that 1 ≀ i < n and s_i β‰  s_{i + 1} (i = 1, 2, 3, 4). For the string "111001" there are two such indices i (i = 3, 5). Recall that binary string is a non-empty sequence of characters where each character is either 0 or 1. Input The first line of the input contains three integers a, b and x (1 ≀ a, b ≀ 100, 1 ≀ x < a + b). Output Print only one string s, where s is any binary string satisfying conditions described above. It is guaranteed that the answer always exists. Examples Input 2 2 1 Output 1100 Input 3 3 3 Output 101100 Input 5 3 6 Output 01010100 Note All possible answers for the first example: * 1100; * 0011. All possible answers for the second example: * 110100; * 101100; * 110010; * 100110; * 011001; * 001101; * 010011; * 001011. Submitted Solution: ``` # -*- coding: utf-8 -*- import sys from itertools import accumulate def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)] def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') INF = 10 ** 18 MOD = 10 ** 9 + 7 a, b, x = MAP() swapped = False if b > a: swapped = True ans = [] for i in range(x-1): if i % 2 == 0 ^ swapped: ans.append('0') a -= 1 else: ans.append('1') b -= 1 if ans and ans[-1] == '0': ans += '1' * b ans += '0' * a else: ans += '0' * a ans += '1' * b print(''.join(ans)) ``` Yes
3,337
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 ≀ i < n) such that s_i β‰  s_{i + 1}. It is guaranteed that the answer always exists. For example, for the string "01010" there are four indices i such that 1 ≀ i < n and s_i β‰  s_{i + 1} (i = 1, 2, 3, 4). For the string "111001" there are two such indices i (i = 3, 5). Recall that binary string is a non-empty sequence of characters where each character is either 0 or 1. Input The first line of the input contains three integers a, b and x (1 ≀ a, b ≀ 100, 1 ≀ x < a + b). Output Print only one string s, where s is any binary string satisfying conditions described above. It is guaranteed that the answer always exists. Examples Input 2 2 1 Output 1100 Input 3 3 3 Output 101100 Input 5 3 6 Output 01010100 Note All possible answers for the first example: * 1100; * 0011. All possible answers for the second example: * 110100; * 101100; * 110010; * 100110; * 011001; * 001101; * 010011; * 001011. Submitted Solution: ``` a1 = input() l1= list(map(int,a1.split())) a=l1[0] b=l1[1] x=l1[2] m=max(a,b) z="" p="1" q="0" if m==a: p="0" q="1" for i in range(x+1): if i%2==0: z= z + p if p=="1": b-=1 else: a-=1 else: z=z + q if q=="1": b-=1 else: a-=1 jj="1"*b pp="0"*a if z[0]=="1": z= jj + "1" + pp + z[1:] else: z= pp + "0" + jj + z[1:] print(z) ``` Yes
3,338
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 ≀ i < n) such that s_i β‰  s_{i + 1}. It is guaranteed that the answer always exists. For example, for the string "01010" there are four indices i such that 1 ≀ i < n and s_i β‰  s_{i + 1} (i = 1, 2, 3, 4). For the string "111001" there are two such indices i (i = 3, 5). Recall that binary string is a non-empty sequence of characters where each character is either 0 or 1. Input The first line of the input contains three integers a, b and x (1 ≀ a, b ≀ 100, 1 ≀ x < a + b). Output Print only one string s, where s is any binary string satisfying conditions described above. It is guaranteed that the answer always exists. Examples Input 2 2 1 Output 1100 Input 3 3 3 Output 101100 Input 5 3 6 Output 01010100 Note All possible answers for the first example: * 1100; * 0011. All possible answers for the second example: * 110100; * 101100; * 110010; * 100110; * 011001; * 001101; * 010011; * 001011. Submitted Solution: ``` from collections import Counter def A(): N = int(input()) c = Counter(input().split()) print(c.most_common(1)[0][1]) def B(): A, B, X = map(int, input().split()) s = ''.join(['0']*A) + ''.join(['1']*B) i = 1 while X > 1: s = s[:i] + '1' + s[i:-1] i += 2 X -= 2 #if X == 0: # s = s[1] + s[0] + s[2:] print(s) def C(): pass def D(): pass def E(): pass B() ``` No
3,339
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 ≀ i < n) such that s_i β‰  s_{i + 1}. It is guaranteed that the answer always exists. For example, for the string "01010" there are four indices i such that 1 ≀ i < n and s_i β‰  s_{i + 1} (i = 1, 2, 3, 4). For the string "111001" there are two such indices i (i = 3, 5). Recall that binary string is a non-empty sequence of characters where each character is either 0 or 1. Input The first line of the input contains three integers a, b and x (1 ≀ a, b ≀ 100, 1 ≀ x < a + b). Output Print only one string s, where s is any binary string satisfying conditions described above. It is guaranteed that the answer always exists. Examples Input 2 2 1 Output 1100 Input 3 3 3 Output 101100 Input 5 3 6 Output 01010100 Note All possible answers for the first example: * 1100; * 0011. All possible answers for the second example: * 110100; * 101100; * 110010; * 100110; * 011001; * 001101; * 010011; * 001011. Submitted Solution: ``` # import sys # sys.stdin=open('/home/mukund/Competitive Coding/input.txt','r') # sys.stdout=open('/home/mukund/Competitive Coding/output.txt','w') [a,b,x]=list(map(int,input().split())) n=int(x/2) s='' if x%2: if b>a: s+='10'*n s+='1'*(a-n) s+='0'*(b-n) else: s+='01'*n s+='0'*(b-n) s+='1'*(a-n) else: if b>a: s+='01'*n s+='1'*(a-n) s+='0'*(b-n) else: s+='10'*n s+='0'*(b-n) s+='1'*(a-n) print(s) ``` No
3,340
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 ≀ i < n) such that s_i β‰  s_{i + 1}. It is guaranteed that the answer always exists. For example, for the string "01010" there are four indices i such that 1 ≀ i < n and s_i β‰  s_{i + 1} (i = 1, 2, 3, 4). For the string "111001" there are two such indices i (i = 3, 5). Recall that binary string is a non-empty sequence of characters where each character is either 0 or 1. Input The first line of the input contains three integers a, b and x (1 ≀ a, b ≀ 100, 1 ≀ x < a + b). Output Print only one string s, where s is any binary string satisfying conditions described above. It is guaranteed that the answer always exists. Examples Input 2 2 1 Output 1100 Input 3 3 3 Output 101100 Input 5 3 6 Output 01010100 Note All possible answers for the first example: * 1100; * 0011. All possible answers for the second example: * 110100; * 101100; * 110010; * 100110; * 011001; * 001101; * 010011; * 001011. Submitted Solution: ``` #!/usr/bin/env python3 a, b, x = [int(i) for i in input().split()] ans = [] flag = 0 for i in range(x): if flag == 0: ans.append('1') flag = 1 b -= 1 else: ans.append('0') flag = 0 a -= 1 ans = [1] * (b) + ans + [0] * (a) for i in range(len(ans)): print(ans[i], end = '') ``` No
3,341
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 ≀ i < n) such that s_i β‰  s_{i + 1}. It is guaranteed that the answer always exists. For example, for the string "01010" there are four indices i such that 1 ≀ i < n and s_i β‰  s_{i + 1} (i = 1, 2, 3, 4). For the string "111001" there are two such indices i (i = 3, 5). Recall that binary string is a non-empty sequence of characters where each character is either 0 or 1. Input The first line of the input contains three integers a, b and x (1 ≀ a, b ≀ 100, 1 ≀ x < a + b). Output Print only one string s, where s is any binary string satisfying conditions described above. It is guaranteed that the answer always exists. Examples Input 2 2 1 Output 1100 Input 3 3 3 Output 101100 Input 5 3 6 Output 01010100 Note All possible answers for the first example: * 1100; * 0011. All possible answers for the second example: * 110100; * 101100; * 110010; * 100110; * 011001; * 001101; * 010011; * 001011. Submitted Solution: ``` a,b,x=input().strip().split(' ') a,b,x=int(a),int(b),int(x) if(x%2): if(a<b): s='01' else: s='10' s*=(x+1)//2 a-=s.count('0') b-=s.count('1') if(a<b): s+='1'*b b=0 else: s+='0'*a a=0 s='1'*b+'0'*a+s else: if(a<b): s='01' else: s='10' s*=x//2 a-=s.count('0') b-=s.count('1') if(a<b): s+='0'*a+'1' b-=1 s='1'*b+s else: s+='1'*b+'0' a-=1 s='0'*a+s print(s) ``` No
3,342
Provide tags and a correct Python 3 solution for this coding contest problem. You have n sticks of the given lengths. Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks. Let S be the area of the rectangle and P be the perimeter of the rectangle. The chosen rectangle should have the value (P^2)/(S) minimal possible. The value is taken without any rounding. If there are multiple answers, print any of them. Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately. Input The first line contains a single integer T (T β‰₯ 1) β€” the number of lists of sticks in the testcase. Then 2T lines follow β€” lines (2i - 1) and 2i of them describe the i-th list. The first line of the pair contains a single integer n (4 ≀ n ≀ 10^6) β€” the number of sticks in the i-th list. The second line of the pair contains n integers a_1, a_2, ..., a_n (1 ≀ a_j ≀ 10^4) β€” lengths of the sticks in the i-th list. It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle. The total number of sticks in all T lists doesn't exceed 10^6 in each testcase. Output Print T lines. The i-th line should contain the answer to the i-th list of the input. That is the lengths of the four sticks you choose from the i-th list, so that they form a rectangle and the value (P^2)/(S) of this rectangle is minimal possible. You can print these four lengths in arbitrary order. If there are multiple answers, print any of them. Example Input 3 4 7 2 2 7 8 2 8 1 4 8 2 1 5 5 5 5 5 5 5 Output 2 7 7 2 2 2 1 1 5 5 5 5 Note There is only one way to choose four sticks in the first list, they form a rectangle with sides 2 and 7, its area is 2 β‹… 7 = 14, perimeter is 2(2 + 7) = 18. (18^2)/(14) β‰ˆ 23.143. The second list contains subsets of four sticks that can form rectangles with sides (1, 2), (2, 8) and (1, 8). Their values are (6^2)/(2) = 18, (20^2)/(16) = 25 and (18^2)/(8) = 40.5, respectively. The minimal one of them is the rectangle (1, 2). You can choose any four of the 5 given sticks from the third list, they will form a square with side 5, which is still a rectangle with sides (5, 5). Tags: greedy Correct Solution: ``` import atexit import io import sys _INPUT_LINES = sys.stdin.read().splitlines() input = iter(_INPUT_LINES).__next__ _OUTPUT_BUFFER = io.StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) from collections import Counter def calc(a, b): return ((2 * (a + b)) ** 2) / (a * b) n = int(input()) for i in range(n): input() arr = list(map(int, input().split())) arr.sort() cnt = Counter() doublesticks = list() for v in arr: if cnt[v] == 1: doublesticks.append(v) cnt[v] = 0 else: cnt[v] = 1 ans = calc(doublesticks[1], doublesticks[0]) idx = 0 for i in range(len(doublesticks) - 1): res = calc(doublesticks[i + 1], doublesticks[i]) if res < ans: ans = res idx = i print(doublesticks[idx], doublesticks[idx], doublesticks[idx + 1], doublesticks[idx + 1]) ```
3,343
Provide tags and a correct Python 3 solution for this coding contest problem. You have n sticks of the given lengths. Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks. Let S be the area of the rectangle and P be the perimeter of the rectangle. The chosen rectangle should have the value (P^2)/(S) minimal possible. The value is taken without any rounding. If there are multiple answers, print any of them. Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately. Input The first line contains a single integer T (T β‰₯ 1) β€” the number of lists of sticks in the testcase. Then 2T lines follow β€” lines (2i - 1) and 2i of them describe the i-th list. The first line of the pair contains a single integer n (4 ≀ n ≀ 10^6) β€” the number of sticks in the i-th list. The second line of the pair contains n integers a_1, a_2, ..., a_n (1 ≀ a_j ≀ 10^4) β€” lengths of the sticks in the i-th list. It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle. The total number of sticks in all T lists doesn't exceed 10^6 in each testcase. Output Print T lines. The i-th line should contain the answer to the i-th list of the input. That is the lengths of the four sticks you choose from the i-th list, so that they form a rectangle and the value (P^2)/(S) of this rectangle is minimal possible. You can print these four lengths in arbitrary order. If there are multiple answers, print any of them. Example Input 3 4 7 2 2 7 8 2 8 1 4 8 2 1 5 5 5 5 5 5 5 Output 2 7 7 2 2 2 1 1 5 5 5 5 Note There is only one way to choose four sticks in the first list, they form a rectangle with sides 2 and 7, its area is 2 β‹… 7 = 14, perimeter is 2(2 + 7) = 18. (18^2)/(14) β‰ˆ 23.143. The second list contains subsets of four sticks that can form rectangles with sides (1, 2), (2, 8) and (1, 8). Their values are (6^2)/(2) = 18, (20^2)/(16) = 25 and (18^2)/(8) = 40.5, respectively. The minimal one of them is the rectangle (1, 2). You can choose any four of the 5 given sticks from the third list, they will form a square with side 5, which is still a rectangle with sides (5, 5). Tags: greedy Correct Solution: ``` import sys T = int(sys.stdin.readline().rstrip()) for i in range(T): n = int(sys.stdin.readline().rstrip()) a = list(map(int, sys.stdin.readline().rstrip().split())) rec = [] a = sorted(a) k = 0 while k < n - 1: if a[k] == a[k + 1]: rec.append(a[k]) k += 1 k += 1 ans1, ans2 = 1, 1e18 for j in range(1, len(rec)): if ((ans1 + ans2) * 2) ** 2 / (ans1 * ans2) > ((rec[j] + rec[j - 1]) * 2) ** 2 / (rec[j] * rec[j - 1]): ans1, ans2 = rec[j], rec[j - 1] print(ans1, ans2, ans1, ans2) ```
3,344
Provide tags and a correct Python 3 solution for this coding contest problem. You have n sticks of the given lengths. Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks. Let S be the area of the rectangle and P be the perimeter of the rectangle. The chosen rectangle should have the value (P^2)/(S) minimal possible. The value is taken without any rounding. If there are multiple answers, print any of them. Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately. Input The first line contains a single integer T (T β‰₯ 1) β€” the number of lists of sticks in the testcase. Then 2T lines follow β€” lines (2i - 1) and 2i of them describe the i-th list. The first line of the pair contains a single integer n (4 ≀ n ≀ 10^6) β€” the number of sticks in the i-th list. The second line of the pair contains n integers a_1, a_2, ..., a_n (1 ≀ a_j ≀ 10^4) β€” lengths of the sticks in the i-th list. It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle. The total number of sticks in all T lists doesn't exceed 10^6 in each testcase. Output Print T lines. The i-th line should contain the answer to the i-th list of the input. That is the lengths of the four sticks you choose from the i-th list, so that they form a rectangle and the value (P^2)/(S) of this rectangle is minimal possible. You can print these four lengths in arbitrary order. If there are multiple answers, print any of them. Example Input 3 4 7 2 2 7 8 2 8 1 4 8 2 1 5 5 5 5 5 5 5 Output 2 7 7 2 2 2 1 1 5 5 5 5 Note There is only one way to choose four sticks in the first list, they form a rectangle with sides 2 and 7, its area is 2 β‹… 7 = 14, perimeter is 2(2 + 7) = 18. (18^2)/(14) β‰ˆ 23.143. The second list contains subsets of four sticks that can form rectangles with sides (1, 2), (2, 8) and (1, 8). Their values are (6^2)/(2) = 18, (20^2)/(16) = 25 and (18^2)/(8) = 40.5, respectively. The minimal one of them is the rectangle (1, 2). You can choose any four of the 5 given sticks from the third list, they will form a square with side 5, which is still a rectangle with sides (5, 5). Tags: greedy Correct Solution: ``` import sys read = sys.stdin.buffer.read input = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines t = int(input()) for case in range(t): n = int(input()) a = list(map(int, input().split())) a.sort() tmp = 10 ** 4 # INF ans = 10 ** 9 i = 0 rec = (0, 0) break_bit = 0 while i < n - 1: # γƒšγ‚’γ‚’ζŽ’γ™ cnt = 2 if a[i] == a[i + 1]: if ans > a[i] / tmp + tmp / a[i]: rec = (tmp, a[i]) ans = a[i] / tmp + tmp / a[i] while i + 2 < n and a[i + 1] == a[i + 2]: cnt += 1 i += 1 # print(i, cnt) if cnt == 4: rec = (a[i], a[i]) # print(rec) break_bit = 1 break tmp = a[i] if break_bit == 1: break i += 1 print(rec[0], rec[0], rec[1], rec[1]) ```
3,345
Provide tags and a correct Python 3 solution for this coding contest problem. You have n sticks of the given lengths. Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks. Let S be the area of the rectangle and P be the perimeter of the rectangle. The chosen rectangle should have the value (P^2)/(S) minimal possible. The value is taken without any rounding. If there are multiple answers, print any of them. Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately. Input The first line contains a single integer T (T β‰₯ 1) β€” the number of lists of sticks in the testcase. Then 2T lines follow β€” lines (2i - 1) and 2i of them describe the i-th list. The first line of the pair contains a single integer n (4 ≀ n ≀ 10^6) β€” the number of sticks in the i-th list. The second line of the pair contains n integers a_1, a_2, ..., a_n (1 ≀ a_j ≀ 10^4) β€” lengths of the sticks in the i-th list. It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle. The total number of sticks in all T lists doesn't exceed 10^6 in each testcase. Output Print T lines. The i-th line should contain the answer to the i-th list of the input. That is the lengths of the four sticks you choose from the i-th list, so that they form a rectangle and the value (P^2)/(S) of this rectangle is minimal possible. You can print these four lengths in arbitrary order. If there are multiple answers, print any of them. Example Input 3 4 7 2 2 7 8 2 8 1 4 8 2 1 5 5 5 5 5 5 5 Output 2 7 7 2 2 2 1 1 5 5 5 5 Note There is only one way to choose four sticks in the first list, they form a rectangle with sides 2 and 7, its area is 2 β‹… 7 = 14, perimeter is 2(2 + 7) = 18. (18^2)/(14) β‰ˆ 23.143. The second list contains subsets of four sticks that can form rectangles with sides (1, 2), (2, 8) and (1, 8). Their values are (6^2)/(2) = 18, (20^2)/(16) = 25 and (18^2)/(8) = 40.5, respectively. The minimal one of them is the rectangle (1, 2). You can choose any four of the 5 given sticks from the third list, they will form a square with side 5, which is still a rectangle with sides (5, 5). Tags: greedy Correct Solution: ``` ans=[] def main(): t=int(input()) for l in range(t): n=int(input()) if n==4: ans.append(input()) else: b=y=num=x=0 d=10**10 for i in sorted(map(int,input().split())): if num==i: c+=1 if c==2: a=b b=i if a!=0 and (a/b+b/a)<d: d=(a/b+b/a) x=a y=b elif c==4: x=y=i break else: num=i c=1 ans.append(str(x)+' '+str(y)+' '+str(x)+' '+str(y)) #print(ans) return ans print('\n'.join(main())) ```
3,346
Provide tags and a correct Python 3 solution for this coding contest problem. You have n sticks of the given lengths. Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks. Let S be the area of the rectangle and P be the perimeter of the rectangle. The chosen rectangle should have the value (P^2)/(S) minimal possible. The value is taken without any rounding. If there are multiple answers, print any of them. Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately. Input The first line contains a single integer T (T β‰₯ 1) β€” the number of lists of sticks in the testcase. Then 2T lines follow β€” lines (2i - 1) and 2i of them describe the i-th list. The first line of the pair contains a single integer n (4 ≀ n ≀ 10^6) β€” the number of sticks in the i-th list. The second line of the pair contains n integers a_1, a_2, ..., a_n (1 ≀ a_j ≀ 10^4) β€” lengths of the sticks in the i-th list. It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle. The total number of sticks in all T lists doesn't exceed 10^6 in each testcase. Output Print T lines. The i-th line should contain the answer to the i-th list of the input. That is the lengths of the four sticks you choose from the i-th list, so that they form a rectangle and the value (P^2)/(S) of this rectangle is minimal possible. You can print these four lengths in arbitrary order. If there are multiple answers, print any of them. Example Input 3 4 7 2 2 7 8 2 8 1 4 8 2 1 5 5 5 5 5 5 5 Output 2 7 7 2 2 2 1 1 5 5 5 5 Note There is only one way to choose four sticks in the first list, they form a rectangle with sides 2 and 7, its area is 2 β‹… 7 = 14, perimeter is 2(2 + 7) = 18. (18^2)/(14) β‰ˆ 23.143. The second list contains subsets of four sticks that can form rectangles with sides (1, 2), (2, 8) and (1, 8). Their values are (6^2)/(2) = 18, (20^2)/(16) = 25 and (18^2)/(8) = 40.5, respectively. The minimal one of them is the rectangle (1, 2). You can choose any four of the 5 given sticks from the third list, they will form a square with side 5, which is still a rectangle with sides (5, 5). Tags: greedy Correct Solution: ``` ###### ### ####### ####### ## # ##### ### ##### # # # # # # # # # # # # # ### # # # # # # # # # # # # # ### ###### ######### # # # # # # ######### # ###### ######### # # # # # # ######### # # # # # # # # # # # #### # # # # # # # # # # ## # # # # # ###### # # ####### ####### # # ##### # # # # from __future__ import print_function # for PyPy2 from itertools import permutations as perm # from fractions import Fraction from collections import * from sys import stdin from bisect import * from heapq import * from math import * g = lambda : stdin.readline().strip() gl = lambda : g().split() gil = lambda : [int(var) for var in gl()] gfl = lambda : [float(var) for var in gl()] gcl = lambda : list(g()) gbs = lambda : [int(var) for var in g()] mod = int(1e9)+7 inf = float("inf") t, = gil() for _ in range(t): n, = gil() a = gil() f = Counter(a) a = [] ai, bi = 1, 1 ans = inf for v in f: fi = f[v] if fi >= 2: a.append(v) if fi >= 4: ai, bi, ans = v, v, 1 break if ans != 1: a.sort() for i in range(1, len(a)): if a[i]/a[i-1] < ans: ai, bi, ans = a[i], a[i-1], a[i]/a[i-1] print(ai, ai, bi, bi) ```
3,347
Provide tags and a correct Python 3 solution for this coding contest problem. You have n sticks of the given lengths. Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks. Let S be the area of the rectangle and P be the perimeter of the rectangle. The chosen rectangle should have the value (P^2)/(S) minimal possible. The value is taken without any rounding. If there are multiple answers, print any of them. Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately. Input The first line contains a single integer T (T β‰₯ 1) β€” the number of lists of sticks in the testcase. Then 2T lines follow β€” lines (2i - 1) and 2i of them describe the i-th list. The first line of the pair contains a single integer n (4 ≀ n ≀ 10^6) β€” the number of sticks in the i-th list. The second line of the pair contains n integers a_1, a_2, ..., a_n (1 ≀ a_j ≀ 10^4) β€” lengths of the sticks in the i-th list. It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle. The total number of sticks in all T lists doesn't exceed 10^6 in each testcase. Output Print T lines. The i-th line should contain the answer to the i-th list of the input. That is the lengths of the four sticks you choose from the i-th list, so that they form a rectangle and the value (P^2)/(S) of this rectangle is minimal possible. You can print these four lengths in arbitrary order. If there are multiple answers, print any of them. Example Input 3 4 7 2 2 7 8 2 8 1 4 8 2 1 5 5 5 5 5 5 5 Output 2 7 7 2 2 2 1 1 5 5 5 5 Note There is only one way to choose four sticks in the first list, they form a rectangle with sides 2 and 7, its area is 2 β‹… 7 = 14, perimeter is 2(2 + 7) = 18. (18^2)/(14) β‰ˆ 23.143. The second list contains subsets of four sticks that can form rectangles with sides (1, 2), (2, 8) and (1, 8). Their values are (6^2)/(2) = 18, (20^2)/(16) = 25 and (18^2)/(8) = 40.5, respectively. The minimal one of them is the rectangle (1, 2). You can choose any four of the 5 given sticks from the third list, they will form a square with side 5, which is still a rectangle with sides (5, 5). Tags: greedy Correct Solution: ``` from sys import stdout, stdin def read(): return stdin.readline().rstrip('\n') def f(a, b): return a / b + b / a results = [] for _ in range(int(read())): read() arr = sorted(map(int, read().split())) i = 0 len_arr_minus_one = len(arr) - 1 prev_el, next_el = None, None min_sticks_el = None min_sticks = None while i < len_arr_minus_one: if arr[i] == arr[i + 1]: prev_el, next_el = next_el, arr[i] i += 2 if prev_el and next_el: if not min_sticks_el: min_sticks_el = (prev_el, next_el) min_sticks = f(prev_el, next_el) continue current_value = f(prev_el, next_el) if min_sticks > current_value: min_sticks = current_value min_sticks_el = (prev_el, next_el) else: i += 1 results.append("{0} {0} {1} {1}".format(min_sticks_el[0], min_sticks_el[1])) stdout.write('\n'.join(results) + '\n') ```
3,348
Provide tags and a correct Python 3 solution for this coding contest problem. You have n sticks of the given lengths. Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks. Let S be the area of the rectangle and P be the perimeter of the rectangle. The chosen rectangle should have the value (P^2)/(S) minimal possible. The value is taken without any rounding. If there are multiple answers, print any of them. Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately. Input The first line contains a single integer T (T β‰₯ 1) β€” the number of lists of sticks in the testcase. Then 2T lines follow β€” lines (2i - 1) and 2i of them describe the i-th list. The first line of the pair contains a single integer n (4 ≀ n ≀ 10^6) β€” the number of sticks in the i-th list. The second line of the pair contains n integers a_1, a_2, ..., a_n (1 ≀ a_j ≀ 10^4) β€” lengths of the sticks in the i-th list. It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle. The total number of sticks in all T lists doesn't exceed 10^6 in each testcase. Output Print T lines. The i-th line should contain the answer to the i-th list of the input. That is the lengths of the four sticks you choose from the i-th list, so that they form a rectangle and the value (P^2)/(S) of this rectangle is minimal possible. You can print these four lengths in arbitrary order. If there are multiple answers, print any of them. Example Input 3 4 7 2 2 7 8 2 8 1 4 8 2 1 5 5 5 5 5 5 5 Output 2 7 7 2 2 2 1 1 5 5 5 5 Note There is only one way to choose four sticks in the first list, they form a rectangle with sides 2 and 7, its area is 2 β‹… 7 = 14, perimeter is 2(2 + 7) = 18. (18^2)/(14) β‰ˆ 23.143. The second list contains subsets of four sticks that can form rectangles with sides (1, 2), (2, 8) and (1, 8). Their values are (6^2)/(2) = 18, (20^2)/(16) = 25 and (18^2)/(8) = 40.5, respectively. The minimal one of them is the rectangle (1, 2). You can choose any four of the 5 given sticks from the third list, they will form a square with side 5, which is still a rectangle with sides (5, 5). Tags: greedy Correct Solution: ``` from sys import stdout, stdin import collections def read(): return stdin.readline().rstrip('\n') def read_array(sep=None, maxsplit=-1): return read().split(sep, maxsplit) def read_int(): return int(read()) def read_int_array(sep=None, maxsplit=-1): return [int(a) for a in read_array(sep, maxsplit)] def write(*args, **kwargs): sep = kwargs.get('sep', ' ') end = kwargs.get('end', '\n') stdout.write(sep.join(str(a) for a in args) + end) def write_array(array, **kwargs): sep = kwargs.get('sep', ' ') end = kwargs.get('end', '\n') stdout.write(sep.join(str(a) for a in array) + end) def f(a, b): return a / b + b / a n = read_int() results = [] for _ in range(n): read_int() arr = collections.Counter(read_int_array(sep=' ')) prev_el, next_el = None, None min_sticks_el = None min_sticks = None keys = sorted(arr.keys()) for k in keys: if arr[k] > 4: arr[k] = 4 while arr[k] > 1: arr[k] -= 2 prev_el, next_el = next_el, k if prev_el and next_el: if not min_sticks_el: min_sticks_el = (prev_el, next_el) min_sticks = f(prev_el, next_el) continue current_value = f(prev_el, next_el) if min_sticks > current_value: min_sticks = current_value min_sticks_el = (prev_el, next_el) results.append("{0} {0} {1} {1}".format(min_sticks_el[0], min_sticks_el[1])) print('\n'.join(results)) ```
3,349
Provide tags and a correct Python 3 solution for this coding contest problem. You have n sticks of the given lengths. Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks. Let S be the area of the rectangle and P be the perimeter of the rectangle. The chosen rectangle should have the value (P^2)/(S) minimal possible. The value is taken without any rounding. If there are multiple answers, print any of them. Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately. Input The first line contains a single integer T (T β‰₯ 1) β€” the number of lists of sticks in the testcase. Then 2T lines follow β€” lines (2i - 1) and 2i of them describe the i-th list. The first line of the pair contains a single integer n (4 ≀ n ≀ 10^6) β€” the number of sticks in the i-th list. The second line of the pair contains n integers a_1, a_2, ..., a_n (1 ≀ a_j ≀ 10^4) β€” lengths of the sticks in the i-th list. It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle. The total number of sticks in all T lists doesn't exceed 10^6 in each testcase. Output Print T lines. The i-th line should contain the answer to the i-th list of the input. That is the lengths of the four sticks you choose from the i-th list, so that they form a rectangle and the value (P^2)/(S) of this rectangle is minimal possible. You can print these four lengths in arbitrary order. If there are multiple answers, print any of them. Example Input 3 4 7 2 2 7 8 2 8 1 4 8 2 1 5 5 5 5 5 5 5 Output 2 7 7 2 2 2 1 1 5 5 5 5 Note There is only one way to choose four sticks in the first list, they form a rectangle with sides 2 and 7, its area is 2 β‹… 7 = 14, perimeter is 2(2 + 7) = 18. (18^2)/(14) β‰ˆ 23.143. The second list contains subsets of four sticks that can form rectangles with sides (1, 2), (2, 8) and (1, 8). Their values are (6^2)/(2) = 18, (20^2)/(16) = 25 and (18^2)/(8) = 40.5, respectively. The minimal one of them is the rectangle (1, 2). You can choose any four of the 5 given sticks from the third list, they will form a square with side 5, which is still a rectangle with sides (5, 5). Tags: greedy Correct Solution: ``` import sys from collections import * l=sys.stdin.readlines()[2::2] r=[] for a in l: a=Counter(map(int,a.split())) s=sorted([k for k in a if a[k]>1]+[k for k in a if a[k]>3]) r+=['%d %d '%min(zip(s,s[1:]),key=lambda a:sum(a)**2/a[0]/a[1])*2] print(*r) ```
3,350
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have n sticks of the given lengths. Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks. Let S be the area of the rectangle and P be the perimeter of the rectangle. The chosen rectangle should have the value (P^2)/(S) minimal possible. The value is taken without any rounding. If there are multiple answers, print any of them. Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately. Input The first line contains a single integer T (T β‰₯ 1) β€” the number of lists of sticks in the testcase. Then 2T lines follow β€” lines (2i - 1) and 2i of them describe the i-th list. The first line of the pair contains a single integer n (4 ≀ n ≀ 10^6) β€” the number of sticks in the i-th list. The second line of the pair contains n integers a_1, a_2, ..., a_n (1 ≀ a_j ≀ 10^4) β€” lengths of the sticks in the i-th list. It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle. The total number of sticks in all T lists doesn't exceed 10^6 in each testcase. Output Print T lines. The i-th line should contain the answer to the i-th list of the input. That is the lengths of the four sticks you choose from the i-th list, so that they form a rectangle and the value (P^2)/(S) of this rectangle is minimal possible. You can print these four lengths in arbitrary order. If there are multiple answers, print any of them. Example Input 3 4 7 2 2 7 8 2 8 1 4 8 2 1 5 5 5 5 5 5 5 Output 2 7 7 2 2 2 1 1 5 5 5 5 Note There is only one way to choose four sticks in the first list, they form a rectangle with sides 2 and 7, its area is 2 β‹… 7 = 14, perimeter is 2(2 + 7) = 18. (18^2)/(14) β‰ˆ 23.143. The second list contains subsets of four sticks that can form rectangles with sides (1, 2), (2, 8) and (1, 8). Their values are (6^2)/(2) = 18, (20^2)/(16) = 25 and (18^2)/(8) = 40.5, respectively. The minimal one of them is the rectangle (1, 2). You can choose any four of the 5 given sticks from the third list, they will form a square with side 5, which is still a rectangle with sides (5, 5). Submitted Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ####################################### from collections import defaultdict as dd for t in range(int(input())): n=int(input()) l=list(map(int,input().split())) l1=dd(int) a=0 for j in l: l1[j]+=1 if l1[j]==4: a=j if a: print(a,a,a,a) else: c=0 x=0 l2=[] for j in l1: if l1[j]>=2: l2.append(j) l2.sort() for j in l2: c+=1 if c==1: a=j elif c==2: b=j else: if x/j+j/x<a/b+b/a: a,b=x,j x=j print(a,a,b,b) ``` Yes
3,351
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have n sticks of the given lengths. Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks. Let S be the area of the rectangle and P be the perimeter of the rectangle. The chosen rectangle should have the value (P^2)/(S) minimal possible. The value is taken without any rounding. If there are multiple answers, print any of them. Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately. Input The first line contains a single integer T (T β‰₯ 1) β€” the number of lists of sticks in the testcase. Then 2T lines follow β€” lines (2i - 1) and 2i of them describe the i-th list. The first line of the pair contains a single integer n (4 ≀ n ≀ 10^6) β€” the number of sticks in the i-th list. The second line of the pair contains n integers a_1, a_2, ..., a_n (1 ≀ a_j ≀ 10^4) β€” lengths of the sticks in the i-th list. It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle. The total number of sticks in all T lists doesn't exceed 10^6 in each testcase. Output Print T lines. The i-th line should contain the answer to the i-th list of the input. That is the lengths of the four sticks you choose from the i-th list, so that they form a rectangle and the value (P^2)/(S) of this rectangle is minimal possible. You can print these four lengths in arbitrary order. If there are multiple answers, print any of them. Example Input 3 4 7 2 2 7 8 2 8 1 4 8 2 1 5 5 5 5 5 5 5 Output 2 7 7 2 2 2 1 1 5 5 5 5 Note There is only one way to choose four sticks in the first list, they form a rectangle with sides 2 and 7, its area is 2 β‹… 7 = 14, perimeter is 2(2 + 7) = 18. (18^2)/(14) β‰ˆ 23.143. The second list contains subsets of four sticks that can form rectangles with sides (1, 2), (2, 8) and (1, 8). Their values are (6^2)/(2) = 18, (20^2)/(16) = 25 and (18^2)/(8) = 40.5, respectively. The minimal one of them is the rectangle (1, 2). You can choose any four of the 5 given sticks from the third list, they will form a square with side 5, which is still a rectangle with sides (5, 5). Submitted Solution: ``` #by Nick "LordVader" Proshin import sys input = sys.stdin.readline out = sys.stdout t = int(input()) for i in range(t): n = int(input()) a = list(map(int, input().split())) if len(set(a)) == 1: print(a[0],a[0],a[0],a[0]) else: a.sort() g1 = False d = {} mx = 10001 for i in a: if i not in d.keys(): d[i] = 1 else: d[i] += 1 if d[i] == 4: g1 = True if i < mx: mx = i if g1: out.write(str(mx)+" "+str(mx)+" "+str(mx)+" "+str(mx)+"\n") else: res = [] for k in d.keys(): if d[k] >= 2: res.append(k) m = len(res) minj = 0 for j in range(m - 1): if res[j]*res[j+1]*(res[minj]**2 + res[minj+1]**2) > res[minj]*res[minj+1]*(res[j]**2+res[j+1]**2): minj = j out.write(str(res[minj])+" "+str(res[minj])+" "+str(res[minj+1])+" "+str(res[minj+1])+"\n") ``` Yes
3,352
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have n sticks of the given lengths. Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks. Let S be the area of the rectangle and P be the perimeter of the rectangle. The chosen rectangle should have the value (P^2)/(S) minimal possible. The value is taken without any rounding. If there are multiple answers, print any of them. Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately. Input The first line contains a single integer T (T β‰₯ 1) β€” the number of lists of sticks in the testcase. Then 2T lines follow β€” lines (2i - 1) and 2i of them describe the i-th list. The first line of the pair contains a single integer n (4 ≀ n ≀ 10^6) β€” the number of sticks in the i-th list. The second line of the pair contains n integers a_1, a_2, ..., a_n (1 ≀ a_j ≀ 10^4) β€” lengths of the sticks in the i-th list. It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle. The total number of sticks in all T lists doesn't exceed 10^6 in each testcase. Output Print T lines. The i-th line should contain the answer to the i-th list of the input. That is the lengths of the four sticks you choose from the i-th list, so that they form a rectangle and the value (P^2)/(S) of this rectangle is minimal possible. You can print these four lengths in arbitrary order. If there are multiple answers, print any of them. Example Input 3 4 7 2 2 7 8 2 8 1 4 8 2 1 5 5 5 5 5 5 5 Output 2 7 7 2 2 2 1 1 5 5 5 5 Note There is only one way to choose four sticks in the first list, they form a rectangle with sides 2 and 7, its area is 2 β‹… 7 = 14, perimeter is 2(2 + 7) = 18. (18^2)/(14) β‰ˆ 23.143. The second list contains subsets of four sticks that can form rectangles with sides (1, 2), (2, 8) and (1, 8). Their values are (6^2)/(2) = 18, (20^2)/(16) = 25 and (18^2)/(8) = 40.5, respectively. The minimal one of them is the rectangle (1, 2). You can choose any four of the 5 given sticks from the third list, they will form a square with side 5, which is still a rectangle with sides (5, 5). Submitted Solution: ``` from sys import stdin def main(): input() l = stdin.read().splitlines()[1::2] for i, s in enumerate(l): cnt, x, n = [], 0., 0 for y in sorted(map(float, s.split())): if x == y: n += 1 else: if n: cnt.append((x, n)) x, n = y, 0 if n: cnt.append((y, n)) x = t = 0. for y, n in cnt: if n > 2: u = v = y break else: z = x / y if t < z: t, u, v = z, x, y x = y l[i] = '%d %d %d %d' % (u, u, v, v) print('\n'.join(l)) if __name__ == '__main__': main() # Made By Mostafa_Khaled ``` Yes
3,353
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have n sticks of the given lengths. Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks. Let S be the area of the rectangle and P be the perimeter of the rectangle. The chosen rectangle should have the value (P^2)/(S) minimal possible. The value is taken without any rounding. If there are multiple answers, print any of them. Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately. Input The first line contains a single integer T (T β‰₯ 1) β€” the number of lists of sticks in the testcase. Then 2T lines follow β€” lines (2i - 1) and 2i of them describe the i-th list. The first line of the pair contains a single integer n (4 ≀ n ≀ 10^6) β€” the number of sticks in the i-th list. The second line of the pair contains n integers a_1, a_2, ..., a_n (1 ≀ a_j ≀ 10^4) β€” lengths of the sticks in the i-th list. It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle. The total number of sticks in all T lists doesn't exceed 10^6 in each testcase. Output Print T lines. The i-th line should contain the answer to the i-th list of the input. That is the lengths of the four sticks you choose from the i-th list, so that they form a rectangle and the value (P^2)/(S) of this rectangle is minimal possible. You can print these four lengths in arbitrary order. If there are multiple answers, print any of them. Example Input 3 4 7 2 2 7 8 2 8 1 4 8 2 1 5 5 5 5 5 5 5 Output 2 7 7 2 2 2 1 1 5 5 5 5 Note There is only one way to choose four sticks in the first list, they form a rectangle with sides 2 and 7, its area is 2 β‹… 7 = 14, perimeter is 2(2 + 7) = 18. (18^2)/(14) β‰ˆ 23.143. The second list contains subsets of four sticks that can form rectangles with sides (1, 2), (2, 8) and (1, 8). Their values are (6^2)/(2) = 18, (20^2)/(16) = 25 and (18^2)/(8) = 40.5, respectively. The minimal one of them is the rectangle (1, 2). You can choose any four of the 5 given sticks from the third list, they will form a square with side 5, which is still a rectangle with sides (5, 5). Submitted Solution: ``` import sys from collections import * l=sys.stdin.readlines()[2::2] r=[] for a in l: a=Counter(map(int,a.split())) s=sorted([k for k in a if a[k]>1]+[k for k in a if a[k]>3]) a=min(zip(s,s[1:]),key=lambda a:sum(a)**2/a[0]/a[1]) r+=['%d %d '%a*2] print('\n'.join(r)) ``` Yes
3,354
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have n sticks of the given lengths. Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks. Let S be the area of the rectangle and P be the perimeter of the rectangle. The chosen rectangle should have the value (P^2)/(S) minimal possible. The value is taken without any rounding. If there are multiple answers, print any of them. Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately. Input The first line contains a single integer T (T β‰₯ 1) β€” the number of lists of sticks in the testcase. Then 2T lines follow β€” lines (2i - 1) and 2i of them describe the i-th list. The first line of the pair contains a single integer n (4 ≀ n ≀ 10^6) β€” the number of sticks in the i-th list. The second line of the pair contains n integers a_1, a_2, ..., a_n (1 ≀ a_j ≀ 10^4) β€” lengths of the sticks in the i-th list. It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle. The total number of sticks in all T lists doesn't exceed 10^6 in each testcase. Output Print T lines. The i-th line should contain the answer to the i-th list of the input. That is the lengths of the four sticks you choose from the i-th list, so that they form a rectangle and the value (P^2)/(S) of this rectangle is minimal possible. You can print these four lengths in arbitrary order. If there are multiple answers, print any of them. Example Input 3 4 7 2 2 7 8 2 8 1 4 8 2 1 5 5 5 5 5 5 5 Output 2 7 7 2 2 2 1 1 5 5 5 5 Note There is only one way to choose four sticks in the first list, they form a rectangle with sides 2 and 7, its area is 2 β‹… 7 = 14, perimeter is 2(2 + 7) = 18. (18^2)/(14) β‰ˆ 23.143. The second list contains subsets of four sticks that can form rectangles with sides (1, 2), (2, 8) and (1, 8). Their values are (6^2)/(2) = 18, (20^2)/(16) = 25 and (18^2)/(8) = 40.5, respectively. The minimal one of them is the rectangle (1, 2). You can choose any four of the 5 given sticks from the third list, they will form a square with side 5, which is still a rectangle with sides (5, 5). Submitted Solution: ``` from sys import stdin from collections import Counter def main(): input() l = stdin.read().splitlines()[1::2] for i, s in enumerate(l): cnt = Counter(s.split()) s = cnt.most_common(1)[0] if cnt[s] > 3: l[i] = '%s %s %s %s' % (s, s, s, s) continue x = t = 0. for y in sorted(float(s) for s, v in cnt.items() if v > 1): z = x / y if t < z: t, u, v = z, x, y x = y l[i] = '%d %d %d %d' % (u, u, v, v) print('\n'.join(l)) if __name__ == '__main__': main() ``` No
3,355
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have n sticks of the given lengths. Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks. Let S be the area of the rectangle and P be the perimeter of the rectangle. The chosen rectangle should have the value (P^2)/(S) minimal possible. The value is taken without any rounding. If there are multiple answers, print any of them. Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately. Input The first line contains a single integer T (T β‰₯ 1) β€” the number of lists of sticks in the testcase. Then 2T lines follow β€” lines (2i - 1) and 2i of them describe the i-th list. The first line of the pair contains a single integer n (4 ≀ n ≀ 10^6) β€” the number of sticks in the i-th list. The second line of the pair contains n integers a_1, a_2, ..., a_n (1 ≀ a_j ≀ 10^4) β€” lengths of the sticks in the i-th list. It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle. The total number of sticks in all T lists doesn't exceed 10^6 in each testcase. Output Print T lines. The i-th line should contain the answer to the i-th list of the input. That is the lengths of the four sticks you choose from the i-th list, so that they form a rectangle and the value (P^2)/(S) of this rectangle is minimal possible. You can print these four lengths in arbitrary order. If there are multiple answers, print any of them. Example Input 3 4 7 2 2 7 8 2 8 1 4 8 2 1 5 5 5 5 5 5 5 Output 2 7 7 2 2 2 1 1 5 5 5 5 Note There is only one way to choose four sticks in the first list, they form a rectangle with sides 2 and 7, its area is 2 β‹… 7 = 14, perimeter is 2(2 + 7) = 18. (18^2)/(14) β‰ˆ 23.143. The second list contains subsets of four sticks that can form rectangles with sides (1, 2), (2, 8) and (1, 8). Their values are (6^2)/(2) = 18, (20^2)/(16) = 25 and (18^2)/(8) = 40.5, respectively. The minimal one of them is the rectangle (1, 2). You can choose any four of the 5 given sticks from the third list, they will form a square with side 5, which is still a rectangle with sides (5, 5). Submitted Solution: ``` from decimal import Decimal, getcontext getcontext().prec = 20 for i in range(int(input())): n = int(input()) *a, = map(int, input().split()) b = [0] * (10 ** 4 + 1) w = [] d = 10 ** 5 ans = [] for j in a: b[j] += 1 if b[j] == 2: w.append(j) elif b[j] == 4: print(j, j, j, j) exit(0) w.sort() for j in range(len(w) - 1): if Decimal(w[j + 1]) / Decimal(w[j]) < d: d = Decimal(w[j + 1]) / Decimal(w[j]) ans = [w[j], w[j + 1]] print(ans[0], ans[0], ans[1], ans[1]) ``` No
3,356
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have n sticks of the given lengths. Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks. Let S be the area of the rectangle and P be the perimeter of the rectangle. The chosen rectangle should have the value (P^2)/(S) minimal possible. The value is taken without any rounding. If there are multiple answers, print any of them. Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately. Input The first line contains a single integer T (T β‰₯ 1) β€” the number of lists of sticks in the testcase. Then 2T lines follow β€” lines (2i - 1) and 2i of them describe the i-th list. The first line of the pair contains a single integer n (4 ≀ n ≀ 10^6) β€” the number of sticks in the i-th list. The second line of the pair contains n integers a_1, a_2, ..., a_n (1 ≀ a_j ≀ 10^4) β€” lengths of the sticks in the i-th list. It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle. The total number of sticks in all T lists doesn't exceed 10^6 in each testcase. Output Print T lines. The i-th line should contain the answer to the i-th list of the input. That is the lengths of the four sticks you choose from the i-th list, so that they form a rectangle and the value (P^2)/(S) of this rectangle is minimal possible. You can print these four lengths in arbitrary order. If there are multiple answers, print any of them. Example Input 3 4 7 2 2 7 8 2 8 1 4 8 2 1 5 5 5 5 5 5 5 Output 2 7 7 2 2 2 1 1 5 5 5 5 Note There is only one way to choose four sticks in the first list, they form a rectangle with sides 2 and 7, its area is 2 β‹… 7 = 14, perimeter is 2(2 + 7) = 18. (18^2)/(14) β‰ˆ 23.143. The second list contains subsets of four sticks that can form rectangles with sides (1, 2), (2, 8) and (1, 8). Their values are (6^2)/(2) = 18, (20^2)/(16) = 25 and (18^2)/(8) = 40.5, respectively. The minimal one of them is the rectangle (1, 2). You can choose any four of the 5 given sticks from the third list, they will form a square with side 5, which is still a rectangle with sides (5, 5). Submitted Solution: ``` for _ in range(int(input())): n = int(input()) A = list(map(int,input().split())) cnt = [0 for i in range(max(A)+1)] for i in A: cnt[i]+=1 C = set(A) B = [] for i in C: if(cnt[i]>=2): B.append(i) B.sort() ans = 1e10 for i in range(1,len(B)): d = B[i]/B[i-1] if(d<ans): ans = d a = B[i] b = B[i-1] print(a,a,b,b) ``` No
3,357
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have n sticks of the given lengths. Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks. Let S be the area of the rectangle and P be the perimeter of the rectangle. The chosen rectangle should have the value (P^2)/(S) minimal possible. The value is taken without any rounding. If there are multiple answers, print any of them. Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately. Input The first line contains a single integer T (T β‰₯ 1) β€” the number of lists of sticks in the testcase. Then 2T lines follow β€” lines (2i - 1) and 2i of them describe the i-th list. The first line of the pair contains a single integer n (4 ≀ n ≀ 10^6) β€” the number of sticks in the i-th list. The second line of the pair contains n integers a_1, a_2, ..., a_n (1 ≀ a_j ≀ 10^4) β€” lengths of the sticks in the i-th list. It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle. The total number of sticks in all T lists doesn't exceed 10^6 in each testcase. Output Print T lines. The i-th line should contain the answer to the i-th list of the input. That is the lengths of the four sticks you choose from the i-th list, so that they form a rectangle and the value (P^2)/(S) of this rectangle is minimal possible. You can print these four lengths in arbitrary order. If there are multiple answers, print any of them. Example Input 3 4 7 2 2 7 8 2 8 1 4 8 2 1 5 5 5 5 5 5 5 Output 2 7 7 2 2 2 1 1 5 5 5 5 Note There is only one way to choose four sticks in the first list, they form a rectangle with sides 2 and 7, its area is 2 β‹… 7 = 14, perimeter is 2(2 + 7) = 18. (18^2)/(14) β‰ˆ 23.143. The second list contains subsets of four sticks that can form rectangles with sides (1, 2), (2, 8) and (1, 8). Their values are (6^2)/(2) = 18, (20^2)/(16) = 25 and (18^2)/(8) = 40.5, respectively. The minimal one of them is the rectangle (1, 2). You can choose any four of the 5 given sticks from the third list, they will form a square with side 5, which is still a rectangle with sides (5, 5). Submitted Solution: ``` n = int(input()) for i in range(n): input() l = sorted([int(x) for x in input().split()]) r = [] while len(l) > 0 and len(r) < 4: if l[0] == l[1]: r.append(l[0]) r.append(l[1]) l = l[2:] else: l = l[1:] print(r) ``` No
3,358
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In an unspecified solar system, there are N planets. A space government company has recently hired space contractors to build M bidirectional Hyperspaceβ„’ highways, each connecting two different planets. The primary objective, which was to make sure that every planet can be reached from any other planet taking only Hyperspaceβ„’ highways, has been completely fulfilled. Unfortunately, lots of space contractors had friends and cousins in the Space Board of Directors of the company, so the company decided to do much more than just connecting all planets. In order to make spending enormous amounts of space money for Hyperspaceβ„’ highways look neccessary, they decided to enforce a strict rule on the Hyperspaceβ„’ highway network: whenever there is a way to travel through some planets and return to the starting point without travelling through any planet twice, every pair of planets on the itinerary should be directly connected by a Hyperspaceβ„’ highway. In other words, the set of planets in every simple cycle induces a complete subgraph. You are designing a Hyperspaceβ„’ navigational app, and the key technical problem you are facing is finding the minimal number of Hyperspaceβ„’ highways one needs to use to travel from planet A to planet B. As this problem is too easy for Bubble Cup, here is a harder task: your program needs to do it for Q pairs of planets. Input The first line contains three positive integers N (1≀ N≀ 100 000), M (1≀ M≀ 500 000) and Q (1≀ Q≀ 200 000), denoting the number of planets, the number of Hyperspaceβ„’ highways, and the number of queries, respectively. Each of the following M lines contains a highway: highway i is given by two integers u_i and v_i (1 ≀ u_i < v_i ≀ N), meaning the planets u_i and v_i are connected by a Hyperspaceβ„’ highway. It is guaranteed that the network of planets and Hyperspaceβ„’ highways forms a simple connected graph. Each of the following Q lines contains a query: query j is given by two integers a_j and b_j (1 ≀ a_j < b_j ≀ N ), meaning we are interested in the minimal number of Hyperspaceβ„’ highways one needs to take to travel from planet a_j to planet b_j. Output Output Q lines: the j-th line of output should contain the minimal number of Hyperspaceβ„’ highways one needs to take to travel from planet a_j to planet b_j. Examples Input 5 7 2 1 2 1 3 1 4 2 3 2 4 3 4 1 5 1 4 2 5 Output 1 2 Input 8 11 4 1 2 2 3 3 4 4 5 1 3 1 6 3 5 3 7 4 7 5 7 6 8 1 5 2 4 6 7 3 8 Output 2 2 3 3 Note The graph from the second sample: <image> Submitted Solution: ``` N = 301000 n = 0 m = 0 q = 0 cnt = [0]*1 Num = [0] * N Up = [0] * N chk = [0] * N ppp = [0] * N par = [[0] * 20 for i in range(N)] Dep = [0] * N T = [None] * N G = [None] * N E = [None] * N def main(): n,m,q = map(int,input().split()) #E = [None] * (n+1) print(n) for i in range(1,m+1): u,v = map(int,input().split()) if E[u] is None: E[u] = [] if E[v] is None: E[v] = [] E[u].append(v) E[v].append(u) result = [] DFS(1,0,E) cnt = [0]*1 BuildTree(1,0) FindDepth(1,0) while q > 0: a,b = map(int,input().split()) result.append(int((Dep[a] + Dep[b] - Dep[LCA(a,b)]*2)/2)) #print(result) q-= 1 for r in result: print(r) def DFS(a,pp,E): cnt[0] = cnt[0]+1 Num[a] = cnt[0] ppp[a] = pp r = Num[a] for v in E[a]: if Num[v]!=0: r = min(r,Num[v]) continue if T[a] is None: T[a] = [] T[a].append(v) DFS(v,a,E) if Up[v] >= Num[a]: chk[v]=1 r = min(r,Up[v]) Up[a] = r def AddEdge(a,b): if G[a] is None: G[a] = [] if G[b] is None: G[b] = [] G[a].append(b) G[b].append(a) def BuildTree(a,c): if c != 0: AddEdge(n+c,a) if T[a] is None: T[a] = [] for v in T[a]: if chk[v] !=0: cnt[0] = cnt[0]+1 AddEdge(n + cnt[0],a) BuildTree(v,cnt[0]) else: BuildTree(v,c) def FindDepth(a,pp): par[a][0] = pp for i in range(0,19): par[a][i+1] = par[par[a][i]][i] for v in G[a]: if v != pp: Dep[v] = Dep[a] + 1 FindDepth(v,a) def LCA(a,b): if Dep[a] < Dep[b]: return LCA(b,a) d = Dep[a] - Dep[b] i = 0 while d != 0: if not (d % 2 == 0): a = par[a][i] d = int(d/2) i += 1 i = 18 while i>=0: if par[a][i] != par[b][i]: a = par[a][i] b = par[b][i] i-=1 if a != b: a = par[a][0] return a main() ``` No
3,359
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In an unspecified solar system, there are N planets. A space government company has recently hired space contractors to build M bidirectional Hyperspaceβ„’ highways, each connecting two different planets. The primary objective, which was to make sure that every planet can be reached from any other planet taking only Hyperspaceβ„’ highways, has been completely fulfilled. Unfortunately, lots of space contractors had friends and cousins in the Space Board of Directors of the company, so the company decided to do much more than just connecting all planets. In order to make spending enormous amounts of space money for Hyperspaceβ„’ highways look neccessary, they decided to enforce a strict rule on the Hyperspaceβ„’ highway network: whenever there is a way to travel through some planets and return to the starting point without travelling through any planet twice, every pair of planets on the itinerary should be directly connected by a Hyperspaceβ„’ highway. In other words, the set of planets in every simple cycle induces a complete subgraph. You are designing a Hyperspaceβ„’ navigational app, and the key technical problem you are facing is finding the minimal number of Hyperspaceβ„’ highways one needs to use to travel from planet A to planet B. As this problem is too easy for Bubble Cup, here is a harder task: your program needs to do it for Q pairs of planets. Input The first line contains three positive integers N (1≀ N≀ 100 000), M (1≀ M≀ 500 000) and Q (1≀ Q≀ 200 000), denoting the number of planets, the number of Hyperspaceβ„’ highways, and the number of queries, respectively. Each of the following M lines contains a highway: highway i is given by two integers u_i and v_i (1 ≀ u_i < v_i ≀ N), meaning the planets u_i and v_i are connected by a Hyperspaceβ„’ highway. It is guaranteed that the network of planets and Hyperspaceβ„’ highways forms a simple connected graph. Each of the following Q lines contains a query: query j is given by two integers a_j and b_j (1 ≀ a_j < b_j ≀ N ), meaning we are interested in the minimal number of Hyperspaceβ„’ highways one needs to take to travel from planet a_j to planet b_j. Output Output Q lines: the j-th line of output should contain the minimal number of Hyperspaceβ„’ highways one needs to take to travel from planet a_j to planet b_j. Examples Input 5 7 2 1 2 1 3 1 4 2 3 2 4 3 4 1 5 1 4 2 5 Output 1 2 Input 8 11 4 1 2 2 3 3 4 4 5 1 3 1 6 3 5 3 7 4 7 5 7 6 8 1 5 2 4 6 7 3 8 Output 2 2 3 3 Note The graph from the second sample: <image> Submitted Solution: ``` N = 301001 n = 0 m = 0 q = 0 cnt = [0]*1 Num = [0] * N Up = [0] * N chk = [0] * N ppp = [0] * N par = [[0] * 20 for i in range(N)] Dep = [0] * N T = [None] * N G = [None] * N E = [None] * N def main(): n,m,q = map(int,input().split()) #E = [None] * (n+1) print(n) for i in range(1,m+1): u,v = map(int,input().split()) if E[u] is None: E[u] = [] if E[v] is None: E[v] = [] E[u].append(v) E[v].append(u) result = [] DFS(1,0,E) cnt = [0]*1 BuildTree(1,0) FindDepth(1,0) while q > 0: a,b = map(int,input().split()) result.append(int((Dep[a] + Dep[b] - Dep[LCA(a,b)]*2)/2)) #print(result) q-= 1 for r in result: print(r) def DFS(a,pp,E): cnt[0] = cnt[0]+1 Num[a] = cnt[0] ppp[a] = pp r = Num[a] for v in E[a]: if Num[v]!=0: r = min(r,Num[v]) continue if T[a] is None: T[a] = [] T[a].append(v) DFS(v,a,E) if Up[v] >= Num[a]: chk[v]=1 r = min(r,Up[v]) Up[a] = r def AddEdge(a,b): if G[a] is None: G[a] = [] if G[b] is None: G[b] = [] G[a].append(b) G[b].append(a) def BuildTree(a,c): if c != 0: AddEdge(n+c,a) if T[a] is None: T[a] = [] for v in T[a]: if chk[v] !=0: cnt[0] = cnt[0]+1 AddEdge(n + cnt[0],a) BuildTree(v,cnt[0]) else: BuildTree(v,c) def FindDepth(a,pp): par[a][0] = pp for i in range(0,19): par[a][i+1] = par[par[a][i]][i] for v in G[a]: if v != pp: Dep[v] = Dep[a] + 1 FindDepth(v,a) def LCA(a,b): if Dep[a] < Dep[b]: return LCA(b,a) d = Dep[a] - Dep[b] i = 0 while d != 0: if not (d % 2 == 0): a = par[a][i] d = int(d/2) i += 1 i = 18 while i>=0: if par[a][i] != par[b][i]: a = par[a][i] b = par[b][i] i-=1 if a != b: a = par[a][0] return a main() ``` No
3,360
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In an unspecified solar system, there are N planets. A space government company has recently hired space contractors to build M bidirectional Hyperspaceβ„’ highways, each connecting two different planets. The primary objective, which was to make sure that every planet can be reached from any other planet taking only Hyperspaceβ„’ highways, has been completely fulfilled. Unfortunately, lots of space contractors had friends and cousins in the Space Board of Directors of the company, so the company decided to do much more than just connecting all planets. In order to make spending enormous amounts of space money for Hyperspaceβ„’ highways look neccessary, they decided to enforce a strict rule on the Hyperspaceβ„’ highway network: whenever there is a way to travel through some planets and return to the starting point without travelling through any planet twice, every pair of planets on the itinerary should be directly connected by a Hyperspaceβ„’ highway. In other words, the set of planets in every simple cycle induces a complete subgraph. You are designing a Hyperspaceβ„’ navigational app, and the key technical problem you are facing is finding the minimal number of Hyperspaceβ„’ highways one needs to use to travel from planet A to planet B. As this problem is too easy for Bubble Cup, here is a harder task: your program needs to do it for Q pairs of planets. Input The first line contains three positive integers N (1≀ N≀ 100 000), M (1≀ M≀ 500 000) and Q (1≀ Q≀ 200 000), denoting the number of planets, the number of Hyperspaceβ„’ highways, and the number of queries, respectively. Each of the following M lines contains a highway: highway i is given by two integers u_i and v_i (1 ≀ u_i < v_i ≀ N), meaning the planets u_i and v_i are connected by a Hyperspaceβ„’ highway. It is guaranteed that the network of planets and Hyperspaceβ„’ highways forms a simple connected graph. Each of the following Q lines contains a query: query j is given by two integers a_j and b_j (1 ≀ a_j < b_j ≀ N ), meaning we are interested in the minimal number of Hyperspaceβ„’ highways one needs to take to travel from planet a_j to planet b_j. Output Output Q lines: the j-th line of output should contain the minimal number of Hyperspaceβ„’ highways one needs to take to travel from planet a_j to planet b_j. Examples Input 5 7 2 1 2 1 3 1 4 2 3 2 4 3 4 1 5 1 4 2 5 Output 1 2 Input 8 11 4 1 2 2 3 3 4 4 5 1 3 1 6 3 5 3 7 4 7 5 7 6 8 1 5 2 4 6 7 3 8 Output 2 2 3 3 Note The graph from the second sample: <image> Submitted Solution: ``` N = 100 n = 0 m = 0 q = 0 cnt = [0]*1 Num = [0] * N Up = [0] * N chk = [0] * N ppp = [0] * N par = [[0] * 20 for i in range(N)] Dep = [0] * N T = [None] * N G = [None] * N E = [None] * N def main(): n,m,q = map(int,input().split()) E = [None] * (n+1) for i in range(1,m+1): u,v = map(int,input().split()) if E[u] is None: E[u] = [] if E[v] is None: E[v] = [] E[u].append(v) E[v].append(u) DFS(1,0,E) cnt = [0]*1 BuildTree(1,0) FindDepth(1,0) while q > 0: a,b = map(int,input().split()) result =int((Dep[a] + Dep[b] - Dep[LCA(a,b)]*2)/2) print(result) q-= 1 def DFS(a,pp,E): cnt[0] = cnt[0]+1 Num[a] = cnt[0] ppp[a] = pp r = Num[a] for v in E[a]: if Num[v]!=0: r = min(r,Num[v]) continue if T[a] is None: T[a] = [] T[a].append(v) DFS(v,a,E) if Up[v] >= Num[a]: chk[v]=1 r = min(r,Up[v]) Up[a] = r def AddEdge(a,b): if G[a] is None: G[a] = [] if G[b] is None: G[b] = [] G[a].append(b) G[b].append(a) def BuildTree(a,c): if c != 0: AddEdge(n+c,a) if T[a] is None: T[a] = [] for v in T[a]: if chk[v] !=0: cnt[0] = cnt[0]+1 AddEdge(n + cnt[0],a) BuildTree(v,cnt[0]) else: BuildTree(v,c) def FindDepth(a,pp): par[a][0] = pp for i in range(0,19): par[a][i+1] = par[par[a][i]][i] for v in G[a]: if v != pp: Dep[v] = Dep[a] + 1 FindDepth(v,a) def LCA(a,b): if Dep[a] < Dep[b]: return LCA(b,a) d = Dep[a] - Dep[b] i = 0 while d != 0: if not (d % 2 == 0): a = par[a][i] d = int(d/2) i += 1 i = 18 while i>=0: if par[a][i] != par[b][i]: a = par[a][i] b = par[b][i] i-=1 if a != b: a = par[a][0] return a ``` No
3,361
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In an unspecified solar system, there are N planets. A space government company has recently hired space contractors to build M bidirectional Hyperspaceβ„’ highways, each connecting two different planets. The primary objective, which was to make sure that every planet can be reached from any other planet taking only Hyperspaceβ„’ highways, has been completely fulfilled. Unfortunately, lots of space contractors had friends and cousins in the Space Board of Directors of the company, so the company decided to do much more than just connecting all planets. In order to make spending enormous amounts of space money for Hyperspaceβ„’ highways look neccessary, they decided to enforce a strict rule on the Hyperspaceβ„’ highway network: whenever there is a way to travel through some planets and return to the starting point without travelling through any planet twice, every pair of planets on the itinerary should be directly connected by a Hyperspaceβ„’ highway. In other words, the set of planets in every simple cycle induces a complete subgraph. You are designing a Hyperspaceβ„’ navigational app, and the key technical problem you are facing is finding the minimal number of Hyperspaceβ„’ highways one needs to use to travel from planet A to planet B. As this problem is too easy for Bubble Cup, here is a harder task: your program needs to do it for Q pairs of planets. Input The first line contains three positive integers N (1≀ N≀ 100 000), M (1≀ M≀ 500 000) and Q (1≀ Q≀ 200 000), denoting the number of planets, the number of Hyperspaceβ„’ highways, and the number of queries, respectively. Each of the following M lines contains a highway: highway i is given by two integers u_i and v_i (1 ≀ u_i < v_i ≀ N), meaning the planets u_i and v_i are connected by a Hyperspaceβ„’ highway. It is guaranteed that the network of planets and Hyperspaceβ„’ highways forms a simple connected graph. Each of the following Q lines contains a query: query j is given by two integers a_j and b_j (1 ≀ a_j < b_j ≀ N ), meaning we are interested in the minimal number of Hyperspaceβ„’ highways one needs to take to travel from planet a_j to planet b_j. Output Output Q lines: the j-th line of output should contain the minimal number of Hyperspaceβ„’ highways one needs to take to travel from planet a_j to planet b_j. Examples Input 5 7 2 1 2 1 3 1 4 2 3 2 4 3 4 1 5 1 4 2 5 Output 1 2 Input 8 11 4 1 2 2 3 3 4 4 5 1 3 1 6 3 5 3 7 4 7 5 7 6 8 1 5 2 4 6 7 3 8 Output 2 2 3 3 Note The graph from the second sample: <image> Submitted Solution: ``` N = 100 n = 0 m = 0 q = 0 cnt = [0]*1 Num = [0] * N Up = [0] * N chk = [0] * N ppp = [0] * N par = [[0] * 20 for i in range(N)] Dep = [0] * N T = [None] * N G = [None] * N E = [None] * N def main(): n,m,q = map(int,input().split()) E = [None] * (n+1) for i in range(1,m+1): u,v = map(int,input().split()) if E[u] is None: E[u] = [] if E[v] is None: E[v] = [] E[u].append(v) E[v].append(u) result = [] DFS(1,0,E) cnt = [0]*1 BuildTree(1,0) FindDepth(1,0) while q > 0: a,b = map(int,input().split()) result.append(int((Dep[a] + Dep[b] - Dep[LCA(a,b)]*2)/2)) #print(result) q-= 1 for r in result: print(r) def DFS(a,pp,E): cnt[0] = cnt[0]+1 Num[a] = cnt[0] ppp[a] = pp r = Num[a] for v in E[a]: if Num[v]!=0: r = min(r,Num[v]) continue if T[a] is None: T[a] = [] T[a].append(v) DFS(v,a,E) if Up[v] >= Num[a]: chk[v]=1 r = min(r,Up[v]) Up[a] = r def AddEdge(a,b): if G[a] is None: G[a] = [] if G[b] is None: G[b] = [] G[a].append(b) G[b].append(a) def BuildTree(a,c): if c != 0: AddEdge(n+c,a) if T[a] is None: T[a] = [] for v in T[a]: if chk[v] !=0: cnt[0] = cnt[0]+1 AddEdge(n + cnt[0],a) BuildTree(v,cnt[0]) else: BuildTree(v,c) def FindDepth(a,pp): par[a][0] = pp for i in range(0,19): par[a][i+1] = par[par[a][i]][i] for v in G[a]: if v != pp: Dep[v] = Dep[a] + 1 FindDepth(v,a) def LCA(a,b): if Dep[a] < Dep[b]: return LCA(b,a) d = Dep[a] - Dep[b] i = 0 while d != 0: if not (d % 2 == 0): a = par[a][i] d = int(d/2) i += 1 i = 18 while i>=0: if par[a][i] != par[b][i]: a = par[a][i] b = par[b][i] i-=1 if a != b: a = par[a][0] return a ``` No
3,362
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two positive integers d and s. Find minimal positive integer n which is divisible by d and has sum of digits equal to s. Input The first line contains two positive integers d and s (1 ≀ d ≀ 500, 1 ≀ s ≀ 5000) separated by space. Output Print the required number or -1 if it doesn't exist. Examples Input 13 50 Output 699998 Input 61 2 Output 1000000000000000000000000000001 Input 15 50 Output -1 Tags: dp, graphs, number theory, shortest paths Correct Solution: ``` import os import sys from io import BytesIO, IOBase _print = print 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 inp(): return sys.stdin.readline().rstrip() def mpint(): return map(int, inp().split(' ')) def itg(): return int(inp()) # ############################## import def extended_gcd(a, b): """returns gcd(a, b), s, r s.t. a * s + b * r == gcd(a, b)""" s, old_s = 0, 1 r, old_r = b, a while r: q = old_r // r old_r, r = r, old_r - q * r old_s, s = s, old_s - q * s return old_r, old_s, (old_r - old_s * a) // b if b else 0 def modinv(a, m): """returns the modular inverse of a w.r.t. to m""" amodm = a % m g, x, _ = extended_gcd(amodm, m) return x % m if g == 1 else None # ############################## main from collections import deque def solve(): d, s = mpint() dp = [[(-1, -1)] * (d + 1) for _ in range(s + 1)] # last_digit, prev_mod dq = deque([(0, 0)]) # (digit_sum, mod) # bfs while dq: digit_sum, mod = dq.popleft() for dg in range(10): dg_sum = digit_sum + dg m = (mod * 10 + dg) % d if dg_sum <= s and dp[dg_sum][m][0] == -1: dp[dg_sum][m] = dg, mod dq.append((dg_sum, m)) # Found the answer # Early termination to speed up if dp[s][0][0] != -1: break # No such answer if dp[s][0][0] == -1: return -1 # backtrace to get answer ans = [] # char list, reverse at the end d = 0 while s: dg, d = dp[s][d] s -= dg ans.append(chr(dg + 48)) return ''.join(reversed(ans)) def main(): print(solve()) DEBUG = 0 URL = 'https://codeforces.com/contest/1070/problem/A' if __name__ == '__main__': # 0: normal, 1: runner, 2: debug, 3: interactive if DEBUG == 1: import requests from ACgenerator.Y_Test_Case_Runner import TestCaseRunner runner = TestCaseRunner(main, URL) inp = runner.input_stream print = runner.output_stream runner.checking() else: if DEBUG != 2: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) if DEBUG: def print(*args, **kwargs): _print(*args, **kwargs) sys.stdout.flush() main() # Please check! ```
3,363
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two positive integers d and s. Find minimal positive integer n which is divisible by d and has sum of digits equal to s. Input The first line contains two positive integers d and s (1 ≀ d ≀ 500, 1 ≀ s ≀ 5000) separated by space. Output Print the required number or -1 if it doesn't exist. Examples Input 13 50 Output 699998 Input 61 2 Output 1000000000000000000000000000001 Input 15 50 Output -1 Tags: dp, graphs, number theory, shortest paths Correct Solution: ``` import os import sys from io import BytesIO, IOBase _print = print 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 inp(): return sys.stdin.readline().rstrip() def mpint(): return map(int, inp().split(' ')) def itg(): return int(inp()) # ############################## import # https://codeforces.com/contest/1070/submission/71820555 # ############################## main from collections import deque D = 507 S = 5007 def solve(): d, sm = mpint() dq = deque([(0, 0)]) mod = [i % d for i in range(S)] dp = [[0] * D for _ in range(S)] ar = [[(0, 0)] * D for _ in range(S)] dp[0][0] = 1 while dq and not dp[sm][0]: s, r = dq.popleft() for i in range(10): a = s + i b = mod[10 * r + i] if a == 0 or a > sm: continue if dp[a][b] == 0: dq.append((a, b)) dp[a][b] = 1 ar[a][b] = s, r if not dp[sm][0]: return -1 s = sm r = 0 ans = [] while s: a, b = ar[s][r] ans.append(chr(ord('0') + s - a)) s, r = ar[s][r] ans.reverse() return ''.join(ans) def main(): print(solve()) DEBUG = 0 URL = 'https://codeforces.com/contest/1070/problem/A' if __name__ == '__main__': # 0: normal, 1: runner, 2: debug, 3: interactive if DEBUG == 1: import requests from ACgenerator.Y_Test_Case_Runner import TestCaseRunner runner = TestCaseRunner(main, URL) inp = runner.input_stream print = runner.output_stream runner.checking() else: if DEBUG != 2: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) if DEBUG: def print(*args, **kwargs): _print(*args, **kwargs) sys.stdout.flush() main() # Please check! ```
3,364
Provide tags and a correct Python 3 solution for this coding contest problem. You are given two positive integers d and s. Find minimal positive integer n which is divisible by d and has sum of digits equal to s. Input The first line contains two positive integers d and s (1 ≀ d ≀ 500, 1 ≀ s ≀ 5000) separated by space. Output Print the required number or -1 if it doesn't exist. Examples Input 13 50 Output 699998 Input 61 2 Output 1000000000000000000000000000001 Input 15 50 Output -1 Tags: dp, graphs, number theory, shortest paths Correct Solution: ``` import os import sys from io import BytesIO, IOBase _print = print 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 inp(): return sys.stdin.readline().rstrip() def mpint(): return map(int, inp().split(' ')) def itg(): return int(inp()) # ############################## import # ############################## main from collections import deque def solve(): d, s = mpint() dp = [[(-1, -1)] * (d + 1) for _ in range(s + 1)] # last_digit, prev_mod dq = deque([(0, 0)]) # (digit_sum, mod) # bfs while dq: digit_sum, mod = dq.popleft() for dg in range(10): dg_sum = digit_sum + dg m = (mod * 10 + dg) % d if dg_sum <= s and dp[dg_sum][m][0] == -1: dp[dg_sum][m] = dg, mod dq.append((dg_sum, m)) # Found the answer # Early termination to speed up if dp[s][0][0] != -1: break # No such answer if dp[s][0][0] == -1: return -1 # backtrace to get answer ans = [] # char list, reverse at the end d = 0 while s: dg, d = dp[s][d] s -= dg ans.append(chr(dg + 48)) return ''.join(reversed(ans)) def main(): print(solve()) DEBUG = 0 URL = 'https://codeforces.com/contest/1070/problem/A' if __name__ == '__main__': # 0: normal, 1: runner, 2: debug, 3: interactive if DEBUG == 1: import requests from ACgenerator.Y_Test_Case_Runner import TestCaseRunner runner = TestCaseRunner(main, URL) inp = runner.input_stream print = runner.output_stream runner.checking() else: if DEBUG != 2: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) if DEBUG: def print(*args, **kwargs): _print(*args, **kwargs) sys.stdout.flush() main() # Please check! ```
3,365
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two positive integers d and s. Find minimal positive integer n which is divisible by d and has sum of digits equal to s. Input The first line contains two positive integers d and s (1 ≀ d ≀ 500, 1 ≀ s ≀ 5000) separated by space. Output Print the required number or -1 if it doesn't exist. Examples Input 13 50 Output 699998 Input 61 2 Output 1000000000000000000000000000001 Input 15 50 Output -1 Submitted Solution: ``` def init(d): n = [] while d > 0: k = min(d, 9) n.append(k) d -= k return n def inc(n): i = 0 while i < len(n): if n[i] != 0: break i += 1 j = i + 1 while j < len(n): if n[j] != 9: break j += 1 if j == len(n): n.append(0) v = n[i] n[i] = 0 n[0] = v - 1 n[j] += 1 if j > i + 1: n[:j] = n[:j][::-1] def to_int(n): a = 0 m = 1 for d in n: a += m * d m *= 10 return a import time def solve(d, s): n = init(s) start = time.monotonic() while True: if time.monotonic() - start > 2.5: return -1 for _ in range(100): m = to_int(n) if m % d == 0: return m inc(n) import sys s, d = tuple(int(i) for i in sys.stdin.readline().split()) n = solve(s, d) print(n) ``` No
3,366
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two positive integers d and s. Find minimal positive integer n which is divisible by d and has sum of digits equal to s. Input The first line contains two positive integers d and s (1 ≀ d ≀ 500, 1 ≀ s ≀ 5000) separated by space. Output Print the required number or -1 if it doesn't exist. Examples Input 13 50 Output 699998 Input 61 2 Output 1000000000000000000000000000001 Input 15 50 Output -1 Submitted Solution: ``` def suma (x:int): summ = 0 while x: summ+=(x%10) x/=10 return summ def summm(x:int): summmm = 0 x = str(x) p = len(x) - 1 for i in range (0, len(x)//2, 1): summmm += int(x[i]) summmm += int(x[p]) p-=1 return summmm def gcd(a:int,b:int): while b: a %= b; a,b = b,a return a d, s = input().split(' ') d = int(d) s = int(s) n = 0 if gcd(d, s) != 1: print(-1) else: while True: n+=d if ((n % d == 0) and (summm(n) == s)): print(n) break ``` No
3,367
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two positive integers d and s. Find minimal positive integer n which is divisible by d and has sum of digits equal to s. Input The first line contains two positive integers d and s (1 ≀ d ≀ 500, 1 ≀ s ≀ 5000) separated by space. Output Print the required number or -1 if it doesn't exist. Examples Input 13 50 Output 699998 Input 61 2 Output 1000000000000000000000000000001 Input 15 50 Output -1 Submitted Solution: ``` n, m = map(int, input().split()) i = n count = 0 while i%n != 0 and sum(list(map(int, list(str(i))))) % m != 0 and count < 100000: i += n count += 1 print (i) ``` No
3,368
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given two positive integers d and s. Find minimal positive integer n which is divisible by d and has sum of digits equal to s. Input The first line contains two positive integers d and s (1 ≀ d ≀ 500, 1 ≀ s ≀ 5000) separated by space. Output Print the required number or -1 if it doesn't exist. Examples Input 13 50 Output 699998 Input 61 2 Output 1000000000000000000000000000001 Input 15 50 Output -1 Submitted Solution: ``` from collections import deque import sys # d, s = map(int, input().split()) # d = 500 # s = 4992 d = 13 s = 50 queue = deque([('0', 0, 0)]) cache = dict() # (n*10 + i) mod d = ((n mod d) * (10 mod d) + (i mod d)) mod d mod10 = 10%d mod_i = [i%d for i in range(0,10)] while len(queue): n, n_mod, n_sum = queue.popleft() # print(n, n_mod, n_sum) if (n_mod, n_sum) in cache or n_sum > s: continue if n_mod == 0 and n_sum == s: print(int(n)) break cache[(n_mod,n_sum)] = 1 for i in range(0,10): queue.append((n + str(i), (n_mod * mod10 + mod_i[i])%d, n_sum + i)) if len(queue) == 0: print(-1) ``` No
3,369
Provide tags and a correct Python 3 solution for this coding contest problem. Bob is an active user of the social network Faithbug. On this network, people are able to engage in a mutual friendship. That is, if a is a friend of b, then b is also a friend of a. Each user thus has a non-negative amount of friends. This morning, somebody anonymously sent Bob the following link: [graph realization problem](https://en.wikipedia.org/wiki/Graph_realization_problem) and Bob wants to know who that was. In order to do that, he first needs to know how the social network looks like. He investigated the profile of every other person on the network and noted down the number of his friends. However, he neglected to note down the number of his friends. Help him find out how many friends he has. Since there may be many possible answers, print all of them. Input The first line contains one integer n (1 ≀ n ≀ 5 β‹… 10^5), the number of people on the network excluding Bob. The second line contains n numbers a_1,a_2, ..., a_n (0 ≀ a_i ≀ n), with a_i being the number of people that person i is a friend of. Output Print all possible values of a_{n+1} β€” the amount of people that Bob can be friend of, in increasing order. If no solution exists, output -1. Examples Input 3 3 3 3 Output 3 Input 4 1 1 1 1 Output 0 2 4 Input 2 0 2 Output -1 Input 35 21 26 18 4 28 2 15 13 16 25 6 32 11 5 31 17 9 3 24 33 14 27 29 1 20 4 12 7 10 30 34 8 19 23 22 Output 13 15 17 19 21 Note In the first test case, the only solution is that everyone is friends with everyone. That is why Bob should have 3 friends. In the second test case, there are three possible solutions (apart from symmetries): * a is friend of b, c is friend of d, and Bob has no friends, or * a is a friend of b and both c and d are friends with Bob, or * Bob is friends of everyone. The third case is impossible to solve, as the second person needs to be a friend with everybody, but the first one is a complete stranger. Tags: binary search, data structures, graphs, greedy, implementation, math, sortings Correct Solution: ``` def main(): n=int(input()) a=list(map(int,input().split())) a.sort(reverse=True) mod=sum(a)%2 counts=[0]*(n+1) for guy in a: counts[guy]+=1 cumcounts=[0]*(n+1) cumcounts[0]=counts[0] for i in range(n): cumcounts[i+1]=cumcounts[i]+counts[i+1] partialsums=[0]*(n+1) curr=0 for i in range(n): curr+=(i+1)*counts[i+1] partialsums[i+1]=curr partialsums.append(0) cumcounts.append(0) sumi=0 diffs=[0]*n altdiffs=[0]*n for i in range(n): sumi+=a[i] rhs=i*(i+1) if a[i]>i: rhs+=partialsums[i]+(i+1)*(n-i-1-cumcounts[i]) else: rhs+=partialsums[a[i]-1]+a[i]*(n-i-1-cumcounts[a[i]-1]) diffs[i]=sumi-rhs rhs2=(i+1)*(i+2) if a[i]>i+1: rhs2+=partialsums[i+1]+(i+2)*(n-i-1-cumcounts[i+1]) else: rhs2+=partialsums[a[i]-1]+a[i]*(n-i-1-cumcounts[a[i]-1]) altdiffs[i]=sumi-rhs2 mini=max(diffs) maxi=-max(altdiffs) mini=max(mini,0) maxi=min(maxi,n) out="" if mini%2!=mod: mini+=1 if maxi%2==mod: maxi+=1 for guy in range(mini,maxi,2): out+=str(guy)+" " if mini>maxi: print(-1) else: print(out) main() ```
3,370
Provide tags and a correct Python 3 solution for this coding contest problem. Bob is an active user of the social network Faithbug. On this network, people are able to engage in a mutual friendship. That is, if a is a friend of b, then b is also a friend of a. Each user thus has a non-negative amount of friends. This morning, somebody anonymously sent Bob the following link: [graph realization problem](https://en.wikipedia.org/wiki/Graph_realization_problem) and Bob wants to know who that was. In order to do that, he first needs to know how the social network looks like. He investigated the profile of every other person on the network and noted down the number of his friends. However, he neglected to note down the number of his friends. Help him find out how many friends he has. Since there may be many possible answers, print all of them. Input The first line contains one integer n (1 ≀ n ≀ 5 β‹… 10^5), the number of people on the network excluding Bob. The second line contains n numbers a_1,a_2, ..., a_n (0 ≀ a_i ≀ n), with a_i being the number of people that person i is a friend of. Output Print all possible values of a_{n+1} β€” the amount of people that Bob can be friend of, in increasing order. If no solution exists, output -1. Examples Input 3 3 3 3 Output 3 Input 4 1 1 1 1 Output 0 2 4 Input 2 0 2 Output -1 Input 35 21 26 18 4 28 2 15 13 16 25 6 32 11 5 31 17 9 3 24 33 14 27 29 1 20 4 12 7 10 30 34 8 19 23 22 Output 13 15 17 19 21 Note In the first test case, the only solution is that everyone is friends with everyone. That is why Bob should have 3 friends. In the second test case, there are three possible solutions (apart from symmetries): * a is friend of b, c is friend of d, and Bob has no friends, or * a is a friend of b and both c and d are friends with Bob, or * Bob is friends of everyone. The third case is impossible to solve, as the second person needs to be a friend with everybody, but the first one is a complete stranger. Tags: binary search, data structures, graphs, greedy, implementation, math, sortings Correct Solution: ``` def main(): n=int(input()) a=list(map(int,input().split())) a.sort(reverse=True) mod=sum(a)%2 counts=[0]*(n+1) for guy in a: counts[guy]+=1 cumcounts=[counts[0]] for i in range(n): cumcounts.append(cumcounts[-1]+counts[i+1]) partialsums=[0] curr=0 for i in range(n): curr+=(i+1)*counts[i+1] partialsums.append(curr) partialsums.append(0) cumcounts.append(0) sumi=0 diffs=[] altdiffs=[] for i in range(n): sumi+=a[i] rhs=i*(i+1) if a[i]>i: rhs+=partialsums[i]+(i+1)*(n-i-1-cumcounts[i]) else: rhs+=partialsums[a[i]-1]+a[i]*(n-i-1-cumcounts[a[i]-1]) diffs.append(sumi-rhs) rhs2=(i+1)*(i+2) if a[i]>i+1: rhs2+=partialsums[i+1]+(i+2)*(n-i-1-cumcounts[i+1]) else: rhs2+=partialsums[a[i]-1]+a[i]*(n-i-1-cumcounts[a[i]-1]) altdiffs.append(sumi-rhs2) mini=max(diffs) maxi=-max(altdiffs) mini=max(mini,0) maxi=min(maxi,n) out="" if mini%2!=mod: mini+=1 if maxi%2==mod: maxi+=1 for guy in range(mini,maxi,2): out+=str(guy)+" " if mini>maxi: print(-1) else: print(out) main() ```
3,371
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Bob is an active user of the social network Faithbug. On this network, people are able to engage in a mutual friendship. That is, if a is a friend of b, then b is also a friend of a. Each user thus has a non-negative amount of friends. This morning, somebody anonymously sent Bob the following link: [graph realization problem](https://en.wikipedia.org/wiki/Graph_realization_problem) and Bob wants to know who that was. In order to do that, he first needs to know how the social network looks like. He investigated the profile of every other person on the network and noted down the number of his friends. However, he neglected to note down the number of his friends. Help him find out how many friends he has. Since there may be many possible answers, print all of them. Input The first line contains one integer n (1 ≀ n ≀ 5 β‹… 10^5), the number of people on the network excluding Bob. The second line contains n numbers a_1,a_2, ..., a_n (0 ≀ a_i ≀ n), with a_i being the number of people that person i is a friend of. Output Print all possible values of a_{n+1} β€” the amount of people that Bob can be friend of, in increasing order. If no solution exists, output -1. Examples Input 3 3 3 3 Output 3 Input 4 1 1 1 1 Output 0 2 4 Input 2 0 2 Output -1 Input 35 21 26 18 4 28 2 15 13 16 25 6 32 11 5 31 17 9 3 24 33 14 27 29 1 20 4 12 7 10 30 34 8 19 23 22 Output 13 15 17 19 21 Note In the first test case, the only solution is that everyone is friends with everyone. That is why Bob should have 3 friends. In the second test case, there are three possible solutions (apart from symmetries): * a is friend of b, c is friend of d, and Bob has no friends, or * a is a friend of b and both c and d are friends with Bob, or * Bob is friends of everyone. The third case is impossible to solve, as the second person needs to be a friend with everybody, but the first one is a complete stranger. Submitted Solution: ``` from bisect import bisect_left as bl from bisect import bisect_right as br import heapq import math from collections import * from functools import reduce,cmp_to_key import sys input = sys.stdin.readline M = mod = 10**9 + 7 def factors(n):return sorted(list(set(reduce(list.__add__,([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))) def inv_mod(n):return pow(n, mod - 2, mod) def li():return [int(i) for i in input().rstrip('\n').split(' ')] def st():return input().rstrip('\n') def val():return int(input()) def li2():return [i for i in input().rstrip('\n').split(' ')] def li3():return [int(i) for i in input().rstrip('\n')] n = val() l = sorted(li(),reverse = 1) while len(l) and l[-1] == 0:l.pop() if len(l) == 0: print(0) exit() lcopy = l[:] visited = {} maxtot = tot = 0 if max(l)>len(l): print(-1) exit() l = l[::-1] help = [0 for i in range(n)] maxtot = mintot = 0 till = 0 for i in range(n): till += help[i] l[i] += till if n - l[i] == i: l[i] -= 1 mintot += 1 if l[i]>0:help[n - l[i]] -= 1 # print(mintot) l = lcopy[::-1] help = [0 for i in range(n)] till = 0 for i in range(n): till += help[i] l[i] += till if l[i]>0: maxtot += 1 l[i] -= 1 else:break if l[i]>0:help[n - l[i]] -= 1 for i in range(mintot,maxtot + 1,2):print(i) ``` No
3,372
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Bob is an active user of the social network Faithbug. On this network, people are able to engage in a mutual friendship. That is, if a is a friend of b, then b is also a friend of a. Each user thus has a non-negative amount of friends. This morning, somebody anonymously sent Bob the following link: [graph realization problem](https://en.wikipedia.org/wiki/Graph_realization_problem) and Bob wants to know who that was. In order to do that, he first needs to know how the social network looks like. He investigated the profile of every other person on the network and noted down the number of his friends. However, he neglected to note down the number of his friends. Help him find out how many friends he has. Since there may be many possible answers, print all of them. Input The first line contains one integer n (1 ≀ n ≀ 5 β‹… 10^5), the number of people on the network excluding Bob. The second line contains n numbers a_1,a_2, ..., a_n (0 ≀ a_i ≀ n), with a_i being the number of people that person i is a friend of. Output Print all possible values of a_{n+1} β€” the amount of people that Bob can be friend of, in increasing order. If no solution exists, output -1. Examples Input 3 3 3 3 Output 3 Input 4 1 1 1 1 Output 0 2 4 Input 2 0 2 Output -1 Input 35 21 26 18 4 28 2 15 13 16 25 6 32 11 5 31 17 9 3 24 33 14 27 29 1 20 4 12 7 10 30 34 8 19 23 22 Output 13 15 17 19 21 Note In the first test case, the only solution is that everyone is friends with everyone. That is why Bob should have 3 friends. In the second test case, there are three possible solutions (apart from symmetries): * a is friend of b, c is friend of d, and Bob has no friends, or * a is a friend of b and both c and d are friends with Bob, or * Bob is friends of everyone. The third case is impossible to solve, as the second person needs to be a friend with everybody, but the first one is a complete stranger. Submitted Solution: ``` import copy def seqWorks(dat, extra): # sort dat + extra. x = copy.deepcopy(dat) x.append(extra) x.sort(key=lambda q:-q) N = len(x) lhsSum = 0 rhsSum = 0 k = 0 lastPositionAtLeastK = 0 while lastPositionAtLeastK < N-1 and x[lastPositionAtLeastK + 1] >= k: lastPositionAtLeastK += 1 for q in range(N): k = q+1 lhsSum += x[q] rhsSum -= min(x[q], k-1) # add the number of items in [q+1, N) that're at least k. while lastPositionAtLeastK >= 0 and x[ lastPositionAtLeastK ] < k: lastPositionAtLeastK -= 1 if lastPositionAtLeastK >= q+1: rhsSum += lastPositionAtLeastK - q rhsFinal = k * (k-1) + rhsSum if lhsSum <= rhsFinal: # this inequality is satisfied. continue # if the sequence fails, return some code telling whether 'extra' was too big or too little. if x[q] >= extra: # extra is small. return "too small" else: return "too big" return 'OK' def largestNotTooBig(dat): total = sum(dat) parity = total % 2 lo2 = 0 # might work? hi2 = len(dat) // 2 + 1 # too high if seqWorks(dat, lo2*2 + parity) == 'too big': return parity - 2 while hi2 - lo2 > 1: curr2 = (lo2 + hi2) // 2 curr = curr2 * 2 + parity result = seqWorks(dat, curr) if result == 'too big': hi2 = curr2 else: lo2 = curr2 return lo2*2 + parity def smallestNotTooSmall(dat): total = sum(dat) parity = total % 2 lo2 = 0 # too small? hi2 = len(dat) // 2 + 1 # not too small if seqWorks(dat, lo2*2 + parity) != 'too small': return lo2*2 + parity while hi2 - lo2 > 1: curr2 = (lo2 + hi2) // 2 curr = curr2 * 2 + parity result = seqWorks(dat, curr) # print("lo2 = {}, hi2 = {}, result = {}".format(lo2, hi2, result)) if result == 'too small': lo2 = curr2 else: hi2 = curr2 return hi2*2 + parity def solve(dat): lower = smallestNotTooSmall(dat) upper = largestNotTooBig(dat) if lower <= upper: print( ' '.join( [str(x) for x in range(lower, upper+1, 2)] ) ) else: print(-1) n = int(input()) dat = list(map(int, input().rstrip().split())) solve(dat) ``` No
3,373
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Bob is an active user of the social network Faithbug. On this network, people are able to engage in a mutual friendship. That is, if a is a friend of b, then b is also a friend of a. Each user thus has a non-negative amount of friends. This morning, somebody anonymously sent Bob the following link: [graph realization problem](https://en.wikipedia.org/wiki/Graph_realization_problem) and Bob wants to know who that was. In order to do that, he first needs to know how the social network looks like. He investigated the profile of every other person on the network and noted down the number of his friends. However, he neglected to note down the number of his friends. Help him find out how many friends he has. Since there may be many possible answers, print all of them. Input The first line contains one integer n (1 ≀ n ≀ 5 β‹… 10^5), the number of people on the network excluding Bob. The second line contains n numbers a_1,a_2, ..., a_n (0 ≀ a_i ≀ n), with a_i being the number of people that person i is a friend of. Output Print all possible values of a_{n+1} β€” the amount of people that Bob can be friend of, in increasing order. If no solution exists, output -1. Examples Input 3 3 3 3 Output 3 Input 4 1 1 1 1 Output 0 2 4 Input 2 0 2 Output -1 Input 35 21 26 18 4 28 2 15 13 16 25 6 32 11 5 31 17 9 3 24 33 14 27 29 1 20 4 12 7 10 30 34 8 19 23 22 Output 13 15 17 19 21 Note In the first test case, the only solution is that everyone is friends with everyone. That is why Bob should have 3 friends. In the second test case, there are three possible solutions (apart from symmetries): * a is friend of b, c is friend of d, and Bob has no friends, or * a is a friend of b and both c and d are friends with Bob, or * Bob is friends of everyone. The third case is impossible to solve, as the second person needs to be a friend with everybody, but the first one is a complete stranger. Submitted Solution: ``` from bisect import bisect_left as bl from bisect import bisect_right as br import heapq import math from collections import * from functools import reduce,cmp_to_key import sys input = sys.stdin.readline M = mod = 10**9 + 7 def factors(n):return sorted(list(set(reduce(list.__add__,([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))) def inv_mod(n):return pow(n, mod - 2, mod) def li():return [int(i) for i in input().rstrip('\n').split(' ')] def st():return input().rstrip('\n') def val():return int(input()) def li2():return [i for i in input().rstrip('\n').split(' ')] def li3():return [int(i) for i in input().rstrip('\n')] n = val() l = sorted(li(),reverse = 1) while len(l) and l[-1] == 0:l.pop() if len(l) == 0: print(0) exit() lcopy = l[:] visited = {} maxtot = tot = 0 if max(l)>len(l): print(-1) exit() l = l[::-1] help = [0 for i in range(n)] maxtot = mintot = 0 till = 0 for i in range(n): till += help[i] l[i] += till if n - l[i] == i: l[i] -= 1 mintot += 1 if l[i]>0:help[n - l[i]] -= 1 # print(mintot) l = lcopy help = [0 for i in range(n)] till = 0 for i in range(n): till += help[i] l[i] += till if l[i]>0: maxtot += 1 l[i] -= 1 else:break if l[i]>0:help[n - l[i]] -= 1 for i in range(mintot,maxtot + 1,2):print(i) ``` No
3,374
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Bob is an active user of the social network Faithbug. On this network, people are able to engage in a mutual friendship. That is, if a is a friend of b, then b is also a friend of a. Each user thus has a non-negative amount of friends. This morning, somebody anonymously sent Bob the following link: [graph realization problem](https://en.wikipedia.org/wiki/Graph_realization_problem) and Bob wants to know who that was. In order to do that, he first needs to know how the social network looks like. He investigated the profile of every other person on the network and noted down the number of his friends. However, he neglected to note down the number of his friends. Help him find out how many friends he has. Since there may be many possible answers, print all of them. Input The first line contains one integer n (1 ≀ n ≀ 5 β‹… 10^5), the number of people on the network excluding Bob. The second line contains n numbers a_1,a_2, ..., a_n (0 ≀ a_i ≀ n), with a_i being the number of people that person i is a friend of. Output Print all possible values of a_{n+1} β€” the amount of people that Bob can be friend of, in increasing order. If no solution exists, output -1. Examples Input 3 3 3 3 Output 3 Input 4 1 1 1 1 Output 0 2 4 Input 2 0 2 Output -1 Input 35 21 26 18 4 28 2 15 13 16 25 6 32 11 5 31 17 9 3 24 33 14 27 29 1 20 4 12 7 10 30 34 8 19 23 22 Output 13 15 17 19 21 Note In the first test case, the only solution is that everyone is friends with everyone. That is why Bob should have 3 friends. In the second test case, there are three possible solutions (apart from symmetries): * a is friend of b, c is friend of d, and Bob has no friends, or * a is a friend of b and both c and d are friends with Bob, or * Bob is friends of everyone. The third case is impossible to solve, as the second person needs to be a friend with everybody, but the first one is a complete stranger. Submitted Solution: ``` n=int(input()) a=list(map(int,input().split())) a.sort(reverse=True) mod=sum(a)%2 counts=[0]*(n+1) for guy in a: counts[guy]+=1 cumcounts=[counts[0]] for i in range(n): cumcounts.append(cumcounts[-1]+counts[i+1]) partialsums=[0] curr=0 for i in range(n): curr+=(i+1)*counts[i+1] partialsums.append(curr) partialsums.append(0) cumcounts.append(0) sumi=0 diffs=[] altdiffs=[] for i in range(n): sumi+=a[i] rhs=i*(i+1) if a[i]>i: rhs+=partialsums[i]+(i+1)*(n-i-1-cumcounts[i]) else: rhs+=partialsums[a[i]-1]+a[i]*(n-i-1-cumcounts[a[i]-1]) diffs.append(sumi-rhs) rhs2=(i+1)*(i+2) if a[i]>i+1: rhs2+=partialsums[i+1]+(i+2)*(n-i-1-cumcounts[i+1]) else: rhs2+=partialsums[a[i]-1]+a[i]*(n-i-1-cumcounts[a[i]-1]) altdiffs.append(sumi-rhs2) mini=max(diffs) maxi=-max(altdiffs) out="" if mini%2!=mod: mini+=1 if maxi%2==mod: maxi+=1 for guy in range(mini,maxi,2): out+=str(guy)+" " if mini>maxi: print(-1) else: print(out) ``` No
3,375
Provide tags and a correct Python 3 solution for this coding contest problem. Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question. Suppose you are given a positive integer a. You want to choose some integer b from 1 to a - 1 inclusive in such a way that the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers a βŠ• b and a \> \& \> b is as large as possible. In other words, you'd like to compute the following function: $$$f(a) = max_{0 < b < a}{gcd(a βŠ• b, a \> \& \> b)}.$$$ Here βŠ• denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR), and \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). The greatest common divisor of two integers x and y is the largest integer g such that both x and y are divided by g without remainder. You are given q integers a_1, a_2, …, a_q. For each of these integers compute the largest possible value of the greatest common divisor (when b is chosen optimally). Input The first line contains an integer q (1 ≀ q ≀ 10^3) β€” the number of integers you need to compute the answer for. After that q integers are given, one per line: a_1, a_2, …, a_q (2 ≀ a_i ≀ 2^{25} - 1) β€” the integers you need to compute the answer for. Output For each integer, print the answer in the same order as the integers are given in input. Example Input 3 2 3 5 Output 3 1 7 Note For the first integer the optimal choice is b = 1, then a βŠ• b = 3, a \> \& \> b = 0, and the greatest common divisor of 3 and 0 is 3. For the second integer one optimal choice is b = 2, then a βŠ• b = 1, a \> \& \> b = 2, and the greatest common divisor of 1 and 2 is 1. For the third integer the optimal choice is b = 2, then a βŠ• b = 7, a \> \& \> b = 0, and the greatest common divisor of 7 and 0 is 7. Tags: constructive algorithms, math, number theory Correct Solution: ``` from collections import defaultdict import math def ncr(n,m): return math.factorial(n)//((math.factorial(m)*math.factorial(n-m))) def gcd(n,m): return math.gcd(n,m) power=[] def cal(): temp=1 power.append(temp) for i in range(2,30): temp*=2 power.append(temp) cal() #print(*power) t=int(input()) for t1 in range(0,t): n=int(input()) ans=1 x=1 for i in range(0,len(power)): if power[i]<=n: ans=power[i] x=i+1 else: break if(pow(2,x)-1 == n): i=2 mx=1 while(i< int(math.sqrt(n))+1): if n%i==0: mx=max(mx,i,n//i) i+=1 print(mx) #print(math.gcd(n^mx,n&mx)) else: print(pow(2,x)-1) ```
3,376
Provide tags and a correct Python 3 solution for this coding contest problem. Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question. Suppose you are given a positive integer a. You want to choose some integer b from 1 to a - 1 inclusive in such a way that the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers a βŠ• b and a \> \& \> b is as large as possible. In other words, you'd like to compute the following function: $$$f(a) = max_{0 < b < a}{gcd(a βŠ• b, a \> \& \> b)}.$$$ Here βŠ• denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR), and \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). The greatest common divisor of two integers x and y is the largest integer g such that both x and y are divided by g without remainder. You are given q integers a_1, a_2, …, a_q. For each of these integers compute the largest possible value of the greatest common divisor (when b is chosen optimally). Input The first line contains an integer q (1 ≀ q ≀ 10^3) β€” the number of integers you need to compute the answer for. After that q integers are given, one per line: a_1, a_2, …, a_q (2 ≀ a_i ≀ 2^{25} - 1) β€” the integers you need to compute the answer for. Output For each integer, print the answer in the same order as the integers are given in input. Example Input 3 2 3 5 Output 3 1 7 Note For the first integer the optimal choice is b = 1, then a βŠ• b = 3, a \> \& \> b = 0, and the greatest common divisor of 3 and 0 is 3. For the second integer one optimal choice is b = 2, then a βŠ• b = 1, a \> \& \> b = 2, and the greatest common divisor of 1 and 2 is 1. For the third integer the optimal choice is b = 2, then a βŠ• b = 7, a \> \& \> b = 0, and the greatest common divisor of 7 and 0 is 7. Tags: constructive algorithms, math, number theory Correct Solution: ``` import math def ans2(n): if n==0: return 1 res = 2**(math.floor(math.log2(n))+1)-1 if res == n: lst = [1,1,1,5,1,21,1,85,73,341,89,1365,1,5461,4681,21845,1,87381,1,349525,299593,1398101,178481,5592405,1082401] res = lst[math.ceil(math.log2(n))-1] if n==2: res = 3 if n==1: res = 1 return res def ans(n): maxg = 1 g = 1 for i in range(1,n): a = i ^ n b = i & n if math.gcd(a,b) > maxg: maxg = math.gcd(a,b) g = i return maxg #for i in range(1,26): # print(ans(2**i-1)) #for i in range(33554430,33554434): # if ans(i)!=ans2(i): # print(i, ans(i), ans2(i)) #print("done") q = int(input()) for p in range(q): num = int(input()) print(ans2(num)) ```
3,377
Provide tags and a correct Python 3 solution for this coding contest problem. Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question. Suppose you are given a positive integer a. You want to choose some integer b from 1 to a - 1 inclusive in such a way that the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers a βŠ• b and a \> \& \> b is as large as possible. In other words, you'd like to compute the following function: $$$f(a) = max_{0 < b < a}{gcd(a βŠ• b, a \> \& \> b)}.$$$ Here βŠ• denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR), and \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). The greatest common divisor of two integers x and y is the largest integer g such that both x and y are divided by g without remainder. You are given q integers a_1, a_2, …, a_q. For each of these integers compute the largest possible value of the greatest common divisor (when b is chosen optimally). Input The first line contains an integer q (1 ≀ q ≀ 10^3) β€” the number of integers you need to compute the answer for. After that q integers are given, one per line: a_1, a_2, …, a_q (2 ≀ a_i ≀ 2^{25} - 1) β€” the integers you need to compute the answer for. Output For each integer, print the answer in the same order as the integers are given in input. Example Input 3 2 3 5 Output 3 1 7 Note For the first integer the optimal choice is b = 1, then a βŠ• b = 3, a \> \& \> b = 0, and the greatest common divisor of 3 and 0 is 3. For the second integer one optimal choice is b = 2, then a βŠ• b = 1, a \> \& \> b = 2, and the greatest common divisor of 1 and 2 is 1. For the third integer the optimal choice is b = 2, then a βŠ• b = 7, a \> \& \> b = 0, and the greatest common divisor of 7 and 0 is 7. Tags: constructive algorithms, math, number theory Correct Solution: ``` import math def factors(num): ans = 1 n = int(math.sqrt(num)) + 1 for i in range(1, n): if num % i == 0: a1 = num // i a2 = i if a1 < num: if a1 > ans: ans = a1 if a2 < num: if a2 > ans: ans = a2 return ans t = int(input()) for _ in range(t): a = int(input()) s1 = len(str(bin(a))) - 2 t1 = "0b" + ("1" * s1) temp = int(t1, 2) ^ a if temp != 0: print(temp ^ a) else: x = factors(a) print(x) ```
3,378
Provide tags and a correct Python 3 solution for this coding contest problem. Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question. Suppose you are given a positive integer a. You want to choose some integer b from 1 to a - 1 inclusive in such a way that the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers a βŠ• b and a \> \& \> b is as large as possible. In other words, you'd like to compute the following function: $$$f(a) = max_{0 < b < a}{gcd(a βŠ• b, a \> \& \> b)}.$$$ Here βŠ• denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR), and \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). The greatest common divisor of two integers x and y is the largest integer g such that both x and y are divided by g without remainder. You are given q integers a_1, a_2, …, a_q. For each of these integers compute the largest possible value of the greatest common divisor (when b is chosen optimally). Input The first line contains an integer q (1 ≀ q ≀ 10^3) β€” the number of integers you need to compute the answer for. After that q integers are given, one per line: a_1, a_2, …, a_q (2 ≀ a_i ≀ 2^{25} - 1) β€” the integers you need to compute the answer for. Output For each integer, print the answer in the same order as the integers are given in input. Example Input 3 2 3 5 Output 3 1 7 Note For the first integer the optimal choice is b = 1, then a βŠ• b = 3, a \> \& \> b = 0, and the greatest common divisor of 3 and 0 is 3. For the second integer one optimal choice is b = 2, then a βŠ• b = 1, a \> \& \> b = 2, and the greatest common divisor of 1 and 2 is 1. For the third integer the optimal choice is b = 2, then a βŠ• b = 7, a \> \& \> b = 0, and the greatest common divisor of 7 and 0 is 7. Tags: constructive algorithms, math, number theory Correct Solution: ``` from math import * q=int(input()) ansarr=[] for l in range(q): n=int(input()) b1=bin(n)[2:] if(b1.count('1')==len(b1)): flag=0 for i in range(2,ceil(sqrt(n))): if(n%i==0): ansarr.append(n//i) flag=1 break if(flag==0): ansarr.append(1) else: i=len(b1) ansarr.append((2**i)-1) print(*ansarr) ```
3,379
Provide tags and a correct Python 3 solution for this coding contest problem. Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question. Suppose you are given a positive integer a. You want to choose some integer b from 1 to a - 1 inclusive in such a way that the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers a βŠ• b and a \> \& \> b is as large as possible. In other words, you'd like to compute the following function: $$$f(a) = max_{0 < b < a}{gcd(a βŠ• b, a \> \& \> b)}.$$$ Here βŠ• denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR), and \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). The greatest common divisor of two integers x and y is the largest integer g such that both x and y are divided by g without remainder. You are given q integers a_1, a_2, …, a_q. For each of these integers compute the largest possible value of the greatest common divisor (when b is chosen optimally). Input The first line contains an integer q (1 ≀ q ≀ 10^3) β€” the number of integers you need to compute the answer for. After that q integers are given, one per line: a_1, a_2, …, a_q (2 ≀ a_i ≀ 2^{25} - 1) β€” the integers you need to compute the answer for. Output For each integer, print the answer in the same order as the integers are given in input. Example Input 3 2 3 5 Output 3 1 7 Note For the first integer the optimal choice is b = 1, then a βŠ• b = 3, a \> \& \> b = 0, and the greatest common divisor of 3 and 0 is 3. For the second integer one optimal choice is b = 2, then a βŠ• b = 1, a \> \& \> b = 2, and the greatest common divisor of 1 and 2 is 1. For the third integer the optimal choice is b = 2, then a βŠ• b = 7, a \> \& \> b = 0, and the greatest common divisor of 7 and 0 is 7. Tags: constructive algorithms, math, number theory Correct Solution: ``` import math def f(p): L = [] for i in range(1,int(math.sqrt(p))+1): if p % i == 0: L.append(i) if i != p//i: L.append(p//i) L.sort() return L[-2] R = lambda: map(int, input().split()) for _ in range(int(input())): n = int(input()) s = bin(n)[2:] l = len(s) p = s.count('1') if p == l: print(f(n)) else: print((2**(l))-1) ```
3,380
Provide tags and a correct Python 3 solution for this coding contest problem. Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question. Suppose you are given a positive integer a. You want to choose some integer b from 1 to a - 1 inclusive in such a way that the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers a βŠ• b and a \> \& \> b is as large as possible. In other words, you'd like to compute the following function: $$$f(a) = max_{0 < b < a}{gcd(a βŠ• b, a \> \& \> b)}.$$$ Here βŠ• denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR), and \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). The greatest common divisor of two integers x and y is the largest integer g such that both x and y are divided by g without remainder. You are given q integers a_1, a_2, …, a_q. For each of these integers compute the largest possible value of the greatest common divisor (when b is chosen optimally). Input The first line contains an integer q (1 ≀ q ≀ 10^3) β€” the number of integers you need to compute the answer for. After that q integers are given, one per line: a_1, a_2, …, a_q (2 ≀ a_i ≀ 2^{25} - 1) β€” the integers you need to compute the answer for. Output For each integer, print the answer in the same order as the integers are given in input. Example Input 3 2 3 5 Output 3 1 7 Note For the first integer the optimal choice is b = 1, then a βŠ• b = 3, a \> \& \> b = 0, and the greatest common divisor of 3 and 0 is 3. For the second integer one optimal choice is b = 2, then a βŠ• b = 1, a \> \& \> b = 2, and the greatest common divisor of 1 and 2 is 1. For the third integer the optimal choice is b = 2, then a βŠ• b = 7, a \> \& \> b = 0, and the greatest common divisor of 7 and 0 is 7. Tags: constructive algorithms, math, number theory Correct Solution: ``` import math def isPowerOfTwo (x): # First x in the below expression # is for the case when x is 0 return (x and (not(x & (x - 1))) ) def main(): t = int(input()) while t > 0: t -= 1 n = int(input()) if isPowerOfTwo(n + 1): s = math.ceil(math.sqrt(n)) ans = 1 for i in range(2, s + 1): if n % i == 0: ans = n / i break ans = int(ans) print(math.gcd(n ^ ans, n & ans)) else: z = bin(n)[2:] newstr = '' for i in range(len(z)): newstr += '1' z = int(newstr, 2) print(z) if __name__ == '__main__': main() ```
3,381
Provide tags and a correct Python 3 solution for this coding contest problem. Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question. Suppose you are given a positive integer a. You want to choose some integer b from 1 to a - 1 inclusive in such a way that the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers a βŠ• b and a \> \& \> b is as large as possible. In other words, you'd like to compute the following function: $$$f(a) = max_{0 < b < a}{gcd(a βŠ• b, a \> \& \> b)}.$$$ Here βŠ• denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR), and \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). The greatest common divisor of two integers x and y is the largest integer g such that both x and y are divided by g without remainder. You are given q integers a_1, a_2, …, a_q. For each of these integers compute the largest possible value of the greatest common divisor (when b is chosen optimally). Input The first line contains an integer q (1 ≀ q ≀ 10^3) β€” the number of integers you need to compute the answer for. After that q integers are given, one per line: a_1, a_2, …, a_q (2 ≀ a_i ≀ 2^{25} - 1) β€” the integers you need to compute the answer for. Output For each integer, print the answer in the same order as the integers are given in input. Example Input 3 2 3 5 Output 3 1 7 Note For the first integer the optimal choice is b = 1, then a βŠ• b = 3, a \> \& \> b = 0, and the greatest common divisor of 3 and 0 is 3. For the second integer one optimal choice is b = 2, then a βŠ• b = 1, a \> \& \> b = 2, and the greatest common divisor of 1 and 2 is 1. For the third integer the optimal choice is b = 2, then a βŠ• b = 7, a \> \& \> b = 0, and the greatest common divisor of 7 and 0 is 7. Tags: constructive algorithms, math, number theory Correct Solution: ``` from math import log q = int(input()) for i in range(q): w = int(input()) if log(w+1,2)>int(log(w+1,2)): print(2**(int(log(w+1,2))+1)-1) else: c = w p = 3 k = False while k == False and p<=int(w**0.5): if w%p==0: k = True c = p else: p+=2 print(w//c) ```
3,382
Provide tags and a correct Python 3 solution for this coding contest problem. Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question. Suppose you are given a positive integer a. You want to choose some integer b from 1 to a - 1 inclusive in such a way that the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers a βŠ• b and a \> \& \> b is as large as possible. In other words, you'd like to compute the following function: $$$f(a) = max_{0 < b < a}{gcd(a βŠ• b, a \> \& \> b)}.$$$ Here βŠ• denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR), and \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). The greatest common divisor of two integers x and y is the largest integer g such that both x and y are divided by g without remainder. You are given q integers a_1, a_2, …, a_q. For each of these integers compute the largest possible value of the greatest common divisor (when b is chosen optimally). Input The first line contains an integer q (1 ≀ q ≀ 10^3) β€” the number of integers you need to compute the answer for. After that q integers are given, one per line: a_1, a_2, …, a_q (2 ≀ a_i ≀ 2^{25} - 1) β€” the integers you need to compute the answer for. Output For each integer, print the answer in the same order as the integers are given in input. Example Input 3 2 3 5 Output 3 1 7 Note For the first integer the optimal choice is b = 1, then a βŠ• b = 3, a \> \& \> b = 0, and the greatest common divisor of 3 and 0 is 3. For the second integer one optimal choice is b = 2, then a βŠ• b = 1, a \> \& \> b = 2, and the greatest common divisor of 1 and 2 is 1. For the third integer the optimal choice is b = 2, then a βŠ• b = 7, a \> \& \> b = 0, and the greatest common divisor of 7 and 0 is 7. Tags: constructive algorithms, math, number theory Correct Solution: ``` from math import gcd, sqrt, ceil def check_pow2(a): return 2 ** a.bit_length() == a + 1 def max_div(a): for i in range(2, ceil(sqrt(a))+1): if a % i == 0: return max(i, a // i) return 1 def solve_dumb(a): mv = 0 for b in range(1, a): v = gcd(a ^ b, a & b) if v > mv: mv = v return mv #print(a, bin(a), mv) def solve(a): if check_pow2(a): return max_div(a) else: return 2 ** (a.bit_length()) - 1 #for i in range(2, 257): # a = i # sd, s = solve_dumb(a), solve(a) # print(a, sd, s) # assert sd == s q = int(input()) for i in range(q): n = int(input()) print(solve(n)) ```
3,383
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question. Suppose you are given a positive integer a. You want to choose some integer b from 1 to a - 1 inclusive in such a way that the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers a βŠ• b and a \> \& \> b is as large as possible. In other words, you'd like to compute the following function: $$$f(a) = max_{0 < b < a}{gcd(a βŠ• b, a \> \& \> b)}.$$$ Here βŠ• denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR), and \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). The greatest common divisor of two integers x and y is the largest integer g such that both x and y are divided by g without remainder. You are given q integers a_1, a_2, …, a_q. For each of these integers compute the largest possible value of the greatest common divisor (when b is chosen optimally). Input The first line contains an integer q (1 ≀ q ≀ 10^3) β€” the number of integers you need to compute the answer for. After that q integers are given, one per line: a_1, a_2, …, a_q (2 ≀ a_i ≀ 2^{25} - 1) β€” the integers you need to compute the answer for. Output For each integer, print the answer in the same order as the integers are given in input. Example Input 3 2 3 5 Output 3 1 7 Note For the first integer the optimal choice is b = 1, then a βŠ• b = 3, a \> \& \> b = 0, and the greatest common divisor of 3 and 0 is 3. For the second integer one optimal choice is b = 2, then a βŠ• b = 1, a \> \& \> b = 2, and the greatest common divisor of 1 and 2 is 1. For the third integer the optimal choice is b = 2, then a βŠ• b = 7, a \> \& \> b = 0, and the greatest common divisor of 7 and 0 is 7. Submitted Solution: ``` q=int(input()) for o in range(q): a=int(input()) s=bin(a).replace('0b', '') flag=0 for c in s: if c=='0': flag=1 break if flag==1: print(pow(2, len(s))-1) else: if a==3: print(1) elif a==7: print(1) elif a==15: print(5) elif a==31: print(1) elif a==63: print(21) elif a==127: print(1) elif a==255: print(85) elif a==511: print(73) elif a==1023: print(341) elif a==2047: print(89) elif a==4095: print(1365) elif a==8191: print(1) elif a==16383: print(5461) elif a==32767: print(4681) elif a==65535: print(21845) elif a==131071: print(1) elif a==262143: print(87381) elif a==524287: print(1) elif a==1048575: print(349525) elif a==2097151: print(299593) elif a==4194303: print(1398101) elif a==8388607: print(178481) elif a==16777215: print(5592405) elif a==33554431: print(1082401) ``` Yes
3,384
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question. Suppose you are given a positive integer a. You want to choose some integer b from 1 to a - 1 inclusive in such a way that the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers a βŠ• b and a \> \& \> b is as large as possible. In other words, you'd like to compute the following function: $$$f(a) = max_{0 < b < a}{gcd(a βŠ• b, a \> \& \> b)}.$$$ Here βŠ• denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR), and \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). The greatest common divisor of two integers x and y is the largest integer g such that both x and y are divided by g without remainder. You are given q integers a_1, a_2, …, a_q. For each of these integers compute the largest possible value of the greatest common divisor (when b is chosen optimally). Input The first line contains an integer q (1 ≀ q ≀ 10^3) β€” the number of integers you need to compute the answer for. After that q integers are given, one per line: a_1, a_2, …, a_q (2 ≀ a_i ≀ 2^{25} - 1) β€” the integers you need to compute the answer for. Output For each integer, print the answer in the same order as the integers are given in input. Example Input 3 2 3 5 Output 3 1 7 Note For the first integer the optimal choice is b = 1, then a βŠ• b = 3, a \> \& \> b = 0, and the greatest common divisor of 3 and 0 is 3. For the second integer one optimal choice is b = 2, then a βŠ• b = 1, a \> \& \> b = 2, and the greatest common divisor of 1 and 2 is 1. For the third integer the optimal choice is b = 2, then a βŠ• b = 7, a \> \& \> b = 0, and the greatest common divisor of 7 and 0 is 7. Submitted Solution: ``` def answer(n): if n==1: return 1 lmb=0 for i in range(26,-1,-1): if 1<<i & n: lmb=i break if n==2**(lmb+1)-1: maxi=1 for i in range(2,int(n**0.5)+1): if n%i==0: maxi=max(maxi,n//i,i) return maxi return 2**(lmb+1)-1 t=int(input()) for i in range(t): n=int(input()) print(answer(n)) ``` Yes
3,385
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question. Suppose you are given a positive integer a. You want to choose some integer b from 1 to a - 1 inclusive in such a way that the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers a βŠ• b and a \> \& \> b is as large as possible. In other words, you'd like to compute the following function: $$$f(a) = max_{0 < b < a}{gcd(a βŠ• b, a \> \& \> b)}.$$$ Here βŠ• denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR), and \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). The greatest common divisor of two integers x and y is the largest integer g such that both x and y are divided by g without remainder. You are given q integers a_1, a_2, …, a_q. For each of these integers compute the largest possible value of the greatest common divisor (when b is chosen optimally). Input The first line contains an integer q (1 ≀ q ≀ 10^3) β€” the number of integers you need to compute the answer for. After that q integers are given, one per line: a_1, a_2, …, a_q (2 ≀ a_i ≀ 2^{25} - 1) β€” the integers you need to compute the answer for. Output For each integer, print the answer in the same order as the integers are given in input. Example Input 3 2 3 5 Output 3 1 7 Note For the first integer the optimal choice is b = 1, then a βŠ• b = 3, a \> \& \> b = 0, and the greatest common divisor of 3 and 0 is 3. For the second integer one optimal choice is b = 2, then a βŠ• b = 1, a \> \& \> b = 2, and the greatest common divisor of 1 and 2 is 1. For the third integer the optimal choice is b = 2, then a βŠ• b = 7, a \> \& \> b = 0, and the greatest common divisor of 7 and 0 is 7. Submitted Solution: ``` for tc in range(int(input())): n=int(input()) h=format(n,'b') if set(h)=={'1'}: k=1 for i in range(2,int(n**0.5)+1): if not n%i: k=i break print(n//k) if k!=1 else print(1) else: print(2**len(h)-1) ``` Yes
3,386
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question. Suppose you are given a positive integer a. You want to choose some integer b from 1 to a - 1 inclusive in such a way that the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers a βŠ• b and a \> \& \> b is as large as possible. In other words, you'd like to compute the following function: $$$f(a) = max_{0 < b < a}{gcd(a βŠ• b, a \> \& \> b)}.$$$ Here βŠ• denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR), and \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). The greatest common divisor of two integers x and y is the largest integer g such that both x and y are divided by g without remainder. You are given q integers a_1, a_2, …, a_q. For each of these integers compute the largest possible value of the greatest common divisor (when b is chosen optimally). Input The first line contains an integer q (1 ≀ q ≀ 10^3) β€” the number of integers you need to compute the answer for. After that q integers are given, one per line: a_1, a_2, …, a_q (2 ≀ a_i ≀ 2^{25} - 1) β€” the integers you need to compute the answer for. Output For each integer, print the answer in the same order as the integers are given in input. Example Input 3 2 3 5 Output 3 1 7 Note For the first integer the optimal choice is b = 1, then a βŠ• b = 3, a \> \& \> b = 0, and the greatest common divisor of 3 and 0 is 3. For the second integer one optimal choice is b = 2, then a βŠ• b = 1, a \> \& \> b = 2, and the greatest common divisor of 1 and 2 is 1. For the third integer the optimal choice is b = 2, then a βŠ• b = 7, a \> \& \> b = 0, and the greatest common divisor of 7 and 0 is 7. Submitted Solution: ``` for _ in range(int(input())): a=int(input()) n=1 while n<=a: n*=2 n-=1 if(a<n): print(n) else: d,ans=2,1 while d*d<=a: if a%d==0: ans=a//d break d+=1 print(ans) ``` Yes
3,387
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question. Suppose you are given a positive integer a. You want to choose some integer b from 1 to a - 1 inclusive in such a way that the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers a βŠ• b and a \> \& \> b is as large as possible. In other words, you'd like to compute the following function: $$$f(a) = max_{0 < b < a}{gcd(a βŠ• b, a \> \& \> b)}.$$$ Here βŠ• denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR), and \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). The greatest common divisor of two integers x and y is the largest integer g such that both x and y are divided by g without remainder. You are given q integers a_1, a_2, …, a_q. For each of these integers compute the largest possible value of the greatest common divisor (when b is chosen optimally). Input The first line contains an integer q (1 ≀ q ≀ 10^3) β€” the number of integers you need to compute the answer for. After that q integers are given, one per line: a_1, a_2, …, a_q (2 ≀ a_i ≀ 2^{25} - 1) β€” the integers you need to compute the answer for. Output For each integer, print the answer in the same order as the integers are given in input. Example Input 3 2 3 5 Output 3 1 7 Note For the first integer the optimal choice is b = 1, then a βŠ• b = 3, a \> \& \> b = 0, and the greatest common divisor of 3 and 0 is 3. For the second integer one optimal choice is b = 2, then a βŠ• b = 1, a \> \& \> b = 2, and the greatest common divisor of 1 and 2 is 1. For the third integer the optimal choice is b = 2, then a βŠ• b = 7, a \> \& \> b = 0, and the greatest common divisor of 7 and 0 is 7. Submitted Solution: ``` t = int(input()) while t>0: t -= 1; n = int(input()) m = n ans = 2 while n>1: n=n//2 ans *= 2 ans -= 1 if ans == m: ans = ans/3 print(ans) ``` No
3,388
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question. Suppose you are given a positive integer a. You want to choose some integer b from 1 to a - 1 inclusive in such a way that the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers a βŠ• b and a \> \& \> b is as large as possible. In other words, you'd like to compute the following function: $$$f(a) = max_{0 < b < a}{gcd(a βŠ• b, a \> \& \> b)}.$$$ Here βŠ• denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR), and \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). The greatest common divisor of two integers x and y is the largest integer g such that both x and y are divided by g without remainder. You are given q integers a_1, a_2, …, a_q. For each of these integers compute the largest possible value of the greatest common divisor (when b is chosen optimally). Input The first line contains an integer q (1 ≀ q ≀ 10^3) β€” the number of integers you need to compute the answer for. After that q integers are given, one per line: a_1, a_2, …, a_q (2 ≀ a_i ≀ 2^{25} - 1) β€” the integers you need to compute the answer for. Output For each integer, print the answer in the same order as the integers are given in input. Example Input 3 2 3 5 Output 3 1 7 Note For the first integer the optimal choice is b = 1, then a βŠ• b = 3, a \> \& \> b = 0, and the greatest common divisor of 3 and 0 is 3. For the second integer one optimal choice is b = 2, then a βŠ• b = 1, a \> \& \> b = 2, and the greatest common divisor of 1 and 2 is 1. For the third integer the optimal choice is b = 2, then a βŠ• b = 7, a \> \& \> b = 0, and the greatest common divisor of 7 and 0 is 7. Submitted Solution: ``` ###### ### ####### ####### ## # ##### ### ##### # # # # # # # # # # # # # ### # # # # # # # # # # # # # ### ###### ######### # # # # # # ######### # ###### ######### # # # # # # ######### # # # # # # # # # # # #### # # # # # # # # # # ## # # # # # ###### # # ####### ####### # # ##### # # # # # from __future__ import print_function # for PyPy2 from collections import Counter, OrderedDict from itertools import permutations as perm from fractions import Fraction from collections import deque from sys import stdin from bisect import * from heapq import * from math import * g = lambda : stdin.readline().strip() gl = lambda : g().split() gil = lambda : [int(var) for var in gl()] gfl = lambda : [float(var) for var in gl()] gcl = lambda : list(g()) gbs = lambda : [int(var) for var in g()] mod = int(1e9)+7 inf = float("inf") q, = gil() for _ in range(q): v, = gil() msb = int(log2(v)) bit = 0 for i in range(msb+1): if v&(1<<i) == 0: bit += (1<<i) if bit: print(bit+v) else: print(1) ``` No
3,389
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question. Suppose you are given a positive integer a. You want to choose some integer b from 1 to a - 1 inclusive in such a way that the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers a βŠ• b and a \> \& \> b is as large as possible. In other words, you'd like to compute the following function: $$$f(a) = max_{0 < b < a}{gcd(a βŠ• b, a \> \& \> b)}.$$$ Here βŠ• denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR), and \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). The greatest common divisor of two integers x and y is the largest integer g such that both x and y are divided by g without remainder. You are given q integers a_1, a_2, …, a_q. For each of these integers compute the largest possible value of the greatest common divisor (when b is chosen optimally). Input The first line contains an integer q (1 ≀ q ≀ 10^3) β€” the number of integers you need to compute the answer for. After that q integers are given, one per line: a_1, a_2, …, a_q (2 ≀ a_i ≀ 2^{25} - 1) β€” the integers you need to compute the answer for. Output For each integer, print the answer in the same order as the integers are given in input. Example Input 3 2 3 5 Output 3 1 7 Note For the first integer the optimal choice is b = 1, then a βŠ• b = 3, a \> \& \> b = 0, and the greatest common divisor of 3 and 0 is 3. For the second integer one optimal choice is b = 2, then a βŠ• b = 1, a \> \& \> b = 2, and the greatest common divisor of 1 and 2 is 1. For the third integer the optimal choice is b = 2, then a βŠ• b = 7, a \> \& \> b = 0, and the greatest common divisor of 7 and 0 is 7. Submitted Solution: ``` # -*- coding: utf-8 -*- import sys, re from collections import deque, defaultdict, Counter from math import sqrt, hypot, factorial, pi, sin, cos, radians if sys.version_info.minor >= 5: from math import gcd else: from fractions import gcd from heapq import heappop, heappush, heapify, heappushpop from bisect import bisect_left, bisect_right from itertools import permutations, combinations, product from operator import itemgetter, mul from copy import deepcopy from functools import reduce, partial from fractions import Fraction from string import ascii_lowercase, ascii_uppercase, digits def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def ceil(a, b=1): return int(-(-a // b)) def round(x): return int((x*2+1) // 2) def fermat(x, y, MOD): return x * pow(y, MOD-2, MOD) % MOD def lcm(x, y): return (x * y) // gcd(x, y) def lcm_list(nums): return reduce(lcm, nums, 1) def gcd_list(nums): return reduce(gcd, nums, nums[0]) def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(): return list(map(int, input().split())) sys.setrecursionlimit(10 ** 9) INF = float('inf') MOD = 10 ** 9 + 7 Q = INT() for i in range(Q): a = INT() bin_a = format(a, 'b') if '0' in bin_a: bin_a = bin_a.replace('0', '1') print(int(bin_a, 2)) else: for i in range(2, int(sqrt(a))+2): if a % i == 0: print(a // i) exit() print(1) ``` No
3,390
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question. Suppose you are given a positive integer a. You want to choose some integer b from 1 to a - 1 inclusive in such a way that the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers a βŠ• b and a \> \& \> b is as large as possible. In other words, you'd like to compute the following function: $$$f(a) = max_{0 < b < a}{gcd(a βŠ• b, a \> \& \> b)}.$$$ Here βŠ• denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR), and \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND). The greatest common divisor of two integers x and y is the largest integer g such that both x and y are divided by g without remainder. You are given q integers a_1, a_2, …, a_q. For each of these integers compute the largest possible value of the greatest common divisor (when b is chosen optimally). Input The first line contains an integer q (1 ≀ q ≀ 10^3) β€” the number of integers you need to compute the answer for. After that q integers are given, one per line: a_1, a_2, …, a_q (2 ≀ a_i ≀ 2^{25} - 1) β€” the integers you need to compute the answer for. Output For each integer, print the answer in the same order as the integers are given in input. Example Input 3 2 3 5 Output 3 1 7 Note For the first integer the optimal choice is b = 1, then a βŠ• b = 3, a \> \& \> b = 0, and the greatest common divisor of 3 and 0 is 3. For the second integer one optimal choice is b = 2, then a βŠ• b = 1, a \> \& \> b = 2, and the greatest common divisor of 1 and 2 is 1. For the third integer the optimal choice is b = 2, then a βŠ• b = 7, a \> \& \> b = 0, and the greatest common divisor of 7 and 0 is 7. Submitted Solution: ``` import sys from math import gcd M = 36 def query(a, b): return gcd(a ^ b, a & b) magicA = [] magicB = [] magic = {} for idx in range(1, M): q = (1 << idx) - 1 magicA.append(q) magic[q] = 1 for jump in range(1, M): x = "1" while(len(x) < M): magicB.append(int(x, 2)) x += "0" * jump + "1" magicB = list(set(magicB)) for ca in magicA: for cb in magicB: if cb < ca: magic[ca] = max(magic[ca], query(ca, cb)) def naive(a): mgcd = 0 for b in range(1, a): mgcd = max(mgcd, query(a, b)) return mgcd tc = int(input()) for t in range(tc): q = int(input()) # q = t a = (1 << (len(bin(q)) - 2)) - 1 if q in magic: a = magic[q] # print('{}: {} {}'.format(q, naive(q), a)) print(a) ``` No
3,391
Provide tags and a correct Python 3 solution for this coding contest problem. Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque. We call this sequence of actions an operation. For example, if deque was [2, 3, 4, 5, 1], on the operation he will write B=3 to the beginning and A=2 to the end, so he will get [3, 4, 5, 1, 2]. The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him q queries. Each query consists of the singular number m_j (j = 1, 2, …, q). It is required for each query to answer which two elements he will pull out on the m_j-th operation. Note that the queries are independent and for each query the numbers A and B should be printed in the order in which they will be pulled out of the deque. Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides. Input The first line contains two integers n and q (2 ≀ n ≀ 10^5, 0 ≀ q ≀ 3 β‹… 10^5) β€” the number of elements in the deque and the number of queries. The second line contains n integers a_1, a_2, ..., a_n, where a_i (0 ≀ a_i ≀ 10^9) β€” the deque element in i-th position. The next q lines contain one number each, meaning m_j (1 ≀ m_j ≀ 10^{18}). Output For each teacher's query, output two numbers A and B β€” the numbers that Valeriy pulls out of the deque for the m_j-th operation. Examples Input 5 3 1 2 3 4 5 1 2 10 Output 1 2 2 3 5 2 Input 2 0 0 0 Output Note Consider all 10 steps for the first test in detail: 1. [1, 2, 3, 4, 5] β€” on the first operation, A and B are 1 and 2, respectively. So, 2 we write to the beginning of the deque, and 1 β€” to the end. We get the following status of the deque: [2, 3, 4, 5, 1]. 2. [2, 3, 4, 5, 1] β‡’ A = 2, B = 3. 3. [3, 4, 5, 1, 2] 4. [4, 5, 1, 2, 3] 5. [5, 1, 2, 3, 4] 6. [5, 2, 3, 4, 1] 7. [5, 3, 4, 1, 2] 8. [5, 4, 1, 2, 3] 9. [5, 1, 2, 3, 4] 10. [5, 2, 3, 4, 1] β‡’ A = 5, B = 2. Tags: data structures, implementation Correct Solution: ``` def getN(): return int(input()) def getList(): return list(map(int, input().split())) from collections import deque n, m = getList() nums = getList() mxnum = max(nums) d = deque(nums) qr = [] for i in range(m): qr.append(getN()) log = [] rot = 0 while(True): # print(d) a = d.popleft() b = d.popleft() log.append((a, b)) if a > b: a, b = b, a d.append(a) d.appendleft(b) rot += 1 if b == mxnum: break for q in qr: if q <= rot: print(log[q - 1][0], log[q - 1][1]) else: res = q - rot - 1 print(b, d[res % (n-1) + 1 ]) # print(d) """ 5 10 1 2 5 4 3 1 2 3 4 5 6 7 8 9 10 """ ```
3,392
Provide tags and a correct Python 3 solution for this coding contest problem. Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque. We call this sequence of actions an operation. For example, if deque was [2, 3, 4, 5, 1], on the operation he will write B=3 to the beginning and A=2 to the end, so he will get [3, 4, 5, 1, 2]. The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him q queries. Each query consists of the singular number m_j (j = 1, 2, …, q). It is required for each query to answer which two elements he will pull out on the m_j-th operation. Note that the queries are independent and for each query the numbers A and B should be printed in the order in which they will be pulled out of the deque. Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides. Input The first line contains two integers n and q (2 ≀ n ≀ 10^5, 0 ≀ q ≀ 3 β‹… 10^5) β€” the number of elements in the deque and the number of queries. The second line contains n integers a_1, a_2, ..., a_n, where a_i (0 ≀ a_i ≀ 10^9) β€” the deque element in i-th position. The next q lines contain one number each, meaning m_j (1 ≀ m_j ≀ 10^{18}). Output For each teacher's query, output two numbers A and B β€” the numbers that Valeriy pulls out of the deque for the m_j-th operation. Examples Input 5 3 1 2 3 4 5 1 2 10 Output 1 2 2 3 5 2 Input 2 0 0 0 Output Note Consider all 10 steps for the first test in detail: 1. [1, 2, 3, 4, 5] β€” on the first operation, A and B are 1 and 2, respectively. So, 2 we write to the beginning of the deque, and 1 β€” to the end. We get the following status of the deque: [2, 3, 4, 5, 1]. 2. [2, 3, 4, 5, 1] β‡’ A = 2, B = 3. 3. [3, 4, 5, 1, 2] 4. [4, 5, 1, 2, 3] 5. [5, 1, 2, 3, 4] 6. [5, 2, 3, 4, 1] 7. [5, 3, 4, 1, 2] 8. [5, 4, 1, 2, 3] 9. [5, 1, 2, 3, 4] 10. [5, 2, 3, 4, 1] β‡’ A = 5, B = 2. Tags: data structures, implementation Correct Solution: ``` import sys input=sys.stdin.readline from collections import defaultdict as dc from collections import Counter from bisect import bisect_right, bisect_left import math from operator import itemgetter from heapq import heapify, heappop, heappush n,q=map(int,input().split()) l=list(map(int,input().split())) p=[] t=[] x=l[0] for i in range(1,n): p.append([x,l[i]]) if l[i]>=x: t.append(x) x=l[i] else: t.append(l[i]) t.insert(0,x) #print(x,t,p) for _ in range(q): a=int(input()) if a<=n-1: print(*p[a-1]) else: y=a-n+1 j=y%(n-1) if j==0: j=-1 print(t[0],t[j]) ```
3,393
Provide tags and a correct Python 3 solution for this coding contest problem. Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque. We call this sequence of actions an operation. For example, if deque was [2, 3, 4, 5, 1], on the operation he will write B=3 to the beginning and A=2 to the end, so he will get [3, 4, 5, 1, 2]. The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him q queries. Each query consists of the singular number m_j (j = 1, 2, …, q). It is required for each query to answer which two elements he will pull out on the m_j-th operation. Note that the queries are independent and for each query the numbers A and B should be printed in the order in which they will be pulled out of the deque. Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides. Input The first line contains two integers n and q (2 ≀ n ≀ 10^5, 0 ≀ q ≀ 3 β‹… 10^5) β€” the number of elements in the deque and the number of queries. The second line contains n integers a_1, a_2, ..., a_n, where a_i (0 ≀ a_i ≀ 10^9) β€” the deque element in i-th position. The next q lines contain one number each, meaning m_j (1 ≀ m_j ≀ 10^{18}). Output For each teacher's query, output two numbers A and B β€” the numbers that Valeriy pulls out of the deque for the m_j-th operation. Examples Input 5 3 1 2 3 4 5 1 2 10 Output 1 2 2 3 5 2 Input 2 0 0 0 Output Note Consider all 10 steps for the first test in detail: 1. [1, 2, 3, 4, 5] β€” on the first operation, A and B are 1 and 2, respectively. So, 2 we write to the beginning of the deque, and 1 β€” to the end. We get the following status of the deque: [2, 3, 4, 5, 1]. 2. [2, 3, 4, 5, 1] β‡’ A = 2, B = 3. 3. [3, 4, 5, 1, 2] 4. [4, 5, 1, 2, 3] 5. [5, 1, 2, 3, 4] 6. [5, 2, 3, 4, 1] 7. [5, 3, 4, 1, 2] 8. [5, 4, 1, 2, 3] 9. [5, 1, 2, 3, 4] 10. [5, 2, 3, 4, 1] β‡’ A = 5, B = 2. Tags: data structures, implementation Correct Solution: ``` def op(arr,num): for i in range(0,num-1): if arr[0]>arr[1]: z=arr.pop(1) arr.append(z) else: z=arr.pop(0) arr.append(z) print (arr[0],arr[1]) def opmod(arr,num): count=0 while arr[0]!=num: if arr[0]>arr[1]: z=arr.pop(1) arr.append(z) else: z=arr.pop(0) arr.append(z) count=count+1 return count a=input() a=a.split() p,q=int(a[0]),int(a[1]) a=input() arr1=a.split() for i in range(0,p): arr1[i]=int(arr1[i]) s=max(arr1) arr2=[] for i in range(0,q): a=int(input()) arr2.append(a) arr3=[] for j in range(0,p): arr3.append(arr1[j]) rounds=opmod(arr3,s)+1 for i in range(0,q): if arr2[i]<rounds: arr4=[] for j in range(0,p): arr4.append(arr1[j]) op(arr4,arr2[i]) else: rec=(arr2[i]-rounds)%(p-1) print (arr3[0],arr3[1+rec]) ```
3,394
Provide tags and a correct Python 3 solution for this coding contest problem. Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque. We call this sequence of actions an operation. For example, if deque was [2, 3, 4, 5, 1], on the operation he will write B=3 to the beginning and A=2 to the end, so he will get [3, 4, 5, 1, 2]. The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him q queries. Each query consists of the singular number m_j (j = 1, 2, …, q). It is required for each query to answer which two elements he will pull out on the m_j-th operation. Note that the queries are independent and for each query the numbers A and B should be printed in the order in which they will be pulled out of the deque. Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides. Input The first line contains two integers n and q (2 ≀ n ≀ 10^5, 0 ≀ q ≀ 3 β‹… 10^5) β€” the number of elements in the deque and the number of queries. The second line contains n integers a_1, a_2, ..., a_n, where a_i (0 ≀ a_i ≀ 10^9) β€” the deque element in i-th position. The next q lines contain one number each, meaning m_j (1 ≀ m_j ≀ 10^{18}). Output For each teacher's query, output two numbers A and B β€” the numbers that Valeriy pulls out of the deque for the m_j-th operation. Examples Input 5 3 1 2 3 4 5 1 2 10 Output 1 2 2 3 5 2 Input 2 0 0 0 Output Note Consider all 10 steps for the first test in detail: 1. [1, 2, 3, 4, 5] β€” on the first operation, A and B are 1 and 2, respectively. So, 2 we write to the beginning of the deque, and 1 β€” to the end. We get the following status of the deque: [2, 3, 4, 5, 1]. 2. [2, 3, 4, 5, 1] β‡’ A = 2, B = 3. 3. [3, 4, 5, 1, 2] 4. [4, 5, 1, 2, 3] 5. [5, 1, 2, 3, 4] 6. [5, 2, 3, 4, 1] 7. [5, 3, 4, 1, 2] 8. [5, 4, 1, 2, 3] 9. [5, 1, 2, 3, 4] 10. [5, 2, 3, 4, 1] β‡’ A = 5, B = 2. Tags: data structures, implementation Correct Solution: ``` n,k=map(int,input().split()) a=list(map(int,input().split())) mx=max(a) ind=a.index(mx) f=0 s=1 ans=[[] for i in range(ind)] for i in range(ind): ans[i].append(a[f]) ans[i].append(a[s]) if(a[f]>=a[s]): a.append(a[s]) s+=1 else: a.append(a[f]) f=s s+=1 a=a[ind:] #print(a) for i in range(k): m=int(input()) if(m<=ind): print(ans[m-1][0],ans[m-1][1]) else: m-=ind m-=1 m%=(n-1) print(a[0],a[1+m]) ```
3,395
Provide tags and a correct Python 3 solution for this coding contest problem. Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque. We call this sequence of actions an operation. For example, if deque was [2, 3, 4, 5, 1], on the operation he will write B=3 to the beginning and A=2 to the end, so he will get [3, 4, 5, 1, 2]. The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him q queries. Each query consists of the singular number m_j (j = 1, 2, …, q). It is required for each query to answer which two elements he will pull out on the m_j-th operation. Note that the queries are independent and for each query the numbers A and B should be printed in the order in which they will be pulled out of the deque. Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides. Input The first line contains two integers n and q (2 ≀ n ≀ 10^5, 0 ≀ q ≀ 3 β‹… 10^5) β€” the number of elements in the deque and the number of queries. The second line contains n integers a_1, a_2, ..., a_n, where a_i (0 ≀ a_i ≀ 10^9) β€” the deque element in i-th position. The next q lines contain one number each, meaning m_j (1 ≀ m_j ≀ 10^{18}). Output For each teacher's query, output two numbers A and B β€” the numbers that Valeriy pulls out of the deque for the m_j-th operation. Examples Input 5 3 1 2 3 4 5 1 2 10 Output 1 2 2 3 5 2 Input 2 0 0 0 Output Note Consider all 10 steps for the first test in detail: 1. [1, 2, 3, 4, 5] β€” on the first operation, A and B are 1 and 2, respectively. So, 2 we write to the beginning of the deque, and 1 β€” to the end. We get the following status of the deque: [2, 3, 4, 5, 1]. 2. [2, 3, 4, 5, 1] β‡’ A = 2, B = 3. 3. [3, 4, 5, 1, 2] 4. [4, 5, 1, 2, 3] 5. [5, 1, 2, 3, 4] 6. [5, 2, 3, 4, 1] 7. [5, 3, 4, 1, 2] 8. [5, 4, 1, 2, 3] 9. [5, 1, 2, 3, 4] 10. [5, 2, 3, 4, 1] β‡’ A = 5, B = 2. Tags: data structures, implementation Correct Solution: ``` a, b = map(int, input().split()) A = list(map(int, input().split())) A.append(-1) B = [] Z = [] AN = [] x, y = A[0], A[1] for i in range(a - 1): Z.append((x, y)) if x > y: B.append(y) y = A[i + 2] else: B.append(x) x, y = y, A[i + 2] for i in range(b): w = int(input()) if w <= len(Z): AN.append(Z[w - 1]) else: w = w % len(B) AN.append((x, B[w - 1])) for W in AN: print(*W) ```
3,396
Provide tags and a correct Python 3 solution for this coding contest problem. Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque. We call this sequence of actions an operation. For example, if deque was [2, 3, 4, 5, 1], on the operation he will write B=3 to the beginning and A=2 to the end, so he will get [3, 4, 5, 1, 2]. The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him q queries. Each query consists of the singular number m_j (j = 1, 2, …, q). It is required for each query to answer which two elements he will pull out on the m_j-th operation. Note that the queries are independent and for each query the numbers A and B should be printed in the order in which they will be pulled out of the deque. Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides. Input The first line contains two integers n and q (2 ≀ n ≀ 10^5, 0 ≀ q ≀ 3 β‹… 10^5) β€” the number of elements in the deque and the number of queries. The second line contains n integers a_1, a_2, ..., a_n, where a_i (0 ≀ a_i ≀ 10^9) β€” the deque element in i-th position. The next q lines contain one number each, meaning m_j (1 ≀ m_j ≀ 10^{18}). Output For each teacher's query, output two numbers A and B β€” the numbers that Valeriy pulls out of the deque for the m_j-th operation. Examples Input 5 3 1 2 3 4 5 1 2 10 Output 1 2 2 3 5 2 Input 2 0 0 0 Output Note Consider all 10 steps for the first test in detail: 1. [1, 2, 3, 4, 5] β€” on the first operation, A and B are 1 and 2, respectively. So, 2 we write to the beginning of the deque, and 1 β€” to the end. We get the following status of the deque: [2, 3, 4, 5, 1]. 2. [2, 3, 4, 5, 1] β‡’ A = 2, B = 3. 3. [3, 4, 5, 1, 2] 4. [4, 5, 1, 2, 3] 5. [5, 1, 2, 3, 4] 6. [5, 2, 3, 4, 1] 7. [5, 3, 4, 1, 2] 8. [5, 4, 1, 2, 3] 9. [5, 1, 2, 3, 4] 10. [5, 2, 3, 4, 1] β‡’ A = 5, B = 2. Tags: data structures, implementation Correct Solution: ``` n, t = map(int, input().split()) a = list(map(int, input().split())) b, c = [], [] u = a[0] for v in a[1:]: b.append(u) if v > u: u, v = v, u c.append(v) for _ in range(t): x = int(input()) if x < n: print(b[x-1], a[x]) else: print(u, c[(x-1) % (n-1)]) ```
3,397
Provide tags and a correct Python 3 solution for this coding contest problem. Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque. We call this sequence of actions an operation. For example, if deque was [2, 3, 4, 5, 1], on the operation he will write B=3 to the beginning and A=2 to the end, so he will get [3, 4, 5, 1, 2]. The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him q queries. Each query consists of the singular number m_j (j = 1, 2, …, q). It is required for each query to answer which two elements he will pull out on the m_j-th operation. Note that the queries are independent and for each query the numbers A and B should be printed in the order in which they will be pulled out of the deque. Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides. Input The first line contains two integers n and q (2 ≀ n ≀ 10^5, 0 ≀ q ≀ 3 β‹… 10^5) β€” the number of elements in the deque and the number of queries. The second line contains n integers a_1, a_2, ..., a_n, where a_i (0 ≀ a_i ≀ 10^9) β€” the deque element in i-th position. The next q lines contain one number each, meaning m_j (1 ≀ m_j ≀ 10^{18}). Output For each teacher's query, output two numbers A and B β€” the numbers that Valeriy pulls out of the deque for the m_j-th operation. Examples Input 5 3 1 2 3 4 5 1 2 10 Output 1 2 2 3 5 2 Input 2 0 0 0 Output Note Consider all 10 steps for the first test in detail: 1. [1, 2, 3, 4, 5] β€” on the first operation, A and B are 1 and 2, respectively. So, 2 we write to the beginning of the deque, and 1 β€” to the end. We get the following status of the deque: [2, 3, 4, 5, 1]. 2. [2, 3, 4, 5, 1] β‡’ A = 2, B = 3. 3. [3, 4, 5, 1, 2] 4. [4, 5, 1, 2, 3] 5. [5, 1, 2, 3, 4] 6. [5, 2, 3, 4, 1] 7. [5, 3, 4, 1, 2] 8. [5, 4, 1, 2, 3] 9. [5, 1, 2, 3, 4] 10. [5, 2, 3, 4, 1] β‡’ A = 5, B = 2. Tags: data structures, implementation Correct Solution: ``` n, q = map(int,input().split()) l = list(map(int,input().split())) m = max(l) tab = [0] * 2*n for i in range(n): tab[i] = l[i] odp = [[0,0]] * n pocz = 0 kon = n - 1 for j in range(n): A = tab[pocz] B = tab[pocz + 1] odp[j] = [A, B] pocz += 1 kon += 1 tab[pocz] = max(A,B) tab[kon] = min(A,B) for i in range(q): query = int(input()) if query <= n: print(odp[query - 1][0], odp[query - 1][1]) else: print(m, tab[(query-2)%(n-1)+n+1]) ```
3,398
Provide tags and a correct Python 3 solution for this coding contest problem. Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque. We call this sequence of actions an operation. For example, if deque was [2, 3, 4, 5, 1], on the operation he will write B=3 to the beginning and A=2 to the end, so he will get [3, 4, 5, 1, 2]. The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him q queries. Each query consists of the singular number m_j (j = 1, 2, …, q). It is required for each query to answer which two elements he will pull out on the m_j-th operation. Note that the queries are independent and for each query the numbers A and B should be printed in the order in which they will be pulled out of the deque. Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides. Input The first line contains two integers n and q (2 ≀ n ≀ 10^5, 0 ≀ q ≀ 3 β‹… 10^5) β€” the number of elements in the deque and the number of queries. The second line contains n integers a_1, a_2, ..., a_n, where a_i (0 ≀ a_i ≀ 10^9) β€” the deque element in i-th position. The next q lines contain one number each, meaning m_j (1 ≀ m_j ≀ 10^{18}). Output For each teacher's query, output two numbers A and B β€” the numbers that Valeriy pulls out of the deque for the m_j-th operation. Examples Input 5 3 1 2 3 4 5 1 2 10 Output 1 2 2 3 5 2 Input 2 0 0 0 Output Note Consider all 10 steps for the first test in detail: 1. [1, 2, 3, 4, 5] β€” on the first operation, A and B are 1 and 2, respectively. So, 2 we write to the beginning of the deque, and 1 β€” to the end. We get the following status of the deque: [2, 3, 4, 5, 1]. 2. [2, 3, 4, 5, 1] β‡’ A = 2, B = 3. 3. [3, 4, 5, 1, 2] 4. [4, 5, 1, 2, 3] 5. [5, 1, 2, 3, 4] 6. [5, 2, 3, 4, 1] 7. [5, 3, 4, 1, 2] 8. [5, 4, 1, 2, 3] 9. [5, 1, 2, 3, 4] 10. [5, 2, 3, 4, 1] β‡’ A = 5, B = 2. Tags: data structures, implementation Correct Solution: ``` # import sys # input = sys.stdin.readline n,queries = list(map(int,input().split())) l = list(map(int,input().split())) if(queries==0): exit() maxval = max(l) pairs = [] count = 0 f = l[0] secix = 1 while(f!=maxval): # print(l) count+=1 f = l[0] s = l[secix] pairs.append([f,s]) f,s= max(f,s), min(f,s) l[0] = f l.append(s) secix+=1 # print(secix) l = [l[0]]+l[secix:] # print(l) for i in range(n-1): pairs.append([maxval,l[1+i]]) # print(pairs) for m in range(queries): q = int(input()) if(q<=count): print(str(pairs[q-1][0]),str(pairs[q-1][1])) else: q-=(count+1) pos = count+(q%(n-1)) print(str(pairs[pos][0]),str(pairs[pos][1])) ```
3,399