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 |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Submitted Solution:
```
import os, sys
from io import BytesIO, IOBase
from types import GeneratorType
from bisect import bisect_left, bisect_right
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string
import heapq as h, time
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#start_time = time.time()
def getInt(): return int(input())
def getStrs(): return input().split()
def getInts(): return list(map(int,input().split()))
def getStr(): return input()
def listStr(): return list(input())
def getMat(n): return [getInts() for _ in range(n)]
def getBin(): return list(map(int,list(input())))
def isInt(s): return '0' <= s[0] <= '9'
def ceil_(a,b): return a//b + (a%b > 0)
MOD = 10**9 + 7
"""
It's possible if there are no dots between hashes
The min number = the min number of connected components
DSU the points
for i in range(1,N+1), for j in range(1,M+1)
row i column j is cell i*M + j
"""
def solve():
def find(a):
if a != p[a]:
p[a] = find(p[a])
return p[a]
def union(a, b):
a, b = find(a), find(b)
if a == b: return
if size[a] > size[b]:
a, b = b, a
p[a] = b
size[b] += size[a]
return
N, M = getInts()
grid = ['.']*(M+2)
for _ in range(N): grid += ['.'] + listStr() + ['.']
grid += ['.']*(M+2)
N += 2
M += 2
num = N*M
bad_row = bad_col = 0
#Check whether it's possible: i.e. whether #.# exists in any row/col
for i in range(1,N-1):
seen_hash = False
seen_dot = False
for j in range(1,M-1):
if grid[i*M + j] == '#':
if seen_dot:
return -1
seen_hash = True
else:
if seen_hash:
seen_dot = True
if not seen_hash: bad_row = 1
for j in range(1,M-1):
seen_hash = False
seen_dot = False
for i in range(1,N-1):
if grid[i*M + j] == '#':
if seen_dot:
return -1
seen_hash = True
else:
if seen_hash:
seen_dot = True
if not seen_hash: bad_col = 1
if bad_row ^ bad_col: return -1
#If we've made it this far, it's possible and we just need to count connected components
p = [i for i in range(num)]
size = [1]*num
for i in range(num-M-1):
if grid[i] != '#':
p[i] = -i-1
continue
if grid[i+1] == '#':
union(i,i+1)
if grid[i+M] == '#':
union(i,i+M)
ans = set()
for i in range(num-M-1):
if p[i] < 0: continue
f = find(i)
if f != -1: ans.add(f)
return len(ans)
#for _ in range(getInt()):
print(solve())
#solve()
#print(time.time()-start_time)
``` | instruction | 0 | 104,598 | 15 | 209,196 |
Yes | output | 1 | 104,598 | 15 | 209,197 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Submitted Solution:
```
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
l = [''] * n
for i in range(n):
l[i] = input().strip()
works = True
rows = [False] * n
cols = [False] * m
for i in range(n):
for j in range(m):
if l[i][j] == '#':
rows[i] = True
cols[j] = True
if all(rows) ^ all(cols):
works = False
for i in range(n):
s = l[i]
left = -1
right = -1
for j in range(m):
if s[j] == '#':
if left == -1:
left = j
right = j
for j in range(left + 1, right):
if s[j] != '#':
works = False
for j in range(m):
left = -1
right = -1
for i in range(n):
if l[i][j] == '#':
if left == -1:
left = i
right = i
for i in range(left + 1, right):
if l[i][j] != '#':
works = False
if works:
visited = [[False] * m for i in range(n)]
out = 0
for i in range(n):
for j in range(m):
if l[i][j] != '#':
visited[i][j] = True
for startX in range(n):
for startY in range(m):
if not visited[startX][startY]:
out += 1
visited[startX][startY] = True
queue = [(startX, startY)]
while queue:
x, y = queue.pop()
for d in range(4):
nX = x + [0,0,-1,1][d]
nY = y + [1,-1,0,0][d]
if 0 <= nX < n and 0 <= nY < m and not visited[nX][nY]:
visited[nX][nY] = True
queue.append((nX, nY))
print(out)
else:
print(-1)
``` | instruction | 0 | 104,599 | 15 | 209,198 |
Yes | output | 1 | 104,599 | 15 | 209,199 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Submitted Solution:
```
import sys
input = sys.stdin.readline
I = lambda : list(input().split())
a,b,=I()
flag=0
sparse=dict()
cc=cr=0
for i in range(int(a)):
x,=I()
adj=[]
for k in range(int(b)):
if k not in sparse:
sparse[k]=list()
if x[k]=='#':
adj.append(k)
sparse[k].append(i)
if len(adj)==0:
cr+=1
elif sorted(adj)!=list(range(min(adj),max(adj)+1)):
flag=1
break
for keys in list(sparse):
if len(sparse[keys])!=0 and (sorted(sparse[keys])!=list(range(min(sparse[keys]),max(sparse[keys])+1))):
flag=1
break
elif len(sparse[keys])==0:
sparse.pop(keys)
cc+=1
if flag==0:
if cr==cc:
flag=0
elif cr==int(a) and cc==int(b):
flag=2
print('0')
else:
flag=1
if flag==1:
print('-1')
if flag==0:
count=0
visited=[]
def check(sparse,item,key):
global count
global visited,a,b
if key in sparse:
if item in sparse[key]:
sparse[key].remove(item)
visited.append([key,item])
c=0
if len(sparse[key])==0:
sparse.pop(key)
if item-1>=0:
c+=check(sparse,item-1,key)
if item+1<=int(a):
c+=check(sparse,item+1,key)
if key-1>=0:
c+=check(sparse,item,key-1)
if key+1<=int(b):
c+=check(sparse,item,key+1)
if c==0:
return 1
else:
return c
else:
return 0
else:
return 0
for key in list(sparse):
if key in sparse:
for item in sparse[key]:
if [key,item] not in visited:
count+=check(sparse,item,key)
print(count)
``` | instruction | 0 | 104,600 | 15 | 209,200 |
No | output | 1 | 104,600 | 15 | 209,201 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Submitted Solution:
```
import sys
input = sys.stdin.buffer.readline
def print(val):
sys.stdout.write(str(val) + '\n')
from collections import deque
def find_components(node,graph,n,m,visited):
queue = deque([node])
while queue:
node = queue[-1]
visited.add(node)
neighbors = [(node[0]+1,node[1]),(node[0]-1,node[1]),\
(node[0],node[1]+1),(node[0],node[1]-1)]
had_neighbors = False
for neighbor in neighbors:
i,j = neighbor
if neighbor not in visited and 0<= i < n and 0<= j < m and graph[i][j] == '#':
queue.append(neighbor)
had_neighbors = True
break
if not had_neighbors:
queue.pop()
def yo():
n,m = map(int,input().split())
graph = [str(input().strip())[2:] for i in range(n)]
e_row = 0
e_column = 0
for row in graph:
if row == "."*m:
e_row = 1
break
for j in range(m):
same = True
for i in range(n):
if graph[i][j] != '.':
same = False
break
if same:
e_column = 1
break
if e_row^e_column == 1:
print(-1)
return
for row in graph:
start = m-1
value = '#'
for j in range(m):
if row[j] == '#':
start = j
break
change = False
gap = False
for j in range(start+1,m):
if row[j] != value:
change = True
elif change:
gap = True
if gap:
print(-1)
break
if not gap:
for j in range(m):
start = n-1
value = '#'
for i in range(n):
if graph[i][j] == '#':
start = i
break
change = False
gap = False
for i in range(start+1,n):
if graph[i][j] != value:
change = True
elif change:
gap = True
if gap:
print(-1)
break
if not gap:
visited = set()
num_components = 0
for i in range(n):
for j in range(m):
if (i,j) not in visited and graph[i][j] == '#':
num_components += 1
find_components((i,j),graph,n,m,visited)
print(num_components)
yo()
``` | instruction | 0 | 104,601 | 15 | 209,202 |
No | output | 1 | 104,601 | 15 | 209,203 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Submitted Solution:
```
n,m=map(int,input().split())
L=[]
for _ in range(n):
L.append(list(input()))
#print(L)
visited=set()
islands=[]
island=1
for i in range(n):
for j in range(m):
if (i,j) not in visited and L[i][j]=="#":
islands.append(1)
stack=[(i,j)]
while stack:
I,J=stack.pop()
visited.add((I,J))
p=[(1,0),(-1,0),(0,1),(0,-1)]
for t in p:
g,h=I+t[0],J+t[1]
if (g,h) not in visited and 0<=g<n and 0<=h<m and L[g][h]=="#":
stack.append((g,h))
#mark(i,j,island)
island+=1
def checkline(arr):
## print(arr)
## lmn=arr.count("#")
## if lmn==1 or lmn==0:
## return True
## return False
##
va=-1
for i in range(len(arr)):
if va==2 and arr[i]=="#":
return False
elif va==1 and arr[i]==".":
va=2
elif arr[i]=="#":
va=1
return True
ans=0
for i in range(n):
if not checkline(L[i]):
ans=-1
break
for j in range(m):
B=[]
for i in range(n):
B.append(L[i][j])
if not checkline(B):
ans=-1
break
if ans!=-1:
p=""
if n==1 or m==1:
for i in range(n):
for j in range(m):
p+=L[i][j]
if 0<p.count("#")<len(p):
print(-1)
elif p.count("#")==len(p):
print(1)
else:
print(0)
else:
print(len(islands))
else:
print(-1)
``` | instruction | 0 | 104,602 | 15 | 209,204 |
No | output | 1 | 104,602 | 15 | 209,205 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Submitted Solution:
```
x,y=[int(i) for i in input().split()]
a=[]
for i in range(x):
a.append(input())
spacer=[0]*x
spaces=[]
for i in range(y):
spaces.append(spacer[::])
tec=['.',0]
rowx=[]
for i in range(x):
rowx.append(tec[::])
rowy=[]
for i in range(y):
rowy.append(tec[::])
nums=0
for i in range(x):
for j in range(y):
if a[i][j]=='.':
if rowy[j][0]=='#':
rowy[j][1]+=1
rowy[j][0]='.'
if rowx[i][0]=='#':
rowx[i][0]='.'
rowx[i][1]+=1
try:
if a[i+1][j]=='#':
spaces[j][i+1]=1
nums+=1
if a[i][j+1]=='#':
spaces[j+1][i]=1
nums+=1
except IndexError:
pass
else:
if rowy[j][0]=='.':
rowy[j][1]+=1
rowy[j][0]='#'
if rowx[i][0]=='.':
rowx[i][1]+=1
rowx[i][0]='#'
if spaces[j][i]==0:
spaces[j][i]=1
nums+=1
try:
if a[i+1][j]=='#':
if spaces[j][i+1]==1:
nums-=1
spaces[j][i+1]=1
if a[j+1][i]=='#':
if spaces[j+1][i]==1:
nums-=1
spaces[j+1][i]=1
except IndexError:
pass
flag=0
summ=0
for i in range(x):
summ+=rowx[i][1]
if rowx[i][1]>2 or rowx[i][1]==0:
flag=1
if summ==0:
flag=0
if flag==0:
for i in range(y):
summ+=rowy[i][1]
if rowy[i][1]>2 or rowy[i][1]==0:
flag=1
if summ==0:
flag=0
if flag==1:
print(-1)
else:
print(nums)
``` | instruction | 0 | 104,603 | 15 | 209,206 |
No | output | 1 | 104,603 | 15 | 209,207 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first.
Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order.
* Choose a starting cell (r_1, c_1) with non-zero value.
* Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2.
* Decrease the value of the starting cell by some positive non-zero integer.
* Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that:
* a shortest path is one that passes through the least number of cells;
* all cells on this path excluding the starting cell, but the finishing cell may be modified;
* the resulting value of each cell must be a non-negative integer;
* the cells are modified independently and not necessarily by the same value.
If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed.
The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally.
Given the initial matrix, if both players play optimally, can you predict who will win?
Input
The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows.
The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix.
The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix.
Output
For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes).
Example
Input
4
1 1
0
1 3
0 0 5
2 2
0 1
1 0
3 3
1 2 3
4 5 6
7 8 9
Output
Jeel
Ashish
Jeel
Ashish
Note
In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner.
In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins. | instruction | 0 | 104,653 | 15 | 209,306 |
Tags: constructive algorithms, games
Correct Solution:
```
from sys import stdin, gettrace
if gettrace():
inputi = input
else:
def input():
return next(stdin)[:-1]
def inputi():
return stdin.buffer.readline()
def solve():
n,m = map(int, inputi().split())
aa = [[int(a) for a in inputi().split()] for _ in range(n)]
xor = [0] * (n+m)
for i in range(n):
for j in range(m):
xor[i+j] ^= aa[i][j]
if any(x != 0 for x in xor):
print("Ashish")
else:
print("Jeel")
def main():
t = int(inputi())
for _ in range(t):
solve()
if __name__ == "__main__":
main()
``` | output | 1 | 104,653 | 15 | 209,307 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first.
Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order.
* Choose a starting cell (r_1, c_1) with non-zero value.
* Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2.
* Decrease the value of the starting cell by some positive non-zero integer.
* Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that:
* a shortest path is one that passes through the least number of cells;
* all cells on this path excluding the starting cell, but the finishing cell may be modified;
* the resulting value of each cell must be a non-negative integer;
* the cells are modified independently and not necessarily by the same value.
If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed.
The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally.
Given the initial matrix, if both players play optimally, can you predict who will win?
Input
The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows.
The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix.
The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix.
Output
For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes).
Example
Input
4
1 1
0
1 3
0 0 5
2 2
0 1
1 0
3 3
1 2 3
4 5 6
7 8 9
Output
Jeel
Ashish
Jeel
Ashish
Note
In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner.
In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins. | instruction | 0 | 104,654 | 15 | 209,308 |
Tags: constructive algorithms, games
Correct Solution:
```
def solve_case():
n, m = [int(x) for x in input().split()]
a = [[int(x) for x in input().split()] for x in range(n)]
xr = [0] * (n + m)
for i in range(n):
for j in range(m):
xr[i + j] ^= a[i][j]
return sum(xr) > 0
def main():
for _ in range(int(input())):
print(['Jeel', 'Ashish'][solve_case()])
main()
``` | output | 1 | 104,654 | 15 | 209,309 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first.
Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order.
* Choose a starting cell (r_1, c_1) with non-zero value.
* Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2.
* Decrease the value of the starting cell by some positive non-zero integer.
* Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that:
* a shortest path is one that passes through the least number of cells;
* all cells on this path excluding the starting cell, but the finishing cell may be modified;
* the resulting value of each cell must be a non-negative integer;
* the cells are modified independently and not necessarily by the same value.
If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed.
The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally.
Given the initial matrix, if both players play optimally, can you predict who will win?
Input
The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows.
The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix.
The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix.
Output
For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes).
Example
Input
4
1 1
0
1 3
0 0 5
2 2
0 1
1 0
3 3
1 2 3
4 5 6
7 8 9
Output
Jeel
Ashish
Jeel
Ashish
Note
In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner.
In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins. | instruction | 0 | 104,655 | 15 | 209,310 |
Tags: constructive algorithms, games
Correct Solution:
```
def solve_case():
n, m = [int(x) for x in input().split()];a = [[int(x) for x in input().split()] for x in range(n)];xr = [0] * (n + m)
for i in range(n):
for j in range(m):xr[i + j] ^= a[i][j]
return sum(xr) > 0
for _ in range(int(input())):print(['Jeel', 'Ashish'][solve_case()])
``` | output | 1 | 104,655 | 15 | 209,311 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first.
Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order.
* Choose a starting cell (r_1, c_1) with non-zero value.
* Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2.
* Decrease the value of the starting cell by some positive non-zero integer.
* Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that:
* a shortest path is one that passes through the least number of cells;
* all cells on this path excluding the starting cell, but the finishing cell may be modified;
* the resulting value of each cell must be a non-negative integer;
* the cells are modified independently and not necessarily by the same value.
If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed.
The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally.
Given the initial matrix, if both players play optimally, can you predict who will win?
Input
The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows.
The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix.
The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix.
Output
For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes).
Example
Input
4
1 1
0
1 3
0 0 5
2 2
0 1
1 0
3 3
1 2 3
4 5 6
7 8 9
Output
Jeel
Ashish
Jeel
Ashish
Note
In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner.
In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins. | instruction | 0 | 104,656 | 15 | 209,312 |
Tags: constructive algorithms, games
Correct Solution:
```
def solve():
n, m = [int(x) for x in input().split()]
a = []
for i in range(n):
v =[int(x) for x in input().split()]
a.append(v)
xorsums = [0] * (n+m-1)
for i in range(n):
for j in range(m):
xorsums[i+j] ^= a[i][j]
f = 0
for i in range(n+m-1):
if xorsums[i] !=0:
f = 1
if f == 1:
print('Ashish')
else:
print('Jeel')
def main():
t = int(input())
for i in range(t):
solve()
main()
``` | output | 1 | 104,656 | 15 | 209,313 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first.
Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order.
* Choose a starting cell (r_1, c_1) with non-zero value.
* Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2.
* Decrease the value of the starting cell by some positive non-zero integer.
* Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that:
* a shortest path is one that passes through the least number of cells;
* all cells on this path excluding the starting cell, but the finishing cell may be modified;
* the resulting value of each cell must be a non-negative integer;
* the cells are modified independently and not necessarily by the same value.
If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed.
The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally.
Given the initial matrix, if both players play optimally, can you predict who will win?
Input
The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows.
The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix.
The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix.
Output
For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes).
Example
Input
4
1 1
0
1 3
0 0 5
2 2
0 1
1 0
3 3
1 2 3
4 5 6
7 8 9
Output
Jeel
Ashish
Jeel
Ashish
Note
In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner.
In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins. | instruction | 0 | 104,657 | 15 | 209,314 |
Tags: constructive algorithms, games
Correct Solution:
```
def nullify(n, m, mat):
xor = [0 for i in range(n+m-1)]
for i in range(n):
for j in range(m):
xor[i+j] ^= mat[i][j]
for i in range(n+m-1):
if xor[i]:
return "Ashish"
return "Jeel"
t = int(input())
for i in range(t):
mat = []
n, m = map(int, input().split())
for j in range(n):
mat.append(list(map(int, input().split())))
print(nullify(n, m, mat))
``` | output | 1 | 104,657 | 15 | 209,315 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first.
Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order.
* Choose a starting cell (r_1, c_1) with non-zero value.
* Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2.
* Decrease the value of the starting cell by some positive non-zero integer.
* Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that:
* a shortest path is one that passes through the least number of cells;
* all cells on this path excluding the starting cell, but the finishing cell may be modified;
* the resulting value of each cell must be a non-negative integer;
* the cells are modified independently and not necessarily by the same value.
If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed.
The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally.
Given the initial matrix, if both players play optimally, can you predict who will win?
Input
The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows.
The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix.
The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix.
Output
For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes).
Example
Input
4
1 1
0
1 3
0 0 5
2 2
0 1
1 0
3 3
1 2 3
4 5 6
7 8 9
Output
Jeel
Ashish
Jeel
Ashish
Note
In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner.
In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins. | instruction | 0 | 104,658 | 15 | 209,316 |
Tags: constructive algorithms, games
Correct Solution:
```
def main():
from sys import stdin
#from math import gcd
from random import randint, choice, shuffle
from functools import lru_cache
input = stdin.readline
#input = open('in', 'r').readline
for _ in range(int(input())):
n, m = map(int, input().split())
a = [[*map(int, input().split())] for i in range(n)]
x = [0] * (n + m)
for i in range(n):
for j in range(m):
x[i + j] ^= a[i][j]
if sum(x) == 0:
print('Jeel')
else:
print('Ashish')
main()
``` | output | 1 | 104,658 | 15 | 209,317 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first.
Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order.
* Choose a starting cell (r_1, c_1) with non-zero value.
* Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2.
* Decrease the value of the starting cell by some positive non-zero integer.
* Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that:
* a shortest path is one that passes through the least number of cells;
* all cells on this path excluding the starting cell, but the finishing cell may be modified;
* the resulting value of each cell must be a non-negative integer;
* the cells are modified independently and not necessarily by the same value.
If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed.
The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally.
Given the initial matrix, if both players play optimally, can you predict who will win?
Input
The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows.
The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix.
The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix.
Output
For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes).
Example
Input
4
1 1
0
1 3
0 0 5
2 2
0 1
1 0
3 3
1 2 3
4 5 6
7 8 9
Output
Jeel
Ashish
Jeel
Ashish
Note
In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner.
In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins. | instruction | 0 | 104,659 | 15 | 209,318 |
Tags: constructive algorithms, games
Correct Solution:
```
#
# author: vongkh
# created: Wed Nov 25 2020
#
from sys import stdin, stdout # only need for big input
def solve():
n, m = list(map(int, input().split()))
a = [[0] * m for _ in range(n)]
for i in range(n):
a[i] = list(map(int, input().split()))
#the point is to find a win condition for yourself and
#force your oponent to be in the lose condition
#the win condition is this problem is a simple implementation
#but the proof is math heavy. Please check the official editorial
win = False
for diagonal in range(n + m - 1):
xor = 0
for i in range(diagonal + 1):
j = diagonal - i
if j >= m or i >= n:
continue
xor = xor ^ a[i][j]
if xor != 0:
win = True
if win :
print("Ashish")
else:
print("Jeel")
def main():
t = 1
t = int(input())
for _ in range(t):
solve()
if __name__ == "__main__":
main()
``` | output | 1 | 104,659 | 15 | 209,319 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first.
Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order.
* Choose a starting cell (r_1, c_1) with non-zero value.
* Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2.
* Decrease the value of the starting cell by some positive non-zero integer.
* Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that:
* a shortest path is one that passes through the least number of cells;
* all cells on this path excluding the starting cell, but the finishing cell may be modified;
* the resulting value of each cell must be a non-negative integer;
* the cells are modified independently and not necessarily by the same value.
If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed.
The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally.
Given the initial matrix, if both players play optimally, can you predict who will win?
Input
The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows.
The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix.
The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix.
Output
For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes).
Example
Input
4
1 1
0
1 3
0 0 5
2 2
0 1
1 0
3 3
1 2 3
4 5 6
7 8 9
Output
Jeel
Ashish
Jeel
Ashish
Note
In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner.
In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins. | instruction | 0 | 104,660 | 15 | 209,320 |
Tags: constructive algorithms, games
Correct Solution:
```
from functools import reduce
def main():
N=int(input())
for _ in range(N):
r,c=map(int,input().split())
M=[list(map(int,input().split())) for _ in range(r)]
L=[reduce(lambda x,y:x^y, (M[s-k][k] for k in range(max(s-r+1,0),min(s,c-1)+1))) for s in range(r+c-1)]
print("Jeel" if all(x==0 for x in L) else "Ashish")
main()
``` | output | 1 | 104,660 | 15 | 209,321 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first.
Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order.
* Choose a starting cell (r_1, c_1) with non-zero value.
* Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2.
* Decrease the value of the starting cell by some positive non-zero integer.
* Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that:
* a shortest path is one that passes through the least number of cells;
* all cells on this path excluding the starting cell, but the finishing cell may be modified;
* the resulting value of each cell must be a non-negative integer;
* the cells are modified independently and not necessarily by the same value.
If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed.
The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally.
Given the initial matrix, if both players play optimally, can you predict who will win?
Input
The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows.
The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix.
The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix.
Output
For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes).
Example
Input
4
1 1
0
1 3
0 0 5
2 2
0 1
1 0
3 3
1 2 3
4 5 6
7 8 9
Output
Jeel
Ashish
Jeel
Ashish
Note
In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner.
In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins.
Submitted Solution:
```
from sys import stdin, gettrace
if gettrace():
inputi = input
else:
def input():
return next(stdin)[:-1]
def inputi():
return stdin.buffer.readline()
def solve():
n,m = map(int, inputi().split())
aa = [[int(a) for a in inputi().split()] for _ in range(n)]
for i in range(max(n, m)):
xor = 0
for j in range(max(0, i-n+1), min(i+1,m)):
xor ^= aa[i-j][j]
if xor != 0:
print("Ashish")
return
print("Jeel")
def main():
t = int(inputi())
for _ in range(t):
solve()
if __name__ == "__main__":
main()
``` | instruction | 0 | 104,661 | 15 | 209,322 |
No | output | 1 | 104,661 | 15 | 209,323 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first.
Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order.
* Choose a starting cell (r_1, c_1) with non-zero value.
* Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2.
* Decrease the value of the starting cell by some positive non-zero integer.
* Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that:
* a shortest path is one that passes through the least number of cells;
* all cells on this path excluding the starting cell, but the finishing cell may be modified;
* the resulting value of each cell must be a non-negative integer;
* the cells are modified independently and not necessarily by the same value.
If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed.
The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally.
Given the initial matrix, if both players play optimally, can you predict who will win?
Input
The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows.
The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix.
The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix.
Output
For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes).
Example
Input
4
1 1
0
1 3
0 0 5
2 2
0 1
1 0
3 3
1 2 3
4 5 6
7 8 9
Output
Jeel
Ashish
Jeel
Ashish
Note
In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner.
In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins.
Submitted Solution:
```
from sys import stdin
tt = int(stdin.readline())
for loop in range(tt):
n,m = map(int,stdin.readline().split())
a = 0
for i in range(n):
tmp = list(map(int,stdin.readline().split()))
for j in tmp:
a ^= j
if a == 0:
print ("Jeel")
else:
print ("Ashish")
``` | instruction | 0 | 104,662 | 15 | 209,324 |
No | output | 1 | 104,662 | 15 | 209,325 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first.
Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order.
* Choose a starting cell (r_1, c_1) with non-zero value.
* Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2.
* Decrease the value of the starting cell by some positive non-zero integer.
* Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that:
* a shortest path is one that passes through the least number of cells;
* all cells on this path excluding the starting cell, but the finishing cell may be modified;
* the resulting value of each cell must be a non-negative integer;
* the cells are modified independently and not necessarily by the same value.
If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed.
The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally.
Given the initial matrix, if both players play optimally, can you predict who will win?
Input
The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows.
The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix.
The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix.
Output
For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes).
Example
Input
4
1 1
0
1 3
0 0 5
2 2
0 1
1 0
3 3
1 2 3
4 5 6
7 8 9
Output
Jeel
Ashish
Jeel
Ashish
Note
In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner.
In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins.
Submitted Solution:
```
#
# author: vongkh
# created: Wed Nov 25 2020
#
from sys import stdin, stdout # only need for big input
def solve():
n, m = list(map(int, input().split()))
a = [[0] * m for _ in range(n)]
for i in range(n):
a[i] = list(map(int, input().split()))
#the point is to find a win condition for yourself and
#force your oponent to be in the lose condition
#the win condition is this problem is a simple implementation
#but the proof is math heavy. Please check the official editorial
win = False
for diagonal in range(n + m - 1):
xor = 0
for i in range(min(n, diagonal+1)):
j = diagonal - i
if j >= m :
break
xor = xor ^ a[i][j]
if xor != 0:
win = True
if win :
print("Ashish")
else:
print("Jeel")
def main():
t = 1
t = int(input())
for _ in range(t):
solve()
if __name__ == "__main__":
main()
``` | instruction | 0 | 104,663 | 15 | 209,326 |
No | output | 1 | 104,663 | 15 | 209,327 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Jeel and Ashish play a game on an n × m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first.
Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order.
* Choose a starting cell (r_1, c_1) with non-zero value.
* Choose a finishing cell (r_2, c_2) such that r_1 ≤ r_2 and c_1 ≤ c_2.
* Decrease the value of the starting cell by some positive non-zero integer.
* Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that:
* a shortest path is one that passes through the least number of cells;
* all cells on this path excluding the starting cell, but the finishing cell may be modified;
* the resulting value of each cell must be a non-negative integer;
* the cells are modified independently and not necessarily by the same value.
If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed.
The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally.
Given the initial matrix, if both players play optimally, can you predict who will win?
Input
The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of each test case is as follows.
The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 100) — the dimensions of the matrix.
The next n lines contain m space separated integers a_{i,j} (0 ≤ a_{i,j} ≤ 10^6) — the values of each cell of the matrix.
Output
For each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes).
Example
Input
4
1 1
0
1 3
0 0 5
2 2
0 1
1 0
3 3
1 2 3
4 5 6
7 8 9
Output
Jeel
Ashish
Jeel
Ashish
Note
In the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner.
In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins.
Submitted Solution:
```
from sys import stdin
tt = int(stdin.readline())
for loop in range(tt):
n,m = map(int,stdin.readline().split())
lis = []
for i in range(n):
tmp = list(map(int,stdin.readline().split()))
lis.append(tmp)
a = 0
s = 0
for k in range(n+m):
for i in range(n):
j = k-i
if j < 0 or m <= j:
continue
a ^= lis[i][j]
s += lis[i][j]
if s > 0:
break
if a == 0:
print ("Jeel")
else:
print ("Ashish")
``` | instruction | 0 | 104,664 | 15 | 209,328 |
No | output | 1 | 104,664 | 15 | 209,329 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.
Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.
Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument.
Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points!
Input
The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points.
Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point.
Output
It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1.
Example
Input
3 5
1 4 4 3 4
1 4 1 4 2
1 4 4 4 3
Output
166374062
Note
Let's look at all possible orders of cities Monuments will be build in:
* [1, 2, 3]:
* the first city controls all points at distance at most 3, in other words, points 1 and 4;
* the second city controls all points at distance at most 2, or points 1, 3 and 5;
* the third city controls all points at distance at most 1, or point 1.
In total, 4 points are controlled.
* [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points.
* [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points.
* [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points.
The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} | instruction | 0 | 104,685 | 15 | 209,370 |
Tags: combinatorics, dp, math, probabilities, two pointers
Correct Solution:
```
p=998244353
def f(x,y):
r=1
x=x%p
if x==0:
return 0
while y>0:
if y%2==1:
r=(r*x)%p
y=y>>1
x=(x*x)%p
return r
n,m=map(int,input().split())
l=[]
for _ in range(n):
l.append(list(map(int,input().split())))
a=1
for i in range(1,n+1):
a=(a*i)%p
q=0
for i in range(m):
v=[0]*n
for j in range(n):
v[j]=l[j][i]
v.sort()
x=1
for j in range(n):
x=(x*(min(v[j]-1,n)-j))%p
q=(q+a-x)%p
print((q*f(a,p-2))%p)
``` | output | 1 | 104,685 | 15 | 209,371 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.
Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.
Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument.
Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points!
Input
The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points.
Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point.
Output
It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1.
Example
Input
3 5
1 4 4 3 4
1 4 1 4 2
1 4 4 4 3
Output
166374062
Note
Let's look at all possible orders of cities Monuments will be build in:
* [1, 2, 3]:
* the first city controls all points at distance at most 3, in other words, points 1 and 4;
* the second city controls all points at distance at most 2, or points 1, 3 and 5;
* the third city controls all points at distance at most 1, or point 1.
In total, 4 points are controlled.
* [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points.
* [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points.
* [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points.
The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} | instruction | 0 | 104,686 | 15 | 209,372 |
Tags: combinatorics, dp, math, probabilities, two pointers
Correct Solution:
```
ans = 0
n,m = map(int,input().split())
mod = 998244353
a = [list(map(int,input().split())) for i in range(n)]
fac = 1
for i in range(1,n+1): fac *= i
inv = pow(fac,mod-2,mod)
for j in range(m):
na = sorted([a[i][j] for i in range(n)])
now = 1
able = 0
for i in range(n):
while len(na) > 0 and na[-1] > n-i:
del na[-1]
able += 1
now *= able
able -= 1
ans += now * inv
ans %= mod
print ((m-ans) % mod)
``` | output | 1 | 104,686 | 15 | 209,373 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.
Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.
Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument.
Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points!
Input
The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points.
Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point.
Output
It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1.
Example
Input
3 5
1 4 4 3 4
1 4 1 4 2
1 4 4 4 3
Output
166374062
Note
Let's look at all possible orders of cities Monuments will be build in:
* [1, 2, 3]:
* the first city controls all points at distance at most 3, in other words, points 1 and 4;
* the second city controls all points at distance at most 2, or points 1, 3 and 5;
* the third city controls all points at distance at most 1, or point 1.
In total, 4 points are controlled.
* [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points.
* [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points.
* [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points.
The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} | instruction | 0 | 104,687 | 15 | 209,374 |
Tags: combinatorics, dp, math, probabilities, two pointers
Correct Solution:
```
n, m = map(int, input().split())
mod = 998244353
dis = [[0]*(m+1) for i in range(n+1)]
# dis = [[1,4,4,3,4], [1,4,1,4,2], [1,4,4,4,3]]
jc = 1
ans = 0
def ksm(a, b, p):
a = a%p
b = b%(p-1)
cheng = a
ret = 1
while b>0:
if b%2:
ret = ret*cheng%p
cheng = cheng*cheng%p
b //= 2
return ret
def inv(a, p=mod):
return ksm(a, p-2, p)
for i in range(n):
jc = jc*(i+1)%mod
for i in range(n):
t = list(map(int, input().split()))
for j in range(m):
dis[i][j] = t[j]
for i in range(m):
c = [0]*(n)
for j in range(n):
c[j] = dis[j][i] - 1
c.sort()
ret = 1
for index, j in enumerate(c):
ret = ret * max(0, j-index)
ret = ret*inv(jc)%mod
ret = ((1 - ret)%mod + mod)%mod
ans = (ans + ret)%mod
print(ans)
``` | output | 1 | 104,687 | 15 | 209,375 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.
Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.
Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument.
Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points!
Input
The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points.
Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point.
Output
It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1.
Example
Input
3 5
1 4 4 3 4
1 4 1 4 2
1 4 4 4 3
Output
166374062
Note
Let's look at all possible orders of cities Monuments will be build in:
* [1, 2, 3]:
* the first city controls all points at distance at most 3, in other words, points 1 and 4;
* the second city controls all points at distance at most 2, or points 1, 3 and 5;
* the third city controls all points at distance at most 1, or point 1.
In total, 4 points are controlled.
* [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points.
* [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points.
* [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points.
The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} | instruction | 0 | 104,688 | 15 | 209,376 |
Tags: combinatorics, dp, math, probabilities, two pointers
Correct Solution:
```
def divisors(M):
d=[]
i=1
while M>=i**2:
if M%i==0:
d.append(i)
if i**2!=M:
d.append(M//i)
i=i+1
return d
def popcount(x):
x = x - ((x >> 1) & 0x55555555)
x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
x = (x + (x >> 4)) & 0x0f0f0f0f
x = x + (x >> 8)
x = x + (x >> 16)
return x & 0x0000007f
def eratosthenes(n):
res=[0 for i in range(n+1)]
prime=set([])
for i in range(2,n+1):
if not res[i]:
prime.add(i)
for j in range(1,n//i+1):
res[i*j]=1
return prime
def factorization(n):
res=[]
for p in prime:
if n%p==0:
while n%p==0:
n//=p
res.append(p)
if n!=1:
res.append(n)
return res
def euler_phi(n):
res = n
for x in range(2,n+1):
if x ** 2 > n:
break
if n%x==0:
res = res//x * (x-1)
while n%x==0:
n //= x
if n!=1:
res = res//n * (n-1)
return res
def ind(b,n):
res=0
while n%b==0:
res+=1
n//=b
return res
def isPrimeMR(n):
d = n - 1
d = d // (d & -d)
L = [2, 3, 5, 7, 11, 13, 17]
for a in L:
t = d
y = pow(a, t, n)
if y == 1: continue
while y != n - 1:
y = (y * y) % n
if y == 1 or t == n - 1: return 0
t <<= 1
return 1
def findFactorRho(n):
from math import gcd
m = 1 << n.bit_length() // 8
for c in range(1, 99):
f = lambda x: (x * x + c) % n
y, r, q, g = 2, 1, 1, 1
while g == 1:
x = y
for i in range(r):
y = f(y)
k = 0
while k < r and g == 1:
ys = y
for i in range(min(m, r - k)):
y = f(y)
q = q * abs(x - y) % n
g = gcd(q, n)
k += m
r <<= 1
if g == n:
g = 1
while g == 1:
ys = f(ys)
g = gcd(abs(x - ys), n)
if g < n:
if isPrimeMR(g): return g
elif isPrimeMR(n // g): return n // g
return findFactorRho(g)
def primeFactor(n):
i = 2
ret = {}
rhoFlg = 0
while i*i <= n:
k = 0
while n % i == 0:
n //= i
k += 1
if k: ret[i] = k
i += 1 + i % 2
if i == 101 and n >= 2 ** 20:
while n > 1:
if isPrimeMR(n):
ret[n], n = 1, 1
else:
rhoFlg = 1
j = findFactorRho(n)
k = 0
while n % j == 0:
n //= j
k += 1
ret[j] = k
if n > 1: ret[n] = 1
if rhoFlg: ret = {x: ret[x] for x in sorted(ret)}
return ret
def divisors(n):
res = [1]
prime = primeFactor(n)
for p in prime:
newres = []
for d in res:
for j in range(prime[p]+1):
newres.append(d*p**j)
res = newres
res.sort()
return res
def xorfactorial(num):
if num==0:
return 0
elif num==1:
return 1
elif num==2:
return 3
elif num==3:
return 0
else:
x=baseorder(num)
return (2**x)*((num-2**x+1)%2)+function(num-2**x)
def xorconv(n,X,Y):
if n==0:
res=[(X[0]*Y[0])%mod]
return res
x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))]
y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))]
z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))]
w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))]
res1=xorconv(n-1,x,y)
res2=xorconv(n-1,z,w)
former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))]
latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))]
former=list(map(lambda x:x%mod,former))
latter=list(map(lambda x:x%mod,latter))
return former+latter
def merge_sort(A,B):
pos_A,pos_B = 0,0
n,m = len(A),len(B)
res = []
while pos_A < n and pos_B < m:
a,b = A[pos_A],B[pos_B]
if a < b:
res.append(a)
pos_A += 1
else:
res.append(b)
pos_B += 1
res += A[pos_A:]
res += B[pos_B:]
return res
class UnionFindVerSize():
def __init__(self, N):
self._parent = [n for n in range(0, N)]
self._size = [1] * N
self.group = N
def find_root(self, x):
if self._parent[x] == x: return x
self._parent[x] = self.find_root(self._parent[x])
stack = [x]
while self._parent[stack[-1]]!=stack[-1]:
stack.append(self._parent[stack[-1]])
for v in stack:
self._parent[v] = stack[-1]
return self._parent[x]
def unite(self, x, y):
gx = self.find_root(x)
gy = self.find_root(y)
if gx == gy: return
self.group -= 1
if self._size[gx] < self._size[gy]:
self._parent[gx] = gy
self._size[gy] += self._size[gx]
else:
self._parent[gy] = gx
self._size[gx] += self._size[gy]
def get_size(self, x):
return self._size[self.find_root(x)]
def is_same_group(self, x, y):
return self.find_root(x) == self.find_root(y)
class WeightedUnionFind():
def __init__(self,N):
self.parent = [i for i in range(N)]
self.size = [1 for i in range(N)]
self.val = [0 for i in range(N)]
self.flag = True
self.edge = [[] for i in range(N)]
def dfs(self,v,pv):
stack = [(v,pv)]
new_parent = self.parent[pv]
while stack:
v,pv = stack.pop()
self.parent[v] = new_parent
for nv,w in self.edge[v]:
if nv!=pv:
self.val[nv] = self.val[v] + w
stack.append((nv,v))
def unite(self,x,y,w):
if not self.flag:
return
if self.parent[x]==self.parent[y]:
self.flag = (self.val[x] - self.val[y] == w)
return
if self.size[self.parent[x]]>self.size[self.parent[y]]:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[x] += self.size[y]
self.val[y] = self.val[x] - w
self.dfs(y,x)
else:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[y] += self.size[x]
self.val[x] = self.val[y] + w
self.dfs(x,y)
class Dijkstra():
class Edge():
def __init__(self, _to, _cost):
self.to = _to
self.cost = _cost
def __init__(self, V):
self.G = [[] for i in range(V)]
self._E = 0
self._V = V
@property
def E(self):
return self._E
@property
def V(self):
return self._V
def add_edge(self, _from, _to, _cost):
self.G[_from].append(self.Edge(_to, _cost))
self._E += 1
def shortest_path(self, s):
import heapq
que = []
d = [10**15] * self.V
d[s] = 0
heapq.heappush(que, (0, s))
while len(que) != 0:
cost, v = heapq.heappop(que)
if d[v] < cost: continue
for i in range(len(self.G[v])):
e = self.G[v][i]
if d[e.to] > d[v] + e.cost:
d[e.to] = d[v] + e.cost
heapq.heappush(que, (d[e.to], e.to))
return d
#Z[i]:length of the longest list starting from S[i] which is also a prefix of S
#O(|S|)
def Z_algorithm(s):
N = len(s)
Z_alg = [0]*N
Z_alg[0] = N
i = 1
j = 0
while i < N:
while i+j < N and s[j] == s[i+j]:
j += 1
Z_alg[i] = j
if j == 0:
i += 1
continue
k = 1
while i+k < N and k + Z_alg[k]<j:
Z_alg[i+k] = Z_alg[k]
k += 1
i += k
j -= k
return Z_alg
class BIT():
def __init__(self,n,mod=0):
self.BIT = [0]*(n+1)
self.num = n
self.mod = mod
def query(self,idx):
res_sum = 0
mod = self.mod
while idx > 0:
res_sum += self.BIT[idx]
if mod:
res_sum %= mod
idx -= idx&(-idx)
return res_sum
#Ai += x O(logN)
def update(self,idx,x):
mod = self.mod
while idx <= self.num:
self.BIT[idx] += x
if mod:
self.BIT[idx] %= mod
idx += idx&(-idx)
return
class dancinglink():
def __init__(self,n,debug=False):
self.n = n
self.debug = debug
self._left = [i-1 for i in range(n)]
self._right = [i+1 for i in range(n)]
self.exist = [True for i in range(n)]
def pop(self,k):
if self.debug:
assert self.exist[k]
L = self._left[k]
R = self._right[k]
if L!=-1:
if R!=self.n:
self._right[L],self._left[R] = R,L
else:
self._right[L] = self.n
elif R!=self.n:
self._left[R] = -1
self.exist[k] = False
def left(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._left[res]
if res==-1:
break
k -= 1
return res
def right(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._right[res]
if res==self.n:
break
k -= 1
return res
class SparseTable():
def __init__(self,A,merge_func,ide_ele):
N=len(A)
n=N.bit_length()
self.table=[[ide_ele for i in range(n)] for i in range(N)]
self.merge_func=merge_func
for i in range(N):
self.table[i][0]=A[i]
for j in range(1,n):
for i in range(0,N-2**j+1):
f=self.table[i][j-1]
s=self.table[i+2**(j-1)][j-1]
self.table[i][j]=self.merge_func(f,s)
def query(self,s,t):
b=t-s+1
m=b.bit_length()-1
return self.merge_func(self.table[s][m],self.table[t-2**m+1][m])
class BinaryTrie:
class node:
def __init__(self,val):
self.left = None
self.right = None
self.max = val
def __init__(self):
self.root = self.node(-10**15)
def append(self,key,val):
pos = self.root
for i in range(29,-1,-1):
pos.max = max(pos.max,val)
if key>>i & 1:
if pos.right is None:
pos.right = self.node(val)
pos = pos.right
else:
pos = pos.right
else:
if pos.left is None:
pos.left = self.node(val)
pos = pos.left
else:
pos = pos.left
pos.max = max(pos.max,val)
def search(self,M,xor):
res = -10**15
pos = self.root
for i in range(29,-1,-1):
if pos is None:
break
if M>>i & 1:
if xor>>i & 1:
if pos.right:
res = max(res,pos.right.max)
pos = pos.left
else:
if pos.left:
res = max(res,pos.left.max)
pos = pos.right
else:
if xor>>i & 1:
pos = pos.right
else:
pos = pos.left
if pos:
res = max(res,pos.max)
return res
def solveequation(edge,ans,n,m):
#edge=[[to,dire,id]...]
x=[0]*m
used=[False]*n
for v in range(n):
if used[v]:
continue
y = dfs(v)
if y!=0:
return False
return x
def dfs(v):
used[v]=True
r=ans[v]
for to,dire,id in edge[v]:
if used[to]:
continue
y=dfs(to)
if dire==-1:
x[id]=y
else:
x[id]=-y
r+=y
return r
class SegmentTree:
def __init__(self, init_val, segfunc, ide_ele):
n = len(init_val)
self.segfunc = segfunc
self.ide_ele = ide_ele
self.num = 1 << (n - 1).bit_length()
self.tree = [ide_ele] * 2 * self.num
self.size = n
for i in range(n):
self.tree[self.num + i] = init_val[i]
for i in range(self.num - 1, 0, -1):
self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])
def update(self, k, x):
k += self.num
self.tree[k] = x
while k > 1:
self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
k >>= 1
def query(self, l, r):
if r==self.size:
r = self.num
res = self.ide_ele
l += self.num
r += self.num
while l < r:
if l & 1:
res = self.segfunc(res, self.tree[l])
l += 1
if r & 1:
res = self.segfunc(res, self.tree[r - 1])
l >>= 1
r >>= 1
return res
def bisect_l(self,l,r,x):
l += self.num
r += self.num
Lmin = -1
Rmin = -1
while l<r:
if l & 1:
if self.tree[l] <= x and Lmin==-1:
Lmin = l
l += 1
if r & 1:
if self.tree[r-1] <=x:
Rmin = r-1
l >>= 1
r >>= 1
if Lmin != -1:
pos = Lmin
while pos<self.num:
if self.tree[2 * pos] <=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
elif Rmin != -1:
pos = Rmin
while pos<self.num:
if self.tree[2 * pos] <=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
else:
return -1
def cmb(n, r, mod):
if ( r<0 or r>n ):
return 0
r = min(r, n-r)
return g1[n] * g2[r] * g2[n-r] % mod
mod = 998244353
N = 100
g1 = [1]*(N+1)
g2 = [1]*(N+1)
inverse = [1]*(N+1)
for i in range( 2, N + 1 ):
g1[i]=( ( g1[i-1] * i ) % mod )
inverse[i]=( ( -inverse[mod % i] * (mod//i) ) % mod )
g2[i]=( (g2[i-1] * inverse[i]) % mod )
inverse[0]=0
import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import gcd,log
input = lambda :sys.stdin.buffer.readline()
mi = lambda :map(int,input().split())
li = lambda :list(mi())
n,m = mi()
d = [li() for i in range(n)]
res = m
for i in range(m):
cnt = [0 for j in range(n)]
flag = True
for j in range(n):
if d[j][i]==1:
flag = False
break
else:
cnt[d[j][i]-2] += 1
if not flag:
continue
tmp = 1
rest = 0
for j in range(n):
rest += 1
for k in range(cnt[j]):
tmp *= rest
tmp %= mod
rest -= 1
res -= tmp * g2[n]
res %= mod
print(res)
``` | output | 1 | 104,688 | 15 | 209,377 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.
Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.
Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument.
Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points!
Input
The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points.
Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point.
Output
It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1.
Example
Input
3 5
1 4 4 3 4
1 4 1 4 2
1 4 4 4 3
Output
166374062
Note
Let's look at all possible orders of cities Monuments will be build in:
* [1, 2, 3]:
* the first city controls all points at distance at most 3, in other words, points 1 and 4;
* the second city controls all points at distance at most 2, or points 1, 3 and 5;
* the third city controls all points at distance at most 1, or point 1.
In total, 4 points are controlled.
* [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points.
* [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points.
* [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points.
The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} | instruction | 0 | 104,689 | 15 | 209,378 |
Tags: combinatorics, dp, math, probabilities, two pointers
Correct Solution:
```
import sys
from sys import stdin
ans = 0
n,m = map(int,stdin.readline().split())
mod = 998244353
a = [list(map(int,stdin.readline().split())) for i in range(n)]
fac = 1
for i in range(1,n+1):
fac *= i
inv = pow(fac,mod-2,mod)
for j in range(m):
na = [a[i][j] for i in range(n)]
na.sort()
now = 1
able = 0
for i in range(n):
while len(na) > 0 and na[-1] > n-i:
del na[-1]
able += 1
now *= able
able -= 1
ans += now * inv
ans %= mod
#print (ans)
print ((m-ans) % mod)
``` | output | 1 | 104,689 | 15 | 209,379 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.
Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.
Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument.
Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points!
Input
The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points.
Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point.
Output
It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1.
Example
Input
3 5
1 4 4 3 4
1 4 1 4 2
1 4 4 4 3
Output
166374062
Note
Let's look at all possible orders of cities Monuments will be build in:
* [1, 2, 3]:
* the first city controls all points at distance at most 3, in other words, points 1 and 4;
* the second city controls all points at distance at most 2, or points 1, 3 and 5;
* the third city controls all points at distance at most 1, or point 1.
In total, 4 points are controlled.
* [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points.
* [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points.
* [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points.
The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} | instruction | 0 | 104,690 | 15 | 209,380 |
Tags: combinatorics, dp, math, probabilities, two pointers
Correct Solution:
```
from bisect import bisect,bisect_left
from collections import *
from heapq import *
from math import gcd,ceil,sqrt,floor,inf
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *
#------------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#------------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def A(n):return [0]*n
def AI(n,x): return [x]*n
def A2(n,m): return [[0]*m for i in range(n)]
def G(n): return [[] for i in range(n)]
def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)]
#------------------------------------------------------------------------
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
mod=10**9+7
farr=[1]
ifa=[]
def fact(x,mod=0):
if mod:
while x>=len(farr):
farr.append(farr[-1]*len(farr)%mod)
else:
while x>=len(farr):
farr.append(farr[-1]*len(farr))
return farr[x]
def ifact(x,mod):
global ifa
fact(x,mod)
ifa.append(pow(farr[-1],mod-2,mod))
for i in range(x,0,-1):
ifa.append(ifa[-1]*i%mod)
ifa.reverse()
def per(i,j,mod=0):
if i<j: return 0
if not mod:
return fact(i)//fact(i-j)
return farr[i]*ifa[i-j]%mod
def com(i,j,mod=0):
if i<j: return 0
if not mod:
return per(i,j)//fact(j)
return per(i,j,mod)*ifa[j]%mod
def catalan(n):
return com(2*n,n)//(n+1)
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def floorsum(a,b,c,n):#sum((a*i+b)//c for i in range(n+1))
if a==0:return b//c*(n+1)
if a>=c or b>=c: return floorsum(a%c,b%c,c,n)+b//c*(n+1)+a//c*n*(n+1)//2
m=(a*n+b)//c
return n*m-floorsum(c,c-b-1,a,m-1)
def inverse(a,m):
a%=m
if a<=1: return a
return ((1-inverse(m,a)*m)//a)%m
def lowbit(n):
return n&-n
class BIT:
def __init__(self,arr):
self.arr=arr
self.n=len(arr)-1
def update(self,x,v):
while x<=self.n:
self.arr[x]+=v
x+=x&-x
def query(self,x):
ans=0
while x:
ans+=self.arr[x]
x&=x-1
return ans
class ST:
def __init__(self,arr):#n!=0
n=len(arr)
mx=n.bit_length()#取不到
self.st=[[0]*mx for i in range(n)]
for i in range(n):
self.st[i][0]=arr[i]
for j in range(1,mx):
for i in range(n-(1<<j)+1):
self.st[i][j]=max(self.st[i][j-1],self.st[i+(1<<j-1)][j-1])
def query(self,l,r):
if l>r:return -inf
s=(r+1-l).bit_length()-1
return max(self.st[l][s],self.st[r-(1<<s)+1][s])
class DSU:#容量+路径压缩
def __init__(self,n):
self.c=[-1]*n
def same(self,x,y):
return self.find(x)==self.find(y)
def find(self,x):
if self.c[x]<0:
return x
self.c[x]=self.find(self.c[x])
return self.c[x]
def union(self,u,v):
u,v=self.find(u),self.find(v)
if u==v:
return False
if self.c[u]>self.c[v]:
u,v=v,u
self.c[u]+=self.c[v]
self.c[v]=u
return True
def size(self,x): return -self.c[self.find(x)]
class UFS:#秩+路径
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
def find(self,x):
if x!=self.parent[x]:
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
pu,pv=self.find(u),self.find(v)
if pu==pv:
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
class UF:#秩+路径+容量,边数
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
self.size=AI(n,1)
self.edge=A(n)
def find(self,x):
if x!=self.parent[x]:
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
pu,pv=self.find(u),self.find(v)
if pu==pv:
self.edge[pu]+=1
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
self.edge[pu]+=self.edge[pv]+1
self.size[pu]+=self.size[pv]
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
self.edge[pv]+=self.edge[pu]+1
self.size[pv]+=self.size[pu]
def Prime(n):
c=0
prime=[]
flag=[0]*(n+1)
for i in range(2,n+1):
if not flag[i]:
prime.append(i)
c+=1
for j in range(c):
if i*prime[j]>n: break
flag[i*prime[j]]=prime[j]
if i%prime[j]==0: break
return prime
def dij(s,graph):
d=AI(n,inf)
d[s]=0
heap=[(0,s)]
vis=A(n)
while heap:
dis,u=heappop(heap)
if vis[u]:
continue
vis[u]=1
for v,w in graph[u]:
if d[v]>d[u]+w:
d[v]=d[u]+w
heappush(heap,(d[v],v))
return d
def bell(s,g):#bellman-Ford
dis=AI(n,inf)
dis[s]=0
for i in range(n-1):
for u,v,w in edge:
if dis[v]>dis[u]+w:
dis[v]=dis[u]+w
change=A(n)
for i in range(n):
for u,v,w in edge:
if dis[v]>dis[u]+w:
dis[v]=dis[u]+w
change[v]=1
return dis
def lcm(a,b): return a*b//gcd(a,b)
def lis(nums):
res=[]
for k in nums:
i=bisect.bisect_left(res,k)
if i==len(res):
res.append(k)
else:
res[i]=k
return len(res)
def RP(nums):#逆序对
n = len(nums)
s=set(nums)
d={}
for i,k in enumerate(sorted(s),1):
d[k]=i
bi=BIT([0]*(len(s)+1))
ans=0
for i in range(n-1,-1,-1):
ans+=bi.query(d[nums[i]]-1)
bi.update(d[nums[i]],1)
return ans
class DLN:
def __init__(self,val):
self.val=val
self.pre=None
self.next=None
def nb(i,j,n,m):
for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]:
if 0<=ni<n and 0<=nj<m:
yield ni,nj
def topo(n):
q=deque()
res=[]
for i in range(1,n+1):
if ind[i]==0:
q.append(i)
res.append(i)
while q:
u=q.popleft()
for v in g[u]:
ind[v]-=1
if ind[v]==0:
q.append(v)
res.append(v)
return res
@bootstrap
def gdfs(r,p):
for ch in g[r]:
if ch!=p:
yield gdfs(ch,r)
yield None
@bootstrap
def dfs(r,p):
for ch,w in g[r]:
if ch!=p:
res[ch]=res[r]^w
yield dfs(ch,r)
yield None
#from random import randint
t=1
mod=998244353
for i in range(t):
n,m=RL()
d=[]
for i in range(n):
d.append(RLL())
ifact(n,mod)
ans=0
for j in range(m):
res=[]
for i in range(n):
ma=d[i][j]-1
res.append(ma)
res.sort()
tmp=1
for i,v in enumerate(res):
if v<=i:
tmp=0
break
else:
tmp=tmp*(v-i)%mod
ans+=(1-tmp*ifa[n]%mod)
ans%=mod
print(ans)
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thr
ead(target=main)
t.start()
t.join()
'''
``` | output | 1 | 104,690 | 15 | 209,381 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.
Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.
Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument.
Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points!
Input
The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points.
Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point.
Output
It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1.
Example
Input
3 5
1 4 4 3 4
1 4 1 4 2
1 4 4 4 3
Output
166374062
Note
Let's look at all possible orders of cities Monuments will be build in:
* [1, 2, 3]:
* the first city controls all points at distance at most 3, in other words, points 1 and 4;
* the second city controls all points at distance at most 2, or points 1, 3 and 5;
* the third city controls all points at distance at most 1, or point 1.
In total, 4 points are controlled.
* [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points.
* [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points.
* [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points.
The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} | instruction | 0 | 104,691 | 15 | 209,382 |
Tags: combinatorics, dp, math, probabilities, two pointers
Correct Solution:
```
from sys import stdin
mod = 998244353
n,m=map(int,input().split())
arr=[]
for i in range(m):
arr.append([])
for i in range(n):
temp=list(map(int,stdin.readline().split()))
for j in range(m):
arr[j].append(temp[j])
for i in range(m):
arr[i].sort()
ans=1
for i in range(1,n+1):
ans*=i
den=ans
ans*=m
ans%=mod
for i in range(m):
temp=1
for j in range(n):
temp*=arr[i][j]-(j+1)
ans -= temp
ans%=mod
ans *= pow(den,mod-2,mod)
ans%=mod
print(ans)
``` | output | 1 | 104,691 | 15 | 209,383 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.
Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.
Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument.
Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points!
Input
The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points.
Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point.
Output
It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1.
Example
Input
3 5
1 4 4 3 4
1 4 1 4 2
1 4 4 4 3
Output
166374062
Note
Let's look at all possible orders of cities Monuments will be build in:
* [1, 2, 3]:
* the first city controls all points at distance at most 3, in other words, points 1 and 4;
* the second city controls all points at distance at most 2, or points 1, 3 and 5;
* the third city controls all points at distance at most 1, or point 1.
In total, 4 points are controlled.
* [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points.
* [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points.
* [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points.
The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353} | instruction | 0 | 104,692 | 15 | 209,384 |
Tags: combinatorics, dp, math, probabilities, two pointers
Correct Solution:
```
def get_one(ns,m):
n=len(ns)
ans=1
for i in range(n):
t=ns[i]-i
if t<=0:
return 0
ans=ans*t%m
return ans
def get_one_pre(ns:list):
ans=[0]*len(ns)
ns.sort()
l=0
for i in range(len(ns)):
for j in range(l,len(ns)):
if i+1<ns[j]:
l = j
ans[i] = len(ns) - l
break
else:
l=j
ans[i]=0
return list(reversed(ans))
def pow(a,b,m):
tb=[a]
for i in range(35):
tb.append(tb[-1]*tb[-1]%m)
ans=1
for i in range(35):
if (b>>i)&1==1:
ans=ans*tb[i]%m
return ans
def inv(a,m):
return pow(a,m-2,m)
def functoria(x,m):
ans=1
for i in range(1,x+1):
ans=ans*i%m
return ans
def gns():
return list(map(int,input().split()))
def gn():
return int(input())
n,m=gns()
md=998244353
ms=[[]for i in range(m)]
for i in range(n):
ns=gns()
for i in range(m):
ms[i].append(ns[i])
sm=0
for i in range(m):
x=get_one_pre(ms[i])
y=get_one(x,md)
sm=(sm+y)%md
f=functoria(n,md)
fv=inv(f,md)
ans=(f*m-sm+md)*fv%md
print(ans)
``` | output | 1 | 104,692 | 15 | 209,385 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.
Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.
Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument.
Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points!
Input
The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points.
Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point.
Output
It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1.
Example
Input
3 5
1 4 4 3 4
1 4 1 4 2
1 4 4 4 3
Output
166374062
Note
Let's look at all possible orders of cities Monuments will be build in:
* [1, 2, 3]:
* the first city controls all points at distance at most 3, in other words, points 1 and 4;
* the second city controls all points at distance at most 2, or points 1, 3 and 5;
* the third city controls all points at distance at most 1, or point 1.
In total, 4 points are controlled.
* [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points.
* [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points.
* [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points.
The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353}
Submitted Solution:
```
from sys import stdin, stdout
import heapq
from collections import defaultdict
import math
import bisect
import io, os
# for interactive problem
# n = int(stdin.readline())
# print(x, flush=True)
#input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def main():
MOD = 998244353
#n = int(input())
n,m = list(map(int, stdin.readline().split()))
dp_div = [0] * (n+2)
dp_div[n+1] = 1
for x in range(n,1,-1):
dp_div[x] = (dp_div[x+1] * x) % MOD
arr = []
for _ in range(n):
arr.append(list(map(int, stdin.readline().split())))
ans = 0
for i in range(m):
v = [0] * (n + 2)
for j in range(n):
x = arr[j][i]
v[x] += 1
pos = 0
cnt = 0
for j in range(1,n+1):
if pos == -1:
break
while v[j] > 0:
v[j] -= 1
if j == 1:
pos = -1
break
if cnt == 0:
pos = n - j + 1
cnt += 1
continue
xx = n - j + 1
yy = n - cnt
if xx >= yy:
pos = -1
break
pos = ((pos * yy) + (xx * dp_div[yy+1]) - (pos * xx)) % MOD
cnt+=1
if pos == -1:
ans = (ans + dp_div[2]) % MOD
else:
while cnt != n:
pos = (pos * (n - cnt)) % MOD
cnt += 1
ans = (ans + pos) % MOD
y_inv = 1
for z in range(2, n+1):
zz = pow(z, MOD-2, MOD)
y_inv = (y_inv * zz) % MOD
#print(y_inv)
print((ans * y_inv) % MOD)
main()
``` | instruction | 0 | 104,693 | 15 | 209,386 |
Yes | output | 1 | 104,693 | 15 | 209,387 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.
Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.
Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument.
Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points!
Input
The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points.
Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point.
Output
It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1.
Example
Input
3 5
1 4 4 3 4
1 4 1 4 2
1 4 4 4 3
Output
166374062
Note
Let's look at all possible orders of cities Monuments will be build in:
* [1, 2, 3]:
* the first city controls all points at distance at most 3, in other words, points 1 and 4;
* the second city controls all points at distance at most 2, or points 1, 3 and 5;
* the third city controls all points at distance at most 1, or point 1.
In total, 4 points are controlled.
* [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points.
* [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points.
* [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points.
The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353}
Submitted Solution:
```
# O(n^2*m + mlog(mod))
import sys
input = sys.stdin.buffer.readline
mod = 998244353
ans = 0
n,m = map(int,input().split())
fact = 1
for i in range(2,n+1):
fact = fact * i % mod
inv_fact = pow(fact,mod-2,mod)
dist = [list(map(int,input().split())) for i in range(n)]
# find expected value of each point (LOE)
for point in range(m):
# if built at or after this time the point will not be conquered by that city
time = [n+1 - dist[city][point] + 1 for city in range(n)]
add = [0] * (n + 2)
for i in time:
add[i] += 1
# of ways to place monuments so that they will not conquer the city
dp = [[0]*(n+1) for i in range(n+2)] # dp[time][to place (at curr time)]
dp[0][0] = 1
for t in range(n+1):
for to_place in range(n+1):
if dp[t][to_place]:
# don't place monument
dp[t+1][to_place+add[t+1]] = (dp[t+1][to_place+add[t+1]] + dp[t][to_place]) % mod
# place monument
if to_place:
dp[t+1][to_place-1+add[t+1]] = (dp[t+1][to_place-1+add[t+1]] + to_place*dp[t][to_place]) % mod
ans = (ans + (fact - dp[n+1][0])*inv_fact) % mod
print(ans)
``` | instruction | 0 | 104,694 | 15 | 209,388 |
Yes | output | 1 | 104,694 | 15 | 209,389 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.
Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.
Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument.
Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points!
Input
The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points.
Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point.
Output
It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1.
Example
Input
3 5
1 4 4 3 4
1 4 1 4 2
1 4 4 4 3
Output
166374062
Note
Let's look at all possible orders of cities Monuments will be build in:
* [1, 2, 3]:
* the first city controls all points at distance at most 3, in other words, points 1 and 4;
* the second city controls all points at distance at most 2, or points 1, 3 and 5;
* the third city controls all points at distance at most 1, or point 1.
In total, 4 points are controlled.
* [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points.
* [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points.
* [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points.
The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353}
Submitted Solution:
```
mod = 998244353
eps = 10**-9
def main():
import sys
from bisect import bisect_left
input = sys.stdin.readline
N, M = map(int, input().split())
A = [[0] * N for _ in range(M)]
for i in range(N):
line = list(map(int, input().split()))
for j in range(M):
A[j][i] = line[j]
F = 1
for i in range(1, N+1):
F = (F * i)%mod
invF = pow(F, mod-2, mod)
ans = 0
for B in A:
B.sort()
tmp = 1
for i in range(N, 0, -1):
j = bisect_left(B, i+1)
k = max(0, N - j - (N - i))
tmp = (tmp * k)%mod
ans = (ans + (F - tmp))%mod
print((ans * invF)%mod)
if __name__ == '__main__':
main()
``` | instruction | 0 | 104,695 | 15 | 209,390 |
Yes | output | 1 | 104,695 | 15 | 209,391 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.
Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.
Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument.
Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points!
Input
The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points.
Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point.
Output
It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1.
Example
Input
3 5
1 4 4 3 4
1 4 1 4 2
1 4 4 4 3
Output
166374062
Note
Let's look at all possible orders of cities Monuments will be build in:
* [1, 2, 3]:
* the first city controls all points at distance at most 3, in other words, points 1 and 4;
* the second city controls all points at distance at most 2, or points 1, 3 and 5;
* the third city controls all points at distance at most 1, or point 1.
In total, 4 points are controlled.
* [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points.
* [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points.
* [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points.
The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353}
Submitted Solution:
```
import time
#start_time = time.time()
#def TIME_(): print(time.time()-start_time)
import os, sys
from io import BytesIO, IOBase
from types import GeneratorType
from bisect import bisect_left, bisect_right
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string, heapq as h
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def getInt(): return int(input())
def getStrs(): return input().split()
def getInts(): return list(map(int,input().split()))
def getStr(): return input()
def listStr(): return list(input())
def getMat(n): return [getInts() for _ in range(n)]
def getBin(): return list(map(int,list(input())))
def isInt(s): return '0' <= s[0] <= '9'
def ceil_(a,b): return a//b + (a%b > 0)
MOD = 998244353
"""
"""
primes = [2,3,5,7,11,13,17,19]
def solve():
N, M = getInts()
dist = [getInts() for _ in range(N)]
num = 0
for j in range(M):
tmp = [dist[i][j] for i in range(N)]
tmp.sort()
mult = 1
for i in range(N):
mult *= max(tmp[i]-1-i,0)
num += mult
denom = 1
for i in range(2,N+1): denom *= i
num = denom*M - num
for i in primes:
if i > N: break
while num % i == 0 and denom % i == 0:
num //= i
denom //= i
num %= MOD
denom %= MOD
return (num * (pow(denom,MOD-2,MOD)))%MOD
#for _ in range(getInt()):
print(solve())
#solve()
#TIME_()
``` | instruction | 0 | 104,696 | 15 | 209,392 |
Yes | output | 1 | 104,696 | 15 | 209,393 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.
Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.
Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument.
Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points!
Input
The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points.
Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point.
Output
It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1.
Example
Input
3 5
1 4 4 3 4
1 4 1 4 2
1 4 4 4 3
Output
166374062
Note
Let's look at all possible orders of cities Monuments will be build in:
* [1, 2, 3]:
* the first city controls all points at distance at most 3, in other words, points 1 and 4;
* the second city controls all points at distance at most 2, or points 1, 3 and 5;
* the third city controls all points at distance at most 1, or point 1.
In total, 4 points are controlled.
* [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points.
* [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points.
* [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points.
The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353}
Submitted Solution:
```
# region fastio # from https://codeforces.com/contest/1333/submission/75948789
import sys, io, os
BUFSIZE = 8192
class FastIO(io.IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = io.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(io.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()
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#endregion
mod = 998244353
N, M = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(N)]
ans = 0
for t in zip(*D):
t = sorted(t)
p = 1
for i, d in enumerate(t, 1):
d -= i
p = p * d % mod
ans += p
denom = 1
for i in range(1, N+1):
denom = denom * i % mod
print(ans)
ans = (M - ans * pow(denom, mod-2, mod)) % mod
print(ans)
``` | instruction | 0 | 104,697 | 15 | 209,394 |
No | output | 1 | 104,697 | 15 | 209,395 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.
Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.
Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument.
Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points!
Input
The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points.
Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point.
Output
It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1.
Example
Input
3 5
1 4 4 3 4
1 4 1 4 2
1 4 4 4 3
Output
166374062
Note
Let's look at all possible orders of cities Monuments will be build in:
* [1, 2, 3]:
* the first city controls all points at distance at most 3, in other words, points 1 and 4;
* the second city controls all points at distance at most 2, or points 1, 3 and 5;
* the third city controls all points at distance at most 1, or point 1.
In total, 4 points are controlled.
* [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points.
* [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points.
* [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points.
The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353}
Submitted Solution:
```
import time
#start_time = time.time()
#def TIME_(): print(time.time()-start_time)
import os, sys
from io import BytesIO, IOBase
from types import GeneratorType
from bisect import bisect_left, bisect_right
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string, heapq as h
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def getInt(): return int(input())
def getStrs(): return input().split()
def getInts(): return list(map(int,input().split()))
def getStr(): return input()
def listStr(): return list(input())
def getMat(n): return [getInts() for _ in range(n)]
def getBin(): return list(map(int,list(input())))
def isInt(s): return '0' <= s[0] <= '9'
def ceil_(a,b): return a//b + (a%b > 0)
MOD = 998244353
LIM = 2*(10**5) # change this bit
facs = [1]
inv_facs = [1]
curr = 1
for j in range(1,LIM+1):
curr *= j
curr %= MOD
facs.append(curr)
inv_facs.append(pow(curr,MOD-2,MOD))
def ncr(n,r): return (facs[n]*inv_facs[n-r]*inv_facs[r])%MOD
"""
"""
primes = [2,3,5,7,11,13,17,19]
def solve():
N, M = getInts()
dist = [getInts() for _ in range(N)]
num = 0
for j in range(M):
tmp = [dist[i][j] for i in range(N)]
tmp.sort()
mult = 1
for i in range(N):
mult *= max(tmp[i]-1-i,0)
num += mult
denom = 1
for i in range(2,N+1): denom *= i
num = denom - num
for i in primes:
if i > N: break
while num % i == 0:
num //= i
denom //= i
num %= MOD
denom %= MOD
return (num * (pow(denom,MOD-2,MOD)))%MOD
#for _ in range(getInt()):
print(solve())
#solve()
#TIME_()
``` | instruction | 0 | 104,698 | 15 | 209,396 |
No | output | 1 | 104,698 | 15 | 209,397 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.
Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.
Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument.
Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points!
Input
The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points.
Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point.
Output
It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1.
Example
Input
3 5
1 4 4 3 4
1 4 1 4 2
1 4 4 4 3
Output
166374062
Note
Let's look at all possible orders of cities Monuments will be build in:
* [1, 2, 3]:
* the first city controls all points at distance at most 3, in other words, points 1 and 4;
* the second city controls all points at distance at most 2, or points 1, 3 and 5;
* the third city controls all points at distance at most 1, or point 1.
In total, 4 points are controlled.
* [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points.
* [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points.
* [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points.
The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353}
Submitted Solution:
```
import time
#start_time = time.time()
#def TIME_(): print(time.time()-start_time)
import os, sys
from io import BytesIO, IOBase
from types import GeneratorType
from bisect import bisect_left, bisect_right
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string, heapq as h
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def getInt(): return int(input())
def getStrs(): return input().split()
def getInts(): return list(map(int,input().split()))
def getStr(): return input()
def listStr(): return list(input())
def getMat(n): return [getInts() for _ in range(n)]
def getBin(): return list(map(int,list(input())))
def isInt(s): return '0' <= s[0] <= '9'
def ceil_(a,b): return a//b + (a%b > 0)
MOD = 998244353
"""
"""
primes = [2,3,5,7,11,13,17,19]
def solve():
N, M = getInts()
dist = [getInts() for _ in range(N)]
num = 0
for j in range(M):
tmp = [dist[i][j] for i in range(N)]
tmp.sort()
mult = 1
for i in range(N):
mult *= max(tmp[i]-1-i,0)
num += mult
denom = 1
for i in range(2,N+1): denom *= i
num = denom*M - num
for i in primes:
if i > N: break
while num % i and denom % i == 0:
num //= i
denom //= i
num %= MOD
denom %= MOD
return (num * (pow(denom,MOD-2,MOD)))%MOD
#for _ in range(getInt()):
print(solve())
#solve()
#TIME_()
``` | instruction | 0 | 104,699 | 15 | 209,398 |
No | output | 1 | 104,699 | 15 | 209,399 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Monocarp is playing a game "Assimilation IV". In this game he manages a great empire: builds cities and conquers new lands.
Monocarp's empire has n cities. In order to conquer new lands he plans to build one Monument in each city. The game is turn-based and, since Monocarp is still amateur, he builds exactly one Monument per turn.
Monocarp has m points on the map he'd like to control using the constructed Monuments. For each point he knows the distance between it and each city. Monuments work in the following way: when built in some city, a Monument controls all points at distance at most 1 to this city. Next turn, the Monument controls all points at distance at most 2, the turn after — at distance at most 3, and so on. Monocarp will build n Monuments in n turns and his empire will conquer all points that are controlled by at least one Monument.
Monocarp can't figure out any strategy, so during each turn he will choose a city for a Monument randomly among all remaining cities (cities without Monuments). Monocarp wants to know how many points (among m of them) he will conquer at the end of turn number n. Help him to calculate the expected number of conquered points!
Input
The first line contains two integers n and m (1 ≤ n ≤ 20; 1 ≤ m ≤ 5 ⋅ 10^4) — the number of cities and the number of points.
Next n lines contains m integers each: the j-th integer of the i-th line d_{i, j} (1 ≤ d_{i, j} ≤ n + 1) is the distance between the i-th city and the j-th point.
Output
It can be shown that the expected number of points Monocarp conquers at the end of the n-th turn can be represented as an irreducible fraction x/y. Print this fraction modulo 998 244 353, i. e. value x ⋅ y^{-1} mod 998244353 where y^{-1} is such number that y ⋅ y^{-1} mod 998244353 = 1.
Example
Input
3 5
1 4 4 3 4
1 4 1 4 2
1 4 4 4 3
Output
166374062
Note
Let's look at all possible orders of cities Monuments will be build in:
* [1, 2, 3]:
* the first city controls all points at distance at most 3, in other words, points 1 and 4;
* the second city controls all points at distance at most 2, or points 1, 3 and 5;
* the third city controls all points at distance at most 1, or point 1.
In total, 4 points are controlled.
* [1, 3, 2]: the first city controls points 1 and 4; the second city — points 1 and 3; the third city — point 1. In total, 3 points.
* [2, 1, 3]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [2, 3, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — point 1. In total, 3 points.
* [3, 1, 2]: the first city controls point 1; the second city — points 1 and 3; the third city — points 1 and 5. In total, 3 points.
* [3, 2, 1]: the first city controls point 1; the second city — points 1, 3 and 5; the third city — points 1 and 5. In total, 3 points.
The expected number of controlled points is (4 + 3 + 3 + 3 + 3 + 3)/(6) = 19/6 or 19 ⋅ 6^{-1} ≡ 19 ⋅ 166374059 ≡ 166374062 \pmod{998244353}
Submitted Solution:
```
a=input()
if a==('Aska'):
print(a)
``` | instruction | 0 | 104,700 | 15 | 209,400 |
No | output | 1 | 104,700 | 15 | 209,401 |
Provide a correct Python 3 solution for this coding contest problem.
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the union of these K segments. Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq K \leq \min(N, 10)
* 1 \leq L_i \leq R_i \leq N
* [L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K
Output
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.
Examples
Input
5 2
1 1
3 4
Output
4
Input
5 2
3 3
5 5
Output
0
Input
5 1
1 2
Output
5
Input
60 3
5 8
1 3
10 15
Output
221823067 | instruction | 0 | 105,027 | 15 | 210,054 |
"Correct Solution:
```
n,k = (int(x) for x in input().split())
lr = []
for _ in range(k):
l,r = (int(x) for x in input().split())
lr.append((l,r))
lr.sort()
mod = 998244353
dp= [0]*(n+1)
dp[1] = 1
for i in range(2,n+1):
cnt = 0
for l,r in lr:
if l >= i:
break
else:
cnt += dp[i-l] - dp[max(0,i-r-1)]
dp[i] = (dp[i-1] + cnt) % mod
print(cnt%mod)
``` | output | 1 | 105,027 | 15 | 210,055 |
Provide a correct Python 3 solution for this coding contest problem.
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the union of these K segments. Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq K \leq \min(N, 10)
* 1 \leq L_i \leq R_i \leq N
* [L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K
Output
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.
Examples
Input
5 2
1 1
3 4
Output
4
Input
5 2
3 3
5 5
Output
0
Input
5 1
1 2
Output
5
Input
60 3
5 8
1 3
10 15
Output
221823067 | instruction | 0 | 105,028 | 15 | 210,056 |
"Correct Solution:
```
MOD = 998244353
N,K = map(int,input().split())
lr = []
for i in range(K):
lr.append(list(map(int,input().split())))
dp = [0] * (10**6)
dp[0] = 1
dpcum = [0] * (10**6)
dpcum[0] = 1
for i in range(1,N+1):
for j in range(K):
dp[i] += dpcum[max(-1,i-lr[j][0])] - dpcum[max(-1,i-lr[j][1]-1)]
dp[i] %= MOD
dpcum[i] = (dpcum[i-1] + dp[i]) % MOD
#print(dp)
print(dp[N-1])
``` | output | 1 | 105,028 | 15 | 210,057 |
Provide a correct Python 3 solution for this coding contest problem.
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the union of these K segments. Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq K \leq \min(N, 10)
* 1 \leq L_i \leq R_i \leq N
* [L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K
Output
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.
Examples
Input
5 2
1 1
3 4
Output
4
Input
5 2
3 3
5 5
Output
0
Input
5 1
1 2
Output
5
Input
60 3
5 8
1 3
10 15
Output
221823067 | instruction | 0 | 105,029 | 15 | 210,058 |
"Correct Solution:
```
def solve(l, r, i):
if i - l < 1:
return 0
return dp[i - l] - dp[max(i - r - 1, 0)]
n, k = map(int, input().split())
MOD = 998244353
lr = [list(map(int, input().split())) for _ in range(k)]
dp = [0] * (n + 1)
dp[1] = 1
for i in range(2, n + 1):
tmp = 0
for l, r in lr:
tmp += solve(l, r, i)
tmp = tmp % MOD
dp[i] = (dp[i - 1] + tmp) % MOD
print(tmp)
``` | output | 1 | 105,029 | 15 | 210,059 |
Provide a correct Python 3 solution for this coding contest problem.
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the union of these K segments. Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq K \leq \min(N, 10)
* 1 \leq L_i \leq R_i \leq N
* [L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K
Output
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.
Examples
Input
5 2
1 1
3 4
Output
4
Input
5 2
3 3
5 5
Output
0
Input
5 1
1 2
Output
5
Input
60 3
5 8
1 3
10 15
Output
221823067 | instruction | 0 | 105,030 | 15 | 210,060 |
"Correct Solution:
```
#dt = {} for i in x: dt[i] = dt.get(i,0)+1
import sys;input = sys.stdin.readline
inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()]
M = 998244353
n,k = ip()
seg = [ip() for i in range(k)]
dp = [0]*(n+1)
pre = [0]*(n+1)
dp[1] = 1
pre[1] = 1
for i in range(2,n+1):
for l,r in seg:
a,b = max(i-r,1),i-l
dp[i] += (pre[b] - pre[a-1])%M
pre[i] += (pre[i-1]+dp[i])%M
print(dp[n]%M)
``` | output | 1 | 105,030 | 15 | 210,061 |
Provide a correct Python 3 solution for this coding contest problem.
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the union of these K segments. Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq K \leq \min(N, 10)
* 1 \leq L_i \leq R_i \leq N
* [L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K
Output
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.
Examples
Input
5 2
1 1
3 4
Output
4
Input
5 2
3 3
5 5
Output
0
Input
5 1
1 2
Output
5
Input
60 3
5 8
1 3
10 15
Output
221823067 | instruction | 0 | 105,031 | 15 | 210,062 |
"Correct Solution:
```
N, K = map(int, input().split())
mod = 998244353
lr = []
for k in range(K):
lr.append(list(map(int, input().split())))
dp = [0]*(2*N+1)
dp[0] = 1
dpsum = 0
for i in range(N):
dpsum += dp[i]%mod
for k in lr:
l = k[0]
r = k[1]
dp[i+l] += dpsum%mod
dp[i+r+1] -= dpsum%mod
print(dp[N-1]%mod)
``` | output | 1 | 105,031 | 15 | 210,063 |
Provide a correct Python 3 solution for this coding contest problem.
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the union of these K segments. Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq K \leq \min(N, 10)
* 1 \leq L_i \leq R_i \leq N
* [L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K
Output
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.
Examples
Input
5 2
1 1
3 4
Output
4
Input
5 2
3 3
5 5
Output
0
Input
5 1
1 2
Output
5
Input
60 3
5 8
1 3
10 15
Output
221823067 | instruction | 0 | 105,032 | 15 | 210,064 |
"Correct Solution:
```
MOD = 998244353
N, K = map(int, input().split())
LRs = []
sums = []
for _ in range(K):
l, r = map(int, input().split())
LRs.append([l, r])
sums.append(1 if l <= 1 <= r else 0)
dp = [0] * (N * 2)
dp[1] = 1
for i in range(2, N+1):
dp[i] = sum(sums) % MOD
for k in range(K):
l, r = LRs[k]
sums[k] = (sums[k] + dp[i-l+1] - dp[i-r]) % MOD
print(dp[N])
``` | output | 1 | 105,032 | 15 | 210,065 |
Provide a correct Python 3 solution for this coding contest problem.
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the union of these K segments. Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq K \leq \min(N, 10)
* 1 \leq L_i \leq R_i \leq N
* [L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K
Output
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.
Examples
Input
5 2
1 1
3 4
Output
4
Input
5 2
3 3
5 5
Output
0
Input
5 1
1 2
Output
5
Input
60 3
5 8
1 3
10 15
Output
221823067 | instruction | 0 | 105,033 | 15 | 210,066 |
"Correct Solution:
```
mod = 998244353
N,K = map(int,input().split())
D = [list(map(int,input().split())) for _ in range(K)]
D.sort()
dp = [0]*N
dp[0] = 1
if D[0][0]<N:
dp[D[0][0]] = 1
for n in range(D[0][0],N-1):
dp[n+1] = dp[n]
for i in range(K):
L,R = D[i]
if n-L+1>=0:
dp[n+1] += dp[n-L+1]
if n-R+1>0:
dp[n+1] -= dp[n-R]
dp[n+1] %= mod
print(dp[N-1])
``` | output | 1 | 105,033 | 15 | 210,067 |
Provide a correct Python 3 solution for this coding contest problem.
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the union of these K segments. Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq K \leq \min(N, 10)
* 1 \leq L_i \leq R_i \leq N
* [L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K
Output
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.
Examples
Input
5 2
1 1
3 4
Output
4
Input
5 2
3 3
5 5
Output
0
Input
5 1
1 2
Output
5
Input
60 3
5 8
1 3
10 15
Output
221823067 | instruction | 0 | 105,034 | 15 | 210,068 |
"Correct Solution:
```
N,K = map(int, input().split())
L = [0]*N
R = [0]*N
DP = [0]*(N+10)
DP[0] = 1
SDP = [0]*(N+10)
SDP[1] = 1
MOD=998244353
for i in range(K):
L[i],R[i] = map(int, input().split())
for i in range(1,N):
for j in range(K):
l = max(0,i-R[j])
r = max(0,i-L[j]+1)
DP[i] += SDP[r] - SDP[l]
SDP[i+1] = (SDP[i] + DP[i])%MOD
print(DP[N-1]%MOD)
``` | output | 1 | 105,034 | 15 | 210,069 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the union of these K segments. Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq K \leq \min(N, 10)
* 1 \leq L_i \leq R_i \leq N
* [L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K
Output
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.
Examples
Input
5 2
1 1
3 4
Output
4
Input
5 2
3 3
5 5
Output
0
Input
5 1
1 2
Output
5
Input
60 3
5 8
1 3
10 15
Output
221823067
Submitted Solution:
```
N, K = map(int, input().split())
LR = [list(map(int, input().split())) for _ in range(K)]
mod = 998244353
dp = [0] * (N + 1)
dpsum = [0] * (N + 1)
dp[1] = 1
dpsum[1] = 1
for i in range(2, N + 1):
for j in range(K):
li = max(i - LR[j][1], 1)
ri = i - LR[j][0]
if ri < 0:
continue
dp[i] += dpsum[ri] - dpsum[li - 1]
dp[i] %= mod
dpsum[i] = dpsum[i - 1] + dp[i]
print(dp[N])
``` | instruction | 0 | 105,035 | 15 | 210,070 |
Yes | output | 1 | 105,035 | 15 | 210,071 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the union of these K segments. Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq K \leq \min(N, 10)
* 1 \leq L_i \leq R_i \leq N
* [L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K
Output
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.
Examples
Input
5 2
1 1
3 4
Output
4
Input
5 2
3 3
5 5
Output
0
Input
5 1
1 2
Output
5
Input
60 3
5 8
1 3
10 15
Output
221823067
Submitted Solution:
```
MOD = 998244353
n, k = map(int, input().split())
left=[]
right=[]
for _ in range(k):
l,r=map(int, input().split())
left+=[l]
right+=[r]
pref = [0,1]
for i in range(n-1):
new = 0
for j in range(k):
new += pref[max(0,i+2-left[j])] - pref[max(0,i+1-right[j])]
#print(pref[max(0,i+2-left[j])], pref[max(0,i+1-right[j])])
pref.append((pref[-1] + new) % MOD)
print(new % MOD)
``` | instruction | 0 | 105,036 | 15 | 210,072 |
Yes | output | 1 | 105,036 | 15 | 210,073 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the union of these K segments. Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq K \leq \min(N, 10)
* 1 \leq L_i \leq R_i \leq N
* [L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K
Output
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.
Examples
Input
5 2
1 1
3 4
Output
4
Input
5 2
3 3
5 5
Output
0
Input
5 1
1 2
Output
5
Input
60 3
5 8
1 3
10 15
Output
221823067
Submitted Solution:
```
MOD = 998244353
N, K = map(int, input().split())
rl = [list(map(int, input().split())) for _ in range(K)]
dp = [0] * (N + 1)
sdp = [0] * (N + 1)
dp[1] = 1
sdp[1] = 1
for i in range(2, N + 1):
for j in range(K):
l, r = rl[j][0], rl[j][1]
tl = max(1, i - r)
tr = max(0, i - l)
dp[i] += sdp[tr] - sdp[tl - 1]
dp[i] %= MOD
sdp[i] += dp[i] + sdp[i - 1]
sdp[i] %= MOD
print(dp[N])
``` | instruction | 0 | 105,037 | 15 | 210,074 |
Yes | output | 1 | 105,037 | 15 | 210,075 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the union of these K segments. Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq K \leq \min(N, 10)
* 1 \leq L_i \leq R_i \leq N
* [L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K
Output
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.
Examples
Input
5 2
1 1
3 4
Output
4
Input
5 2
3 3
5 5
Output
0
Input
5 1
1 2
Output
5
Input
60 3
5 8
1 3
10 15
Output
221823067
Submitted Solution:
```
N, K = map(int, input().split())
T = []
mod = 998244353
for i in range(K):
L, R = map(int, input().split())
T.append([L, R])
dp = [0]*(N+1)
dp[1] = 1
Total = [0]*(N+1)
Total[1] = 1
for i in range(2, N+1):
for j in range(K):
L, R = T[j]
dp[i] += Total[max(0, i-L)] - Total[max(0, i-R-1)]
dp[i] %= mod
Total[i] = Total[i-1] + dp[i]
Total[i] %= mod
print(dp[N])
``` | instruction | 0 | 105,038 | 15 | 210,076 |
Yes | output | 1 | 105,038 | 15 | 210,077 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the union of these K segments. Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq K \leq \min(N, 10)
* 1 \leq L_i \leq R_i \leq N
* [L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K
Output
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.
Examples
Input
5 2
1 1
3 4
Output
4
Input
5 2
3 3
5 5
Output
0
Input
5 1
1 2
Output
5
Input
60 3
5 8
1 3
10 15
Output
221823067
Submitted Solution:
```
n, k = map(int,input().split())
l_r = [ list(map(int, input().split())) for _ in range(k) ]
s_l = [ list(range(l,r+1)) for l,r in l_r ]
d = [0] * n
d[0] = 1
for i in range(1, n):
c = 0
for s in s_l:
if s <= i and d[i-s] > 0:
c += d[i-s]
d[i] = c%998244353
print(d[-1]%998244353)
``` | instruction | 0 | 105,039 | 15 | 210,078 |
No | output | 1 | 105,039 | 15 | 210,079 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the union of these K segments. Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq K \leq \min(N, 10)
* 1 \leq L_i \leq R_i \leq N
* [L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K
Output
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.
Examples
Input
5 2
1 1
3 4
Output
4
Input
5 2
3 3
5 5
Output
0
Input
5 1
1 2
Output
5
Input
60 3
5 8
1 3
10 15
Output
221823067
Submitted Solution:
```
import numpy as np
N,K = list(map(int, input().split()))
LRs = [list(map(int, input().split())) for _ in range(K)]
move_list = []
checker = np.zeros(N+1 ,dtype = int)
for LR in LRs:
# for i in range(LR[0], LR[1]+1):
# move_list.append(i)
for i in range(LR[0], LR[1]+1):
checker[i] = 1
#print(move_list)
#move_list.sort()
#print(move_list)
for index, check in enumerate(checker):
if(check == 1):
move_list.append(index)
#print(move_list)
dp = np.zeros(N+1, dtype = int)
dp[1] = 1
for i in range(1, N+1):
for j in move_list:
if(i < j):
break
# print(i,j)
dp[i] = (dp[i] +dp[i-j]) % 998244353
print(dp[N])
``` | instruction | 0 | 105,040 | 15 | 210,080 |
No | output | 1 | 105,040 | 15 | 210,081 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the union of these K segments. Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq K \leq \min(N, 10)
* 1 \leq L_i \leq R_i \leq N
* [L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K
Output
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.
Examples
Input
5 2
1 1
3 4
Output
4
Input
5 2
3 3
5 5
Output
0
Input
5 1
1 2
Output
5
Input
60 3
5 8
1 3
10 15
Output
221823067
Submitted Solution:
```
N, K = map(int, input().split())
L, R = [], []
for _ in range(K):
l, r = map(int, input().split())
L.append(l)
R.append(r)
mod = 998244353
dp = [0] * N
dp[0] = 1
for i in range(N):
for l, r in zip(L, R):
if i - l >= 0:
dp[i] = (dp[i] + sum(dp[max(0, i - r):i - l + 1])) % mod
print(dp[-1])
``` | instruction | 0 | 105,041 | 15 | 210,082 |
No | output | 1 | 105,041 | 15 | 210,083 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N cells arranged in a row, numbered 1, 2, \ldots, N from left to right.
Tak lives in these cells and is currently on Cell 1. He is trying to reach Cell N by using the procedure described below.
You are given an integer K that is less than or equal to 10, and K non-intersecting segments [L_1, R_1], [L_2, R_2], \ldots, [L_K, R_K]. Let S be the union of these K segments. Here, the segment [l, r] denotes the set consisting of all integers i that satisfy l \leq i \leq r.
* When you are on Cell i, pick an integer d from S and move to Cell i + d. You cannot move out of the cells.
To help Tak, find the number of ways to go to Cell N, modulo 998244353.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq K \leq \min(N, 10)
* 1 \leq L_i \leq R_i \leq N
* [L_i, R_i] and [L_j, R_j] do not intersect (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
L_1 R_1
L_2 R_2
:
L_K R_K
Output
Print the number of ways for Tak to go from Cell 1 to Cell N, modulo 998244353.
Examples
Input
5 2
1 1
3 4
Output
4
Input
5 2
3 3
5 5
Output
0
Input
5 1
1 2
Output
5
Input
60 3
5 8
1 3
10 15
Output
221823067
Submitted Solution:
```
N, K = map(int, input().split())
LR = set()
MOD = 998244353
for i in range(K):
l, r = map(int, input().split())
for j in range(l, r + 1):
LR.add(j)
#print(list(LR))
class Search:
def __init__(self):
self.ans = 0
def dfs(self, now):
if now == N:
self.ans += 1
return
if now > N:
return
for d in LR:
self.dfs(d + now)
s = Search()
s.dfs(1)
print(s.ans % MOD)
# LR = [list(map(int,input().split())) for i in range(N)]
# dp = [0] * (N + 1)
# dp[0] = 1
# for i in range(1, N):
# for d in LR:
# if i - d < 0: break
# dp[i] += (dp[i - d]) % MOD
# print(dp[N-1] % MOD)
``` | instruction | 0 | 105,042 | 15 | 210,084 |
No | output | 1 | 105,042 | 15 | 210,085 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.