message stringlengths 2 19.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 322 108k | cluster float64 15 15 | __index_level_0__ int64 644 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.
We assume that Bajtek can only heap up snow drifts at integer coordinates.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift.
Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.
Output
Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.
Examples
Input
2
2 1
1 2
Output
1
Input
2
2 1
4 1
Output
0 | instruction | 0 | 96,404 | 15 | 192,808 |
Tags: brute force, dfs and similar, dsu, graphs
Correct Solution:
```
def arr_inp(n):
if n == 1:
return [int(x) for x in stdin.readline().split()]
elif n == 2:
return [float(x) for x in stdin.readline().split()]
else:
return [str(x) for x in stdin.readline().split()]
def dfs_util(x, y):
if visit[x, y]:
return
visit[x, y] = 1
ix1, ix2 = bisect_left(xs[x], y), bisect_left(ys[y], x)
if ix1 < len(xs[x]) - 1:
dfs_util(x, xs[x][ix1 + 1])
if ix1 > 0:
dfs_util(x, xs[x][ix1 - 1])
if ix2 < len(ys[y]) - 1:
dfs_util(ys[y][ix2 + 1], y)
if ix2 > 0:
dfs_util(ys[y][ix2 - 1], y)
def dfs():
cnt = 0
for x, y in points:
if not visit[x, y]:
dfs_util(x, y)
cnt += 1
return cnt
from sys import *
from collections import *
from bisect import *
points, visit, xs, ys = [], defaultdict(int), defaultdict(list), defaultdict(list)
for i in range(int(input())):
x, y = arr_inp(1)
points.append([x, y])
insort_right(ys[y], x)
insort_right(xs[x], y)
print(dfs() - 1)
``` | output | 1 | 96,404 | 15 | 192,809 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.
We assume that Bajtek can only heap up snow drifts at integer coordinates.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift.
Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.
Output
Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.
Examples
Input
2
2 1
1 2
Output
1
Input
2
2 1
4 1
Output
0 | instruction | 0 | 96,405 | 15 | 192,810 |
Tags: brute force, dfs and similar, dsu, graphs
Correct Solution:
```
n=int(input())
ans=1
xl=[]
yl=[]
for i in range(n):
x,y=map(int,input().split())
xl.append({x})
yl.append({y})
for i in range(n-1):
for j in range(i+1,n):
if xl[i]&xl[j] or yl[i]&yl[j]:
xl[j]|=xl[i]
yl[j]|=yl[i]
ans+=1
break
print(n-ans)
# Made By Mostafa_Khaled
``` | output | 1 | 96,405 | 15 | 192,811 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.
We assume that Bajtek can only heap up snow drifts at integer coordinates.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift.
Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.
Output
Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.
Examples
Input
2
2 1
1 2
Output
1
Input
2
2 1
4 1
Output
0
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 = 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)
class UnionFind:
def __init__(self, size):
self.table = [-1 for _ in range(size)]
def find(self, x):
if self.table[x] < 0:
return x
else:
self.table[x] = self.find(self.table[x])
return self.table[x]
def union(self, x, y):
s1 = self.find(x)
s2 = self.find(y)
if s1 != s2:
if self.table[s1] <= self.table[s2]:
self.table[s1] += self.table[s2]
self.table[s2] = s1
else:
self.table[s2] += self.table[s1]
self.table[s1] = s2
return True
return False
def subsetall(self):
a = []
for i in range(len(self.table)):
if self.table[i] < 0:
a.append((i, -self.table[i]))
return a
def main():
n = I()
xy = [LI() for _ in range(n)]
uf = UnionFind(n)
for i in range(n):
x,y = xy[i]
for j in range(i+1,n):
a,b = xy[j]
if a == x or b == y:
uf.union(i,j)
r = 0
for i in range(n):
if uf.find(i) == i:
r += 1
return r - 1
print(main())
``` | instruction | 0 | 96,408 | 15 | 192,816 |
Yes | output | 1 | 96,408 | 15 | 192,817 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.
We assume that Bajtek can only heap up snow drifts at integer coordinates.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift.
Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.
Output
Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.
Examples
Input
2
2 1
1 2
Output
1
Input
2
2 1
4 1
Output
0
Submitted Solution:
```
n=int(input())
store=[0]*(n+1)
l=[]
def dfs(node):
store[node]=1
for i in range(n):
if ((l[i][0]==l[node][0] or l[i][1]==l[node][1]) and store[i]==0):
dfs(i)
for i in range(n):
x,y=map(int,input().split())
l.append([x,y])
count=-1
for i in range(n):
if (not store[i]):
dfs(i)
count+=1
print(count)
``` | instruction | 0 | 96,409 | 15 | 192,818 |
Yes | output | 1 | 96,409 | 15 | 192,819 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.
We assume that Bajtek can only heap up snow drifts at integer coordinates.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift.
Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.
Output
Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.
Examples
Input
2
2 1
1 2
Output
1
Input
2
2 1
4 1
Output
0
Submitted Solution:
```
from collections import defaultdict
n=int(input())
x_,y_=[],[]
x1,y1=[],[]
for i in range(n):
x,y=map(int,input().split())
x_.append(x)
y_.append(y)
count=0
for i in range(n):
for j in range(i+1,n):
#print(x_[i],x_[j])
if x_[i]!=x_[j] and y_[i]!=y_[j] and x_[j] not in x1 and y_[j] not in y1:
count+=1
x1.append(x_[j])
y1.append(y_[j])
print(count)
``` | instruction | 0 | 96,413 | 15 | 192,826 |
No | output | 1 | 96,413 | 15 | 192,827 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.
We assume that Bajtek can only heap up snow drifts at integer coordinates.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift.
Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.
Output
Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.
Examples
Input
2
2 1
1 2
Output
1
Input
2
2 1
4 1
Output
0
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 = 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():
n = I()
aa = [LI() for _ in range(n)]
nn = len(aa[0])
r = inf
for i in range(n):
for j in range(nn-1):
t = abs(aa[i][j] - aa[i][j+1])
if r > t:
r = t
for j in range(n-1):
for i in range(nn):
t = abs(aa[j][i] - aa[j+1][i])
if r > t:
r = t
return r
print(main())
``` | instruction | 0 | 96,415 | 15 | 192,830 |
No | output | 1 | 96,415 | 15 | 192,831 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with 4 rows and n (n ≤ 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k ≤ 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
<image> Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n), representing the number of columns and the number of cars, respectively.
The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.
In the first and last line, an integer 1 ≤ x ≤ k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).
In the second and third line, an integer 1 ≤ x ≤ k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).
Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.
Output
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.
If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.
Examples
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
Note
In the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible. | instruction | 0 | 96,725 | 15 | 193,450 |
Tags: constructive algorithms, implementation
Correct Solution:
```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
max = 20000
def test(x1, x2, n, s):
for i in range(x1+1, x2+1):
if s[n][i] != 0:
return False
return True
def lastshift(n, s, a):
m = 0
for i in range(n):
if s[1][i] != 0 and s[1][i] == s[0][i]:
s[1][i] = 0
m += 1
a.append([s[0][i], 1, i+1] )
# elif s[2][i] != 0 and s[2][i] == s[0][i] and s[1][i] == 0:
# s[2][i] = 0
# m += 1
# a.append([s[0][i], 2, i+1])
# a.append([s[0][i], 1, i+1])
if s[2][i] != 0 and s[2][i] == s[3][i]:
s[2][i] = 0
m += 1
a.append([s[3][i], 4, i+1])
# elif s[2][i] != 0 and s[1][i] == s[3][i] and s[2][i] == 0:
# s[1][i] = 0
# m += 1
# a.append([s[3][i], 3, i+1])
# a.append([s[3][i], 4, i+1])
return(m)
(n, k) = (int(i) for i in input().split())
s = []
s.append([int(i) for i in input().split()])
s.append([int(i) for i in input().split()])
s.append([int(i) for i in input().split()])
s.append([int(i) for i in input().split()])
start = time.time()
a = []
m = lastshift(n, s, a)
I = -1
z = 0
for i in range(n):
if s[1][i] == 0:
l = 1
I = i
break
if s[2][i] == 0:
l = 2
I = i
break
if I >= 0:
while(m < k):
b = s[1][0]
e = s[2][n-1]
if l == 1:
for i in range(I, n-1):
# print(s[1][i], s[1][i+1])
s[1][i] = s[1][i+1]
# print(s[1][i], s[1][i+1])
if s[1][i+1] != 0:
a.append([s[1][i+1], 2, i+1])
if e!=0:
a.append([e, 2, n])
for i in range(n-1, 0, -1):
s[2][i] = s[2][i-1]
if s[2][i] != 0:
a.append([s[2][i], 3, i+1])
if b!=0:
a.append([b, 3, 1])
for i in range(I-1):
s[1][i] = s[1][i+1]
if s[1][i+1] != 0:
a.append([s[1][i+1], 2, i+1])
s[1][n-1] = e
s[2][0] = b
else:
for i in range(I, 0, -1):
s[2][i] = s[2][i-1]
if s[2][i] != 0:
a.append([s[2][i], 3, i+1])
if b!=0:
a.append([b, 3, 1])
for i in range(n-1):
s[1][i] = s[1][i+1]
if s[1][i] != 0:
a.append([s[1][i], 2, i+1])
if e!=0:
a.append([e, 2, n])
s[1][n-1] = e
s[2][0] = b
for i in range(n-1, I+1, -1):
s[2][i] = s[2][i-1]
if s[2][i] != 0:
a.append([s[2][i], 3, i+1])
I += 2*l-3
if I == -1:
I = 0
l = 2
if I == n:
I = n-1
l = 1
# print(l, I)
s[l][I] = 0
# print(a[z:])
# z = len(a)
# for i in range(4):
# for j in range(n):
# print(s[i][j], end=" ")
# print()
# print()
m += lastshift(n, s, a)
# print(a[z:])
# z = len(a)
# for i in range(4):
# for j in range(n):
# print(s[i][j], end=" ")
# print()
# print()
print(len(a))
for i in range(len(a)):
print(a[i][0], a[i][1], a[i][2])
else:
print(-1)
finish = time.time()
#print(finish - start)
``` | output | 1 | 96,725 | 15 | 193,451 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with 4 rows and n (n ≤ 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k ≤ 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
<image> Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n), representing the number of columns and the number of cars, respectively.
The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.
In the first and last line, an integer 1 ≤ x ≤ k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).
In the second and third line, an integer 1 ≤ x ≤ k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).
Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.
Output
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.
If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.
Examples
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
Note
In the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible. | instruction | 0 | 96,726 | 15 | 193,452 |
Tags: constructive algorithms, implementation
Correct Solution:
```
#!/usr/bin/python3
def parknext(N, P, sq, rem):
for i in range(N):
if P[0][i] == P[1][i] and P[0][i] > 0:
sq.append((P[0][i], 1, i + 1))
P[0][i] = P[1][i] = 0
rem[0] -= 1
if P[3][i] == P[2][i] and P[3][i] > 0:
sq.append((P[3][i], 4, i + 1))
P[3][i] = P[2][i] = 0
rem[0] -= 1
def rotnext(N, pos):
c, r = pos
assert r == 1 or r == 2
if r == 1 and c == N - 1:
return (N - 1, 2)
if r == 2 and c == 0:
return (0, 1)
if r == 1:
return (c + 1, r)
return (c - 1, r)
def rot(N, P, sq):
pos = None
for c in range(N):
for r in (1, 2):
# print(P[c][r])
if P[r][c] == 0:
pos = (c, r)
break
if pos is not None:
break
if pos is None:
return False
origpos = pos
prev = pos
cur = rotnext(N, pos)
while cur != origpos:
pc, pr = prev
cc, cr = cur
assert P[pr][pc] == 0
if P[cr][cc] > 0:
sq.append((P[cr][cc], pr + 1, pc + 1))
P[pr][pc] = P[cr][cc]
P[cr][cc] = 0
prev = cur
cur = rotnext(N, cur)
return True
def solve(N, K, P):
sq = []
rem = [K]
parknext(N, P, sq, rem)
while rem[0] > 0:
# print(P)
if not rot(N, P, sq):
return -1
parknext(N, P, sq, rem)
return sq
def main():
N, K = [int(e) for e in input().split(' ')]
P = []
for _ in range(4):
a = [int(e) for e in input().split(' ')]
assert len(a) == N
P.append(a)
ans = solve(N, K, P)
if ans == -1:
print("-1")
else:
print(len(ans))
for l in ans:
print(' '.join(map(str, l)))
if __name__ == '__main__':
main()
``` | output | 1 | 96,726 | 15 | 193,453 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with 4 rows and n (n ≤ 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k ≤ 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
<image> Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n), representing the number of columns and the number of cars, respectively.
The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.
In the first and last line, an integer 1 ≤ x ≤ k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).
In the second and third line, an integer 1 ≤ x ≤ k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).
Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.
Output
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.
If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.
Examples
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
Note
In the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible. | instruction | 0 | 96,727 | 15 | 193,454 |
Tags: constructive algorithms, implementation
Correct Solution:
```
all_the_moves = []
parked = 0
n, k = map(int, input().split())
park = []
park += [[int(x) for x in input().split()]]
park += [[int(x) for x in input().split()]]
park += [[int(x) for x in input().split()]]
park += [[int(x) for x in input().split()]]
def add_move(car, r, c):
global all_the_moves
if car == 0:
return
all_the_moves += [(car, r, c)]
def cycle():
if len(park[1]) == 1:
if park[1][0] != 0:
add_move(park[1][0], 2, 0)
park[1][0], park[2][0] = park[2][0], park[1][0]
elif park[2][0] != 0:
add_move(park[2][0], 1, 0)
park[1][0], park[2][0] = park[2][0], park[1][0]
return
if 0 not in park[1]:
i = park[2].index(0)
park[2][i], park[1][i] = park[1][i], park[2][i]
add_move(park[2][i], 2, i)
i = park[1].index(0)
for j in range(i, 0, -1):
add_move(park[1][j - 1], 1, j)
park[1][j], park[1][j - 1] = park[1][j - 1], park[1][j]
add_move(park[2][0], 1, 0)
park[1][0], park[2][0] = park[2][0], park[1][0]
for j in range(n - 1):
add_move(park[2][j + 1], 2, j)
park[2][j], park[2][j + 1] = park[2][j + 1], park[2][j]
if i < n - 1:
add_move(park[1][n - 1], 2, n - 1)
park[1][n - 1], park[2][n - 1] = park[2][n - 1], park[1][n - 1]
for j in range(n - 2, i, -1):
add_move(park[1][j], 1, j + 1)
park[1][j], park[1][j + 1] = park[1][j + 1], park[1][j]
def cars_to_their_places():
global all_the_moves
global parked
for i in range(n):
if park[0][i] != 0 and park[0][i] == park[1][i]:
all_the_moves += [(park[0][i], 0, i)]
park[1][i] = 0
parked += 1
for i in range(n):
if park[3][i] != 0 and park[3][i] == park[2][i]:
all_the_moves += [(park[3][i], 3, i)]
park[2][i] = 0
parked += 1
cars_to_their_places()
if k == 2 * n and parked == 0:
print(-1)
else:
while parked < k:
cycle()
cars_to_their_places()
if len(all_the_moves) <= 2 * 10 ** 4:
print(len(all_the_moves))
for i, r, c in all_the_moves:
print(i, r + 1, c + 1)
else:
print(-1)
``` | output | 1 | 96,727 | 15 | 193,455 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with 4 rows and n (n ≤ 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k ≤ 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
<image> Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n), representing the number of columns and the number of cars, respectively.
The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.
In the first and last line, an integer 1 ≤ x ≤ k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).
In the second and third line, an integer 1 ≤ x ≤ k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).
Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.
Output
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.
If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.
Examples
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
Note
In the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible. | instruction | 0 | 96,728 | 15 | 193,456 |
Tags: constructive algorithms, implementation
Correct Solution:
```
n, k = list(map(int, input().split()))
table = []
for row in range(4):
table.append(list(map(int, input().split())))
moves = []
def make_move(start,finish):
moves.append((table[start[0]][start[1]], finish[0]+1, finish[1]+1))
table[finish[0]][finish[1]] = table[start[0]][start[1]]
table[start[0]][start[1]] = 0
def move_all_to_places():
for pos in range(n):
if (table[1][pos] == table[0][pos]) and table[1][pos]:
make_move((1,pos), (0,pos))
if (table[2][pos] == table[3][pos]) and table[2][pos]:
make_move((2,pos), (3,pos))
move_all_to_places()
found = False
for pos in range(n):
if table[1][pos] == 0:
found = True
break
if table[2][pos] == 0:
found = True
break
if not found:
print(-1)
exit()
for cnt in range(20000):
if (table[1][0] != 0) and (table[2][0] == 0) :
make_move((1,0), (2,0)) # moved down
if n == 1:
continue
for pos in range(1,n):
if (table[1][pos-1] == 0) and (table[1][pos] != 0):
make_move((1,pos), (1, pos-1))
move_all_to_places()
if (table[1][n-1] == 0) and (table[2][n-1] != 0) :
make_move((2,n-1), (1,n-1)) # moved up
for pos in range(n-2,-1, -1):
if (table[2][pos+1] == 0) and (table[2][pos] != 0):
make_move((2,pos), (2, pos+1))
move_all_to_places()
if len(moves) > 20000:
print(-1)
exit()
print(len(moves))
for m in moves:
print(*m)
``` | output | 1 | 96,728 | 15 | 193,457 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with 4 rows and n (n ≤ 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k ≤ 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
<image> Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n), representing the number of columns and the number of cars, respectively.
The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.
In the first and last line, an integer 1 ≤ x ≤ k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).
In the second and third line, an integer 1 ≤ x ≤ k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).
Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.
Output
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.
If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.
Examples
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
Note
In the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible. | instruction | 0 | 96,729 | 15 | 193,458 |
Tags: constructive algorithms, implementation
Correct Solution:
```
n, k = map(int, input().strip().split())
p = list()
for _ in range(4):
p.append(list(map(int, input().strip().split())))
def find():
for i in range(n):
if p[1][i] != 0 and p[0][i] == p[1][i]:
car = p[1][i]
p[1][i] = 0
return [car, 1, i + 1]
if p[2][i] != 0 and p[3][i] == p[2][i]:
car = p[2][i]
p[2][i] = 0
return [car, 4, i + 1]
return list()
def rotate():
for c in range(n):
if p[1][c] != 0:
nc = c + 1
nr = 1
if nc == n:
nc = n - 1
nr = 2
if p[nr][nc] == 0:
ans.append([p[1][c], nr + 1, nc + 1])
p[nr][nc] = p[1][c]
p[1][c] = 0
return
for c in range(n):
if p[2][c] != 0:
nc = c - 1
nr = 2
if nc == -1:
nc = 0
nr = 1
if p[nr][nc] == 0:
ans.append([p[2][c], nr + 1, nc + 1])
p[nr][nc] = p[2][c]
p[2][c] = 0
return
cnt = 0
ans = list()
while cnt < k:
cur = find()
if len(cur) == 0 and k == 2 * n and cnt == 0:
print(-1)
exit(0)
if cur:
ans.append(cur)
cnt += 1
# print(p)
rotate()
# print(p)
print(len(ans))
for e in ans:
print(' '.join(map(str, e)))
``` | output | 1 | 96,729 | 15 | 193,459 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with 4 rows and n (n ≤ 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k ≤ 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
<image> Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n), representing the number of columns and the number of cars, respectively.
The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.
In the first and last line, an integer 1 ≤ x ≤ k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).
In the second and third line, an integer 1 ≤ x ≤ k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).
Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.
Output
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.
If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.
Examples
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
Note
In the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible. | instruction | 0 | 96,730 | 15 | 193,460 |
Tags: constructive algorithms, implementation
Correct Solution:
```
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
sys.setrecursionlimit(10000)
def read_int():
return int(input())
def read_int_n():
return list(map(int, input().split()))
def read_float():
return float(input())
def read_float_n():
return list(map(float, input().split()))
def read_str():
return input()
def read_str_n():
return list(map(str, input().split()))
def error_print(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.time()
ret = f(*args, **kwargs)
e = time.time()
error_print(e - s, 'sec')
return ret
return wrap
@mt
def slv(N, K, S):
error_print('------')
for s in S:
error_print(s)
ans = []
for i, (p, c) in enumerate(zip(S[0], S[1])):
if c != 0 and p == c:
ans.append((c , 1, i+1))
S[1][i] = 0
for i, (p, c) in enumerate(zip(S[3], S[2])):
if c != 0 and p == c:
ans.append((c , 4, i+1))
S[2][i] = 0
while len(ans) <= 20000 and sum(S[1]) + sum(S[2]) != 0:
error_print('------')
m = len(ans)
for s in S:
error_print(s)
S1 = [c for c in S[1]]
S2 = [c for c in S[2]]
for i in range(N):
c = S[1][i]
if i == 0:
if c != 0 and S[2][0] == 0:
ans.append((c, 3, i+1))
S1[i] = 0
S2[i] = c
else:
if c != 0 and S[1][i-1] == 0:
ans.append((c, 2, i))
S1[i] = 0
S1[i-1] = c
for i in range(0, N)[::-1]:
c = S[2][i]
if i == N-1:
if c != 0 and S[1][i] == 0:
ans.append((c, 2, i+1))
S2[i] = 0
S1[i] = c
else:
if c != 0 and S[2][i+1] == 0:
ans.append((c, 3, i+2))
S2[i] = 0
S2[i+1] = c
S[1] = S1
S[2] = S2
for i, (p, c) in enumerate(zip(S[0], S[1])):
if c != 0 and p == c:
ans.append((c , 1, i+1))
S[1][i] = 0
for i, (p, c) in enumerate(zip(S[3], S[2])):
if c != 0 and p == c:
ans.append((c , 4, i+1))
S[2][i] = 0
if len(ans) == m:
break
if len(ans) > 20000:
return -1
if sum(S[1]) + sum(S[2]) != 0:
return -1
error_print('------')
for s in S:
error_print(s)
return str(len(ans)) + '\n' + '\n'.join(map(lambda x: ' '.join(map(str, x)), ans))
def main():
N, K = read_int_n()
S = [read_int_n() for _ in range(4)]
print(slv(N, K, S))
if __name__ == '__main__':
main()
``` | output | 1 | 96,730 | 15 | 193,461 |
Provide a correct Python 3 solution for this coding contest problem.
Yukiya, the owner of Aizuyama Ski Resort, has prepared a course for advanced skiers with obstacles and jumping hills. There are various ways to slide on the course, and users who can slide in all patterns during the season will be given a gift.
Let's create a program for the oil tree shop that outputs the number of patterns of how to slide based on the floor plan of the course.
<image>
The course is represented by a grid of X x Y squares as shown above. It is assumed that the origin is at the upper left, the x coordinate increases as it goes to the right, and the y coordinate increases as it goes down.
Each gliding pattern starts at the highest point (y = 1, but without obstacles) and progresses towards the goal (y = Y). A runner in a grid square (x, y) can move to either (x − 1, y + 1), (x, y + 1), or (x + 1, y + 1). I will. There are obstacles and jumping platforms in the squares, and you cannot enter the squares with obstacles, and when you enter the squares with jumping platforms, you will move to (x, y + 2). However, there is no jumping platform in the highest cell (the cell with y = 1), and when entering a cell with a jumping platform, you can only enter from the cell with the same x coordinate. Starting from the top of the course (y = 1) and crossing the bottom without deviating from the course (y ≥ Y), it is considered as one way of sliding and ends.
Create a program that takes the course information as input and outputs the total number of slips.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
X Y
c11 c21 ... cX1
c12 c22 ... cX2
::
c1Y c2Y ... cXY
The first line gives the course size X, Y (1 ≤ X, Y ≤ 15). Course information is given in the Y line that follows. cij (one of 0, 1, or 2) is an integer that represents the information of the squares of x = i, y = j, where 0 is a movable square, 1 is a square with an obstacle, and 2 is a square with a jumping platform. Represents.
The number of datasets does not exceed 50.
Output
For each input dataset, the number of patterns of how to slide the course is output on one line.
Example
Input
5 5
0 0 0 0 1
2 1 0 2 0
1 0 0 1 1
0 2 1 2 0
0 1 0 0 0
5 5
0 0 1 0 0
2 1 0 2 0
1 0 0 1 1
0 2 1 2 0
0 1 0 0 0
15 15
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0
Output
8
6
52694573 | instruction | 0 | 96,874 | 15 | 193,748 |
"Correct Solution:
```
def printF(field,w,h):
for i in range(h):
print(field[i])
def getp(f,p,y,x,h,w,v):
if y<0 or x<0 or x>=w:
return 0
if y>=h:
if v==True:
return 1
return 0
k = f[y][x]
r = 0
if k==0:
if p[y][x]>=0:
return p[y][x]
r = getp(f,p,y+1,x-1,h,w,False)+getp(f,p,y+1,x,h,w,True)+getp(f,p,y+1,x+1,h,w,False)
p[y][x] = r
elif k==1:
r = 0
elif k==2:
if v == True:
if p[y][x]>=0:
return p[y][x]
r = getp(f,p,y+2,x,h,w,True)
p[y][x] = r
else:
r = 0
#print("gp({},{},{}):({},{})".format(x,y,v,k,r))
return r
w,h = map(int,input().split())
while w!=0 and h != 0:
field = []
for i in range(h):
field.append(list(map(int,input().split())))
#initialize
p = []
for i in range(h):
p.append([-1]*w)
#calc
print(sum(map(lambda x:getp(field,p,0,x,h,w,True), range(w))))
w,h = map(int,input().split())
``` | output | 1 | 96,874 | 15 | 193,749 |
Provide a correct Python 3 solution for this coding contest problem.
Yukiya, the owner of Aizuyama Ski Resort, has prepared a course for advanced skiers with obstacles and jumping hills. There are various ways to slide on the course, and users who can slide in all patterns during the season will be given a gift.
Let's create a program for the oil tree shop that outputs the number of patterns of how to slide based on the floor plan of the course.
<image>
The course is represented by a grid of X x Y squares as shown above. It is assumed that the origin is at the upper left, the x coordinate increases as it goes to the right, and the y coordinate increases as it goes down.
Each gliding pattern starts at the highest point (y = 1, but without obstacles) and progresses towards the goal (y = Y). A runner in a grid square (x, y) can move to either (x − 1, y + 1), (x, y + 1), or (x + 1, y + 1). I will. There are obstacles and jumping platforms in the squares, and you cannot enter the squares with obstacles, and when you enter the squares with jumping platforms, you will move to (x, y + 2). However, there is no jumping platform in the highest cell (the cell with y = 1), and when entering a cell with a jumping platform, you can only enter from the cell with the same x coordinate. Starting from the top of the course (y = 1) and crossing the bottom without deviating from the course (y ≥ Y), it is considered as one way of sliding and ends.
Create a program that takes the course information as input and outputs the total number of slips.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
X Y
c11 c21 ... cX1
c12 c22 ... cX2
::
c1Y c2Y ... cXY
The first line gives the course size X, Y (1 ≤ X, Y ≤ 15). Course information is given in the Y line that follows. cij (one of 0, 1, or 2) is an integer that represents the information of the squares of x = i, y = j, where 0 is a movable square, 1 is a square with an obstacle, and 2 is a square with a jumping platform. Represents.
The number of datasets does not exceed 50.
Output
For each input dataset, the number of patterns of how to slide the course is output on one line.
Example
Input
5 5
0 0 0 0 1
2 1 0 2 0
1 0 0 1 1
0 2 1 2 0
0 1 0 0 0
5 5
0 0 1 0 0
2 1 0 2 0
1 0 0 1 1
0 2 1 2 0
0 1 0 0 0
15 15
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0
Output
8
6
52694573 | instruction | 0 | 96,875 | 15 | 193,750 |
"Correct Solution:
```
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0203
"""
import sys
from sys import stdin
from collections import deque, defaultdict
input = stdin.readline
def solve(field):
BLANK, OBSTACLE, JUMP = 0, 1, 2
ans = 0 # ??????????????°???????????°
dy = [1, 1, 1] # ?????????????????????????????????????§???????
dx = [0, -1, 1]
x_limit = len(field[0])
y_limit = len(field)
path = defaultdict(int) # ??????????????????????????°???????????°????????????'x???_y???'???????????????
Q = deque()
for x, m in enumerate(field[0]):
if m == BLANK: # ?????????????????°?????´?????????????????????????????????
t = '{}_{}'.format(x, 0)
Q.append((x, 0))
path[t] = 1
while Q:
cx, cy = Q.popleft() # ?????¨??°?????§?¨?
t = '{}_{}'.format(cx, cy)
num = path.pop(t)
if field[cy][cx] == OBSTACLE:
continue
elif field[cy][cx] == JUMP: # ?????£????????§?????°?????????????????£????????°
if cy+2 > y_limit-1:
ans += num
else:
t = '{}_{}'.format(cx, cy+2)
if not path[t]:
Q.append((cx, cy+2))
path[t] += num
continue
elif cy == y_limit -1:
ans += num
continue
for i in range(len(dx)):
nx = cx + dx[i] # ?????°????????§?¨?
ny = cy + dy[i]
if 0<= nx < x_limit:
if (ny >= y_limit - 1) and field[ny][nx] == BLANK:
ans += num
else:
if field[ny][nx] == JUMP and dx[i] == 0: # ?????£????????°????????£??????????????\????????´???
if ny+2 > y_limit - 1:
ans += num
else:
t = '{}_{}'.format(nx, ny+2)
if not path[t]:
Q.append((nx, ny+2))
path[t] += num
elif field[ny][nx] == BLANK:
t = '{}_{}'.format(nx, ny)
if not path[t]:
Q.append((nx, ny))
path[t] += num
return ans
def main(args):
while True:
X, Y = map(int, input().strip().split())
if X == 0 and Y == 0:
break
field = []
for _ in range(Y):
temp = [int(x) for x in input().strip().split()]
field.append(temp)
result = solve(field)
print(result)
if __name__ == '__main__':
main(sys.argv[1:])
``` | output | 1 | 96,875 | 15 | 193,751 |
Provide a correct Python 3 solution for this coding contest problem.
Yukiya, the owner of Aizuyama Ski Resort, has prepared a course for advanced skiers with obstacles and jumping hills. There are various ways to slide on the course, and users who can slide in all patterns during the season will be given a gift.
Let's create a program for the oil tree shop that outputs the number of patterns of how to slide based on the floor plan of the course.
<image>
The course is represented by a grid of X x Y squares as shown above. It is assumed that the origin is at the upper left, the x coordinate increases as it goes to the right, and the y coordinate increases as it goes down.
Each gliding pattern starts at the highest point (y = 1, but without obstacles) and progresses towards the goal (y = Y). A runner in a grid square (x, y) can move to either (x − 1, y + 1), (x, y + 1), or (x + 1, y + 1). I will. There are obstacles and jumping platforms in the squares, and you cannot enter the squares with obstacles, and when you enter the squares with jumping platforms, you will move to (x, y + 2). However, there is no jumping platform in the highest cell (the cell with y = 1), and when entering a cell with a jumping platform, you can only enter from the cell with the same x coordinate. Starting from the top of the course (y = 1) and crossing the bottom without deviating from the course (y ≥ Y), it is considered as one way of sliding and ends.
Create a program that takes the course information as input and outputs the total number of slips.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
X Y
c11 c21 ... cX1
c12 c22 ... cX2
::
c1Y c2Y ... cXY
The first line gives the course size X, Y (1 ≤ X, Y ≤ 15). Course information is given in the Y line that follows. cij (one of 0, 1, or 2) is an integer that represents the information of the squares of x = i, y = j, where 0 is a movable square, 1 is a square with an obstacle, and 2 is a square with a jumping platform. Represents.
The number of datasets does not exceed 50.
Output
For each input dataset, the number of patterns of how to slide the course is output on one line.
Example
Input
5 5
0 0 0 0 1
2 1 0 2 0
1 0 0 1 1
0 2 1 2 0
0 1 0 0 0
5 5
0 0 1 0 0
2 1 0 2 0
1 0 0 1 1
0 2 1 2 0
0 1 0 0 0
15 15
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0
Output
8
6
52694573 | instruction | 0 | 96,876 | 15 | 193,752 |
"Correct Solution:
```
def solve(c):
w, h = len(c[0]), len(c)
dp = [[0] * w for _ in range(h)]
#?????????
for x in range(w):
if c[1][x] == 0:
dp[1][x] = 1
for y in range(2, h):
for x in range(w):
if c[y][x] == 1:
continue
if c[y - 2][x] == 2:
dp[y][x] += dp[y - 2][x]
if c[y - 1][x] == 0:
dp[y][x] += dp[y - 1][x]
if c[y][x] == 0:
if c[y - 1][x - 1] == 0:
dp[y][x] += dp[y - 1][x - 1]
if c[y - 1][x + 1] == 0:
dp[y][x] += dp[y - 1][x + 1]
return sum(dp[-1]) + sum(dp[-2][x] for x in range(w) if c[-2][x] == 2)
import sys
f = sys.stdin
while True:
w, h = map(int, f.readline().split())
if w == 0:
break
course = [[1] * (w + 2)] + [[1] + list(map(int, f.readline().split())) + [1] for _ in range(h)]
print(solve(course))
``` | output | 1 | 96,876 | 15 | 193,753 |
Provide a correct Python 3 solution for this coding contest problem.
Yukiya, the owner of Aizuyama Ski Resort, has prepared a course for advanced skiers with obstacles and jumping hills. There are various ways to slide on the course, and users who can slide in all patterns during the season will be given a gift.
Let's create a program for the oil tree shop that outputs the number of patterns of how to slide based on the floor plan of the course.
<image>
The course is represented by a grid of X x Y squares as shown above. It is assumed that the origin is at the upper left, the x coordinate increases as it goes to the right, and the y coordinate increases as it goes down.
Each gliding pattern starts at the highest point (y = 1, but without obstacles) and progresses towards the goal (y = Y). A runner in a grid square (x, y) can move to either (x − 1, y + 1), (x, y + 1), or (x + 1, y + 1). I will. There are obstacles and jumping platforms in the squares, and you cannot enter the squares with obstacles, and when you enter the squares with jumping platforms, you will move to (x, y + 2). However, there is no jumping platform in the highest cell (the cell with y = 1), and when entering a cell with a jumping platform, you can only enter from the cell with the same x coordinate. Starting from the top of the course (y = 1) and crossing the bottom without deviating from the course (y ≥ Y), it is considered as one way of sliding and ends.
Create a program that takes the course information as input and outputs the total number of slips.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
X Y
c11 c21 ... cX1
c12 c22 ... cX2
::
c1Y c2Y ... cXY
The first line gives the course size X, Y (1 ≤ X, Y ≤ 15). Course information is given in the Y line that follows. cij (one of 0, 1, or 2) is an integer that represents the information of the squares of x = i, y = j, where 0 is a movable square, 1 is a square with an obstacle, and 2 is a square with a jumping platform. Represents.
The number of datasets does not exceed 50.
Output
For each input dataset, the number of patterns of how to slide the course is output on one line.
Example
Input
5 5
0 0 0 0 1
2 1 0 2 0
1 0 0 1 1
0 2 1 2 0
0 1 0 0 0
5 5
0 0 1 0 0
2 1 0 2 0
1 0 0 1 1
0 2 1 2 0
0 1 0 0 0
15 15
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0
Output
8
6
52694573 | instruction | 0 | 96,877 | 15 | 193,754 |
"Correct Solution:
```
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0203
"""
import sys
from sys import stdin
from collections import deque, defaultdict
input = stdin.readline
def solve(field):
BLANK, OBSTACLE, JUMP = 0, 1, 2
ans = 0 # ??????????????°???????????°
# dy = [1, 1, 1]
dx = [0, -1, 1] # ?????????????????????????????????????§???????
x_limit = len(field[0])
y_limit = len(field)
path = defaultdict(int) # ??????????????????????????°???????????°????????????'x???_y???'???????????????
Q = deque() # ?????§??????????????????????????¨??????????????\???
# ???????????§??????????????§????????´????????¢???????????\??????????????????
for x, m in enumerate(field[0]):
if m == BLANK: # ?????????????????°?????´?????????????????????????????????
k = '{}_{}'.format(x, 0)
Q.append((x, 0))
path[k] = 1
while Q:
cx, cy = Q.popleft() # ?????¨??°?????§?¨?
k = '{}_{}'.format(cx, cy)
num = path.pop(k) # ????????§?¨?????????????????????°
if field[cy][cx] == OBSTACLE: # ?????£????????§?????°??????????????????????????±????????????????????????????????§?????£?????????????????
continue
elif field[cy][cx] == JUMP: # ?????£????????§?????°?????????????????£????????°
if cy+2 > y_limit-1: # ?????£???????????????????¶?????????´??????OK??¨?????????
ans += num
else:
k = '{}_{}'.format(cx, cy+2)
if not path[k]:
Q.append((cx, cy+2))
path[k] += num
continue
elif cy == y_limit -1:
ans += num
continue
for i in range(3): # ?????????3???len(dy)?????????
nx = cx + dx[i] # ?????°????????§?¨?
ny = cy + 1 # ??????+1????????§???dy[i]??¨?????????????????????OK
if 0<= nx < x_limit:
if field[ny][nx] == JUMP and dx[i] == 0: # ?????£????????°????????£??????????????\????????´???
if ny+2 > y_limit - 1:
ans += num
else:
k = '{}_{}'.format(nx, ny+2)
if not path[k]:
Q.append((nx, ny+2))
path[k] += num
elif field[ny][nx] == BLANK:
if (ny >= y_limit - 1):
ans += num
else:
k = '{}_{}'.format(nx, ny)
if not path[k]:
Q.append((nx, ny))
path[k] += num
return ans
def solve2(field):
BLANK, OBSTACLE, JUMP = 0, 1, 2
ans = 0 # ??????????????°???????????°
dy = [1, 1, 1] # ?????????????????????????????????????§???????
dx = [0, -1, 1]
x_limit = len(field[0])
y_limit = len(field)
path = defaultdict(int) # ??????????????????????????°???????????°????????????'x???_y???'???????????????
Q = deque()
for x, m in enumerate(field[0]):
if m == BLANK: # ?????????????????°?????´?????????????????????????????????
t = '{}_{}'.format(x, 0)
Q.append((x, 0))
path[t] = 1
while Q:
cx, cy = Q.popleft() # ?????¨??°?????§?¨?
t = '{}_{}'.format(cx, cy)
num = path.pop(t)
if field[cy][cx] == OBSTACLE:
continue
elif field[cy][cx] == JUMP: # ?????£????????§?????°?????????????????£????????°
if cy+2 > y_limit-1:
ans += num
else:
t = '{}_{}'.format(cx, cy+2)
if not path[t]:
Q.append((cx, cy+2))
path[t] += num
continue
elif cy == y_limit -1:
ans += num
continue
for i in range(3): # ?????????3???len(dy)?????????
nx = cx + dx[i] # ?????°????????§?¨?
ny = cy + dy[i]
if 0<= nx < x_limit:
if field[ny][nx] == JUMP and dx[i] == 0: # ?????£????????°????????£??????????????\????????´???
if ny+2 > y_limit - 1:
ans += num
else:
t = '{}_{}'.format(nx, ny+2)
if not path[t]:
Q.append((nx, ny+2))
path[t] += num
elif field[ny][nx] == BLANK:
if (ny >= y_limit - 1):
ans += num
else:
t = '{}_{}'.format(nx, ny)
if not path[t]:
Q.append((nx, ny))
path[t] += num
return ans
def main(args):
while True:
X, Y = map(int, input().strip().split())
if X == 0 and Y == 0:
break
field = []
for _ in range(Y):
temp = [int(x) for x in input().strip().split()]
field.append(temp)
result = solve2(field)
print(result)
if __name__ == '__main__':
main(sys.argv[1:])
``` | output | 1 | 96,877 | 15 | 193,755 |
Provide a correct Python 3 solution for this coding contest problem.
Yukiya, the owner of Aizuyama Ski Resort, has prepared a course for advanced skiers with obstacles and jumping hills. There are various ways to slide on the course, and users who can slide in all patterns during the season will be given a gift.
Let's create a program for the oil tree shop that outputs the number of patterns of how to slide based on the floor plan of the course.
<image>
The course is represented by a grid of X x Y squares as shown above. It is assumed that the origin is at the upper left, the x coordinate increases as it goes to the right, and the y coordinate increases as it goes down.
Each gliding pattern starts at the highest point (y = 1, but without obstacles) and progresses towards the goal (y = Y). A runner in a grid square (x, y) can move to either (x − 1, y + 1), (x, y + 1), or (x + 1, y + 1). I will. There are obstacles and jumping platforms in the squares, and you cannot enter the squares with obstacles, and when you enter the squares with jumping platforms, you will move to (x, y + 2). However, there is no jumping platform in the highest cell (the cell with y = 1), and when entering a cell with a jumping platform, you can only enter from the cell with the same x coordinate. Starting from the top of the course (y = 1) and crossing the bottom without deviating from the course (y ≥ Y), it is considered as one way of sliding and ends.
Create a program that takes the course information as input and outputs the total number of slips.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
X Y
c11 c21 ... cX1
c12 c22 ... cX2
::
c1Y c2Y ... cXY
The first line gives the course size X, Y (1 ≤ X, Y ≤ 15). Course information is given in the Y line that follows. cij (one of 0, 1, or 2) is an integer that represents the information of the squares of x = i, y = j, where 0 is a movable square, 1 is a square with an obstacle, and 2 is a square with a jumping platform. Represents.
The number of datasets does not exceed 50.
Output
For each input dataset, the number of patterns of how to slide the course is output on one line.
Example
Input
5 5
0 0 0 0 1
2 1 0 2 0
1 0 0 1 1
0 2 1 2 0
0 1 0 0 0
5 5
0 0 1 0 0
2 1 0 2 0
1 0 0 1 1
0 2 1 2 0
0 1 0 0 0
15 15
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0
Output
8
6
52694573 | instruction | 0 | 96,878 | 15 | 193,756 |
"Correct Solution:
```
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0203
"""
import sys
from sys import stdin
from collections import deque, defaultdict
input = stdin.readline
def solve(field):
BLANK, OBSTACLE, JUMP = 0, 1, 2
ans = 0 # ??????????????°???????????°
# dy = [1, 1, 1]
dx = [0, -1, 1] # ?????????????????????????????????????§???????
x_limit = len(field[0])
y_limit = len(field)
path = defaultdict(int) # ??????????????????????????°???????????°????????????'x???_y???'???????????????
Q = deque() # ?????§??????????????????????????¨??????????????\???
# ???????????§??????????????§????????´????????¢???????????\??????????????????
for x, m in enumerate(field[0]):
if m == BLANK: # ?????????????????°?????´?????????????????????????????????
k = '{}_{}'.format(x, 0)
Q.append((x, 0))
path[k] = 1
while Q:
cx, cy = Q.popleft() # ?????¨??°?????§?¨?
k = '{}_{}'.format(cx, cy)
num = path.pop(k) # ????????§?¨?????????????????????°
if field[cy][cx] == OBSTACLE: # ?????£????????§?????°??????????????????????????±????????????????????????????????§?????£?????????????????
continue
elif field[cy][cx] == JUMP: # ?????£????????§?????°?????????????????£????????°
if cy+2 > y_limit-1: # ?????£???????????????????¶?????????´??????OK??¨?????????
ans += num
else:
k = '{}_{}'.format(cx, cy+2)
if not path[k]:
Q.append((cx, cy+2))
path[k] += num
continue
elif cy == y_limit -1:
ans += num
continue
for i in range(3): # ?????????3???len(dy)?????????
nx = cx + dx[i] # ?????°????????§?¨?
ny = cy + 1 # ??????+1????????§???dy[i]??¨?????????????????????OK
if 0<= nx < x_limit:
if field[ny][nx] == JUMP and dx[i] == 0: # ?????£????????°????????£??????????????\????????´???
if ny+2 > y_limit - 1:
ans += num
else:
k = '{}_{}'.format(nx, ny+2)
if not path[k]:
Q.append((nx, ny+2))
path[k] += num
elif field[ny][nx] == BLANK:
if (ny >= y_limit - 1):
ans += num
else:
k = '{}_{}'.format(nx, ny)
if not path[k]:
Q.append((nx, ny))
path[k] += num
return ans
def main(args):
while True:
X, Y = map(int, input().strip().split())
if X == 0 and Y == 0:
break
field = []
for _ in range(Y):
temp = [int(x) for x in input().strip().split()]
field.append(temp)
result = solve(field)
print(result)
if __name__ == '__main__':
main(sys.argv[1:])
``` | output | 1 | 96,878 | 15 | 193,757 |
Provide a correct Python 3 solution for this coding contest problem.
Yukiya, the owner of Aizuyama Ski Resort, has prepared a course for advanced skiers with obstacles and jumping hills. There are various ways to slide on the course, and users who can slide in all patterns during the season will be given a gift.
Let's create a program for the oil tree shop that outputs the number of patterns of how to slide based on the floor plan of the course.
<image>
The course is represented by a grid of X x Y squares as shown above. It is assumed that the origin is at the upper left, the x coordinate increases as it goes to the right, and the y coordinate increases as it goes down.
Each gliding pattern starts at the highest point (y = 1, but without obstacles) and progresses towards the goal (y = Y). A runner in a grid square (x, y) can move to either (x − 1, y + 1), (x, y + 1), or (x + 1, y + 1). I will. There are obstacles and jumping platforms in the squares, and you cannot enter the squares with obstacles, and when you enter the squares with jumping platforms, you will move to (x, y + 2). However, there is no jumping platform in the highest cell (the cell with y = 1), and when entering a cell with a jumping platform, you can only enter from the cell with the same x coordinate. Starting from the top of the course (y = 1) and crossing the bottom without deviating from the course (y ≥ Y), it is considered as one way of sliding and ends.
Create a program that takes the course information as input and outputs the total number of slips.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
X Y
c11 c21 ... cX1
c12 c22 ... cX2
::
c1Y c2Y ... cXY
The first line gives the course size X, Y (1 ≤ X, Y ≤ 15). Course information is given in the Y line that follows. cij (one of 0, 1, or 2) is an integer that represents the information of the squares of x = i, y = j, where 0 is a movable square, 1 is a square with an obstacle, and 2 is a square with a jumping platform. Represents.
The number of datasets does not exceed 50.
Output
For each input dataset, the number of patterns of how to slide the course is output on one line.
Example
Input
5 5
0 0 0 0 1
2 1 0 2 0
1 0 0 1 1
0 2 1 2 0
0 1 0 0 0
5 5
0 0 1 0 0
2 1 0 2 0
1 0 0 1 1
0 2 1 2 0
0 1 0 0 0
15 15
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0
Output
8
6
52694573 | instruction | 0 | 96,879 | 15 | 193,758 |
"Correct Solution:
```
while True:
X, Y = map(int, input().split())
if X == 0:
break
a = [[1]+list(map(int, input().split()))+[1] for _ in [0]*Y] + [[0]*(X+2)]
dp = [list(map(lambda x: x^1, a[0]))] + [[0]*(X+2) for _ in [0]*Y]
for y in range(Y-1):
for x, (square, cnt) in enumerate(zip(a[y][1:], dp[y][1:-1]), start=1):
if square == 0:
for tx in range(x-1, x+2):
if a[y+1][tx] == 0 or a[y+1][tx] == 2 and x == tx:
dp[y+1][tx] += cnt
elif square == 2:
dp[y+2][x] += cnt
for x in range(1, X+1):
if a[Y-1][x] != 1:
dp[Y][x] += dp[Y-1][x]
print(sum(dp[-1]))
``` | output | 1 | 96,879 | 15 | 193,759 |
Provide a correct Python 3 solution for this coding contest problem.
Yukiya, the owner of Aizuyama Ski Resort, has prepared a course for advanced skiers with obstacles and jumping hills. There are various ways to slide on the course, and users who can slide in all patterns during the season will be given a gift.
Let's create a program for the oil tree shop that outputs the number of patterns of how to slide based on the floor plan of the course.
<image>
The course is represented by a grid of X x Y squares as shown above. It is assumed that the origin is at the upper left, the x coordinate increases as it goes to the right, and the y coordinate increases as it goes down.
Each gliding pattern starts at the highest point (y = 1, but without obstacles) and progresses towards the goal (y = Y). A runner in a grid square (x, y) can move to either (x − 1, y + 1), (x, y + 1), or (x + 1, y + 1). I will. There are obstacles and jumping platforms in the squares, and you cannot enter the squares with obstacles, and when you enter the squares with jumping platforms, you will move to (x, y + 2). However, there is no jumping platform in the highest cell (the cell with y = 1), and when entering a cell with a jumping platform, you can only enter from the cell with the same x coordinate. Starting from the top of the course (y = 1) and crossing the bottom without deviating from the course (y ≥ Y), it is considered as one way of sliding and ends.
Create a program that takes the course information as input and outputs the total number of slips.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
X Y
c11 c21 ... cX1
c12 c22 ... cX2
::
c1Y c2Y ... cXY
The first line gives the course size X, Y (1 ≤ X, Y ≤ 15). Course information is given in the Y line that follows. cij (one of 0, 1, or 2) is an integer that represents the information of the squares of x = i, y = j, where 0 is a movable square, 1 is a square with an obstacle, and 2 is a square with a jumping platform. Represents.
The number of datasets does not exceed 50.
Output
For each input dataset, the number of patterns of how to slide the course is output on one line.
Example
Input
5 5
0 0 0 0 1
2 1 0 2 0
1 0 0 1 1
0 2 1 2 0
0 1 0 0 0
5 5
0 0 1 0 0
2 1 0 2 0
1 0 0 1 1
0 2 1 2 0
0 1 0 0 0
15 15
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0
Output
8
6
52694573 | instruction | 0 | 96,880 | 15 | 193,760 |
"Correct Solution:
```
while(True):
X,Y = map(int, input().split())
if X==0 and Y==0:
break
ar = [list(map(int, input().split())) for _ in range(Y)]
ar.append([0]*X)
br = [[0]*X for _ in range(Y+1)]
for j in range(X):
if ar[-2][j] != 1:
br[-2][j] = 1
br[-1][j] = 1
for i in range(Y-2,-1,-1):
for j in range(X):
if j-1 >= 0 and ar[i][j] != 2 and ar[i+1][j-1] == 0: br[i][j] += br[i+1][j-1]
if j+1 < X and ar[i][j] != 2 and ar[i+1][j+1] == 0: br[i][j] += br[i+1][j+1]
if ar[i][j] != 2 and ar[i+1][j] != 1: br[i][j] += br[i+1][j]
if ar[i][j] == 2 and ar[i+2][j] != 1: br[i][j] += br[i+2][j]
for j in range(X):
if ar[i][j] == 1: br[i][j] = 0
print(sum(br[0]))
``` | output | 1 | 96,880 | 15 | 193,761 |
Provide a correct Python 3 solution for this coding contest problem.
Yukiya, the owner of Aizuyama Ski Resort, has prepared a course for advanced skiers with obstacles and jumping hills. There are various ways to slide on the course, and users who can slide in all patterns during the season will be given a gift.
Let's create a program for the oil tree shop that outputs the number of patterns of how to slide based on the floor plan of the course.
<image>
The course is represented by a grid of X x Y squares as shown above. It is assumed that the origin is at the upper left, the x coordinate increases as it goes to the right, and the y coordinate increases as it goes down.
Each gliding pattern starts at the highest point (y = 1, but without obstacles) and progresses towards the goal (y = Y). A runner in a grid square (x, y) can move to either (x − 1, y + 1), (x, y + 1), or (x + 1, y + 1). I will. There are obstacles and jumping platforms in the squares, and you cannot enter the squares with obstacles, and when you enter the squares with jumping platforms, you will move to (x, y + 2). However, there is no jumping platform in the highest cell (the cell with y = 1), and when entering a cell with a jumping platform, you can only enter from the cell with the same x coordinate. Starting from the top of the course (y = 1) and crossing the bottom without deviating from the course (y ≥ Y), it is considered as one way of sliding and ends.
Create a program that takes the course information as input and outputs the total number of slips.
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by two lines of zeros. Each dataset is given in the following format:
X Y
c11 c21 ... cX1
c12 c22 ... cX2
::
c1Y c2Y ... cXY
The first line gives the course size X, Y (1 ≤ X, Y ≤ 15). Course information is given in the Y line that follows. cij (one of 0, 1, or 2) is an integer that represents the information of the squares of x = i, y = j, where 0 is a movable square, 1 is a square with an obstacle, and 2 is a square with a jumping platform. Represents.
The number of datasets does not exceed 50.
Output
For each input dataset, the number of patterns of how to slide the course is output on one line.
Example
Input
5 5
0 0 0 0 1
2 1 0 2 0
1 0 0 1 1
0 2 1 2 0
0 1 0 0 0
5 5
0 0 1 0 0
2 1 0 2 0
1 0 0 1 1
0 2 1 2 0
0 1 0 0 0
15 15
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0
Output
8
6
52694573 | instruction | 0 | 96,881 | 15 | 193,762 |
"Correct Solution:
```
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0203
"""
import sys
from sys import stdin
from collections import deque, defaultdict
input = stdin.readline
def solve(field):
BLANK, OBSTACLE, JUMP = 0, 1, 2
ans = 0 # ??????????????°???????????°
dy = [1, 1, 1] # ?????????????????????????????????????§???????
dx = [0, -1, 1]
x_limit = len(field[0])
y_limit = len(field)
path = defaultdict(int) # ??????????????????????????°???????????°????????????'x???_y???'???????????????
Q = deque()
for x, m in enumerate(field[0]):
if m == BLANK: # ?????????????????°?????´?????????????????????????????????
t = '{}_{}'.format(x, 0)
Q.append((x, 0))
path[t] = 1
if y_limit < 2:
return len(Q)
while Q:
cx, cy = Q.popleft() # ?????¨??°?????§?¨?
t = '{}_{}'.format(cx, cy)
num = path.pop(t)
if field[cy][cx] == OBSTACLE:
continue
elif field[cy][cx] == JUMP: # ?????£????????§?????°?????????????????£????????°
if cy+2 > y_limit-1:
ans += num
else:
t = '{}_{}'.format(cx, cy+2)
if not path[t]:
Q.append((cx, cy+2))
path[t] += num
continue
elif cy == y_limit -1:
ans += num
continue
for i in range(len(dx)):
nx = cx + dx[i] # ?????°????????§?¨?
ny = cy + dy[i]
if 0<= nx < x_limit:
if (ny >= y_limit - 1) and field[ny][nx] == BLANK:
ans += num
else:
if field[ny][nx] == JUMP and dx[i] == 0: # ?????£????????°????????£??????????????\????????´???
if ny+2 > y_limit - 1:
ans += num
else:
t = '{}_{}'.format(nx, ny+2)
if not path[t]:
Q.append((nx, ny+2))
path[t] += num
elif field[ny][nx] == BLANK:
t = '{}_{}'.format(nx, ny)
if not path[t]:
Q.append((nx, ny))
path[t] += num
return ans
def main(args):
while True:
X, Y = map(int, input().strip().split())
if X == 0 and Y == 0:
break
field = []
for _ in range(Y):
temp = [int(x) for x in input().strip().split()]
field.append(temp)
result = solve(field)
print(result)
if __name__ == '__main__':
main(sys.argv[1:])
``` | output | 1 | 96,881 | 15 | 193,763 |
Provide a correct Python 3 solution for this coding contest problem.
Bob is playing a popular game called "Dungeon". The game is played on a rectangular board consisting of W × H squares. Each square is identified with its column and row number, thus the square located in the x-th column and the y-th row is represented as (x, y). The left-most square in the top row is (0, 0) and the right-most square in the bottom row is (W-1, H-1).
Bob moves a character "BomBom" to clear the game. BomBom is initially located at (0, 0). The game is won if Bob successfully destroys all the enemy characters on the board by manipulating BomBom cleverly. The enemy characters are fixed on specific squares, and Bob can manipulate BomBom using the following two operations any number of times.
* One-square movement in the up, down, left, or right direction within the board
* Using a bomb, eliminate all the enemy characters that are located in the same column and row as that of BomBom
BomBom consumes a Cost when it moves from one square to another. BomBom can use a bomb any number of times without consuming a Cost. Use of a bomb has no effect on BomBom’s behavior and it can move even to a square where an enemy character is located.
Given the board size and enemy information, make a program to evaluate the minimum Cost BomBom consumes before it destroys all enemy characters.
Input
The input is given in the following format.
W H N
x_1 y_1
x_2 y_2
:
x_N y_N
The first line provides the number of squares in the horizontal direction W (1 ≤ W ≤ 105), in the vertical direction H (1 ≤ H ≤ 105), and the number of enemy characters N (1 ≤ N ≤ 105). Each of the subsequent N lines provides location information of the i-th enemy, column x_i (0 ≤ x_i ≤ W-1) and row y_i (0 ≤ y_i ≤ H-1). The number of enemy characters in a specific square can be either one or zero.
Output
Output the minimum Cost in a line.
Examples
Input
5 4 4
0 3
1 1
2 2
2 3
Output
2
Input
6 6 5
2 1
5 2
3 3
1 4
1 5
Output
4
Input
8 8 4
6 0
7 0
0 6
0 7
Output
0 | instruction | 0 | 96,890 | 15 | 193,780 |
"Correct Solution:
```
w, h, n = map(int, input().split())
xys = sorted([list(map(int, input().split())) for _ in range(n)])
y_max = [0]
for _, y in reversed(xys):
y_max.append(max(y_max[-1], y))
xs = [0] + [x for x, _ in xys]
print(min([xs[i] + y_max[n - i] for i in range(n + 1)]))
``` | output | 1 | 96,890 | 15 | 193,781 |
Provide a correct Python 3 solution for this coding contest problem.
Bob is playing a popular game called "Dungeon". The game is played on a rectangular board consisting of W × H squares. Each square is identified with its column and row number, thus the square located in the x-th column and the y-th row is represented as (x, y). The left-most square in the top row is (0, 0) and the right-most square in the bottom row is (W-1, H-1).
Bob moves a character "BomBom" to clear the game. BomBom is initially located at (0, 0). The game is won if Bob successfully destroys all the enemy characters on the board by manipulating BomBom cleverly. The enemy characters are fixed on specific squares, and Bob can manipulate BomBom using the following two operations any number of times.
* One-square movement in the up, down, left, or right direction within the board
* Using a bomb, eliminate all the enemy characters that are located in the same column and row as that of BomBom
BomBom consumes a Cost when it moves from one square to another. BomBom can use a bomb any number of times without consuming a Cost. Use of a bomb has no effect on BomBom’s behavior and it can move even to a square where an enemy character is located.
Given the board size and enemy information, make a program to evaluate the minimum Cost BomBom consumes before it destroys all enemy characters.
Input
The input is given in the following format.
W H N
x_1 y_1
x_2 y_2
:
x_N y_N
The first line provides the number of squares in the horizontal direction W (1 ≤ W ≤ 105), in the vertical direction H (1 ≤ H ≤ 105), and the number of enemy characters N (1 ≤ N ≤ 105). Each of the subsequent N lines provides location information of the i-th enemy, column x_i (0 ≤ x_i ≤ W-1) and row y_i (0 ≤ y_i ≤ H-1). The number of enemy characters in a specific square can be either one or zero.
Output
Output the minimum Cost in a line.
Examples
Input
5 4 4
0 3
1 1
2 2
2 3
Output
2
Input
6 6 5
2 1
5 2
3 3
1 4
1 5
Output
4
Input
8 8 4
6 0
7 0
0 6
0 7
Output
0 | instruction | 0 | 96,891 | 15 | 193,782 |
"Correct Solution:
```
W, H, N = map(int, input().split())
P = [list(map(int, input().split())) for i in range(N)]
P.sort()
st = []
for x, y in P:
while st and (st[-1][0] == x or st[-1][1] <= y):
st.pop()
st.append((x, y))
ans = 10**9
prv = 0
for x, y in st:
ans = min(ans, prv+y)
prv = x
ans = min(ans, prv)
print(ans)
``` | output | 1 | 96,891 | 15 | 193,783 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bob is playing a popular game called "Dungeon". The game is played on a rectangular board consisting of W × H squares. Each square is identified with its column and row number, thus the square located in the x-th column and the y-th row is represented as (x, y). The left-most square in the top row is (0, 0) and the right-most square in the bottom row is (W-1, H-1).
Bob moves a character "BomBom" to clear the game. BomBom is initially located at (0, 0). The game is won if Bob successfully destroys all the enemy characters on the board by manipulating BomBom cleverly. The enemy characters are fixed on specific squares, and Bob can manipulate BomBom using the following two operations any number of times.
* One-square movement in the up, down, left, or right direction within the board
* Using a bomb, eliminate all the enemy characters that are located in the same column and row as that of BomBom
BomBom consumes a Cost when it moves from one square to another. BomBom can use a bomb any number of times without consuming a Cost. Use of a bomb has no effect on BomBom’s behavior and it can move even to a square where an enemy character is located.
Given the board size and enemy information, make a program to evaluate the minimum Cost BomBom consumes before it destroys all enemy characters.
Input
The input is given in the following format.
W H N
x_1 y_1
x_2 y_2
:
x_N y_N
The first line provides the number of squares in the horizontal direction W (1 ≤ W ≤ 105), in the vertical direction H (1 ≤ H ≤ 105), and the number of enemy characters N (1 ≤ N ≤ 105). Each of the subsequent N lines provides location information of the i-th enemy, column x_i (0 ≤ x_i ≤ W-1) and row y_i (0 ≤ y_i ≤ H-1). The number of enemy characters in a specific square can be either one or zero.
Output
Output the minimum Cost in a line.
Examples
Input
5 4 4
0 3
1 1
2 2
2 3
Output
2
Input
6 6 5
2 1
5 2
3 3
1 4
1 5
Output
4
Input
8 8 4
6 0
7 0
0 6
0 7
Output
0
Submitted Solution:
```
class Node(object):#Nodeを扱うクラス
def __init__(self, name):
self.name = name
def getName(self):#Nodeの名前を返す
return self.name
def __str__(self):
return self.name
class Node_W(Node):#重さ付きNodeを扱うクラス
def __init__(self, name):
self.name = name
self.w = 0
def addWeight(self,weight):
self.w += weight
class Edge(object):#エッジを扱うクラス
def __init__(self, src, dest):
self.src = src
self.dest = dest
def getSource(self):#親Nodeを返す
return self.src
def getDestination(self):#子Nodeを返す
return self.dest
def __str__(self):
return self.src + "->" + self.dest
class Graph(object):
def __init__(self):
self.Nodes = []#グラフ上のNode
self.Edges = {}#グラフ上のエッジ親Nodeのキーに対して子Nodeのリストを返す
def addNode(self, node):#グラフにNodeを加える
if(node in self.Nodes):
raise ValueError("そのNodeはもうあるよ")
else:
self.Nodes.append(node)
self.Edges[node] = []#nodeの子Nodeのリスト
def addEdges(self, edge):#グラフ上にエッジを加える
src = edge.getSource()
dest = edge.getDestination()
if src not in self.Nodes or dest not in self.Nodes:
raise ValueError("そのNodeはグラフ上にありません")
else:
self.Edges[src].append(dest)
def getChildList(self,node):#nodeの子Nodeのリストを返す
return self.Edges[node]
def put_player(self, x, y, W, H, L):#x, yはplayerの座標, W, Hはx, y座標の限界,Lは受け取ったNode_W型を含むリスト
k = W - H
index = (H*y) + x + k*y
if index >= H*W:
raise ValueError("そんな座標はないよ")
else:
L[index].w = 1
def __str__(self):
s = ""
for src in self.Nodes:
for dest in self.Edges[src]:
s = s + src.getNode() + "->" + dest.getNode() + '\n'
return s
def ShowPath(path):#pathはNode_W型からなるリスト
s = ""
for nextNode in range(len(path)):
s = s + path[nextNode].getName() + "(" + str(path[nextNode].w) + ")"
if nextNode != len(path) - 1:
s = s + "->"
return s
all_path1 = []#すべての経路を保存する
count = 0
def all_search(g, start, end, path, all_path, toPrint = True):#グラフ上の全経路を保存する
path = path + [start]
if toPrint == True:
ShowPath(path)
all_path.append(path)
for child in g.getChildList(start):
if child not in path:#ループはしない
newpath = all_search(g,child,end,path,all_path,toPrint = True)
def make_field(W,H):
#W,Hはint型
k = 0
k = W - H
Nodes= [] #pointの要素数分だけNode_Wを作りリストに保存する
for i in range(0,W * H,1):
Nodes.append(Node_W(str(i)))
g = Graph()
for i in range(0,W*H, 1):#グラフ上にNodesで作ったNodeを追加する
g.addNode(Nodes[i])
for i in range(H):
for w in range(W):
num = (H*i) + w + k * i
if(i != H - 1):#この時は下につなげるNodeがある
g.addEdges(Edge(Nodes[num],Nodes[num + W]))
if(w != W - 1):#この時は横につなげるNodeがある
g.addEdges(Edge(Nodes[num], Nodes[num + 1]))
return g
class Player(object):
def __init__(self, x, y, L,g,W,H):#x,yはplayerを配置する座標, LはNode_W型を含むリスト,gはplayerを配置するField,W,Xはx座標y座標の限界
g.put_player(x,y,W,H,L)
class Main(Player):
def __init__(self,L,g,W,H):
g.put_player(0,0,W,H,L)
self.cost = 0
self.now_position = 0
self.W = W
self.H = H
self.L = L
def move(self,g, node):#gはgraph型,nodeはNode型,与えられたNodeへ進む
g.Nodes[self.now_position].w = 0
self.now_position = int(node.getName())
g.Nodes[self.now_position].w = 0
if(int(node.getName()) == 0):
self.cost += 0 #0番に移動する場合はコスト0
else:
self.cost += 1
def destroy(self, g):
h1 = self.W
h2 = self.W
mod = self.now_position % self.W
i = 1
j = 1
k = self.W - self.H
g.Nodes[self.now_position].w = 0
while(self.now_position - h1 >= 0):#現在位置の上の敵を消す
g.Nodes[self.now_position - h1].w = 0
h1 += self.W
while(self.now_position + h2 < self.H * self.W):#現在位置の下の敵を消す
g.Nodes[self.now_position + h2].w = 0
h2 += self.W
while((self.now_position - i) % self.W != self.W - 1 and self.now_position - i < self.H * self.W and self.now_position - i > 0):#現在位置の左の敵を消す
g.Nodes[self.now_position - i].w = 0
i += 1
while((self.now_position + j) % self.W != 0 and self.now_position + j < self.H * self.W and self.now_position + j > 0):#現在位置の右の敵を消す
g.Nodes[self.now_position + j].w = 0
j += 1
def ShowGraph(g,H,W):#gはgraph型
result = ""
k = W - H
for h in range(H):
for w in range(W):
result = result + g.Nodes[(H * h) + w + k*h].getName() + "(" + str(g.Nodes[(H*h) + w + k * h].w) + ")"
if(w != W - 1):
result = result + "->"
else:
result = result + '\n'
if (h != H -1):
for w in range(W):
t = int(g.Nodes[(H*h) + w + k * h].getName())
s = 0
while(t//10 != 0):
s += 1
t /= 10
result = result + "↓" + " " + " "*s
s = 0
if(w == W - 1):
result = result + '\n'
return result
def SearchWeight(g):#gはgraph型,graph上のNodeがすべて0ならTrue,それ以外ならFalseを返す
for i in range(len(g.Nodes)):
if g.Nodes[i].w == 1:
return False
return True
def test1():#グラフが正常につくられているかテスト
g = make_field(6,6)
start = g.Nodes[0]
end = g.Nodes[6*6 - 1]
all_path = []
all_search(g, start, end, [], all_path,toPrint = True )
main = Player(0,0,g.Nodes,g,6,6)
enemy1 = Player(1,1,g.Nodes,g, 6,6)
enemy2 = Player(5,5,g.Nodes,g, 6,6)
for i in range(len(all_path)):
print(ShowPath(all_path[i]))
print(str(i))
def test2():#正常に爆破ができるのかを確かめるテスト
W, H = map(int, input().split())
g = make_field(W, H)
all_path = []
start = g.Nodes[0]
end = g.Nodes[W*H - 1]
main = Main(g.Nodes,g,W,H)
N = int(input())
for i in range(N):
x, y = map(int, input().split())
Player(x, y, g.Nodes,g,W,H)
all_search(g,start, end, [], all_path, toPrint = True)
print(ShowGraph(g, H, W))
main.move(g,g.Nodes[6])
main.destroy(g)
print("爆破!")
print(ShowGraph(g,H,W))
def test3():#グラフ上のある経路を正常に動くのかテスト
W, H = map(int, input().split())
g = make_field(W, H)
all_path = []
start = g.Nodes[0]
end = g.Nodes[W*H - 1]
main = Main(g.Nodes,g,W,H)
N = int(input())
for i in range(N):
x, y = map(int, input().split())
Player(x, y, g.Nodes,g,W,H)
all_search(g,start, end, [], all_path, toPrint = True)
print(ShowPath(all_path[4]))
print()#改行
print(ShowGraph(g, H, W))
print()#改行
for path in (all_path[4]):
main.move(g,path)
print(str(path.getName())+"番に移動しました!")
print()#改行
print(ShowGraph(g, H, W))
print()
print("現在までのコスト :",str(main.cost))
print()#改行
for i in range(len(all_path)):
print(ShowPath(all_path[i]))
print(str(i))
def test4():#1つの経路で動くたびに爆発できるのかテスト
W, H = map(int, input().split())
g = make_field(W, H)
all_path = []
start = g.Nodes[0]
end = g.Nodes[W*H - 1]
main = Main(g.Nodes,g,W,H)
N = int(input())
for i in range(N):
x, y = map(int, input().split())
Player(x, y, g.Nodes,g,W,H)
all_search(g,start, end, [], all_path, toPrint = True)
print(ShowPath(all_path[4]))
print()#改行
print(ShowGraph(g, H, W))
print()#改行
for path in (all_path[4]):
main.move(g,path)
print(str(path.getName())+"番に移動しました!")
print()#改行
print(ShowGraph(g, H, W))
main.destroy(g)
print("爆破しました!")
print(ShowGraph(g, H, W))
print()
print("現在までのコスト :",str(main.cost))
print()#改行
def test5():#全経路に関して爆発を試す
W, H = map(int, input().split())
X = []
Y = []
g = make_field(W, H)
all_path = []
start = g.Nodes[0]
end = g.Nodes[W*H - 1]
N = int(input())
for i in range(N):
x, y = map(int, input().split())
X.append(x)
Y.append(y)
all_search(g,start, end, [], all_path, toPrint = True)
print()#改行
print(ShowGraph(g, H, W))
print()#改行
for root in all_path:
for i in range(N):
Player(X[i], Y[i], g.Nodes, g, W, H)
main = Main(g.Nodes,g,W,H)
for path in (root):
print(ShowPath(root))
main.move(g,path)
print(str(path.getName())+"番に移動しました!")
print()#改行
print(ShowGraph(g, H, W))
main.destroy(g)
print("爆破しました!")
print(ShowGraph(g, H, W))
if(SearchWeight(g) == True):
print("全滅や!")
else:
print("まだ敵がおるで!")
print()
print("現在までのコスト :",str(main.cost))
print()#改行
def test6():#全経路に関して爆発を試す
W, H = map(int, input().split())
X = []
Y = []
min = H*W #最小のコストを保存
g = make_field(W, H)
all_path = []
start = g.Nodes[0]
end = g.Nodes[W*H - 1]
N = int(input())
for i in range(N):
x, y = map(int, input().split())
X.append(x)
Y.append(y)
all_search(g,start, end, [], all_path, toPrint = True)
print()#改行
print(ShowGraph(g, H, W))
print()#改行
for root in all_path:
for i in range(N):
Player(X[i], Y[i], g.Nodes, g, W, H)
main = Main(g.Nodes,g,W,H)
for path in (root):
print(ShowPath(root))
main.move(g,path)
print(str(path.getName())+"番に移動しました!")
print()#改行
print(ShowGraph(g, H, W))
main.destroy(g)
print("爆破しました!")
print(ShowGraph(g, H, W))
if(SearchWeight(g) == True):
print("全滅や!")
if main.cost < min:
min = main.cost
break
else:
print("まだ敵がおるで!")
print()
print("現在までのコスト :",str(main.cost))
print()#改行
print("現在の最小コスト :",str(min))
def test7():
W, H, N = map(int, input().split())
X = []
Y = []
l = 0
min = H*W #最小のコストを保存
g = make_field(W, H)
all_path = []
start = g.Nodes[0]
end = g.Nodes[W*H - 1]
for i in range(N):
x, y = map(int, input().split())
X.append(x)
Y.append(y)
all_search(g,start, end, [], all_path, toPrint = False)
for root in all_path:
for i in range(N):
Player(X[i], Y[i], g.Nodes, g, W, H)
main = Main(g.Nodes,g,W,H)
for path in (root):
main.move(g,path)
main.destroy(g)
if(SearchWeight(g) == True):
if main.cost < min:
min = main.cost
l = root
break
print(str(min))
print(ShowPath(l))
for i in range(N):
Player(X[i], Y[i], g.Nodes, g, W, H)
main = Main(g.Nodes, g, W, H)
for path in (root):
print(ShowPath(root))
main.move(g,path)
print(str(path.getName())+"番に移動しました!")
print()#改行
print(ShowGraph(g, H, W))
main.destroy(g)
print("爆破しました!")
print(ShowGraph(g, H, W))
if(SearchWeight(g) == True):
print("全滅や!")
break
else:
print("まだ敵がおるで!")
print()
print("現在までのコスト :",str(main.cost))
print()#改行
def test8():
W, H, N = map(int, input().split())
X = []
Y = []
min = H*W #最小のコストを保存
g = make_field(W, H)
all_path = []
start = g.Nodes[0]
end = g.Nodes[W*H - 1]
for i in range(N):
x, y = map(int, input().split())
X.append(x)
Y.append(y)
all_search(g,start, end, [], all_path, toPrint = False)
for root in all_path:
for i in range(N):
Player(X[i], Y[i], g.Nodes, g, W, H)
main = Main(g.Nodes,g,W,H)
for path in (root):
main.move(g,path)
main.destroy(g)
if(SearchWeight(g) == True):
if main.cost < min:
min = main.cost
break
print(str(min))
test8()
``` | instruction | 0 | 96,892 | 15 | 193,784 |
No | output | 1 | 96,892 | 15 | 193,785 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bob is playing a popular game called "Dungeon". The game is played on a rectangular board consisting of W × H squares. Each square is identified with its column and row number, thus the square located in the x-th column and the y-th row is represented as (x, y). The left-most square in the top row is (0, 0) and the right-most square in the bottom row is (W-1, H-1).
Bob moves a character "BomBom" to clear the game. BomBom is initially located at (0, 0). The game is won if Bob successfully destroys all the enemy characters on the board by manipulating BomBom cleverly. The enemy characters are fixed on specific squares, and Bob can manipulate BomBom using the following two operations any number of times.
* One-square movement in the up, down, left, or right direction within the board
* Using a bomb, eliminate all the enemy characters that are located in the same column and row as that of BomBom
BomBom consumes a Cost when it moves from one square to another. BomBom can use a bomb any number of times without consuming a Cost. Use of a bomb has no effect on BomBom’s behavior and it can move even to a square where an enemy character is located.
Given the board size and enemy information, make a program to evaluate the minimum Cost BomBom consumes before it destroys all enemy characters.
Input
The input is given in the following format.
W H N
x_1 y_1
x_2 y_2
:
x_N y_N
The first line provides the number of squares in the horizontal direction W (1 ≤ W ≤ 105), in the vertical direction H (1 ≤ H ≤ 105), and the number of enemy characters N (1 ≤ N ≤ 105). Each of the subsequent N lines provides location information of the i-th enemy, column x_i (0 ≤ x_i ≤ W-1) and row y_i (0 ≤ y_i ≤ H-1). The number of enemy characters in a specific square can be either one or zero.
Output
Output the minimum Cost in a line.
Examples
Input
5 4 4
0 3
1 1
2 2
2 3
Output
2
Input
6 6 5
2 1
5 2
3 3
1 4
1 5
Output
4
Input
8 8 4
6 0
7 0
0 6
0 7
Output
0
Submitted Solution:
```
w, h, n = map(int, input().split())
a = []
for _ in range(n):
a.append(tuple(map(int, input().split())))
mins = min(w, h)
i = 0
while i < mins:
mins = min(mins, i + max((j[0] > i) * j[1] for j in a))
i += 1
print(mins)
``` | instruction | 0 | 96,893 | 15 | 193,786 |
No | output | 1 | 96,893 | 15 | 193,787 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bob is playing a popular game called "Dungeon". The game is played on a rectangular board consisting of W × H squares. Each square is identified with its column and row number, thus the square located in the x-th column and the y-th row is represented as (x, y). The left-most square in the top row is (0, 0) and the right-most square in the bottom row is (W-1, H-1).
Bob moves a character "BomBom" to clear the game. BomBom is initially located at (0, 0). The game is won if Bob successfully destroys all the enemy characters on the board by manipulating BomBom cleverly. The enemy characters are fixed on specific squares, and Bob can manipulate BomBom using the following two operations any number of times.
* One-square movement in the up, down, left, or right direction within the board
* Using a bomb, eliminate all the enemy characters that are located in the same column and row as that of BomBom
BomBom consumes a Cost when it moves from one square to another. BomBom can use a bomb any number of times without consuming a Cost. Use of a bomb has no effect on BomBom’s behavior and it can move even to a square where an enemy character is located.
Given the board size and enemy information, make a program to evaluate the minimum Cost BomBom consumes before it destroys all enemy characters.
Input
The input is given in the following format.
W H N
x_1 y_1
x_2 y_2
:
x_N y_N
The first line provides the number of squares in the horizontal direction W (1 ≤ W ≤ 105), in the vertical direction H (1 ≤ H ≤ 105), and the number of enemy characters N (1 ≤ N ≤ 105). Each of the subsequent N lines provides location information of the i-th enemy, column x_i (0 ≤ x_i ≤ W-1) and row y_i (0 ≤ y_i ≤ H-1). The number of enemy characters in a specific square can be either one or zero.
Output
Output the minimum Cost in a line.
Examples
Input
5 4 4
0 3
1 1
2 2
2 3
Output
2
Input
6 6 5
2 1
5 2
3 3
1 4
1 5
Output
4
Input
8 8 4
6 0
7 0
0 6
0 7
Output
0
Submitted Solution:
```
class Node(object):#Nodeを扱うクラス
def __init__(self, name):
self.name = name
def getName(self):#Nodeの名前を返す
return self.name
def __str__(self):
return self.name
class Node_W(Node):#重さ付きNodeを扱うクラス
def __init__(self, name):
self.name = name
self.w = 0
def addWeight(self,weight):
self.w += weight
class Edge(object):#エッジを扱うクラス
def __init__(self, src, dest):
self.src = src
self.dest = dest
def getSource(self):#親Nodeを返す
return self.src
def getDestination(self):#子Nodeを返す
return self.dest
def __str__(self):
return self.src + "->" + self.dest
class Graph(object):
def __init__(self):
self.Nodes = []#グラフ上のNode
self.Edges = {}#グラフ上のエッジ親Nodeのキーに対して子Nodeのリストを返す
def addNode(self, node):#グラフにNodeを加える
if(node in self.Nodes):
raise ValueError("そのNodeはもうあるよ")
else:
self.Nodes.append(node)
self.Edges[node] = []#nodeの子Nodeのリスト
def addEdges(self, edge):#グラフ上にエッジを加える
src = edge.getSource()
dest = edge.getDestination()
if src not in self.Nodes or dest not in self.Nodes:
raise ValueError("そのNodeはグラフ上にありません")
else:
self.Edges[src].append(dest)
def getChildList(self,node):#nodeの子Nodeのリストを返す
return self.Edges[node]
def put_player(self, x, y, W, H, L):#x, yはplayerの座標, W, Hはx, y座標の限界,Lは受け取ったNode_W型を含むリスト
k = W - H
index = (H*y) + x + k*y
if index >= H*W:
raise ValueError("そんな座標はないよ")
else:
L[index].w = 1
def __str__(self):
s = ""
for src in self.Nodes:
for dest in self.Edges[src]:
s = s + src.getNode() + "->" + dest.getNode() + '\n'
return s
def ShowPath(path):#pathはNode_W型からなるリスト
s = ""
for nextNode in range(len(path)):
s = s + path[nextNode].getName() + "(" + str(path[nextNode].w) + ")"
if nextNode != len(path) - 1:
s = s + "->"
return s
all_path1 = []#すべての経路を保存する
count = 0
def all_search(g, start, end, path, all_path, toPrint = True):#グラフ上の全経路を保存する
path = path + [start]
if toPrint == True:
ShowPath(path)
all_path.append(path)
for child in g.getChildList(start):
if child not in path:#ループはしない
newpath = all_search(g,child,end,path,all_path,toPrint = True)
def make_field(W,H):
#W,Hはint型
k = 0
if (W < H):
k = W - H
elif(W > H):
k = W - H
Nodes= [] #pointの要素数分だけNode_Wを作りリストに保存する
for i in range(0,W * H,1):
Nodes.append(Node_W(str(i)))
g = Graph()
for i in range(0,W*H, 1):#グラフ上にNodesで作ったNodeを追加する
g.addNode(Nodes[i])
for i in range(H):
for w in range(W):
num = (H*i) + w + k * i
if(i != H - 1):#この時は下につなげるNodeがある
g.addEdges(Edge(Nodes[num],Nodes[num + W]))
if(w != W - 1):#この時は横につなげるNodeがある
g.addEdges(Edge(Nodes[num], Nodes[num + 1]))
return g
class Player(object):
def __init__(self, x, y, L,g,W,H):#x,yはplayerを配置する座標, LはNode_W型を含むリスト,gはplayerを配置するField,W,Xはx座標y座標の限界
g.put_player(x,y,W,H,L)
class Main(Player):
def __init__(self,L,g,W,H):
g.put_player(0,0,W,H,L)
self.cost = 0
self.now_position = 0
self.W = W
self.H = H
self.L = L
def move(self,g, node):#gはgraph型,nodeはNode型,与えられたNodeへ進む
g.Nodes[self.now_position].w = 0
self.now_position = int(node.getName())
g.Nodes[self.now_position].w = 0
if(int(node.getName()) == 0):
self.cost += 0 #0番に移動する場合はコスト0
else:
self.cost += 1
def destroy(self, g):
h1 = self.H
h2 = self.H
mod = self.now_position % self.W
i = 1
j = 1
k = self.W - self.H
g.Nodes[self.now_position].w = 0
while(self.now_position - h1 >= 0):#現在位置の上の敵を消す
g.Nodes[self.now_position - h1].w = 0
h1 += self.H - k
while(self.now_position + h2 < self.H * self.W):#現在位置の下の敵を消す
g.Nodes[self.now_position + h2].w = 0
h2 += self.H + k
while((self.now_position - i) % self.W != self.W - 1 and self.now_position - i < self.H * self.W and self.now_position - i > 0):#現在位置の左の敵を消す
g.Nodes[self.now_position - i].w = 0
i += 1
while((self.now_position + j) % self.W != 0 and self.now_position + j < self.H * self.W and self.now_position + j > 0):#現在位置の右の敵を消す
g.Nodes[self.now_position + j].w = 0
j += 1
def ShowGraph(g,H,W):#gはgraph型
result = ""
k = W - H
for h in range(H):
for w in range(W):
result = result + g.Nodes[(H * h) + w + k*h].getName() + "(" + str(g.Nodes[(H*h) + w + k * h].w) + ")"
if(w != W - 1):
result = result + "->"
else:
result = result + '\n'
if (h != H -1):
for w in range(W):
t = int(g.Nodes[(H*h) + w + k * h].getName())
s = 0
while(t//10 != 0):
s += 1
t /= 10
result = result + "↓" + " " + " "*s
s = 0
if(w == W - 1):
result = result + '\n'
return result
def SearchWeight(g):#gはgraph型,graph上のNodeがすべて0ならTrue,それ以外ならFalseを返す
for i in range(len(g.Nodes)):
if g.Nodes[i].w == 1:
return False
return True
def test1():#グラフが正常につくられているかテスト
g = make_field(6,6)
start = g.Nodes[0]
end = g.Nodes[6*6 - 1]
all_path = []
all_search(g, start, end, [], all_path,toPrint = True )
main = Player(0,0,g.Nodes,g,6,6)
enemy1 = Player(1,1,g.Nodes,g, 6,6)
enemy2 = Player(5,5,g.Nodes,g, 6,6)
for i in range(len(all_path)):
print(ShowPath(all_path[i]))
print(str(i))
def test2():#正常に爆破ができるのかを確かめるテスト
W, H = map(int, input().split())
g = make_field(W, H)
all_path = []
start = g.Nodes[0]
end = g.Nodes[W*H - 1]
main = Main(g.Nodes,g,W,H)
N = int(input())
for i in range(N):
x, y = map(int, input().split())
Player(x, y, g.Nodes,g,W,H)
all_search(g,start, end, [], all_path, toPrint = True)
print(ShowGraph(g, H, W))
main.move(g,g.Nodes[6])
main.destroy(g)
print("爆破!")
print(ShowGraph(g,H,W))
def test3():#グラフ上のある経路を正常に動くのかテスト
W, H = map(int, input().split())
g = make_field(W, H)
all_path = []
start = g.Nodes[0]
end = g.Nodes[W*H - 1]
main = Main(g.Nodes,g,W,H)
N = int(input())
for i in range(N):
x, y = map(int, input().split())
Player(x, y, g.Nodes,g,W,H)
all_search(g,start, end, [], all_path, toPrint = True)
print(ShowPath(all_path[4]))
print()#改行
print(ShowGraph(g, H, W))
print()#改行
for path in (all_path[4]):
main.move(g,path)
print(str(path.getName())+"番に移動しました!")
print()#改行
print(ShowGraph(g, H, W))
print()
print("現在までのコスト :",str(main.cost))
print()#改行
for i in range(len(all_path)):
print(ShowPath(all_path[i]))
print(str(i))
def test4():#1つの経路で動くたびに爆発できるのかテスト
W, H = map(int, input().split())
g = make_field(W, H)
all_path = []
start = g.Nodes[0]
end = g.Nodes[W*H - 1]
main = Main(g.Nodes,g,W,H)
N = int(input())
for i in range(N):
x, y = map(int, input().split())
Player(x, y, g.Nodes,g,W,H)
all_search(g,start, end, [], all_path, toPrint = True)
print(ShowPath(all_path[4]))
print()#改行
print(ShowGraph(g, H, W))
print()#改行
for path in (all_path[4]):
main.move(g,path)
print(str(path.getName())+"番に移動しました!")
print()#改行
print(ShowGraph(g, H, W))
main.destroy(g)
print("爆破しました!")
print(ShowGraph(g, H, W))
print()
print("現在までのコスト :",str(main.cost))
print()#改行
def test5():#全経路に関して爆発を試す
W, H = map(int, input().split())
X = []
Y = []
g = make_field(W, H)
all_path = []
start = g.Nodes[0]
end = g.Nodes[W*H - 1]
N = int(input())
for i in range(N):
x, y = map(int, input().split())
X.append(x)
Y.append(y)
all_search(g,start, end, [], all_path, toPrint = True)
print()#改行
print(ShowGraph(g, H, W))
print()#改行
for root in all_path:
for i in range(N):
Player(X[i], Y[i], g.Nodes, g, W, H)
main = Main(g.Nodes,g,W,H)
for path in (root):
print(ShowPath(root))
main.move(g,path)
print(str(path.getName())+"番に移動しました!")
print()#改行
print(ShowGraph(g, H, W))
main.destroy(g)
print("爆破しました!")
print(ShowGraph(g, H, W))
if(SearchWeight(g) == True):
print("全滅や!")
else:
print("まだ敵がおるで!")
print()
print("現在までのコスト :",str(main.cost))
print()#改行
def test6():#全経路に関して爆発を試す
W, H = map(int, input().split())
X = []
Y = []
min = H*W #最小のコストを保存
g = make_field(W, H)
all_path = []
start = g.Nodes[0]
end = g.Nodes[W*H - 1]
N = int(input())
for i in range(N):
x, y = map(int, input().split())
X.append(x)
Y.append(y)
all_search(g,start, end, [], all_path, toPrint = True)
print()#改行
print(ShowGraph(g, H, W))
print()#改行
for root in all_path:
for i in range(N):
Player(X[i], Y[i], g.Nodes, g, W, H)
main = Main(g.Nodes,g,W,H)
for path in (root):
print(ShowPath(root))
main.move(g,path)
print(str(path.getName())+"番に移動しました!")
print()#改行
print(ShowGraph(g, H, W))
main.destroy(g)
print("爆破しました!")
print(ShowGraph(g, H, W))
if(SearchWeight(g) == True):
print("全滅や!")
if main.cost < min:
min = main.cost
break
else:
print("まだ敵がおるで!")
print()
print("現在までのコスト :",str(main.cost))
print()#改行
print("現在の最小コスト :",str(min))
def test7():
W, H, N = map(int, input().split())
X = []
Y = []
l = 0
min = H*W #最小のコストを保存
g = make_field(W, H)
all_path = []
start = g.Nodes[0]
end = g.Nodes[W*H - 1]
for i in range(N):
x, y = map(int, input().split())
X.append(x)
Y.append(y)
all_search(g,start, end, [], all_path, toPrint = False)
for root in all_path:
for i in range(N):
Player(X[i], Y[i], g.Nodes, g, W, H)
main = Main(g.Nodes,g,W,H)
for path in (root):
main.move(g,path)
main.destroy(g)
if(SearchWeight(g) == True):
if main.cost < min:
min = main.cost
l = root
break
print(str(min))
print(ShowPath(l))
for i in range(N):
Player(X[i], Y[i], g.Nodes, g, W, H)
main = Main(g.Nodes, g, W, H)
for path in (root):
print(ShowPath(root))
main.move(g,path)
print(str(path.getName())+"番に移動しました!")
print()#改行
print(ShowGraph(g, H, W))
main.destroy(g)
print("爆破しました!")
print(ShowGraph(g, H, W))
if(SearchWeight(g) == True):
print("全滅や!")
break
else:
print("まだ敵がおるで!")
print()
print("現在までのコスト :",str(main.cost))
print()#改行
def test8():
W, H, N = map(int, input().split())
X = []
Y = []
min = H*W #最小のコストを保存
g = make_field(W, H)
all_path = []
start = g.Nodes[0]
end = g.Nodes[W*H - 1]
for i in range(N):
x, y = map(int, input().split())
X.append(x)
Y.append(y)
all_search(g,start, end, [], all_path, toPrint = False)
for root in all_path:
for i in range(N):
Player(X[i], Y[i], g.Nodes, g, W, H)
main = Main(g.Nodes,g,W,H)
for path in (root):
main.move(g,path)
main.destroy(g)
if(SearchWeight(g) == True):
if main.cost < min:
min = main.cost
break
print(str(min))
test8()
``` | instruction | 0 | 96,894 | 15 | 193,788 |
No | output | 1 | 96,894 | 15 | 193,789 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bob is playing a popular game called "Dungeon". The game is played on a rectangular board consisting of W × H squares. Each square is identified with its column and row number, thus the square located in the x-th column and the y-th row is represented as (x, y). The left-most square in the top row is (0, 0) and the right-most square in the bottom row is (W-1, H-1).
Bob moves a character "BomBom" to clear the game. BomBom is initially located at (0, 0). The game is won if Bob successfully destroys all the enemy characters on the board by manipulating BomBom cleverly. The enemy characters are fixed on specific squares, and Bob can manipulate BomBom using the following two operations any number of times.
* One-square movement in the up, down, left, or right direction within the board
* Using a bomb, eliminate all the enemy characters that are located in the same column and row as that of BomBom
BomBom consumes a Cost when it moves from one square to another. BomBom can use a bomb any number of times without consuming a Cost. Use of a bomb has no effect on BomBom’s behavior and it can move even to a square where an enemy character is located.
Given the board size and enemy information, make a program to evaluate the minimum Cost BomBom consumes before it destroys all enemy characters.
Input
The input is given in the following format.
W H N
x_1 y_1
x_2 y_2
:
x_N y_N
The first line provides the number of squares in the horizontal direction W (1 ≤ W ≤ 105), in the vertical direction H (1 ≤ H ≤ 105), and the number of enemy characters N (1 ≤ N ≤ 105). Each of the subsequent N lines provides location information of the i-th enemy, column x_i (0 ≤ x_i ≤ W-1) and row y_i (0 ≤ y_i ≤ H-1). The number of enemy characters in a specific square can be either one or zero.
Output
Output the minimum Cost in a line.
Examples
Input
5 4 4
0 3
1 1
2 2
2 3
Output
2
Input
6 6 5
2 1
5 2
3 3
1 4
1 5
Output
4
Input
8 8 4
6 0
7 0
0 6
0 7
Output
0
Submitted Solution:
```
class Node(object):#Nodeを扱うクラス
def __init__(self, name):
self.name = name
def getName(self):#Nodeの名前を返す
return self.name
def __str__(self):
return self.name
class Node_W(Node):#重さ付きNodeを扱うクラス
def __init__(self, name):
self.name = name
self.w = 0
def addWeight(self,weight):
self.w += weight
class Edge(object):#エッジを扱うクラス
def __init__(self, src, dest):
self.src = src
self.dest = dest
def getSource(self):#親Nodeを返す
return self.src
def getDestination(self):#子Nodeを返す
return self.dest
def __str__(self):
return self.src + "->" + self.dest
class Graph(object):
def __init__(self):
self.Nodes = []#グラフ上のNode
self.Edges = {}#グラフ上のエッジ親Nodeのキーに対して子Nodeのリストを返す
def addNode(self, node):#グラフにNodeを加える
if(node in self.Nodes):
raise ValueError("そのNodeはもうあるよ")
else:
self.Nodes.append(node)
self.Edges[node] = []#nodeの子Nodeのリスト
def addEdges(self, edge):#グラフ上にエッジを加える
src = edge.getSource()
dest = edge.getDestination()
if src not in self.Nodes or dest not in self.Nodes:
raise ValueError("そのNodeはグラフ上にありません")
else:
self.Edges[src].append(dest)
def getChildList(self,node):#nodeの子Nodeのリストを返す
return self.Edges[node]
def put_player(self, x, y, W, H, L):#x, yはplayerの座標, W, Hはx, y座標の限界,Lは受け取ったNode_W型を含むリスト
index = (H*y) + x
if index >= H*W:
raise ValueError("そんな座標はないよ")
else:
L[index].w = 1
def __str__(self):
s = ""
for src in self.Nodes:
for dest in self.Edges[src]:
s = s + src.getNode() + "->" + dest.getNode() + '\n'
return s
def ShowPath(path):#pathはNode_W型からなるリスト
s = ""
for nextNode in range(len(path)):
s = s + path[nextNode].getName() + "(" + str(path[nextNode].w) + ")"
if nextNode != len(path) - 1:
s = s + "->"
return s
all_path1 = []#すべての経路を保存する
count = 0
def all_search(g, start, end, path, all_path, toPrint = True):#グラフ上の全経路を保存する
path = path + [start]
if toPrint == True:
ShowPath(path)
all_path.append(path)
for child in g.getChildList(start):
if child not in path:#ループはしない
newpath = all_search(g,child,end,path,all_path,toPrint = True)
def make_field(W,H):
#W,Hはint型
point = [[0 for i in range(H)] for j in range(W)]
for x in range(W):
for y in range(H):
point[x][y] = 0
Nodes= [] #pointの要素数分だけNode_Wを作りリストに保存する
for i in range(0,W * H,1):
Nodes.append(Node_W(str(i)))
g = Graph()
for i in range(0,W*H, 1):#グラフ上にNodesで作ったNodeを追加する
g.addNode(Nodes[i])
for i in range(H):
for w in range(W):
num = (H*i) + w
if(i != H - 1):#この時は下につなげるNodeがある
g.addEdges(Edge(Nodes[num],Nodes[num + W]))
if(w != W - 1):#この時は横につなげるNodeがある
g.addEdges(Edge(Nodes[num], Nodes[num + 1]))
return g
class Player(object):
def __init__(self, x, y, L,g,W,H):#x,yはplayerを配置する座標, LはNode_W型を含むリスト,gはplayerを配置するField,W,Xはx座標y座標の限界
g.put_player(x,y,W,H,L)
class Main(Player):
def __init__(self,L,g,W,H):
g.put_player(0,0,W,H,L)
self.cost = 0
self.now_position = 0
self.W = W
self.H = H
self.L = L
def move(self,g, node):#gはgraph型,nodeはNode型,与えられたNodeへ進む
g.Nodes[self.now_position].w = 0
self.now_position = int(node.getName())
g.Nodes[self.now_position].w = 1
if(int(node.getName()) == 0):
self.cost += 0 #0番に移動する場合はコスト0
else:
self.cost += 1
def destroy(self, g):
h1 = self.H
h2 = self.H
mod = self.now_position % self.W
i = 1
j = 1
g.Nodes[self.now_position].w = 0
while(self.now_position - h1 >= 0):#現在位置の上の敵を消す
g.Nodes[self.now_position - h1].w = 0
h1 += self.H
while(self.now_position + h2 < self.H * self.W):#現在位置の下の敵を消す
g.Nodes[self.now_position + h2].w = 0
h2 += self.H
while((self.now_position - i) % self.W != self.W - 1 and self.now_position - i < self.H * self.W):#現在位置の左の敵を消す
g.Nodes[self.now_position - i].w = 0
i += 1
while((self.now_position + j) % self.W != 0 and self.now_position + j < self.H * self.W):#現在位置の右の敵を消す
g.Nodes[self.now_position + j].w = 0
j += 1
def ShowGraph(g,H,W):#gはgraph型
result = ""
for h in range(H):
for w in range(W):
result = result + g.Nodes[(H * h) + w].getName() + "(" + str(g.Nodes[(H*h) + w].w) + ")"
if(w != W - 1):
result = result + "->"
else:
result = result + '\n'
if (h != H -1):
for w in range(W):
k = int(g.Nodes[(H*h) + w].getName())
s = 0
while(k//10 != 0):
s += 1
k /= 10
result = result + "↓" + " " + " "*s
s = 0
if(w == W - 1):
result = result + '\n'
return result
def SearchWeight(g):#gはgraph型,graph上のNodeがすべて0ならTrue,それ以外ならFalseを返す
for i in range(len(g.Nodes)):
if g.Nodes[i].w == 1:
return False
return True
def test7():
W, H, N = map(int, input().split())
X = []
Y = []
min = H*W #最小のコストを保存
g = make_field(W, H)
all_path = []
start = g.Nodes[0]
end = g.Nodes[W*H - 1]
for i in range(N):
x, y = map(int, input().split())
X.append(x)
Y.append(y)
all_search(g,start, end, [], all_path, toPrint = False)
for root in all_path:
for i in range(N):
Player(X[i], Y[i], g.Nodes, g, W, H)
main = Main(g.Nodes,g,W,H)
for path in (root):
main.move(g,path)
main.destroy(g)
if(SearchWeight(g) == True):
if main.cost < min:
min = main.cost
break
print(str(min))
test7()
``` | instruction | 0 | 96,895 | 15 | 193,790 |
No | output | 1 | 96,895 | 15 | 193,791 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?
The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.
Input
The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 105, 1 ≤ n ≤ 2000).
Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≤ ri ≤ h, 1 ≤ ci ≤ w) — the number of the row and column of the i-th cell.
It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.
Output
Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7.
Examples
Input
3 4 2
2 2
2 3
Output
2
Input
100 100 3
15 16
16 15
99 88
Output
545732279 | instruction | 0 | 97,409 | 15 | 194,818 |
Tags: combinatorics, dp, math, number theory
Correct Solution:
```
fact = [1]
fTQJsiXxvUFMlBVGazWH = int
fTQJsiXxvUFMlBVGazWp = map
fTQJsiXxvUFMlBVGazWC = input
fTQJsiXxvUFMlBVGazWn = range
fTQJsiXxvUFMlBVGazWg = max
fTQJsiXxvUFMlBVGazWo = pow
fTQJsiXxvUFMlBVGazWu = tuple
fTQJsiXxvUFMlBVGazWI = print
rfact = [1]
MOD = fTQJsiXxvUFMlBVGazWH(1e9)+7
n, m, k = fTQJsiXxvUFMlBVGazWp(
fTQJsiXxvUFMlBVGazWH, fTQJsiXxvUFMlBVGazWC().split())
for i in fTQJsiXxvUFMlBVGazWn(1, fTQJsiXxvUFMlBVGazWg(2*n, 2*m)+2):
fact += [fact[-1]*i % MOD]
rfact += [rfact[-1]*fTQJsiXxvUFMlBVGazWo(i, MOD-2, MOD) % MOD]
def cmb(n, k):
return fact[n]*rfact[k]*rfact[n-k] % MOD
points = [fTQJsiXxvUFMlBVGazWu(fTQJsiXxvUFMlBVGazWp(
fTQJsiXxvUFMlBVGazWH, fTQJsiXxvUFMlBVGazWC().split()))for i in fTQJsiXxvUFMlBVGazWn(k)]
points += [(n, m)]
points.sort()
dp = []
for i in fTQJsiXxvUFMlBVGazWn(k+1):
tmp = cmb(points[i][0]+points[i][1]-2, points[i][0]-1)
for j in fTQJsiXxvUFMlBVGazWn(i):
if points[j][0] <= points[i][0]and points[j][1] <= points[i][1]:
tmp -= (dp[j]*cmb(points[i][0]-points[j][0]+points[i]
[1]-points[j][1], points[i][1]-points[j][1])) % MOD
tmp += MOD
tmp %= MOD
dp += [tmp]
fTQJsiXxvUFMlBVGazWI(dp[k])
``` | output | 1 | 97,409 | 15 | 194,819 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?
The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.
Input
The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 105, 1 ≤ n ≤ 2000).
Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≤ ri ≤ h, 1 ≤ ci ≤ w) — the number of the row and column of the i-th cell.
It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.
Output
Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7.
Examples
Input
3 4 2
2 2
2 3
Output
2
Input
100 100 3
15 16
16 15
99 88
Output
545732279 | instruction | 0 | 97,410 | 15 | 194,820 |
Tags: combinatorics, dp, math, number theory
Correct Solution:
```
MOD = 10**9+7
fact = [1]*200013
for i in range(1,200013):
fact[i] = (fact[i-1]*i)%MOD
inv = [1]*200013
for i in range(2,200013):
inv[i] = (-(MOD//i)*inv[MOD%i])%MOD
for i in range(2,200013):
inv[i] = (inv[i]*inv[i-1])%MOD
def combo(a,b):
return (fact[a]*inv[b]*inv[a-b])%MOD
h,w,n = map(int,input().split())
pt = []
for i in range(n):
r,c = map(int,input().split())
r,c = r-1,c-1
pt.append(r*w+c)
pt.append(h*w-1)
pt.sort()
dp = []
for i in range(n+1):
r,c = pt[i]//w,pt[i]%w
dp.append(combo(r+c,r))
for j in range(i):
r1,c1 = pt[j]//w,pt[j]%w
if r1<=r and c1<=c:
dp[i]-=dp[j]*combo(r+c-r1-c1,r-r1)
dp[i]%=MOD
print(dp[n])
``` | output | 1 | 97,410 | 15 | 194,821 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?
The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.
Input
The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 105, 1 ≤ n ≤ 2000).
Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≤ ri ≤ h, 1 ≤ ci ≤ w) — the number of the row and column of the i-th cell.
It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.
Output
Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7.
Examples
Input
3 4 2
2 2
2 3
Output
2
Input
100 100 3
15 16
16 15
99 88
Output
545732279 | instruction | 0 | 97,411 | 15 | 194,822 |
Tags: combinatorics, dp, math, number theory
Correct Solution:
```
MOD = 10**9+7
fact = [1]*200013
for i in range(1,200013):
fact[i] = (fact[i-1]*i)%MOD
inv = [1]*200013
for i in range(2,200013):
inv[i] = (-(MOD//i)*inv[MOD%i])%MOD
for i in range(2,200013):
inv[i] = (inv[i]*inv[i-1])%MOD
def C(n,k):
return (fact[n]*inv[k]*inv[n-k])%MOD
def rasch(x,y):
global mas
res = C(x+y-2,x-1)%MOD
for i in mas:
if (x==i[0] and y==i[1]): break
if i[0]<=x and i[1]<=y :
l=C(x-i[0]+y-i[1],x-i[0])
k=rasch(i[0],i[1]) if not i[3] else i[2]
i[2]=k%MOD
i[3]=1
res-=l*k%MOD
return res%MOD
h,w,n = map(int,input().split(" "))
mas=[]
for i in range(n):
x,y= map(int,input().split(" "))
mas.append([x,y,0,0])
mas.sort(key=lambda x: x[0]+x[1])
print(rasch(h,w)%MOD)
``` | output | 1 | 97,411 | 15 | 194,823 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?
The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.
Input
The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 105, 1 ≤ n ≤ 2000).
Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≤ ri ≤ h, 1 ≤ ci ≤ w) — the number of the row and column of the i-th cell.
It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.
Output
Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7.
Examples
Input
3 4 2
2 2
2 3
Output
2
Input
100 100 3
15 16
16 15
99 88
Output
545732279 | instruction | 0 | 97,412 | 15 | 194,824 |
Tags: combinatorics, dp, math, number theory
Correct Solution:
```
from sys import stdin
input = stdin.buffer.readline
f, inv = [1], [1, 1]
mod = 1000000007
def c(n, k):
return f[n] * inv[k] * inv[n - k] % mod
h, w, n = map(int, input().split())
for i in range(1, 200001):
f.append(f[i - 1] * i % mod)
for i in range(2, 200001):
inv.append((-(mod // i) * inv[mod % i]) % mod)
for i in range(2, 200001):
inv[i] *= inv[i - 1]
inv[i] %= mod
a = []
for i in range(n):
a.append([*map(int, input().split())])
a.sort()
a.append([h, w])
dp = [0] * (n + 1)
for i in range(n + 1):
dp[i] = c(a[i][0] + a[i][1] - 2, a[i][0] - 1)
for j in range(0, i):
if a[i][0] >= a[j][0] and a[i][1] >= a[j][1]:
dp[i] -= dp[j] * c(a[i][0] - a[j][0] + a[i][1] - a[j][1], a[i][0] - a[j][0])
dp[i] %= mod
print(dp[n])
``` | output | 1 | 97,412 | 15 | 194,825 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?
The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.
Input
The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 105, 1 ≤ n ≤ 2000).
Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≤ ri ≤ h, 1 ≤ ci ≤ w) — the number of the row and column of the i-th cell.
It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.
Output
Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7.
Examples
Input
3 4 2
2 2
2 3
Output
2
Input
100 100 3
15 16
16 15
99 88
Output
545732279 | instruction | 0 | 97,413 | 15 | 194,826 |
Tags: combinatorics, dp, math, number theory
Correct Solution:
```
#!/usr/bin/env python
# 560E_chess.py - Codeforces.com 560E Chess program
#
# Copyright (C) 2015 Sergey
"""
Input
The first line of the input contains three integers:
h,w,n the sides of the board and the number of black cells
Next n lines contain the description of black cells. The ith
of these lines contains numbers ri,?ci the number of the row and
column of the i-th cell.
It is guaranteed that the upper left and lower right cell are white
and all cells in the description are distinct.
Output
Print a single line the remainder of the number of ways to move Gerald's
pawn from the upper lef to the lower right corner modulo 10^9+7.
"""
# Standard modules
import unittest
import sys
# Additional modules
###############################################################################
# Chess Class
###############################################################################
class Chess:
""" Chess representation """
N = 200001
MOD = 10**9+7
def __init__(self, args):
""" Default constructor """
self.h, self.w, self.imax, self.numa, self.numb = args
# Sort black cells
self.pt = sorted(zip(self.numa, self.numb))
self.pt.append((self.h, self.w))
# Populate factorial
self.fact = [1]
prev = 1
for i in range(1, self.N):
f = (prev * i) % self.MOD
self.fact.append(f)
prev = f
# Populate Inv factorial
self.inv = [0] * self.N
self.inv[self.N-1] = self.modInvfact(self.N-1)
for i in range(self.N-2, -1, -1):
self.inv[i] = (self.inv[i+1] * (i+1)) % self.MOD
# Populate number of ways
self.ways = []
for i in range(len(self.pt)):
(h, w) = self.pt[i]
self.ways.append(self.modC(h + w - 2, h - 1))
for j in range(i):
(hj, wj) = self.pt[j]
if (hj <= h and wj <= w):
mult = self.modC(h - hj + w - wj, h - hj)
self.ways[i] = self.modSub(
self.ways[i], self.ways[j] * mult, self.MOD)
def modC(self, n, k):
return (
self.fact[n] *
((self.inv[k] * self.inv[n-k]) % self.MOD)) % self.MOD
def modInvfact(self, n):
return self.modExp(self.fact[n], self.MOD-2, self.MOD)
def modExp(self, n, e, p):
res = 1
while e > 0:
if (e % 2 == 1):
res = (res * n) % p
e >>= 1
n = (n * n) % p
return res
def modSub(self, a, b, p):
return ((a - b) % p + p) % p
def calculate(self):
""" Main calcualtion function of the class """
result = self.ways[-1]
return str(result)
###############################################################################
# Helping classes
###############################################################################
###############################################################################
# Chess Class testing wrapper code
###############################################################################
def get_inputs(test_inputs=None):
it = iter(test_inputs.split("\n")) if test_inputs else None
def uinput():
""" Unit-testable input function wrapper """
if it:
return next(it)
else:
return sys.stdin.readline()
# Getting string inputs. Place all uinput() calls here
h, w, imax = list(map(int, uinput().split()))
numnums = list(map(int, " ".join(uinput() for i in range(imax)).split()))
# Splitting numnums into n arrays
numa = []
numb = []
for i in range(0, 2*imax, 2):
numa.append(numnums[i])
numb.append(numnums[i+1])
# Decoding inputs into a list
return [h, w, imax, numa, numb]
def calculate(test_inputs=None):
""" Base class calculate method wrapper """
return Chess(get_inputs(test_inputs)).calculate()
###############################################################################
# Unit Tests
###############################################################################
class unitTests(unittest.TestCase):
def test_Chess_class__basic_functions(self):
""" Chess class basic functions testing """
# Constructor test
d = Chess([3, 4, 2, [2, 2], [2, 3]])
self.assertEqual(d.imax, 2)
self.assertEqual(d.pt[0], (2, 2))
# modExp
self.assertEqual(d.modExp(3, 3, 6), 3)
# Factorials
self.assertEqual(d.fact[3], 6)
self.assertEqual(d.inv[3], d.modInvfact(3))
# Binominal
self.assertEqual(d.modC(4, 2), 6)
# Ways
self.assertEqual(d.ways[0], 2)
def test_sample_tests(self):
""" Quiz sample tests. Add \n to separate lines """
# Sample test 1
test = "3 4 2\n2 2\n2 3"
self.assertEqual(calculate(test), "2")
self.assertEqual(get_inputs(test)[0], 3)
self.assertEqual(list(get_inputs(test)[3]), [2, 2])
self.assertEqual(list(get_inputs(test)[4]), [2, 3])
# Sample test 2
test = "100 100 3\n15 16\n16 15\n99 88"
self.assertEqual(calculate(test), "545732279")
# Sample test 3
test = "1\n12"
# self.assertEqual(calculate(test), "0")
# My test 4
test = "1\n12"
# self.assertEqual(calculate(test), "0")
def test_time_limit_test(self):
""" Quiz time limit test """
import random
# Time limit test
imax = 2000
h = 100000
w = 99000
num = str(imax)
test = str(h) + " " + str(w) + " " + num + "\n"
numnums = [str(i) + " " + str(i+1) for i in range(imax)]
test += "\n".join(numnums) + "\n"
import timeit
start = timeit.default_timer()
args = get_inputs(test)
init = timeit.default_timer()
d = Chess(args)
calc = timeit.default_timer()
d.calculate()
stop = timeit.default_timer()
print(
"\nTime Test: " +
"{0:.3f}s (inp {1:.3f}s init {2:.3f}s calc {3:.3f}s)".
format(stop-start, init-start, calc-init, stop-calc))
if __name__ == "__main__":
# Avoiding recursion limitaions
sys.setrecursionlimit(100000)
if sys.argv[-1] == "-ut":
unittest.main(argv=[" "])
# Print the result string
sys.stdout.write(calculate())
``` | output | 1 | 97,413 | 15 | 194,827 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?
The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.
Input
The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 105, 1 ≤ n ≤ 2000).
Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≤ ri ≤ h, 1 ≤ ci ≤ w) — the number of the row and column of the i-th cell.
It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.
Output
Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7.
Examples
Input
3 4 2
2 2
2 3
Output
2
Input
100 100 3
15 16
16 15
99 88
Output
545732279 | instruction | 0 | 97,414 | 15 | 194,828 |
Tags: combinatorics, dp, math, number theory
Correct Solution:
```
h,w,n = map(int, input().split())
l = [tuple(map(int, input().split())) for i in range(n)]
l.sort()
l += [(h,w)]
N,B = (h + w + 1)<<1, 10**9+7
fac,inv = [1] * N, [1] * N
for i in range(2, N):
fac[i] = (i * fac[i-1]) % B
inv[i] = (-(B//i) * (inv[B%i])) % B
for i in range(2, N):
inv[i] = (inv[i] * inv[i-1]) % B
C = lambda u, v: (((fac[u] * inv[v]) % B) * inv[u - v]) % B
d = []
for i in range(n+1):
d += [C(l[i][0] + l[i][1] - 2, l[i][0] - 1)]
for j in range(i):
if l[j][1] <= l[i][1]:
d[i] = (d[i] + B - (d[j] * C(l[i][0] + l[i][1] - l[j][0] - l[j][1], l[i][0] - l[j][0]) % B)) % B
print(d[n])
``` | output | 1 | 97,414 | 15 | 194,829 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?
The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.
Input
The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 105, 1 ≤ n ≤ 2000).
Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≤ ri ≤ h, 1 ≤ ci ≤ w) — the number of the row and column of the i-th cell.
It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.
Output
Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7.
Examples
Input
3 4 2
2 2
2 3
Output
2
Input
100 100 3
15 16
16 15
99 88
Output
545732279 | instruction | 0 | 97,415 | 15 | 194,830 |
Tags: combinatorics, dp, math, number theory
Correct Solution:
```
def init_factorials(N, mod):
f = 1
fac = [1] * N
for i in range(1, N):
f *= i
f %= mod
fac[i] = f
return fac
def init_inv(N, mod, fac):
b = bin(mod-2)[2:][-1::-1]
ret = 1
tmp = fac[N]
if b[0] == '1':
ret = fac[N]
for bi in b[1:]:
tmp *= tmp
tmp %= mod
if bi == '1':
ret *= tmp
ret %= mod
inv = [1] * (N + 1)
inv[N] = ret
for i in range(N-1, 0, -1):
ret *= i + 1
ret %= mod
inv[i] = ret
return inv
def f(r, c, mod, fac, inv):
return (fac[r + c] * inv[r] * inv[c]) % mod
def read_data():
h, w, n = map(int, input().split())
blacks = []
for i in range(n):
r, c = map(int, input().split())
blacks.append((r, c))
return h, w, n, blacks
def solve(h, w, n, blacks):
mod = 10**9 + 7
fac = init_factorials(h + w + 10, mod)
inv = init_inv(h + w + 5, mod, fac)
ans = (fac[h+w-2]*inv[h-1]*inv[w-1]) % mod
eb = [(r + c, r, c) for r, c in blacks]
eb.sort()
blacks = [(r, c) for rc, r, c in eb]
g = [f(r-1, c-1, mod, fac, inv) for r, c in blacks]
hw = h+w
for i, (r, c) in enumerate(blacks):
gi = g[i]
rc = r + c
ans -= gi*fac[hw-rc]*inv[h-r]*inv[w-c]
ans %= mod
for j, (rj, cj) in enumerate(blacks[i+1:], i+1):
if r <= rj and c <= cj:
g[j] -= gi*fac[rj+cj-rc]*inv[rj-r]*inv[cj-c]
g[j] %= mod
return ans
h, w, n, blacks = read_data()
print(solve(h, w, n, blacks))
``` | output | 1 | 97,415 | 15 | 194,831 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?
The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.
Input
The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 105, 1 ≤ n ≤ 2000).
Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≤ ri ≤ h, 1 ≤ ci ≤ w) — the number of the row and column of the i-th cell.
It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.
Output
Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7.
Examples
Input
3 4 2
2 2
2 3
Output
2
Input
100 100 3
15 16
16 15
99 88
Output
545732279 | instruction | 0 | 97,416 | 15 | 194,832 |
Tags: combinatorics, dp, math, number theory
Correct Solution:
```
MOD = 10**9+7
fact = [1]*200013
for i in range(1,200013):
fact[i] = (fact[i-1]*i)%MOD
inv = [1]*200013
for i in range(2,200013):
inv[i] = (-(MOD//i)*inv[MOD%i])%MOD
for i in range(2,200013):
inv[i] = (inv[i]*inv[i-1])%MOD
def C(n,k):
return (fact[n]*inv[k]*inv[n-k])%MOD
h,w,n = map(int,input().split(" "))
mas=[]
for i in range(n):
x,y= map(int,input().split(" "))
mas.append([x,y,0,0])
mas.append([h,w,0,0])
mas.sort(key=lambda x: x[0]+x[1])
for j in mas:
j[2] = C(j[0]+j[1]-2,j[0]-1)%MOD
for i in mas:
if (j[0]==i[0] and j[1]==i[1]): break
if i[0]<=j[0] and i[1]<=j[1]:
l=C(j[0]-i[0]+j[1]-i[1],j[0]-i[0])%MOD
k= i[2]
j[2]-=l*k%MOD
print(mas[-1][2]%(10**9+7))
``` | output | 1 | 97,416 | 15 | 194,833 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?
The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.
Input
The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 105, 1 ≤ n ≤ 2000).
Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≤ ri ≤ h, 1 ≤ ci ≤ w) — the number of the row and column of the i-th cell.
It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.
Output
Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7.
Examples
Input
3 4 2
2 2
2 3
Output
2
Input
100 100 3
15 16
16 15
99 88
Output
545732279
Submitted Solution:
```
fact = [1]
rfact = [1]
MOD = int(1e9) + 7
n,m, k = map(int, input().split())
for i in range(1, max(2*n,2*m)+2):
fact += [fact[-1] * i % MOD]
rfact += [rfact[-1] * pow(i, MOD - 2, MOD) % MOD]
def cmb(n, k):
return fact[n] * rfact[k] * rfact[n-k] % MOD
points = [tuple(map(int, input().split())) for i in range(k)]
points += [(n,m)]
points.sort()
dp = []
for i in range(k+1):
tmp = cmb(points[i][0] + points[i][1] - 2, points[i][0] - 1)
for j in range(i):
if points[j][0] <= points[i][0] and points[j][1] <= points[i][1]:
tmp -= (dp[j]*cmb(points[i][0] - points[j][0] + points[i][1] - points[j][1], points[i][1] - points[j][1])) % MOD
tmp += MOD
tmp %= MOD
dp += [tmp]
print(dp[k])
``` | instruction | 0 | 97,417 | 15 | 194,834 |
Yes | output | 1 | 97,417 | 15 | 194,835 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?
The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.
Input
The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 105, 1 ≤ n ≤ 2000).
Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≤ ri ≤ h, 1 ≤ ci ≤ w) — the number of the row and column of the i-th cell.
It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.
Output
Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7.
Examples
Input
3 4 2
2 2
2 3
Output
2
Input
100 100 3
15 16
16 15
99 88
Output
545732279
Submitted Solution:
```
MOD = 10**9+7
fact = [1]*200003
for i in range(1,200003):
fact[i] = (fact[i-1]*i)%MOD
inv = [1]*200003
for i in range(2,200003):
inv[i] = (-(MOD//i)*inv[MOD%i])%MOD
for i in range(2,200003):
inv[i] = (inv[i]*inv[i-1])%MOD
def C(n,k):
return (fact[n]*inv[k]*inv[n-k])%MOD
h,w,n = map(int,input().split(" "))
mas=[]
for i in range(n):
x,y= map(int,input().split(" "))
mas.append([x,y,0,0])
mas.append([h,w,0,0])
mas.sort(key=lambda x: x[0]+x[1])
for j in mas:
j[2] = C(j[0]+j[1]-2,j[0]-1)%MOD
for i in mas:
if (j[0]==i[0] and j[1]==i[1]): break
if i[0]<=j[0] and i[1]<=j[1]:
l=C(j[0]-i[0]+j[1]-i[1],j[0]-i[0])%MOD
k= i[2]
j[2]-=l*k%MOD
print(mas[-1][2]%MOD)
``` | instruction | 0 | 97,418 | 15 | 194,836 |
Yes | output | 1 | 97,418 | 15 | 194,837 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?
The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.
Input
The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 105, 1 ≤ n ≤ 2000).
Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≤ ri ≤ h, 1 ≤ ci ≤ w) — the number of the row and column of the i-th cell.
It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.
Output
Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7.
Examples
Input
3 4 2
2 2
2 3
Output
2
Input
100 100 3
15 16
16 15
99 88
Output
545732279
Submitted Solution:
```
import math
def countPaths(h,w):
return int(math.factorial(h+w-2)/(math.factorial(h-1)*(math.factorial(w-1))))%(10**9+7)
h, w, n = [int(i) for i in input().split()]
black = []
for i in range(n):
black.append([int(i) for i in input().split()])
ans=countPaths(h,w)
for i in range(len(black)):
ans -= (countPaths(black[i][0],black[i][1])*countPaths(h-black[i][0]+1,w-black[i][1]+1))%(10**9+7)
for j in range(i):
if black[j][0] <= black[i][0] and black[j][1] <= black[i][1]:
ans += (countPaths(black[j][0],black[j][1])*countPaths(black[i][0]-black[j][0]+1,black[i][1]-black[j][1]+1)*countPaths(h-black[i][0]+1,w-black[i][1]+1))%(10**9+7)
elif black[j][0] >= black[i][0] and black[j][1] >= black[i][1]:
ans += (countPaths(black[i][0],black[i][1])*(countPaths(black[i][0] - black[j][0],black[i][1] - black[j][1])*countPaths(h-black[j][0]+1,w-black[j][1]+1)))%(10**9+7)
print(ans%(10**9+7))
``` | instruction | 0 | 97,419 | 15 | 194,838 |
No | output | 1 | 97,419 | 15 | 194,839 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?
The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.
Input
The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 105, 1 ≤ n ≤ 2000).
Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≤ ri ≤ h, 1 ≤ ci ≤ w) — the number of the row and column of the i-th cell.
It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.
Output
Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7.
Examples
Input
3 4 2
2 2
2 3
Output
2
Input
100 100 3
15 16
16 15
99 88
Output
545732279
Submitted Solution:
```
h,w,n = map(int, input().split())
l = [tuple(map(int, input().split())) for i in range(n)]
l.sort()
l += [(h,w)]
N,B = (h + w + 1)<<1, 10**9+7
fac,inv = [1] * N, [1] * N
for i in range(2, N):
fac[i] = (i * fac[i-1]) % B
inv[i] = (-(B//i) * (inv[B%i])) % B
for i in range(2, N):
inv[i] = (inv[i] * inv[i-1]) % B
C = lambda u, v: (((fac[u] * inv[v])) * inv[u - v]) % B
d = []
for i in range(n+1):
d += [C(l[i][0] + l[i][1] - 2, l[i][0] - 1)]
for j in range(i):
if l[j][1] < l[i][1]:
d[i] = (d[i] + B - (d[j] * C(l[i][0] + l[i][1] - l[j][0] - l[j][1], l[i][0] - l[j][0]) % B)) % B
print(d[n])
``` | instruction | 0 | 97,420 | 15 | 194,840 |
No | output | 1 | 97,420 | 15 | 194,841 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?
The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.
Input
The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 105, 1 ≤ n ≤ 2000).
Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≤ ri ≤ h, 1 ≤ ci ≤ w) — the number of the row and column of the i-th cell.
It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.
Output
Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7.
Examples
Input
3 4 2
2 2
2 3
Output
2
Input
100 100 3
15 16
16 15
99 88
Output
545732279
Submitted Solution:
```
h, w, n = map(int, input().split(" "))
l = []
grid = []
row = []
for i in range(n):
y, x = map(int, input().split(" "))
l.append((x, y))
def solve(x, y, l):
if x == 1 and y == 1:
return 1
else:
if x != 1 and y != 1:
if not (x, y-1) in l and not (x-1, y) in l:
return solve(x, y-1, l) + solve(x-1, y, l)
elif not (x, y-1) in l:
return solve(x-1, y, l)
elif not (x-1, y) in l:
return solve(x, y-1, l)
else:
return 0
elif x == 1:
if not (x, y-1) in l:
return solve(x, y-1, l)
else:
return 0
elif y == 1:
if not (x-1, y) in l:
return solve(x-1, y, l)
print(solve(w, h, l)/2)
``` | instruction | 0 | 97,421 | 15 | 194,842 |
No | output | 1 | 97,421 | 15 | 194,843 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Giant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?
The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.
Input
The first line of the input contains three integers: h, w, n — the sides of the board and the number of black cells (1 ≤ h, w ≤ 105, 1 ≤ n ≤ 2000).
Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≤ ri ≤ h, 1 ≤ ci ≤ w) — the number of the row and column of the i-th cell.
It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.
Output
Print a single line — the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7.
Examples
Input
3 4 2
2 2
2 3
Output
2
Input
100 100 3
15 16
16 15
99 88
Output
545732279
Submitted Solution:
```
firstString = input()
secondString = input()
def sortedStr (word):
if (len(word) % 2 == 1):
return word
mid = int(len(word)/2)
left = sortedStr(word[mid:])
right = sortedStr(word[:mid])
if (left > right):
return right + left
else:
return left + right
valid = sortedStr(firstString) == sortedStr(secondString)
print("YES" if valid else "NO")
``` | instruction | 0 | 97,422 | 15 | 194,844 |
No | output | 1 | 97,422 | 15 | 194,845 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The campus has m rooms numbered from 0 to m - 1. Also the x-mouse lives in the campus. The x-mouse is not just a mouse: each second x-mouse moves from room i to the room i ⋅ x mod{m} (in fact, it teleports from one room to another since it doesn't visit any intermediate room). Starting position of the x-mouse is unknown.
You are responsible to catch the x-mouse in the campus, so you are guessing about minimum possible number of traps (one trap in one room) you need to place. You are sure that if the x-mouse enters a trapped room, it immediately gets caught.
And the only observation you made is GCD (x, m) = 1.
Input
The only line contains two integers m and x (2 ≤ m ≤ 10^{14}, 1 ≤ x < m, GCD (x, m) = 1) — the number of rooms and the parameter of x-mouse.
Output
Print the only integer — minimum number of traps you need to install to catch the x-mouse.
Examples
Input
4 3
Output
3
Input
5 2
Output
2
Note
In the first example you can, for example, put traps in rooms 0, 2, 3. If the x-mouse starts in one of this rooms it will be caught immediately. If x-mouse starts in the 1-st rooms then it will move to the room 3, where it will be caught.
In the second example you can put one trap in room 0 and one trap in any other room since x-mouse will visit all rooms 1..m-1 if it will start in any of these rooms. | instruction | 0 | 97,832 | 15 | 195,664 |
Tags: bitmasks, math, number theory
Correct Solution:
```
from math import gcd
def powmod(a,b,m):
a%=m
r=1
while b:
if b&1:r=r*a%m
a=a*a%m
b>>=1
return r
def f(n):
r=[]
if (n&1)==0:
e=0
while (n&1)==0:n>>=1;e+=1
yield (2,e)
p=3
while n>1:
if p*p>n:p=n
if n%p:
p+=2
continue
e=1;n//=p
while n%p==0:n//=p;e+=1
yield (p,e)
p+=2
return r
m,x=map(int,input().split())
p=2
r=[(1,1)]
for p,e in f(m):
assert e>=1
ord=p-1
assert powmod(x,ord,p)==1
for pi,ei in f(p-1):
while ord % pi == 0 and powmod(x,ord//pi,p)==1: ord//=pi
ords=[(1,1),(ord,p-1)]
q=p
for v in range(2,e+1):
q*=p
if powmod(x,ord,q)!=1:ord*=p
assert powmod(x,ord,q)==1
ords.append((ord,q//p*(p-1)))
r=[(a//gcd(a,c)*c,b*d) for a,b in r for c,d in ords]
print(sum(y//x for x,y in r))
``` | output | 1 | 97,832 | 15 | 195,665 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The campus has m rooms numbered from 0 to m - 1. Also the x-mouse lives in the campus. The x-mouse is not just a mouse: each second x-mouse moves from room i to the room i ⋅ x mod{m} (in fact, it teleports from one room to another since it doesn't visit any intermediate room). Starting position of the x-mouse is unknown.
You are responsible to catch the x-mouse in the campus, so you are guessing about minimum possible number of traps (one trap in one room) you need to place. You are sure that if the x-mouse enters a trapped room, it immediately gets caught.
And the only observation you made is GCD (x, m) = 1.
Input
The only line contains two integers m and x (2 ≤ m ≤ 10^{14}, 1 ≤ x < m, GCD (x, m) = 1) — the number of rooms and the parameter of x-mouse.
Output
Print the only integer — minimum number of traps you need to install to catch the x-mouse.
Examples
Input
4 3
Output
3
Input
5 2
Output
2
Note
In the first example you can, for example, put traps in rooms 0, 2, 3. If the x-mouse starts in one of this rooms it will be caught immediately. If x-mouse starts in the 1-st rooms then it will move to the room 3, where it will be caught.
In the second example you can put one trap in room 0 and one trap in any other room since x-mouse will visit all rooms 1..m-1 if it will start in any of these rooms.
Submitted Solution:
```
from math import sqrt
def factor(n):
potentional_p = 3
itog_list = {}
if n % 2 == 0:
itog_list[2] = 0
while n % 2 == 0:
n = n // 2
itog_list[2] += 1
while n - 1:
if potentional_p > sqrt(n):
if n in itog_list:
itog_list[n] += 1
else:
itog_list[n] = 1
return itog_list
while n % potentional_p == 0:
n = n // potentional_p
if potentional_p in itog_list:
itog_list[potentional_p] += 1
else:
itog_list[potentional_p] = 1
potentional_p += 2
return itog_list
m, x = map(int, input().split())
F = factor(m)
fi = 1
for p in F:
fi *= p ** (F[p] - 1) * (p - 1)
print(fi + 1)
``` | instruction | 0 | 97,833 | 15 | 195,666 |
No | output | 1 | 97,833 | 15 | 195,667 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The campus has m rooms numbered from 0 to m - 1. Also the x-mouse lives in the campus. The x-mouse is not just a mouse: each second x-mouse moves from room i to the room i ⋅ x mod{m} (in fact, it teleports from one room to another since it doesn't visit any intermediate room). Starting position of the x-mouse is unknown.
You are responsible to catch the x-mouse in the campus, so you are guessing about minimum possible number of traps (one trap in one room) you need to place. You are sure that if the x-mouse enters a trapped room, it immediately gets caught.
And the only observation you made is GCD (x, m) = 1.
Input
The only line contains two integers m and x (2 ≤ m ≤ 10^{14}, 1 ≤ x < m, GCD (x, m) = 1) — the number of rooms and the parameter of x-mouse.
Output
Print the only integer — minimum number of traps you need to install to catch the x-mouse.
Examples
Input
4 3
Output
3
Input
5 2
Output
2
Note
In the first example you can, for example, put traps in rooms 0, 2, 3. If the x-mouse starts in one of this rooms it will be caught immediately. If x-mouse starts in the 1-st rooms then it will move to the room 3, where it will be caught.
In the second example you can put one trap in room 0 and one trap in any other room since x-mouse will visit all rooms 1..m-1 if it will start in any of these rooms.
Submitted Solution:
```
m ,n = map(int,input().split())
if m !=0 or n!=0:
if m == 0 :
print(n)
elif n ==0 :
print(m)
elif m>n:
print(n)
elif n>m:
print(m)
``` | instruction | 0 | 97,835 | 15 | 195,670 |
No | output | 1 | 97,835 | 15 | 195,671 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.
In order to lose weight, Bashar is going to run for k kilometers. Bashar is going to run in a place that looks like a grid of n rows and m columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4 n m - 2n - 2m) roads.
Let's take, for example, n = 3 and m = 4. In this case, there are 34 roads. It is the picture of this case (arrows describe roads):
<image>
Bashar wants to run by these rules:
* He starts at the top-left cell in the grid;
* In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row i and in the column j, i.e. in the cell (i, j) he will move to:
* in the case 'U' to the cell (i-1, j);
* in the case 'D' to the cell (i+1, j);
* in the case 'L' to the cell (i, j-1);
* in the case 'R' to the cell (i, j+1);
* He wants to run exactly k kilometers, so he wants to make exactly k moves;
* Bashar can finish in any cell of the grid;
* He can't go out of the grid so at any moment of the time he should be on some cell;
* Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times.
Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.
You should give him a steps to do and since Bashar can't remember too many steps, a should not exceed 3000. In every step, you should give him an integer f and a string of moves s of length at most 4 which means that he should repeat the moves in the string s for f times. He will perform the steps in the order you print them.
For example, if the steps are 2 RUD, 3 UUL then the moves he is going to move are RUD + RUD + UUL + UUL + UUL = RUDRUDUULUULUUL.
Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to k kilometers or say, that it is impossible?
Input
The only line contains three integers n, m and k (1 ≤ n, m ≤ 500, 1 ≤ k ≤ 10 ^{9}), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
Output
If there is no possible way to run k kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.
If the answer is "YES", on the second line print an integer a (1 ≤ a ≤ 3000) — the number of steps, then print a lines describing the steps.
To describe a step, print an integer f (1 ≤ f ≤ 10^{9}) and a string of moves s of length at most 4. Every character in s should be 'U', 'D', 'L' or 'R'.
Bashar will start from the top-left cell. Make sure to move exactly k moves without visiting the same road twice and without going outside the grid. He can finish at any cell.
We can show that if it is possible to run exactly k kilometers, then it is possible to describe the path under such output constraints.
Examples
Input
3 3 4
Output
YES
2
2 R
2 L
Input
3 3 1000000000
Output
NO
Input
3 3 8
Output
YES
3
2 R
2 D
1 LLRR
Input
4 4 9
Output
YES
1
3 RLD
Input
3 4 16
Output
YES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
Note
The moves Bashar is going to move in the first example are: "RRLL".
It is not possible to run 1000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.
The moves Bashar is going to move in the third example are: "RRDDLLRR".
The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
<image> | instruction | 0 | 98,002 | 15 | 196,004 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
"""
This template is made by Satwik_Tiwari.
python programmers can use this template :)) .
"""
#===============================================================================================
#importing some useful libraries.
import sys
import bisect
import heapq
from math import *
from collections import Counter as counter # Counter(list) return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl #
from bisect import bisect_right as br
from bisect import bisect
#===============================================================================================
#some shortcuts
mod = pow(10, 9) + 7
def inp(): return sys.stdin.readline().strip() #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nl(): out("\n") #as stdout.write always print sring.
def testcase(t):
for p in range(t):
solve()
def printlist(a) :
for p in range(0,len(a)):
out(str(a[p]) + ' ')
def lcm(a,b): return (a*b)//gcd(a,b)
#===============================================================================================
# code here ;))
def func(n,m,k):
if((4*m*n)-(2*n)-(2*m) < k):
return True
else:
return False
def solve():
n,m,k = sep()
if(func(n,m,k)):
print('NO')
else:
print('YES')
ans = []
if(m-1 > 0):
ans.append([m-1,'R'])
for i in range(m-1):
# s1 = 'D'*(n-1) + ('U')*(n-1)
if(n-1 > 0):
ans.append([n-1,'DLR'])
# temp = n-1
# a = temp//4
# if(a>0):
# ans.append([a,'DDDD'])
# temp = temp - (4*a)
# if(temp > 0):
# ans.append([1,'D'*temp])
temp = n-1
a = temp//4
if(a>0):
ans.append([a,'UUUU'])
temp = temp - (4*a)
if(temp > 0):
ans.append([1,'U'*temp+'L'])
else:
ans.append([1,'L'])
temp = n-1
a = temp//4
if(a>0):
ans.append([a,'DDDD'])
temp = temp-(4*a)
if(temp > 0):
ans.append([1,'D'*temp])
temp = n-1
a = temp//4
if(a>0):
ans.append([a,'UUUU'])
temp = temp-(4*a)
if(temp > 0):
ans.append([1,'U'*temp])
# for i in range(n-1):
# # ans.append([1,'D'])
# help = (m-1) - (((m-1)//4)*4)
# if(help > 0):
# ans.append([1,'D'+'R'*help])
# # s1 = 'R'*(m-1) + 'L'*(m-1)
# temp = m-1-help
# a = temp//4
# if(a>0):
# ans.append([a,'RRRR'])
# temp = temp - (4*a)
# if(temp > 0):
# ans.append([1,'R'*temp])
# temp = m-1
# a = temp//4
# if(a>0):
# ans.append([a,'LLLL'])
# temp = temp - (4*a)
# if(temp > 0):
# ans.append([1,'L'*temp])
ans.append([n-1,'U'*(n-1)])
finall = []
cnt = 0
index = 0
while(True):
if(cnt+len(ans[index][1])*ans[index][0] == k):
finall.append(ans[index])
break
if(cnt+len(ans[index][1])*ans[index][0] < k):
finall.append(ans[index])
cnt += len(ans[index][1])*ans[index][0]
index+=1
else:
rem = k-cnt
if(ans[index][0] == 1):
finall.append([1,ans[index][1][:rem]])
break
else:
b = rem//(len(ans[index][1]))
if(b>0):
finall.append([b,ans[index][1]])
rem = rem - (len(ans[index][1])*b)
if(rem > 0):
finall.append([1,ans[index][1][:rem]])
# temp = ans[index][1][:rem]
# finall.append([1,temp])
break
print(len(finall))
for i in range(0,len(finall)):
print(finall[i][0],finall[i][1])
testcase(1)
# testcase(1)
``` | output | 1 | 98,002 | 15 | 196,005 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.
In order to lose weight, Bashar is going to run for k kilometers. Bashar is going to run in a place that looks like a grid of n rows and m columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4 n m - 2n - 2m) roads.
Let's take, for example, n = 3 and m = 4. In this case, there are 34 roads. It is the picture of this case (arrows describe roads):
<image>
Bashar wants to run by these rules:
* He starts at the top-left cell in the grid;
* In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row i and in the column j, i.e. in the cell (i, j) he will move to:
* in the case 'U' to the cell (i-1, j);
* in the case 'D' to the cell (i+1, j);
* in the case 'L' to the cell (i, j-1);
* in the case 'R' to the cell (i, j+1);
* He wants to run exactly k kilometers, so he wants to make exactly k moves;
* Bashar can finish in any cell of the grid;
* He can't go out of the grid so at any moment of the time he should be on some cell;
* Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times.
Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.
You should give him a steps to do and since Bashar can't remember too many steps, a should not exceed 3000. In every step, you should give him an integer f and a string of moves s of length at most 4 which means that he should repeat the moves in the string s for f times. He will perform the steps in the order you print them.
For example, if the steps are 2 RUD, 3 UUL then the moves he is going to move are RUD + RUD + UUL + UUL + UUL = RUDRUDUULUULUUL.
Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to k kilometers or say, that it is impossible?
Input
The only line contains three integers n, m and k (1 ≤ n, m ≤ 500, 1 ≤ k ≤ 10 ^{9}), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
Output
If there is no possible way to run k kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.
If the answer is "YES", on the second line print an integer a (1 ≤ a ≤ 3000) — the number of steps, then print a lines describing the steps.
To describe a step, print an integer f (1 ≤ f ≤ 10^{9}) and a string of moves s of length at most 4. Every character in s should be 'U', 'D', 'L' or 'R'.
Bashar will start from the top-left cell. Make sure to move exactly k moves without visiting the same road twice and without going outside the grid. He can finish at any cell.
We can show that if it is possible to run exactly k kilometers, then it is possible to describe the path under such output constraints.
Examples
Input
3 3 4
Output
YES
2
2 R
2 L
Input
3 3 1000000000
Output
NO
Input
3 3 8
Output
YES
3
2 R
2 D
1 LLRR
Input
4 4 9
Output
YES
1
3 RLD
Input
3 4 16
Output
YES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
Note
The moves Bashar is going to move in the first example are: "RRLL".
It is not possible to run 1000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.
The moves Bashar is going to move in the third example are: "RRDDLLRR".
The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
<image> | instruction | 0 | 98,003 | 15 | 196,006 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
from __future__ import division, print_function
import os
import sys, math
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def main():
n, m, k = map(int, input().split())
if k > 4*n*m - 2*n - 2*m:
print ("NO")
return
print ("YES")
v = list()
ans = list()
for i in range(n):
if m-1:
v.append((m-1, 'R'))
v.append((m-1, 'L'))
v.append((1, 'D'))
v.pop()
if m-1:
v.pop()
for i in range(m):
if n-1:
v.append((n-1, 'U'))
v.append((n-1, 'D'))
v.append((1, 'L'))
v.pop()
if n-1:
v.pop()
ind = 0
while k:
if k >= v[ind][0]:
ans.append(v[ind])
k -= v[ind][0]
else:
ans.append((k, v[ind][1]))
k = 0
ind += 1
print (len(ans))
for val in ans:
print (val[0], val[1])
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
``` | output | 1 | 98,003 | 15 | 196,007 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.
In order to lose weight, Bashar is going to run for k kilometers. Bashar is going to run in a place that looks like a grid of n rows and m columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4 n m - 2n - 2m) roads.
Let's take, for example, n = 3 and m = 4. In this case, there are 34 roads. It is the picture of this case (arrows describe roads):
<image>
Bashar wants to run by these rules:
* He starts at the top-left cell in the grid;
* In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row i and in the column j, i.e. in the cell (i, j) he will move to:
* in the case 'U' to the cell (i-1, j);
* in the case 'D' to the cell (i+1, j);
* in the case 'L' to the cell (i, j-1);
* in the case 'R' to the cell (i, j+1);
* He wants to run exactly k kilometers, so he wants to make exactly k moves;
* Bashar can finish in any cell of the grid;
* He can't go out of the grid so at any moment of the time he should be on some cell;
* Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times.
Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.
You should give him a steps to do and since Bashar can't remember too many steps, a should not exceed 3000. In every step, you should give him an integer f and a string of moves s of length at most 4 which means that he should repeat the moves in the string s for f times. He will perform the steps in the order you print them.
For example, if the steps are 2 RUD, 3 UUL then the moves he is going to move are RUD + RUD + UUL + UUL + UUL = RUDRUDUULUULUUL.
Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to k kilometers or say, that it is impossible?
Input
The only line contains three integers n, m and k (1 ≤ n, m ≤ 500, 1 ≤ k ≤ 10 ^{9}), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
Output
If there is no possible way to run k kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.
If the answer is "YES", on the second line print an integer a (1 ≤ a ≤ 3000) — the number of steps, then print a lines describing the steps.
To describe a step, print an integer f (1 ≤ f ≤ 10^{9}) and a string of moves s of length at most 4. Every character in s should be 'U', 'D', 'L' or 'R'.
Bashar will start from the top-left cell. Make sure to move exactly k moves without visiting the same road twice and without going outside the grid. He can finish at any cell.
We can show that if it is possible to run exactly k kilometers, then it is possible to describe the path under such output constraints.
Examples
Input
3 3 4
Output
YES
2
2 R
2 L
Input
3 3 1000000000
Output
NO
Input
3 3 8
Output
YES
3
2 R
2 D
1 LLRR
Input
4 4 9
Output
YES
1
3 RLD
Input
3 4 16
Output
YES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
Note
The moves Bashar is going to move in the first example are: "RRLL".
It is not possible to run 1000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.
The moves Bashar is going to move in the third example are: "RRDDLLRR".
The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
<image> | instruction | 0 | 98,004 | 15 | 196,008 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
n, m, k = map(int, input().split())
mx = 2 * (m - 1) * n + 2 * (n - 1) * m
have = 0
res = []
if k > mx:
print('NO')
exit(0)
def check(a, b):
global k, have
if not have + a * len(b) >= k:
have += a * len(b)
res.append((a, b))
return
bf = (k - have) // len(b)
have += bf * len(b)
if bf > 0:
res.append((bf, b))
if k <= have:
print_res()
return
b = b[:k - have]
res.append((1, b))
print_res()
def print_res():
print('YES')
print(len(res))
for i in res:
print(i[0], i[1])
exit(0)
for i in range(n):
if m - 1 > 0:
check(m - 1, 'R')
if i != n - 1:
if m - 1 > 0:
check(m - 1, 'DUL')
check(1, 'D')
else:
if m - 1 > 0:
check(m - 1, 'L')
if n - 1 > 0:
check(n - 1, 'U')
``` | output | 1 | 98,004 | 15 | 196,009 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.
In order to lose weight, Bashar is going to run for k kilometers. Bashar is going to run in a place that looks like a grid of n rows and m columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4 n m - 2n - 2m) roads.
Let's take, for example, n = 3 and m = 4. In this case, there are 34 roads. It is the picture of this case (arrows describe roads):
<image>
Bashar wants to run by these rules:
* He starts at the top-left cell in the grid;
* In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row i and in the column j, i.e. in the cell (i, j) he will move to:
* in the case 'U' to the cell (i-1, j);
* in the case 'D' to the cell (i+1, j);
* in the case 'L' to the cell (i, j-1);
* in the case 'R' to the cell (i, j+1);
* He wants to run exactly k kilometers, so he wants to make exactly k moves;
* Bashar can finish in any cell of the grid;
* He can't go out of the grid so at any moment of the time he should be on some cell;
* Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times.
Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.
You should give him a steps to do and since Bashar can't remember too many steps, a should not exceed 3000. In every step, you should give him an integer f and a string of moves s of length at most 4 which means that he should repeat the moves in the string s for f times. He will perform the steps in the order you print them.
For example, if the steps are 2 RUD, 3 UUL then the moves he is going to move are RUD + RUD + UUL + UUL + UUL = RUDRUDUULUULUUL.
Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to k kilometers or say, that it is impossible?
Input
The only line contains three integers n, m and k (1 ≤ n, m ≤ 500, 1 ≤ k ≤ 10 ^{9}), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
Output
If there is no possible way to run k kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.
If the answer is "YES", on the second line print an integer a (1 ≤ a ≤ 3000) — the number of steps, then print a lines describing the steps.
To describe a step, print an integer f (1 ≤ f ≤ 10^{9}) and a string of moves s of length at most 4. Every character in s should be 'U', 'D', 'L' or 'R'.
Bashar will start from the top-left cell. Make sure to move exactly k moves without visiting the same road twice and without going outside the grid. He can finish at any cell.
We can show that if it is possible to run exactly k kilometers, then it is possible to describe the path under such output constraints.
Examples
Input
3 3 4
Output
YES
2
2 R
2 L
Input
3 3 1000000000
Output
NO
Input
3 3 8
Output
YES
3
2 R
2 D
1 LLRR
Input
4 4 9
Output
YES
1
3 RLD
Input
3 4 16
Output
YES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
Note
The moves Bashar is going to move in the first example are: "RRLL".
It is not possible to run 1000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.
The moves Bashar is going to move in the third example are: "RRDDLLRR".
The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
<image> | instruction | 0 | 98,005 | 15 | 196,010 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
def output_ans(ans):
print('YES')
print(len(ans))
for x in ans:
print(x[0], x[1])
if __name__ == '__main__':
n, m, k = [int(x) for x in input().split(' ')]
ans_list = list()
ans_list.append((m - 1, 'R'))
ans_list.append((m - 1, 'L'))
for _ in range(n - 1):
ans_list.append((1, 'D'))
ans_list.append((m - 1, 'RUD'))
ans_list.append((m - 1, 'L'))
ans_list.append((n - 1, 'U'))
count = 0
ans = list()
for op in ans_list:
if op[0] == 0:
continue
for x in range(op[0]):
for j in range(len(op[1])):
count += 1
if count == k:
if x > 0:
ans.append((x, op[1]))
ans.append((1, op[1][0:j + 1]))
output_ans(ans)
exit(0)
ans.append((op[0], op[1]))
if k > count:
print('NO')
exit(0)
output_ans(ans)
``` | output | 1 | 98,005 | 15 | 196,011 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.
In order to lose weight, Bashar is going to run for k kilometers. Bashar is going to run in a place that looks like a grid of n rows and m columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4 n m - 2n - 2m) roads.
Let's take, for example, n = 3 and m = 4. In this case, there are 34 roads. It is the picture of this case (arrows describe roads):
<image>
Bashar wants to run by these rules:
* He starts at the top-left cell in the grid;
* In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row i and in the column j, i.e. in the cell (i, j) he will move to:
* in the case 'U' to the cell (i-1, j);
* in the case 'D' to the cell (i+1, j);
* in the case 'L' to the cell (i, j-1);
* in the case 'R' to the cell (i, j+1);
* He wants to run exactly k kilometers, so he wants to make exactly k moves;
* Bashar can finish in any cell of the grid;
* He can't go out of the grid so at any moment of the time he should be on some cell;
* Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times.
Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.
You should give him a steps to do and since Bashar can't remember too many steps, a should not exceed 3000. In every step, you should give him an integer f and a string of moves s of length at most 4 which means that he should repeat the moves in the string s for f times. He will perform the steps in the order you print them.
For example, if the steps are 2 RUD, 3 UUL then the moves he is going to move are RUD + RUD + UUL + UUL + UUL = RUDRUDUULUULUUL.
Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to k kilometers or say, that it is impossible?
Input
The only line contains three integers n, m and k (1 ≤ n, m ≤ 500, 1 ≤ k ≤ 10 ^{9}), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
Output
If there is no possible way to run k kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.
If the answer is "YES", on the second line print an integer a (1 ≤ a ≤ 3000) — the number of steps, then print a lines describing the steps.
To describe a step, print an integer f (1 ≤ f ≤ 10^{9}) and a string of moves s of length at most 4. Every character in s should be 'U', 'D', 'L' or 'R'.
Bashar will start from the top-left cell. Make sure to move exactly k moves without visiting the same road twice and without going outside the grid. He can finish at any cell.
We can show that if it is possible to run exactly k kilometers, then it is possible to describe the path under such output constraints.
Examples
Input
3 3 4
Output
YES
2
2 R
2 L
Input
3 3 1000000000
Output
NO
Input
3 3 8
Output
YES
3
2 R
2 D
1 LLRR
Input
4 4 9
Output
YES
1
3 RLD
Input
3 4 16
Output
YES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
Note
The moves Bashar is going to move in the first example are: "RRLL".
It is not possible to run 1000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.
The moves Bashar is going to move in the third example are: "RRDDLLRR".
The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
<image> | instruction | 0 | 98,006 | 15 | 196,012 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
r = 'R'
l = 'L'
u = 'U'
d = 'D'
def EPath(n,m,k):
f=[]
a=min(m,k)
if(a!=0):
f.append((a,r)) #r
if(a==k):
return f
k = k-a
a=min(m,k)
if(a!=0):
f.append((a,l)) #l
if(a==k):
return f
k = k-a
for _ in range(n): #rmlmudlm
a=min(1,k)
if(a!=0):
f.append((a,d)) #d
if(a==k):
return f
k = k-a
a=min(m,k)
if(a!=0):
f.append((a,r)) #r
if(a==k):
return f
k = k-a
a=min(3*m,k)
if(a==k):
if(a//3 !=0):
f.append((a//3,u+d+l)) #udl
if(a%3==1):
f.append((1,u))
if(a%3==2):
f.append((1,u+d))
return f
else:
if(a!=0):
f.append((m,u+d+l)) #udl
k = k-a
a=min(n,k)
if(a!=0):
f.append((a,u)) #u
if(a==k):
return f
k = k-a
return f
n,m,k = (int(x) for x in input().split())
if(k>(4*n*m-n*2-m*2)):
print('NO')
else:
print('YES')
f = EPath(n-1,m-1,k)
print(len(f))
for i,j in f:
print(i,j)
``` | output | 1 | 98,006 | 15 | 196,013 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.
In order to lose weight, Bashar is going to run for k kilometers. Bashar is going to run in a place that looks like a grid of n rows and m columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4 n m - 2n - 2m) roads.
Let's take, for example, n = 3 and m = 4. In this case, there are 34 roads. It is the picture of this case (arrows describe roads):
<image>
Bashar wants to run by these rules:
* He starts at the top-left cell in the grid;
* In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row i and in the column j, i.e. in the cell (i, j) he will move to:
* in the case 'U' to the cell (i-1, j);
* in the case 'D' to the cell (i+1, j);
* in the case 'L' to the cell (i, j-1);
* in the case 'R' to the cell (i, j+1);
* He wants to run exactly k kilometers, so he wants to make exactly k moves;
* Bashar can finish in any cell of the grid;
* He can't go out of the grid so at any moment of the time he should be on some cell;
* Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times.
Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.
You should give him a steps to do and since Bashar can't remember too many steps, a should not exceed 3000. In every step, you should give him an integer f and a string of moves s of length at most 4 which means that he should repeat the moves in the string s for f times. He will perform the steps in the order you print them.
For example, if the steps are 2 RUD, 3 UUL then the moves he is going to move are RUD + RUD + UUL + UUL + UUL = RUDRUDUULUULUUL.
Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to k kilometers or say, that it is impossible?
Input
The only line contains three integers n, m and k (1 ≤ n, m ≤ 500, 1 ≤ k ≤ 10 ^{9}), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
Output
If there is no possible way to run k kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.
If the answer is "YES", on the second line print an integer a (1 ≤ a ≤ 3000) — the number of steps, then print a lines describing the steps.
To describe a step, print an integer f (1 ≤ f ≤ 10^{9}) and a string of moves s of length at most 4. Every character in s should be 'U', 'D', 'L' or 'R'.
Bashar will start from the top-left cell. Make sure to move exactly k moves without visiting the same road twice and without going outside the grid. He can finish at any cell.
We can show that if it is possible to run exactly k kilometers, then it is possible to describe the path under such output constraints.
Examples
Input
3 3 4
Output
YES
2
2 R
2 L
Input
3 3 1000000000
Output
NO
Input
3 3 8
Output
YES
3
2 R
2 D
1 LLRR
Input
4 4 9
Output
YES
1
3 RLD
Input
3 4 16
Output
YES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
Note
The moves Bashar is going to move in the first example are: "RRLL".
It is not possible to run 1000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.
The moves Bashar is going to move in the third example are: "RRDDLLRR".
The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
<image> | instruction | 0 | 98,007 | 15 | 196,014 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
import sys
read = lambda: list(map(int, sys.stdin.readline().strip().split()))
n, m, k = read()
maxx = 4*n*m-2*n-2*m
if k > maxx:
print("NO")
else:
i = 0
ans = []
while i <= n-1:
#print(i)
if i == n -1:
if m -1 <=k and m-1 >0:
ans.append((m-1, 'R'))
k -= (m-1)
if k == 0:
break
elif m-1 > k:
ans.append((k, 'R'))
k -= k
break
if m-1 <=k and m-1>0:
ans.append((m-1, 'L'))
k -= (m-1)
if k == 0:
break
elif m-1 > k:
ans.append((k, 'L'))
k -= k
break
break
if m-1 <=k and m-1 > 0:
ans.append((m-1, 'R'))
k -= (m-1)
if k == 0:
break
elif m-1 > k:
ans.append((k, 'R'))
k -= k
break
if 3*(m-1) <= k and m-1 > 0:
ans.append((m-1, 'DUL'))
k -= (3*(m-1))
if k == 0:
break
elif 3*(m-1) >k:
if k >= 3:
ans.append((k//3, 'DUL'))
k -= (k//3)*3
if k == 2:
ans.append((1, 'DU'))
k -= 2
if k == 1:
ans.append((1, 'D'))
k -= 1
break
if k > 0:
ans.append((1, 'D'))
k -= 1
i += 1
if k == 0:
break
if k > 0:
ans.append((k, 'U'))
print("YES")
print(len(ans))
for tup in ans:
print(tup[0], tup[1])
``` | output | 1 | 98,007 | 15 | 196,015 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.
In order to lose weight, Bashar is going to run for k kilometers. Bashar is going to run in a place that looks like a grid of n rows and m columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4 n m - 2n - 2m) roads.
Let's take, for example, n = 3 and m = 4. In this case, there are 34 roads. It is the picture of this case (arrows describe roads):
<image>
Bashar wants to run by these rules:
* He starts at the top-left cell in the grid;
* In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row i and in the column j, i.e. in the cell (i, j) he will move to:
* in the case 'U' to the cell (i-1, j);
* in the case 'D' to the cell (i+1, j);
* in the case 'L' to the cell (i, j-1);
* in the case 'R' to the cell (i, j+1);
* He wants to run exactly k kilometers, so he wants to make exactly k moves;
* Bashar can finish in any cell of the grid;
* He can't go out of the grid so at any moment of the time he should be on some cell;
* Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times.
Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.
You should give him a steps to do and since Bashar can't remember too many steps, a should not exceed 3000. In every step, you should give him an integer f and a string of moves s of length at most 4 which means that he should repeat the moves in the string s for f times. He will perform the steps in the order you print them.
For example, if the steps are 2 RUD, 3 UUL then the moves he is going to move are RUD + RUD + UUL + UUL + UUL = RUDRUDUULUULUUL.
Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to k kilometers or say, that it is impossible?
Input
The only line contains three integers n, m and k (1 ≤ n, m ≤ 500, 1 ≤ k ≤ 10 ^{9}), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
Output
If there is no possible way to run k kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.
If the answer is "YES", on the second line print an integer a (1 ≤ a ≤ 3000) — the number of steps, then print a lines describing the steps.
To describe a step, print an integer f (1 ≤ f ≤ 10^{9}) and a string of moves s of length at most 4. Every character in s should be 'U', 'D', 'L' or 'R'.
Bashar will start from the top-left cell. Make sure to move exactly k moves without visiting the same road twice and without going outside the grid. He can finish at any cell.
We can show that if it is possible to run exactly k kilometers, then it is possible to describe the path under such output constraints.
Examples
Input
3 3 4
Output
YES
2
2 R
2 L
Input
3 3 1000000000
Output
NO
Input
3 3 8
Output
YES
3
2 R
2 D
1 LLRR
Input
4 4 9
Output
YES
1
3 RLD
Input
3 4 16
Output
YES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
Note
The moves Bashar is going to move in the first example are: "RRLL".
It is not possible to run 1000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.
The moves Bashar is going to move in the third example are: "RRDDLLRR".
The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
<image> | instruction | 0 | 98,008 | 15 | 196,016 |
Tags: constructive algorithms, graphs, implementation
Correct Solution:
```
import io, os
# import bisect
import sys
import math
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n, m, k = map(int, input().split())
phase = 0
times = 0
if k > 4*n*m-2*m-2*n:
print("NO")
else:
print("YES")
output = []
if n>1:
while(k and times<m-1):
if phase == 0: # down
if k >= (n-1)*3:
output.append((n-1, "DRL"))
k -= 3*(n-1)
else:
if k//3:
output.append((k//3, 'DRL'))
if k % 3:
output.append((1, "DRL"[:k % 3]))
k=0
elif phase == 1:
if k >= (n-1):
output.append((n-1, "U"))
k -= (n-1)
else:
output.append((k, 'U'))
k=0
elif phase == 2:
output.append((1,'R'))
k-=1
times+=1
phase += 1
phase=phase % 3
if k:
output.append((min(k,n-1),'D'))
k -= min(k,n-1)
if k:
output.append((min(k,n-1),'U'))
k -= min(k,n-1)
else:
output.append((min(m-1,k),'R'))
k-=min(m-1,k)
if k:
output.append((k,'L'))
print(len(output))
# print(output)
for zz in output:
print(*zz)
``` | output | 1 | 98,008 | 15 | 196,017 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.