message stringlengths 2 44.5k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 276 109k | cluster float64 23 23 | __index_level_0__ int64 552 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given two segments s1 and s2, print the coordinate of the cross point of them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
* The given segments have a cross point and are not in parallel.
Input
The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3
Output
For each query, print the coordinate of the cross point. The output values should be in a decimal fraction with an error less than 0.00000001.
Example
Input
3
0 0 2 0 1 1 1 -1
0 0 1 1 0 1 1 0
0 0 1 1 1 0 0 1
Output
1.0000000000 0.0000000000
0.5000000000 0.5000000000
0.5000000000 0.5000000000
Submitted Solution:
```
q = int(input())
for i in range(q):
a,b,c,d,e,f,g,h = [int(i) for i in input().split()]
A = a*d-b*c
B = e*h-f*g
C = d-b
D = c-a
E = f-h
F = e-g
det = C*F - D*E
print((A*D + B*E)/det,(A*F + B*C)/det)
``` | instruction | 0 | 96,929 | 23 | 193,858 |
No | output | 1 | 96,929 | 23 | 193,859 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given two segments s1 and s2, print the coordinate of the cross point of them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
* The given segments have a cross point and are not in parallel.
Input
The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3
Output
For each query, print the coordinate of the cross point. The output values should be in a decimal fraction with an error less than 0.00000001.
Example
Input
3
0 0 2 0 1 1 1 -1
0 0 1 1 0 1 1 0
0 0 1 1 1 0 0 1
Output
1.0000000000 0.0000000000
0.5000000000 0.5000000000
0.5000000000 0.5000000000
Submitted Solution:
```
import math
EPS=1e-10
#点类
class Point():
def __init__(self,x,y):
self.x=x
self.y=y
def __sub__(self,p):
return Point(self.x - p.x, self.y - p.y);
def __add__(self,p):
return Point(self.x + p.x, self.y + p.y)
def __mul__(self,a): #a: scalar
return Point(self.x * a, self.y * a)
def __truediv__(self,a): #a: scalar
return Point(self.x / a, self.y / a)
def __str__(self):
return str(self.x)+','+str(self.y)
def __repr__(self):
return 'Point('+str(self.x)+','+str(self.y)+')'
def __lt__(self, other):
if self.y-other.y==0:
return self.x<other.x
else:
return self.y<other.y
def __eq__(self, other):
return abs(self.x-other.x)<EPS and abs(self.y-other.y)<EPS
# 线段类
class Segment():
def __init__(self,p1, p2):
self.p1=p1
self.p2=p2
def __str__(self):
return 'segment:('+str(self.p1)+';'+str(self.p2)+')'
def __repr__(self):
return 'segment:('+str(self.p1)+';'+str(self.p2)+')'
class Circle():
def __init__(self,c, r):
self.c=c
self.r=r
def __str__(self):
return 'Circle:(center point: '+str(self.c)+'; radius: '+str(self.r)+')'
def __repr__(self):
return 'Circle:(center point: '+str(self.c)+'; radius: '+str(self.r)+')'
#定义多边形
class Polygon():
def __init__(self,ps=[]):
self.ps=ps
self.size=len(ps)
def __getitem__(self, i):#iter override
return self.ps[i]
def __setitem__(self,i,p):
self.ps[i]=p
def __iter__(self):
return self.ps
def addpoint(self,i,p):
self.ps.insert(i,p)
self.size+=1
def delpoint(self,i):
self.size-=1
return self.ps.pop(i)
def sortYX(self):
self.ps.sort()
#self.ps.sort(key=attrgetter('y','x'))
def __str__(self):
return 'Polygon:'+str(tuple(self.ps))
def __repr__(self):
return 'Polygon:'+str(tuple(self.ps))
def __len__(self):
return len(self.ps)
def __eq__(self, other):
return self.ps==other.ps
def draw(self):
turtle.screensize(800,800,"black")
#turtle.setup(width=0.9,height=0.9)
turtle.title("Polygon convex hull")
turtle.setworldcoordinates(-400,-400,400,400)
#print(turtle.screensize())
#mywin = turtle.Screen()
#mywin.
t=turtle.Turtle()
#mywin=turtle.Screen()
t.pencolor("red")
for pt in self.ps:
t.goto(pt.x,pt.y)
t.dot(10,'white')
#***************************点、向量****************************
#向量的模的平方
def norm(p):
return p.x * p.x + p.y * p.y
#向量P的长度
def length(p):
return math.sqrt(p.x * p.x + p.y * p.y)
# 向量的(点)内积, dot(a,b)=|a|*|b|*cos(a,b) (从a,到b的角)
# =============================================================================
# r=dot(a,b),得到矢量a和b的点积,如果两个矢量都非零矢量
# r<0:两矢量夹角为钝角;
# r=0:两矢量夹角为直角;
# r>0:两矢量夹角为锐角
# =============================================================================
def dot(a, b) :
return a.x * b.x + a.y * b.y
# =============================================================================
# # 向量的(叉)外积 cross(a,b)=|a||b|*sin(a,b) (从a,到b的角)由a,b构成的平行四边的面积
# r=cross(a,b),得到向量a和向量b的叉积
# r>0:b在矢量a的逆时针方向;
# r=0:a,b 平行共线;
# r<0:b在向量a的顺时针方向
# =============================================================================
def cross( a, b) :
return a.x * b.y - a.y * b.x
# 点p在线段s上的投影
def project(s, p):
base = s.p2 - s.p1
r = dot(p - s.p1, base) / norm(base)
return s.p1 + base * r
# 点a到点b的距离
def getDistance(a, b) :
return length(a - b)
# 线段l和点p的距离
def getDistanceLP(l, p) :
return abs( cross(l.p2 - l.p1, p - l.p1) / length(l.p2 - l.p1) )
#getDistanceLP(s3, p7)
#线段s与点p的距离
def getDistanceSP(s, p) :
if (dot(s.p2 - s.p1, p - s.p1) < 0.0):
return length(p - s.p1)
if (dot(s.p1 - s.p2, p - s.p2) < 0.0):
return length(p - s.p2)
return getDistanceLP(s, p)
#print(getDistanceLP(s3, Point(5,5)))
#print(getDistanceSP(s3, Point(5,5)))
#*************************线段********************************/
# 线段s1,s2是否正交 <==> 内积为0
def isOrthogonalSG(s1, s2) :
return abs(dot(s1.p2 - s1.p1, s2.p2 - s2.p1))<EPS
# 线段s1,s2是否平行 <==> 叉积为0
def isParallelLN(s1,s2) :
return abs(cross(s1.p2 - s1.p1, s2.p2 - s2.p1))<0
# 逆时针方向ccw(Counter-Clockwise)
COUNTER_CLOCKWISE = 1;
CLOCKWISE = -1;
ONLINE_BACK = -2;
ONLINE_FRONT = 2;
ON_SEGMENT = 0;
def ccw(p0, p1, p2) :
a = p1 - p0
b = p2 - p0
if (cross(a, b) > EPS):
return COUNTER_CLOCKWISE
if (cross(a, b) < -EPS):
return CLOCKWISE
if (dot(a, b) < -EPS):
return ONLINE_BACK
if (norm(a) < norm(b)):
return ONLINE_FRONT
return ON_SEGMENT;
def toleft(p0,p1,p2):
a = p1 - p0
b = p2 - p0
tmp=cross(a,b)
if tmp > EPS:
return 1
elif abs(tmp)<EPS and norm(a)<=norm(b):
return 2 #共线,p2在p0p1的右延长线上
elif abs(tmp)<EPS and norm(a)>norm(b):
return -2 #共线,p2在p0p1的left延长线上
else:
return -1
#以线段s为对称轴与点p成线对称的点
def reflect(s, p) :
return p + (project(s, p) - p) * 2.0
#判断线段s1和s2是否相交
def intersectSG(s1, s2) :
return intersectP4(s1.p1, s1.p2, s2.p1, s2.p2)
# 线段s1和线段s2的距离
def getDistanceSG(s1, s2) :
# 相交
if (intersectSG(s1, s2)):
return 0.0
return min(getDistanceSP(s1, s2.p1), getDistanceSP(s1, s2.p2),\
getDistanceSP(s2, s1.p1), getDistanceSP(s2, s1.p2))
# 判断线段p1p2和线段p3p4是否相交
def intersectP4(p1, p2, p3, p4) :
return ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0 and \
ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0
# 线段s1与线段s2的交点
def getCrossPoint(s1,s2) :
base = s2.p2 - s2.p1;
d1 = abs(cross(base, s1.p1 - s2.p1));
d2 = abs(cross(base, s1.p2 - s2.p1));
t = d1 / (d1 + d2);
return s1.p1 + (s1.p2 - s1.p1) * t;
q=int(input())
for i in range(0,q):
s= [int(x) for x in input().split()]
p0=Point(s[0],s[1])
p1=Point(s[2],s[3])
p2=Point(s[4],s[5])
p3=Point(s[6],s[7])
s1=Segment(p0,p1)
s2=Segment(p2,p3)
rt=getCrossPoint(s1,s2)
print("{:.12f},{:.12f}".format(rt.x,rt.y))
``` | instruction | 0 | 96,930 | 23 | 193,860 |
No | output | 1 | 96,930 | 23 | 193,861 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given two segments s1 and s2, print the coordinate of the cross point of them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
* The given segments have a cross point and are not in parallel.
Input
The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3
Output
For each query, print the coordinate of the cross point. The output values should be in a decimal fraction with an error less than 0.00000001.
Example
Input
3
0 0 2 0 1 1 1 -1
0 0 1 1 0 1 1 0
0 0 1 1 1 0 0 1
Output
1.0000000000 0.0000000000
0.5000000000 0.5000000000
0.5000000000 0.5000000000
Submitted Solution:
```
import math
EPS=1e-14
#点类
class Point():
def __init__(self,x,y):
self.x=x
self.y=y
def __sub__(self,p):
return Point(self.x - p.x, self.y - p.y);
def __add__(self,p):
return Point(self.x + p.x, self.y + p.y)
def __mul__(self,a): #a: scalar
return Point(self.x * a, self.y * a)
def __truediv__(self,a): #a: scalar
return Point(self.x / a, self.y / a)
def __str__(self):
return str(self.x)+','+str(self.y)
def __repr__(self):
return 'Point('+str(self.x)+','+str(self.y)+')'
def __lt__(self, other):
if self.y-other.y==0:
return self.x<other.x
else:
return self.y<other.y
def __eq__(self, other):
return abs(self.x-other.x)<EPS and abs(self.y-other.y)<EPS
# 线段类
class Segment():
def __init__(self,p1, p2):
self.p1=p1
self.p2=p2
def __str__(self):
return 'segment:('+str(self.p1)+';'+str(self.p2)+')'
def __repr__(self):
return 'segment:('+str(self.p1)+';'+str(self.p2)+')'
class Circle():
def __init__(self,c, r):
self.c=c
self.r=r
def __str__(self):
return 'Circle:(center point: '+str(self.c)+'; radius: '+str(self.r)+')'
def __repr__(self):
return 'Circle:(center point: '+str(self.c)+'; radius: '+str(self.r)+')'
#定义多边形
class Polygon():
def __init__(self,ps=[]):
self.ps=ps
self.size=len(ps)
def __getitem__(self, i):#iter override
return self.ps[i]
def __setitem__(self,i,p):
self.ps[i]=p
def __iter__(self):
return self.ps
def addpoint(self,i,p):
self.ps.insert(i,p)
self.size+=1
def delpoint(self,i):
self.size-=1
return self.ps.pop(i)
def sortYX(self):
self.ps.sort()
#self.ps.sort(key=attrgetter('y','x'))
def __str__(self):
return 'Polygon:'+str(tuple(self.ps))
def __repr__(self):
return 'Polygon:'+str(tuple(self.ps))
def __len__(self):
return len(self.ps)
def __eq__(self, other):
return self.ps==other.ps
def draw(self):
turtle.screensize(800,800,"black")
#turtle.setup(width=0.9,height=0.9)
turtle.title("Polygon convex hull")
turtle.setworldcoordinates(-400,-400,400,400)
#print(turtle.screensize())
#mywin = turtle.Screen()
#mywin.
t=turtle.Turtle()
#mywin=turtle.Screen()
t.pencolor("red")
for pt in self.ps:
t.goto(pt.x,pt.y)
t.dot(10,'white')
#***************************点、向量****************************
#向量的模的平方
def norm(p):
return p.x * p.x + p.y * p.y
#向量P的长度
def length(p):
return math.sqrt(p.x * p.x + p.y * p.y)
# 向量的(点)内积, dot(a,b)=|a|*|b|*cos(a,b) (从a,到b的角)
# =============================================================================
# r=dot(a,b),得到矢量a和b的点积,如果两个矢量都非零矢量
# r<0:两矢量夹角为钝角;
# r=0:两矢量夹角为直角;
# r>0:两矢量夹角为锐角
# =============================================================================
def dot(a, b) :
return a.x * b.x + a.y * b.y
# =============================================================================
# # 向量的(叉)外积 cross(a,b)=|a||b|*sin(a,b) (从a,到b的角)由a,b构成的平行四边的面积
# r=cross(a,b),得到向量a和向量b的叉积
# r>0:b在矢量a的逆时针方向;
# r=0:a,b 平行共线;
# r<0:b在向量a的顺时针方向
# =============================================================================
def cross( a, b) :
return a.x * b.y - a.y * b.x
# 点p在线段s上的投影
def project(s, p):
base = s.p2 - s.p1
r = dot(p - s.p1, base) / norm(base)
return s.p1 + base * r
# 点a到点b的距离
def getDistance(a, b) :
return length(a - b)
# 线段l和点p的距离
def getDistanceLP(l, p) :
return abs( cross(l.p2 - l.p1, p - l.p1) / length(l.p2 - l.p1) )
#getDistanceLP(s3, p7)
#线段s与点p的距离
def getDistanceSP(s, p) :
if (dot(s.p2 - s.p1, p - s.p1) < 0.0):
return length(p - s.p1)
if (dot(s.p1 - s.p2, p - s.p2) < 0.0):
return length(p - s.p2)
return getDistanceLP(s, p)
#print(getDistanceLP(s3, Point(5,5)))
#print(getDistanceSP(s3, Point(5,5)))
#*************************线段********************************/
# 线段s1,s2是否正交 <==> 内积为0
def isOrthogonalSG(s1, s2) :
return abs(dot(s1.p2 - s1.p1, s2.p2 - s2.p1))<EPS
# 线段s1,s2是否平行 <==> 叉积为0
def isParallelLN(s1,s2) :
return abs(cross(s1.p2 - s1.p1, s2.p2 - s2.p1))<0
# 逆时针方向ccw(Counter-Clockwise)
COUNTER_CLOCKWISE = 1;
CLOCKWISE = -1;
ONLINE_BACK = -2;
ONLINE_FRONT = 2;
ON_SEGMENT = 0;
def ccw(p0, p1, p2) :
a = p1 - p0
b = p2 - p0
if (cross(a, b) > EPS):
return COUNTER_CLOCKWISE
if (cross(a, b) < -EPS):
return CLOCKWISE
if (dot(a, b) < -EPS):
return ONLINE_BACK
if (norm(a) < norm(b)):
return ONLINE_FRONT
return ON_SEGMENT;
def toleft(p0,p1,p2):
a = p1 - p0
b = p2 - p0
tmp=cross(a,b)
if tmp > EPS:
return 1
elif abs(tmp)<EPS and norm(a)<=norm(b):
return 2 #共线,p2在p0p1的右延长线上
elif abs(tmp)<EPS and norm(a)>norm(b):
return -2 #共线,p2在p0p1的left延长线上
else:
return -1
#以线段s为对称轴与点p成线对称的点
def reflect(s, p) :
return p + (project(s, p) - p) * 2.0
#判断线段s1和s2是否相交
def intersectSG(s1, s2) :
return intersectP4(s1.p1, s1.p2, s2.p1, s2.p2)
# 线段s1和线段s2的距离
def getDistanceSG(s1, s2) :
# 相交
if (intersectSG(s1, s2)):
return 0.0
return min(getDistanceSP(s1, s2.p1), getDistanceSP(s1, s2.p2),\
getDistanceSP(s2, s1.p1), getDistanceSP(s2, s1.p2))
# 判断线段p1p2和线段p3p4是否相交
def intersectP4(p1, p2, p3, p4) :
return ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0 and \
ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0
# 线段s1与线段s2的交点
def getCrossPoint(s1,s2) :
base = s2.p2 - s2.p1;
d1 = abs(cross(base, s1.p1 - s2.p1));
d2 = abs(cross(base, s1.p2 - s2.p1));
if d1+d2==0:
return s2.p1
t = d1 / (d1 + d2);
return s1.p1 + (s1.p2 - s1.p1) * t;
q=int(input())
for i in range(0,q):
s= [int(x) for x in input().split()]
p0=Point(s[0],s[1])
p1=Point(s[2],s[3])
p2=Point(s[4],s[5])
p3=Point(s[6],s[7])
s1=Segment(p0,p1)
s2=Segment(p2,p3)
rt=getCrossPoint(s1,s2)
print("{:.12f},{:.12f}".format(rt.x,rt.y))
``` | instruction | 0 | 96,931 | 23 | 193,862 |
No | output | 1 | 96,931 | 23 | 193,863 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For given two segments s1 and s2, print the coordinate of the cross point of them.
s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3.
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xpi, ypi ≤ 10000
* p0 ≠ p1 and p2 ≠ p3.
* The given segments have a cross point and are not in parallel.
Input
The entire input looks like:
q (the number of queries)
1st query
2nd query
...
qth query
Each query consists of integer coordinates of end points of s1 and s2 in the following format:
xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3
Output
For each query, print the coordinate of the cross point. The output values should be in a decimal fraction with an error less than 0.00000001.
Example
Input
3
0 0 2 0 1 1 1 -1
0 0 1 1 0 1 1 0
0 0 1 1 1 0 0 1
Output
1.0000000000 0.0000000000
0.5000000000 0.5000000000
0.5000000000 0.5000000000
Submitted Solution:
```
def cross(c1, c2):
return c1.real * c2.imag - c1.imag * c2.real
def print_cross_point(p1, p2, p3, p4):
# p1 and p2 are end points of a segment.
# p3 and p4 are end points of the other segment.
base = p4 - p3
hypo1 = p1 - p3
hypo2 = p2 - p3
d1 = abs(cross(base, hypo1)) / abs(base)
d2 = abs(cross(base, hypo2)) / abs(base)
cp = p1 + d1 / (d1 + d2) * (p2 - p1)
print("{0:.10f}, {1:.10f}".format(cp.real, cp.imag))
import sys
file_input = sys.stdin
sq = file_input.readline()
for line in file_input:
x_p0, y_p0, x_p1, y_p1, x_p2, y_p2, x_p3, y_p3 = map(int, line.split())
p0 = x_p0 + y_p0 * 1j
p1 = x_p1 + y_p1 * 1j
p2 = x_p2 + y_p2 * 1j
p3 = x_p3 + y_p3 * 1j
print_cross_point(p0, p1, p2, p3)
``` | instruction | 0 | 96,932 | 23 | 193,864 |
No | output | 1 | 96,932 | 23 | 193,865 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n points in k-dimensional space. Let the distance between two points a_x and a_y be ∑ _{i = 1}^{k} |a_{x, i} - a_{y, i}| (it is also known as Manhattan distance).
You have to process q queries of the following two types:
* 1 i b_1 b_2 ... b_k — set i-th element of a to the point (b_1, b_2, ..., b_k);
* 2 l r — find the maximum distance between two points a_i and a_j, where l ≤ i, j ≤ r.
Input
The first line contains two numbers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 5) — the number of elements in a and the number of dimensions of the space, respectively.
Then n lines follow, each containing k integers a_{i, 1}, a_{i, 2}, ..., a_{i, k} (-10^6 ≤ a_{i, j} ≤ 10^6) — the coordinates of i-th point.
The next line contains one integer q (1 ≤ q ≤ 2 ⋅ 10^5) — the number of queries.
Then q lines follow, each denoting a query. There are two types of queries:
* 1 i b_1 b_2 ... b_k (1 ≤ i ≤ n, -10^6 ≤ b_j ≤ 10^6) — set i-th element of a to the point (b_1, b_2, ..., b_k);
* 2 l r (1 ≤ l ≤ r ≤ n) — find the maximum distance between two points a_i and a_j, where l ≤ i, j ≤ r.
There is at least one query of the second type.
Output
Print the answer for each query of the second type.
Example
Input
5 2
1 2
2 3
3 4
4 5
5 6
7
2 1 5
2 1 3
2 3 5
1 5 -1 -2
2 1 5
1 4 -1 -2
2 1 5
Output
8
4
4
12
10
Submitted Solution:
```
a = [0]
for i in range(20000000):
a.append(i)
``` | instruction | 0 | 96,972 | 23 | 193,944 |
No | output | 1 | 96,972 | 23 | 193,945 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n points in k-dimensional space. Let the distance between two points a_x and a_y be ∑ _{i = 1}^{k} |a_{x, i} - a_{y, i}| (it is also known as Manhattan distance).
You have to process q queries of the following two types:
* 1 i b_1 b_2 ... b_k — set i-th element of a to the point (b_1, b_2, ..., b_k);
* 2 l r — find the maximum distance between two points a_i and a_j, where l ≤ i, j ≤ r.
Input
The first line contains two numbers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 5) — the number of elements in a and the number of dimensions of the space, respectively.
Then n lines follow, each containing k integers a_{i, 1}, a_{i, 2}, ..., a_{i, k} (-10^6 ≤ a_{i, j} ≤ 10^6) — the coordinates of i-th point.
The next line contains one integer q (1 ≤ q ≤ 2 ⋅ 10^5) — the number of queries.
Then q lines follow, each denoting a query. There are two types of queries:
* 1 i b_1 b_2 ... b_k (1 ≤ i ≤ n, -10^6 ≤ b_j ≤ 10^6) — set i-th element of a to the point (b_1, b_2, ..., b_k);
* 2 l r (1 ≤ l ≤ r ≤ n) — find the maximum distance between two points a_i and a_j, where l ≤ i, j ≤ r.
There is at least one query of the second type.
Output
Print the answer for each query of the second type.
Example
Input
5 2
1 2
2 3
3 4
4 5
5 6
7
2 1 5
2 1 3
2 3 5
1 5 -1 -2
2 1 5
1 4 -1 -2
2 1 5
Output
8
4
4
12
10
Submitted Solution:
```
import sys
import threading
#import resource
#resource.setrlimit(resource.RLIMIT_STACK, (2**29,-1))
#resource.setrlimit(resource.RLIMIT_STACK, (resource.RLIM_INFINITY, resource.RLIM_INFINITY))
#sys.setrecursionlimit(200000)
#thread.stack_size(10**8)
def f(n):
if (n%1000 == 0):
print(n)
#sys.setrecursionlimit(sys.getrecursionlimit() + 1)
f(n+1)
def main():
f(1)
if __name__ == "__main__":
sys.setrecursionlimit(200000)
threading.stack_size(102400000)
thread = threading.Thread(target=main)
thread.start()
``` | instruction | 0 | 96,973 | 23 | 193,946 |
No | output | 1 | 96,973 | 23 | 193,947 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n points in k-dimensional space. Let the distance between two points a_x and a_y be ∑ _{i = 1}^{k} |a_{x, i} - a_{y, i}| (it is also known as Manhattan distance).
You have to process q queries of the following two types:
* 1 i b_1 b_2 ... b_k — set i-th element of a to the point (b_1, b_2, ..., b_k);
* 2 l r — find the maximum distance between two points a_i and a_j, where l ≤ i, j ≤ r.
Input
The first line contains two numbers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 5) — the number of elements in a and the number of dimensions of the space, respectively.
Then n lines follow, each containing k integers a_{i, 1}, a_{i, 2}, ..., a_{i, k} (-10^6 ≤ a_{i, j} ≤ 10^6) — the coordinates of i-th point.
The next line contains one integer q (1 ≤ q ≤ 2 ⋅ 10^5) — the number of queries.
Then q lines follow, each denoting a query. There are two types of queries:
* 1 i b_1 b_2 ... b_k (1 ≤ i ≤ n, -10^6 ≤ b_j ≤ 10^6) — set i-th element of a to the point (b_1, b_2, ..., b_k);
* 2 l r (1 ≤ l ≤ r ≤ n) — find the maximum distance between two points a_i and a_j, where l ≤ i, j ≤ r.
There is at least one query of the second type.
Output
Print the answer for each query of the second type.
Example
Input
5 2
1 2
2 3
3 4
4 5
5 6
7
2 1 5
2 1 3
2 3 5
1 5 -1 -2
2 1 5
1 4 -1 -2
2 1 5
Output
8
4
4
12
10
Submitted Solution:
```
n, k = map(int, input().split())
points = [None] + [tuple(map(int, input().split())) for i in range(n)]
c = []
segTree = []
def cal(point, idx):
global k
ret = 0
for i in range(k):
ret += points[point][i] * c[idx][i]
return ret
def cal2(point, idx):
global k
ret = 0
for i in range(k):
ret += point[i] * c[idx][i]
return ret
def buildSegTree(i, left, right):
global points, c
if left == right:
return {'l':left, 'r':right, 'max':cal(left, i), 'min':cal(left, i), 'lc':None, 'rc':None}
else:
mid = (left + right) >> 1
lc = buildSegTree(i, left, mid)
rc = buildSegTree(i, mid + 1, right)
return {'l':left, 'r':right, 'max':max(lc['max'], rc['max']),
'min':min(lc['min'], rc['min']), 'lc':lc, 'rc':rc}
for i in range(2 ** k):
tmp = []
for j in range(k):
tmp.append(1 if (i & 1) else -1)
i >>= 1
c.append(tmp)
# print(c)
for i in range(2 ** k):
segTree.append(buildSegTree(i, 1, n))
# print(segTree[0]) # debug
def change(seg, idx, newval):
if seg['l'] == seg['r']:
seg['max'] = newval
seg['min'] = newval
else:
if idx <= ((seg['l'] + seg['r']) >> 1):
change(seg['lc'], idx, newval)
else:
change(seg['rc'], idx, newval)
seg['max'] = max(seg['lc']['max'], seg['rc']['max'])
seg['min'] = min(seg['lc']['min'], seg['rc']['min'])
inf = 10 ** 7
def maxmin(seg, l, r):
if l == seg['l'] and r == seg['r']:
return (seg['max'], seg['min'])
r1, r2 = -inf, inf
mid = (seg['l'] + seg['r']) >> 1
if l <= mid:
tup = maxmin(seg['lc'], l, mid)
r1 = max(tup[0], r1)
r2 = min(tup[1], r2)
if r > mid:
tup = maxmin(seg['rc'], mid + 1, r)
r1 = max(tup[0], r1)
r2 = min(tup[1], r2)
return (r1, r2)
ans = []
q = int(input())
for i in range(q):
query = list(map(int, input().split()))
if query[0] == 1:
for j in range(2 ** k):
change(segTree[j], query[1], cal2(query[2:], j))
# print(segTree[0]) # debug
else:
res = [maxmin(segTree[j], query[1], query[2]) for j in range(2 ** k)]
ans.append(max([k[0] - k[1] for k in res]))
print(*ans, sep='\n')
``` | instruction | 0 | 96,974 | 23 | 193,948 |
No | output | 1 | 96,974 | 23 | 193,949 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n points in k-dimensional space. Let the distance between two points a_x and a_y be ∑ _{i = 1}^{k} |a_{x, i} - a_{y, i}| (it is also known as Manhattan distance).
You have to process q queries of the following two types:
* 1 i b_1 b_2 ... b_k — set i-th element of a to the point (b_1, b_2, ..., b_k);
* 2 l r — find the maximum distance between two points a_i and a_j, where l ≤ i, j ≤ r.
Input
The first line contains two numbers n and k (1 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ k ≤ 5) — the number of elements in a and the number of dimensions of the space, respectively.
Then n lines follow, each containing k integers a_{i, 1}, a_{i, 2}, ..., a_{i, k} (-10^6 ≤ a_{i, j} ≤ 10^6) — the coordinates of i-th point.
The next line contains one integer q (1 ≤ q ≤ 2 ⋅ 10^5) — the number of queries.
Then q lines follow, each denoting a query. There are two types of queries:
* 1 i b_1 b_2 ... b_k (1 ≤ i ≤ n, -10^6 ≤ b_j ≤ 10^6) — set i-th element of a to the point (b_1, b_2, ..., b_k);
* 2 l r (1 ≤ l ≤ r ≤ n) — find the maximum distance between two points a_i and a_j, where l ≤ i, j ≤ r.
There is at least one query of the second type.
Output
Print the answer for each query of the second type.
Example
Input
5 2
1 2
2 3
3 4
4 5
5 6
7
2 1 5
2 1 3
2 3 5
1 5 -1 -2
2 1 5
1 4 -1 -2
2 1 5
Output
8
4
4
12
10
Submitted Solution:
```
a = [0]
for i in range(50000000):
a.append(i)
``` | instruction | 0 | 96,975 | 23 | 193,950 |
No | output | 1 | 96,975 | 23 | 193,951 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 ≤ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 ≤ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image> | instruction | 0 | 97,004 | 23 | 194,008 |
Tags: brute force, strings
Correct Solution:
```
if __name__ == '__main__':
cin = lambda: [*map(int, input().split())] #一行一行读
n, m = cin()
se = set()
x = [tuple(sorted(cin())) for _ in range(m)]
for e in x:
se.add((e[0] - 1, e[1] - 1))
for i in range(1, n):
if n % i != 0:
continue
ok = True
for e in se:
if tuple(sorted([(e[0] + i) % n, (e[1] + i) % n])) not in se:
# print(i, e, tuple([(e[0] + i) % n, (e[1] + i) % n]))
ok = False
break
if ok:
print('Yes')
exit(0)
print('No')
``` | output | 1 | 97,004 | 23 | 194,009 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 ≤ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 ≤ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image> | instruction | 0 | 97,005 | 23 | 194,010 |
Tags: brute force, strings
Correct Solution:
```
"""
Satwik_Tiwari ;) .
30th july , 2020 - Thursday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter # Counter(list) return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
#If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
#If the element is already present in the list,
# the right most position where element has to be inserted is returned
#==============================================================================================
#fast I/O region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
#===============================================================================================
#some shortcuts
mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n") #as stdout.write always print sring.
def testcase(t):
for p in range(t):
solve()
def printlist(a) :
for p in range(0,len(a)):
out(str(a[p]) + ' ')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(a,b):
ans = 1
while(b>0):
if(b%2==1):
ans*=a
a*=a
b//=2
return ans
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
#===============================================================================================
# code here ;))
def solve():
n,m = sep()
div =[]
for i in range(1,floor(n**(0.5))+1):
if(n%i==0):
div.append(i)
if((n//i)!=n and (n//i)!=i):
div.append(n//i)
graph = set()
for i in range(m):
a,b=sep()
a-=1
b-=1
a,b = min(a,b),max(a,b)
graph.add((a,b))
for i in range(len(div)):
f = True
for j in graph:
a,b = (j[0]+div[i])%n , (j[1]+div[i])%n
a,b = min(a,b),max(a,b)
if((a,b) not in graph):
f = False
break
if(f):
print('Yes')
return
print('No')
testcase(1)
# testcase(int(inp()))
``` | output | 1 | 97,005 | 23 | 194,011 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 ≤ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 ≤ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image> | instruction | 0 | 97,006 | 23 | 194,012 |
Tags: brute force, strings
Correct Solution:
```
nz = [int(x) for x in input().split()]
edges = set()
divisors = set()
for x in range (0,nz[1]):
uv = [ y for y in input().split()]
edges.add(uv[0] + ' ' + uv[1])
for x in range(1,nz[0]):
if nz[0] % x == 0:
divisors.add(x)
flag = 0
for y in divisors:
flag = 0
for x in edges:
u = (int(x.split()[0]) + y) % nz[0]
v = (int(x.split()[1]) + y) % nz[0]
if u == 0:
u = nz[0]
if v == 0:
v = nz[0]
if str(u) + ' ' + str(v) not in edges:
if str(v) + ' ' + str(u) not in edges:
flag = 1
break
if flag == 0:
print("Yes")
break
if flag == 1:
print("No")
``` | output | 1 | 97,006 | 23 | 194,013 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 ≤ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 ≤ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image> | instruction | 0 | 97,007 | 23 | 194,014 |
Tags: brute force, strings
Correct Solution:
```
def gcd(x,y):
while y:
x,y = y,x%y
return x
def lcm(a,b): return (a*b)//gcd(a,b)
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
kk=lambda:map(int,input().split())
k2=lambda:map(lambda x:int(x)-1, input().split())
ll=lambda:list(kk())
n,m=kk()
nodes = [[] for _ in range(n)]
for _ in range(m):
n1,n2=k2()
nodes[n1].append((n2-n1)%n)
nodes[n2].append((n1-n2)%n)
seen = {}
nextv=0
lists = []
node2,used = [0]*n, [False]*n
for i,no in enumerate(nodes):
t = tuple(sorted(no))
if not t in seen:
seen[t],nextv = nextv,nextv+1
lists.append([])
lists[seen[t]].append(i)
node2[i] = seen[t]
lists.sort(key=len)
valids = set()
for i in range(nextv-1):
cl = lists[i]
n0 = cl[0]
continueing = True
while continueing:
continueing = False
for j in range(1,len(cl)):
if used[cl[j]]: continue
dist = cl[j]-n0
if n%dist != 0: continue
for k in range(n0, n+n0, dist):
k = k%n
if used[k] or node2[k] != node2[n0]:
break
else:
# we found a working one.
valids.add(dist)
for k in range(n0, n+n0, dist):
k = k%n
used[k]=True
cl = [x for x in cl if (x-n0)%dist != 0]
n0 = cl[0] if cl else 0
continueing= True
break
if len(cl) > 0:
print("NO")
exit()
lc =1
for value in valids:
lc = lcm(lc, value)
print("YES" if lc< n else "NO")
``` | output | 1 | 97,007 | 23 | 194,015 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 ≤ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 ≤ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image> | instruction | 0 | 97,008 | 23 | 194,016 |
Tags: brute force, strings
Correct Solution:
```
import sys
import collections
# see tutorial at https://codeforces.com/blog/entry/66878
n, m = map(int, input().split())
# segment length -> start
segs = set()
for _ in range(m):
start, end = map(int, input().split())
segs.add((start-1, end-1))
def get_divisors(n):
"""
:param n:
:return: divisors of n excluding n itself
"""
divisors = []
for i in range(1, n):
if n % i == 0:
divisors.append(i)
return divisors
divisors = get_divisors(n)
# try out all divisors as the total (actual) rotation period, not just the rotation period for a subset of segments
for k in divisors:
for sega, segb in segs:
if ((sega + k) % n, (segb + k) % n) not in segs and ((segb + k) % n, (sega + k) % n) not in segs:
# this k doesn't work
break
else:
print('Yes')
sys.exit()
print('No')
``` | output | 1 | 97,008 | 23 | 194,017 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 ≤ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 ≤ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image> | instruction | 0 | 97,009 | 23 | 194,018 |
Tags: brute force, strings
Correct Solution:
```
import sys
def No():
print('No')
sys.exit()
def divi(n):
res = [1]
for i in range(2, int(n**0.5)+1):
if n % i == 0:
res.append(i)
if i != n // i:
res.append(n//i)
return res
N, M = map(int, input().split())
DN = divi(N)
dis = [set() for _ in range(N//2 + 1)]
for i in range(M):
a, b = map(lambda x:int(x) - 1, sys.stdin.readline().split())
fn, ln = (a - b)%N, (b - a)%N
if fn < ln:
dis[fn].add(b)
elif ln < fn:
dis[ln].add(a)
else:
dis[fn].add(a)
dis[fn].add(b)
for dn in DN:
for D in dis:
if not D:
continue
for d in D:
if (d+dn)%N not in D:
break
else:
continue
break
else:
print('Yes')
sys.exit()
No()
``` | output | 1 | 97,009 | 23 | 194,019 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 ≤ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 ≤ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image> | instruction | 0 | 97,010 | 23 | 194,020 |
Tags: brute force, strings
Correct Solution:
```
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def main():
n, m = map(int, input().split())
S = set()
for i in range(m):
a, b = map(int, input().split())
a, b = a-1, b-1
if a > b:
a, b = b, a
S.add((a, b))
def make_divisors(n):
divisors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n//i)
#divisors.sort(reverse=True)
return divisors
D = make_divisors(n)
for d in D:
if d == n:
continue
T = set()
flag = True
for a, b in S:
na = (a+d)%n
nb = (b+d)%n
if na > nb:
na, nb = nb, na
if (na, nb) not in S:
flag = False
break
T.add((na, nb))
if not flag:
continue
for a, b in S:
if (a, b) not in T:
break
else:
print('Yes')
exit()
else:
print('No')
if __name__ == '__main__':
main()
``` | output | 1 | 97,010 | 23 | 194,021 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 ≤ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 ≤ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image> | instruction | 0 | 97,011 | 23 | 194,022 |
Tags: brute force, strings
Correct Solution:
```
n, m = map(int, input().split())
arr = [set() for i in range(n)]
for i in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
f = b - a
if f < 0:
f += n
arr[a].add(f)
f = a - b
if f < 0:
f += n
arr[b].add(f)
lst = [1]
for i in range(2, int(n ** 0.5) + 1):
if (n % i == 0):
lst.append(i)
lst.append(n // i)
flag = 0
#print(lst)
for el in lst:
for i in range(n):
next = (i + el) % n
if arr[i] != arr[next]:
flag = 1
break
if flag == 0:
print("Yes")
# print(el)
exit(0)
flag = 0
print("No")
``` | output | 1 | 97,011 | 23 | 194,023 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 ≤ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 ≤ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Submitted Solution:
```
n, m = map(int, input().split())
a = []
for i in range(m):
a.append(list(map(int, input().split())))
if (a[i][0] > a[i][1]):
a[i][0], a[i][1] = a[i][1], a[i][0]
if (a[i][1] - a[i][0] > n / 2):
a[i][0] += n
a[i][0], a[i][1] = a[i][1], a[i][0]
if (m == 1):
if (a[0][1] - a[0][i] == n / 2):
print("Yes")
else:
print("No")
exit(0)
a.sort()
for i in range(m):
a.append([a[i][0] + n, a[i][1] + n])
b = []
for i in range(2 * m - 1):
if (a[i][1] - a[i][0] == n / 2):
b.append((a[i][1] - a[i][0], min(a[i + 1][0] - a[i][0], n - a[i + 1][0] + a[i][0])))
else:
b.append((a[i][1] - a[i][0], a[i + 1][0] - a[i][0]))
# Z function
z = [0] * 2 * m
l = r = 0
for i in range(1, m):
if (i <= r):
z[i] = min(z[i - l], r - i + 1)
while (i + z[i] < len(b) and b[i + z[i]] == b[z[i]]):
z[i] += 1
if (i + z[i] - 1 > r):
l = i
r = i + z[i] - 1
if (z[i] >= m):
print("Yes")
exit(0)
print("No")
``` | instruction | 0 | 97,012 | 23 | 194,024 |
Yes | output | 1 | 97,012 | 23 | 194,025 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 ≤ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 ≤ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Submitted Solution:
```
from math import gcd
def primes():
yield 2; yield 3; yield 5; yield 7;
bps = (p for p in primes()) # separate supply of "base" primes (b.p.)
p = next(bps) and next(bps) # discard 2, then get 3
q = p * p # 9 - square of next base prime to keep track of,
sieve = {} # in the sieve dict
n = 9 # n is the next candidate number
while True:
if n not in sieve: # n is not a multiple of any of base primes,
if n < q: # below next base prime's square, so
yield n # n is prime
else:
p2 = p + p # n == p * p: for prime p, add p * p + 2 * p
sieve[q + p2] = p2 # to the dict, with 2 * p as the increment step
p = next(bps); q = p * p # pull next base prime, and get its square
else:
s = sieve.pop(n); nxt = n + s # n's a multiple of some b.p., find next multiple
while nxt in sieve: nxt += s # ensure each entry is unique
sieve[nxt] = s # nxt is next non-marked multiple of this prime
n += 2 # work on odds only
import itertools
def get_prime_divisors(limit):
return list(itertools.filterfalse(lambda p: limit % p, itertools.takewhile(lambda p: p <= limit, primes())))
n, m = map(int, input().split())
data = {}
for _ in range(m):
a, b = map(int, input().split())
a, b = min(a, b)-1, max(a, b)-1
x, y = b-a, n-b+a
if x <= y:
if x in data:
data[x].add(a)
else:
data[x] = set([a])
if y <= x:
if y in data:
data[y].add(b)
else:
data[y] = set([b])
t = n
for s in data.values():
t = gcd(t, len(s))
if t == 1:
print("No")
else:
tests = get_prime_divisors(t)
for k in tests:
d = n//k
for s in data.values():
if any(map(lambda v: (v+d)%n not in s, s)):
break
else:
print("Yes")
break
else:
print("No")
``` | instruction | 0 | 97,013 | 23 | 194,026 |
Yes | output | 1 | 97,013 | 23 | 194,027 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 ≤ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 ≤ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Submitted Solution:
```
def divs(n):
res = []
for i in range(1, int(n ** 0.5) + 1):
if n % i == 0:
res.append(i)
res.append(n // i)
if int(n ** 0.5) ** 2 == n:
res.pop()
return res
def main():
n, m = map(int, input().split())
angles = [set() for i in range(n)]
for i in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
a1 = b - a
if a1 < 0:
a1 += n
angles[a].add(a1)
b1 = a - b
if b1 < 0:
b1 += n
angles[b].add(b1)
d = divs(n)
for di in d:
if di == n:
continue
flag = 1
for i in range(n):
if angles[i] != angles[(i + di) % n]:
flag = 0
break
if flag == 1:
print("Yes")
return 0
print("No")
return 0
main()
``` | instruction | 0 | 97,014 | 23 | 194,028 |
Yes | output | 1 | 97,014 | 23 | 194,029 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 ≤ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 ≤ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Submitted Solution:
```
(n,m) = [int(x) for x in input().split()]
segs =set()
for i in range(m):
segs.add(tuple(sorted((int(x)-1 for x in input().split()))))
for i in range(1,n):
if n%i!=0:
continue
j=0
for a,b in segs:
if tuple(sorted(((a+i)%n,(b+i)%n))) not in segs:
break
j+=1
if j==m:
print("Yes")
exit()
print("No")
``` | instruction | 0 | 97,015 | 23 | 194,030 |
Yes | output | 1 | 97,015 | 23 | 194,031 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 ≤ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 ≤ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Submitted Solution:
```
from math import gcd
def primes():
yield 2; yield 3; yield 5; yield 7;
bps = (p for p in primes()) # separate supply of "base" primes (b.p.)
p = next(bps) and next(bps) # discard 2, then get 3
q = p * p # 9 - square of next base prime to keep track of,
sieve = {} # in the sieve dict
n = 9 # n is the next candidate number
while True:
if n not in sieve: # n is not a multiple of any of base primes,
if n < q: # below next base prime's square, so
yield n # n is prime
else:
p2 = p + p # n == p * p: for prime p, add p * p + 2 * p
sieve[q + p2] = p2 # to the dict, with 2 * p as the increment step
p = next(bps); q = p * p # pull next base prime, and get its square
else:
s = sieve.pop(n); nxt = n + s # n's a multiple of some b.p., find next multiple
while nxt in sieve: nxt += s # ensure each entry is unique
sieve[nxt] = s # nxt is next non-marked multiple of this prime
n += 2 # work on odds only
import itertools
def get_prime_divisors(limit):
return list(itertools.filterfalse(lambda p: limit % p, itertools.takewhile(lambda p: p <= limit, primes())))
n, m = map(int, input().split())
data = {}
for _ in range(m):
a, b = map(int, input().split())
a, b = min(a, b), max(a, b)
x, y = b-a, n-b+a
if x <= y:
if x in data:
data[x].add(a)
else:
data[x] = set([a])
if y <= x:
if y in data:
data[y].add(b)
else:
data[y] = set([b])
t = n
for s in data.values():
t = gcd(t, len(s))
if t == 1:
print("No")
else:
tests = get_prime_divisors(t)
for k in tests:
d = n//k
for s in data.values():
if any(map(lambda v: (v+d)%n not in s, s)):
break
else:
print("Yes")
break
else:
print("No")
``` | instruction | 0 | 97,016 | 23 | 194,032 |
No | output | 1 | 97,016 | 23 | 194,033 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 ≤ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 ≤ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Submitted Solution:
```
import sys
import collections
n, m = map(int, input().split())
# segment length -> start
len2start = collections.defaultdict(set)
for _ in range(m):
start, end = map(int, input().split())
len2start[(end - start) % n].update([start - 1, end - 1])
def get_divisors(n):
"""
:param n:
:return: divisors of n excluding n itself
"""
divisors = []
for i in range(1, n):
if n % i == 0:
divisors.append(i)
return divisors
divisors = get_divisors(n)
for length, segs in len2start.items():
# try out all divisors
for k in divisors:
if len(segs) == 0:
break
for phase in range(k):
for p in range(n // k):
if (phase + k*p) % n not in segs:
break
else:
# if this k, phase and p work, delete the corresponding numbers
for p in range(n // k):
segs.remove((phase + k*p) % n)
if len(segs) > 0:
print('No')
sys.exit()
print('Yes')
``` | instruction | 0 | 97,017 | 23 | 194,034 |
No | output | 1 | 97,017 | 23 | 194,035 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 ≤ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 ≤ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Submitted Solution:
```
import sys
def No():
print('No')
sys.exit()
def divi(n):
res = [1]
for i in range(2, int(n**0.5)+1):
if n % i == 0:
res.append(i)
if i != n // i:
res.append(n//i)
return res
N, M = map(int, input().split())
DN = divi(N)
dis = [set() for _ in range(N//2 + 1)]
for i in range(M):
a, b = map(int, sys.stdin.readline().split())
fn, ln = (a - b)%N, (b - a)%N
if fn < ln:
dis[fn].add(b)
elif ln < fn:
dis[ln].add(a)
else:
dis[fn].add(a)
dis[fn].add(b)
for dn in DN:
for D in dis:
if not D:
continue
for d in D:
if (d+dn)%N not in D:
break
else:
continue
break
else:
print('Yes')
sys.exit()
No()
``` | instruction | 0 | 97,018 | 23 | 194,036 |
No | output | 1 | 97,018 | 23 | 194,037 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 ≤ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned n points.
Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer k (1 ≤ k < n), such that if all segments are rotated clockwise around the center of the circle by k units, the new image will be the same as the original one.
Input
The first line contains two space-separated integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number of segments, respectively.
The i-th of the following m lines contains two space-separated integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) that describe a segment connecting points a_i and b_i.
It is guaranteed that no segments coincide.
Output
Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks).
You can output each letter in any case (upper or lower).
Examples
Input
12 6
1 3
3 7
5 7
7 11
9 11
11 3
Output
Yes
Input
9 6
4 5
5 6
7 8
8 9
1 2
2 3
Output
Yes
Input
10 3
1 2
3 2
7 2
Output
No
Input
10 2
1 6
2 7
Output
Yes
Note
The first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of 120 degrees around the center.
<image>
Submitted Solution:
```
(n,m) = [int(x) for x in input().split()]
segs =[]
for i in range(m):
segs+=[[int(x) for x in input().split()]]
i=0
j=1
len = 1
while(j<m):
if abs(segs[j][1]-segs[j][0])==abs(segs[i][1]-segs[i][0]):
i+=1
j+=1
len = j-i
else:
if(i==0):
j+=1
else:
i=0
len=j+1
poss = "Yes"
if(len==m):
poss="No"
for i in range(0,m-2*len,len):
if(poss=="No"):
break
diff = abs(segs[i+len][0]-segs[i][0])
for j in range(i+len,i+len+len):
if(segs[i][0]+diff!=segs[j][0]):
poss="No"
break
print(poss)
``` | instruction | 0 | 97,019 | 23 | 194,038 |
No | output | 1 | 97,019 | 23 | 194,039 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two lists of segments [al_1, ar_1], [al_2, ar_2], ..., [al_n, ar_n] and [bl_1, br_1], [bl_2, br_2], ..., [bl_n, br_n].
Initially, all segments [al_i, ar_i] are equal to [l_1, r_1] and all segments [bl_i, br_i] are equal to [l_2, r_2].
In one step, you can choose one segment (either from the first or from the second list) and extend it by 1. In other words, suppose you've chosen segment [x, y] then you can transform it either into [x - 1, y] or into [x, y + 1].
Let's define a total intersection I as the sum of lengths of intersections of the corresponding pairs of segments, i.e. ∑_{i=1}^{n}{intersection_length([al_i, ar_i], [bl_i, br_i])}. Empty intersection has length 0 and length of a segment [x, y] is equal to y - x.
What is the minimum number of steps you need to make I greater or equal to k?
Input
The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 10^9) — the length of lists and the minimum required total intersection.
The second line of each test case contains two integers l_1 and r_1 (1 ≤ l_1 ≤ r_1 ≤ 10^9) — the segment all [al_i, ar_i] are equal to initially.
The third line of each test case contains two integers l_2 and r_2 (1 ≤ l_2 ≤ r_2 ≤ 10^9) — the segment all [bl_i, br_i] are equal to initially.
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
Print t integers — one per test case. For each test case, print the minimum number of step you need to make I greater or equal to k.
Example
Input
3
3 5
1 2
3 4
2 1000000000
1 1
999999999 999999999
10 3
5 10
7 8
Output
7
2000000000
0
Note
In the first test case, we can achieve total intersection 5, for example, using next strategy:
* make [al_1, ar_1] from [1, 2] to [1, 4] in 2 steps;
* make [al_2, ar_2] from [1, 2] to [1, 3] in 1 step;
* make [bl_1, br_1] from [3, 4] to [1, 4] in 2 steps;
* make [bl_2, br_2] from [3, 4] to [1, 4] in 2 steps.
In result, I = intersection_length([al_1, ar_1], [bl_1, br_1]) + intersection_length([al_2, ar_2], [bl_2, br_2]) + \\\ + intersection_length([al_3, ar_3], [bl_3, br_3]) = 3 + 2 + 0 = 5
In the second test case, we can make [al_1, ar_1] = [0, 1000000000] in 1000000000 steps and [bl_1, br_1] = [0, 1000000000] in 1000000000 steps.
In the third test case, the total intersection I is already equal to 10 > 3, so we don't need to do any steps.
Submitted Solution:
```
import sys
import math
read = sys.stdin.buffer.read
# input = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
t = int(input())
for case in range(t):
n, k = map(int, input().split())
l1, r1 = map(int, input().split())
l2, r2 = map(int, input().split())
origin_inter = max(0, min(r1, r2) - max(l1, l2))
ans = 0
k -= origin_inter * n
if k <= 0:
ans = 0
elif origin_inter > 0:
# まず伸ばせるまで伸ばす。その後、2ターンで1伸ばす
if k <= n * ((r1 - l1) + (r2 - l2) - origin_inter * 2):
ans += k
else:
ans = 2 * k - n * ((r1 - l1) + (r2 - l2) - origin_inter * 2)
else:
margin = max(l1, l2) - min(r1, r2)
len_inter = max(r1, r2) - min(l1, l2)
# 何本を使うかを決め打つ
ans = 10 ** 10
for i in range(1, n + 1):
tmp_i = margin * i
if k > len_inter * i:
tmp_i += len_inter * i + (k - len_inter * i) * 2
else:
tmp_i += k
# print(i, tmp_i, margin, len_inter)
ans = min(tmp_i, ans)
"""bit = 0
while bit == 0 or k > dif:
ans += dif
if max(r1, r2) - min(l1, l2) >= k: # kの方が小さい dif を足して +1でいくべき
ans += k
k = 0
break
else:
ans += max(r1, r2) - min(l1, l2)
k -= max(r1, r2) - min(l1, l2)
bit = 1
ans += 2 * k"""
print(ans)
``` | instruction | 0 | 97,158 | 23 | 194,316 |
Yes | output | 1 | 97,158 | 23 | 194,317 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two lists of segments [al_1, ar_1], [al_2, ar_2], ..., [al_n, ar_n] and [bl_1, br_1], [bl_2, br_2], ..., [bl_n, br_n].
Initially, all segments [al_i, ar_i] are equal to [l_1, r_1] and all segments [bl_i, br_i] are equal to [l_2, r_2].
In one step, you can choose one segment (either from the first or from the second list) and extend it by 1. In other words, suppose you've chosen segment [x, y] then you can transform it either into [x - 1, y] or into [x, y + 1].
Let's define a total intersection I as the sum of lengths of intersections of the corresponding pairs of segments, i.e. ∑_{i=1}^{n}{intersection_length([al_i, ar_i], [bl_i, br_i])}. Empty intersection has length 0 and length of a segment [x, y] is equal to y - x.
What is the minimum number of steps you need to make I greater or equal to k?
Input
The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 10^9) — the length of lists and the minimum required total intersection.
The second line of each test case contains two integers l_1 and r_1 (1 ≤ l_1 ≤ r_1 ≤ 10^9) — the segment all [al_i, ar_i] are equal to initially.
The third line of each test case contains two integers l_2 and r_2 (1 ≤ l_2 ≤ r_2 ≤ 10^9) — the segment all [bl_i, br_i] are equal to initially.
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
Print t integers — one per test case. For each test case, print the minimum number of step you need to make I greater or equal to k.
Example
Input
3
3 5
1 2
3 4
2 1000000000
1 1
999999999 999999999
10 3
5 10
7 8
Output
7
2000000000
0
Note
In the first test case, we can achieve total intersection 5, for example, using next strategy:
* make [al_1, ar_1] from [1, 2] to [1, 4] in 2 steps;
* make [al_2, ar_2] from [1, 2] to [1, 3] in 1 step;
* make [bl_1, br_1] from [3, 4] to [1, 4] in 2 steps;
* make [bl_2, br_2] from [3, 4] to [1, 4] in 2 steps.
In result, I = intersection_length([al_1, ar_1], [bl_1, br_1]) + intersection_length([al_2, ar_2], [bl_2, br_2]) + \\\ + intersection_length([al_3, ar_3], [bl_3, br_3]) = 3 + 2 + 0 = 5
In the second test case, we can make [al_1, ar_1] = [0, 1000000000] in 1000000000 steps and [bl_1, br_1] = [0, 1000000000] in 1000000000 steps.
In the third test case, the total intersection I is already equal to 10 > 3, so we don't need to do any steps.
Submitted Solution:
```
import sys
readline = sys.stdin.readline
def solve():
N, K = map(int, readline().split())
L1, R1 = map(int, readline().split())
L2, R2 = map(int, readline().split())
if L1 > L2:
L1, L2 = L2, L1
R1, R2 = R2, R1
if R1 < L2:
gap = L2 - R1
union = R2 - L1
ans = gap
if K <= union:
ans += K
print(ans)
return
ans += union
rem = K - union
if N == 1:
print(ans + 2 * rem)
return
t = min(rem // union, N - 1)
ans += t * (gap + union)
rem -= t * union
if t == N - 1:
print(ans + 2 * rem)
return
if 2*rem < gap + rem:
print(ans + 2 * rem)
return
else:
print(ans + gap + rem)
return
else:
ovl = min(R1, R2) - L2
if ovl * N >= K:
print(0)
return
union = max(R1, R2) - L1
if union * N >= K:
print(K - ovl * N)
return
else:
ans = union * N - ovl * N
ans += 2 * (K - union * N)
print(ans)
return
T = int(readline())
for i in range(T):
solve()
``` | instruction | 0 | 97,159 | 23 | 194,318 |
Yes | output | 1 | 97,159 | 23 | 194,319 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two lists of segments [al_1, ar_1], [al_2, ar_2], ..., [al_n, ar_n] and [bl_1, br_1], [bl_2, br_2], ..., [bl_n, br_n].
Initially, all segments [al_i, ar_i] are equal to [l_1, r_1] and all segments [bl_i, br_i] are equal to [l_2, r_2].
In one step, you can choose one segment (either from the first or from the second list) and extend it by 1. In other words, suppose you've chosen segment [x, y] then you can transform it either into [x - 1, y] or into [x, y + 1].
Let's define a total intersection I as the sum of lengths of intersections of the corresponding pairs of segments, i.e. ∑_{i=1}^{n}{intersection_length([al_i, ar_i], [bl_i, br_i])}. Empty intersection has length 0 and length of a segment [x, y] is equal to y - x.
What is the minimum number of steps you need to make I greater or equal to k?
Input
The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 10^9) — the length of lists and the minimum required total intersection.
The second line of each test case contains two integers l_1 and r_1 (1 ≤ l_1 ≤ r_1 ≤ 10^9) — the segment all [al_i, ar_i] are equal to initially.
The third line of each test case contains two integers l_2 and r_2 (1 ≤ l_2 ≤ r_2 ≤ 10^9) — the segment all [bl_i, br_i] are equal to initially.
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
Print t integers — one per test case. For each test case, print the minimum number of step you need to make I greater or equal to k.
Example
Input
3
3 5
1 2
3 4
2 1000000000
1 1
999999999 999999999
10 3
5 10
7 8
Output
7
2000000000
0
Note
In the first test case, we can achieve total intersection 5, for example, using next strategy:
* make [al_1, ar_1] from [1, 2] to [1, 4] in 2 steps;
* make [al_2, ar_2] from [1, 2] to [1, 3] in 1 step;
* make [bl_1, br_1] from [3, 4] to [1, 4] in 2 steps;
* make [bl_2, br_2] from [3, 4] to [1, 4] in 2 steps.
In result, I = intersection_length([al_1, ar_1], [bl_1, br_1]) + intersection_length([al_2, ar_2], [bl_2, br_2]) + \\\ + intersection_length([al_3, ar_3], [bl_3, br_3]) = 3 + 2 + 0 = 5
In the second test case, we can make [al_1, ar_1] = [0, 1000000000] in 1000000000 steps and [bl_1, br_1] = [0, 1000000000] in 1000000000 steps.
In the third test case, the total intersection I is already equal to 10 > 3, so we don't need to do any steps.
Submitted Solution:
```
######################################################
############Created by Devesh Kumar###################
#############devesh1102@gmail.com####################
##########For CodeForces(Devesh1102)#################
#####################2020#############################
######################################################
import sys
input = sys.stdin.readline
# import sys
import heapq
import copy
import math
import decimal
# import sys.stdout.flush as flush
# from decimal import *
#heapq.heapify(li)
#
#heapq.heappush(li,4)
#
#heapq.heappop(li)
#
# & Bitwise AND Operator 10 & 7 = 2
# | Bitwise OR Operator 10 | 7 = 15
# ^ Bitwise XOR Operator 10 ^ 7 = 13
# << Bitwise Left Shift operator 10<<2 = 40
# >> Bitwise Right Shift Operator
# '''############ ---- Input Functions ---- #######Start#####'''
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def insr2():
s = input()
return((s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
############ ---- Input Functions ---- #######End
# #####
def pr_list(a):
print( *a , sep=" ")
def main():
tests = inp()
# tests = 1
mod = 1000000007
limit = 10**18
ans = 0
stack = []
hashm = {}
arr = []
heapq.heapify(arr)
for test in range(tests):
[n,k] = inlt()
[a1,a2] = inlt()
[b1,b2] = inlt()
# if test == 39:
# print(n,k,[a1,a2],[b1,b2])
# if (a1<b1)and
def swap(a,b):
temp = a
a= b
b =temp
return [a,b]
if a2 <b1 or b2<a1:
if a2 > b1:
[a1,b1] = swap(a1,b1)
[a2,b2] = swap(a2,b2)
mini = b1 - a2
maxi = b2 - a1
if k <= maxi:
print(mini + k)
else:
case1 = (k- maxi)*2 + mini + maxi
a = min ((k//maxi) , n)
if k//maxi >=n:
a = n
case2 = a * (mini + maxi) + 2*(k- a*maxi)
else:
a = k//maxi
case2 = a * (mini + maxi) + min(k-a*maxi + mini, 2*(k- a*maxi))
print(min(case1,case2))
else:
if a2 > b2:
[a1,b1] = swap(a1,b1)
[a2,b2] = swap(a2,b2)
curr = (a2 - max(b1,a1))*n
if k<=curr:
print(0)
else:
maxi = (b2 - min(a1,b1))*n
if k<=maxi:
print(k - curr)
else:
print(2*(k-maxi) + maxi - curr)
if __name__== "__main__":
main()
``` | instruction | 0 | 97,160 | 23 | 194,320 |
Yes | output | 1 | 97,160 | 23 | 194,321 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two lists of segments [al_1, ar_1], [al_2, ar_2], ..., [al_n, ar_n] and [bl_1, br_1], [bl_2, br_2], ..., [bl_n, br_n].
Initially, all segments [al_i, ar_i] are equal to [l_1, r_1] and all segments [bl_i, br_i] are equal to [l_2, r_2].
In one step, you can choose one segment (either from the first or from the second list) and extend it by 1. In other words, suppose you've chosen segment [x, y] then you can transform it either into [x - 1, y] or into [x, y + 1].
Let's define a total intersection I as the sum of lengths of intersections of the corresponding pairs of segments, i.e. ∑_{i=1}^{n}{intersection_length([al_i, ar_i], [bl_i, br_i])}. Empty intersection has length 0 and length of a segment [x, y] is equal to y - x.
What is the minimum number of steps you need to make I greater or equal to k?
Input
The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 10^9) — the length of lists and the minimum required total intersection.
The second line of each test case contains two integers l_1 and r_1 (1 ≤ l_1 ≤ r_1 ≤ 10^9) — the segment all [al_i, ar_i] are equal to initially.
The third line of each test case contains two integers l_2 and r_2 (1 ≤ l_2 ≤ r_2 ≤ 10^9) — the segment all [bl_i, br_i] are equal to initially.
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
Print t integers — one per test case. For each test case, print the minimum number of step you need to make I greater or equal to k.
Example
Input
3
3 5
1 2
3 4
2 1000000000
1 1
999999999 999999999
10 3
5 10
7 8
Output
7
2000000000
0
Note
In the first test case, we can achieve total intersection 5, for example, using next strategy:
* make [al_1, ar_1] from [1, 2] to [1, 4] in 2 steps;
* make [al_2, ar_2] from [1, 2] to [1, 3] in 1 step;
* make [bl_1, br_1] from [3, 4] to [1, 4] in 2 steps;
* make [bl_2, br_2] from [3, 4] to [1, 4] in 2 steps.
In result, I = intersection_length([al_1, ar_1], [bl_1, br_1]) + intersection_length([al_2, ar_2], [bl_2, br_2]) + \\\ + intersection_length([al_3, ar_3], [bl_3, br_3]) = 3 + 2 + 0 = 5
In the second test case, we can make [al_1, ar_1] = [0, 1000000000] in 1000000000 steps and [bl_1, br_1] = [0, 1000000000] in 1000000000 steps.
In the third test case, the total intersection I is already equal to 10 > 3, so we don't need to do any steps.
Submitted Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default='z', func=lambda a, b: min(a, b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] <= key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
for ik in range(int(input())):
n,k=map(int,input().split())
l1,r1=map(int,input().split())
l2,r2=map(int,input().split())
gap=max(0,-min(r1,r2)+max(l1,l2))
lap=max(0,min(r1,r2)-max(l1,l2))
total=max(r1,r2)-min(l1,l2)
#print(gap,lap,total)
if lap*n>=k:
print(0)
continue
lap1=lap
lap*=n
ans=0
t=min(k-lap,total-lap1)
ans+=gap+t
n-=1
lap+=t
#print(ans,lap,total,k)
while(lap<k):
t=min(k-lap,total-lap1)
#print(t)
if n==0:
break
elif gap<=t:
lap+=t
ans+=t+gap
n-=1
else:
ans+=2*t
lap+=t
#print(ans,lap)
if lap<k:
ans+=2*(k-lap)
print(ans)
``` | instruction | 0 | 97,161 | 23 | 194,322 |
Yes | output | 1 | 97,161 | 23 | 194,323 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two lists of segments [al_1, ar_1], [al_2, ar_2], ..., [al_n, ar_n] and [bl_1, br_1], [bl_2, br_2], ..., [bl_n, br_n].
Initially, all segments [al_i, ar_i] are equal to [l_1, r_1] and all segments [bl_i, br_i] are equal to [l_2, r_2].
In one step, you can choose one segment (either from the first or from the second list) and extend it by 1. In other words, suppose you've chosen segment [x, y] then you can transform it either into [x - 1, y] or into [x, y + 1].
Let's define a total intersection I as the sum of lengths of intersections of the corresponding pairs of segments, i.e. ∑_{i=1}^{n}{intersection_length([al_i, ar_i], [bl_i, br_i])}. Empty intersection has length 0 and length of a segment [x, y] is equal to y - x.
What is the minimum number of steps you need to make I greater or equal to k?
Input
The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 10^9) — the length of lists and the minimum required total intersection.
The second line of each test case contains two integers l_1 and r_1 (1 ≤ l_1 ≤ r_1 ≤ 10^9) — the segment all [al_i, ar_i] are equal to initially.
The third line of each test case contains two integers l_2 and r_2 (1 ≤ l_2 ≤ r_2 ≤ 10^9) — the segment all [bl_i, br_i] are equal to initially.
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
Print t integers — one per test case. For each test case, print the minimum number of step you need to make I greater or equal to k.
Example
Input
3
3 5
1 2
3 4
2 1000000000
1 1
999999999 999999999
10 3
5 10
7 8
Output
7
2000000000
0
Note
In the first test case, we can achieve total intersection 5, for example, using next strategy:
* make [al_1, ar_1] from [1, 2] to [1, 4] in 2 steps;
* make [al_2, ar_2] from [1, 2] to [1, 3] in 1 step;
* make [bl_1, br_1] from [3, 4] to [1, 4] in 2 steps;
* make [bl_2, br_2] from [3, 4] to [1, 4] in 2 steps.
In result, I = intersection_length([al_1, ar_1], [bl_1, br_1]) + intersection_length([al_2, ar_2], [bl_2, br_2]) + \\\ + intersection_length([al_3, ar_3], [bl_3, br_3]) = 3 + 2 + 0 = 5
In the second test case, we can make [al_1, ar_1] = [0, 1000000000] in 1000000000 steps and [bl_1, br_1] = [0, 1000000000] in 1000000000 steps.
In the third test case, the total intersection I is already equal to 10 > 3, so we don't need to do any steps.
Submitted Solution:
```
import sys
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0
def main():
n,k = map(int,readline().split())
a = list(map(int,readline().split()))
b = list(map(int,readline().split()))
#left側が小さい方をaとする
if a[0] > b[0]:
a,b = b,a
score = 0
cost = 0
#初期状態でのスコア
score_init = max(0,a[1]-b[0])*n
if score_init >= k:
print(0)
return
#case 1
if a[0] <= b[0] and b[1] <= a[1]:
res = b[0] - a[0] + a[1] - b[1]
score += res*n
cost += res*n
if k <= score+score_init:
print(k-score_init)
return
#case 2-1
elif a[1] > b[0]:
res = b[0]-a[0] + b[1]-a[1]
score += res*n
cost += res*n
if k <= score+score_init:
print(k-score_init)
return
#case 3
else:
one_term_score = b[1]-a[0]
one_term_cost = a[1]-a[0]+b[1]-b[0]+(b[0]-a[1])*2
if k < one_term_score*n: #途中で終了条件に達しそうならば
#何回まで確定で回すか
let = k//one_term_score
score += one_term_score*let
cost += one_term_cost*let
#余りはコスト2払ったほうがお得な場合もあるのでまた場合分け
if k-score < b[0]-a[1]:
pass
else:
cost += b[0]-a[1]+(k-score)
score = k
else: #そうでないなら全部回しちゃう
score += one_term_score*n
cost += one_term_cost*n
#あとは全部コスト2払って1伸ばす
if score + score_init < k:
cost += 2*(k-score - score_init)
print(cost)
if __name__ == "__main__":
n = int(readline())
for i in range(n):
main()
``` | instruction | 0 | 97,162 | 23 | 194,324 |
No | output | 1 | 97,162 | 23 | 194,325 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two lists of segments [al_1, ar_1], [al_2, ar_2], ..., [al_n, ar_n] and [bl_1, br_1], [bl_2, br_2], ..., [bl_n, br_n].
Initially, all segments [al_i, ar_i] are equal to [l_1, r_1] and all segments [bl_i, br_i] are equal to [l_2, r_2].
In one step, you can choose one segment (either from the first or from the second list) and extend it by 1. In other words, suppose you've chosen segment [x, y] then you can transform it either into [x - 1, y] or into [x, y + 1].
Let's define a total intersection I as the sum of lengths of intersections of the corresponding pairs of segments, i.e. ∑_{i=1}^{n}{intersection_length([al_i, ar_i], [bl_i, br_i])}. Empty intersection has length 0 and length of a segment [x, y] is equal to y - x.
What is the minimum number of steps you need to make I greater or equal to k?
Input
The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 10^9) — the length of lists and the minimum required total intersection.
The second line of each test case contains two integers l_1 and r_1 (1 ≤ l_1 ≤ r_1 ≤ 10^9) — the segment all [al_i, ar_i] are equal to initially.
The third line of each test case contains two integers l_2 and r_2 (1 ≤ l_2 ≤ r_2 ≤ 10^9) — the segment all [bl_i, br_i] are equal to initially.
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
Print t integers — one per test case. For each test case, print the minimum number of step you need to make I greater or equal to k.
Example
Input
3
3 5
1 2
3 4
2 1000000000
1 1
999999999 999999999
10 3
5 10
7 8
Output
7
2000000000
0
Note
In the first test case, we can achieve total intersection 5, for example, using next strategy:
* make [al_1, ar_1] from [1, 2] to [1, 4] in 2 steps;
* make [al_2, ar_2] from [1, 2] to [1, 3] in 1 step;
* make [bl_1, br_1] from [3, 4] to [1, 4] in 2 steps;
* make [bl_2, br_2] from [3, 4] to [1, 4] in 2 steps.
In result, I = intersection_length([al_1, ar_1], [bl_1, br_1]) + intersection_length([al_2, ar_2], [bl_2, br_2]) + \\\ + intersection_length([al_3, ar_3], [bl_3, br_3]) = 3 + 2 + 0 = 5
In the second test case, we can make [al_1, ar_1] = [0, 1000000000] in 1000000000 steps and [bl_1, br_1] = [0, 1000000000] in 1000000000 steps.
In the third test case, the total intersection I is already equal to 10 > 3, so we don't need to do any steps.
Submitted Solution:
```
from bisect import *
from collections import *
from math import gcd,ceil,sqrt,floor,inf
from heapq import *
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *
#------------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#------------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
#------------------------------------------------------------------------
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
farr=[1]
ifa=[]
def fact(x,mod=0):
if mod:
while x>=len(farr):
farr.append(farr[-1]*len(farr)%mod)
else:
while x>=len(farr):
farr.append(farr[-1]*len(farr))
return farr[x]
def ifact(x,mod):
global ifa
ifa.append(pow(farr[-1],mod-2,mod))
for i in range(x,0,-1):
ifa.append(ifa[-1]*i%mod)
ifa=ifa[::-1]
def per(i,j,mod=0):
if i<j: return 0
if not mod:
return fact(i)//fact(i-j)
return farr[i]*ifa[i-j]%mod
def com(i,j,mod=0):
if i<j: return 0
if not mod:
return per(i,j)//fact(j)
return per(i,j,mod)*ifa[j]%mod
def catalan(n):
return com(2*n,n)//(n+1)
def linc(f,t,l,r):
while l<r:
mid=(l+r)//2
if t>f(mid):
l=mid+1
else:
r=mid
return l
def rinc(f,t,l,r):
while l<r:
mid=(l+r+1)//2
if t<f(mid):
r=mid-1
else:
l=mid
return l
def ldec(f,t,l,r):
while l<r:
mid=(l+r)//2
if t<f(mid):
l=mid+1
else:
r=mid
return l
def rdec(f,t,l,r):
while l<r:
mid=(l+r+1)//2
if t>f(mid):
r=mid-1
else:
l=mid
return l
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def binfun(x):
c=0
for w in arr:
c+=ceil(w/x)
return c
def lowbit(n):
return n&-n
def inverse(a,m):
a%=m
if a<=1: return a
return ((1-inverse(m,a)*m)//a)%m
class BIT:
def __init__(self,arr):
self.arr=arr
self.n=len(arr)-1
def update(self,x,v):
while x<=self.n:
self.arr[x]+=v
x+=x&-x
def query(self,x):
ans=0
while x:
ans+=self.arr[x]
x&=x-1
return ans
'''
class SMT:
def __init__(self,arr):
self.n=len(arr)-1
self.arr=[0]*(self.n<<2)
self.lazy=[0]*(self.n<<2)
def Build(l,r,rt):
if l==r:
self.arr[rt]=arr[l]
return
m=(l+r)>>1
Build(l,m,rt<<1)
Build(m+1,r,rt<<1|1)
self.pushup(rt)
Build(1,self.n,1)
def pushup(self,rt):
self.arr[rt]=self.arr[rt<<1]+self.arr[rt<<1|1]
def pushdown(self,rt,ln,rn):#lr,rn表区间数字数
if self.lazy[rt]:
self.lazy[rt<<1]+=self.lazy[rt]
self.lazy[rt<<1|1]=self.lazy[rt]
self.arr[rt<<1]+=self.lazy[rt]*ln
self.arr[rt<<1|1]+=self.lazy[rt]*rn
self.lazy[rt]=0
def update(self,L,R,c,l=1,r=None,rt=1):#L,R表示操作区间
if r==None: r=self.n
if L<=l and r<=R:
self.arr[rt]+=c*(r-l+1)
self.lazy[rt]+=c
return
m=(l+r)>>1
self.pushdown(rt,m-l+1,r-m)
if L<=m: self.update(L,R,c,l,m,rt<<1)
if R>m: self.update(L,R,c,m+1,r,rt<<1|1)
self.pushup(rt)
def query(self,L,R,l=1,r=None,rt=1):
if r==None: r=self.n
#print(L,R,l,r,rt)
if L<=l and R>=r:
return self.arr[rt]
m=(l+r)>>1
self.pushdown(rt,m-l+1,r-m)
ans=0
if L<=m: ans+=self.query(L,R,l,m,rt<<1)
if R>m: ans+=self.query(L,R,m+1,r,rt<<1|1)
return ans
'''
class DSU:#容量+路径压缩
def __init__(self,n):
self.c=[-1]*n
def same(self,x,y):
return self.find(x)==self.find(y)
def find(self,x):
if self.c[x]<0:
return x
self.c[x]=self.find(self.c[x])
return self.c[x]
def union(self,u,v):
u,v=self.find(u),self.find(v)
if u==v:
return False
if self.c[u]<self.c[v]:
u,v=v,u
self.c[u]+=self.c[v]
self.c[v]=u
return True
def size(self,x): return -self.c[self.find(x)]
class UFS:#秩+路径
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
def find(self,x):
if x!=self.parent[x]:
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
pu,pv=self.find(u),self.find(v)
if pu==pv:
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
def Prime(n):
c=0
prime=[]
flag=[0]*(n+1)
for i in range(2,n+1):
if not flag[i]:
prime.append(i)
c+=1
for j in range(c):
if i*prime[j]>n: break
flag[i*prime[j]]=prime[j]
if i%prime[j]==0: break
return prime
def dij(s,graph):
d={}
d[s]=0
heap=[(0,s)]
seen=set()
while heap:
dis,u=heappop(heap)
if u in seen:
continue
for v in graph[u]:
if v not in d or d[v]>d[u]+graph[u][v]:
d[v]=d[u]+graph[u][v]
heappush(heap,(d[v],v))
return d
def GP(it): return [(ch,len(list(g))) for ch,g in groupby(it)]
class DLN:
def __init__(self,val):
self.val=val
self.pre=None
self.next=None
t=N()
for i in range(t):
n,k=RL()
l1,r1=RL()
l2,r2=RL()
if l1>l2:
l1,r1,l2,r2=l2,r2,l1,r1
if r1<l2:
#print((r2-l1),(r2-r1+l2-l1))
if n==1 or 2*(r2-l1)<=(r2-r1+l2-l1):
if k<=r2-r1:
ans=l2-r1+k
else:
ans=r2-r1+l2-l1+(k-r2+l1)*2
else:
d,m=divmod(k,r2-l1)
if d+1<=n:
ans=d*(r2-r1+l2-l1)+min(l2-r1+m,m*2)
else:
m=k-(r2-l1)*n
ans=n*(r2-r1+l2-l1)+m*2
else:
a=min(r1,r2)-l2
p=max(r1,r2)-l1
if n*a>=k:
ans=0
elif n*p>=k:
ans=k-n*a
else:
ans=n*(p-a)+(k-n*p)*2
print(ans)
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thread(target=main)
t.start()
t.join()
'''
``` | instruction | 0 | 97,163 | 23 | 194,326 |
No | output | 1 | 97,163 | 23 | 194,327 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two lists of segments [al_1, ar_1], [al_2, ar_2], ..., [al_n, ar_n] and [bl_1, br_1], [bl_2, br_2], ..., [bl_n, br_n].
Initially, all segments [al_i, ar_i] are equal to [l_1, r_1] and all segments [bl_i, br_i] are equal to [l_2, r_2].
In one step, you can choose one segment (either from the first or from the second list) and extend it by 1. In other words, suppose you've chosen segment [x, y] then you can transform it either into [x - 1, y] or into [x, y + 1].
Let's define a total intersection I as the sum of lengths of intersections of the corresponding pairs of segments, i.e. ∑_{i=1}^{n}{intersection_length([al_i, ar_i], [bl_i, br_i])}. Empty intersection has length 0 and length of a segment [x, y] is equal to y - x.
What is the minimum number of steps you need to make I greater or equal to k?
Input
The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 10^9) — the length of lists and the minimum required total intersection.
The second line of each test case contains two integers l_1 and r_1 (1 ≤ l_1 ≤ r_1 ≤ 10^9) — the segment all [al_i, ar_i] are equal to initially.
The third line of each test case contains two integers l_2 and r_2 (1 ≤ l_2 ≤ r_2 ≤ 10^9) — the segment all [bl_i, br_i] are equal to initially.
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
Print t integers — one per test case. For each test case, print the minimum number of step you need to make I greater or equal to k.
Example
Input
3
3 5
1 2
3 4
2 1000000000
1 1
999999999 999999999
10 3
5 10
7 8
Output
7
2000000000
0
Note
In the first test case, we can achieve total intersection 5, for example, using next strategy:
* make [al_1, ar_1] from [1, 2] to [1, 4] in 2 steps;
* make [al_2, ar_2] from [1, 2] to [1, 3] in 1 step;
* make [bl_1, br_1] from [3, 4] to [1, 4] in 2 steps;
* make [bl_2, br_2] from [3, 4] to [1, 4] in 2 steps.
In result, I = intersection_length([al_1, ar_1], [bl_1, br_1]) + intersection_length([al_2, ar_2], [bl_2, br_2]) + \\\ + intersection_length([al_3, ar_3], [bl_3, br_3]) = 3 + 2 + 0 = 5
In the second test case, we can make [al_1, ar_1] = [0, 1000000000] in 1000000000 steps and [bl_1, br_1] = [0, 1000000000] in 1000000000 steps.
In the third test case, the total intersection I is already equal to 10 > 3, so we don't need to do any steps.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def print_list(l):
print(' '.join(map(str,l)))
# import heapq as hq
# import bisect as bs
# from collections import deque as dq
from collections import defaultdict as dc
# from math import ceil,floor,sqrt
# from collections import Counter
for _ in range(N()):
n,k = RL()
l1,r1 = RL()
l2,r2 = RL()
l1,l2,r1,r2 = min(l1,l2),max(l1,l2),min(r1,r2),max(r1,r2)
dic = max(0,l2-r1)
inc = max(0,r1-l2)
al = r2-l1
now = inc*n
if now>=k:
print(0)
else:
res = 0
tt = dic+(al-inc)
tmp = k-now-(al-inc)
if tmp<=0:
print(dic+k-now)
else:
r1 = tt+tmp*2
key = max((k-now)//(al-inc),n)
r3 = tt*key+2*((k-now)-key*(al-inc))
r2 = tt*key
if (k-now)%(al-inc)>0 and key<n:
r2+=dic+((k-now)%(al-inc))
else:
r2 = r3
res = min(r1,r2,r3)
print(res)
``` | instruction | 0 | 97,164 | 23 | 194,328 |
No | output | 1 | 97,164 | 23 | 194,329 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two lists of segments [al_1, ar_1], [al_2, ar_2], ..., [al_n, ar_n] and [bl_1, br_1], [bl_2, br_2], ..., [bl_n, br_n].
Initially, all segments [al_i, ar_i] are equal to [l_1, r_1] and all segments [bl_i, br_i] are equal to [l_2, r_2].
In one step, you can choose one segment (either from the first or from the second list) and extend it by 1. In other words, suppose you've chosen segment [x, y] then you can transform it either into [x - 1, y] or into [x, y + 1].
Let's define a total intersection I as the sum of lengths of intersections of the corresponding pairs of segments, i.e. ∑_{i=1}^{n}{intersection_length([al_i, ar_i], [bl_i, br_i])}. Empty intersection has length 0 and length of a segment [x, y] is equal to y - x.
What is the minimum number of steps you need to make I greater or equal to k?
Input
The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 10^9) — the length of lists and the minimum required total intersection.
The second line of each test case contains two integers l_1 and r_1 (1 ≤ l_1 ≤ r_1 ≤ 10^9) — the segment all [al_i, ar_i] are equal to initially.
The third line of each test case contains two integers l_2 and r_2 (1 ≤ l_2 ≤ r_2 ≤ 10^9) — the segment all [bl_i, br_i] are equal to initially.
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
Print t integers — one per test case. For each test case, print the minimum number of step you need to make I greater or equal to k.
Example
Input
3
3 5
1 2
3 4
2 1000000000
1 1
999999999 999999999
10 3
5 10
7 8
Output
7
2000000000
0
Note
In the first test case, we can achieve total intersection 5, for example, using next strategy:
* make [al_1, ar_1] from [1, 2] to [1, 4] in 2 steps;
* make [al_2, ar_2] from [1, 2] to [1, 3] in 1 step;
* make [bl_1, br_1] from [3, 4] to [1, 4] in 2 steps;
* make [bl_2, br_2] from [3, 4] to [1, 4] in 2 steps.
In result, I = intersection_length([al_1, ar_1], [bl_1, br_1]) + intersection_length([al_2, ar_2], [bl_2, br_2]) + \\\ + intersection_length([al_3, ar_3], [bl_3, br_3]) = 3 + 2 + 0 = 5
In the second test case, we can make [al_1, ar_1] = [0, 1000000000] in 1000000000 steps and [bl_1, br_1] = [0, 1000000000] in 1000000000 steps.
In the third test case, the total intersection I is already equal to 10 > 3, so we don't need to do any steps.
Submitted Solution:
```
import time,math as mt,bisect,sys
from sys import stdin,stdout
from collections import deque
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
pi=3.14159265358979323846264338327950
def II(): # to take integer input
return int(stdin.readline())
def IO(): # to take string input
return stdin.readline()
def IP(): # to take tuple as input
return map(int,stdin.readline().split())
def L(): # to take list as input
return list(map(int,stdin.readline().split()))
def P(x): # to print integer,list,string etc..
return stdout.write(str(x)+"\n")
def PI(x,y): # to print tuple separatedly
return stdout.write(str(x)+" "+str(y)+"\n")
def lcm(a,b): # to calculate lcm
return (a*b)//gcd(a,b)
def gcd(a,b): # to calculate gcd
if a==0:
return b
elif b==0:
return a
if a>b:
return gcd(a%b,b)
else:
return gcd(a,b%a)
def readTree(): # to read tree
v=int(input())
adj=[set() for i in range(v+1)]
for i in range(v-1):
u1,u2=In()
adj[u1].add(u2)
adj[u2].add(u1)
return adj,v
def bfs(adj,v): # a schema of bfs
visited=[False]*(v+1)
q=deque()
while q:
pass
def sieve():
li=[True]*1000001
li[0],li[1]=False,False
for i in range(2,len(li),1):
if li[i]==True:
for j in range(i*i,len(li),i):
li[j]=False
prime=[]
for i in range(1000001):
if li[i]==True:
prime.append(i)
return prime
def setBit(n):
count=0
while n!=0:
n=n&(n-1)
count+=1
return count
mx=10**7
spf=[mx]*(mx+1)
def SPF():
spf[1]=1
for i in range(2,mx+1):
if spf[i]==mx:
spf[i]=i
for j in range(i*i,mx+1,i):
if i<spf[j]:
spf[j]=i
return
#####################################################################################
mod=10**9+7
def solve():
n,k=IP()
l1,r1=IP()
l2,r2=IP()
a=[[l1,r1] for i in range(n)]
b=[[l2,r2] for i in range(n)]
x,y=max(l1,l2),min(r1,r2)
inter=max(0,y-x)
if (y>x):
k-=(y-x)*n
steps=0
for i in range(n):
if k<=0:
break
reqd=min(k,max(r1,r2)-min(l1,l2)-inter)
cost=max(0,(x-y))+reqd
if i>=2:
cost=min(cost,reqd*2)
k-=reqd
steps+=cost
if k>0:
steps+=k*2
P(steps)
return
t=II()
for i in range(t):
solve()
#######
#
#
####### # # # #### # # #
# # # # # # # # # # #
# #### # # #### #### # #
###### # # #### # # # # #
``` | instruction | 0 | 97,165 | 23 | 194,330 |
No | output | 1 | 97,165 | 23 | 194,331 |
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two lists of segments [al_1, ar_1], [al_2, ar_2], ..., [al_n, ar_n] and [bl_1, br_1], [bl_2, br_2], ..., [bl_n, br_n].
Initially, all segments [al_i, ar_i] are equal to [l_1, r_1] and all segments [bl_i, br_i] are equal to [l_2, r_2].
In one step, you can choose one segment (either from the first or from the second list) and extend it by 1. In other words, suppose you've chosen segment [x, y] then you can transform it either into [x - 1, y] or into [x, y + 1].
Let's define a total intersection I as the sum of lengths of intersections of the corresponding pairs of segments, i.e. ∑_{i=1}^{n}{intersection_length([al_i, ar_i], [bl_i, br_i])}. Empty intersection has length 0 and length of a segment [x, y] is equal to y - x.
What is the minimum number of steps you need to make I greater or equal to k?
Input
The first line contains the single integer t (1 ≤ t ≤ 1000) — the number of test cases.
The first line of each test case contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ k ≤ 10^9) — the length of lists and the minimum required total intersection.
The second line of each test case contains two integers l_1 and r_1 (1 ≤ l_1 ≤ r_1 ≤ 10^9) — the segment all [al_i, ar_i] are equal to initially.
The third line of each test case contains two integers l_2 and r_2 (1 ≤ l_2 ≤ r_2 ≤ 10^9) — the segment all [bl_i, br_i] are equal to initially.
It's guaranteed that the sum of n doesn't exceed 2 ⋅ 10^5.
Output
Print t integers — one per test case. For each test case, print the minimum number of step you need to make I greater or equal to k.
Example
Input
3
3 5
1 2
3 4
2 1000000000
1 1
999999999 999999999
10 3
5 10
7 8
Output
7
2000000000
0
Note
In the first test case, we can achieve total intersection 5, for example, using next strategy:
* make [al_1, ar_1] from [1, 2] to [1, 4] in 2 steps;
* make [al_2, ar_2] from [1, 2] to [1, 3] in 1 step;
* make [bl_1, br_1] from [3, 4] to [1, 4] in 2 steps;
* make [bl_2, br_2] from [3, 4] to [1, 4] in 2 steps.
In result, I = intersection_length([al_1, ar_1], [bl_1, br_1]) + intersection_length([al_2, ar_2], [bl_2, br_2]) + \\\ + intersection_length([al_3, ar_3], [bl_3, br_3]) = 3 + 2 + 0 = 5
In the second test case, we can make [al_1, ar_1] = [0, 1000000000] in 1000000000 steps and [bl_1, br_1] = [0, 1000000000] in 1000000000 steps.
In the third test case, the total intersection I is already equal to 10 > 3, so we don't need to do any steps.
Submitted Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
pr=stdout.write
import heapq
raw_input = stdin.readline
def ni():
return int(raw_input())
def li():
return list(map(int,raw_input().split()))
def pn(n):
stdout.write(str(n)+'\n')
def pa(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return (map(int,stdin.read().split()))
range = xrange # not for python 3.0+
for t in range(ni()):
n,k=li()
l1,r1=li()
l2,r2=li()
df=0
if not ( (l2<=r1 and l2>=l1) or (r2>=l1 and r2<=r1)):
df=min(int(abs(r2-l1)),int(abs(l2-r1)))
else:
if (l2<=r1 and l2>=l1):
ln=min(r2,r1)-l2
else:
ln=r2-max(l1,l2)
ans=min(k,ln*n)
k-=ans
ans=0
mx=max(r2-l2,r1-l1)
ans+=min(k,mx*n)
k-=min(k,mx*n)
pn(ans+(2*k))
continue
mx=max(l1,l2,r1,r2)-min(l1,l2,r1,r2)
ans=df
if k<mx:
print ans+k
continue
ans+=mx
k-=mx
if mx:
cst=(df+mx)/float(mx)
else:
cst=10**12
if cst<2:
for i in range(n-1):
if k<mx:
ans+=min(2*k,k+df)
k-=k
else:
ans+=mx+df
k-=mx
ans+=2*k
pn(ans)
``` | instruction | 0 | 97,166 | 23 | 194,332 |
No | output | 1 | 97,166 | 23 | 194,333 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gerald is setting the New Year table. The table has the form of a circle; its radius equals R. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal r. Each plate must be completely inside the table and must touch the edge of the table. Of course, the plates must not intersect, but they can touch each other. Help Gerald determine whether the table is large enough for n plates.
Input
The first line contains three integers n, R and r (1 ≤ n ≤ 100, 1 ≤ r, R ≤ 1000) — the number of plates, the radius of the table and the plates' radius.
Output
Print "YES" (without the quotes) if it is possible to place n plates on the table by the rules given above. If it is impossible, print "NO".
Remember, that each plate must touch the edge of the table.
Examples
Input
4 10 4
Output
YES
Input
5 10 4
Output
NO
Input
1 10 10
Output
YES
Note
The possible arrangement of the plates for the first sample is:
<image> | instruction | 0 | 97,167 | 23 | 194,334 |
Tags: geometry, math
Correct Solution:
```
from math import asin, pi
n, R, r = map(int, input().split())
if n == 1 and r <= R:
print('YES')
elif 2 * r > R:
print('NO')
elif (pi / asin(r / (R - r))) + 10 ** -6 >= n:
print('YES')
else:
print('NO')
``` | output | 1 | 97,167 | 23 | 194,335 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gerald is setting the New Year table. The table has the form of a circle; its radius equals R. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal r. Each plate must be completely inside the table and must touch the edge of the table. Of course, the plates must not intersect, but they can touch each other. Help Gerald determine whether the table is large enough for n plates.
Input
The first line contains three integers n, R and r (1 ≤ n ≤ 100, 1 ≤ r, R ≤ 1000) — the number of plates, the radius of the table and the plates' radius.
Output
Print "YES" (without the quotes) if it is possible to place n plates on the table by the rules given above. If it is impossible, print "NO".
Remember, that each plate must touch the edge of the table.
Examples
Input
4 10 4
Output
YES
Input
5 10 4
Output
NO
Input
1 10 10
Output
YES
Note
The possible arrangement of the plates for the first sample is:
<image> | instruction | 0 | 97,168 | 23 | 194,336 |
Tags: geometry, math
Correct Solution:
```
import math
def Rp(n, R, r):
if n == 1:
return r
else:
return r * (1 + 1 / math.sin(math.pi / n)) - 1e-6
n, R, r = map(int, input().split())
print("YES" if R >= Rp(n, R, r) else "NO")
``` | output | 1 | 97,168 | 23 | 194,337 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gerald is setting the New Year table. The table has the form of a circle; its radius equals R. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal r. Each plate must be completely inside the table and must touch the edge of the table. Of course, the plates must not intersect, but they can touch each other. Help Gerald determine whether the table is large enough for n plates.
Input
The first line contains three integers n, R and r (1 ≤ n ≤ 100, 1 ≤ r, R ≤ 1000) — the number of plates, the radius of the table and the plates' radius.
Output
Print "YES" (without the quotes) if it is possible to place n plates on the table by the rules given above. If it is impossible, print "NO".
Remember, that each plate must touch the edge of the table.
Examples
Input
4 10 4
Output
YES
Input
5 10 4
Output
NO
Input
1 10 10
Output
YES
Note
The possible arrangement of the plates for the first sample is:
<image> | instruction | 0 | 97,169 | 23 | 194,338 |
Tags: geometry, math
Correct Solution:
```
import math
n, R, r = map(int, input().split())
if n == 1:
print("YES" if r <= R else "NO")
exit(0)
theta = math.pi / n
RR = r / math.sin(theta) + r
print("YES" if R >= RR else "NO")
``` | output | 1 | 97,169 | 23 | 194,339 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gerald is setting the New Year table. The table has the form of a circle; its radius equals R. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal r. Each plate must be completely inside the table and must touch the edge of the table. Of course, the plates must not intersect, but they can touch each other. Help Gerald determine whether the table is large enough for n plates.
Input
The first line contains three integers n, R and r (1 ≤ n ≤ 100, 1 ≤ r, R ≤ 1000) — the number of plates, the radius of the table and the plates' radius.
Output
Print "YES" (without the quotes) if it is possible to place n plates on the table by the rules given above. If it is impossible, print "NO".
Remember, that each plate must touch the edge of the table.
Examples
Input
4 10 4
Output
YES
Input
5 10 4
Output
NO
Input
1 10 10
Output
YES
Note
The possible arrangement of the plates for the first sample is:
<image> | instruction | 0 | 97,170 | 23 | 194,340 |
Tags: geometry, math
Correct Solution:
```
"""
Author : Arif Ahmad
Date :
Algo :
Difficulty :
"""
def main():
n, R, r = map(int, input().split())
if n == 1:
if r <= R: print('YES')
else: print('NO')
else:
import math
# calculate side of inscribed n-gon
a = (R - r) * math.sin(math.pi / n)
#print(a)
if r < a+1e-7: print('YES')
else: print('NO')
if __name__ == '__main__':
main()
``` | output | 1 | 97,170 | 23 | 194,341 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gerald is setting the New Year table. The table has the form of a circle; its radius equals R. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal r. Each plate must be completely inside the table and must touch the edge of the table. Of course, the plates must not intersect, but they can touch each other. Help Gerald determine whether the table is large enough for n plates.
Input
The first line contains three integers n, R and r (1 ≤ n ≤ 100, 1 ≤ r, R ≤ 1000) — the number of plates, the radius of the table and the plates' radius.
Output
Print "YES" (without the quotes) if it is possible to place n plates on the table by the rules given above. If it is impossible, print "NO".
Remember, that each plate must touch the edge of the table.
Examples
Input
4 10 4
Output
YES
Input
5 10 4
Output
NO
Input
1 10 10
Output
YES
Note
The possible arrangement of the plates for the first sample is:
<image> | instruction | 0 | 97,171 | 23 | 194,342 |
Tags: geometry, math
Correct Solution:
```
from math import sin, pi
def table(n, R, r):
if r > R:
return "NO"
if n == 1:
return "YES"
if 2 * r < (R - r) * sin(pi / n) * 2 + 1e-8:
return "YES"
return "NO"
n, R, r = [int(i) for i in input().split()]
print(table(n, R, r))
``` | output | 1 | 97,171 | 23 | 194,343 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gerald is setting the New Year table. The table has the form of a circle; its radius equals R. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal r. Each plate must be completely inside the table and must touch the edge of the table. Of course, the plates must not intersect, but they can touch each other. Help Gerald determine whether the table is large enough for n plates.
Input
The first line contains three integers n, R and r (1 ≤ n ≤ 100, 1 ≤ r, R ≤ 1000) — the number of plates, the radius of the table and the plates' radius.
Output
Print "YES" (without the quotes) if it is possible to place n plates on the table by the rules given above. If it is impossible, print "NO".
Remember, that each plate must touch the edge of the table.
Examples
Input
4 10 4
Output
YES
Input
5 10 4
Output
NO
Input
1 10 10
Output
YES
Note
The possible arrangement of the plates for the first sample is:
<image> | instruction | 0 | 97,172 | 23 | 194,344 |
Tags: geometry, math
Correct Solution:
```
import math
n,R,r=map(int,input().split())
if n==1 :
if r>R :
print("NO")
else:
print("YES")
quit()
if n==2 :
if 2*r>R :
print("NO")
else:
print("YES")
quit()
Rv=2*r/(2*math.sin(360/2/n*math.pi/180))
t=r+Rv
if t>R :
print("NO")
else :
print("YES")
``` | output | 1 | 97,172 | 23 | 194,345 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gerald is setting the New Year table. The table has the form of a circle; its radius equals R. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal r. Each plate must be completely inside the table and must touch the edge of the table. Of course, the plates must not intersect, but they can touch each other. Help Gerald determine whether the table is large enough for n plates.
Input
The first line contains three integers n, R and r (1 ≤ n ≤ 100, 1 ≤ r, R ≤ 1000) — the number of plates, the radius of the table and the plates' radius.
Output
Print "YES" (without the quotes) if it is possible to place n plates on the table by the rules given above. If it is impossible, print "NO".
Remember, that each plate must touch the edge of the table.
Examples
Input
4 10 4
Output
YES
Input
5 10 4
Output
NO
Input
1 10 10
Output
YES
Note
The possible arrangement of the plates for the first sample is:
<image> | instruction | 0 | 97,173 | 23 | 194,346 |
Tags: geometry, math
Correct Solution:
```
from math import pi, sin
n, R, r = map(int, input().split())
print('NO' if r > R or (n > 1 and ((R - r) * sin(pi / n) + 0.0000001) < r) else 'YES')
``` | output | 1 | 97,173 | 23 | 194,347 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gerald is setting the New Year table. The table has the form of a circle; its radius equals R. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal r. Each plate must be completely inside the table and must touch the edge of the table. Of course, the plates must not intersect, but they can touch each other. Help Gerald determine whether the table is large enough for n plates.
Input
The first line contains three integers n, R and r (1 ≤ n ≤ 100, 1 ≤ r, R ≤ 1000) — the number of plates, the radius of the table and the plates' radius.
Output
Print "YES" (without the quotes) if it is possible to place n plates on the table by the rules given above. If it is impossible, print "NO".
Remember, that each plate must touch the edge of the table.
Examples
Input
4 10 4
Output
YES
Input
5 10 4
Output
NO
Input
1 10 10
Output
YES
Note
The possible arrangement of the plates for the first sample is:
<image> | instruction | 0 | 97,174 | 23 | 194,348 |
Tags: geometry, math
Correct Solution:
```
import math
n,R,r=map(int,input().split())
if 2*r>R and n>1:
print('NO')
exit()
if n==1 and r<=R:
print('YES')
exit()
if n==1 and r>R:
print('NO')
exit()
if n>1 and r>=R:
print('NO')
exit()
c = 2*math.pi/(2*math.asin(r/(R-r)))
if c-n>-10**-6:
print('YES')
else:
print('NO')
``` | output | 1 | 97,174 | 23 | 194,349 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gerald is setting the New Year table. The table has the form of a circle; its radius equals R. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal r. Each plate must be completely inside the table and must touch the edge of the table. Of course, the plates must not intersect, but they can touch each other. Help Gerald determine whether the table is large enough for n plates.
Input
The first line contains three integers n, R and r (1 ≤ n ≤ 100, 1 ≤ r, R ≤ 1000) — the number of plates, the radius of the table and the plates' radius.
Output
Print "YES" (without the quotes) if it is possible to place n plates on the table by the rules given above. If it is impossible, print "NO".
Remember, that each plate must touch the edge of the table.
Examples
Input
4 10 4
Output
YES
Input
5 10 4
Output
NO
Input
1 10 10
Output
YES
Note
The possible arrangement of the plates for the first sample is:
<image>
Submitted Solution:
```
from math import cos,pi
p,R,r = map(int,input().split())
if p==1:
if R>=r:
print("YES")
else:
print("NO")
exit()
angle = (p-2)*pi/(p*2)
side = r/cos(angle)
# print(side)
if side+r<=R:
print("YES")
else:
print("NO")
``` | instruction | 0 | 97,175 | 23 | 194,350 |
Yes | output | 1 | 97,175 | 23 | 194,351 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gerald is setting the New Year table. The table has the form of a circle; its radius equals R. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal r. Each plate must be completely inside the table and must touch the edge of the table. Of course, the plates must not intersect, but they can touch each other. Help Gerald determine whether the table is large enough for n plates.
Input
The first line contains three integers n, R and r (1 ≤ n ≤ 100, 1 ≤ r, R ≤ 1000) — the number of plates, the radius of the table and the plates' radius.
Output
Print "YES" (without the quotes) if it is possible to place n plates on the table by the rules given above. If it is impossible, print "NO".
Remember, that each plate must touch the edge of the table.
Examples
Input
4 10 4
Output
YES
Input
5 10 4
Output
NO
Input
1 10 10
Output
YES
Note
The possible arrangement of the plates for the first sample is:
<image>
Submitted Solution:
```
n,R,r = map(int,input().strip().split())
if r>R:
print("NO")
elif 2*r>R:
if n==1:
print("YES")
else:
print("NO")
else:
import math
cnt = math.pi/(math.asin(r/(R-r)))
if cnt>n or abs(cnt-n)<=1e-6:
print("YES")
else:
print("NO")
``` | instruction | 0 | 97,176 | 23 | 194,352 |
Yes | output | 1 | 97,176 | 23 | 194,353 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gerald is setting the New Year table. The table has the form of a circle; its radius equals R. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal r. Each plate must be completely inside the table and must touch the edge of the table. Of course, the plates must not intersect, but they can touch each other. Help Gerald determine whether the table is large enough for n plates.
Input
The first line contains three integers n, R and r (1 ≤ n ≤ 100, 1 ≤ r, R ≤ 1000) — the number of plates, the radius of the table and the plates' radius.
Output
Print "YES" (without the quotes) if it is possible to place n plates on the table by the rules given above. If it is impossible, print "NO".
Remember, that each plate must touch the edge of the table.
Examples
Input
4 10 4
Output
YES
Input
5 10 4
Output
NO
Input
1 10 10
Output
YES
Note
The possible arrangement of the plates for the first sample is:
<image>
Submitted Solution:
```
import math
n,R,r=map(int,input().split())
if n==1 and R>=r:
print("YES")
elif (R-r)*math.sin(math.pi/n)+1e-9<r:
print("NO")
else:
print("YES")
``` | instruction | 0 | 97,177 | 23 | 194,354 |
Yes | output | 1 | 97,177 | 23 | 194,355 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gerald is setting the New Year table. The table has the form of a circle; its radius equals R. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal r. Each plate must be completely inside the table and must touch the edge of the table. Of course, the plates must not intersect, but they can touch each other. Help Gerald determine whether the table is large enough for n plates.
Input
The first line contains three integers n, R and r (1 ≤ n ≤ 100, 1 ≤ r, R ≤ 1000) — the number of plates, the radius of the table and the plates' radius.
Output
Print "YES" (without the quotes) if it is possible to place n plates on the table by the rules given above. If it is impossible, print "NO".
Remember, that each plate must touch the edge of the table.
Examples
Input
4 10 4
Output
YES
Input
5 10 4
Output
NO
Input
1 10 10
Output
YES
Note
The possible arrangement of the plates for the first sample is:
<image>
Submitted Solution:
```
from math import (asin, pi)
def calc(r1, r2):
res = r2 / r1
if res > 1:
return 0
elif 0.5 < res <= 1:
return 1
else:
tmp = r2 / (r1 - r2)
theta = asin(tmp)
return pi / theta
if __name__ == '__main__':
n, R, r = map(int, input().split())
ans = calc(R, r)
if ans >= n or abs(ans - n) <= 1e-6:
print("YES")
else:
print("NO")
``` | instruction | 0 | 97,178 | 23 | 194,356 |
Yes | output | 1 | 97,178 | 23 | 194,357 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gerald is setting the New Year table. The table has the form of a circle; its radius equals R. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal r. Each plate must be completely inside the table and must touch the edge of the table. Of course, the plates must not intersect, but they can touch each other. Help Gerald determine whether the table is large enough for n plates.
Input
The first line contains three integers n, R and r (1 ≤ n ≤ 100, 1 ≤ r, R ≤ 1000) — the number of plates, the radius of the table and the plates' radius.
Output
Print "YES" (without the quotes) if it is possible to place n plates on the table by the rules given above. If it is impossible, print "NO".
Remember, that each plate must touch the edge of the table.
Examples
Input
4 10 4
Output
YES
Input
5 10 4
Output
NO
Input
1 10 10
Output
YES
Note
The possible arrangement of the plates for the first sample is:
<image>
Submitted Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
from collections import defaultdict
from itertools import permutations
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
n,R,r=map(int,input().split())
y=2*r/math.sin(math.pi/n)+r
if y>=R:
print("YES")
else:
print("NO")
``` | instruction | 0 | 97,179 | 23 | 194,358 |
No | output | 1 | 97,179 | 23 | 194,359 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gerald is setting the New Year table. The table has the form of a circle; its radius equals R. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal r. Each plate must be completely inside the table and must touch the edge of the table. Of course, the plates must not intersect, but they can touch each other. Help Gerald determine whether the table is large enough for n plates.
Input
The first line contains three integers n, R and r (1 ≤ n ≤ 100, 1 ≤ r, R ≤ 1000) — the number of plates, the radius of the table and the plates' radius.
Output
Print "YES" (without the quotes) if it is possible to place n plates on the table by the rules given above. If it is impossible, print "NO".
Remember, that each plate must touch the edge of the table.
Examples
Input
4 10 4
Output
YES
Input
5 10 4
Output
NO
Input
1 10 10
Output
YES
Note
The possible arrangement of the plates for the first sample is:
<image>
Submitted Solution:
```
from math import asin, pi
n, R, r = map(int, input().split())
if r > R:
print('NO')
elif 2 * r > R:
print('YES' if n == 1 else 'NO')
else:
a = 2 * asin(r / (R - r))
maxx = (2 * pi) / a + 1
print('YES' if maxx >= n else 'NO')
``` | instruction | 0 | 97,180 | 23 | 194,360 |
No | output | 1 | 97,180 | 23 | 194,361 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gerald is setting the New Year table. The table has the form of a circle; its radius equals R. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal r. Each plate must be completely inside the table and must touch the edge of the table. Of course, the plates must not intersect, but they can touch each other. Help Gerald determine whether the table is large enough for n plates.
Input
The first line contains three integers n, R and r (1 ≤ n ≤ 100, 1 ≤ r, R ≤ 1000) — the number of plates, the radius of the table and the plates' radius.
Output
Print "YES" (without the quotes) if it is possible to place n plates on the table by the rules given above. If it is impossible, print "NO".
Remember, that each plate must touch the edge of the table.
Examples
Input
4 10 4
Output
YES
Input
5 10 4
Output
NO
Input
1 10 10
Output
YES
Note
The possible arrangement of the plates for the first sample is:
<image>
Submitted Solution:
```
import math
n, R, r = map(int, input().split())
if r > R: print("NO")
elif n < 3: print("YES") if n * r <= R else print("NO")
else: print("YES") if n*r <= (R-r)*math.pi else print("NO")
``` | instruction | 0 | 97,181 | 23 | 194,362 |
No | output | 1 | 97,181 | 23 | 194,363 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kavi has 2n points lying on the OX axis, i-th of which is located at x = i.
Kavi considers all ways to split these 2n points into n pairs. Among those, he is interested in good pairings, which are defined as follows:
Consider n segments with ends at the points in correspondent pairs. The pairing is called good, if for every 2 different segments A and B among those, at least one of the following holds:
* One of the segments A and B lies completely inside the other.
* A and B have the same length.
Consider the following example:
<image>
A is a good pairing since the red segment lies completely inside the blue segment.
B is a good pairing since the red and the blue segment have the same length.
C is not a good pairing since none of the red or blue segments lies inside the other, neither do they have the same size.
Kavi is interested in the number of good pairings, so he wants you to find it for him. As the result can be large, find this number modulo 998244353.
Two pairings are called different, if some two points are in one pair in some pairing and in different pairs in another.
Input
The single line of the input contains a single integer n (1≤ n ≤ 10^6).
Output
Print the number of good pairings modulo 998244353.
Examples
Input
1
Output
1
Input
2
Output
3
Input
3
Output
6
Input
100
Output
688750769
Note
The good pairings for the second example are:
<image>
In the third example, the good pairings are:
<image>
Submitted Solution:
```
# cook your dish here
n=int(input())
if n==1:
print(1)
else:
summ=1
mod=998244353
divisor=[0]*n
for i in range(1,n+1):
for j in range(i,n+1,i):
divisor[j-1]+=1
for i in range(2,n+1):
divisor[i-1]+=summ
if divisor[i-1]>mod:
divisor[i-1]-=mod
summ+=divisor[i-1]
if summ>mod:
summ-=mod
print(divisor[n-1])
``` | instruction | 0 | 97,239 | 23 | 194,478 |
Yes | output | 1 | 97,239 | 23 | 194,479 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kavi has 2n points lying on the OX axis, i-th of which is located at x = i.
Kavi considers all ways to split these 2n points into n pairs. Among those, he is interested in good pairings, which are defined as follows:
Consider n segments with ends at the points in correspondent pairs. The pairing is called good, if for every 2 different segments A and B among those, at least one of the following holds:
* One of the segments A and B lies completely inside the other.
* A and B have the same length.
Consider the following example:
<image>
A is a good pairing since the red segment lies completely inside the blue segment.
B is a good pairing since the red and the blue segment have the same length.
C is not a good pairing since none of the red or blue segments lies inside the other, neither do they have the same size.
Kavi is interested in the number of good pairings, so he wants you to find it for him. As the result can be large, find this number modulo 998244353.
Two pairings are called different, if some two points are in one pair in some pairing and in different pairs in another.
Input
The single line of the input contains a single integer n (1≤ n ≤ 10^6).
Output
Print the number of good pairings modulo 998244353.
Examples
Input
1
Output
1
Input
2
Output
3
Input
3
Output
6
Input
100
Output
688750769
Note
The good pairings for the second example are:
<image>
In the third example, the good pairings are:
<image>
Submitted Solution:
```
# by the authority of GOD author: manhar singh sachdev #
def some_random_function():
"""due to the fast IO template, my code gets caught in
plag check for no reason. That is why, I am making
random functions"""
x = 10
x *= 100
i_dont_know = x
why_am_i_writing_this = x*x
print(i_dont_know)
print(why_am_i_writing_this)
def some_random_function5():
"""due to the fast IO template, my code gets caught in
plag check for no reason. That is why, I am making
random functions"""
x = 10
x *= 100
i_dont_know = x
why_am_i_writing_this = x*x
print(i_dont_know)
print(why_am_i_writing_this)
import os,sys
from io import BytesIO,IOBase
from array import array
# 2D list [[0]*large_index for _ in range(small_index)]
# switch from integers to floats if all integers are ≤ 2^52 and > 32 bit int
# fast mod https://github.com/cheran-senthil/PyRival/blob/master/pyrival/misc/mod.py
def main():
mod = 998244353
n = int(input())
dp = array('i',[1]+[0]*n)
fac = [0 for _ in range(n+1)]
for i in range(1,n//2+1):
for j in range(i+i,n+1,i):
fac[j] += 1
su = 1
for i in range(1,n+1):
dp[i] = (su+fac[i])%mod
su = (su+dp[i])%mod
print(dp[n])
#Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def some_random_function1():
"""due to the fast IO template, my code gets caught in
plag check for no reason. That is why, I am making
random functions"""
x = 10
x *= 100
i_dont_know = x
why_am_i_writing_this = x*x
print(i_dont_know)
print(why_am_i_writing_this)
def some_random_function2():
"""due to the fast IO template, my code gets caught in
plag check for no reason. That is why, I am making
random functions"""
x = 10
x *= 100
i_dont_know = x
why_am_i_writing_this = x*x
print(i_dont_know)
print(why_am_i_writing_this)
def some_random_function3():
"""due to the fast IO template, my code gets caught in
plag check for no reason. That is why, I am making
random functions"""
x = 10
x *= 100
i_dont_know = x
why_am_i_writing_this = x*x
print(i_dont_know)
print(why_am_i_writing_this)
def some_random_function4():
"""due to the fast IO template, my code gets caught in
plag check for no reason. That is why, I am making
random functions"""
x = 10
x *= 100
i_dont_know = x
why_am_i_writing_this = x*x
print(i_dont_know)
print(why_am_i_writing_this)
def some_random_function6():
"""due to the fast IO template, my code gets caught in
plag check for no reason. That is why, I am making
random functions"""
x = 10
x *= 100
i_dont_know = x
why_am_i_writing_this = x*x
print(i_dont_know)
print(why_am_i_writing_this)
def some_random_function7():
"""due to the fast IO template, my code gets caught in
plag check for no reason. That is why, I am making
random functions"""
x = 10
x *= 100
i_dont_know = x
why_am_i_writing_this = x*x
print(i_dont_know)
print(why_am_i_writing_this)
def some_random_function8():
"""due to the fast IO template, my code gets caught in
plag check for no reason. That is why, I am making
random functions"""
x = 10
x *= 100
i_dont_know = x
why_am_i_writing_this = x*x
print(i_dont_know)
print(why_am_i_writing_this)
if __name__ == '__main__':
main()
``` | instruction | 0 | 97,240 | 23 | 194,480 |
Yes | output | 1 | 97,240 | 23 | 194,481 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.