text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide a correct Python 3 solution for this coding contest problem.
JOI has a stove in your room. JOI himself is resistant to the cold, so he doesn't need to put on the stove when he is alone in the room, but he needs to put on the stove when there are visitors.
On this day, there are N guests under JOI. The ith (1 \ leq i \ leq N) visitor arrives at time T_i and leaves at time T_i + 1. There can never be more than one visitor at the same time.
JOI can turn the stove on and off at any time. However, each time you turn on the stove, you will consume one match. JOI has only K matches, so he can only stove up to K times. The stove is gone at the beginning of the day.
When the stove is on, fuel is consumed by that amount, so I want to set the time when the stove is on and off and minimize the total time when the stove is on.
Example
Input
3 2
1
3
6
Output
4
"Correct Solution:
```
n, k = map(int, input().split())
li = [int(input()) for i in range(n)]
diff = []
for j in range(n-1):
diff.append(li[j+1]-li[j]-1)
diff.sort(reverse=True)
print(n+sum(diff[k-1:]))
```
| 96,900 |
Provide a correct Python 3 solution for this coding contest problem.
JOI has a stove in your room. JOI himself is resistant to the cold, so he doesn't need to put on the stove when he is alone in the room, but he needs to put on the stove when there are visitors.
On this day, there are N guests under JOI. The ith (1 \ leq i \ leq N) visitor arrives at time T_i and leaves at time T_i + 1. There can never be more than one visitor at the same time.
JOI can turn the stove on and off at any time. However, each time you turn on the stove, you will consume one match. JOI has only K matches, so he can only stove up to K times. The stove is gone at the beginning of the day.
When the stove is on, fuel is consumed by that amount, so I want to set the time when the stove is on and off and minimize the total time when the stove is on.
Example
Input
3 2
1
3
6
Output
4
"Correct Solution:
```
n, k = map(int, input().split())
t = [int(input()) for _ in range(n)]
v = [0 for _ in range(n -1)]
for i in range(n - 1):
v[i] = t[i + 1] - t[i] - 1
v.sort(reverse = True)
print(t[-1] - t[0] + 1 - sum(v[:(k - 1)]))
```
| 96,901 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
JOI has a stove in your room. JOI himself is resistant to the cold, so he doesn't need to put on the stove when he is alone in the room, but he needs to put on the stove when there are visitors.
On this day, there are N guests under JOI. The ith (1 \ leq i \ leq N) visitor arrives at time T_i and leaves at time T_i + 1. There can never be more than one visitor at the same time.
JOI can turn the stove on and off at any time. However, each time you turn on the stove, you will consume one match. JOI has only K matches, so he can only stove up to K times. The stove is gone at the beginning of the day.
When the stove is on, fuel is consumed by that amount, so I want to set the time when the stove is on and off and minimize the total time when the stove is on.
Example
Input
3 2
1
3
6
Output
4
Submitted Solution:
```
def gen_kcombination(lis,k):
if k >= len(lis):
return [lis]
kcombs = []
if k == 1:
return [[x] for x in lis]
for i in range(len(lis) - k+1):
kcombs += [[lis[i]] + x for x in gen_kcombination(lis[i+1:],k-1)]
return kcombs
n,k = map(int,input().split())
numbers = []
times = []
for i in range(n):
numbers.append(i)
times.append(int(input()))
candidates = [ [0] + x for x in gen_kcombination(numbers[1:],k-1)]
bestTime = times[-1] + 1
for i in range(len(candidates)):
candidate = candidates[i]
time = 0
for j in range(k-1):
igniteTime = times[candidate[j]]
extinguishTime = times[candidate[j+1]-1] + 1
time += extinguishTime - igniteTime
time += times[-1] + 1 - times[candidate[-1]]
if bestTime >= time:
bestTime = time
print(time)
```
No
| 96,902 |
Provide a correct Python 3 solution for this coding contest problem.
Multiple polygonal lines are given on the xy-plane. Given a list of polygonal lines and a template, you must find out polygonal lines which have the same shape as the template.
A polygonal line consists of several line segments parallel to x-axis or y-axis. It is defined by a list of xy-coordinates of vertices from the start-point to the end-point in order, and always turns 90 degrees at each vertex. A single polygonal line does not pass the same point twice. Two polygonal lines have the same shape when they fully overlap each other only with rotation and translation within xy-plane (i.e. without magnification or a flip). The vertices given in reverse order from the start-point to the end-point is the same as that given in order.
Figure 1 shows examples of polygonal lines. In this figure, polygonal lines A and B have the same shape.
Write a program that answers polygonal lines which have the same shape as the template.
<image>
---
Figure 1: Polygonal lines
Input
The input consists of multiple datasets. The end of the input is indicated by a line which contains a zero.
A dataset is given as follows.
> n
> Polygonal line0
> Polygonal line1
> Polygonal line2
> ...
> Polygonal linen
n is the number of polygonal lines for the object of search on xy-plane. n is an integer, and 1 <= n <= 50. Polygonal line0 indicates the template.
A polygonal line is given as follows.
> m
> x1 y1
> x2 y2
> ...
> xm ym
>
m is the number of the vertices of a polygonal line (3 <= m <= 10). xi and yi, separated by a space, are the x- and y-coordinates of a vertex, respectively (-10000 < xi < 10000, -10000 <yi < 10000).
Output
For each dataset in the input, your program should report numbers assigned to the polygonal lines that have the same shape as the template, in ascending order. Each number must be written in a separate line without any other characters such as leading or trailing spaces.
Five continuous "+"s must be placed in a line at the end of each dataset.
Example
Input
5
5
0 0
2 0
2 1
4 1
4 0
5
0 0
0 2
-1 2
-1 4
0 4
5
0 0
0 1
-2 1
-2 2
0 2
5
0 0
0 -1
2 -1
2 0
4 0
5
0 0
2 0
2 -1
4 -1
4 0
5
0 0
2 0
2 1
4 1
4 0
4
4
-60 -75
-60 -78
-42 -78
-42 -6
4
10 3
10 7
-4 7
-4 40
4
-74 66
-74 63
-92 63
-92 135
4
-12 22
-12 25
-30 25
-30 -47
4
12 -22
12 -25
30 -25
30 47
3
5
-8 5
-8 2
0 2
0 4
8 4
5
-3 -1
0 -1
0 7
-2 7
-2 16
5
-1 6
-1 3
7 3
7 5
16 5
5
0 1
0 -2
8 -2
8 0
17 0
0
Output
1
3
5
+++++
3
4
+++++
+++++
"Correct Solution:
```
# python template for atcoder1
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
def solve():
N = int(input())
if N == 0:
exit()
n = int(input())
true_Poly = [list(map(int, input().split())) for _ in range(n)]
serach_Polys = []
for _ in range(N):
n = int(input())
serach_Polys.append([list(map(int, input().split()))
for _ in range(n)])
ans = []
for i, poly in enumerate(serach_Polys):
if is_same(true_Poly, poly):
ans.append(i+1)
if ans:
print("\n".join(map(str, ans)))
print("+"*5)
def is_same(poly1, poly2):
if len(poly1) != len(poly2):
return False
poly_1_turn = calc_turn(poly1)
poly_1_len = calc_dist(poly1)
poly_2_turn = calc_turn(poly2)
poly_2_len = calc_dist(poly2)
if all(a == b for a, b in zip(poly_2_turn, poly_1_turn)) and all(a == b for a, b in zip(poly_2_len, poly_1_len)):
return True
poly_2_rev_turn = calc_turn(list(reversed(poly2)))
poly_2_rev_len = calc_dist(list(reversed(poly2)))
if all(a == b for a, b in zip(poly_2_rev_turn, poly_1_turn)) and all(a == b for a, b in zip(poly_2_rev_len, poly_1_len)):
return True
return False
def dist(p1, p2):
return sum([abs(x1-x2) for x1, x2 in zip(p1, p2)])
def calc_dist(poly):
return [dist(p1, p2) for p1, p2 in zip(poly, poly[1:])]
def turn(p1, p2, p3):
"""
右回りが1 左が-1
"""
if p1[0] == p2[0]:
if p1[1] < p2[1]:
if p3[0] > p2[0]:
return 1
else:
return 0
else:
if p3[0] > p2[0]:
return 0
else:
return 1
else:
if p1[0] < p2[0]:
if p3[1] > p2[1]:
return 0
else:
return 1
else:
if p3[1] > p2[1]:
return 1
else:
return 0
def calc_turn(poly):
return [turn(p1, p2, p3) for p1, p2, p3 in zip(poly, poly[1:], poly[2:])]
while True:
solve()
```
| 96,903 |
Provide a correct Python 3 solution for this coding contest problem.
Multiple polygonal lines are given on the xy-plane. Given a list of polygonal lines and a template, you must find out polygonal lines which have the same shape as the template.
A polygonal line consists of several line segments parallel to x-axis or y-axis. It is defined by a list of xy-coordinates of vertices from the start-point to the end-point in order, and always turns 90 degrees at each vertex. A single polygonal line does not pass the same point twice. Two polygonal lines have the same shape when they fully overlap each other only with rotation and translation within xy-plane (i.e. without magnification or a flip). The vertices given in reverse order from the start-point to the end-point is the same as that given in order.
Figure 1 shows examples of polygonal lines. In this figure, polygonal lines A and B have the same shape.
Write a program that answers polygonal lines which have the same shape as the template.
<image>
---
Figure 1: Polygonal lines
Input
The input consists of multiple datasets. The end of the input is indicated by a line which contains a zero.
A dataset is given as follows.
> n
> Polygonal line0
> Polygonal line1
> Polygonal line2
> ...
> Polygonal linen
n is the number of polygonal lines for the object of search on xy-plane. n is an integer, and 1 <= n <= 50. Polygonal line0 indicates the template.
A polygonal line is given as follows.
> m
> x1 y1
> x2 y2
> ...
> xm ym
>
m is the number of the vertices of a polygonal line (3 <= m <= 10). xi and yi, separated by a space, are the x- and y-coordinates of a vertex, respectively (-10000 < xi < 10000, -10000 <yi < 10000).
Output
For each dataset in the input, your program should report numbers assigned to the polygonal lines that have the same shape as the template, in ascending order. Each number must be written in a separate line without any other characters such as leading or trailing spaces.
Five continuous "+"s must be placed in a line at the end of each dataset.
Example
Input
5
5
0 0
2 0
2 1
4 1
4 0
5
0 0
0 2
-1 2
-1 4
0 4
5
0 0
0 1
-2 1
-2 2
0 2
5
0 0
0 -1
2 -1
2 0
4 0
5
0 0
2 0
2 -1
4 -1
4 0
5
0 0
2 0
2 1
4 1
4 0
4
4
-60 -75
-60 -78
-42 -78
-42 -6
4
10 3
10 7
-4 7
-4 40
4
-74 66
-74 63
-92 63
-92 135
4
-12 22
-12 25
-30 25
-30 -47
4
12 -22
12 -25
30 -25
30 47
3
5
-8 5
-8 2
0 2
0 4
8 4
5
-3 -1
0 -1
0 7
-2 7
-2 16
5
-1 6
-1 3
7 3
7 5
16 5
5
0 1
0 -2
8 -2
8 0
17 0
0
Output
1
3
5
+++++
3
4
+++++
+++++
"Correct Solution:
```
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,copy,time
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(input())
def inpl(): return list(map(int, input().split()))
def inpl_str(): return list(input().split())
def calc_ar(bx,by,x,y):
if bx == x:
if y > by:
return 1
else:
return 3
else:
if x > bx:
return 0
else:
return 2
while True:
N = inp()
if N == 0:
break
else:
lines = []
for _ in range(N+1):
m = inp()
xys = [inpl() for _ in range(m)]
dd = []
for i in range(1,m):
bx,by = xys[i-1]
x,y = xys[i]
if x == bx:
dd.append(abs(y-by))
else:
dd.append(abs(x-bx))
ar = []
for i in range(2,m):
x0,y0 = xys[i-2]
x1,y1 = xys[i-1]
x2,y2 = xys[i]
ar01 = calc_ar(x0,y0,x1,y1)
ar12 = calc_ar(x1,y1,x2,y2)
ar.append((ar12 - ar01)%4)
lines.append([dd]+[ar])
for i in range(1,N+1):
dd,ar = lines[i]
if lines[0] == [dd]+[ar]:
print(i)
else:
dd = list(reversed(dd))
ar = [(a+2)%4 for a in reversed(ar)]
if lines[0] == [dd]+[ar]:
print(i)
print('+++++')
```
| 96,904 |
Provide a correct Python 3 solution for this coding contest problem.
Multiple polygonal lines are given on the xy-plane. Given a list of polygonal lines and a template, you must find out polygonal lines which have the same shape as the template.
A polygonal line consists of several line segments parallel to x-axis or y-axis. It is defined by a list of xy-coordinates of vertices from the start-point to the end-point in order, and always turns 90 degrees at each vertex. A single polygonal line does not pass the same point twice. Two polygonal lines have the same shape when they fully overlap each other only with rotation and translation within xy-plane (i.e. without magnification or a flip). The vertices given in reverse order from the start-point to the end-point is the same as that given in order.
Figure 1 shows examples of polygonal lines. In this figure, polygonal lines A and B have the same shape.
Write a program that answers polygonal lines which have the same shape as the template.
<image>
---
Figure 1: Polygonal lines
Input
The input consists of multiple datasets. The end of the input is indicated by a line which contains a zero.
A dataset is given as follows.
> n
> Polygonal line0
> Polygonal line1
> Polygonal line2
> ...
> Polygonal linen
n is the number of polygonal lines for the object of search on xy-plane. n is an integer, and 1 <= n <= 50. Polygonal line0 indicates the template.
A polygonal line is given as follows.
> m
> x1 y1
> x2 y2
> ...
> xm ym
>
m is the number of the vertices of a polygonal line (3 <= m <= 10). xi and yi, separated by a space, are the x- and y-coordinates of a vertex, respectively (-10000 < xi < 10000, -10000 <yi < 10000).
Output
For each dataset in the input, your program should report numbers assigned to the polygonal lines that have the same shape as the template, in ascending order. Each number must be written in a separate line without any other characters such as leading or trailing spaces.
Five continuous "+"s must be placed in a line at the end of each dataset.
Example
Input
5
5
0 0
2 0
2 1
4 1
4 0
5
0 0
0 2
-1 2
-1 4
0 4
5
0 0
0 1
-2 1
-2 2
0 2
5
0 0
0 -1
2 -1
2 0
4 0
5
0 0
2 0
2 -1
4 -1
4 0
5
0 0
2 0
2 1
4 1
4 0
4
4
-60 -75
-60 -78
-42 -78
-42 -6
4
10 3
10 7
-4 7
-4 40
4
-74 66
-74 63
-92 63
-92 135
4
-12 22
-12 25
-30 25
-30 -47
4
12 -22
12 -25
30 -25
30 47
3
5
-8 5
-8 2
0 2
0 4
8 4
5
-3 -1
0 -1
0 7
-2 7
-2 16
5
-1 6
-1 3
7 3
7 5
16 5
5
0 1
0 -2
8 -2
8 0
17 0
0
Output
1
3
5
+++++
3
4
+++++
+++++
"Correct Solution:
```
from sys import exit, stderr, stdin
input = stdin.readline
# setrecursionlimit(10**7)
def debug(var, name="hoge"):
print(name +":" + str(type(var)) + " = " + repr(var), file=stderr)
return
def main():
while(1):
N = int(input())
if N == 0:
break
lines = [0] * (N+1)
for i in range(N+1):
M = int(input())
# はじめはべつに
line = [list(map(int,input().split()))]
par = line[0].copy()
line[0][0] -= par[0]
line[0][1] -= par[1]
for _ in range(M-1):
line.append(list(map(int,input().split())))
line[-1][0] -= par[0]
line[-1][1] -= par[1]
lines[i] = line
# print(lines)
# i が見るの
for i in range(1, N+1):
# はじめと終わりを反転
for __ in range(2):
for _ in range(4):
if lines[0] == lines[i]:
print(i)
# ans += 1
break
for j in range(len(lines[i])):
lines[i][j][0], lines[i][j][1] = lines[i][j][1], -lines[i][j][0]
lines[i] = lines[i][::-1]
# print(lines[i])
par = lines[i][0].copy()
lines[i][0][0] -= par[0]
lines[i][0][1] -= par[1]
for j in range(1, len(lines[i])):
lines[i][j][0] -= par[0]
lines[i][j][1] -= par[1]
print("+++++")
if __name__ == "__main__":
main()
```
| 96,905 |
Provide a correct Python 3 solution for this coding contest problem.
Multiple polygonal lines are given on the xy-plane. Given a list of polygonal lines and a template, you must find out polygonal lines which have the same shape as the template.
A polygonal line consists of several line segments parallel to x-axis or y-axis. It is defined by a list of xy-coordinates of vertices from the start-point to the end-point in order, and always turns 90 degrees at each vertex. A single polygonal line does not pass the same point twice. Two polygonal lines have the same shape when they fully overlap each other only with rotation and translation within xy-plane (i.e. without magnification or a flip). The vertices given in reverse order from the start-point to the end-point is the same as that given in order.
Figure 1 shows examples of polygonal lines. In this figure, polygonal lines A and B have the same shape.
Write a program that answers polygonal lines which have the same shape as the template.
<image>
---
Figure 1: Polygonal lines
Input
The input consists of multiple datasets. The end of the input is indicated by a line which contains a zero.
A dataset is given as follows.
> n
> Polygonal line0
> Polygonal line1
> Polygonal line2
> ...
> Polygonal linen
n is the number of polygonal lines for the object of search on xy-plane. n is an integer, and 1 <= n <= 50. Polygonal line0 indicates the template.
A polygonal line is given as follows.
> m
> x1 y1
> x2 y2
> ...
> xm ym
>
m is the number of the vertices of a polygonal line (3 <= m <= 10). xi and yi, separated by a space, are the x- and y-coordinates of a vertex, respectively (-10000 < xi < 10000, -10000 <yi < 10000).
Output
For each dataset in the input, your program should report numbers assigned to the polygonal lines that have the same shape as the template, in ascending order. Each number must be written in a separate line without any other characters such as leading or trailing spaces.
Five continuous "+"s must be placed in a line at the end of each dataset.
Example
Input
5
5
0 0
2 0
2 1
4 1
4 0
5
0 0
0 2
-1 2
-1 4
0 4
5
0 0
0 1
-2 1
-2 2
0 2
5
0 0
0 -1
2 -1
2 0
4 0
5
0 0
2 0
2 -1
4 -1
4 0
5
0 0
2 0
2 1
4 1
4 0
4
4
-60 -75
-60 -78
-42 -78
-42 -6
4
10 3
10 7
-4 7
-4 40
4
-74 66
-74 63
-92 63
-92 135
4
-12 22
-12 25
-30 25
-30 -47
4
12 -22
12 -25
30 -25
30 47
3
5
-8 5
-8 2
0 2
0 4
8 4
5
-3 -1
0 -1
0 7
-2 7
-2 16
5
-1 6
-1 3
7 3
7 5
16 5
5
0 1
0 -2
8 -2
8 0
17 0
0
Output
1
3
5
+++++
3
4
+++++
+++++
"Correct Solution:
```
ans_list = []
while True:
n = int(input())
if not n:
break
xy = []
for i in range(n + 1):
xy.append([])
m = int(input())
x, y = map(int, input().split())
for j in range(m - 1):
a, b = map(int, input().split())
xy[i].append([a - x, b - y])
if 0 > xy[i][0][0]:
for j in range(m - 1):
this = xy[i][j]
xy[i][j] = [this[0] * -1, this[1] * -1]
elif 0 < xy[i][0][1]:
for j in range(m - 1):
this = xy[i][j]
xy[i][j] = [this[1], this[0] * -1]
elif 0 > xy[i][0][1]:
for j in range(m - 1):
this = xy[i][j]
xy[i][j] = [this[1] * -1, this[0]]
ans = []
import copy
check1 = copy.copy(xy[0])
check2 = []
for i in check1[::-1]:
check2.append([i[1], i[0]])
check2 += [[0, 0]]
for i in range(1, len(check2)):
check2[i][0] = check2[i][0] - check2[0][0]
check2[i][1] = check2[i][1] - check2[0][1]
check2[i][1] *= -1
del check2[0]
m = len(check2) + 1
if 0 > check2[0][0]:
for j in range(m - 1):
this = check2[j]
check2[j] = [this[0] * -1, this[1] * -1]
elif 0 < check2[0][1]:
for j in range(m - 1):
this = check2[j]
check2[j] = [this[1], this[0] * -1]
elif 0 > check2[0][1]:
for j in range(m - 1):
this = check2[j]
check2[j] = [this[1] * -1, this[0]]
for i in range(1, n + 1):
if check1 == xy[i] or check2 == xy[i]:
ans.append(i)
ans.append("+++++")
ans_list.append(ans)
for i in ans_list:
for j in i:
print(j)
```
| 96,906 |
Provide a correct Python 3 solution for this coding contest problem.
Multiple polygonal lines are given on the xy-plane. Given a list of polygonal lines and a template, you must find out polygonal lines which have the same shape as the template.
A polygonal line consists of several line segments parallel to x-axis or y-axis. It is defined by a list of xy-coordinates of vertices from the start-point to the end-point in order, and always turns 90 degrees at each vertex. A single polygonal line does not pass the same point twice. Two polygonal lines have the same shape when they fully overlap each other only with rotation and translation within xy-plane (i.e. without magnification or a flip). The vertices given in reverse order from the start-point to the end-point is the same as that given in order.
Figure 1 shows examples of polygonal lines. In this figure, polygonal lines A and B have the same shape.
Write a program that answers polygonal lines which have the same shape as the template.
<image>
---
Figure 1: Polygonal lines
Input
The input consists of multiple datasets. The end of the input is indicated by a line which contains a zero.
A dataset is given as follows.
> n
> Polygonal line0
> Polygonal line1
> Polygonal line2
> ...
> Polygonal linen
n is the number of polygonal lines for the object of search on xy-plane. n is an integer, and 1 <= n <= 50. Polygonal line0 indicates the template.
A polygonal line is given as follows.
> m
> x1 y1
> x2 y2
> ...
> xm ym
>
m is the number of the vertices of a polygonal line (3 <= m <= 10). xi and yi, separated by a space, are the x- and y-coordinates of a vertex, respectively (-10000 < xi < 10000, -10000 <yi < 10000).
Output
For each dataset in the input, your program should report numbers assigned to the polygonal lines that have the same shape as the template, in ascending order. Each number must be written in a separate line without any other characters such as leading or trailing spaces.
Five continuous "+"s must be placed in a line at the end of each dataset.
Example
Input
5
5
0 0
2 0
2 1
4 1
4 0
5
0 0
0 2
-1 2
-1 4
0 4
5
0 0
0 1
-2 1
-2 2
0 2
5
0 0
0 -1
2 -1
2 0
4 0
5
0 0
2 0
2 -1
4 -1
4 0
5
0 0
2 0
2 1
4 1
4 0
4
4
-60 -75
-60 -78
-42 -78
-42 -6
4
10 3
10 7
-4 7
-4 40
4
-74 66
-74 63
-92 63
-92 135
4
-12 22
-12 25
-30 25
-30 -47
4
12 -22
12 -25
30 -25
30 47
3
5
-8 5
-8 2
0 2
0 4
8 4
5
-3 -1
0 -1
0 7
-2 7
-2 16
5
-1 6
-1 3
7 3
7 5
16 5
5
0 1
0 -2
8 -2
8 0
17 0
0
Output
1
3
5
+++++
3
4
+++++
+++++
"Correct Solution:
```
# coding: utf-8
while 1:
n=int(input())
if n==0:
break
data=[[] for i in range(n+1)]
for i in range(n+1):
m=int(input())
x,y=map(int,input().split())
for j in range(m-1):
_x,_y=map(int,input().split())
data[i].append((abs(_x+_y-x-y),1 if x<_x else 3 if x>_x else 0 if y<_y else 2))
x,y=_x,_y
for i in range(1,n+1):
d=[(e[0],(e[1]+(data[0][0][1]-data[i][0][1]))%4) for e in data[i]]
f=[(e[0],(e[1]+(data[0][0][1]-data[i][-1][1]))%4) for e in data[i][::-1]]
if data[0]==d:
print(i)
elif data[0]==f:
print(i)
print('+++++')
```
| 96,907 |
Provide a correct Python 3 solution for this coding contest problem.
Multiple polygonal lines are given on the xy-plane. Given a list of polygonal lines and a template, you must find out polygonal lines which have the same shape as the template.
A polygonal line consists of several line segments parallel to x-axis or y-axis. It is defined by a list of xy-coordinates of vertices from the start-point to the end-point in order, and always turns 90 degrees at each vertex. A single polygonal line does not pass the same point twice. Two polygonal lines have the same shape when they fully overlap each other only with rotation and translation within xy-plane (i.e. without magnification or a flip). The vertices given in reverse order from the start-point to the end-point is the same as that given in order.
Figure 1 shows examples of polygonal lines. In this figure, polygonal lines A and B have the same shape.
Write a program that answers polygonal lines which have the same shape as the template.
<image>
---
Figure 1: Polygonal lines
Input
The input consists of multiple datasets. The end of the input is indicated by a line which contains a zero.
A dataset is given as follows.
> n
> Polygonal line0
> Polygonal line1
> Polygonal line2
> ...
> Polygonal linen
n is the number of polygonal lines for the object of search on xy-plane. n is an integer, and 1 <= n <= 50. Polygonal line0 indicates the template.
A polygonal line is given as follows.
> m
> x1 y1
> x2 y2
> ...
> xm ym
>
m is the number of the vertices of a polygonal line (3 <= m <= 10). xi and yi, separated by a space, are the x- and y-coordinates of a vertex, respectively (-10000 < xi < 10000, -10000 <yi < 10000).
Output
For each dataset in the input, your program should report numbers assigned to the polygonal lines that have the same shape as the template, in ascending order. Each number must be written in a separate line without any other characters such as leading or trailing spaces.
Five continuous "+"s must be placed in a line at the end of each dataset.
Example
Input
5
5
0 0
2 0
2 1
4 1
4 0
5
0 0
0 2
-1 2
-1 4
0 4
5
0 0
0 1
-2 1
-2 2
0 2
5
0 0
0 -1
2 -1
2 0
4 0
5
0 0
2 0
2 -1
4 -1
4 0
5
0 0
2 0
2 1
4 1
4 0
4
4
-60 -75
-60 -78
-42 -78
-42 -6
4
10 3
10 7
-4 7
-4 40
4
-74 66
-74 63
-92 63
-92 135
4
-12 22
-12 25
-30 25
-30 -47
4
12 -22
12 -25
30 -25
30 47
3
5
-8 5
-8 2
0 2
0 4
8 4
5
-3 -1
0 -1
0 7
-2 7
-2 16
5
-1 6
-1 3
7 3
7 5
16 5
5
0 1
0 -2
8 -2
8 0
17 0
0
Output
1
3
5
+++++
3
4
+++++
+++++
"Correct Solution:
```
class Line:
def __init__(self, n, points):
self.n = n
self.points = points
def getDesc(self):
desc1 = self.getDist(self.points[0], self.points[1])
faceDir = self.getDir(self.points[0], self.points[1])
for i in range(1, self.n - 1):
newDir = self.getDir(self.points[i], self.points[i+1])
desc1 += self.getTurn(faceDir, newDir)
desc1 += self.getDist(self.points[i], self.points[i+1])
faceDir = newDir
desc2 = self.getDist(self.points[-1], self.points[-2])
faceDir = self.getDir(self.points[-1], self.points[-2])
for i in range(self.n - 2, 0, -1):
newDir = self.getDir(self.points[i], self.points[i-1])
desc2 += self.getTurn(faceDir, newDir)
desc2 += self.getDist(self.points[i], self.points[i-1])
faceDir = newDir
return sorted([desc1, desc2])
def getTurn(self, origDir, destDir):
if origDir == 'N':
if destDir == 'E':
return '1'
elif destDir == 'S':
return '2'
elif destDir == 'W':
return '3'
if origDir == 'E':
if destDir == 'S':
return '1'
elif destDir == 'W':
return '2'
elif destDir == 'N':
return '3'
if origDir == 'S':
if destDir == 'W':
return '1'
elif destDir == 'N':
return '2'
elif destDir == 'E':
return '3'
if origDir == 'W':
if destDir == 'N':
return '1'
elif destDir == 'E':
return '2'
elif destDir == 'S':
return '3'
def getDir(self, p1, p2):
if p1[1] < p2[1]:
return 'N'
if p1[0] < p2[0]:
return 'E'
if p1[0] > p2[0]:
return 'W'
if p1[1] > p2[1]:
return 'S'
def getDist(self, p1, p2):
if p1[0] != p2[0]:
return str(abs(p1[0] - p2[0]))
return str(abs(p1[1] - p2[1]))
def getPolyLine():
n = int(input())
points = []
for _ in range(n):
x, y = list(map(int, input().strip().split()))
points.append( (x, y) )
return Line(n, points)
if __name__ == '__main__':
while True:
N = int(input())
if N == 0:
break
polyLine = getPolyLine()
template = polyLine.getDesc()
P = polyLine.n
for idx in range(1, N + 1):
polyLine = getPolyLine()
desc = polyLine.getDesc()
if polyLine.n == P and desc[0] == template[0] and desc[1] == template[1]:
print(idx)
print("+++++")
```
| 96,908 |
Provide a correct Python 3 solution for this coding contest problem.
Multiple polygonal lines are given on the xy-plane. Given a list of polygonal lines and a template, you must find out polygonal lines which have the same shape as the template.
A polygonal line consists of several line segments parallel to x-axis or y-axis. It is defined by a list of xy-coordinates of vertices from the start-point to the end-point in order, and always turns 90 degrees at each vertex. A single polygonal line does not pass the same point twice. Two polygonal lines have the same shape when they fully overlap each other only with rotation and translation within xy-plane (i.e. without magnification or a flip). The vertices given in reverse order from the start-point to the end-point is the same as that given in order.
Figure 1 shows examples of polygonal lines. In this figure, polygonal lines A and B have the same shape.
Write a program that answers polygonal lines which have the same shape as the template.
<image>
---
Figure 1: Polygonal lines
Input
The input consists of multiple datasets. The end of the input is indicated by a line which contains a zero.
A dataset is given as follows.
> n
> Polygonal line0
> Polygonal line1
> Polygonal line2
> ...
> Polygonal linen
n is the number of polygonal lines for the object of search on xy-plane. n is an integer, and 1 <= n <= 50. Polygonal line0 indicates the template.
A polygonal line is given as follows.
> m
> x1 y1
> x2 y2
> ...
> xm ym
>
m is the number of the vertices of a polygonal line (3 <= m <= 10). xi and yi, separated by a space, are the x- and y-coordinates of a vertex, respectively (-10000 < xi < 10000, -10000 <yi < 10000).
Output
For each dataset in the input, your program should report numbers assigned to the polygonal lines that have the same shape as the template, in ascending order. Each number must be written in a separate line without any other characters such as leading or trailing spaces.
Five continuous "+"s must be placed in a line at the end of each dataset.
Example
Input
5
5
0 0
2 0
2 1
4 1
4 0
5
0 0
0 2
-1 2
-1 4
0 4
5
0 0
0 1
-2 1
-2 2
0 2
5
0 0
0 -1
2 -1
2 0
4 0
5
0 0
2 0
2 -1
4 -1
4 0
5
0 0
2 0
2 1
4 1
4 0
4
4
-60 -75
-60 -78
-42 -78
-42 -6
4
10 3
10 7
-4 7
-4 40
4
-74 66
-74 63
-92 63
-92 135
4
-12 22
-12 25
-30 25
-30 -47
4
12 -22
12 -25
30 -25
30 47
3
5
-8 5
-8 2
0 2
0 4
8 4
5
-3 -1
0 -1
0 7
-2 7
-2 16
5
-1 6
-1 3
7 3
7 5
16 5
5
0 1
0 -2
8 -2
8 0
17 0
0
Output
1
3
5
+++++
3
4
+++++
+++++
"Correct Solution:
```
def check(a, b):
for _ in range(4):
if a == b:
return True
b = list(map(lambda x: [-x[1], x[0]], b))
return False
def main(n):
lines = [None] * n
for i in range(n):
m = int(input())
xy = [None] * m
for j in range(m):
xy[j] = list(map(int, input().split()))
lines[i] = xy
x, y = lines[0][0]
ans = list(map(lambda z: [z[0] - x, z[1] - y], lines[0]))
for num, line in enumerate(lines[1:]):
x, y = line[0]
fline = list(map(lambda z: [z[0] - x, z[1] - y], line))
x, y = line[-1]
eline = list(map(lambda z: [z[0] - x, z[1] - y], line[::-1]))
if check(ans, fline) or check(ans, eline):
print(num+1)
print("+" * 5)
while 1:
n = int(input())
if n == 0:
break
main(n + 1)
```
| 96,909 |
Provide a correct Python 3 solution for this coding contest problem.
Multiple polygonal lines are given on the xy-plane. Given a list of polygonal lines and a template, you must find out polygonal lines which have the same shape as the template.
A polygonal line consists of several line segments parallel to x-axis or y-axis. It is defined by a list of xy-coordinates of vertices from the start-point to the end-point in order, and always turns 90 degrees at each vertex. A single polygonal line does not pass the same point twice. Two polygonal lines have the same shape when they fully overlap each other only with rotation and translation within xy-plane (i.e. without magnification or a flip). The vertices given in reverse order from the start-point to the end-point is the same as that given in order.
Figure 1 shows examples of polygonal lines. In this figure, polygonal lines A and B have the same shape.
Write a program that answers polygonal lines which have the same shape as the template.
<image>
---
Figure 1: Polygonal lines
Input
The input consists of multiple datasets. The end of the input is indicated by a line which contains a zero.
A dataset is given as follows.
> n
> Polygonal line0
> Polygonal line1
> Polygonal line2
> ...
> Polygonal linen
n is the number of polygonal lines for the object of search on xy-plane. n is an integer, and 1 <= n <= 50. Polygonal line0 indicates the template.
A polygonal line is given as follows.
> m
> x1 y1
> x2 y2
> ...
> xm ym
>
m is the number of the vertices of a polygonal line (3 <= m <= 10). xi and yi, separated by a space, are the x- and y-coordinates of a vertex, respectively (-10000 < xi < 10000, -10000 <yi < 10000).
Output
For each dataset in the input, your program should report numbers assigned to the polygonal lines that have the same shape as the template, in ascending order. Each number must be written in a separate line without any other characters such as leading or trailing spaces.
Five continuous "+"s must be placed in a line at the end of each dataset.
Example
Input
5
5
0 0
2 0
2 1
4 1
4 0
5
0 0
0 2
-1 2
-1 4
0 4
5
0 0
0 1
-2 1
-2 2
0 2
5
0 0
0 -1
2 -1
2 0
4 0
5
0 0
2 0
2 -1
4 -1
4 0
5
0 0
2 0
2 1
4 1
4 0
4
4
-60 -75
-60 -78
-42 -78
-42 -6
4
10 3
10 7
-4 7
-4 40
4
-74 66
-74 63
-92 63
-92 135
4
-12 22
-12 25
-30 25
-30 -47
4
12 -22
12 -25
30 -25
30 47
3
5
-8 5
-8 2
0 2
0 4
8 4
5
-3 -1
0 -1
0 7
-2 7
-2 16
5
-1 6
-1 3
7 3
7 5
16 5
5
0 1
0 -2
8 -2
8 0
17 0
0
Output
1
3
5
+++++
3
4
+++++
+++++
"Correct Solution:
```
# -*- coding: utf-8 -*-
def main():
N = int(input())
while N:
lines = []
for _ in range(N+1):
tmp = []
M = int(input())
x0, y0 = map(int, input().split())
x1, y1 = map(int, input().split())
x2, y2 = map(int, input().split())
L1 = abs(x0 + y0 - x1 - y1)
L2 = abs(x1 + y1 - x2 - y2)
v1 = [(x1-x0)//L1, (y1-y0)//L1]
v2 = [(x2-x1)//L2, (y2-y1)//L2]
tmp.append(str(L1))
if [-v1[1], v1[0]] == v2:
tmp.append("L")
else:
tmp.append("R")
tmp.append(str(L2))
for _ in range(M-3):
x0, y0 = x1, y1
x1, y1 = x2, y2
x2, y2 = map(int, input().split())
L1 = L2
L2 = abs(x1 + y1 - x2 - y2)
v1 = v2
v2 = [(x2-x1)//L2, (y2-y1)//L2]
if [-v1[1], v1[0]] == v2:
tmp.append("L")
else:
tmp.append("R")
tmp.append(str(L2))
lines.append(tmp)
base1 = "".join(lines[0])
base2 = ""
for l in lines[0][::-1]:
if l == "L":
base2 += "R"
elif l == "R":
base2 += "L"
else:
base2 += l
for i, line in enumerate(lines[1:], start=1):
l = "".join(line)
if l == base1 or l == base2:
print(i)
print("+++++")
N = int(input())
if __name__ == "__main__":
main()
```
| 96,910 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Multiple polygonal lines are given on the xy-plane. Given a list of polygonal lines and a template, you must find out polygonal lines which have the same shape as the template.
A polygonal line consists of several line segments parallel to x-axis or y-axis. It is defined by a list of xy-coordinates of vertices from the start-point to the end-point in order, and always turns 90 degrees at each vertex. A single polygonal line does not pass the same point twice. Two polygonal lines have the same shape when they fully overlap each other only with rotation and translation within xy-plane (i.e. without magnification or a flip). The vertices given in reverse order from the start-point to the end-point is the same as that given in order.
Figure 1 shows examples of polygonal lines. In this figure, polygonal lines A and B have the same shape.
Write a program that answers polygonal lines which have the same shape as the template.
<image>
---
Figure 1: Polygonal lines
Input
The input consists of multiple datasets. The end of the input is indicated by a line which contains a zero.
A dataset is given as follows.
> n
> Polygonal line0
> Polygonal line1
> Polygonal line2
> ...
> Polygonal linen
n is the number of polygonal lines for the object of search on xy-plane. n is an integer, and 1 <= n <= 50. Polygonal line0 indicates the template.
A polygonal line is given as follows.
> m
> x1 y1
> x2 y2
> ...
> xm ym
>
m is the number of the vertices of a polygonal line (3 <= m <= 10). xi and yi, separated by a space, are the x- and y-coordinates of a vertex, respectively (-10000 < xi < 10000, -10000 <yi < 10000).
Output
For each dataset in the input, your program should report numbers assigned to the polygonal lines that have the same shape as the template, in ascending order. Each number must be written in a separate line without any other characters such as leading or trailing spaces.
Five continuous "+"s must be placed in a line at the end of each dataset.
Example
Input
5
5
0 0
2 0
2 1
4 1
4 0
5
0 0
0 2
-1 2
-1 4
0 4
5
0 0
0 1
-2 1
-2 2
0 2
5
0 0
0 -1
2 -1
2 0
4 0
5
0 0
2 0
2 -1
4 -1
4 0
5
0 0
2 0
2 1
4 1
4 0
4
4
-60 -75
-60 -78
-42 -78
-42 -6
4
10 3
10 7
-4 7
-4 40
4
-74 66
-74 63
-92 63
-92 135
4
-12 22
-12 25
-30 25
-30 -47
4
12 -22
12 -25
30 -25
30 47
3
5
-8 5
-8 2
0 2
0 4
8 4
5
-3 -1
0 -1
0 7
-2 7
-2 16
5
-1 6
-1 3
7 3
7 5
16 5
5
0 1
0 -2
8 -2
8 0
17 0
0
Output
1
3
5
+++++
3
4
+++++
+++++
Submitted Solution:
```
while 1:
n=int(input())
if n==0:
break
data=[[] for i in range(n+1)]
for i in range(n+1):
m=int(input())
x,y=map(int,input().split())
for j in range(m-1):
_x,_y=map(int,input().split())
data[i].append((abs(_x+_y-x-y),1 if x<_x else 3 if x>_x else 0 if y< _y else 2 ))
x,y=_x,_y
for i in range(1,n+1):
d=[(e[0], (e[1]+(data[0][0][1]-data[i][0][1]))%4) for e in data[i]]
f=[(e[0], (e[1]+(data[0][0][1]-data[i][-1][1]))%4) for e in data[i][::-1]]
if data[0]==d:
print(i)
elif data[0]==f:
print(i)
print('+++++')
```
Yes
| 96,911 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Multiple polygonal lines are given on the xy-plane. Given a list of polygonal lines and a template, you must find out polygonal lines which have the same shape as the template.
A polygonal line consists of several line segments parallel to x-axis or y-axis. It is defined by a list of xy-coordinates of vertices from the start-point to the end-point in order, and always turns 90 degrees at each vertex. A single polygonal line does not pass the same point twice. Two polygonal lines have the same shape when they fully overlap each other only with rotation and translation within xy-plane (i.e. without magnification or a flip). The vertices given in reverse order from the start-point to the end-point is the same as that given in order.
Figure 1 shows examples of polygonal lines. In this figure, polygonal lines A and B have the same shape.
Write a program that answers polygonal lines which have the same shape as the template.
<image>
---
Figure 1: Polygonal lines
Input
The input consists of multiple datasets. The end of the input is indicated by a line which contains a zero.
A dataset is given as follows.
> n
> Polygonal line0
> Polygonal line1
> Polygonal line2
> ...
> Polygonal linen
n is the number of polygonal lines for the object of search on xy-plane. n is an integer, and 1 <= n <= 50. Polygonal line0 indicates the template.
A polygonal line is given as follows.
> m
> x1 y1
> x2 y2
> ...
> xm ym
>
m is the number of the vertices of a polygonal line (3 <= m <= 10). xi and yi, separated by a space, are the x- and y-coordinates of a vertex, respectively (-10000 < xi < 10000, -10000 <yi < 10000).
Output
For each dataset in the input, your program should report numbers assigned to the polygonal lines that have the same shape as the template, in ascending order. Each number must be written in a separate line without any other characters such as leading or trailing spaces.
Five continuous "+"s must be placed in a line at the end of each dataset.
Example
Input
5
5
0 0
2 0
2 1
4 1
4 0
5
0 0
0 2
-1 2
-1 4
0 4
5
0 0
0 1
-2 1
-2 2
0 2
5
0 0
0 -1
2 -1
2 0
4 0
5
0 0
2 0
2 -1
4 -1
4 0
5
0 0
2 0
2 1
4 1
4 0
4
4
-60 -75
-60 -78
-42 -78
-42 -6
4
10 3
10 7
-4 7
-4 40
4
-74 66
-74 63
-92 63
-92 135
4
-12 22
-12 25
-30 25
-30 -47
4
12 -22
12 -25
30 -25
30 47
3
5
-8 5
-8 2
0 2
0 4
8 4
5
-3 -1
0 -1
0 7
-2 7
-2 16
5
-1 6
-1 3
7 3
7 5
16 5
5
0 1
0 -2
8 -2
8 0
17 0
0
Output
1
3
5
+++++
3
4
+++++
+++++
Submitted Solution:
```
import sys
def spin(x):
result=[]
for i in x:
result.append([-1*i[1],i[0]])
return result
def rev(x):
y=x.copy()
y.reverse()
a=y[0][0]
b=y[0][1]
for i in y:
i[0]-=a
i[1]-=b
return y
def check(x):
if x==line_original or spin(x)==line_original or spin(spin(x))==line_original or spin(spin(spin(x)))==line_original:
return True
else:
return False
while True:
n=int(input())
if n==0:
sys.exit()
m=int(input())
line_original=[[0,0]]
a,b=[int(i) for i in input().split(" ")]
for count in range(m-1):
p,q=[int(i) for i in input().split(" ")]
line_original.append([p-a,q-b])
line_list=[]
for loop in range(n):
m=int(input())
line=[[0,0]]
a,b=[int(i) for i in input().split(" ")]
for count in range(m-1):
p,q=[int(i) for i in input().split(" ")]
line.append([p-a,q-b])
line_list.append(line)
for i in range(n):
if (check(line_list[i])==True) or (check(rev(line_list[i]))==True):
print(i+1)
print("+++++")
```
Yes
| 96,912 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Multiple polygonal lines are given on the xy-plane. Given a list of polygonal lines and a template, you must find out polygonal lines which have the same shape as the template.
A polygonal line consists of several line segments parallel to x-axis or y-axis. It is defined by a list of xy-coordinates of vertices from the start-point to the end-point in order, and always turns 90 degrees at each vertex. A single polygonal line does not pass the same point twice. Two polygonal lines have the same shape when they fully overlap each other only with rotation and translation within xy-plane (i.e. without magnification or a flip). The vertices given in reverse order from the start-point to the end-point is the same as that given in order.
Figure 1 shows examples of polygonal lines. In this figure, polygonal lines A and B have the same shape.
Write a program that answers polygonal lines which have the same shape as the template.
<image>
---
Figure 1: Polygonal lines
Input
The input consists of multiple datasets. The end of the input is indicated by a line which contains a zero.
A dataset is given as follows.
> n
> Polygonal line0
> Polygonal line1
> Polygonal line2
> ...
> Polygonal linen
n is the number of polygonal lines for the object of search on xy-plane. n is an integer, and 1 <= n <= 50. Polygonal line0 indicates the template.
A polygonal line is given as follows.
> m
> x1 y1
> x2 y2
> ...
> xm ym
>
m is the number of the vertices of a polygonal line (3 <= m <= 10). xi and yi, separated by a space, are the x- and y-coordinates of a vertex, respectively (-10000 < xi < 10000, -10000 <yi < 10000).
Output
For each dataset in the input, your program should report numbers assigned to the polygonal lines that have the same shape as the template, in ascending order. Each number must be written in a separate line without any other characters such as leading or trailing spaces.
Five continuous "+"s must be placed in a line at the end of each dataset.
Example
Input
5
5
0 0
2 0
2 1
4 1
4 0
5
0 0
0 2
-1 2
-1 4
0 4
5
0 0
0 1
-2 1
-2 2
0 2
5
0 0
0 -1
2 -1
2 0
4 0
5
0 0
2 0
2 -1
4 -1
4 0
5
0 0
2 0
2 1
4 1
4 0
4
4
-60 -75
-60 -78
-42 -78
-42 -6
4
10 3
10 7
-4 7
-4 40
4
-74 66
-74 63
-92 63
-92 135
4
-12 22
-12 25
-30 25
-30 -47
4
12 -22
12 -25
30 -25
30 47
3
5
-8 5
-8 2
0 2
0 4
8 4
5
-3 -1
0 -1
0 7
-2 7
-2 16
5
-1 6
-1 3
7 3
7 5
16 5
5
0 1
0 -2
8 -2
8 0
17 0
0
Output
1
3
5
+++++
3
4
+++++
+++++
Submitted Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
rr = []
def f(a):
m = len(a)
r = []
if a[0][0] == a[1][0]:
if a[0][1] < a[1][1]:
r = [(a[i][0]-a[i+1][0], a[i][1]-a[i+1][1]) for i in range(m-1)]
else:
r = [(a[i+1][0]-a[i][0], a[i+1][1]-a[i][1]) for i in range(m-1)]
else:
if a[0][0] < a[1][0]:
r = [(a[i+1][1]-a[i][1], a[i][0]-a[i+1][0]) for i in range(m-1)]
else:
r = [(a[i][1]-a[i+1][1], a[i+1][0]-a[i][0]) for i in range(m-1)]
return tuple(r)
while True:
n = I()
if n == 0:
break
a = []
for _ in range(n+1):
m = I()
a.append([LI() for _ in range(m)])
t = f(a[0])
r = []
for i in range(1,n+1):
if t == f(a[i]) or t == f(a[i][::-1]):
rr.append(i)
rr.append('+++++')
return '\n'.join(map(str, rr))
print(main())
```
Yes
| 96,913 |
Provide a correct Python 3 solution for this coding contest problem.
<!--
Problem D
-->
Tally Counters
A number of tally counters are placed in a row. Pushing the button on a counter will increment the displayed value by one, or, when the value is already the maximum, it goes down to one. All the counters are of the same model with the same maximum value.
<image> Fig. D-1 Tally Counters
Starting from the values initially displayed on each of the counters, you want to change all the displayed values to target values specified for each. As you don't want the hassle, however, of pushing buttons of many counters one be one, you devised a special tool. Using the tool, you can push buttons of one or more adjacent counters, one push for each, in a single operation. You can choose an arbitrary number of counters at any position in each operation, as far as they are consecutively lined up.
How many operations are required at least to change the displayed values on counters to the target values?
Input
The input consists of multiple datasets, each in the following format.
> n m
> a1 a2 ... an
> b1 b2 ... bn
>
Each dataset consists of 3 lines. The first line contains n (1 ≤ n ≤ 1000) and m (1 ≤ m ≤ 10000), the number of counters and the maximum value displayed on counters, respectively. The second line contains the initial values on counters, ai (1 ≤ ai ≤ m), separated by spaces. The third line contains the target values on counters, bi (1 ≤ bi ≤ m), separated by spaces.
The end of the input is indicated by a line containing two zeros. The number of datasets does not exceed 100.
Output
For each dataset, print in a line the minimum number of operations required to make all of the counters display the target values.
Sample Input
4 5
2 3 1 4
2 5 5 2
3 100
1 10 100
1 10 100
5 10000
4971 7482 1238 8523 1823
3287 9013 9812 297 1809
0 0
Output for the Sample Input
4
0
14731
Example
Input
4 5
2 3 1 4
2 5 5 2
3 100
1 10 100
1 10 100
5 10000
4971 7482 1238 8523 1823
3287 9013 9812 297 1809
0 0
Output
4
0
14731
"Correct Solution:
```
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve(C, N, M, range = range, min = min):
K = N // 4 + 1
S = [0]*K
T = [0]*K
U = [0]*(K+1)
for i in range(N-1):
U[0] = 10**18
for j in range(K):
U[j+1] = min(U[j], S[j])
k = K-1
ci = C[i]; cj = C[i+1]
r = 10**18
for j in range(K-1, -1, -1):
while ci + k*M > cj + j*M:
r = min(r, ci + k*M + S[k])
k -= 1
T[j] = min(r - j*M - cj, U[k+1])
S, T = T, S
ci = C[-1]
for i in range(K):
S[i] += ci + i*M
write("%d\n" % min(S))
while 1:
N, M = map(int, readline().split())
if N == 0:
break
*A, = map(int, readline().split())
*B, = map(int, readline().split())
C = [(b - a) % M for a, b in zip(A, B)]
solve(C, N, M)
```
| 96,914 |
Provide a correct Python 3 solution for this coding contest problem.
Saving electricity is very important!
You are in the office represented as R \times C grid that consists of walls and rooms. It is guaranteed that, for any pair of rooms in the office, there exists exactly one route between the two rooms. It takes 1 unit of time for you to move to the next room (that is, the grid adjacent to the current room). Rooms are so dark that you need to switch on a light when you enter a room. When you leave the room, you can either leave the light on, or of course you can switch off the light. Each room keeps consuming electric power while the light is on.
Today you have a lot of tasks across the office. Tasks are given as a list of coordinates, and they need to be done in the specified order. To save electricity, you want to finish all the tasks with the minimal amount of electric power.
The problem is not so easy though, because you will consume electricity not only when light is on, but also when you switch on/off the light. Luckily, you know the cost of power consumption per unit time and also the cost to switch on/off the light for all the rooms in the office. Besides, you are so smart that you don't need any time to do the tasks themselves. So please figure out the optimal strategy to minimize the amount of electric power consumed.
After you finished all the tasks, please DO NOT leave the light on at any room. It's obviously wasting!
Input
The first line of the input contains three positive integers R (0 \lt R \leq 50), C (0 \lt C \leq 50) and M (2 \leq M \leq 1000). The following R lines, which contain C characters each, describe the layout of the office. '.' describes a room and '#' describes a wall.
This is followed by three matrices with R rows, C columns each. Every elements of the matrices are positive integers. The (r, c) element in the first matrix describes the power consumption per unit of time for the room at the coordinate (r, c). The (r, c) element in the second matrix and the third matrix describe the cost to turn on the light and the cost to turn off the light, respectively, in the room at the coordinate (r, c).
Each of the last M lines contains two positive integers, which describe the coodinates of the room for you to do the task.
Note that you cannot do the i-th task if any of the j-th task (0 \leq j \leq i) is left undone.
Output
Print one integer that describes the minimal amount of electric power consumed when you finished all the tasks.
Examples
Input
1 3 2
...
1 1 1
1 2 1
1 1 1
0 0
0 2
Output
7
Input
3 3 5
...
.##
..#
1 1 1
1 0 0
1 1 0
3 3 3
3 0 0
3 3 0
5 4 5
4 0 0
5 4 0
1 0
2 1
0 2
2 0
0 0
Output
77
Input
5 5 10
.###
....
.#
..#.#
....
0 12 0 0 0
0 4 3 2 10
0 0 0 99 0
11 13 0 2 0
0 1 1 2 1
0 4 0 0 0
0 13 8 2 4
0 0 0 16 0
1 1 0 2 0
0 2 3 1 99
0 2 0 0 0
0 12 2 12 2
0 0 0 3 0
4 14 0 16 0
0 2 14 2 90
0 1
3 0
4 4
1 4
1 1
4 4
1 1
4 3
3 0
1 4
Output
777
"Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**13
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
rr = []
def f():
r,c,m = LI()
a = [[1] * (c+2)] + [[1] + [None if c == '.' else 1 for c in S()] + [1] for _ in range(r)] + [[1] * (c+2)]
cost = [[1] * (c+2)] + [[1] + LI() + [1] for _ in range(r)] + [[1] * (c+2)]
on = [[1] * (c+2)] + [[1] + LI() + [1] for _ in range(r)] + [[1] * (c+2)]
off = [[1] * (c+2)] + [[1] + LI() + [1] for _ in range(r)] + [[1] * (c+2)]
ms = [tuple(map(lambda x: x+1, LI())) for _ in range(m)]
e = collections.defaultdict(list)
for i in range(1,r+1):
for j in range(1,c+1):
if a[i][j]:
continue
for di,dj in dd:
if a[i+di][j+dj]:
continue
e[(i,j)].append(((i+di,j+dj), 1))
def search(s):
d = collections.defaultdict(lambda: inf)
d[s] = 0
q = []
heapq.heappush(q, (0, s))
v = collections.defaultdict(bool)
while len(q):
k, u = heapq.heappop(q)
if v[u]:
continue
v[u] = True
for uv, ud in e[u]:
if v[uv]:
continue
vd = k + ud
if d[uv] > vd:
d[uv] = vd
heapq.heappush(q, (vd, uv))
return d
ad = {}
for k in ms:
if k in ad:
continue
ad[k] = search(k)
ti = 0
td = collections.defaultdict(list)
c = ms[0]
td[c].append(0)
for t in ms[1:]:
while c != t:
cc = ad[t][c]
for di,dj in dd:
ni = c[0] + di
nj = c[1] + dj
n = (ni, nj)
if ad[t][n] == cc - 1:
ti += 1
td[n].append(ti)
c = n
break
r = 0
for k,v in sorted(td.items()):
i = k[0]
j = k[1]
cs = cost[i][j]
onf = on[i][j] + off[i][j]
tr = onf
for vi in range(len(v)-1):
sa = v[vi+1] - v[vi]
tr += min(cs * sa, onf)
r += tr
return r
while True:
rr.append(f())
break
return '\n'.join(map(str,rr))
print(main())
```
| 96,915 |
Provide a correct Python 3 solution for this coding contest problem.
Fox Ciel is developing an artificial intelligence (AI) for a game. This game is described as a game tree T with n vertices. Each node in the game has an evaluation value which shows how good a situation is. This value is the same as maximum value of child nodes’ values multiplied by -1. Values on leaf nodes are evaluated with Ciel’s special function -- which is a bit heavy. So, she will use alpha-beta pruning for getting root node’s evaluation value to decrease the number of leaf nodes to be calculated.
By the way, changing evaluation order of child nodes affects the number of calculation on the leaf nodes. Therefore, Ciel wants to know the minimum and maximum number of times to calculate in leaf nodes when she could evaluate child node in arbitrary order. She asked you to calculate minimum evaluation number of times and maximum evaluation number of times in leaf nodes.
Ciel uses following algotithm:
function negamax(node, α, β)
if node is a terminal node
return value of leaf node
else
foreach child of node
val := -negamax(child, -β, -α)
if val >= β
return val
if val > α
α := val
return α
[NOTE] negamax algorithm
Input
Input follows following format:
n
p_1 p_2 ... p_n
k_1 t_{11} t_{12} ... t_{1k}
:
:
k_n t_{n1} t_{n2} ... t_{nk}
The first line contains an integer n, which means the number of vertices in game tree T.
The second line contains n integers p_i, which means the evaluation value of vertex i.
Then, next n lines which contain the information of game tree T.
k_i is the number of child nodes of vertex i, and t_{ij} is the indices of the child node of vertex i.
Input follows following constraints:
* 2 \leq n \leq 100
* -10,000 \leq p_i \leq 10,000
* 0 \leq k_i \leq 5
* 2 \leq t_{ij} \leq n
* Index of root node is 1.
* Evaluation value except leaf node is always 0. This does not mean the evaluation values of non-leaf nodes are 0. You have to calculate them if necessary.
* Leaf node sometimes have evaluation value of 0.
* Game tree T is tree structure.
Output
Print the minimum evaluation number of times and the maximum evaluation number of times in leaf node.
Please separated by whitespace between minimum and maximum.
minimum maximum
Sample Input 1
3
0 1 1
2 2 3
0
0
Output for the Sample Input 1
2 2
Sample Input 2
8
0 0 100 100 0 -100 -100 -100
2 2 5
2 3 4
0
0
3 6 7 8
0
0
0
Output for the Sample Input 2
3 5
Sample Input 3
8
0 0 100 100 0 100 100 100
2 2 5
2 3 4
0
0
3 6 7 8
0
0
0
Output for the Sample Input 3
3 4
Sample Input 4
19
0 100 0 100 0 0 0 0 0 1 2 3 4 5 6 7 8 9 10
2 2 3
0
2 4 5
0
3 6 7 8
3 9 10 11
3 12 13 14
3 15 16 17
2 18 19
0
0
0
0
0
0
0
0
0
0
Output for the Sample Input 4
7 12
Example
Input
3
0 1 1
2 2 3
0
0
Output
2 2
"Correct Solution:
```
from collections import deque
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N = int(readline())
*P, = map(int, readline().split())
G = []
prt = [0]*N
for i in range(N):
k, *t = map(int, readline().split())
G.append([e-1 for e in t])
for e in t:
prt[e-1] = i
*D, = map(len, G)
A = [0]*N
deg = D[:]
que = deque()
for v in range(N):
if deg[v] == 0:
A[v] = P[v]
que.append(v)
while que:
v = que.popleft()
p = prt[v]
deg[p] -= 1
if deg[p] == 0:
A[p] = max(-A[w] for w in G[p])
que.append(p)
for v in range(N):
if D[v] == 0:
A[v] = P[v]
else:
A[v] = max(-A[w] for w in G[v])
memo = {}
def dfs(v, state, c, a, b):
key = (v, state, a, b)
if key in memo:
return memo[key]
if c == D[v]:
if c == 0:
return 1, 1
return 0, 0
c0 = N+1; c1 = 0
Gv = G[v]
for k in range(D[v]):
if state & (1 << k):
continue
w = Gv[k]
s0, s1 = dfs(w, 0, 0, -b, -a)
val = -A[w]
if val >= b:
c0 = min(c0, s0); c1 = max(c1, s1)
continue
t0, t1 = dfs(v, state | (1 << k), c+1, max(a, val), b)
c0 = min(c0, s0+t0)
c1 = max(c1, s1+t1)
memo[key] = c0, c1
return c0, c1
INF = 10**9
r0, r1 = dfs(0, 0, 0, -INF, INF)
write("%d %d\n" % (r0, r1))
solve()
```
| 96,916 |
Provide a correct Python 3 solution for this coding contest problem.
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
"Correct Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
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
"""
import sys
class Segment(object):
__slots__ = ('source', 'target')
def __init__(self, source, target):
self.source = complex(source)
self.target = complex(target)
def cross(a, b):
return a.real * b.imag - a.imag * b.real
def dot(a, b):
return a.real * b.real + a.imag * b.imag
def get_cross_point(s1, s2):
base_vector = s2.target - s2.source
d1 = abs(cross(base_vector, s1.source - s2.source))
d2 = abs(cross(base_vector, s1.target - s2.source))
t = d1 / (d1 + d2)
cross_point = s1.source + (s1.target - s1.source) * t
print('{real:.10f} {imag:.10f}'.format(real=cross_point.real, imag=cross_point.imag))
return None
def solve(_lines):
for line in _lines:
line = tuple(map(int, line))
p0, p1, p2, p3 = (x + y * 1j for x, y in zip(line[::2], line[1::2]))
s1, s2 = Segment(p0, p1), Segment(p2, p3)
get_cross_point(s1, s2)
return None
if __name__ == '__main__':
_input = sys.stdin.readlines()
l_num = int(_input[0])
lines = map(lambda x: x.split(), _input[1:])
solve(lines)
```
| 96,917 |
Provide a correct Python 3 solution for this coding contest problem.
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
"Correct Solution:
```
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_C&lang=jp
"""
import sys
from sys import stdin
input = stdin.readline
class Point(object):
epsilon = 1e-10
def __init__(self, x=0.0, y=0.0):
if isinstance(x, tuple):
self.x = x[0]
self.y = x[1]
else:
self.x = x
self.y = y
# ????????????
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Point(self.x - other.x, self.y - other.y)
def __mul__(self, other):
return Point(other * self.x, other * self.y)
def __truediv__(self, other):
return Point(other / self.x, other / self.y)
def __lt__(self, other):
if self.x == other.x:
return self.y < other.y
else:
return self.x < other.x
def __eq__(self, other):
from math import fabs
if fabs(self.x - other.x) < Point.epsilon and fabs(self.y - other.y) < Point.epsilon:
return True
else:
return False
def norm(self):
return self.x * self.x + self.y * self.y
def abs(self):
from math import sqrt
return sqrt(self.norm())
class Vector(Point):
def __init__(self, x=0.0, y=0.0):
if isinstance(x, tuple):
self.x = x[0]
self.y = x[1]
elif isinstance(x, Point):
self.x = x.x
self.y = x.y
else:
self.x = x
self.y = y
# ????????????
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __mul__(self, other):
return Vector(other * self.x, other * self.y)
def __truediv__(self, other):
return Vector(other / self.x, other / self.y)
@classmethod
def dot(cls, a, b):
return a.x * b.x + a.y * b.y
@classmethod
def cross(cls, a, b):
return a.x * b.y - a.y * b.x
@classmethod
def is_orthogonal(cls, a, b):
return Vector.dot(a, b) == 0.0
@classmethod
def is_parallel(cls, a, b):
return Vector.cross(a, b) == 0.0
class Segment(object):
def __init__(self, p1=Point(), p2=Point()):
if isinstance(p1, Point):
self.p1 = p1
self.p2 = p2
elif isinstance(p1, tuple):
self.p1 = Point(p1[0], p1[1])
self.p2 = Point(p2[0], p2[1])
@classmethod
def is_orthogonal(cls, s1, s2):
a = Vector(s1.p2 - s1.p1)
b = Vector(s2.p2 - s2.p1)
return Vector.is_orthogonal(a, b)
@classmethod
def is_parallel(cls, s1, s2):
a = Vector(s1.p2 - s1.p1)
b = Vector(s2.p2 - s2.p1)
return Vector.is_parallel(a, b)
class Line(Segment):
pass
class Cirle(object):
def __init__(self, c=Point(), r=0.0):
self.c = c
self.r = r
def ccw(p0, p1, p2):
a = Vector(p1 - p0)
b = Vector(p2 - p0)
epsilon = 1e-10
if Vector.cross(a, b) > epsilon:
return 1 # 'COUNTER_CLOCKWISE'
elif Vector.cross(a, b) < -epsilon:
return -1 # 'CLOCKWISE'
elif Vector.dot(a, b) < -epsilon:
return 2 # 'ONLINE_BACK'
elif a.norm() < b.norm():
return -2 # 'ONLINE_FRONT'
else:
return 0 # 'ON_SEGMENT'
def cross_point(s1, s2):
base = s2.p2 - s2.p1
d1 = abs(Vector.cross(base, s1.p1-s2.p1))
d2 = abs(Vector.cross(base, s1.p2-s2.p1))
t = d1 / (d1 + d2)
return s1.p1 + (s1.p2 - s1.p1) * t
def main(args):
q = int(input())
for _ in range(q):
x_p0, y_p0, x_p1, y_p1, x_p2, y_p2, x_p3, y_p3 = map(int, input().split())
p0 = Point(x_p0, y_p0)
p1 = Point(x_p1, y_p1)
p2 = Point(x_p2, y_p2)
p3 = Point(x_p3, y_p3)
s1 = Segment(p0, p1)
s2 = Segment(p2, p3)
result = cross_point(s1, s2)
print('{:.10f} {:.10f}'.format(result.x, result.y))
if __name__ == '__main__':
main(sys.argv[1:])
```
| 96,918 |
Provide a correct Python 3 solution for this coding contest problem.
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
"Correct Solution:
```
def cross(a: complex, b: complex) -> float:
return float(a.real * b.imag - a.imag * b.real)
def cross_point(p1: complex, p2: complex, p3: complex, p4: complex) -> complex:
base = p4 - p3
hypo1 = p1 - p3
hypo2 = p2 - p3
d1 = abs(cross(base, hypo1)) / abs(base)
d2 = abs(cross(base, hypo2)) / abs(base)
cross_point = p1 + d1 / (d1 + d2) * (p2 - p1)
return cross_point
if __name__ == "__main__":
q = int(input())
for _ in range(q):
x_p0, y_p0, x_p1, y_p1, x_p2, y_p2, x_p3, y_p3 = map(lambda x: int(x),
input().split())
p0 = complex(x_p0, y_p0)
p1 = complex(x_p1, y_p1)
p2 = complex(x_p2, y_p2)
p3 = complex(x_p3, y_p3)
ans = cross_point(p0, p1, p2, p3)
print(f"{ans.real} {ans.imag}")
```
| 96,919 |
Provide a correct Python 3 solution for this coding contest problem.
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
"Correct Solution:
```
EPS = 10**(-9)
def is_equal(a,b):
return abs(a-b) < EPS
def norm(v,i=2):
import math
ret = 0
n = len(v)
for j in range(n):
ret += abs(v[j])**i
return math.pow(ret,1/i)
class Vector(list):
"""
ベクトルクラス
対応演算子
+ : ベクトル和
- : ベクトル差
* : スカラー倍、または内積
/ : スカラー除法
** : 外積
+= : ベクトル和
-= : ベクトル差
*= : スカラー倍
/= : スカラー除法
メソッド
self.norm(i) : L{i}ノルムを計算
"""
def __add__(self,other):
n = len(self)
ret = [0]*n
for i in range(n):
ret[i] = super().__getitem__(i) + other.__getitem__(i)
return self.__class__(ret)
def __radd__(self,other):
n = len(self)
ret = [0]*n
for i in range(n):
ret[i] = other.__getitem__(i) + super().__getitem__(i)
return self.__class__(ret)
def __iadd__(self, other):
n = len(self)
for i in range(n):
self[i] += other.__getitem__(i)
return self
def __sub__(self,others):
n = len(self)
ret = [0]*n
for i in range(n):
ret[i] = super().__getitem__(i) - others.__getitem__(i)
return self.__class__(ret)
def __isub__(self, other):
n = len(self)
for i in range(n):
self[i] -= other.__getitem__(i)
return self
def __rsub__(self,others):
n = len(self)
ret = [0]*n
for i in range(n):
ret[i] = others.__getitem__(i) - super().__getitem__(i)
return self.__class__(ret)
def __mul__(self,other):
n = len(self)
if isinstance(other,list):
ret = 0
for i in range(n):
ret += super().__getitem__(i)*other.__getitem__(i)
return ret
else:
ret = [0]*n
for i in range(n):
ret[i] = super().__getitem__(i)*other
return self.__class__(ret)
def __rmul__(self,other):
n = len(self)
if isinstance(other,list):
ret = 0
for i in range(n):
ret += super().__getitem__(i)*other.__getitem__(i)
return ret
else:
ret = [0]*n
for i in range(n):
ret[i] = super().__getitem__(i)*other
return self.__class__(ret)
def __truediv__(self,other):
"""
ベクトルのスカラー除法
Vector/scalar
"""
n = len(self)
ret = [0]*n
for i in range(n):
ret[i] = super().__getitem__(i)/other
return self.__class__(ret)
def norm(self,i):
"""
L{i}ノルム
self.norm(i)
"""
return norm(self,i)
def __pow__(self,other):
"""
外積
self**other
"""
n = len(self)
ret = [0]*3
x = self[:]
y = other[:]
if n == 2:
x.append(0)
y.append(0)
if n == 2 or n == 3:
for i in range(3):
ret[0],ret[1],ret[2] = x[1]*y[2]-x[2]*y[1],x[2]*y[0]-x[0]*y[2],x[0]*y[1]-x[1]*y[0]
ret = Vector(ret)
if n == 2:
return ret
else:
return ret
class Segment:
"""
線分クラス
methods
length() :
get_unit_vec() :
projection(vector) :
is_vertical(segment) :
is_horizontal(segment) :
reflection() :
include() :
distance() :
ccw() :
intersect() :
"""
def __init__(self,v1,v2):
self.v1 = v1
self.v2 = v2
def length(self):
return norm(self.v1-self.v2)
def get_unit_vec(self):
#方向単位ベクトル
dist = norm(self.v2-self.v1)
if dist != 0:
return (self.v2-self.v1)/dist
else:
return False
def projection(self,vector):
#射影点(線分を直線と見たときの)
unit_vec = self.get_unit_vec()
t = unit_vec*(vector-self.v1)
return self.v1 + t*unit_vec
def is_vertical(self,other):
#線分の直交判定
return is_equal(0,self.get_unit_vec()*other.get_unit_vec())
def is_horizontal(self,other):
#線分の平行判定
return is_equal(0,self.get_unit_vec()**other.get_unit_vec())
def reflection(self,vector):
#反射点(線分を直線と見たときの)
projection = self.projection(vector)
v = projection - vector
return projection + vector
def include(self,vector):
#線分が点を含むか否か
proj = self.projection(vector)
if not is_equal(norm(proj-vector),0):
return False
else:
n = len(self.v1)
f = True
for i in range(n):
f &= ((self.v1[i] <= vector[i] <= self.v2[i]) or (self.v2[i] <= vector[i] <=self.v1[i]))
return f
def distance(self,other):
#点と線分の距離
if isinstance(other,Vector):
proj = self.projection(other)
if self.include(proj):
return norm(proj-other)
else:
ret = []
ret.append(norm(self.v1-other))
ret.append(norm(self.v2-other))
return min(ret)
def ccw(self,vector):
"""
線分に対して点が反時計回りの位置にある(1)か時計回りの位置にある(-1)か線分上にある(0)か
ただし、直線上にはあるが線分上にはない場合は反時計回りの位置にあると判定して1を返す。
"""
direction = self.v2 - self.v1
v = vector - self.v1
if self.include(vector):
return 0
else:
cross = direction**v
if cross[2] <= 0:
return 1
else:
return -1
def intersect(self,segment):
"""
線分の交差判定
"""
ccw12 = self.ccw(segment.v1)
ccw13 = self.ccw(segment.v2)
ccw20 = segment.ccw(self.v1)
ccw21 = segment.ccw(self.v2)
if ccw12*ccw13*ccw20*ccw21 == 0:
return True
else:
if ccw12*ccw13 < 0 and ccw20*ccw21 < 0:
return True
else:
return False
def intersect_point(self,segment):
d1 = norm(self.projection(segment.v1) - segment.v1)
d2 = norm(self.projection(segment.v2) - segment.v2)
return segment.v1 + (d1/(d1 + d2)) * (segment.v2 - segment.v1)
class Line(Segment):
"""
直線クラス
"""
#直線上に点が存在するか否か
def include(self,vector):
proj = self.projection(vector)
return is_equal(norm(proj-vector),0)
q = int(input())
tmp = [0]*q
for i in range(q):
tmp[i] = list(map(int,input().split()))
for i in range(q):
p0,p1,p2,p3 = Vector(tmp[i][0:2]),Vector(tmp[i][2:4]),Vector(tmp[i][4:6]),Vector(tmp[i][6:8])
S1 = Segment(p0,p1)
S2 = Segment(p2,p3)
print(*S1.intersect_point(S2))
```
| 96,920 |
Provide a correct Python 3 solution for this coding contest problem.
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
"Correct Solution:
```
EPS = 1e-4
#外積
def OuterProduct(one, two):
tmp = one.conjugate() * two
return tmp.imag
#直線の交点,平行の場合はFを返す
def Crosspoint(a, b, c, d):
if abs(OuterProduct(b-a, d-c)) <= EPS:
return False
else:
u = OuterProduct(c-a, d-a) / OuterProduct(b-a, d-c)
return (1-u)*a + u*b
n = int(input())
for _ in range(n):
pp = list(map(int, input().split()))
p = [complex(pp[i], pp[i+1]) for i in range(0, 8, 2)]
ans = Crosspoint(p[0], p[1], p[2], p[3])
print(ans.real, ans.imag)
```
| 96,921 |
Provide a correct Python 3 solution for this coding contest problem.
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
"Correct Solution:
```
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Point(self.x - other.x, self.y - other.y)
def __mul__(self, other):
return Point(self.x * other, self.y * other)
def __floordiv__(self, other):
return Point(self.x / other, self.y / other)
def __repr__(self):
return str(self.x) + ' ' + str(self.y)
class Vector(Point):
pass
class Line:
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
class Segment(Line):
pass
def points_to_vector(p1, p2):
x = p1.x - p2.x
y = p1.y - p2.y
return Vector(x, y)
def vector(p):
return Vector(p.x, p.y)
def dot(v1, v2):
return v1.x * v2.x + v1.y * v2.y
def cross(v1, v2):
return v1.x * v2.y - v1.y * v2.x
def norm(v):
return v.x**2 + v.y**2
def distance(v):
return math.sqrt(norm(v))
def project(s, p):
base = points_to_vector(s.p1, s.p2)
hypo = points_to_vector(p, s.p1)
r = dot(hypo, base) / norm(base)
return s.p1 + base * r
def reflect(s, p):
return p + (project(s, p) -p) * 2
def get_distance(s1, s2):
if intersect_s(s1, s2):
return 0
d1 = get_distance_sp(s1, s2.p1)
d2 = get_distance_sp(s1, s2.p2)
d3 = get_distance_sp(s2, s1.p1)
d4 = get_distance_sp(s2, s1.p2)
return min(d1, min(d2, min(d3, d4)))
def get_distance_pp(p1, p2):
return distance(p1 - p2)
def get_distance_lp(l, p):
return abs(cross(l.p2 - l.p1, p - l.p1) / distance(l.p2 - l.p1))
def get_distance_sp(s, p):
if dot(s.p2 - s.p1, p - s.p1) < 0:
return distance(p - s.p1)
elif dot(s.p1 - s.p2, p - s.p2) < 0:
return distance(p - s.p2)
else:
return get_distance_lp(s, p)
def ccw(p0, p1, p2):
EPS = 1e-10
COUNTER_CLOCKWISE = 1
CLOCKWISE = -1
ONLINE_BACK = 2
ONLINE_FRONT = -2
ON_SEGMENT = 0
v1 = p1 - p0
v2 = p2 - p0
if cross(v1, v2) > EPS:
return COUNTER_CLOCKWISE
elif cross(v1, v2) < -EPS:
return CLOCKWISE
elif dot(v1, v2) < -EPS:
return ONLINE_BACK
elif norm(v1) < norm(v2):
return ONLINE_FRONT
else:
return ON_SEGMENT
def intersect_p(p1, p2, p3, p4):
return ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0 and ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0
def intersect_s(s1, s2):
return intersect_p(s1.p1, s1.p2, s2.p1, s2.p2)
def get_cross_point(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
import sys
# sys.stdin = open('input.txt')
q = int(input())
for i in range(q):
temp = list(map(int, input().split()))
points = []
for j in range(0, 8, 2):
points.append(Point(temp[j], temp[j+1]))
s1 = Segment(points[0], points[1])
s2 = Segment(points[2], points[3])
print(get_cross_point(s1, s2))
```
| 96,922 |
Provide a correct Python 3 solution for this coding contest problem.
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
"Correct Solution:
```
from sys import stdin
class Vector:
def __init__(self, x=None, y=None):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __mul__(self, k):
return Vector(self.x * k, self.y * k)
def __gt__(self, other):
return self.x > other.x and self.y > other.yb
def __lt__(self, other):
return self.x < other.x and self.y < other.yb
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def dot(self, other):
return self.x * other.x + self.y * other.y
# usually cross operation return Vector but it returns scalor
def cross(self, other):
return self.x * other.y - self.y * other.x
def norm(self):
return self.x * self.x + self.y * self.y
def abs(self):
return math.sqrt(self.norm())
class Point(Vector):
def __init__(self, *args, **kargs):
return super().__init__(*args, **kargs)
class Segment:
def __init__(self, p1=Point(0, 0), p2=Point(1, 1)):
self.p1 = p1
self.p2 = p2
def get_cross_point(s1, s2):
base = s2.p2 - s2.p1
hypo1 = s1.p1 - s2.p1
hypo2 = s1.p2 - s2.p1
d1 = abs(base.cross(hypo1))
d2 = abs(base.cross(hypo2))
t = d1 / (d1 + d2)
return s1.p1 + (s1.p2 - s1.p1) * t
def read_and_print_results(n):
for _ in range(n):
line = stdin.readline().strip().split()
p0 = Vector(int(line[0]), int(line[1]))
p1 = Vector(int(line[2]), int(line[3]))
p2 = Vector(int(line[4]), int(line[5]))
p3 = Vector(int(line[6]), int(line[7]))
s1 = Segment(p0, p1)
s2 = Segment(p2, p3)
p = get_cross_point(s1, s2)
print("{0:0.10f} {1:0.10f}".format(p.x, p.y))
n = int(input())
read_and_print_results(n)
```
| 96,923 |
Provide a correct Python 3 solution for this coding contest problem.
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
"Correct Solution:
```
class Line:
def __init__(self,p1,p2):
if p1[1] < p2[1]:self.s=p2;self.e=p1
elif p1[1] > p2[1]:self.s=p1;self.e=p2
else:
if p1[0] < p2[0]:self.s=p1;self.e=p2
else:self.s=p2;self.e=p1
def cross(a,b):return a[0]*b[1] - a[1]*b[0]
def CrossPoint(l,m):
crsl = cross(l.s,l.e)
crsm = cross(m.s,m.e)
det = (l.s[1] - l.e[1])*(m.e[0] - m.s[0]) - (l.e[0]-l.s[0])*(m.s[1]-m.e[1])
x = (m.s[0] - m.e[0]) * crsl + (l.e[0] - l.s[0]) * crsm
y = (m.s[1] - m.e[1]) * crsl + (l.e[1] - l.s[1]) * crsm
return [x/det,y/det]
q = int(input())
for i in range(q):
x0,y0,x1,y1,x2,y2,x3,y3 = [int(i) for i in input().split()]
l = Line([x0,y0],[x1,y1])
m = Line([x2,y2],[x3,y3])
P = CrossPoint(l,m)
print(P[0],P[1])
```
| 96,924 |
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:
```
from math import sqrt
q = int(input())
class Segment:pass
def add(a,b):
return [a[0] + b[0],a[1] + b[1]]
def sub(a, b):
return [a[0] - b[0],a[1] - b[1]]
def multi(k, a):
return [k*a[0],k*a[1]]
def cross(a, b):
return a[0] * b[1] - a[1] * b[0]
def norm(a):
return sqrt(a[0] ** 2 + a[1] ** 2)
for i in range(q):
xp0,yp0,xp1,yp1,xp2,yp2,xp3,yp3 = map(int, input().split())
s1 = Segment()
s2 = Segment()
s1.p1 = [xp0, yp0]
s1.p2 = [xp1, yp1]
s2.p1 = [xp2, yp2]
s2.p2 = [xp3, yp3]
base = sub(s2.p2, s2.p1)
d1 = abs(cross(base, (sub(s1.p1, s2.p1))))/norm(base)
d2 = abs(cross(base, (sub(s1.p2, s2.p1))))/norm(base)
t = d1/(d1+d2)
x = add(s1.p1 , multi(t,sub(s1.p2, s1.p1)))
print(x[0],x[1])
```
Yes
| 96,925 |
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:
```
#!/usr/bin/env python3
# CGL_2_C: Segments/Lines - Cross Point
def crossing_point(p0, p1, p2, p3):
x0, y0 = p0
x1, y1 = p1
x2, y2 = p2
x3, y3 = p3
if x0 != x1 and x2 != x3:
a0 = (y0 - y1) / (x0 - x1)
b0 = (x1*y0 - y1*x0) / (x1 - x0)
a1 = (y2 - y3) / (x2 - x3)
b1 = (x3*y2 - y3*x2) / (x3 - x2)
return (b0-b1) / (a1-a0), (a1*b0-a0*b1) / (a1-a0)
elif x0 != x1:
a0 = (y0 - y1) / (x0 - x1)
b0 = (x1*y0 - y1*x0) / (x1 - x0)
return x2, a0 * x2 + b0
elif x2 != x3:
a1 = (y2 - y3) / (x2 - x3)
b1 = (x3*y2 - y3*x2) / (x3 - x2)
return x0, a1 * x0 + b1
else:
raise ValueError('p0p1 and p2p3 is parallel')
def run():
q = int(input())
for _ in range(q):
x0, y0, x1, y1, x2, y2, x3, y3 = [int(i) for i in input().split()]
x, y = crossing_point((x0, y0), (x1, y1), (x2, y2), (x3, y3))
print("{:.10f} {:.10f}".format(x, y))
if __name__ == '__main__':
run()
```
Yes
| 96,926 |
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
def equals(a, b):
return abs(a - b) < EPS
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, p):
return Point(self.x + p.x, self.y + p.y)
def __sub__(self, p):
return Point(self.x - p.x, self.y - p.y)
def __mul__(self, a):
return Point(self.x * a, self.y * a)
def __rmul__(self, a):
return self * a
def __truediv__(self, a):
return Point(self.x / a, self.y / a)
def norm(self):
return self.x * self.x + self.y * self.y
def abs(self):
return math.sqrt(self.norm())
def __lt__(self, p):
if self.x != p.x:
return self. x < p.x
else:
return self.y < p.y
def __eq__(self, p):
return equals(self.x, p.x) and equals(self.y, p.y)
class Segment:
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
def dot(a, b):
return a.x * b.x + a.y * b.y
def cross(a, b):
return a.x * b.y - a.y * b.x
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
if __name__ == '__main__':
q = int(input())
ans = []
for i in range(q):
x0, y0, x1, y1, x2, y2, x3, y3 = [int(v) for v in input().split()]
s1 = Segment(Point(x0, y0), Point(x1, y1))
s2 = Segment(Point(x2, y2), Point(x3, y3))
ans.append(getCrossPoint(s1, s2))
for v in ans:
print('{0:.10f} {1:.10f}'.format(v.x, v.y))
```
Yes
| 96,927 |
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 vc(p,q):
return[p[0]-q[0],p[1]-q[1]]
def cross(u,v):
return(u[0]*v[1]-u[1]*v[0])
n = int(input())
for _ in range(n):
x0,y0,x1,y1,x2,y2,x3,y3 = map(int,input().split())
p0,p1,p2,p3 = [x0,y0],[x1,y1],[x2,y2],[x3,y3]
v01 = vc(p1,p0)
v02 = vc(p2,p0)
v03 = vc(p3,p0)
d1 = cross(v01,v02)
d2 = cross(v01,v03)
#print(v01,v02,v03,d1,d2)
if d1 == 0:
#print("p2")
print(*p2)
elif d2 ==0:
#print("p3")
print(*p3)
else:
mu = abs(d1)/(abs(d1)+abs(d2))
#print(mu)
v23 = vc(p3,p2)
ans = [p2[0]+mu*v23[0], p2[1]+mu*v23[1]]
print(*ans)
```
Yes
| 96,928 |
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)
```
No
| 96,929 |
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))
```
No
| 96,930 |
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))
```
No
| 96,931 |
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)
```
No
| 96,932 |
Provide a correct Python 3 solution for this coding contest problem.
Compare given two sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}$ lexicographically.
Constraints
* $1 \leq n, m \leq 1,000$
* $0 \leq a_i, b_i \leq 1,000$
Input
The input is given in the following format.
$n$
$a_0 \; a_1, ..., \; a_{n-1}$
$m$
$b_0 \; b_1, ..., \; b_{m-1}$
The number of elements in $A$ and its elements $a_i$ are given in the first and second lines respectively. The number of elements in $B$ and its elements $b_i$ are given in the third and fourth lines respectively. All input are given in integers.
Output
Print 1 $B$ is greater than $A$, otherwise 0.
Examples
Input
3
1 2 3
2
2 4
Output
1
Input
4
5 4 7 0
5
1 2 3 4 5
Output
0
Input
3
1 1 2
4
1 1 2 2
Output
1
"Correct Solution:
```
n = int(input())
a = list(input().split())
m = int(input())
b = list(input().split())
# for i in range(max(len(a),len(b))):
# if a[i] == b[i]:
# if i+1 >= len(a) and len(b) > i+1 :
# print('1')
# break
# elif i+1 >= len(b):
# print('0')
# break
# pass
# elif a[i] < b[i]:
# print('1')
# break
# else:
# print('0')
# break
print(+(a < b))
```
| 96,933 |
Provide a correct Python 3 solution for this coding contest problem.
Compare given two sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}$ lexicographically.
Constraints
* $1 \leq n, m \leq 1,000$
* $0 \leq a_i, b_i \leq 1,000$
Input
The input is given in the following format.
$n$
$a_0 \; a_1, ..., \; a_{n-1}$
$m$
$b_0 \; b_1, ..., \; b_{m-1}$
The number of elements in $A$ and its elements $a_i$ are given in the first and second lines respectively. The number of elements in $B$ and its elements $b_i$ are given in the third and fourth lines respectively. All input are given in integers.
Output
Print 1 $B$ is greater than $A$, otherwise 0.
Examples
Input
3
1 2 3
2
2 4
Output
1
Input
4
5 4 7 0
5
1 2 3 4 5
Output
0
Input
3
1 1 2
4
1 1 2 2
Output
1
"Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
m = int(input())
b = list(map(int, input().split()))
k = min(n, m)
f = 2
for i in range(k):
if a[i] < b[i]:
f = 1
break
if a[i] > b[i]:
f = 0
break
if f == 2:
f = 0
if n<m:
f = 1
print(f)
```
| 96,934 |
Provide a correct Python 3 solution for this coding contest problem.
Compare given two sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}$ lexicographically.
Constraints
* $1 \leq n, m \leq 1,000$
* $0 \leq a_i, b_i \leq 1,000$
Input
The input is given in the following format.
$n$
$a_0 \; a_1, ..., \; a_{n-1}$
$m$
$b_0 \; b_1, ..., \; b_{m-1}$
The number of elements in $A$ and its elements $a_i$ are given in the first and second lines respectively. The number of elements in $B$ and its elements $b_i$ are given in the third and fourth lines respectively. All input are given in integers.
Output
Print 1 $B$ is greater than $A$, otherwise 0.
Examples
Input
3
1 2 3
2
2 4
Output
1
Input
4
5 4 7 0
5
1 2 3 4 5
Output
0
Input
3
1 1 2
4
1 1 2 2
Output
1
"Correct Solution:
```
n = int(input())
A = list(map(int, input().split()))
m = int(input())
B = list(map(int, input().split()))
if B <= A:
print(0)
elif A < B:
print(1)
```
| 96,935 |
Provide a correct Python 3 solution for this coding contest problem.
Compare given two sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}$ lexicographically.
Constraints
* $1 \leq n, m \leq 1,000$
* $0 \leq a_i, b_i \leq 1,000$
Input
The input is given in the following format.
$n$
$a_0 \; a_1, ..., \; a_{n-1}$
$m$
$b_0 \; b_1, ..., \; b_{m-1}$
The number of elements in $A$ and its elements $a_i$ are given in the first and second lines respectively. The number of elements in $B$ and its elements $b_i$ are given in the third and fourth lines respectively. All input are given in integers.
Output
Print 1 $B$ is greater than $A$, otherwise 0.
Examples
Input
3
1 2 3
2
2 4
Output
1
Input
4
5 4 7 0
5
1 2 3 4 5
Output
0
Input
3
1 1 2
4
1 1 2 2
Output
1
"Correct Solution:
```
input()
a = list(map(int, input().split(' ')))
input()
b = list(map(int, input().split(' ')))
print(1 if a<b else 0)
```
| 96,936 |
Provide a correct Python 3 solution for this coding contest problem.
Compare given two sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}$ lexicographically.
Constraints
* $1 \leq n, m \leq 1,000$
* $0 \leq a_i, b_i \leq 1,000$
Input
The input is given in the following format.
$n$
$a_0 \; a_1, ..., \; a_{n-1}$
$m$
$b_0 \; b_1, ..., \; b_{m-1}$
The number of elements in $A$ and its elements $a_i$ are given in the first and second lines respectively. The number of elements in $B$ and its elements $b_i$ are given in the third and fourth lines respectively. All input are given in integers.
Output
Print 1 $B$ is greater than $A$, otherwise 0.
Examples
Input
3
1 2 3
2
2 4
Output
1
Input
4
5 4 7 0
5
1 2 3 4 5
Output
0
Input
3
1 1 2
4
1 1 2 2
Output
1
"Correct Solution:
```
n1 = int(input())
txt1 = input().split()
n2 = int(input())
txt2 = input().split()
for i in range(min(n1, n2)):
c1, c2 = txt1[i], txt2[i]
if c1 != c2:
print([0, 1][c1 < c2])
break
else:
print([0, 1][n1 < n2])
```
| 96,937 |
Provide a correct Python 3 solution for this coding contest problem.
Compare given two sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}$ lexicographically.
Constraints
* $1 \leq n, m \leq 1,000$
* $0 \leq a_i, b_i \leq 1,000$
Input
The input is given in the following format.
$n$
$a_0 \; a_1, ..., \; a_{n-1}$
$m$
$b_0 \; b_1, ..., \; b_{m-1}$
The number of elements in $A$ and its elements $a_i$ are given in the first and second lines respectively. The number of elements in $B$ and its elements $b_i$ are given in the third and fourth lines respectively. All input are given in integers.
Output
Print 1 $B$ is greater than $A$, otherwise 0.
Examples
Input
3
1 2 3
2
2 4
Output
1
Input
4
5 4 7 0
5
1 2 3 4 5
Output
0
Input
3
1 1 2
4
1 1 2 2
Output
1
"Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
m = int(input())
b = list(map(int, input().split()))
la = len(a)
lb = len(b)
l = min(la, lb)
for i in range(l):
if a[i] > b[i]:
print(0)
break
elif a[i] < b[i]:
print(1)
break
else:
if la >= lb:
print(0)
else:
print(1)
```
| 96,938 |
Provide a correct Python 3 solution for this coding contest problem.
Compare given two sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}$ lexicographically.
Constraints
* $1 \leq n, m \leq 1,000$
* $0 \leq a_i, b_i \leq 1,000$
Input
The input is given in the following format.
$n$
$a_0 \; a_1, ..., \; a_{n-1}$
$m$
$b_0 \; b_1, ..., \; b_{m-1}$
The number of elements in $A$ and its elements $a_i$ are given in the first and second lines respectively. The number of elements in $B$ and its elements $b_i$ are given in the third and fourth lines respectively. All input are given in integers.
Output
Print 1 $B$ is greater than $A$, otherwise 0.
Examples
Input
3
1 2 3
2
2 4
Output
1
Input
4
5 4 7 0
5
1 2 3 4 5
Output
0
Input
3
1 1 2
4
1 1 2 2
Output
1
"Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
m = int(input())
b = list(map(int, input().split()))
if a < b:
print(1)
else:
print(0)
```
| 96,939 |
Provide a correct Python 3 solution for this coding contest problem.
Compare given two sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}$ lexicographically.
Constraints
* $1 \leq n, m \leq 1,000$
* $0 \leq a_i, b_i \leq 1,000$
Input
The input is given in the following format.
$n$
$a_0 \; a_1, ..., \; a_{n-1}$
$m$
$b_0 \; b_1, ..., \; b_{m-1}$
The number of elements in $A$ and its elements $a_i$ are given in the first and second lines respectively. The number of elements in $B$ and its elements $b_i$ are given in the third and fourth lines respectively. All input are given in integers.
Output
Print 1 $B$ is greater than $A$, otherwise 0.
Examples
Input
3
1 2 3
2
2 4
Output
1
Input
4
5 4 7 0
5
1 2 3 4 5
Output
0
Input
3
1 1 2
4
1 1 2 2
Output
1
"Correct Solution:
```
n=input()
A=str("".join(input().split()))
n=input()
B=str("".join(input().split()))
li=sorted([A]+[B])
if li[0]==A and A!=B:
print(1)
else:
print(0)
```
| 96,940 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Compare given two sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}$ lexicographically.
Constraints
* $1 \leq n, m \leq 1,000$
* $0 \leq a_i, b_i \leq 1,000$
Input
The input is given in the following format.
$n$
$a_0 \; a_1, ..., \; a_{n-1}$
$m$
$b_0 \; b_1, ..., \; b_{m-1}$
The number of elements in $A$ and its elements $a_i$ are given in the first and second lines respectively. The number of elements in $B$ and its elements $b_i$ are given in the third and fourth lines respectively. All input are given in integers.
Output
Print 1 $B$ is greater than $A$, otherwise 0.
Examples
Input
3
1 2 3
2
2 4
Output
1
Input
4
5 4 7 0
5
1 2 3 4 5
Output
0
Input
3
1 1 2
4
1 1 2 2
Output
1
Submitted Solution:
```
def resolve():
import sys
from collections import deque
input = sys.stdin.readline
input()
A = [int(i) for i in input().split()]
input()
B = [int(i) for i in input().split()]
A = deque(A)
B = deque(B)
while len(A) > 0 and len(B) > 0:
a = A.popleft()
b = B.popleft()
if a == b:
continue
elif a < b:
print(1)
return
else:
print(0)
return
if len(B) > 0:
print(1)
else:
print(0)
resolve()
```
Yes
| 96,941 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Compare given two sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}$ lexicographically.
Constraints
* $1 \leq n, m \leq 1,000$
* $0 \leq a_i, b_i \leq 1,000$
Input
The input is given in the following format.
$n$
$a_0 \; a_1, ..., \; a_{n-1}$
$m$
$b_0 \; b_1, ..., \; b_{m-1}$
The number of elements in $A$ and its elements $a_i$ are given in the first and second lines respectively. The number of elements in $B$ and its elements $b_i$ are given in the third and fourth lines respectively. All input are given in integers.
Output
Print 1 $B$ is greater than $A$, otherwise 0.
Examples
Input
3
1 2 3
2
2 4
Output
1
Input
4
5 4 7 0
5
1 2 3 4 5
Output
0
Input
3
1 1 2
4
1 1 2 2
Output
1
Submitted Solution:
```
# coding=utf-8
N = int(input())
A = list(map(int, input().split()))
M = int(input())
B = list(map(int, input().split()))
if A < B:
print("1")
else:
print("0")
```
Yes
| 96,942 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Compare given two sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}$ lexicographically.
Constraints
* $1 \leq n, m \leq 1,000$
* $0 \leq a_i, b_i \leq 1,000$
Input
The input is given in the following format.
$n$
$a_0 \; a_1, ..., \; a_{n-1}$
$m$
$b_0 \; b_1, ..., \; b_{m-1}$
The number of elements in $A$ and its elements $a_i$ are given in the first and second lines respectively. The number of elements in $B$ and its elements $b_i$ are given in the third and fourth lines respectively. All input are given in integers.
Output
Print 1 $B$ is greater than $A$, otherwise 0.
Examples
Input
3
1 2 3
2
2 4
Output
1
Input
4
5 4 7 0
5
1 2 3 4 5
Output
0
Input
3
1 1 2
4
1 1 2 2
Output
1
Submitted Solution:
```
input(); A = input().split()
input(); B = input().split()
print(1 if A < B else 0)
```
Yes
| 96,943 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Compare given two sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}$ lexicographically.
Constraints
* $1 \leq n, m \leq 1,000$
* $0 \leq a_i, b_i \leq 1,000$
Input
The input is given in the following format.
$n$
$a_0 \; a_1, ..., \; a_{n-1}$
$m$
$b_0 \; b_1, ..., \; b_{m-1}$
The number of elements in $A$ and its elements $a_i$ are given in the first and second lines respectively. The number of elements in $B$ and its elements $b_i$ are given in the third and fourth lines respectively. All input are given in integers.
Output
Print 1 $B$ is greater than $A$, otherwise 0.
Examples
Input
3
1 2 3
2
2 4
Output
1
Input
4
5 4 7 0
5
1 2 3 4 5
Output
0
Input
3
1 1 2
4
1 1 2 2
Output
1
Submitted Solution:
```
from itertools import zip_longest
if __name__ == '__main__':
int(input())
A = list(map(int,input().split()))
int(input())
B = list(map(int,input().split()))
win = 0
for a,b in zip_longest(A,B,fillvalue=-1):
if a < b:
win = 1
break
elif a > b:
win = 0
break
print(win)
```
Yes
| 96,944 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Compare given two sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}$ lexicographically.
Constraints
* $1 \leq n, m \leq 1,000$
* $0 \leq a_i, b_i \leq 1,000$
Input
The input is given in the following format.
$n$
$a_0 \; a_1, ..., \; a_{n-1}$
$m$
$b_0 \; b_1, ..., \; b_{m-1}$
The number of elements in $A$ and its elements $a_i$ are given in the first and second lines respectively. The number of elements in $B$ and its elements $b_i$ are given in the third and fourth lines respectively. All input are given in integers.
Output
Print 1 $B$ is greater than $A$, otherwise 0.
Examples
Input
3
1 2 3
2
2 4
Output
1
Input
4
5 4 7 0
5
1 2 3 4 5
Output
0
Input
3
1 1 2
4
1 1 2 2
Output
1
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
m = int(input())
b = list(map(int, input().split()))
la = len(a)
lb = len(b)
l = min(la, lb)
for i in range(l):
if a[i] < b[i]:
print(1)
break
elif a[i] > b[i]:
print(2)
break
else:
if la < lb:
print(1)
else:
print(2)
```
No
| 96,945 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Compare given two sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}$ lexicographically.
Constraints
* $1 \leq n, m \leq 1,000$
* $0 \leq a_i, b_i \leq 1,000$
Input
The input is given in the following format.
$n$
$a_0 \; a_1, ..., \; a_{n-1}$
$m$
$b_0 \; b_1, ..., \; b_{m-1}$
The number of elements in $A$ and its elements $a_i$ are given in the first and second lines respectively. The number of elements in $B$ and its elements $b_i$ are given in the third and fourth lines respectively. All input are given in integers.
Output
Print 1 $B$ is greater than $A$, otherwise 0.
Examples
Input
3
1 2 3
2
2 4
Output
1
Input
4
5 4 7 0
5
1 2 3 4 5
Output
0
Input
3
1 1 2
4
1 1 2 2
Output
1
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
m = int(input())
b = list(map(int, input().split()))
la = len(a)
lb = len(b)
l = min(la, lb)
for i in range(l):
if a[i] > b[i]:
print(0)
break
elif a[i] < b[i]:
print(1)
break
else:
if la < lb:
print(0)
else:
print(1)
```
No
| 96,946 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Compare given two sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}$ lexicographically.
Constraints
* $1 \leq n, m \leq 1,000$
* $0 \leq a_i, b_i \leq 1,000$
Input
The input is given in the following format.
$n$
$a_0 \; a_1, ..., \; a_{n-1}$
$m$
$b_0 \; b_1, ..., \; b_{m-1}$
The number of elements in $A$ and its elements $a_i$ are given in the first and second lines respectively. The number of elements in $B$ and its elements $b_i$ are given in the third and fourth lines respectively. All input are given in integers.
Output
Print 1 $B$ is greater than $A$, otherwise 0.
Examples
Input
3
1 2 3
2
2 4
Output
1
Input
4
5 4 7 0
5
1 2 3 4 5
Output
0
Input
3
1 1 2
4
1 1 2 2
Output
1
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
m = int(input())
b = list(map(int, input().split()))
la = len(a)
lb = len(b)
l = min(la, lb)
for i in range(l):
if a[i] < b[i]:
print(0)
break
elif a[i] > b[i]:
print(1)
break
else:
if la < lb:
print(0)
else:
print(1)
```
No
| 96,947 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Compare given two sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}$ lexicographically.
Constraints
* $1 \leq n, m \leq 1,000$
* $0 \leq a_i, b_i \leq 1,000$
Input
The input is given in the following format.
$n$
$a_0 \; a_1, ..., \; a_{n-1}$
$m$
$b_0 \; b_1, ..., \; b_{m-1}$
The number of elements in $A$ and its elements $a_i$ are given in the first and second lines respectively. The number of elements in $B$ and its elements $b_i$ are given in the third and fourth lines respectively. All input are given in integers.
Output
Print 1 $B$ is greater than $A$, otherwise 0.
Examples
Input
3
1 2 3
2
2 4
Output
1
Input
4
5 4 7 0
5
1 2 3 4 5
Output
0
Input
3
1 1 2
4
1 1 2 2
Output
1
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split())
m = int(input())
b = list(map(int, input()))
la = len(a)
lb = len(b)
l = min(la, lb)
for i in range(l):
if a[i] < b[i]:
print(1)
break
elif a[i] > b[i]:
print(2)
break
else:
if la < lb:
print(1)
else:
print(2)
```
No
| 96,948 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from 1 to n.
It is known that, from the capital (the city with the number 1), you can reach any other city by moving along the roads.
The President of Berland plans to improve the country's road network. The budget is enough to repair exactly n-1 roads. The President plans to choose a set of n-1 roads such that:
* it is possible to travel from the capital to any other city along the n-1 chosen roads,
* if d_i is the number of roads needed to travel from the capital to city i, moving only along the n-1 chosen roads, then d_1 + d_2 + ... + d_n is minimized (i.e. as minimal as possible).
In other words, the set of n-1 roads should preserve the connectivity of the country, and the sum of distances from city 1 to all cities should be minimized (where you can only use the n-1 chosen roads).
The president instructed the ministry to prepare k possible options to choose n-1 roads so that both conditions above are met.
Write a program that will find k possible ways to choose roads for repair. If there are fewer than k ways, then the program should output all possible valid ways to choose roads.
Input
The first line of the input contains integers n, m and k (2 ≤ n ≤ 2⋅10^5, n-1 ≤ m ≤ 2⋅10^5, 1 ≤ k ≤ 2⋅10^5), where n is the number of cities in the country, m is the number of roads and k is the number of options to choose a set of roads for repair. It is guaranteed that m ⋅ k ≤ 10^6.
The following m lines describe the roads, one road per line. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the numbers of the cities that the i-th road connects. There is at most one road between a pair of cities. The given set of roads is such that you can reach any city from the capital.
Output
Print t (1 ≤ t ≤ k) — the number of ways to choose a set of roads for repair. Recall that you need to find k different options; if there are fewer than k of them, then you need to find all possible different valid options.
In the following t lines, print the options, one per line. Print an option as a string of m characters where the j-th character is equal to '1' if the j-th road is included in the option, and is equal to '0' if the road is not included. The roads should be numbered according to their order in the input. The options can be printed in any order. All the t lines should be different.
Since it is guaranteed that m ⋅ k ≤ 10^6, the total length of all the t lines will not exceed 10^6.
If there are several answers, output any of them.
Examples
Input
4 4 3
1 2
2 3
1 4
4 3
Output
2
1110
1011
Input
4 6 3
1 2
2 3
1 4
4 3
2 4
1 3
Output
1
101001
Input
5 6 2
1 2
1 3
2 4
2 5
3 4
3 5
Output
2
111100
110110
Tags: brute force, dfs and similar, graphs, shortest paths
Correct Solution:
```
import sys
import io, os
input = sys.stdin.buffer.readline
n,m,k = map(int,input().split())
AB = []
g = [[] for _ in range(n)]
for i in range(m):
a,b = map(int, input().split())
a,b = a-1, b-1
g[a].append(b)
g[b].append(a)
AB.append((a,b))
from collections import deque
q = deque([])
q.append(0)
d = [-1]*n
d[0] = 0
while q:
v = q.popleft()
for u in g[v]:
if d[u] == -1:
d[u] = d[v]+1
q.append(u)
#print(d)
inc = [[] for _ in range(n)]
for i, (a, b) in enumerate(AB):
if d[a]+1 == d[b]:
inc[b].append(i)
if d[b]+1 == d[a]:
inc[a].append(i)
#print(inc)
F = [0]*n
res = []
for i in range(k):
s = ['0']*m
for j in range(1, n):
s[inc[j][F[j]]] = '1'
res.append(''.join(s))
flag = False
for j in range(1, n):
if F[j]+1 < len(inc[j]):
flag = True
F[j] += 1
break
else:
F[j] = 0
if not flag:
break
print(len(res))
print(*res, sep='\n')
```
| 96,949 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from 1 to n.
It is known that, from the capital (the city with the number 1), you can reach any other city by moving along the roads.
The President of Berland plans to improve the country's road network. The budget is enough to repair exactly n-1 roads. The President plans to choose a set of n-1 roads such that:
* it is possible to travel from the capital to any other city along the n-1 chosen roads,
* if d_i is the number of roads needed to travel from the capital to city i, moving only along the n-1 chosen roads, then d_1 + d_2 + ... + d_n is minimized (i.e. as minimal as possible).
In other words, the set of n-1 roads should preserve the connectivity of the country, and the sum of distances from city 1 to all cities should be minimized (where you can only use the n-1 chosen roads).
The president instructed the ministry to prepare k possible options to choose n-1 roads so that both conditions above are met.
Write a program that will find k possible ways to choose roads for repair. If there are fewer than k ways, then the program should output all possible valid ways to choose roads.
Input
The first line of the input contains integers n, m and k (2 ≤ n ≤ 2⋅10^5, n-1 ≤ m ≤ 2⋅10^5, 1 ≤ k ≤ 2⋅10^5), where n is the number of cities in the country, m is the number of roads and k is the number of options to choose a set of roads for repair. It is guaranteed that m ⋅ k ≤ 10^6.
The following m lines describe the roads, one road per line. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the numbers of the cities that the i-th road connects. There is at most one road between a pair of cities. The given set of roads is such that you can reach any city from the capital.
Output
Print t (1 ≤ t ≤ k) — the number of ways to choose a set of roads for repair. Recall that you need to find k different options; if there are fewer than k of them, then you need to find all possible different valid options.
In the following t lines, print the options, one per line. Print an option as a string of m characters where the j-th character is equal to '1' if the j-th road is included in the option, and is equal to '0' if the road is not included. The roads should be numbered according to their order in the input. The options can be printed in any order. All the t lines should be different.
Since it is guaranteed that m ⋅ k ≤ 10^6, the total length of all the t lines will not exceed 10^6.
If there are several answers, output any of them.
Examples
Input
4 4 3
1 2
2 3
1 4
4 3
Output
2
1110
1011
Input
4 6 3
1 2
2 3
1 4
4 3
2 4
1 3
Output
1
101001
Input
5 6 2
1 2
1 3
2 4
2 5
3 4
3 5
Output
2
111100
110110
Tags: brute force, dfs and similar, graphs, shortest paths
Correct Solution:
```
from math import inf
import heapq
n, m, k = map(int, input().split(' '))
edge = [[] for _ in range(n)]
for i in range(m):
a, b = map(int, input().split(' '))
edge[a-1].append((i, b-1))
edge[b-1].append((i, a-1))
d = [inf for _ in range(n)]
d[0] = 0
q = [0 for _ in range(n)]
f = 0
r = 1
while f < r:
i = q[f]
f += 1
for (_, j) in edge[i]:
if d[j] == inf:
d[j] = d[i]+1
q[r] = j
r += 1
#print(d)
pre = [[] for _ in range(n)]
for i in range(n):
for (ind, j) in edge[i]:
if d[j] == d[i]-1:
pre[i].append((ind, j))
#print(pre)
s = [0 for _ in range(n)]
top = n
sol = []
while top > 0:
#print(top, s)
if top == n:
u = ['0' for _ in range(m)]
#print(s)
for i in range(1,n):
u[pre[i][s[i]][0]] = '1'
sol.append("".join(u))
if len(sol) == k:
break
top -= 1
else:
s[top] += 1
if s[top] == len(pre[top]):
top -= 1
#s[top] += 1
else:
top += 1
if top < n:
s[top] = -1
print(len(sol))
for x in sol:
print(x)
```
| 96,950 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from 1 to n.
It is known that, from the capital (the city with the number 1), you can reach any other city by moving along the roads.
The President of Berland plans to improve the country's road network. The budget is enough to repair exactly n-1 roads. The President plans to choose a set of n-1 roads such that:
* it is possible to travel from the capital to any other city along the n-1 chosen roads,
* if d_i is the number of roads needed to travel from the capital to city i, moving only along the n-1 chosen roads, then d_1 + d_2 + ... + d_n is minimized (i.e. as minimal as possible).
In other words, the set of n-1 roads should preserve the connectivity of the country, and the sum of distances from city 1 to all cities should be minimized (where you can only use the n-1 chosen roads).
The president instructed the ministry to prepare k possible options to choose n-1 roads so that both conditions above are met.
Write a program that will find k possible ways to choose roads for repair. If there are fewer than k ways, then the program should output all possible valid ways to choose roads.
Input
The first line of the input contains integers n, m and k (2 ≤ n ≤ 2⋅10^5, n-1 ≤ m ≤ 2⋅10^5, 1 ≤ k ≤ 2⋅10^5), where n is the number of cities in the country, m is the number of roads and k is the number of options to choose a set of roads for repair. It is guaranteed that m ⋅ k ≤ 10^6.
The following m lines describe the roads, one road per line. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the numbers of the cities that the i-th road connects. There is at most one road between a pair of cities. The given set of roads is such that you can reach any city from the capital.
Output
Print t (1 ≤ t ≤ k) — the number of ways to choose a set of roads for repair. Recall that you need to find k different options; if there are fewer than k of them, then you need to find all possible different valid options.
In the following t lines, print the options, one per line. Print an option as a string of m characters where the j-th character is equal to '1' if the j-th road is included in the option, and is equal to '0' if the road is not included. The roads should be numbered according to their order in the input. The options can be printed in any order. All the t lines should be different.
Since it is guaranteed that m ⋅ k ≤ 10^6, the total length of all the t lines will not exceed 10^6.
If there are several answers, output any of them.
Examples
Input
4 4 3
1 2
2 3
1 4
4 3
Output
2
1110
1011
Input
4 6 3
1 2
2 3
1 4
4 3
2 4
1 3
Output
1
101001
Input
5 6 2
1 2
1 3
2 4
2 5
3 4
3 5
Output
2
111100
110110
Tags: brute force, dfs and similar, graphs, shortest paths
Correct Solution:
```
from collections import deque
import sys
input = sys.stdin.readline
def bfs(s):
q = deque()
q.append(s)
dist = [-1] * (n + 1)
dist[s] = 0
while q:
i = q.popleft()
di = dist[i]
for j, c in G[i]:
if dist[j] == -1:
dist[j] = di + 1
q.append(j)
return dist
n, m, k = map(int, input().split())
G = [[] for _ in range(n + 1)]
for i in range(m):
a, b = map(int, input().split())
G[a].append((b, i))
G[b].append((a, i))
dist = bfs(1)
parent = [[] for _ in range(n + 1)]
for i in range(2, n + 1):
di = dist[i]
for j, c in G[i]:
if dist[j] == di - 1:
parent[i].append(c)
t = 1
for s in parent:
t *= max(1, len(s))
if t > k:
t = k
break
print(t)
x = [0] * (n - 1)
l = [len(parent[i]) for i in range(2, n + 1)]
ans = ["0"] * m
for i in range(n - 1):
ans[parent[i + 2][x[i]]] = "1"
print("".join(ans))
for i in range(t - 1):
ans = ["0"] * m
for i in range(n - 1):
if x[i] + 1 < l[i]:
x[i] += 1
break
x[i] += 1
x[i] %= l[i]
for i in range(n - 1):
ans[parent[i + 2][x[i]]] = "1"
print("".join(ans))
```
| 96,951 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from 1 to n.
It is known that, from the capital (the city with the number 1), you can reach any other city by moving along the roads.
The President of Berland plans to improve the country's road network. The budget is enough to repair exactly n-1 roads. The President plans to choose a set of n-1 roads such that:
* it is possible to travel from the capital to any other city along the n-1 chosen roads,
* if d_i is the number of roads needed to travel from the capital to city i, moving only along the n-1 chosen roads, then d_1 + d_2 + ... + d_n is minimized (i.e. as minimal as possible).
In other words, the set of n-1 roads should preserve the connectivity of the country, and the sum of distances from city 1 to all cities should be minimized (where you can only use the n-1 chosen roads).
The president instructed the ministry to prepare k possible options to choose n-1 roads so that both conditions above are met.
Write a program that will find k possible ways to choose roads for repair. If there are fewer than k ways, then the program should output all possible valid ways to choose roads.
Input
The first line of the input contains integers n, m and k (2 ≤ n ≤ 2⋅10^5, n-1 ≤ m ≤ 2⋅10^5, 1 ≤ k ≤ 2⋅10^5), where n is the number of cities in the country, m is the number of roads and k is the number of options to choose a set of roads for repair. It is guaranteed that m ⋅ k ≤ 10^6.
The following m lines describe the roads, one road per line. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the numbers of the cities that the i-th road connects. There is at most one road between a pair of cities. The given set of roads is such that you can reach any city from the capital.
Output
Print t (1 ≤ t ≤ k) — the number of ways to choose a set of roads for repair. Recall that you need to find k different options; if there are fewer than k of them, then you need to find all possible different valid options.
In the following t lines, print the options, one per line. Print an option as a string of m characters where the j-th character is equal to '1' if the j-th road is included in the option, and is equal to '0' if the road is not included. The roads should be numbered according to their order in the input. The options can be printed in any order. All the t lines should be different.
Since it is guaranteed that m ⋅ k ≤ 10^6, the total length of all the t lines will not exceed 10^6.
If there are several answers, output any of them.
Examples
Input
4 4 3
1 2
2 3
1 4
4 3
Output
2
1110
1011
Input
4 6 3
1 2
2 3
1 4
4 3
2 4
1 3
Output
1
101001
Input
5 6 2
1 2
1 3
2 4
2 5
3 4
3 5
Output
2
111100
110110
Tags: brute force, dfs and similar, graphs, shortest paths
Correct Solution:
```
from math import inf
nmk = list(map(int, input().split(' ')))
n = nmk[0]
m = nmk[1]
k = nmk[2]
a = []
for i in range(m):
a.append(list(map(int, input().split(' '))))
smej = [[] for j in range(n)]
nums = {}
t = 0
for i in a:
nums.update({(i[0], i[1]):t})
t += 1
smej[i[0]-1].append(i[1]-1)
smej[i[1]-1].append(i[0]-1)
dists = [inf for i in range(n)]
dists[0] = 0
q = [0]
while len(q) > 0:
u = q.pop(0)
for i in smej[u]:
if (dists[i] == inf):
q.append(i)
dists[i] = dists[u] + 1
p = [[] for i in range(n)]
for i in range(1, n):
for j in smej[i]:
if(dists[j] == dists[i]-1):
try:
p[i].append(nums[(j+1,i+1)])
except:
p[i].append(nums[(i+1,j+1)])
am = 1
p.pop(0)
for i in range(len(p)):
am *= len(p[i])
if(am < k):
print(am)
else:
print(k)
f = [0 for i in range(len(p))]
ans = []
for i in range(k):
s = ['0'for i in range(m)]
for j in range(len(p)):
s[p[j][f[j]]] = '1'
s = ''.join(s)
ans.append(s)
ok = False
first = True
for j in range(len(p)-1, -1, -1):
if first:
first = False
if(f[j]+1 == len(p[j])):
if(j == 0):
ok = True
break
f[j] = 0
f[j-1]+= 1
else:
f[j]+= 1
break
else:
if(f[j] == len(p[j])):
if(j == 0):
ok = True
break
else:
f[j] = 0
f[j-1] += 1
if ok:
break
for j in range(len(ans)):
print(ans[j])
```
| 96,952 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from 1 to n.
It is known that, from the capital (the city with the number 1), you can reach any other city by moving along the roads.
The President of Berland plans to improve the country's road network. The budget is enough to repair exactly n-1 roads. The President plans to choose a set of n-1 roads such that:
* it is possible to travel from the capital to any other city along the n-1 chosen roads,
* if d_i is the number of roads needed to travel from the capital to city i, moving only along the n-1 chosen roads, then d_1 + d_2 + ... + d_n is minimized (i.e. as minimal as possible).
In other words, the set of n-1 roads should preserve the connectivity of the country, and the sum of distances from city 1 to all cities should be minimized (where you can only use the n-1 chosen roads).
The president instructed the ministry to prepare k possible options to choose n-1 roads so that both conditions above are met.
Write a program that will find k possible ways to choose roads for repair. If there are fewer than k ways, then the program should output all possible valid ways to choose roads.
Input
The first line of the input contains integers n, m and k (2 ≤ n ≤ 2⋅10^5, n-1 ≤ m ≤ 2⋅10^5, 1 ≤ k ≤ 2⋅10^5), where n is the number of cities in the country, m is the number of roads and k is the number of options to choose a set of roads for repair. It is guaranteed that m ⋅ k ≤ 10^6.
The following m lines describe the roads, one road per line. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the numbers of the cities that the i-th road connects. There is at most one road between a pair of cities. The given set of roads is such that you can reach any city from the capital.
Output
Print t (1 ≤ t ≤ k) — the number of ways to choose a set of roads for repair. Recall that you need to find k different options; if there are fewer than k of them, then you need to find all possible different valid options.
In the following t lines, print the options, one per line. Print an option as a string of m characters where the j-th character is equal to '1' if the j-th road is included in the option, and is equal to '0' if the road is not included. The roads should be numbered according to their order in the input. The options can be printed in any order. All the t lines should be different.
Since it is guaranteed that m ⋅ k ≤ 10^6, the total length of all the t lines will not exceed 10^6.
If there are several answers, output any of them.
Examples
Input
4 4 3
1 2
2 3
1 4
4 3
Output
2
1110
1011
Input
4 6 3
1 2
2 3
1 4
4 3
2 4
1 3
Output
1
101001
Input
5 6 2
1 2
1 3
2 4
2 5
3 4
3 5
Output
2
111100
110110
Tags: brute force, dfs and similar, graphs, shortest paths
Correct Solution:
```
import sys
input=lambda:sys.stdin.readline().rstrip()
sys.setrecursionlimit(200001)
n,m,k=map(int,input().split())
edge=[[]for _ in range(n)]
di={}
for i in range(m):
a,b=map(int,input().split())
a-=1
b-=1
if a>b:a,b=b,a
di[(a,b)]=i
edge[a].append(b)
edge[b].append(a)
d=[10**10]*n
d[0]=0
root=[set()for _ in range(n)]
queue=[0]
for node in queue:
for mode in edge[node]:
if d[mode]!=10**10:
if d[mode]+1==d[node]:
root[node].add(mode)
elif d[mode]==d[node]+1:
root[mode].add(node)
continue
d[mode]=d[node]+1
queue.append(mode)
for i in range(n):root[i]=list(root[i])
t=1
for i in range(1,n):t*=len(root[i])
print(min(t,k))
for i in range(min(t,k)):
ans=["0"]*m
for j in range(1,n):
i,jj=divmod(i,len(root[j]))
ans[di[(min(j,root[j][jj]),max(j,root[j][jj]))]]="1"
print("".join(ans))
```
| 96,953 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from 1 to n.
It is known that, from the capital (the city with the number 1), you can reach any other city by moving along the roads.
The President of Berland plans to improve the country's road network. The budget is enough to repair exactly n-1 roads. The President plans to choose a set of n-1 roads such that:
* it is possible to travel from the capital to any other city along the n-1 chosen roads,
* if d_i is the number of roads needed to travel from the capital to city i, moving only along the n-1 chosen roads, then d_1 + d_2 + ... + d_n is minimized (i.e. as minimal as possible).
In other words, the set of n-1 roads should preserve the connectivity of the country, and the sum of distances from city 1 to all cities should be minimized (where you can only use the n-1 chosen roads).
The president instructed the ministry to prepare k possible options to choose n-1 roads so that both conditions above are met.
Write a program that will find k possible ways to choose roads for repair. If there are fewer than k ways, then the program should output all possible valid ways to choose roads.
Input
The first line of the input contains integers n, m and k (2 ≤ n ≤ 2⋅10^5, n-1 ≤ m ≤ 2⋅10^5, 1 ≤ k ≤ 2⋅10^5), where n is the number of cities in the country, m is the number of roads and k is the number of options to choose a set of roads for repair. It is guaranteed that m ⋅ k ≤ 10^6.
The following m lines describe the roads, one road per line. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the numbers of the cities that the i-th road connects. There is at most one road between a pair of cities. The given set of roads is such that you can reach any city from the capital.
Output
Print t (1 ≤ t ≤ k) — the number of ways to choose a set of roads for repair. Recall that you need to find k different options; if there are fewer than k of them, then you need to find all possible different valid options.
In the following t lines, print the options, one per line. Print an option as a string of m characters where the j-th character is equal to '1' if the j-th road is included in the option, and is equal to '0' if the road is not included. The roads should be numbered according to their order in the input. The options can be printed in any order. All the t lines should be different.
Since it is guaranteed that m ⋅ k ≤ 10^6, the total length of all the t lines will not exceed 10^6.
If there are several answers, output any of them.
Examples
Input
4 4 3
1 2
2 3
1 4
4 3
Output
2
1110
1011
Input
4 6 3
1 2
2 3
1 4
4 3
2 4
1 3
Output
1
101001
Input
5 6 2
1 2
1 3
2 4
2 5
3 4
3 5
Output
2
111100
110110
Tags: brute force, dfs and similar, graphs, shortest paths
Correct Solution:
```
n, m, k = [int(x) for x in input().split()]
E = [[] for _ in range(n)]
for i in range(m):
a, b = [int(x) for x in input().split()]
E[a - 1].append((b - 1, i))
E[b - 1].append((a - 1, i))
Q = [0]
INFTY = n + 1
levels = [INFTY] * n
levels[0] = 0
E_min = [[] for _ in range(n)]
# bfs
while len(Q) > 0:
city = Q.pop(0)
for adj, i in E[city]:
if levels[city] + 1 <= levels[adj]:
if levels[adj] == INFTY:
Q.append(adj)
levels[adj] = levels[city] + 1
E_min[adj].append(i)
def gen_poss(city, selected, all_poss, next_choice, poss):
if len(all_poss) >= k:
return
if poss >= k:
all_poss.append(''.join(selected))
return
if city == n:
all_poss.append(''.join(selected))
else:
# choose one from E_min[edge]
for i in E_min[city]:
selected[i] = '1'
next_city = next_choice[city] # skip edges with only one choice
gen_poss(next_city, selected, all_poss, next_choice, poss * len(E_min[city]))
selected[i] = '0'
next_choice = [0] * n
selected = ['0'] * m
nc = n
for i in range(n - 1, -1, -1):
next_choice[i] = nc
if len(E_min[i]) > 1:
nc = i
if len(E_min[i]) >= 1:
selected[E_min[i][0]] = '1'
all_poss = []
gen_poss(next_choice[0], selected, all_poss, next_choice, 1)
print('{}\n{}'.format(len(all_poss), '\n'.join(all_poss)))
```
| 96,954 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from 1 to n.
It is known that, from the capital (the city with the number 1), you can reach any other city by moving along the roads.
The President of Berland plans to improve the country's road network. The budget is enough to repair exactly n-1 roads. The President plans to choose a set of n-1 roads such that:
* it is possible to travel from the capital to any other city along the n-1 chosen roads,
* if d_i is the number of roads needed to travel from the capital to city i, moving only along the n-1 chosen roads, then d_1 + d_2 + ... + d_n is minimized (i.e. as minimal as possible).
In other words, the set of n-1 roads should preserve the connectivity of the country, and the sum of distances from city 1 to all cities should be minimized (where you can only use the n-1 chosen roads).
The president instructed the ministry to prepare k possible options to choose n-1 roads so that both conditions above are met.
Write a program that will find k possible ways to choose roads for repair. If there are fewer than k ways, then the program should output all possible valid ways to choose roads.
Input
The first line of the input contains integers n, m and k (2 ≤ n ≤ 2⋅10^5, n-1 ≤ m ≤ 2⋅10^5, 1 ≤ k ≤ 2⋅10^5), where n is the number of cities in the country, m is the number of roads and k is the number of options to choose a set of roads for repair. It is guaranteed that m ⋅ k ≤ 10^6.
The following m lines describe the roads, one road per line. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the numbers of the cities that the i-th road connects. There is at most one road between a pair of cities. The given set of roads is such that you can reach any city from the capital.
Output
Print t (1 ≤ t ≤ k) — the number of ways to choose a set of roads for repair. Recall that you need to find k different options; if there are fewer than k of them, then you need to find all possible different valid options.
In the following t lines, print the options, one per line. Print an option as a string of m characters where the j-th character is equal to '1' if the j-th road is included in the option, and is equal to '0' if the road is not included. The roads should be numbered according to their order in the input. The options can be printed in any order. All the t lines should be different.
Since it is guaranteed that m ⋅ k ≤ 10^6, the total length of all the t lines will not exceed 10^6.
If there are several answers, output any of them.
Examples
Input
4 4 3
1 2
2 3
1 4
4 3
Output
2
1110
1011
Input
4 6 3
1 2
2 3
1 4
4 3
2 4
1 3
Output
1
101001
Input
5 6 2
1 2
1 3
2 4
2 5
3 4
3 5
Output
2
111100
110110
Tags: brute force, dfs and similar, graphs, shortest paths
Correct Solution:
```
import sys
import os
class Path():
def __init__(self, idx, s, d):
self.idx = idx
self.s = s
self.d = d
def __eq__(self, rhs):
return self.s == rhs.s and self.d == rhs.d
def __hash__(self):
return self.s * 100000 + self.d
def shortestPath(n, k, paths):
ps = dict()
for p in paths:
if p.s not in ps:
ps[p.s] = [p]
else:
ps[p.s].append(p)
if p.d not in ps:
ps[p.d] = [p]
else:
ps[p.d].append(p)
d = set()
open = set()
d.add(1)
for e in paths:
if e.s == 1 or e.d == 1:
open.add(e)
general_edges = []
general_choices = []
while len(d) < n:
newd = set()
choices = dict()
for e in open:
oe = e.s
if e.s in d:
oe = e.d
newd.add(oe)
if oe not in choices:
choices[oe] = [e.idx]
else:
choices[oe].append(e.idx)
d.update(newd)
for oe, p in choices.items():
if len(p) > 1:
general_choices.append(p)
else:
general_edges.append(p[0])
open = set()
for node in newd:
for p in ps[node]:
if (p.s in d) != (p.d in d):
open.add(p)
maxk = 1
for choice in general_choices:
maxk *= len(choice)
k = min(k, maxk)
print(k)
output = ['0'] * len(paths)
for e in general_edges:
output[e] = '1'
for e in general_choices:
output[e[0]] = '1'
for i in range(k):
print(''.join(output))
for choice in general_choices:
done = False
for i in range(len(choice) - 1):
if output[choice[i]] == '1':
output[choice[i]] = '0'
output[choice[i + 1]] = '1'
done = True
break
if done:
break
output[choice[len(choice) - 1]] = '0'
output[choice[0]] = '1'
def main():
n, m, k = (int(x) for x in input().split())
paths = []
for i in range(m):
path = [int(x) for x in input().split()]
paths.append(Path(i, path[0], path[1]))
shortestPath(n, k, paths)
if __name__ == '__main__':
main()
```
| 96,955 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from 1 to n.
It is known that, from the capital (the city with the number 1), you can reach any other city by moving along the roads.
The President of Berland plans to improve the country's road network. The budget is enough to repair exactly n-1 roads. The President plans to choose a set of n-1 roads such that:
* it is possible to travel from the capital to any other city along the n-1 chosen roads,
* if d_i is the number of roads needed to travel from the capital to city i, moving only along the n-1 chosen roads, then d_1 + d_2 + ... + d_n is minimized (i.e. as minimal as possible).
In other words, the set of n-1 roads should preserve the connectivity of the country, and the sum of distances from city 1 to all cities should be minimized (where you can only use the n-1 chosen roads).
The president instructed the ministry to prepare k possible options to choose n-1 roads so that both conditions above are met.
Write a program that will find k possible ways to choose roads for repair. If there are fewer than k ways, then the program should output all possible valid ways to choose roads.
Input
The first line of the input contains integers n, m and k (2 ≤ n ≤ 2⋅10^5, n-1 ≤ m ≤ 2⋅10^5, 1 ≤ k ≤ 2⋅10^5), where n is the number of cities in the country, m is the number of roads and k is the number of options to choose a set of roads for repair. It is guaranteed that m ⋅ k ≤ 10^6.
The following m lines describe the roads, one road per line. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the numbers of the cities that the i-th road connects. There is at most one road between a pair of cities. The given set of roads is such that you can reach any city from the capital.
Output
Print t (1 ≤ t ≤ k) — the number of ways to choose a set of roads for repair. Recall that you need to find k different options; if there are fewer than k of them, then you need to find all possible different valid options.
In the following t lines, print the options, one per line. Print an option as a string of m characters where the j-th character is equal to '1' if the j-th road is included in the option, and is equal to '0' if the road is not included. The roads should be numbered according to their order in the input. The options can be printed in any order. All the t lines should be different.
Since it is guaranteed that m ⋅ k ≤ 10^6, the total length of all the t lines will not exceed 10^6.
If there are several answers, output any of them.
Examples
Input
4 4 3
1 2
2 3
1 4
4 3
Output
2
1110
1011
Input
4 6 3
1 2
2 3
1 4
4 3
2 4
1 3
Output
1
101001
Input
5 6 2
1 2
1 3
2 4
2 5
3 4
3 5
Output
2
111100
110110
Submitted Solution:
```
import sys
input=lambda:sys.stdin.readline().rstrip()
sys.setrecursionlimit(200001)
n,m,k=map(int,input().split())
edge=[[]for _ in range(n)]
di={}
for i in range(m):
a,b=map(int,input().split())
a-=1
b-=1
if a>b:a,b=b,a
di[(a,b)]=i
edge[a].append(b)
edge[b].append(a)
d=[10**10]*n
d[0]=0
root=[set()for _ in range(n)]
queue=[0]
for node in queue:
for mode in edge[node]:
if d[mode]!=10**10:
if d[mode]+1==d[node]:
root[node].add(mode)
elif d[mode]==d[node]+1:
root[mode].add(node)
continue
d[mode]=d[node]+1
queue.append(mode)
for i in range(n):root[i]=list(root[i])
ans=["0"]*m
anss=[]
def f(i,k):
for j in root[i]:
ii=min(i,j)
jj=max(i,j)
ans[di[(ii,jj)]]="1"
if i==n-1:
k-=1
anss.append("".join(ans))
else:
k-=f(i+1,k)
ans[di[(ii,jj)]]="0"
if k==0:break
return k
f(1,k)
print(len(anss))
for i in anss:print(i)
```
No
| 96,956 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from 1 to n.
It is known that, from the capital (the city with the number 1), you can reach any other city by moving along the roads.
The President of Berland plans to improve the country's road network. The budget is enough to repair exactly n-1 roads. The President plans to choose a set of n-1 roads such that:
* it is possible to travel from the capital to any other city along the n-1 chosen roads,
* if d_i is the number of roads needed to travel from the capital to city i, moving only along the n-1 chosen roads, then d_1 + d_2 + ... + d_n is minimized (i.e. as minimal as possible).
In other words, the set of n-1 roads should preserve the connectivity of the country, and the sum of distances from city 1 to all cities should be minimized (where you can only use the n-1 chosen roads).
The president instructed the ministry to prepare k possible options to choose n-1 roads so that both conditions above are met.
Write a program that will find k possible ways to choose roads for repair. If there are fewer than k ways, then the program should output all possible valid ways to choose roads.
Input
The first line of the input contains integers n, m and k (2 ≤ n ≤ 2⋅10^5, n-1 ≤ m ≤ 2⋅10^5, 1 ≤ k ≤ 2⋅10^5), where n is the number of cities in the country, m is the number of roads and k is the number of options to choose a set of roads for repair. It is guaranteed that m ⋅ k ≤ 10^6.
The following m lines describe the roads, one road per line. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the numbers of the cities that the i-th road connects. There is at most one road between a pair of cities. The given set of roads is such that you can reach any city from the capital.
Output
Print t (1 ≤ t ≤ k) — the number of ways to choose a set of roads for repair. Recall that you need to find k different options; if there are fewer than k of them, then you need to find all possible different valid options.
In the following t lines, print the options, one per line. Print an option as a string of m characters where the j-th character is equal to '1' if the j-th road is included in the option, and is equal to '0' if the road is not included. The roads should be numbered according to their order in the input. The options can be printed in any order. All the t lines should be different.
Since it is guaranteed that m ⋅ k ≤ 10^6, the total length of all the t lines will not exceed 10^6.
If there are several answers, output any of them.
Examples
Input
4 4 3
1 2
2 3
1 4
4 3
Output
2
1110
1011
Input
4 6 3
1 2
2 3
1 4
4 3
2 4
1 3
Output
1
101001
Input
5 6 2
1 2
1 3
2 4
2 5
3 4
3 5
Output
2
111100
110110
Submitted Solution:
```
import sys
input=lambda:sys.stdin.readline().rstrip()
sys.setrecursionlimit(200001)
n,m,k=map(int,input().split())
edge=[[]for _ in range(n)]
di={}
for i in range(m):
a,b=map(int,input().split())
a-=1
b-=1
if a>b:a,b=b,a
di[(a,b)]=i
edge[a].append(b)
edge[b].append(a)
d=[10**10]*n
d[0]=0
root=[set()for _ in range(n)]
queue=[0]
for node in queue:
for mode in edge[node]:
if d[mode]!=10**10:
if d[mode]+1==d[node]:
root[node].add(mode)
elif d[mode]==d[node]+1:
root[mode].add(node)
continue
d[mode]=d[node]+1
queue.append(mode)
for i in range(n):root[i]=list(root[i])
ans=["0"]*m
anss=[]
def f(i,k):
for j in root[i]:
ii=min(i,j)
jj=max(i,j)
ans[di[(ii,jj)]]="1"
if i==n-1:
k-=1
anss.append("".join(ans))
if k==0:
print(len(anss))
for i in anss:print(i)
exit()
else:
k-=f(i+1,k)
ans[di[(ii,jj)]]="0"
if k==0:break
return k
f(1,k)
print(len(anss))
for i in anss:print(i)
```
No
| 96,957 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from 1 to n.
It is known that, from the capital (the city with the number 1), you can reach any other city by moving along the roads.
The President of Berland plans to improve the country's road network. The budget is enough to repair exactly n-1 roads. The President plans to choose a set of n-1 roads such that:
* it is possible to travel from the capital to any other city along the n-1 chosen roads,
* if d_i is the number of roads needed to travel from the capital to city i, moving only along the n-1 chosen roads, then d_1 + d_2 + ... + d_n is minimized (i.e. as minimal as possible).
In other words, the set of n-1 roads should preserve the connectivity of the country, and the sum of distances from city 1 to all cities should be minimized (where you can only use the n-1 chosen roads).
The president instructed the ministry to prepare k possible options to choose n-1 roads so that both conditions above are met.
Write a program that will find k possible ways to choose roads for repair. If there are fewer than k ways, then the program should output all possible valid ways to choose roads.
Input
The first line of the input contains integers n, m and k (2 ≤ n ≤ 2⋅10^5, n-1 ≤ m ≤ 2⋅10^5, 1 ≤ k ≤ 2⋅10^5), where n is the number of cities in the country, m is the number of roads and k is the number of options to choose a set of roads for repair. It is guaranteed that m ⋅ k ≤ 10^6.
The following m lines describe the roads, one road per line. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the numbers of the cities that the i-th road connects. There is at most one road between a pair of cities. The given set of roads is such that you can reach any city from the capital.
Output
Print t (1 ≤ t ≤ k) — the number of ways to choose a set of roads for repair. Recall that you need to find k different options; if there are fewer than k of them, then you need to find all possible different valid options.
In the following t lines, print the options, one per line. Print an option as a string of m characters where the j-th character is equal to '1' if the j-th road is included in the option, and is equal to '0' if the road is not included. The roads should be numbered according to their order in the input. The options can be printed in any order. All the t lines should be different.
Since it is guaranteed that m ⋅ k ≤ 10^6, the total length of all the t lines will not exceed 10^6.
If there are several answers, output any of them.
Examples
Input
4 4 3
1 2
2 3
1 4
4 3
Output
2
1110
1011
Input
4 6 3
1 2
2 3
1 4
4 3
2 4
1 3
Output
1
101001
Input
5 6 2
1 2
1 3
2 4
2 5
3 4
3 5
Output
2
111100
110110
Submitted Solution:
```
import sys,math
from collections import defaultdict,deque
import itertools
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
n,m,k = inpl()
g = [[] for _ in range(n)]
edge = {}
for i in range(m):
a,b = inpl()
a,b = a-1,b-1
g[a].append(b)
g[b].append(a)
edge[(a,b)] = i
edge[(b,a)] = i
de = set()
dist = [INF] * n
dist[0] = 0
pre = [-1] * n
q = deque()
q.append(0)
while q:
now = q.popleft()
for nx in g[now]:
if pre[now] == nx: continue
if dist[nx] == INF:
dist[nx] = dist[now] + 1
pre[nx] = now
q.append(nx)
elif dist[nx] > dist[now] + 1:
de.add(edge[pre[nx],nx])
pre[nx] = now
dist[nx] = dist[now] + 1
q.append(nx)
elif dist[nx] == dist[now] + 1:
de.add(edge[pre[nx],nx])
de.add(edge[now,nx])
else:
de.add(edge[now,nx])
# print(de)
de = list(de)
cnt = 0
for pt in itertools.combinations(de,m-(n-1)):
if cnt == k: break
res = ['1'] * m
for x in pt:
res[x] = '0'
print(''.join(res))
cnt += 1
```
No
| 96,958 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from 1 to n.
It is known that, from the capital (the city with the number 1), you can reach any other city by moving along the roads.
The President of Berland plans to improve the country's road network. The budget is enough to repair exactly n-1 roads. The President plans to choose a set of n-1 roads such that:
* it is possible to travel from the capital to any other city along the n-1 chosen roads,
* if d_i is the number of roads needed to travel from the capital to city i, moving only along the n-1 chosen roads, then d_1 + d_2 + ... + d_n is minimized (i.e. as minimal as possible).
In other words, the set of n-1 roads should preserve the connectivity of the country, and the sum of distances from city 1 to all cities should be minimized (where you can only use the n-1 chosen roads).
The president instructed the ministry to prepare k possible options to choose n-1 roads so that both conditions above are met.
Write a program that will find k possible ways to choose roads for repair. If there are fewer than k ways, then the program should output all possible valid ways to choose roads.
Input
The first line of the input contains integers n, m and k (2 ≤ n ≤ 2⋅10^5, n-1 ≤ m ≤ 2⋅10^5, 1 ≤ k ≤ 2⋅10^5), where n is the number of cities in the country, m is the number of roads and k is the number of options to choose a set of roads for repair. It is guaranteed that m ⋅ k ≤ 10^6.
The following m lines describe the roads, one road per line. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the numbers of the cities that the i-th road connects. There is at most one road between a pair of cities. The given set of roads is such that you can reach any city from the capital.
Output
Print t (1 ≤ t ≤ k) — the number of ways to choose a set of roads for repair. Recall that you need to find k different options; if there are fewer than k of them, then you need to find all possible different valid options.
In the following t lines, print the options, one per line. Print an option as a string of m characters where the j-th character is equal to '1' if the j-th road is included in the option, and is equal to '0' if the road is not included. The roads should be numbered according to their order in the input. The options can be printed in any order. All the t lines should be different.
Since it is guaranteed that m ⋅ k ≤ 10^6, the total length of all the t lines will not exceed 10^6.
If there are several answers, output any of them.
Examples
Input
4 4 3
1 2
2 3
1 4
4 3
Output
2
1110
1011
Input
4 6 3
1 2
2 3
1 4
4 3
2 4
1 3
Output
1
101001
Input
5 6 2
1 2
1 3
2 4
2 5
3 4
3 5
Output
2
111100
110110
Submitted Solution:
```
n, m, k = [int(x) for x in input().split()]
E = [[] for _ in range(n)]
for i in range(m):
a, b = [int(x) for x in input().split()]
E[a - 1].append((b - 1, i))
Q = [0]
INFTY = n + 1
levels = [INFTY] * n
levels[0] = 0
E_min = [[] for _ in range(n)]
while len(Q) > 0:
city = Q.pop(0)
for adj, i in E[city]:
if levels[city] + 1 <= levels[adj]:
if levels[adj] == INFTY:
Q.append(adj)
levels[adj] = levels[city] + 1
E_min[adj].append(i)
def gen_poss(edge, selected, all_poss):
if len(all_poss) >= k:
return
if edge == n:
all_poss.append(''.join(selected))
else:
# choose one from E_min[edge]
if len(E_min[edge]) == 0:
gen_poss(edge + 1, selected, all_poss)
else:
for i in E_min[edge]:
selected[i] = '1'
gen_poss(edge + 1, selected, all_poss)
selected[i] = '0'
all_poss = []
gen_poss(0, ['0'] * m, all_poss)
print('{}\n{}'.format(len(all_poss), '\n'.join(all_poss)))
```
No
| 96,959 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loops and multiple edges.
Input
The first line contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
The following n - 1 lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≤ u_i, v_i ≤ n). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.
Output
Print a single integer — the minimum number of edges you have to add in order to make the shortest distance from the vertex 1 to any other vertex at most 2. Note that you are not allowed to add loops and multiple edges.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
5 7
Output
2
Input
7
1 2
1 3
2 4
2 5
3 6
1 7
Output
0
Input
7
1 2
2 3
3 4
3 5
3 6
3 7
Output
1
Note
The tree corresponding to the first example: <image> The answer is 2, some of the possible answers are the following: [(1, 5), (1, 6)], [(1, 4), (1, 7)], [(1, 6), (1, 7)].
The tree corresponding to the second example: <image> The answer is 0.
The tree corresponding to the third example: <image> The answer is 1, only one possible way to reach it is to add the edge (1, 3).
Tags: dp, graphs, greedy
Correct Solution:
```
from sys import stdin
n = int(stdin.readline())
g = dict()
for i in range(n-1):
u,v = map(int,stdin.readline().split())
g.setdefault(u-1,[]).append(v-1)
g.setdefault(v-1, []).append(u-1)
st = [0]
rank = [0]*n
tree = [0]*n
msk = [0]*n
rd = dict()
while len(st)>0:
top = st.pop()
msk[top] = 1
for c in g[top]:
if msk[c] == 0:
st.append(c)
tree[c] = top
rank[c] = rank[top]+1
rd.setdefault(rank[c], []).append(c)
max_rank = max(rank)
reach = [0]*n
build = [0]*n
ans = 0
for r in range(max_rank, 2, -1):
for node in rd[r]:
if reach[node] == 0:
reach[node] = 1
reach[tree[node]] = 1
reach[tree[tree[node]]] = 1
build[tree[node]] = 1
print(sum(build))
```
| 96,960 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loops and multiple edges.
Input
The first line contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
The following n - 1 lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≤ u_i, v_i ≤ n). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.
Output
Print a single integer — the minimum number of edges you have to add in order to make the shortest distance from the vertex 1 to any other vertex at most 2. Note that you are not allowed to add loops and multiple edges.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
5 7
Output
2
Input
7
1 2
1 3
2 4
2 5
3 6
1 7
Output
0
Input
7
1 2
2 3
3 4
3 5
3 6
3 7
Output
1
Note
The tree corresponding to the first example: <image> The answer is 2, some of the possible answers are the following: [(1, 5), (1, 6)], [(1, 4), (1, 7)], [(1, 6), (1, 7)].
The tree corresponding to the second example: <image> The answer is 0.
The tree corresponding to the third example: <image> The answer is 1, only one possible way to reach it is to add the edge (1, 3).
Tags: dp, graphs, greedy
Correct Solution:
```
from collections import defaultdict
from collections import deque
import sys
input = sys.stdin.readline
def bfs(s):
q = deque()
q.append(s)
dist = [-1] * (n + 1)
dist[s] = 0
p = []
parent = [1] * (n + 1)
ok = [0] * (n + 1)
while q:
i = q.popleft()
d = dist[i]
if d < 3:
ok[i] = 1
p.append(i)
for j in G[i]:
if dist[j] == -1:
q.append(j)
dist[j] = d + 1
parent[j] = i
ans = 0
while p:
i = p.pop()
j = parent[i]
if not ok[i]:
ok[j] = 1
ans += 1
for k in G[j]:
ok[k] = 1
return ans
n = int(input())
G = [[] for _ in range(n + 1)]
for _ in range(n - 1):
u, v = map(int, input().split())
G[u].append(v)
G[v].append(u)
ans = bfs(1)
print(ans)
```
| 96,961 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loops and multiple edges.
Input
The first line contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
The following n - 1 lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≤ u_i, v_i ≤ n). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.
Output
Print a single integer — the minimum number of edges you have to add in order to make the shortest distance from the vertex 1 to any other vertex at most 2. Note that you are not allowed to add loops and multiple edges.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
5 7
Output
2
Input
7
1 2
1 3
2 4
2 5
3 6
1 7
Output
0
Input
7
1 2
2 3
3 4
3 5
3 6
3 7
Output
1
Note
The tree corresponding to the first example: <image> The answer is 2, some of the possible answers are the following: [(1, 5), (1, 6)], [(1, 4), (1, 7)], [(1, 6), (1, 7)].
The tree corresponding to the second example: <image> The answer is 0.
The tree corresponding to the third example: <image> The answer is 1, only one possible way to reach it is to add the edge (1, 3).
Tags: dp, graphs, greedy
Correct Solution:
```
import sys
def get_new_edges(graph):
n = len(graph)
far_vertex = []
pi = [None]*n
visit = [False]*n
visit[0]
queue = [[0,0]]
i = 0
while True:
if i >= len(queue): break
current, d = queue[i]
i += 1
visit[current] = True
for v in graph[current]:
if not visit[v]:
u = [v, d+1]
pi[v] = current
queue.append(u)
if d+1 > 2:
far_vertex.append(u)
far_vertex.sort(key=lambda x: -x[1])
pos = [None]*n
for i, e in enumerate(far_vertex):
pos[e[0]] = i
count = 0
for i in range(len(far_vertex)):
if not far_vertex[i]: continue
vertex, depth = far_vertex[i]
father = pi[vertex]
count += 1
if pos[father]:
far_vertex[pos[father]] = None
for u in graph[father]:
if pos[u]:
far_vertex[pos[u]] = None
return count
def read_int_line():
return map(int, sys.stdin.readline().split())
vertex_count = int(input())
graph = [[] for _ in range(vertex_count)]
for i in range(vertex_count - 1):
v1, v2 = read_int_line()
v1 -= 1
v2 -= 1
graph[v1].append(v2)
graph[v2].append(v1)
print(get_new_edges(graph))
```
| 96,962 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loops and multiple edges.
Input
The first line contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
The following n - 1 lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≤ u_i, v_i ≤ n). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.
Output
Print a single integer — the minimum number of edges you have to add in order to make the shortest distance from the vertex 1 to any other vertex at most 2. Note that you are not allowed to add loops and multiple edges.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
5 7
Output
2
Input
7
1 2
1 3
2 4
2 5
3 6
1 7
Output
0
Input
7
1 2
2 3
3 4
3 5
3 6
3 7
Output
1
Note
The tree corresponding to the first example: <image> The answer is 2, some of the possible answers are the following: [(1, 5), (1, 6)], [(1, 4), (1, 7)], [(1, 6), (1, 7)].
The tree corresponding to the second example: <image> The answer is 0.
The tree corresponding to the third example: <image> The answer is 1, only one possible way to reach it is to add the edge (1, 3).
Tags: dp, graphs, greedy
Correct Solution:
```
import sys
from collections import deque
import heapq
input = sys.stdin.readline
N=int(input())
EDGE=[list(map(int,input().split())) for i in range(N-1)]
EDGELIST=[[] for i in range(N+1)]
for i,j in EDGE:
EDGELIST[i].append(j)
EDGELIST[j].append(i)
#EDGES=[[] for i in range(N+1)]
REDG=[None for i in range(N+1)]
QUE=deque([1])
check=[0]*(N+1)
DEPTH=[None]*(N+1)
i=0
while QUE:
NQUE=deque()
i+=1
while QUE:
x=QUE.pop()
DEPTH[x]=i
check[x]=1
for to in EDGELIST[x]:
if check[to]==1:
continue
else:
#EDGES[x].append(to)
REDG[to]=x
NQUE.append(to)
QUE=NQUE
check=[0]*(N+1)
check[1]=1
#NEXT=[]
#for i in EDGES[1]:
# check[i]=1
# NEXT.append(i)
#for j in NEXT:
# for k in EDGES[j]:
# check[k]=1
LEAF=[]
for i in range(2,N+1):
if len(EDGELIST[i])==1:
LEAF.append((-DEPTH[i],i))
QUE=LEAF
heapq.heapify(QUE)
ANS=0
#print(check,QUE)
while QUE:
dep,x=heapq.heappop(QUE)
if check[x]!=0 or dep>=-3:
continue
if check[REDG[x]]==2:
continue
if check[x]==0:
check[x]=1
if check[REDG[REDG[x]]]==0:
check[REDG[REDG[x]]]=1
check[REDG[x]]=2
heapq.heappush(QUE,(-DEPTH[REDG[REDG[REDG[x]]]],REDG[REDG[REDG[x]]]))
ANS+=1
#print(x,QUE,check)
print(ANS)
```
| 96,963 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an undirected tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loops and multiple edges.
Input
The first line contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
The following n - 1 lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≤ u_i, v_i ≤ n). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.
Output
Print a single integer — the minimum number of edges you have to add in order to make the shortest distance from the vertex 1 to any other vertex at most 2. Note that you are not allowed to add loops and multiple edges.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
5 7
Output
2
Input
7
1 2
1 3
2 4
2 5
3 6
1 7
Output
0
Input
7
1 2
2 3
3 4
3 5
3 6
3 7
Output
1
Note
The tree corresponding to the first example: <image> The answer is 2, some of the possible answers are the following: [(1, 5), (1, 6)], [(1, 4), (1, 7)], [(1, 6), (1, 7)].
The tree corresponding to the second example: <image> The answer is 0.
The tree corresponding to the third example: <image> The answer is 1, only one possible way to reach it is to add the edge (1, 3).
Tags: dp, graphs, greedy
Correct Solution:
```
import sys
from collections import deque
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
n = inp()
edges = [[] for _ in range(n)]
for _ in range(n-1):
a,b = inpl()
a,b = a-1,b-1
edges[a].append(b)
edges[b].append(a)
dist = [-1] * n
dist[0] = 0
pa = [-1] * n
se = set()
pq = []
q = deque()
q.append(0)
while q:
now = q.popleft()
for nx in edges[now]:
if dist[nx] != -1:
continue
pa[nx] = now
dist[nx] = dist[now] + 1
if dist[nx] > 2:
se.add(nx)
pq.append((dist[nx], nx))
q.append(nx)
pq = pq[::-1]
res = 0
ind = 0
while se:
d,v = pq[ind]
ind += 1
if not v in se:
continue
res += 1
pv = pa[v]
se.discard(pv)
for nv in edges[pv]:
se.discard(nv)
print(res)
```
| 96,964 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loops and multiple edges.
Input
The first line contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
The following n - 1 lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≤ u_i, v_i ≤ n). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.
Output
Print a single integer — the minimum number of edges you have to add in order to make the shortest distance from the vertex 1 to any other vertex at most 2. Note that you are not allowed to add loops and multiple edges.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
5 7
Output
2
Input
7
1 2
1 3
2 4
2 5
3 6
1 7
Output
0
Input
7
1 2
2 3
3 4
3 5
3 6
3 7
Output
1
Note
The tree corresponding to the first example: <image> The answer is 2, some of the possible answers are the following: [(1, 5), (1, 6)], [(1, 4), (1, 7)], [(1, 6), (1, 7)].
The tree corresponding to the second example: <image> The answer is 0.
The tree corresponding to the third example: <image> The answer is 1, only one possible way to reach it is to add the edge (1, 3).
Submitted Solution:
```
n=int(input())
l=[[] for i in range(n+2)]
visited=[False for i in range(n+2)]
for i in range(n-1):
a,b=map(int,input().split())
l[a].append(b)
l[b].append(a)
dp=[[] for i in range(n+2)]
f=[-1 for i in range(n+2)]
def dfs(n,p):
dp[p].append(n)
p+=1
for i in l[n]:
if not visited[i]:
f[i]=n
visited[i]=True
dfs(i,p)
visited[n]=False
ans=0
dfs(1,0)
for i in range(n,2,-1):
for j in dp[i]:
if not visited[j]:
visited[j]=True
visited[f[j]]=True
ans+=1
for k in (l[f[j]]):
visited[k]=True
print(ans)
```
No
| 96,965 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loops and multiple edges.
Input
The first line contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
The following n - 1 lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≤ u_i, v_i ≤ n). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.
Output
Print a single integer — the minimum number of edges you have to add in order to make the shortest distance from the vertex 1 to any other vertex at most 2. Note that you are not allowed to add loops and multiple edges.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
5 7
Output
2
Input
7
1 2
1 3
2 4
2 5
3 6
1 7
Output
0
Input
7
1 2
2 3
3 4
3 5
3 6
3 7
Output
1
Note
The tree corresponding to the first example: <image> The answer is 2, some of the possible answers are the following: [(1, 5), (1, 6)], [(1, 4), (1, 7)], [(1, 6), (1, 7)].
The tree corresponding to the second example: <image> The answer is 0.
The tree corresponding to the third example: <image> The answer is 1, only one possible way to reach it is to add the edge (1, 3).
Submitted Solution:
```
import sys
from collections import deque
import heapq
input = sys.stdin.readline
N=int(input())
EDGE=[list(map(int,input().split())) for i in range(N-1)]
EDGELIST=[[] for i in range(N+1)]
for i,j in EDGE:
EDGELIST[i].append(j)
EDGELIST[j].append(i)
EDGES=[[] for i in range(N+1)]
REDG=[None for i in range(N+1)]
QUE=deque([1])
check=[0]*(N+1)
DEPTH=[None]*(N+1)
i=0
while QUE:
NQUE=deque()
i+=1
while QUE:
x=QUE.pop()
DEPTH[x]=i
check[x]=1
for to in EDGELIST[x]:
if check[to]==1:
continue
else:
EDGES[x].append(to)
REDG[to]=x
NQUE.append(to)
QUE=NQUE
check=[0]*(N+1)
check[1]=1
NEXT=[]
for i in EDGES[1]:
check[i]=1
NEXT.append(i)
for j in NEXT:
for k in EDGES[j]:
check[k]=1
LEAF=[]
for i in range(2,N+1):
if EDGES[i]==[]:
LEAF.append((-DEPTH[i],i))
QUE=LEAF
heapq.heapify(QUE)
ANS=0
#print(check,QUE)
while QUE:
_,x=QUE.pop()
if check[x]!=0:
continue
if check[REDG[x]]==2:
continue
check[x]=check[REDG[REDG[x]]]=1
check[REDG[x]]=2
heapq.heappush(QUE,(-DEPTH[REDG[REDG[REDG[x]]]],REDG[REDG[REDG[x]]]))
ANS+=1
#print(x,QUE,check)
print(ANS)
```
No
| 96,966 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loops and multiple edges.
Input
The first line contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
The following n - 1 lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≤ u_i, v_i ≤ n). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.
Output
Print a single integer — the minimum number of edges you have to add in order to make the shortest distance from the vertex 1 to any other vertex at most 2. Note that you are not allowed to add loops and multiple edges.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
5 7
Output
2
Input
7
1 2
1 3
2 4
2 5
3 6
1 7
Output
0
Input
7
1 2
2 3
3 4
3 5
3 6
3 7
Output
1
Note
The tree corresponding to the first example: <image> The answer is 2, some of the possible answers are the following: [(1, 5), (1, 6)], [(1, 4), (1, 7)], [(1, 6), (1, 7)].
The tree corresponding to the second example: <image> The answer is 0.
The tree corresponding to the third example: <image> The answer is 1, only one possible way to reach it is to add the edge (1, 3).
Submitted Solution:
```
from sys import stdin
n = int(stdin.readline())
g = dict()
for i in range(n-1):
u,v = map(int,stdin.readline().split())
g.setdefault(u-1,[]).append(v-1)
g.setdefault(v-1, []).append(u-1)
st = [0]
rank = [0]*n
tree = [0]*n
msk = [0]*n
rd = dict()
while len(st)>0:
top = st.pop()
msk[top] = 1
for c in g[top]:
if msk[c] == 0:
st.append(c)
tree[c] = top
rank[c] = rank[top]+1
rd.setdefault(rank[c], []).append(c)
max_rank = max(rank)
reach = [0]*n
for r in range(max_rank, 2, -1):
for node in rd[r]:
if reach[node] == 0:
reach[tree[node]] = 1
print(sum(reach))
```
No
| 96,967 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loops and multiple edges.
Input
The first line contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree.
The following n - 1 lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≤ u_i, v_i ≤ n). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.
Output
Print a single integer — the minimum number of edges you have to add in order to make the shortest distance from the vertex 1 to any other vertex at most 2. Note that you are not allowed to add loops and multiple edges.
Examples
Input
7
1 2
2 3
2 4
4 5
4 6
5 7
Output
2
Input
7
1 2
1 3
2 4
2 5
3 6
1 7
Output
0
Input
7
1 2
2 3
3 4
3 5
3 6
3 7
Output
1
Note
The tree corresponding to the first example: <image> The answer is 2, some of the possible answers are the following: [(1, 5), (1, 6)], [(1, 4), (1, 7)], [(1, 6), (1, 7)].
The tree corresponding to the second example: <image> The answer is 0.
The tree corresponding to the third example: <image> The answer is 1, only one possible way to reach it is to add the edge (1, 3).
Submitted Solution:
```
import sys
def get_new_edges(graph):
n = len(graph)
far_vertex = []
pi = [None]*n
visit = [False]*n
visit[0]
queue = [[0,0]]
i = 0
while True:
if i >= len(queue): break
current, d = queue[i]
i += 1
visit[current] = True
for v in graph[current]:
if not visit[v]:
u = [v, d+1]
pi[v] = current
queue.append(u)
if d+1 > 2:
far_vertex.append(u)
far_vertex.sort(key=lambda x: -x[1])
pos = [None]*n
for i, e in enumerate(far_vertex):
pos[e[0]] = i
count = 0
for i in range(len(far_vertex)):
if not far_vertex[i]: continue
vertex, depth = far_vertex[i]
father = pi[vertex]
g_father = pi[father]
count += 1
for u in graph[father]:
if pos[u] and u != g_father:
far_vertex[pos[u]] = None
return count
def read_int_line():
return map(int, sys.stdin.readline().split())
vertex_count = int(input())
graph = [[] for _ in range(vertex_count)]
for i in range(vertex_count - 1):
v1, v2 = read_int_line()
v1 -= 1
v2 -= 1
graph[v1].append(v2)
graph[v2].append(v1)
print(get_new_edges(graph))
```
No
| 96,968 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After all the events in Orlando we all know, Sasha and Roma decided to find out who is still the team's biggest loser. Thankfully, Masha found somewhere a revolver with a rotating cylinder of n bullet slots able to contain exactly k bullets, now the boys have a chance to resolve the problem once and for all.
Sasha selects any k out of n slots he wishes and puts bullets there. Roma spins the cylinder so that every of n possible cylinder's shifts is equiprobable. Then the game starts, the players take turns, Sasha starts: he puts the gun to his head and shoots. If there was no bullet in front of the trigger, the cylinder shifts by one position and the weapon is given to Roma for make the same move. The game continues until someone is shot, the survivor is the winner.
Sasha does not want to lose, so he must choose slots for bullets in such a way as to minimize the probability of its own loss. Of all the possible variant he wants to select the lexicographically minimal one, where an empty slot is lexicographically less than a charged one.
More formally, the cylinder of n bullet slots able to contain k bullets can be represented as a string of n characters. Exactly k of them are "X" (charged slots) and the others are "." (uncharged slots).
Let us describe the process of a shot. Suppose that the trigger is in front of the first character of the string (the first slot). If a shot doesn't kill anyone and the cylinder shifts, then the string shifts left. So the first character becomes the last one, the second character becomes the first one, and so on. But the trigger doesn't move. It will be in front of the first character of the resulting string.
Among all the strings that give the minimal probability of loss, Sasha choose the lexicographically minimal one. According to this very string, he charges the gun. You have to help Sasha to charge the gun. For that, each xi query must be answered: is there a bullet in the positions xi?
Input
The first line contains three integers n, k and p (1 ≤ n ≤ 1018, 0 ≤ k ≤ n, 1 ≤ p ≤ 1000) — the number of slots in the cylinder, the number of bullets and the number of queries. Then follow p lines; they are the queries. Each line contains one integer xi (1 ≤ xi ≤ n) the number of slot to describe.
Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is preferred to use cin, cout streams or the %I64d specificator.
Output
For each query print "." if the slot should be empty and "X" if the slot should be charged.
Examples
Input
3 1 3
1
2
3
Output
..X
Input
6 3 6
1
2
3
4
5
6
Output
.X.X.X
Input
5 2 5
1
2
3
4
5
Output
...XX
Note
The lexicographical comparison of is performed by the < operator in modern programming languages. The a string is lexicographically less that the b string, if there exists such i (1 ≤ i ≤ n), that ai < bi, and for any j (1 ≤ j < i) aj = bj.
Tags: constructive algorithms, greedy
Correct Solution:
```
n, k, p = map(int, input().split())
for i in range(p):
pos = int(input())
if n % 2:
if pos == n:
print('X' if k > 0 else '.', end='')
else:
if k * 2 > n + 1:
print('X' if (pos & 1) == 0 or (n - pos) // 2 \
+ n // 2 + 1<= k else '.', end='')
else:
print('X' if (pos & 1) == 0 and \
(n + 1 - pos) // 2 < k else '.', end='')
else:
if k * 2 > n:
print('X' if (pos & 1) == 0 or (n - pos + 1) // 2 + \
n // 2 <= k else '.', end='')
else:
print('X' if (pos & 1) == 0 and (n - pos + 2) // 2 <= k \
else '.', end='')
```
| 96,969 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After all the events in Orlando we all know, Sasha and Roma decided to find out who is still the team's biggest loser. Thankfully, Masha found somewhere a revolver with a rotating cylinder of n bullet slots able to contain exactly k bullets, now the boys have a chance to resolve the problem once and for all.
Sasha selects any k out of n slots he wishes and puts bullets there. Roma spins the cylinder so that every of n possible cylinder's shifts is equiprobable. Then the game starts, the players take turns, Sasha starts: he puts the gun to his head and shoots. If there was no bullet in front of the trigger, the cylinder shifts by one position and the weapon is given to Roma for make the same move. The game continues until someone is shot, the survivor is the winner.
Sasha does not want to lose, so he must choose slots for bullets in such a way as to minimize the probability of its own loss. Of all the possible variant he wants to select the lexicographically minimal one, where an empty slot is lexicographically less than a charged one.
More formally, the cylinder of n bullet slots able to contain k bullets can be represented as a string of n characters. Exactly k of them are "X" (charged slots) and the others are "." (uncharged slots).
Let us describe the process of a shot. Suppose that the trigger is in front of the first character of the string (the first slot). If a shot doesn't kill anyone and the cylinder shifts, then the string shifts left. So the first character becomes the last one, the second character becomes the first one, and so on. But the trigger doesn't move. It will be in front of the first character of the resulting string.
Among all the strings that give the minimal probability of loss, Sasha choose the lexicographically minimal one. According to this very string, he charges the gun. You have to help Sasha to charge the gun. For that, each xi query must be answered: is there a bullet in the positions xi?
Input
The first line contains three integers n, k and p (1 ≤ n ≤ 1018, 0 ≤ k ≤ n, 1 ≤ p ≤ 1000) — the number of slots in the cylinder, the number of bullets and the number of queries. Then follow p lines; they are the queries. Each line contains one integer xi (1 ≤ xi ≤ n) the number of slot to describe.
Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is preferred to use cin, cout streams or the %I64d specificator.
Output
For each query print "." if the slot should be empty and "X" if the slot should be charged.
Examples
Input
3 1 3
1
2
3
Output
..X
Input
6 3 6
1
2
3
4
5
6
Output
.X.X.X
Input
5 2 5
1
2
3
4
5
Output
...XX
Note
The lexicographical comparison of is performed by the < operator in modern programming languages. The a string is lexicographically less that the b string, if there exists such i (1 ≤ i ≤ n), that ai < bi, and for any j (1 ≤ j < i) aj = bj.
Tags: constructive algorithms, greedy
Correct Solution:
```
n, k, p = map(int, input().split())
for i in range(p):
pos = int(input())
if n % 2:
if pos == n:
print('X' if k > 0 else '.', end='')
else:
if k * 2 > n + 1:
print('X' if (pos & 1) == 0 or (n - pos) // 2 \
+ n // 2 + 1<= k else '.', end='')
else:
print('X' if (pos & 1) == 0 and \
(n + 1 - pos) // 2 < k else '.', end='')
else:
if k * 2 > n:
print('X' if (pos & 1) == 0 or (n - pos + 1) // 2 + \
n // 2 <= k else '.', end='')
else:
print('X' if (pos & 1) == 0 and (n - pos + 2) // 2 <= k \
else '.', end='')
# Made By Mostafa_Khaled
```
| 96,970 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After all the events in Orlando we all know, Sasha and Roma decided to find out who is still the team's biggest loser. Thankfully, Masha found somewhere a revolver with a rotating cylinder of n bullet slots able to contain exactly k bullets, now the boys have a chance to resolve the problem once and for all.
Sasha selects any k out of n slots he wishes and puts bullets there. Roma spins the cylinder so that every of n possible cylinder's shifts is equiprobable. Then the game starts, the players take turns, Sasha starts: he puts the gun to his head and shoots. If there was no bullet in front of the trigger, the cylinder shifts by one position and the weapon is given to Roma for make the same move. The game continues until someone is shot, the survivor is the winner.
Sasha does not want to lose, so he must choose slots for bullets in such a way as to minimize the probability of its own loss. Of all the possible variant he wants to select the lexicographically minimal one, where an empty slot is lexicographically less than a charged one.
More formally, the cylinder of n bullet slots able to contain k bullets can be represented as a string of n characters. Exactly k of them are "X" (charged slots) and the others are "." (uncharged slots).
Let us describe the process of a shot. Suppose that the trigger is in front of the first character of the string (the first slot). If a shot doesn't kill anyone and the cylinder shifts, then the string shifts left. So the first character becomes the last one, the second character becomes the first one, and so on. But the trigger doesn't move. It will be in front of the first character of the resulting string.
Among all the strings that give the minimal probability of loss, Sasha choose the lexicographically minimal one. According to this very string, he charges the gun. You have to help Sasha to charge the gun. For that, each xi query must be answered: is there a bullet in the positions xi?
Input
The first line contains three integers n, k and p (1 ≤ n ≤ 1018, 0 ≤ k ≤ n, 1 ≤ p ≤ 1000) — the number of slots in the cylinder, the number of bullets and the number of queries. Then follow p lines; they are the queries. Each line contains one integer xi (1 ≤ xi ≤ n) the number of slot to describe.
Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is preferred to use cin, cout streams or the %I64d specificator.
Output
For each query print "." if the slot should be empty and "X" if the slot should be charged.
Examples
Input
3 1 3
1
2
3
Output
..X
Input
6 3 6
1
2
3
4
5
6
Output
.X.X.X
Input
5 2 5
1
2
3
4
5
Output
...XX
Note
The lexicographical comparison of is performed by the < operator in modern programming languages. The a string is lexicographically less that the b string, if there exists such i (1 ≤ i ≤ n), that ai < bi, and for any j (1 ≤ j < i) aj = bj.
Submitted Solution:
```
n, k, p = map(int, input().split())
for i in range(p):
pos = int(input())
if n % 2:
print('.' if n - pos >= k else 'X', end='')
else:
if k * 2 > n:
print('X' if (pos & 1) == 0 or (n - pos + 1) // 2 + \
n // 2 <= k else '.', end='')
else:
print('X' if (pos & 1) == 0 and (n - pos + 2) // 2 <= k \
else '.', end='')
```
No
| 96,971 |
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)
```
No
| 96,972 |
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()
```
No
| 96,973 |
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')
```
No
| 96,974 |
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)
```
No
| 96,975 |
Provide tags and a correct Python 3 solution for this coding contest problem.
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen:
* Andrew, Dmitry and Michal should eat at least x, y and z grapes, respectively.
* Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only.
* On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes.
* Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.
Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with a green grapes, b purple grapes and c black grapes.
However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?
It is not required to distribute all the grapes, so it's possible that some of them will remain unused.
Input
The first line contains three integers x, y and z (1 ≤ x, y, z ≤ 10^5) — the number of grapes Andrew, Dmitry and Michal want to eat.
The second line contains three integers a, b, c (1 ≤ a, b, c ≤ 10^5) — the number of green, purple and black grapes in the box.
Output
If there is a grape distribution that allows everyone to be happy, print "YES", otherwise print "NO".
Examples
Input
1 6 2
4 3 3
Output
YES
Input
5 1 1
4 3 2
Output
NO
Note
In the first example, there is only one possible distribution:
Andrew should take 1 green grape, Dmitry should take 3 remaining green grapes and 3 purple grapes, and Michal will take 2 out of 3 available black grapes.
In the second test, there is no possible distribution, since Andrew is not be able to eat enough green grapes. :(
Tags: brute force, greedy, implementation
Correct Solution:
```
if __name__ == "__main__":
i1 = input()
i2 = input()
x,y,z = map(int, i1.split())
a,b,c = map(int, i2.split())
if x > a:
print('NO')
else:
a -= x
if a + b < y:
print('NO')
else:
if a + b + c < y + z:
print('NO')
else:
print('YES')
```
| 96,976 |
Provide tags and a correct Python 3 solution for this coding contest problem.
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen:
* Andrew, Dmitry and Michal should eat at least x, y and z grapes, respectively.
* Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only.
* On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes.
* Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.
Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with a green grapes, b purple grapes and c black grapes.
However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?
It is not required to distribute all the grapes, so it's possible that some of them will remain unused.
Input
The first line contains three integers x, y and z (1 ≤ x, y, z ≤ 10^5) — the number of grapes Andrew, Dmitry and Michal want to eat.
The second line contains three integers a, b, c (1 ≤ a, b, c ≤ 10^5) — the number of green, purple and black grapes in the box.
Output
If there is a grape distribution that allows everyone to be happy, print "YES", otherwise print "NO".
Examples
Input
1 6 2
4 3 3
Output
YES
Input
5 1 1
4 3 2
Output
NO
Note
In the first example, there is only one possible distribution:
Andrew should take 1 green grape, Dmitry should take 3 remaining green grapes and 3 purple grapes, and Michal will take 2 out of 3 available black grapes.
In the second test, there is no possible distribution, since Andrew is not be able to eat enough green grapes. :(
Tags: brute force, greedy, implementation
Correct Solution:
```
x,y,z = map(int,input().split())
a,b,c = map(int,input().split())
if((a>=x) and (b+a-x>=y) and (c+(b+(a-x)-y)>=z)):
print("YES")
else:
print("NO")
```
| 96,977 |
Provide tags and a correct Python 3 solution for this coding contest problem.
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen:
* Andrew, Dmitry and Michal should eat at least x, y and z grapes, respectively.
* Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only.
* On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes.
* Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.
Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with a green grapes, b purple grapes and c black grapes.
However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?
It is not required to distribute all the grapes, so it's possible that some of them will remain unused.
Input
The first line contains three integers x, y and z (1 ≤ x, y, z ≤ 10^5) — the number of grapes Andrew, Dmitry and Michal want to eat.
The second line contains three integers a, b, c (1 ≤ a, b, c ≤ 10^5) — the number of green, purple and black grapes in the box.
Output
If there is a grape distribution that allows everyone to be happy, print "YES", otherwise print "NO".
Examples
Input
1 6 2
4 3 3
Output
YES
Input
5 1 1
4 3 2
Output
NO
Note
In the first example, there is only one possible distribution:
Andrew should take 1 green grape, Dmitry should take 3 remaining green grapes and 3 purple grapes, and Michal will take 2 out of 3 available black grapes.
In the second test, there is no possible distribution, since Andrew is not be able to eat enough green grapes. :(
Tags: brute force, greedy, implementation
Correct Solution:
```
a, d, m = map(int, input().split())
g, p, b = map(int, input().split())
n = g+p+b
if g < a or d > g+p-a or n < a+d+m:
print('NO')
else:
print('YES')
```
| 96,978 |
Provide tags and a correct Python 3 solution for this coding contest problem.
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen:
* Andrew, Dmitry and Michal should eat at least x, y and z grapes, respectively.
* Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only.
* On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes.
* Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.
Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with a green grapes, b purple grapes and c black grapes.
However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?
It is not required to distribute all the grapes, so it's possible that some of them will remain unused.
Input
The first line contains three integers x, y and z (1 ≤ x, y, z ≤ 10^5) — the number of grapes Andrew, Dmitry and Michal want to eat.
The second line contains three integers a, b, c (1 ≤ a, b, c ≤ 10^5) — the number of green, purple and black grapes in the box.
Output
If there is a grape distribution that allows everyone to be happy, print "YES", otherwise print "NO".
Examples
Input
1 6 2
4 3 3
Output
YES
Input
5 1 1
4 3 2
Output
NO
Note
In the first example, there is only one possible distribution:
Andrew should take 1 green grape, Dmitry should take 3 remaining green grapes and 3 purple grapes, and Michal will take 2 out of 3 available black grapes.
In the second test, there is no possible distribution, since Andrew is not be able to eat enough green grapes. :(
Tags: brute force, greedy, implementation
Correct Solution:
```
a,b,c=map(int,input().split())
x,y,z=map(int,input().split())
if x>=a and (x-a)+y>=b and x-a+y-b+z>=c:
print("YES")
else:
print("NO")
```
| 96,979 |
Provide tags and a correct Python 3 solution for this coding contest problem.
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen:
* Andrew, Dmitry and Michal should eat at least x, y and z grapes, respectively.
* Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only.
* On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes.
* Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.
Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with a green grapes, b purple grapes and c black grapes.
However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?
It is not required to distribute all the grapes, so it's possible that some of them will remain unused.
Input
The first line contains three integers x, y and z (1 ≤ x, y, z ≤ 10^5) — the number of grapes Andrew, Dmitry and Michal want to eat.
The second line contains three integers a, b, c (1 ≤ a, b, c ≤ 10^5) — the number of green, purple and black grapes in the box.
Output
If there is a grape distribution that allows everyone to be happy, print "YES", otherwise print "NO".
Examples
Input
1 6 2
4 3 3
Output
YES
Input
5 1 1
4 3 2
Output
NO
Note
In the first example, there is only one possible distribution:
Andrew should take 1 green grape, Dmitry should take 3 remaining green grapes and 3 purple grapes, and Michal will take 2 out of 3 available black grapes.
In the second test, there is no possible distribution, since Andrew is not be able to eat enough green grapes. :(
Tags: brute force, greedy, implementation
Correct Solution:
```
x, y, z = list(map(int, input().split()))
a, b, c = list(map(int, input().split()))
if x <= a and y <= (a-x) + b and z <= a + b + c - x -y:
print('YES')
else:
print('NO')
```
| 96,980 |
Provide tags and a correct Python 3 solution for this coding contest problem.
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen:
* Andrew, Dmitry and Michal should eat at least x, y and z grapes, respectively.
* Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only.
* On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes.
* Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.
Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with a green grapes, b purple grapes and c black grapes.
However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?
It is not required to distribute all the grapes, so it's possible that some of them will remain unused.
Input
The first line contains three integers x, y and z (1 ≤ x, y, z ≤ 10^5) — the number of grapes Andrew, Dmitry and Michal want to eat.
The second line contains three integers a, b, c (1 ≤ a, b, c ≤ 10^5) — the number of green, purple and black grapes in the box.
Output
If there is a grape distribution that allows everyone to be happy, print "YES", otherwise print "NO".
Examples
Input
1 6 2
4 3 3
Output
YES
Input
5 1 1
4 3 2
Output
NO
Note
In the first example, there is only one possible distribution:
Andrew should take 1 green grape, Dmitry should take 3 remaining green grapes and 3 purple grapes, and Michal will take 2 out of 3 available black grapes.
In the second test, there is no possible distribution, since Andrew is not be able to eat enough green grapes. :(
Tags: brute force, greedy, implementation
Correct Solution:
```
x,y,z=map(int,input().split())
a,b,c=map(int,input().split())
bl=True
if(x>a):
bl=False
if(x+y)>(a+b):
bl=False
if(x+y+z)>(a+b+c):
bl=False
if(bl):
print("YES")
else:
print("NO")
```
| 96,981 |
Provide tags and a correct Python 3 solution for this coding contest problem.
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen:
* Andrew, Dmitry and Michal should eat at least x, y and z grapes, respectively.
* Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only.
* On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes.
* Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.
Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with a green grapes, b purple grapes and c black grapes.
However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?
It is not required to distribute all the grapes, so it's possible that some of them will remain unused.
Input
The first line contains three integers x, y and z (1 ≤ x, y, z ≤ 10^5) — the number of grapes Andrew, Dmitry and Michal want to eat.
The second line contains three integers a, b, c (1 ≤ a, b, c ≤ 10^5) — the number of green, purple and black grapes in the box.
Output
If there is a grape distribution that allows everyone to be happy, print "YES", otherwise print "NO".
Examples
Input
1 6 2
4 3 3
Output
YES
Input
5 1 1
4 3 2
Output
NO
Note
In the first example, there is only one possible distribution:
Andrew should take 1 green grape, Dmitry should take 3 remaining green grapes and 3 purple grapes, and Michal will take 2 out of 3 available black grapes.
In the second test, there is no possible distribution, since Andrew is not be able to eat enough green grapes. :(
Tags: brute force, greedy, implementation
Correct Solution:
```
import sys
x, y, z = map(int, input().split())
a, b, c = map(int, input().split())
count = a + b + c
if(x > a):
print("NO")
sys.exit()
a -= x
count -= x
if(y > (a + b)):
print("NO")
sys.exit()
count -= y
if(z > count):
print("NO")
sys.exit()
print("YES")
```
| 96,982 |
Provide tags and a correct Python 3 solution for this coding contest problem.
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen:
* Andrew, Dmitry and Michal should eat at least x, y and z grapes, respectively.
* Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only.
* On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes.
* Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.
Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with a green grapes, b purple grapes and c black grapes.
However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?
It is not required to distribute all the grapes, so it's possible that some of them will remain unused.
Input
The first line contains three integers x, y and z (1 ≤ x, y, z ≤ 10^5) — the number of grapes Andrew, Dmitry and Michal want to eat.
The second line contains three integers a, b, c (1 ≤ a, b, c ≤ 10^5) — the number of green, purple and black grapes in the box.
Output
If there is a grape distribution that allows everyone to be happy, print "YES", otherwise print "NO".
Examples
Input
1 6 2
4 3 3
Output
YES
Input
5 1 1
4 3 2
Output
NO
Note
In the first example, there is only one possible distribution:
Andrew should take 1 green grape, Dmitry should take 3 remaining green grapes and 3 purple grapes, and Michal will take 2 out of 3 available black grapes.
In the second test, there is no possible distribution, since Andrew is not be able to eat enough green grapes. :(
Tags: brute force, greedy, implementation
Correct Solution:
```
x, y, z = map(int, input().split())
a, b, c = map(int, input().split())
if x + y + z > a + b + c:
print("NO")
exit()
if x <= a:
a -= x
x = 0
else:
print("NO")
exit()
if z >= c:
z -= c
c = 0
else:
c -= z
z = 0
if z > 0:
if a + b >= z + y:
print("YES")
else:
print("NO")
exit()
else:
if y <= a + b:
print("YES")
else:
print("NO")
```
| 96,983 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen:
* Andrew, Dmitry and Michal should eat at least x, y and z grapes, respectively.
* Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only.
* On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes.
* Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.
Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with a green grapes, b purple grapes and c black grapes.
However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?
It is not required to distribute all the grapes, so it's possible that some of them will remain unused.
Input
The first line contains three integers x, y and z (1 ≤ x, y, z ≤ 10^5) — the number of grapes Andrew, Dmitry and Michal want to eat.
The second line contains three integers a, b, c (1 ≤ a, b, c ≤ 10^5) — the number of green, purple and black grapes in the box.
Output
If there is a grape distribution that allows everyone to be happy, print "YES", otherwise print "NO".
Examples
Input
1 6 2
4 3 3
Output
YES
Input
5 1 1
4 3 2
Output
NO
Note
In the first example, there is only one possible distribution:
Andrew should take 1 green grape, Dmitry should take 3 remaining green grapes and 3 purple grapes, and Michal will take 2 out of 3 available black grapes.
In the second test, there is no possible distribution, since Andrew is not be able to eat enough green grapes. :(
Submitted Solution:
```
names=input().split()
grapes=input().split()
x,y,z=int(names[0]),int(names[1]),int(names[2])
a,b,c=int(grapes[0]),int(grapes[1]),int(grapes[2])
flag=0
total=a+b+c
if(x<=total-(c+b)):
a=a-x
total=a+b+c
flag+=1
if(y<=total-c):
temp=(a+b)-y
total=temp+c
flag+=1
if(z<=total):
flag+=1
if(flag==3):
print("YES")
else:
print("No")
```
Yes
| 96,984 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen:
* Andrew, Dmitry and Michal should eat at least x, y and z grapes, respectively.
* Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only.
* On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes.
* Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.
Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with a green grapes, b purple grapes and c black grapes.
However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?
It is not required to distribute all the grapes, so it's possible that some of them will remain unused.
Input
The first line contains three integers x, y and z (1 ≤ x, y, z ≤ 10^5) — the number of grapes Andrew, Dmitry and Michal want to eat.
The second line contains three integers a, b, c (1 ≤ a, b, c ≤ 10^5) — the number of green, purple and black grapes in the box.
Output
If there is a grape distribution that allows everyone to be happy, print "YES", otherwise print "NO".
Examples
Input
1 6 2
4 3 3
Output
YES
Input
5 1 1
4 3 2
Output
NO
Note
In the first example, there is only one possible distribution:
Andrew should take 1 green grape, Dmitry should take 3 remaining green grapes and 3 purple grapes, and Michal will take 2 out of 3 available black grapes.
In the second test, there is no possible distribution, since Andrew is not be able to eat enough green grapes. :(
Submitted Solution:
```
x , y , z = list(map(int,input().split()))
g , p , b = list(map(int,input().split()))
if g>=x and (g-x)+p>=y and ((g-x)+p)-y+b>=z:
print("YES")
else:
print("NO")
```
Yes
| 96,985 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen:
* Andrew, Dmitry and Michal should eat at least x, y and z grapes, respectively.
* Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only.
* On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes.
* Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.
Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with a green grapes, b purple grapes and c black grapes.
However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?
It is not required to distribute all the grapes, so it's possible that some of them will remain unused.
Input
The first line contains three integers x, y and z (1 ≤ x, y, z ≤ 10^5) — the number of grapes Andrew, Dmitry and Michal want to eat.
The second line contains three integers a, b, c (1 ≤ a, b, c ≤ 10^5) — the number of green, purple and black grapes in the box.
Output
If there is a grape distribution that allows everyone to be happy, print "YES", otherwise print "NO".
Examples
Input
1 6 2
4 3 3
Output
YES
Input
5 1 1
4 3 2
Output
NO
Note
In the first example, there is only one possible distribution:
Andrew should take 1 green grape, Dmitry should take 3 remaining green grapes and 3 purple grapes, and Michal will take 2 out of 3 available black grapes.
In the second test, there is no possible distribution, since Andrew is not be able to eat enough green grapes. :(
Submitted Solution:
```
x,y,z = map(int,input().split(" "))
a,b,c = map(int,input().split(" "))
total_grapes = a + b + c
if a < x:
print("NO")
else:
total_grapes -= x
a -= x
if (a + b) < y:
print("NO")
else:
total_grapes -= y
if total_grapes < z:
print("NO")
else:
print("YES")
```
Yes
| 96,986 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen:
* Andrew, Dmitry and Michal should eat at least x, y and z grapes, respectively.
* Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only.
* On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes.
* Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.
Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with a green grapes, b purple grapes and c black grapes.
However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?
It is not required to distribute all the grapes, so it's possible that some of them will remain unused.
Input
The first line contains three integers x, y and z (1 ≤ x, y, z ≤ 10^5) — the number of grapes Andrew, Dmitry and Michal want to eat.
The second line contains three integers a, b, c (1 ≤ a, b, c ≤ 10^5) — the number of green, purple and black grapes in the box.
Output
If there is a grape distribution that allows everyone to be happy, print "YES", otherwise print "NO".
Examples
Input
1 6 2
4 3 3
Output
YES
Input
5 1 1
4 3 2
Output
NO
Note
In the first example, there is only one possible distribution:
Andrew should take 1 green grape, Dmitry should take 3 remaining green grapes and 3 purple grapes, and Michal will take 2 out of 3 available black grapes.
In the second test, there is no possible distribution, since Andrew is not be able to eat enough green grapes. :(
Submitted Solution:
```
# Got any Grapes
def grapes(num, types):
if num[0] > types[0]:
return "NO"
else:
types[0] -= num[0]
if num[1] > (types[0] + types[1]):
return "NO"
else:
if num[1] - types[0] <= 0:
types[0] -= num[1]
else:
num[1] -= types[0]
types[0] = 0
types[1] -= num[1]
if num[2] > sum(types):
return "NO"
return "YES"
num = list(map(int, input().rstrip().split()))
types = list(map(int, input().rstrip().split()))
print(grapes(num, types))
```
Yes
| 96,987 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen:
* Andrew, Dmitry and Michal should eat at least x, y and z grapes, respectively.
* Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only.
* On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes.
* Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.
Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with a green grapes, b purple grapes and c black grapes.
However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?
It is not required to distribute all the grapes, so it's possible that some of them will remain unused.
Input
The first line contains three integers x, y and z (1 ≤ x, y, z ≤ 10^5) — the number of grapes Andrew, Dmitry and Michal want to eat.
The second line contains three integers a, b, c (1 ≤ a, b, c ≤ 10^5) — the number of green, purple and black grapes in the box.
Output
If there is a grape distribution that allows everyone to be happy, print "YES", otherwise print "NO".
Examples
Input
1 6 2
4 3 3
Output
YES
Input
5 1 1
4 3 2
Output
NO
Note
In the first example, there is only one possible distribution:
Andrew should take 1 green grape, Dmitry should take 3 remaining green grapes and 3 purple grapes, and Michal will take 2 out of 3 available black grapes.
In the second test, there is no possible distribution, since Andrew is not be able to eat enough green grapes. :(
Submitted Solution:
```
x,y,z=map(int,input().split())
a,b,c=map(int,input().split())
if a<x:
print("NO")
else:
a-=x;
if y>(a+c):
print("NO")
else:
if z>(a+c+b-y):
print("NO")
else:
print("YES")
```
No
| 96,988 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen:
* Andrew, Dmitry and Michal should eat at least x, y and z grapes, respectively.
* Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only.
* On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes.
* Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.
Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with a green grapes, b purple grapes and c black grapes.
However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?
It is not required to distribute all the grapes, so it's possible that some of them will remain unused.
Input
The first line contains three integers x, y and z (1 ≤ x, y, z ≤ 10^5) — the number of grapes Andrew, Dmitry and Michal want to eat.
The second line contains three integers a, b, c (1 ≤ a, b, c ≤ 10^5) — the number of green, purple and black grapes in the box.
Output
If there is a grape distribution that allows everyone to be happy, print "YES", otherwise print "NO".
Examples
Input
1 6 2
4 3 3
Output
YES
Input
5 1 1
4 3 2
Output
NO
Note
In the first example, there is only one possible distribution:
Andrew should take 1 green grape, Dmitry should take 3 remaining green grapes and 3 purple grapes, and Michal will take 2 out of 3 available black grapes.
In the second test, there is no possible distribution, since Andrew is not be able to eat enough green grapes. :(
Submitted Solution:
```
a,d,m=map(int,input().split())
x,y,z=map(int,input().split())
count=0
y=x+y
if x>=a:
x-=a;count+=1
if y>=d:
y-=d;count+=1
if y+z>=m:
count+=1
if count==3:
print('YES')
else:
print('NO')
```
No
| 96,989 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen:
* Andrew, Dmitry and Michal should eat at least x, y and z grapes, respectively.
* Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only.
* On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes.
* Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.
Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with a green grapes, b purple grapes and c black grapes.
However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?
It is not required to distribute all the grapes, so it's possible that some of them will remain unused.
Input
The first line contains three integers x, y and z (1 ≤ x, y, z ≤ 10^5) — the number of grapes Andrew, Dmitry and Michal want to eat.
The second line contains three integers a, b, c (1 ≤ a, b, c ≤ 10^5) — the number of green, purple and black grapes in the box.
Output
If there is a grape distribution that allows everyone to be happy, print "YES", otherwise print "NO".
Examples
Input
1 6 2
4 3 3
Output
YES
Input
5 1 1
4 3 2
Output
NO
Note
In the first example, there is only one possible distribution:
Andrew should take 1 green grape, Dmitry should take 3 remaining green grapes and 3 purple grapes, and Michal will take 2 out of 3 available black grapes.
In the second test, there is no possible distribution, since Andrew is not be able to eat enough green grapes. :(
Submitted Solution:
```
x,y,z = [int(i) for i in input().split()]
a,b,c = [int(i) for i in input().split()]
andrew = a-x
dmitry = (a-x+b) - y
michal = a+b+c - andrew - dmitry
if andrew >= 0 and dmitry >= 0 and michal >= 0:
print('YES')
else:
print('NO')
```
No
| 96,990 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the following should happen:
* Andrew, Dmitry and Michal should eat at least x, y and z grapes, respectively.
* Andrew has an extreme affinity for green grapes, thus he will eat green grapes and green grapes only.
* On the other hand, Dmitry is not a fan of black grapes — any types of grapes except black would do for him. In other words, Dmitry can eat green and purple grapes.
* Michal has a common taste — he enjoys grapes in general and will be pleased with any types of grapes, as long as the quantity is sufficient.
Knowing that his friends are so fond of grapes, Aki decided to host a grape party with them. He has prepared a box with a green grapes, b purple grapes and c black grapes.
However, Aki isn't sure if the box he prepared contains enough grapes to make everyone happy. Can you please find out whether it's possible to distribute grapes so that everyone is happy or Aki has to buy some more grapes?
It is not required to distribute all the grapes, so it's possible that some of them will remain unused.
Input
The first line contains three integers x, y and z (1 ≤ x, y, z ≤ 10^5) — the number of grapes Andrew, Dmitry and Michal want to eat.
The second line contains three integers a, b, c (1 ≤ a, b, c ≤ 10^5) — the number of green, purple and black grapes in the box.
Output
If there is a grape distribution that allows everyone to be happy, print "YES", otherwise print "NO".
Examples
Input
1 6 2
4 3 3
Output
YES
Input
5 1 1
4 3 2
Output
NO
Note
In the first example, there is only one possible distribution:
Andrew should take 1 green grape, Dmitry should take 3 remaining green grapes and 3 purple grapes, and Michal will take 2 out of 3 available black grapes.
In the second test, there is no possible distribution, since Andrew is not be able to eat enough green grapes. :(
Submitted Solution:
```
p,q,r=input("").split(" ")
p=int(p)
q=int(q)
r=int(r)
a,b,c=input("").split(" ")
a=int(a)
b=int(b)
c=int(c)
count=0
if p<=a:
count+=1
a-=p
if q<=a+b:
count+=1
d=q-(a+b)
if r<=d+c:
count+=1
if count==3:
print("YES")
else:
print("NO")
```
No
| 96,991 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n.
Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries.
A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it.
A cyclic shift of a permutation (p_1, p_2, …, p_n) is a permutation (p_i, p_{i + 1}, …, p_{n}, p_1, p_2, …, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1).
A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, …, a_{i_k} for some i_1, i_2, …, i_k such that l ≤ i_1 < i_2 < … < i_k ≤ r.
Input
The first line contains three integers n, m, q (1 ≤ n, m, q ≤ 2 ⋅ 10^5) — the length of the permutation p, the length of the array a and the number of queries.
The next line contains n integers from 1 to n, where the i-th of them is the i-th element of the permutation. Each integer from 1 to n appears exactly once.
The next line contains m integers from 1 to n, the i-th of them is the i-th element of the array a.
The next q lines describe queries. The i-th of these lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m), meaning that the i-th query is about the subsegment of the array from the l_i-th to the r_i-th positions, inclusive.
Output
Print a single string of length q, consisting of 0 and 1, the digit on the i-th positions should be 1, if the subsegment of array a from the l_i-th to the r_i-th positions, inclusive, contains a subsequence that is a cyclic shift of p, and 0 otherwise.
Examples
Input
3 6 3
2 1 3
1 2 3 1 2 3
1 5
2 6
3 5
Output
110
Input
2 4 3
2 1
1 1 2 2
1 2
2 3
3 4
Output
010
Note
In the first example the segment from the 1-st to the 5-th positions is 1, 2, 3, 1, 2. There is a subsequence 1, 3, 2 that is a cyclic shift of the permutation. The subsegment from the 2-nd to the 6-th positions also contains a subsequence 2, 1, 3 that is equal to the permutation. The subsegment from the 3-rd to the 5-th positions is 3, 1, 2, there is only one subsequence of length 3 (3, 1, 2), but it is not a cyclic shift of the permutation.
In the second example the possible cyclic shifts are 1, 2 and 2, 1. The subsegment from the 1-st to the 2-nd positions is 1, 1, its subsequences are not cyclic shifts of the permutation. The subsegment from the 2-nd to the 3-rd positions is 1, 2, it coincides with the permutation. The subsegment from the 3 to the 4 positions is 2, 2, its subsequences are not cyclic shifts of the permutation.
Tags: data structures, dfs and similar, dp, math, trees
Correct Solution:
```
# 注意array cache順序 QQ
from math import log, floor
"""
class RMQ:
'''
maximum version rmq
query: max([l, r])
'''
def __init__(self, nums):
size = floor(log(len(nums)) // log(2)) + 1
self.nums = [nums]
for i in range(1, size):
last = self.nums[-1]
delta = 1 << (i-1)
self.nums.append([max(last[j], last[j + delta])
for j in range(len(nums) - 2 * delta + 1)])
def query(self, l, r):
delta = floor(log(r - l + 1) // log(2))
return max(self.nums[delta][l], self.nums[delta][r-2**delta+1])
"""
n, m, q = map(int, input().split())
perms = list(map(int, input().split()))
nums = list(map(int, input().split()))
logit = floor(log(n) // log(2)) + 1
current_max_index = [-1]*(n+1)
prevs = [[-1]*m for i in range(logit)]
prev_map = [-2]*(n+1)
for i, j in zip(perms[1:]+[perms[0]], perms):
prev_map[i] = j
# Update the one step case
for idx, ele in enumerate(nums):
prevs[0][idx] = current_max_index[prev_map[ele]]
current_max_index[ele] = idx
# Update the n_step table
for i in range(1, logit):
for idx, ele in enumerate(nums):
if prevs[i-1][idx] != -1:
prevs[i][idx] = prevs[i-1][prevs[i-1][idx]]
prev_n = []
# Create the update sequence
use = [i for i in range(n.bit_length()) if 1 & (n - 1) >> i]
max_pre = -1
ran = [-1] * (m+2)
for i in range(m):
t = i
for dim in use:
t = prevs[dim][t]
if t == -1:
break
max_pre = max(t, max_pre)
ran[i] = max_pre
"""
for i in range(m):
remain = n - 1
idx = i
while remain and idx != -1:
ma = floor(log(remain) // log(2))
idx = prevs[ma][idx]
remain -= 2**ma
prev_n.append(idx)
"""
#rmq = RMQ(prev_n)
ans = [None]*q
for i in range(q):
l, r = map(int, input().split())
ans[i] = str(int(l - 1 <= ran[r-1]))
print("".join(ans))
```
| 96,992 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n.
Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries.
A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it.
A cyclic shift of a permutation (p_1, p_2, …, p_n) is a permutation (p_i, p_{i + 1}, …, p_{n}, p_1, p_2, …, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1).
A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, …, a_{i_k} for some i_1, i_2, …, i_k such that l ≤ i_1 < i_2 < … < i_k ≤ r.
Input
The first line contains three integers n, m, q (1 ≤ n, m, q ≤ 2 ⋅ 10^5) — the length of the permutation p, the length of the array a and the number of queries.
The next line contains n integers from 1 to n, where the i-th of them is the i-th element of the permutation. Each integer from 1 to n appears exactly once.
The next line contains m integers from 1 to n, the i-th of them is the i-th element of the array a.
The next q lines describe queries. The i-th of these lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m), meaning that the i-th query is about the subsegment of the array from the l_i-th to the r_i-th positions, inclusive.
Output
Print a single string of length q, consisting of 0 and 1, the digit on the i-th positions should be 1, if the subsegment of array a from the l_i-th to the r_i-th positions, inclusive, contains a subsequence that is a cyclic shift of p, and 0 otherwise.
Examples
Input
3 6 3
2 1 3
1 2 3 1 2 3
1 5
2 6
3 5
Output
110
Input
2 4 3
2 1
1 1 2 2
1 2
2 3
3 4
Output
010
Note
In the first example the segment from the 1-st to the 5-th positions is 1, 2, 3, 1, 2. There is a subsequence 1, 3, 2 that is a cyclic shift of the permutation. The subsegment from the 2-nd to the 6-th positions also contains a subsequence 2, 1, 3 that is equal to the permutation. The subsegment from the 3-rd to the 5-th positions is 3, 1, 2, there is only one subsequence of length 3 (3, 1, 2), but it is not a cyclic shift of the permutation.
In the second example the possible cyclic shifts are 1, 2 and 2, 1. The subsegment from the 1-st to the 2-nd positions is 1, 1, its subsequences are not cyclic shifts of the permutation. The subsegment from the 2-nd to the 3-rd positions is 1, 2, it coincides with the permutation. The subsegment from the 3 to the 4 positions is 2, 2, its subsequences are not cyclic shifts of the permutation.
Tags: data structures, dfs and similar, dp, math, trees
Correct Solution:
```
import os
from io import BytesIO, StringIO
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
def input_as_list():
return list(map(int, input().split()))
def array_of(f, *dim):
return [array_of(f, *dim[1:]) for _ in range(dim[0])] if dim else f()
def main():
n, m, q = input_as_list()
p = input_as_list()
a = input_as_list()
if n == 1:
print('1' * q)
return
next_p = array_of(int, n)
next_a = array_of(int, m)
prev = p[-1] - 1
for pi in p:
pi -= 1
next_p[prev] = pi
prev = pi
idx_a = array_of(int, n)
for i in range(len(a) - 1, -1, -1):
ai = a[i] - 1
next_a[i] = idx_a[next_p[ai]]
idx_a[ai] = i
ep = array_of(int, m)
parent = next_a
children = array_of(list, m)
roots = []
for i, p in enumerate(parent):
if p == 0:
roots.append(i)
else:
children[p].append(i)
rank = array_of(int, m)
parent_ex = array_of(list, m)
for r in roots:
stack = [r]
while stack:
p = stack.pop()
for c in children[p]:
rank[c] = rank[p] + 1
parent_ex[c].append(p)
i = 1
while 2 ** i <= rank[c]:
parent_ex[c].append(parent_ex[parent_ex[c][-1]][i - 1])
i += 1
stack.append(c)
for i in range(m):
y = i
s = 0
try:
for j in reversed(range(20)):
if n - s - 1 >= 2**j:
y = parent_ex[y][j]
s += 2**j
ep[i] = y
except IndexError:
pass
mn = 200000
flag = False
for i in range(len(ep) - 1, -1, -1):
epi = ep[i]
if epi != 0:
if epi > mn:
ep[i] = mn
mn = min(mn, epi)
flag = True
else:
if flag:
ep[i] = mn
out = []
for _ in range(q):
l, r = map(int, input().split())
l, r = l - 1, r - 1
if ep[l] == 0 or ep[l] > r:
out.append('0')
else:
out.append('1')
print(''.join(out))
main()
```
| 96,993 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n.
Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries.
A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it.
A cyclic shift of a permutation (p_1, p_2, …, p_n) is a permutation (p_i, p_{i + 1}, …, p_{n}, p_1, p_2, …, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1).
A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, …, a_{i_k} for some i_1, i_2, …, i_k such that l ≤ i_1 < i_2 < … < i_k ≤ r.
Input
The first line contains three integers n, m, q (1 ≤ n, m, q ≤ 2 ⋅ 10^5) — the length of the permutation p, the length of the array a and the number of queries.
The next line contains n integers from 1 to n, where the i-th of them is the i-th element of the permutation. Each integer from 1 to n appears exactly once.
The next line contains m integers from 1 to n, the i-th of them is the i-th element of the array a.
The next q lines describe queries. The i-th of these lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m), meaning that the i-th query is about the subsegment of the array from the l_i-th to the r_i-th positions, inclusive.
Output
Print a single string of length q, consisting of 0 and 1, the digit on the i-th positions should be 1, if the subsegment of array a from the l_i-th to the r_i-th positions, inclusive, contains a subsequence that is a cyclic shift of p, and 0 otherwise.
Examples
Input
3 6 3
2 1 3
1 2 3 1 2 3
1 5
2 6
3 5
Output
110
Input
2 4 3
2 1
1 1 2 2
1 2
2 3
3 4
Output
010
Note
In the first example the segment from the 1-st to the 5-th positions is 1, 2, 3, 1, 2. There is a subsequence 1, 3, 2 that is a cyclic shift of the permutation. The subsegment from the 2-nd to the 6-th positions also contains a subsequence 2, 1, 3 that is equal to the permutation. The subsegment from the 3-rd to the 5-th positions is 3, 1, 2, there is only one subsequence of length 3 (3, 1, 2), but it is not a cyclic shift of the permutation.
In the second example the possible cyclic shifts are 1, 2 and 2, 1. The subsegment from the 1-st to the 2-nd positions is 1, 1, its subsequences are not cyclic shifts of the permutation. The subsegment from the 2-nd to the 3-rd positions is 1, 2, it coincides with the permutation. The subsegment from the 3 to the 4 positions is 2, 2, its subsequences are not cyclic shifts of the permutation.
Tags: data structures, dfs and similar, dp, math, trees
Correct Solution:
```
# 注意array cache順序 QQ
from math import log, floor
class RMQ:
'''
maximum version rmq
query: max([l, r])
'''
def __init__(self, nums):
size = floor(log(len(nums)) // log(2)) + 1
self.nums = [nums]
for i in range(1, size):
last = self.nums[-1]
delta = 1 << (i-1)
self.nums.append([max(last[j], last[j + delta])
for j in range(len(nums) - 2 * delta + 1)])
def query(self, l, r):
delta = floor(log(r - l + 1) // log(2))
return max(self.nums[delta][l], self.nums[delta][r-2**delta+1])
n, m, q = map(int, input().split())
perms = list(map(int, input().split()))
nums = list(map(int, input().split()))
logit = floor(log(n) // log(2)) + 1
current_max_index = [-1]*(n+1)
prevs = [[-1]*m for i in range(logit)]
prev_map = [-2]*(n+1)
for i, j in zip(perms[1:]+[perms[0]], perms):
prev_map[i] = j
# Update the one step case
for idx, ele in enumerate(nums):
prevs[0][idx] = current_max_index[prev_map[ele]]
current_max_index[ele] = idx
# Update the n_step table
for i in range(1, logit):
for idx, ele in enumerate(nums):
if prevs[i-1][idx] != -1:
prevs[i][idx] = prevs[i-1][prevs[i-1][idx]]
prev_n = []
# Create the update sequence
use = [i for i in range(n.bit_length()) if 1 & (n - 1) >> i]
max_pre = -1
ran = [-1] * (m+2)
for i in range(m):
t = i
for dim in use:
t = prevs[dim][t]
if t == -1:
break
max_pre = max(t, max_pre)
ran[i] = max_pre
"""
for i in range(m):
remain = n - 1
idx = i
while remain and idx != -1:
ma = floor(log(remain) // log(2))
idx = prevs[ma][idx]
remain -= 2**ma
prev_n.append(idx)
"""
#rmq = RMQ(prev_n)
ans = []
for i in range(q):
l, r = map(int, input().split())
if ran[r-1] >= l - 1:
ans.append("1")
else:
ans.append("0")
print("".join(ans))
```
| 96,994 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n.
Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries.
A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it.
A cyclic shift of a permutation (p_1, p_2, …, p_n) is a permutation (p_i, p_{i + 1}, …, p_{n}, p_1, p_2, …, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1).
A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, …, a_{i_k} for some i_1, i_2, …, i_k such that l ≤ i_1 < i_2 < … < i_k ≤ r.
Input
The first line contains three integers n, m, q (1 ≤ n, m, q ≤ 2 ⋅ 10^5) — the length of the permutation p, the length of the array a and the number of queries.
The next line contains n integers from 1 to n, where the i-th of them is the i-th element of the permutation. Each integer from 1 to n appears exactly once.
The next line contains m integers from 1 to n, the i-th of them is the i-th element of the array a.
The next q lines describe queries. The i-th of these lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m), meaning that the i-th query is about the subsegment of the array from the l_i-th to the r_i-th positions, inclusive.
Output
Print a single string of length q, consisting of 0 and 1, the digit on the i-th positions should be 1, if the subsegment of array a from the l_i-th to the r_i-th positions, inclusive, contains a subsequence that is a cyclic shift of p, and 0 otherwise.
Examples
Input
3 6 3
2 1 3
1 2 3 1 2 3
1 5
2 6
3 5
Output
110
Input
2 4 3
2 1
1 1 2 2
1 2
2 3
3 4
Output
010
Note
In the first example the segment from the 1-st to the 5-th positions is 1, 2, 3, 1, 2. There is a subsequence 1, 3, 2 that is a cyclic shift of the permutation. The subsegment from the 2-nd to the 6-th positions also contains a subsequence 2, 1, 3 that is equal to the permutation. The subsegment from the 3-rd to the 5-th positions is 3, 1, 2, there is only one subsequence of length 3 (3, 1, 2), but it is not a cyclic shift of the permutation.
In the second example the possible cyclic shifts are 1, 2 and 2, 1. The subsegment from the 1-st to the 2-nd positions is 1, 1, its subsequences are not cyclic shifts of the permutation. The subsegment from the 2-nd to the 3-rd positions is 1, 2, it coincides with the permutation. The subsegment from the 3 to the 4 positions is 2, 2, its subsequences are not cyclic shifts of the permutation.
Tags: data structures, dfs and similar, dp, math, trees
Correct Solution:
```
import sys
class segmentTree:
def __init__(self, n):
self.n = n
self.seg = [self.n + 1] * (self.n << 1)
def update(self, p, value):
p += self.n
self.seg[p] = value
while p > 1:
p >>= 1
self.seg[p] = min(self.seg[p * 2], self.seg[p * 2 + 1])
def query(self, l, r):
res = self.n
l += self.n
r += self.n
while l < r:
if l & 1:
res = min(res, self.seg[l])
l += 1
if r & 1:
res = min(res, self.seg[r - 1])
r -= 1
l >>= 1
r >>= 1
return res
inp = [int(x) for x in sys.stdin.read().split()]
n, m, q = inp[0], inp[1], inp[2]
p = [inp[idx] for idx in range(3, n + 3)]
index_arr = [0] * (n + 1)
for i in range(n): index_arr[p[i]] = i
a = [inp[idx] for idx in range(n + 3, n + 3 + m)]
leftmost_pos = [m] * (n + 1)
next = [-1] * m
for i in range(m - 1, -1, -1):
index = index_arr[a[i]]
right_index = 0 if index == n - 1 else index + 1
right = p[right_index]
next[i] = leftmost_pos[right]
leftmost_pos[a[i]] = i
log = 0
while (1 << log) <= n: log += 1
log += 1
dp = [[m for _ in range(m + 1)] for _ in range(log)]
for i in range(m):
dp[0][i] = next[i]
for j in range(1, log):
for i in range(m):
dp[j][i] = dp[j - 1][dp[j - 1][i]]
tree = segmentTree(m)
for i in range(m):
p = i
len = n - 1
for j in range(log - 1, -1, -1):
if (1 << j) <= len:
p = dp[j][p]
len -= (1 << j)
tree.update(i, p)
inp_idx = n + m + 3
ans = []
for i in range(q):
l, r = inp[inp_idx] - 1, inp[inp_idx + 1] - 1
inp_idx += 2
if tree.query(l, r + 1) <= r:
ans.append('1')
else:
ans.append('0')
print(''.join(ans))
```
| 96,995 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n.
Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries.
A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it.
A cyclic shift of a permutation (p_1, p_2, …, p_n) is a permutation (p_i, p_{i + 1}, …, p_{n}, p_1, p_2, …, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1).
A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, …, a_{i_k} for some i_1, i_2, …, i_k such that l ≤ i_1 < i_2 < … < i_k ≤ r.
Input
The first line contains three integers n, m, q (1 ≤ n, m, q ≤ 2 ⋅ 10^5) — the length of the permutation p, the length of the array a and the number of queries.
The next line contains n integers from 1 to n, where the i-th of them is the i-th element of the permutation. Each integer from 1 to n appears exactly once.
The next line contains m integers from 1 to n, the i-th of them is the i-th element of the array a.
The next q lines describe queries. The i-th of these lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m), meaning that the i-th query is about the subsegment of the array from the l_i-th to the r_i-th positions, inclusive.
Output
Print a single string of length q, consisting of 0 and 1, the digit on the i-th positions should be 1, if the subsegment of array a from the l_i-th to the r_i-th positions, inclusive, contains a subsequence that is a cyclic shift of p, and 0 otherwise.
Examples
Input
3 6 3
2 1 3
1 2 3 1 2 3
1 5
2 6
3 5
Output
110
Input
2 4 3
2 1
1 1 2 2
1 2
2 3
3 4
Output
010
Note
In the first example the segment from the 1-st to the 5-th positions is 1, 2, 3, 1, 2. There is a subsequence 1, 3, 2 that is a cyclic shift of the permutation. The subsegment from the 2-nd to the 6-th positions also contains a subsequence 2, 1, 3 that is equal to the permutation. The subsegment from the 3-rd to the 5-th positions is 3, 1, 2, there is only one subsequence of length 3 (3, 1, 2), but it is not a cyclic shift of the permutation.
In the second example the possible cyclic shifts are 1, 2 and 2, 1. The subsegment from the 1-st to the 2-nd positions is 1, 1, its subsequences are not cyclic shifts of the permutation. The subsegment from the 2-nd to the 3-rd positions is 1, 2, it coincides with the permutation. The subsegment from the 3 to the 4 positions is 2, 2, its subsequences are not cyclic shifts of the permutation.
Tags: data structures, dfs and similar, dp, math, trees
Correct Solution:
```
import sys
N, M, Q = map(int, sys.stdin.readline().split())
P = list(map(int, sys.stdin.readline().split()))
A = list(map(int, sys.stdin.readline().split()))
k = N.bit_length()
bef = [-2]*(N+1)
for p, q in zip(P[1:]+[P[0]], P):
bef[p] = q
recentapp = [-1] * (N+1)
prepoints = [[-1]*(M+2) for _ in range(k)]
for i, a in enumerate(A, 1):
prepoints[0][i] = recentapp[bef[a]]
recentapp[a] = i
for dim in range(1, k):
for i in range(1, M+1):
prepoints[dim][i] = prepoints[dim-1][prepoints[dim-1][i]]
use = [i for i in range(k) if 1 & (N - 1) >> i]
ran = [-1] * (M+2)
maxpre = -1
for i in range(1, M+1):
t = i
for dim in use:
t = prepoints[dim][t]
maxpre = max(maxpre, t)
ran[i] = maxpre
Ans = [None]*Q
for q in range(Q):
l, r = map(int, sys.stdin.readline().split())
Ans[q] = str(int(l <= ran[r]))
print(''.join(Ans))
```
| 96,996 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n.
Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries.
A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it.
A cyclic shift of a permutation (p_1, p_2, …, p_n) is a permutation (p_i, p_{i + 1}, …, p_{n}, p_1, p_2, …, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1).
A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, …, a_{i_k} for some i_1, i_2, …, i_k such that l ≤ i_1 < i_2 < … < i_k ≤ r.
Input
The first line contains three integers n, m, q (1 ≤ n, m, q ≤ 2 ⋅ 10^5) — the length of the permutation p, the length of the array a and the number of queries.
The next line contains n integers from 1 to n, where the i-th of them is the i-th element of the permutation. Each integer from 1 to n appears exactly once.
The next line contains m integers from 1 to n, the i-th of them is the i-th element of the array a.
The next q lines describe queries. The i-th of these lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m), meaning that the i-th query is about the subsegment of the array from the l_i-th to the r_i-th positions, inclusive.
Output
Print a single string of length q, consisting of 0 and 1, the digit on the i-th positions should be 1, if the subsegment of array a from the l_i-th to the r_i-th positions, inclusive, contains a subsequence that is a cyclic shift of p, and 0 otherwise.
Examples
Input
3 6 3
2 1 3
1 2 3 1 2 3
1 5
2 6
3 5
Output
110
Input
2 4 3
2 1
1 1 2 2
1 2
2 3
3 4
Output
010
Note
In the first example the segment from the 1-st to the 5-th positions is 1, 2, 3, 1, 2. There is a subsequence 1, 3, 2 that is a cyclic shift of the permutation. The subsegment from the 2-nd to the 6-th positions also contains a subsequence 2, 1, 3 that is equal to the permutation. The subsegment from the 3-rd to the 5-th positions is 3, 1, 2, there is only one subsequence of length 3 (3, 1, 2), but it is not a cyclic shift of the permutation.
In the second example the possible cyclic shifts are 1, 2 and 2, 1. The subsegment from the 1-st to the 2-nd positions is 1, 1, its subsequences are not cyclic shifts of the permutation. The subsegment from the 2-nd to the 3-rd positions is 1, 2, it coincides with the permutation. The subsegment from the 3 to the 4 positions is 2, 2, its subsequences are not cyclic shifts of the permutation.
Tags: data structures, dfs and similar, dp, math, trees
Correct Solution:
```
# 注意array cache順序 QQ
from math import log, floor
import sys
"""
class RMQ:
'''
maximum version rmq
query: max([l, r])
'''
def __init__(self, nums):
size = floor(log(len(nums)) // log(2)) + 1
self.nums = [nums]
for i in range(1, size):
last = self.nums[-1]
delta = 1 << (i-1)
self.nums.append([max(last[j], last[j + delta])
for j in range(len(nums) - 2 * delta + 1)])
def query(self, l, r):
delta = floor(log(r - l + 1) // log(2))
return max(self.nums[delta][l], self.nums[delta][r-2**delta+1])
"""
n, m, q = map(int, sys.stdin.readline().split())
perms = list(map(int, sys.stdin.readline().split()))
nums = list(map(int, sys.stdin.readline().split()))
logit = floor(log(n) // log(2)) + 1
current_max_index = [-1]*(n+1)
prevs = [[-1]*m for i in range(logit)]
prev_map = [-2]*(n+1)
for i, j in zip(perms[1:]+[perms[0]], perms):
prev_map[i] = j
# Update the one step case
for idx, ele in enumerate(nums):
prevs[0][idx] = current_max_index[prev_map[ele]]
current_max_index[ele] = idx
# Update the n_step table
for i in range(1, logit):
for idx, ele in enumerate(nums):
if prevs[i-1][idx] != -1:
prevs[i][idx] = prevs[i-1][prevs[i-1][idx]]
prev_n = []
# Create the update sequence
use = [i for i in range(n.bit_length()) if 1 & (n - 1) >> i]
max_pre = -1
ran = [-1] * (m+2)
for i in range(m):
t = i
for dim in use:
t = prevs[dim][t]
if t == -1:
break
max_pre = max(t, max_pre)
ran[i] = max_pre
"""
for i in range(m):
remain = n - 1
idx = i
while remain and idx != -1:
ma = floor(log(remain) // log(2))
idx = prevs[ma][idx]
remain -= 2**ma
prev_n.append(idx)
"""
#rmq = RMQ(prev_n)
ans = [None]*q
for i in range(q):
l, r = map(int, sys.stdin.readline().split())
ans[i] = str(int(l - 1 <= ran[r-1]))
print("".join(ans))
```
| 96,997 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n.
Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries.
A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it.
A cyclic shift of a permutation (p_1, p_2, …, p_n) is a permutation (p_i, p_{i + 1}, …, p_{n}, p_1, p_2, …, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1).
A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, …, a_{i_k} for some i_1, i_2, …, i_k such that l ≤ i_1 < i_2 < … < i_k ≤ r.
Input
The first line contains three integers n, m, q (1 ≤ n, m, q ≤ 2 ⋅ 10^5) — the length of the permutation p, the length of the array a and the number of queries.
The next line contains n integers from 1 to n, where the i-th of them is the i-th element of the permutation. Each integer from 1 to n appears exactly once.
The next line contains m integers from 1 to n, the i-th of them is the i-th element of the array a.
The next q lines describe queries. The i-th of these lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m), meaning that the i-th query is about the subsegment of the array from the l_i-th to the r_i-th positions, inclusive.
Output
Print a single string of length q, consisting of 0 and 1, the digit on the i-th positions should be 1, if the subsegment of array a from the l_i-th to the r_i-th positions, inclusive, contains a subsequence that is a cyclic shift of p, and 0 otherwise.
Examples
Input
3 6 3
2 1 3
1 2 3 1 2 3
1 5
2 6
3 5
Output
110
Input
2 4 3
2 1
1 1 2 2
1 2
2 3
3 4
Output
010
Note
In the first example the segment from the 1-st to the 5-th positions is 1, 2, 3, 1, 2. There is a subsequence 1, 3, 2 that is a cyclic shift of the permutation. The subsegment from the 2-nd to the 6-th positions also contains a subsequence 2, 1, 3 that is equal to the permutation. The subsegment from the 3-rd to the 5-th positions is 3, 1, 2, there is only one subsequence of length 3 (3, 1, 2), but it is not a cyclic shift of the permutation.
In the second example the possible cyclic shifts are 1, 2 and 2, 1. The subsegment from the 1-st to the 2-nd positions is 1, 1, its subsequences are not cyclic shifts of the permutation. The subsegment from the 2-nd to the 3-rd positions is 1, 2, it coincides with the permutation. The subsegment from the 3 to the 4 positions is 2, 2, its subsequences are not cyclic shifts of the permutation.
Tags: data structures, dfs and similar, dp, math, trees
Correct Solution:
```
from math import log, floor
import sys
class RMQ:
'''
maximum version rmq
query: max([l, r])
'''
def __init__(self, nums):
size = floor(log(len(nums)) // log(2)) + 1
self.nums = [nums]
for i in range(1, size):
last = self.nums[-1]
delta = 1 << (i-1)
self.nums.append([max(last[j], last[j + delta])
for j in range(len(nums) - 2 * delta + 1)])
def query(self, l, r):
delta = floor(log(r - l + 1) // log(2))
return max(self.nums[delta][l], self.nums[delta][r-2**delta+1])
n, m, q = list(map(int, sys.stdin.readline().split()))
perms = list(map(int, sys.stdin.readline().split()))
nums = list(map(int, sys.stdin.readline().split()))
logit = floor(log(n) // log(2)) + 1
current_max_index = [-1]*(n+1)
prevs = [[-1]*m for i in range(logit)]
prev_map = {perms[i]:perms[i-1] for i in range(n)}
# Update the one step case
for idx, ele in enumerate(nums):
prevs[0][idx] = current_max_index[prev_map[ele]]
current_max_index[ele] = idx
# Update the n_step table
for i in range(1, logit):
for idx, ele in enumerate(nums):
if prevs[i-1][idx] != -1:
prevs[i][idx] = prevs[i-1][prevs[i-1][idx]]
prev_n = []
for i in range(m):
remain = n - 1
idx = i
while remain and idx != -1:
ma = floor(log(remain) // log(2))
idx = prevs[ma][idx]
remain -= 2**ma
prev_n.append(idx)
rmq = RMQ(prev_n)
ans = []
for i in range(q):
l, r = list(map(int, sys.stdin.readline().split()))
if rmq.query(l-1, r-1) >= l-1:
ans.append("1")
else:
ans.append("0")
print("".join(ans))
```
| 96,998 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n.
Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries.
A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it.
A cyclic shift of a permutation (p_1, p_2, …, p_n) is a permutation (p_i, p_{i + 1}, …, p_{n}, p_1, p_2, …, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1).
A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, …, a_{i_k} for some i_1, i_2, …, i_k such that l ≤ i_1 < i_2 < … < i_k ≤ r.
Input
The first line contains three integers n, m, q (1 ≤ n, m, q ≤ 2 ⋅ 10^5) — the length of the permutation p, the length of the array a and the number of queries.
The next line contains n integers from 1 to n, where the i-th of them is the i-th element of the permutation. Each integer from 1 to n appears exactly once.
The next line contains m integers from 1 to n, the i-th of them is the i-th element of the array a.
The next q lines describe queries. The i-th of these lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m), meaning that the i-th query is about the subsegment of the array from the l_i-th to the r_i-th positions, inclusive.
Output
Print a single string of length q, consisting of 0 and 1, the digit on the i-th positions should be 1, if the subsegment of array a from the l_i-th to the r_i-th positions, inclusive, contains a subsequence that is a cyclic shift of p, and 0 otherwise.
Examples
Input
3 6 3
2 1 3
1 2 3 1 2 3
1 5
2 6
3 5
Output
110
Input
2 4 3
2 1
1 1 2 2
1 2
2 3
3 4
Output
010
Note
In the first example the segment from the 1-st to the 5-th positions is 1, 2, 3, 1, 2. There is a subsequence 1, 3, 2 that is a cyclic shift of the permutation. The subsegment from the 2-nd to the 6-th positions also contains a subsequence 2, 1, 3 that is equal to the permutation. The subsegment from the 3-rd to the 5-th positions is 3, 1, 2, there is only one subsequence of length 3 (3, 1, 2), but it is not a cyclic shift of the permutation.
In the second example the possible cyclic shifts are 1, 2 and 2, 1. The subsegment from the 1-st to the 2-nd positions is 1, 1, its subsequences are not cyclic shifts of the permutation. The subsegment from the 2-nd to the 3-rd positions is 1, 2, it coincides with the permutation. The subsegment from the 3 to the 4 positions is 2, 2, its subsequences are not cyclic shifts of the permutation.
Tags: data structures, dfs and similar, dp, math, trees
Correct Solution:
```
import sys
inp = [int(x) for x in sys.stdin.read().split()]
n, m, q = inp[0], inp[1], inp[2]
p = [inp[idx] for idx in range(3, n + 3)]
index_arr = [0] * (n + 1)
for i in range(n): index_arr[p[i]] = i
a = [inp[idx] for idx in range(n + 3, n + 3 + m)]
leftmost_pos = [m] * (n + 1)
next = [-1] * m
for i in range(m - 1, -1, -1):
index = index_arr[a[i]]
right_index = 0 if index == n - 1 else index + 1
right = p[right_index]
next[i] = leftmost_pos[right]
leftmost_pos[a[i]] = i
log = 0
while (1 << log) <= n: log += 1
log += 1
dp = [[m for _ in range(m + 1)] for _ in range(log)]
for i in range(m):
dp[0][i] = next[i]
for j in range(1, log):
for i in range(m):
dp[j][i] = dp[j - 1][dp[j - 1][i]]
last = [0] * m
for i in range(m):
p = i
len = n - 1
for j in range(log - 1, -1, -1):
if (1 << j) <= len:
p = dp[j][p]
len -= (1 << j)
last[i] = p
for i in range(m - 2, -1, -1):
last[i] = min(last[i], last[i + 1])
inp_idx = n + m + 3
ans = []
for i in range(q):
l, r = inp[inp_idx] - 1, inp[inp_idx + 1] - 1
inp_idx += 2
if last[l] <= r:
ans.append('1')
else:
ans.append('0')
print(''.join(ans))
```
| 96,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.