text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change.
You have to find the minimum number of digits in which these two numbers can differ.
Input
The first line contains integer k (1 ≤ k ≤ 109).
The second line contains integer n (1 ≤ n < 10100000).
There are no leading zeros in n. It's guaranteed that this situation is possible.
Output
Print the minimum number of digits in which the initial number and n can differ.
Examples
Input
3
11
Output
1
Input
3
99
Output
0
Note
In the first example, the initial number could be 12.
In the second example the sum of the digits of n is not less than k. The initial number could be equal to n.
Submitted Solution:
```
import sys
#========MAIN=============
n = int(input())
k = list(str(input()))
a = []
for i in range(100):
a.append(1)
Klength = len(k)
ans = 0
for i in range(Klength-1):
a[i] = int(k[i])
ans += a[i]
a.sort()
sum = 0
if ans >= n:
print("0")
sys.exit(0)
for i in range(Klength-1):
sum += 1
ans += 9 - a[i]
if ans >= n:
print(sum)
break
```
No
| 105,000 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change.
You have to find the minimum number of digits in which these two numbers can differ.
Input
The first line contains integer k (1 ≤ k ≤ 109).
The second line contains integer n (1 ≤ n < 10100000).
There are no leading zeros in n. It's guaranteed that this situation is possible.
Output
Print the minimum number of digits in which the initial number and n can differ.
Examples
Input
3
11
Output
1
Input
3
99
Output
0
Note
In the first example, the initial number could be 12.
In the second example the sum of the digits of n is not less than k. The initial number could be equal to n.
Submitted Solution:
```
#!/usr/bin/python3
k = int(input())
n = int(input())
def sum_of_digits(n):
l = len(str(n))
r = 10**(l-1)
s = 0
for i in range(l-1, -1, -1):
t = n//10**i
s += t
n -= t*10**i
return s
def digits(n):
l = len(str(n))
r = 10**(l-1)
a = []
for i in range(l-1, -1, -1):
t = n//10**i
a.append(t)
n -= t*10**i
return a
if sum_of_digits(n) >= k:
print(0)
else:
r = sorted(digits(n))
s = 0
i = 0
while s < k and i < n:
s += 9
i += 1
print(i)
```
No
| 105,001 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change.
You have to find the minimum number of digits in which these two numbers can differ.
Input
The first line contains integer k (1 ≤ k ≤ 109).
The second line contains integer n (1 ≤ n < 10100000).
There are no leading zeros in n. It's guaranteed that this situation is possible.
Output
Print the minimum number of digits in which the initial number and n can differ.
Examples
Input
3
11
Output
1
Input
3
99
Output
0
Note
In the first example, the initial number could be 12.
In the second example the sum of the digits of n is not less than k. The initial number could be equal to n.
Submitted Solution:
```
k = int(input())
n = sorted(list(map(int, list(input()))))
s = sum(n)
count = 0
i = 0
while s < k and i < len(n):
s += 9 - n[i]
count += 1
print(count)
```
No
| 105,002 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher.
Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive).
Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.
You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers.
Input
First line of input contains q (1 ≤ q ≤ 105) — number of queries.
Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018).
Output
You have to output q lines, each containing a single integer, the answer to the corresponding query.
Examples
Input
2
2 4 9
3 1 10
Output
1
2
Input
2
2 1 100
5 1 100
Output
21
4
Note
In sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get:
* 4 = 1002,
* 5 = 1012,
* 6 = 1102,
* 7 = 1112,
* 8 = 10002,
* 9 = 10012.
Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1.
Submitted Solution:
```
n = int(input())
for i in range(n):
l = list(map(int, input().split()))
base = l[0]
count = 0
for j in range(l[1], l[2]+1):
print("-"+str(j))
flag = 0
new = ""
while j:
mod = j % base
j = j // base
new = chr(48 + mod + 7*(mod > 9)) + new
listzero = [0]*base
print(new+"----"+str(j))
#print(listzero)
for k in new:
listzero[int(k)] = listzero[int(k)] + 1
print(listzero)
for kin in listzero:
if kin%2==0:
continue
else:
flag = 1
break
if flag == 0:
count = count + 1
print(count)
```
No
| 105,003 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Two best friends Serozha and Gena play a game.
Initially there is one pile consisting of n stones on the table. During one move one pile should be taken and divided into an arbitrary number of piles consisting of a1 > a2 > ... > ak > 0 stones. The piles should meet the condition a1 - a2 = a2 - a3 = ... = ak - 1 - ak = 1. Naturally, the number of piles k should be no less than two.
The friends play in turns. The player who cannot make a move loses. Serozha makes the first move. Who will win if both players play in the optimal way?
Input
The single line contains a single integer n (1 ≤ n ≤ 105).
Output
If Serozha wins, print k, which represents the minimal number of piles into which he can split the initial one during the first move in order to win the game.
If Gena wins, print "-1" (without the quotes).
Examples
Input
3
Output
2
Input
6
Output
-1
Input
100
Output
8
Tags: dp, games, math
Correct Solution:
```
import math
from collections import Counter
n = int(input())
g = [0 for i in range(n + 1)]
prefix_xor = g.copy()
def in_range(d, k):
if (2 * k - d * d + d) % (2 * d) != 0:
return -1
x = (2 * k - d * d + d) / (2 * d)
return int(x) if x > 0 else -1
def mex(arr):
counter = Counter()
for i in arr:
counter[i] += 1
for i in range(0, len(arr) + 1):
if counter[i] == 0:
return i
def find_move(arr):
for i in range(0, len(arr)):
if arr[i] == 0:
return i
return -1
if n < 3:
print(-1)
exit(0)
for i in range(3, n + 1):
for_range = range(2, int(math.sqrt(2 * i)) + 1)
filter_range = [l for l in for_range if in_range(l, i) > 0]
branches = [prefix_xor[in_range(d, i) + d - 1] ^ prefix_xor[in_range(d, i) - 1] for d in filter_range]
g[i] = mex(branches)
prefix_xor[i] = prefix_xor[i - 1] ^ g[i]
if i == n:
print(-1 if g[i] == 0 else filter_range[find_move(branches)])
```
| 105,004 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Two best friends Serozha and Gena play a game.
Initially there is one pile consisting of n stones on the table. During one move one pile should be taken and divided into an arbitrary number of piles consisting of a1 > a2 > ... > ak > 0 stones. The piles should meet the condition a1 - a2 = a2 - a3 = ... = ak - 1 - ak = 1. Naturally, the number of piles k should be no less than two.
The friends play in turns. The player who cannot make a move loses. Serozha makes the first move. Who will win if both players play in the optimal way?
Input
The single line contains a single integer n (1 ≤ n ≤ 105).
Output
If Serozha wins, print k, which represents the minimal number of piles into which he can split the initial one during the first move in order to win the game.
If Gena wins, print "-1" (without the quotes).
Examples
Input
3
Output
2
Input
6
Output
-1
Input
100
Output
8
Submitted Solution:
```
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n = int(input())
dp = [0] * (n + 1)
for i in range(2, n):
nim = dp[i] ^ 1
total = i
for j in range(i - 1, 0, -1):
total += j
nim ^= dp[j]
if total > n:
break
dp[total] |= nim
if total == n:
print(i - j + 1)
exit()
print(-1)
```
No
| 105,005 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Two best friends Serozha and Gena play a game.
Initially there is one pile consisting of n stones on the table. During one move one pile should be taken and divided into an arbitrary number of piles consisting of a1 > a2 > ... > ak > 0 stones. The piles should meet the condition a1 - a2 = a2 - a3 = ... = ak - 1 - ak = 1. Naturally, the number of piles k should be no less than two.
The friends play in turns. The player who cannot make a move loses. Serozha makes the first move. Who will win if both players play in the optimal way?
Input
The single line contains a single integer n (1 ≤ n ≤ 105).
Output
If Serozha wins, print k, which represents the minimal number of piles into which he can split the initial one during the first move in order to win the game.
If Gena wins, print "-1" (without the quotes).
Examples
Input
3
Output
2
Input
6
Output
-1
Input
100
Output
8
Submitted Solution:
```
import math
from collections import Counter
n = int(input())
g = [0 for i in range(n + 1)]
prefix_xor = g.copy()
def in_range(d, k):
if (2 * k - d * d + d) % (2 * d) != 0:
return -1
x = (2 * k - d * d + d) / (2 * d)
return int(x) if x > 0 else -1
def mex(arr):
counter = Counter()
for i in arr:
counter[i] += 1
for i in range(0, len(arr) + 1):
if counter[i] == 0:
return i
def find_move(arr):
for i in range(0, len(arr)):
if arr[i] == 0:
return i
return -1
for i in range(3, n + 1):
for_range = range(2, int(math.sqrt(2 * i)) + 1)
filter_range = [l for l in for_range if in_range(l, i) > 0]
branches = [prefix_xor[in_range(d, i) + d - 1] ^ prefix_xor[in_range(d, i) - 1] for d in filter_range]
g[i] = mex(branches)
prefix_xor[i] ^= g[i]
if i == n:
print(-1 if g[i] == 0 else filter_range[find_move(branches)])
```
No
| 105,006 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Two best friends Serozha and Gena play a game.
Initially there is one pile consisting of n stones on the table. During one move one pile should be taken and divided into an arbitrary number of piles consisting of a1 > a2 > ... > ak > 0 stones. The piles should meet the condition a1 - a2 = a2 - a3 = ... = ak - 1 - ak = 1. Naturally, the number of piles k should be no less than two.
The friends play in turns. The player who cannot make a move loses. Serozha makes the first move. Who will win if both players play in the optimal way?
Input
The single line contains a single integer n (1 ≤ n ≤ 105).
Output
If Serozha wins, print k, which represents the minimal number of piles into which he can split the initial one during the first move in order to win the game.
If Gena wins, print "-1" (without the quotes).
Examples
Input
3
Output
2
Input
6
Output
-1
Input
100
Output
8
Submitted Solution:
```
from math import sqrt
def ii():return int(input())
def si():return input()
def mi():return map(int,input().split())
def li():return list(mi())
abc="abcdefghijklmnopqrstuvwxyz"
t=ii()
i=2
f=0
while(1):
s=t-(i*(i-1))//2
if(s<=0):
f=1
break
if(s%i==0 and i%2==0):
break
i+=1
if(f==1):
print("-1")
else:
print(i)
```
No
| 105,007 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Two best friends Serozha and Gena play a game.
Initially there is one pile consisting of n stones on the table. During one move one pile should be taken and divided into an arbitrary number of piles consisting of a1 > a2 > ... > ak > 0 stones. The piles should meet the condition a1 - a2 = a2 - a3 = ... = ak - 1 - ak = 1. Naturally, the number of piles k should be no less than two.
The friends play in turns. The player who cannot make a move loses. Serozha makes the first move. Who will win if both players play in the optimal way?
Input
The single line contains a single integer n (1 ≤ n ≤ 105).
Output
If Serozha wins, print k, which represents the minimal number of piles into which he can split the initial one during the first move in order to win the game.
If Gena wins, print "-1" (without the quotes).
Examples
Input
3
Output
2
Input
6
Output
-1
Input
100
Output
8
Submitted Solution:
```
import math
from collections import Counter
n = int(input())
g = [0 for i in range(n + 1)]
prefix_xor = g.copy()
def in_range(d, k):
if (2 * k - d * d + d) % (2 * d) != 0:
return -1
x = (2 * k - d * d + d) / (2 * d)
return int(x) if x > 0 else -1
def mex(arr):
counter = Counter()
for i in arr:
counter[i] += 1
for i in range(0, len(arr) + 1):
if counter[i] == 0:
return i
def find_move(arr):
for i in range(0, len(arr)):
if arr[i] == 0:
return i
return -1
for i in range(3, n + 1):
for_range = range(2, int(math.sqrt(2 * i)) + 1)
filter_range = [l for l in for_range if in_range(l, i) > 0]
branches = [prefix_xor[in_range(d, i) + d - 1] ^ prefix_xor[in_range(d, i) - 1] for d in filter_range]
g[i] = mex(branches)
prefix_xor[i] = prefix_xor[i-1] ^ g[i]
if i == n:
print(-1 if g[i] == 0 else filter_range[find_move(branches)])
```
No
| 105,008 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We had a string s consisting of n lowercase Latin letters. We made k copies of this string, thus obtaining k identical strings s1, s2, ..., sk. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string).
You are given k strings s1, s2, ..., sk, and you have to restore any string s so that it is possible to obtain these strings by performing aforementioned operations. Note that the total length of the strings you are given doesn't exceed 5000 (that is, k·n ≤ 5000).
Input
The first line contains two integers k and n (1 ≤ k ≤ 2500, 2 ≤ n ≤ 5000, k · n ≤ 5000) — the number of strings we obtained, and the length of each of these strings.
Next k lines contain the strings s1, s2, ..., sk, each consisting of exactly n lowercase Latin letters.
Output
Print any suitable string s, or -1 if such string doesn't exist.
Examples
Input
3 4
abac
caab
acba
Output
acab
Input
3 4
kbbu
kbub
ubkb
Output
kbub
Input
5 4
abcd
dcba
acbd
dbca
zzzz
Output
-1
Note
In the first example s1 is obtained by swapping the second and the fourth character in acab, s2 is obtained by swapping the first and the second character, and to get s3, we swap the third and the fourth character.
In the second example s1 is obtained by swapping the third and the fourth character in kbub, s2 — by swapping the second and the fourth, and s3 — by swapping the first and the third.
In the third example it's impossible to obtain given strings by aforementioned operations.
Tags: brute force, hashing, implementation, strings
Correct Solution:
```
def solve():
read=lambda:list(map(int,input().split()))
from collections import Counter as co
k,n=read()
s=input()
repeated=(len(s)!=len(set(s)))
etalon=co(s)
a=[]
kk=[]
ap=a.append
for i in range(k-1):
ap(input())
if co(a[-1])!=etalon:
print(-1)
exit()
ss=False
for i in a:
if i!=s:
ss=i
for j in range(len(s)):
if s[j]!=ss[j]:
kk.append(j)
break
if len(kk)>4:
print(-1)
exit()
if ss:
if repeated:
for i in a:
k = 0
for j in range(len(i)):
if s[j] != i[j]: k += 1
if k != 0 and k != 2: break
else:
print(s)
exit()
if len(kk)!=2:
for i in range(len(kk)):
for j in range(i):
stry=s[:kk[j]]+s[kk[i]]+s[kk[j]+1:kk[i]]+s[kk[j]]+s[kk[i]+1:]
for u in a:
k = 0
for j in range(len(u)):
if stry[j] != u[j]: k += 1
if not(k==0 and repeated) and k != 2: break
else:
print(stry)
exit()
if len(kk)==2:
for change in kk:
for i in range(len(s)):
if change==i:
continue
if i >change:
stry = s[:change] + s[i] + s[change + 1:i] + s[change] + s[i + 1:]
else:
stry = s[:i] + s[change] + s[i + 1:change] + s[i] + s[change + 1:]
for u in a:
k = 0
for j in range(len(u)):
if stry[j] != u[j]: k += 1
if not(k==0 and repeated) and k != 2: break
else:
print(stry)
exit()
print(-1)
else:
if repeated:
print(s)
exit()
print(s[1]+s[0]+s[2:])
solve()
```
| 105,009 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We had a string s consisting of n lowercase Latin letters. We made k copies of this string, thus obtaining k identical strings s1, s2, ..., sk. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string).
You are given k strings s1, s2, ..., sk, and you have to restore any string s so that it is possible to obtain these strings by performing aforementioned operations. Note that the total length of the strings you are given doesn't exceed 5000 (that is, k·n ≤ 5000).
Input
The first line contains two integers k and n (1 ≤ k ≤ 2500, 2 ≤ n ≤ 5000, k · n ≤ 5000) — the number of strings we obtained, and the length of each of these strings.
Next k lines contain the strings s1, s2, ..., sk, each consisting of exactly n lowercase Latin letters.
Output
Print any suitable string s, or -1 if such string doesn't exist.
Examples
Input
3 4
abac
caab
acba
Output
acab
Input
3 4
kbbu
kbub
ubkb
Output
kbub
Input
5 4
abcd
dcba
acbd
dbca
zzzz
Output
-1
Note
In the first example s1 is obtained by swapping the second and the fourth character in acab, s2 is obtained by swapping the first and the second character, and to get s3, we swap the third and the fourth character.
In the second example s1 is obtained by swapping the third and the fourth character in kbub, s2 — by swapping the second and the fourth, and s3 — by swapping the first and the third.
In the third example it's impossible to obtain given strings by aforementioned operations.
Tags: brute force, hashing, implementation, strings
Correct Solution:
```
read=lambda:list(map(int,input().split()))
from collections import Counter as co
k,n=read()
s=input()
repeated=(len(s)!=len(set(s)))
etalon=co(s)
a=[]
kk=[]
ap=a.append
for i in range(k-1):
ap(input())
if co(a[-1])!=etalon:
print(-1)
exit()
ss=False
for i in a:
if i!=s:
ss=i
for j in range(len(s)):
if s[j]!=ss[j]:
kk.append(j)
break
if len(kk)>4:
print(-1)
exit()
if ss:
if repeated:
for i in a:
k = 0
for j in range(len(i)):
if s[j] != i[j]: k += 1
if k != 0 and k != 2: break
else:
print(s)
exit()
if len(kk)!=2:
for i in range(len(kk)):
for j in range(i):
stry=s[:kk[j]]+s[kk[i]]+s[kk[j]+1:kk[i]]+s[kk[j]]+s[kk[i]+1:]
#print(stry)
for u in a:
k = 0
for j in range(len(u)):
if stry[j] != u[j]: k += 1
#print(stry,i,k)
if not(k==0 and repeated) and k != 2: break
else:
print(stry)
exit()
if len(kk)==2:
for change in kk:
for i in range(len(s)):
if change==i:
continue
if i >change:
stry = s[:change] + s[i] + s[change + 1:i] + s[change] + s[i + 1:]
else:
stry = s[:i] + s[change] + s[i + 1:change] + s[i] + s[change + 1:]
for u in a:
k = 0
for j in range(len(u)):
if stry[j] != u[j]: k += 1
#print(stry,i,k)
if not(k==0 and repeated) and k != 2: break
else:
print(stry)
exit()
print(-1)
else:
if repeated:
print(s)
exit()
print(s[1]+s[0]+s[2:])
```
| 105,010 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We had a string s consisting of n lowercase Latin letters. We made k copies of this string, thus obtaining k identical strings s1, s2, ..., sk. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string).
You are given k strings s1, s2, ..., sk, and you have to restore any string s so that it is possible to obtain these strings by performing aforementioned operations. Note that the total length of the strings you are given doesn't exceed 5000 (that is, k·n ≤ 5000).
Input
The first line contains two integers k and n (1 ≤ k ≤ 2500, 2 ≤ n ≤ 5000, k · n ≤ 5000) — the number of strings we obtained, and the length of each of these strings.
Next k lines contain the strings s1, s2, ..., sk, each consisting of exactly n lowercase Latin letters.
Output
Print any suitable string s, or -1 if such string doesn't exist.
Examples
Input
3 4
abac
caab
acba
Output
acab
Input
3 4
kbbu
kbub
ubkb
Output
kbub
Input
5 4
abcd
dcba
acbd
dbca
zzzz
Output
-1
Note
In the first example s1 is obtained by swapping the second and the fourth character in acab, s2 is obtained by swapping the first and the second character, and to get s3, we swap the third and the fourth character.
In the second example s1 is obtained by swapping the third and the fourth character in kbub, s2 — by swapping the second and the fourth, and s3 — by swapping the first and the third.
In the third example it's impossible to obtain given strings by aforementioned operations.
Tags: brute force, hashing, implementation, strings
Correct Solution:
```
import collections
def swapCharacters(strings, k, n):
"""
Time: O(n^2 * k)
Space: O(1)
"""
if k == 1:
s0 = list(strings[0])
s0[0], s0[1] = s0[1], s0[0]
return ''.join(s0)
# Initial check for validity
freq = collections.Counter(strings[0])
canSame = (max(freq.values()) >= 2) # could swap two of the same characters ==> same string
for s in strings:
if collections.Counter(s) != freq:
return -1
# Find diff indices between first two strings
max_dist = 0
max_dist_s = None
s0 = strings[0]
for s1 in strings[1:]:
dist = HammingDistance(s0, s1, n)
if dist > max_dist:
max_dist = dist
max_dist_s = s1
# Hamming distance <= 2*2 between input strings to be valid
if max_dist > 4:
return -1
diffs = [i for i in range(n) if s0[i] != s1[i]]
# Checks all possible strings which match first two -- Finding strings (O(N)), testing string (O(KN))
s0 = list(s0)
for i in diffs:
for j in range(n):
# try swapping
s0[i], s0[j] = s0[j], s0[i]
# see if matches second string now
#dist = sum([s0[i] != s1[i] for i in diffs])
dist = HammingDistance(s0, s1, n)
if dist == 2 or (dist == 0 and canSame):
cand = ''.join(s0)
if verifyAll(strings, k, n, cand, canSame):
return cand
# revert
s0[i], s0[j] = s0[j], s0[i]
# nothing works
return -1
def HammingDistance(s0, s1, n):
count = 0
for i in range(n):
if s0[i] != s1[i]:
count += 1
return count
def verifyAll(strings, k, n, cand, canSame):
for s in strings:
dist = HammingDistance(s, cand, n)
if (dist != 0 or not canSame) and dist != 2:
return False
return True
k, n = [int(x) for x in input().split()]
strings = set() # discard duplicates
for _ in range(k):
strings.add(input())
strings = list(strings)
k = len(strings)
res = swapCharacters(strings, k, n)
print(res)
```
| 105,011 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We had a string s consisting of n lowercase Latin letters. We made k copies of this string, thus obtaining k identical strings s1, s2, ..., sk. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string).
You are given k strings s1, s2, ..., sk, and you have to restore any string s so that it is possible to obtain these strings by performing aforementioned operations. Note that the total length of the strings you are given doesn't exceed 5000 (that is, k·n ≤ 5000).
Input
The first line contains two integers k and n (1 ≤ k ≤ 2500, 2 ≤ n ≤ 5000, k · n ≤ 5000) — the number of strings we obtained, and the length of each of these strings.
Next k lines contain the strings s1, s2, ..., sk, each consisting of exactly n lowercase Latin letters.
Output
Print any suitable string s, or -1 if such string doesn't exist.
Examples
Input
3 4
abac
caab
acba
Output
acab
Input
3 4
kbbu
kbub
ubkb
Output
kbub
Input
5 4
abcd
dcba
acbd
dbca
zzzz
Output
-1
Note
In the first example s1 is obtained by swapping the second and the fourth character in acab, s2 is obtained by swapping the first and the second character, and to get s3, we swap the third and the fourth character.
In the second example s1 is obtained by swapping the third and the fourth character in kbub, s2 — by swapping the second and the fourth, and s3 — by swapping the first and the third.
In the third example it's impossible to obtain given strings by aforementioned operations.
Tags: brute force, hashing, implementation, strings
Correct Solution:
```
def solve():
read=lambda:list(map(int,input().split()))
from collections import Counter as co
k,n=read()
s=list(input())
repeated=(len(s)!=len(set(s)))
etalon=co(s)
a=[]
kk=[]
ap=a.append
for i in range(k-1):
ap(list(input()))
if co(a[-1])!=etalon:
print(-1)
exit()
ss=False
for i in a:
if i!=s:
ss=i
for j in range(len(s)):
if s[j]!=ss[j]:
kk.append(j)
break
if len(kk)>4:
print(-1)
exit()
if ss:
if repeated:
for i in a:
k = 0
for j in range(len(i)):
if s[j] != i[j]: k += 1
if k != 0 and k != 2: break
else:
print(''.join(s))
exit()
if len(kk)!=2:
for i in range(len(kk)):
for j in range(i):
stry=s[:kk[j]]+[s[kk[i]]]+s[kk[j]+1:kk[i]]+[s[kk[j]]]+s[kk[i]+1:]
for u in a:
k = 0
for j in range(len(u)):
if stry[j] != u[j]: k += 1
if not(k==0 and repeated) and k != 2: break
else:
print(''.join(stry))
exit()
if len(kk)==2:
for change in kk:
for i in range(len(s)):
if change==i:
continue
if i >change:
stry = s[:change] + [s[i]] + s[change + 1:i] + [s[change]] + s[i + 1:]
else:
stry = s[:i] + [s[change]] + s[i + 1:change] + [s[i]] + s[change + 1:]
for u in a:
k = 0
for j in range(len(u)):
if stry[j] != u[j]: k += 1
if not(k==0 and repeated) and k != 2: break
else:
print(''.join(stry))
exit()
print(-1)
else:
if repeated:
print(''.join(s))
exit()
print(s[1]+s[0]+''.join(s[2:]))
solve()
```
| 105,012 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We had a string s consisting of n lowercase Latin letters. We made k copies of this string, thus obtaining k identical strings s1, s2, ..., sk. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string).
You are given k strings s1, s2, ..., sk, and you have to restore any string s so that it is possible to obtain these strings by performing aforementioned operations. Note that the total length of the strings you are given doesn't exceed 5000 (that is, k·n ≤ 5000).
Input
The first line contains two integers k and n (1 ≤ k ≤ 2500, 2 ≤ n ≤ 5000, k · n ≤ 5000) — the number of strings we obtained, and the length of each of these strings.
Next k lines contain the strings s1, s2, ..., sk, each consisting of exactly n lowercase Latin letters.
Output
Print any suitable string s, or -1 if such string doesn't exist.
Examples
Input
3 4
abac
caab
acba
Output
acab
Input
3 4
kbbu
kbub
ubkb
Output
kbub
Input
5 4
abcd
dcba
acbd
dbca
zzzz
Output
-1
Note
In the first example s1 is obtained by swapping the second and the fourth character in acab, s2 is obtained by swapping the first and the second character, and to get s3, we swap the third and the fourth character.
In the second example s1 is obtained by swapping the third and the fourth character in kbub, s2 — by swapping the second and the fourth, and s3 — by swapping the first and the third.
In the third example it's impossible to obtain given strings by aforementioned operations.
Tags: brute force, hashing, implementation, strings
Correct Solution:
```
#!/usr/bin/env python3
n,k = map(int, input().split())
nn = []
ans = ''
for i in range(n):
mid = input()
if mid in nn:
ans = mid
continue
nn.append(mid)
n = len(nn)
if len(nn) == 1:
ans = nn[0]
ans = list(ans)
ans[0],ans[1] = ans[1],ans[0]
print(''.join(ans))
else:
diff = []
check = True
cnt = {chr(97+i):0 for i in range(26)}
for v in range(k):
cnt[nn[0][v]] += 1
for i in range(n):
cnt2 = {chr(97+i):0 for i in range(26)}
for j in range(k):
cnt2[nn[i][j]] += 1
if cnt != cnt2:
print('-1')
check = False
break
if check:
check = False
for i in range(n):
check = False
for j in range(i,n):
diff = [l for l in range(k) if nn[i][l] != nn[j][l]]
if len(diff) > 4:
check = True
print('-1')
break;
if check:
break
diff = [l for l in range(k) if nn[0][l] != nn[1][l]]
mid = []
check2 = False
for i in range(k):
if nn[0][i] in mid:
check2 = True
break
mid.append(nn[0][i])
#print(diff)
if not check:
res = list(nn[0])
check = False
for i in range(len(diff)):
if check:
break
for j in range(k):
if i == j:
continue
res[diff[i]],res[j] = res[j], res[diff[i]]
ans = ''.join(res)
#print(ans)
check = True
for x in range(n):
mid = [ans[y] for y in range(k) if nn[x][y] != ans[y]]
#print(len(diff))
if len(mid) == 2:
continue
elif len(mid) == 0 and check2:
continue
else:
check = False
if check:
print(ans)
check = True
break
res[diff[i]],res[j] = res[j],res[diff[i]]
if not check:
print('-1')
```
| 105,013 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We had a string s consisting of n lowercase Latin letters. We made k copies of this string, thus obtaining k identical strings s1, s2, ..., sk. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string).
You are given k strings s1, s2, ..., sk, and you have to restore any string s so that it is possible to obtain these strings by performing aforementioned operations. Note that the total length of the strings you are given doesn't exceed 5000 (that is, k·n ≤ 5000).
Input
The first line contains two integers k and n (1 ≤ k ≤ 2500, 2 ≤ n ≤ 5000, k · n ≤ 5000) — the number of strings we obtained, and the length of each of these strings.
Next k lines contain the strings s1, s2, ..., sk, each consisting of exactly n lowercase Latin letters.
Output
Print any suitable string s, or -1 if such string doesn't exist.
Examples
Input
3 4
abac
caab
acba
Output
acab
Input
3 4
kbbu
kbub
ubkb
Output
kbub
Input
5 4
abcd
dcba
acbd
dbca
zzzz
Output
-1
Note
In the first example s1 is obtained by swapping the second and the fourth character in acab, s2 is obtained by swapping the first and the second character, and to get s3, we swap the third and the fourth character.
In the second example s1 is obtained by swapping the third and the fourth character in kbub, s2 — by swapping the second and the fourth, and s3 — by swapping the first and the third.
In the third example it's impossible to obtain given strings by aforementioned operations.
Tags: brute force, hashing, implementation, strings
Correct Solution:
```
import sys
k, n = map(int, input().split())
s = [list(word.rstrip()) for word in sys.stdin]
double = True if max(s[0].count(chr(i+97)) for i in range(26)) > 1 else False
diff = [set() for _ in range(k)]
diff_cnt = [0]*k
for i in range(1, k):
for j in range(n):
if s[0][j] != s[i][j]:
diff[i].add(j)
diff_cnt[i] += 1
if diff_cnt[i] > 4:
print(-1)
exit()
for i in range(n):
for j in range(i+1, n):
s[0][i], s[0][j] = s[0][j], s[0][i]
for x in range(1, k):
w = [y for y in diff[x] | {i, j} if s[0][y] != s[x][y]]
if double and len(w) == 0:
continue
if len(w) == 2 and s[0][w[0]] == s[x][w[1]] and s[0][w[1]] == s[x][w[0]]:
continue
break
else:
print(''.join(s[0]))
exit()
s[0][i], s[0][j] = s[0][j], s[0][i]
print(-1)
```
| 105,014 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We had a string s consisting of n lowercase Latin letters. We made k copies of this string, thus obtaining k identical strings s1, s2, ..., sk. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string).
You are given k strings s1, s2, ..., sk, and you have to restore any string s so that it is possible to obtain these strings by performing aforementioned operations. Note that the total length of the strings you are given doesn't exceed 5000 (that is, k·n ≤ 5000).
Input
The first line contains two integers k and n (1 ≤ k ≤ 2500, 2 ≤ n ≤ 5000, k · n ≤ 5000) — the number of strings we obtained, and the length of each of these strings.
Next k lines contain the strings s1, s2, ..., sk, each consisting of exactly n lowercase Latin letters.
Output
Print any suitable string s, or -1 if such string doesn't exist.
Examples
Input
3 4
abac
caab
acba
Output
acab
Input
3 4
kbbu
kbub
ubkb
Output
kbub
Input
5 4
abcd
dcba
acbd
dbca
zzzz
Output
-1
Note
In the first example s1 is obtained by swapping the second and the fourth character in acab, s2 is obtained by swapping the first and the second character, and to get s3, we swap the third and the fourth character.
In the second example s1 is obtained by swapping the third and the fourth character in kbub, s2 — by swapping the second and the fourth, and s3 — by swapping the first and the third.
In the third example it's impossible to obtain given strings by aforementioned operations.
Submitted Solution:
```
import collections
def swapCharacters(strings, k, n):
"""
Time: O(n^2 * k)
Space: O(1)
"""
if k == 1:
return strings[0]
# Initial check for validity
freq = collections.Counter(strings[0])
for s in strings:
if collections.Counter(s) != freq:
return -1
# Find diff indices between first two strings
max_dist = 0
max_dist_s = None
s0 = strings[0]
for s1 in strings[1:]:
dist = HammingDistance(s0, s1, n)
if dist > max_dist:
max_dist = dist
max_dist_s = s1
# Hamming distance <= 2*2 between input strings to be valid
if max_dist > 4:
return -1
diffs = [i for i in range(n) if s0[i] != s1[i]]
# Checks all possible strings which match first two -- Finding strings (O(N)), testing string (O(KN))
s0 = list(s0)
for i in diffs:
for j in range(n):
# try swapping
s0[i], s0[j] = s0[j], s0[i]
# see if matches second string now
#dist = sum([s0[i] != s1[i] for i in diffs])
dist = HammingDistance(s0, s1, n)
if dist == 0 or dist == 2:
cand = ''.join(s0)
if verifyAll(strings, k, n, cand):
return cand
# revert
s0[i], s0[j] = s0[j], s0[i]
# nothing works
return -1
def HammingDistance(s0, s1, n):
count = 0
for i in range(n):
if s0[i] != s1[i]:
count += 1
return count
def verifyAll(strings, k, n, cand):
for s in strings:
dist = HammingDistance(s, cand, n)
if dist != 0 and dist != 2:
return False
return True
k, n = [int(x) for x in input().split()]
strings = []
for _ in range(k):
strings.append(input())
res = swapCharacters(strings, k, n)
print(res)
```
No
| 105,015 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We had a string s consisting of n lowercase Latin letters. We made k copies of this string, thus obtaining k identical strings s1, s2, ..., sk. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string).
You are given k strings s1, s2, ..., sk, and you have to restore any string s so that it is possible to obtain these strings by performing aforementioned operations. Note that the total length of the strings you are given doesn't exceed 5000 (that is, k·n ≤ 5000).
Input
The first line contains two integers k and n (1 ≤ k ≤ 2500, 2 ≤ n ≤ 5000, k · n ≤ 5000) — the number of strings we obtained, and the length of each of these strings.
Next k lines contain the strings s1, s2, ..., sk, each consisting of exactly n lowercase Latin letters.
Output
Print any suitable string s, or -1 if such string doesn't exist.
Examples
Input
3 4
abac
caab
acba
Output
acab
Input
3 4
kbbu
kbub
ubkb
Output
kbub
Input
5 4
abcd
dcba
acbd
dbca
zzzz
Output
-1
Note
In the first example s1 is obtained by swapping the second and the fourth character in acab, s2 is obtained by swapping the first and the second character, and to get s3, we swap the third and the fourth character.
In the second example s1 is obtained by swapping the third and the fourth character in kbub, s2 — by swapping the second and the fourth, and s3 — by swapping the first and the third.
In the third example it's impossible to obtain given strings by aforementioned operations.
Submitted Solution:
```
k, n = map(int, input().split())
se = None
for _ in range(k):
s = input()
nse = set([s])
for i in range(n-1):
for j in range(i+1, n):
ns = []
for k in range(n):
if k != i and k != j:
ns.append(s[k])
elif k == i:
ns.append(s[j])
else:
ns.append(s[i])
nse.add(''.join(ns))
print(nse)
if se is None:
se = nse
else:
se &= nse
if len(se) == 0:
print(-1)
exit()
se = list(se)
print(se[0])
```
No
| 105,016 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We had a string s consisting of n lowercase Latin letters. We made k copies of this string, thus obtaining k identical strings s1, s2, ..., sk. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string).
You are given k strings s1, s2, ..., sk, and you have to restore any string s so that it is possible to obtain these strings by performing aforementioned operations. Note that the total length of the strings you are given doesn't exceed 5000 (that is, k·n ≤ 5000).
Input
The first line contains two integers k and n (1 ≤ k ≤ 2500, 2 ≤ n ≤ 5000, k · n ≤ 5000) — the number of strings we obtained, and the length of each of these strings.
Next k lines contain the strings s1, s2, ..., sk, each consisting of exactly n lowercase Latin letters.
Output
Print any suitable string s, or -1 if such string doesn't exist.
Examples
Input
3 4
abac
caab
acba
Output
acab
Input
3 4
kbbu
kbub
ubkb
Output
kbub
Input
5 4
abcd
dcba
acbd
dbca
zzzz
Output
-1
Note
In the first example s1 is obtained by swapping the second and the fourth character in acab, s2 is obtained by swapping the first and the second character, and to get s3, we swap the third and the fourth character.
In the second example s1 is obtained by swapping the third and the fourth character in kbub, s2 — by swapping the second and the fourth, and s3 — by swapping the first and the third.
In the third example it's impossible to obtain given strings by aforementioned operations.
Submitted Solution:
```
from itertools import permutations
class UniqueElement:
def __init__(self, value, occurrences):
self.value = value
self.occurrences = occurrences
def perm_unique(elements):
e_set = set(elements)
list_unique = [UniqueElement(i, elements.count(i)) for i in e_set]
u = len(elements)
return perm_unique_helper(list_unique, [0] * u, u - 1)
def perm_unique_helper(list_unique, result_list, d):
if d < 0:
yield tuple(result_list)
else:
for i in list_unique:
if i.occurrences > 0:
result_list[d] = i.value
i.occurrences -= 1
for g in perm_unique_helper(list_unique, result_list, d - 1):
yield g
i.occurrences += 1
def count(s):
counter = {}
for ch in s:
if ch not in counter:
counter[ch] = 0
counter[ch] += 1
return counter
def hamming_distance(s1, s2, get_diff=False):
assert len(s1) == len(s2)
diff = []
for ch1, ch2 in zip(s1, s2):
if ch1 != ch2:
diff.append(1)
else:
diff.append(0)
if not get_diff:
return sum(diff)
else:
return sum(diff), diff
def final_check(ss, ans):
for s in ss:
if hamming_distance(s, ans) not in {0, 2}:
return False
return True
def main():
k, n = tuple(int(s) for s in input().split())
ss = [input() for _ in range(k)]
if k == 1:
s = list(ss[0])
s[0], s[1] = s[1], s[0]
print(''.join(s))
return
counter = count(ss[0])
for s in ss[1:]:
if counter != count(s):
print(-1)
return
dis, diff = hamming_distance(ss[0], ss[1], get_diff=True)
if dis > 4:
print(-1)
return
diff_chs = [ch for ch, is_diff in zip(ss[0], diff) if is_diff]
for perm in permutations(diff_chs):
asd = 0
new_str = []
for ch, is_diff in zip(ss[0], diff):
if is_diff:
new_str.append(perm[asd])
asd += 1
else:
new_str.append(ch)
new_str = ''.join(new_str)
if final_check(ss, new_str):
print(new_str)
return
print(-1)
if __name__ == '__main__':
main()
```
No
| 105,017 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We had a string s consisting of n lowercase Latin letters. We made k copies of this string, thus obtaining k identical strings s1, s2, ..., sk. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string).
You are given k strings s1, s2, ..., sk, and you have to restore any string s so that it is possible to obtain these strings by performing aforementioned operations. Note that the total length of the strings you are given doesn't exceed 5000 (that is, k·n ≤ 5000).
Input
The first line contains two integers k and n (1 ≤ k ≤ 2500, 2 ≤ n ≤ 5000, k · n ≤ 5000) — the number of strings we obtained, and the length of each of these strings.
Next k lines contain the strings s1, s2, ..., sk, each consisting of exactly n lowercase Latin letters.
Output
Print any suitable string s, or -1 if such string doesn't exist.
Examples
Input
3 4
abac
caab
acba
Output
acab
Input
3 4
kbbu
kbub
ubkb
Output
kbub
Input
5 4
abcd
dcba
acbd
dbca
zzzz
Output
-1
Note
In the first example s1 is obtained by swapping the second and the fourth character in acab, s2 is obtained by swapping the first and the second character, and to get s3, we swap the third and the fourth character.
In the second example s1 is obtained by swapping the third and the fourth character in kbub, s2 — by swapping the second and the fourth, and s3 — by swapping the first and the third.
In the third example it's impossible to obtain given strings by aforementioned operations.
Submitted Solution:
```
n,jks=map(int,input().split())
m=[]
m.append(input())
c=set(m[0])
def Tr(s):
for w in m:
f=[]
for i in range(jks):
if w[i]!=s[i]:
f.append(i)
if len(f)==2 and w[f[0]]==s[f[1]] and w[f[1]]==s[f[0]]:
pass
elif len(f)==0 and len(set(s))!=len(s):
pass
else:
return False
return True
for i in range(1,n):
m.append(input())
# if c!=set(m[i]):
# print(-1)
# break
#else:
a=m[0]
b=m[1]
f=[]
for i in range(jks):
if a[i]!=b[i]:
f.append(i)
if len(f)>4:
print(-1)
else:
for a in m[:2]:
sl=list(a)
for x in f:
for i in range(jks):
if i==x:
continue
slc=sl.copy()
slc[x],slc[i]=slc[i],slc[x]
sls=''.join(slc)
if Tr(sls):
print(sls)
break
else:
continue
break
else:
continue
break
else:
print(-1)
```
No
| 105,018 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today you are going to lead a group of elven archers to defend the castle that is attacked by an army of angry orcs. Three sides of the castle are protected by impassable mountains and the remaining side is occupied by a long wall that is split into n sections. At this moment there are exactly ai archers located at the i-th section of this wall. You know that archer who stands at section i can shoot orcs that attack section located at distance not exceeding r, that is all such sections j that |i - j| ≤ r. In particular, r = 0 means that archers are only capable of shooting at orcs who attack section i.
Denote as defense level of section i the total number of archers who can shoot at the orcs attacking this section. Reliability of the defense plan is the minimum value of defense level of individual wall section.
There is a little time left till the attack so you can't redistribute archers that are already located at the wall. However, there is a reserve of k archers that you can distribute among wall sections in arbitrary way. You would like to achieve maximum possible reliability of the defence plan.
Input
The first line of the input contains three integers n, r and k (1 ≤ n ≤ 500 000, 0 ≤ r ≤ n, 0 ≤ k ≤ 1018) — the number of sections of the wall, the maximum distance to other section archers can still shoot and the number of archers yet to be distributed along the wall. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the current number of archers at each section.
Output
Print one integer — the maximum possible value of defense plan reliability, i.e. the maximum possible value of minimum defense level if we distribute k additional archers optimally.
Examples
Input
5 0 6
5 4 3 4 9
Output
5
Input
4 2 0
1 2 3 4
Output
6
Input
5 1 1
2 1 2 1 2
Output
3
Tags: binary search, data structures, greedy, two pointers
Correct Solution:
```
import sys
BORDER = 1 << 30
def build(x=0):
high = low = 0
i = 0
while x and i < 30:
if x & 1:
low += (1 << i)
x >>= 1
i += 1
i = 0
while x:
if x & 1:
high += (1 << i)
x >>= 1
i += 1
return high, low
def add(x_high, x_low, y_high, y_low):
x_high += y_high
x_low += y_low
if x_low >= BORDER:
x_low -= BORDER
x_high += 1
elif x_low < 0:
x_low += BORDER
x_high -= 1
return x_high, x_low
n, r, k = map(int, sys.stdin.buffer.readline().decode('utf-8').split())
a = list(map(int, sys.stdin.buffer.readline().decode('utf-8').split()))
k_high, k_low = build(k)
left = build(sum(a[:r]))
minus_high, minus_low = [0]*n, [0]*n
w = 2*r+1
def solve(level_high, level_low):
used_high = used_low = 0
acc_high, acc_low = left
for i in range(n):
if minus_low[i] or minus_high[i]:
acc_high, acc_low =\
add(acc_high, acc_low, -minus_high[i], -minus_low[i])
minus_high[i] = minus_low[i] = 0
acc_high, acc_low = \
add(acc_high, acc_low,
0, (a[i+r] if i+r < n else 0) - (a[i-r-1] if i-r >= 1 else 0))
if acc_high < level_high or acc_high == level_high and acc_low < level_low:
used_high, used_low = add(
used_high, used_low,
level_high - acc_high, level_low - acc_low)
if used_high > k_high or used_high == k_high and used_low > k_low:
break
if i+w < n:
minus_high[i+w] = level_high - acc_high
minus_low[i+w] = level_low - acc_low
acc_high = level_high
acc_low = level_low
for i in range(i+1, n):
if minus_low[i] or minus_high[i]:
minus_low[i] = minus_high[i] = 0
return used_high < k_high or used_high == k_high and used_low <= k_low
ok, ng = min(a) + k // n, k + sum(a) + 1
while abs(ok - ng) > 1:
mid = (ok + ng) >> 1
if solve(*build(mid)):
ok = mid
else:
ng = mid
print(ok)
```
| 105,019 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Today you are going to lead a group of elven archers to defend the castle that is attacked by an army of angry orcs. Three sides of the castle are protected by impassable mountains and the remaining side is occupied by a long wall that is split into n sections. At this moment there are exactly ai archers located at the i-th section of this wall. You know that archer who stands at section i can shoot orcs that attack section located at distance not exceeding r, that is all such sections j that |i - j| ≤ r. In particular, r = 0 means that archers are only capable of shooting at orcs who attack section i.
Denote as defense level of section i the total number of archers who can shoot at the orcs attacking this section. Reliability of the defense plan is the minimum value of defense level of individual wall section.
There is a little time left till the attack so you can't redistribute archers that are already located at the wall. However, there is a reserve of k archers that you can distribute among wall sections in arbitrary way. You would like to achieve maximum possible reliability of the defence plan.
Input
The first line of the input contains three integers n, r and k (1 ≤ n ≤ 500 000, 0 ≤ r ≤ n, 0 ≤ k ≤ 1018) — the number of sections of the wall, the maximum distance to other section archers can still shoot and the number of archers yet to be distributed along the wall. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the current number of archers at each section.
Output
Print one integer — the maximum possible value of defense plan reliability, i.e. the maximum possible value of minimum defense level if we distribute k additional archers optimally.
Examples
Input
5 0 6
5 4 3 4 9
Output
5
Input
4 2 0
1 2 3 4
Output
6
Input
5 1 1
2 1 2 1 2
Output
3
Tags: binary search, data structures, greedy, two pointers
Correct Solution:
```
import sys
border = 1 << 30
def build(x=0):
res = [0, 0]
i = 0
while x and i < 30:
if x & 1:
res[1] += (1 << i)
x >>= 1
i += 1
i = 0
while x:
if x & 1:
res[0] += (1 << i)
x >>= 1
i += 1
return res
n, r, k = map(int, sys.stdin.buffer.readline().decode('utf-8').split())
a = list(map(int, sys.stdin.buffer.readline().decode('utf-8').split()))
k_big, k_small = build(k)
left = build(sum(a[:r]))
minus_big, minus_small = [0]*n, [0]*n
w = 2*r+1
def solve(level_big, level_small):
used_big = used_small = 0
acc_big, acc_small = left
for i in range(n):
if minus_small[i] or minus_big[i]:
acc_big -= minus_big[i]
acc_small -= minus_small[i]
if acc_small < 0:
acc_small += border
acc_big -= 1
elif acc_small >= border:
acc_small -= border
acc_big += 1
minus_big[i] = minus_small[i] = 0
acc_small += (a[i+r] if i+r < n else 0) - (a[i-r-1] if i-r >= 1 else 0)
if acc_small >= border:
acc_small -= border
acc_big += 1
elif acc_small < 0:
acc_small += border
acc_big -= 1
if acc_big < level_big or acc_big == level_big and acc_small < level_small:
used_big += level_big - acc_big
used_small += level_small - acc_small
if used_small >= border:
used_small -= border
used_big += 1
elif used_small < 0:
used_small += border
used_big -= 1
if used_big > k_big or used_big == k_big and used_small > k_small:
break
if i+w < n:
minus_big[i+w] = level_big - acc_big
minus_small[i+w] = level_small - acc_small
acc_big = level_big
acc_small = level_small
for i in range(i+1, n):
if minus_small[i] or minus_big[i]:
minus_small[i] = minus_big[i] = 0
return used_big < k_big or used_big == k_big and used_small <= k_small
ok, ng = min(a), k + sum(a) + 1
while abs(ok - ng) > 1:
mid = (ok + ng) >> 1
if solve(*build(mid)):
ok = mid
else:
ng = mid
print(ok)
```
| 105,020 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today you are going to lead a group of elven archers to defend the castle that is attacked by an army of angry orcs. Three sides of the castle are protected by impassable mountains and the remaining side is occupied by a long wall that is split into n sections. At this moment there are exactly ai archers located at the i-th section of this wall. You know that archer who stands at section i can shoot orcs that attack section located at distance not exceeding r, that is all such sections j that |i - j| ≤ r. In particular, r = 0 means that archers are only capable of shooting at orcs who attack section i.
Denote as defense level of section i the total number of archers who can shoot at the orcs attacking this section. Reliability of the defense plan is the minimum value of defense level of individual wall section.
There is a little time left till the attack so you can't redistribute archers that are already located at the wall. However, there is a reserve of k archers that you can distribute among wall sections in arbitrary way. You would like to achieve maximum possible reliability of the defence plan.
Input
The first line of the input contains three integers n, r and k (1 ≤ n ≤ 500 000, 0 ≤ r ≤ n, 0 ≤ k ≤ 1018) — the number of sections of the wall, the maximum distance to other section archers can still shoot and the number of archers yet to be distributed along the wall. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the current number of archers at each section.
Output
Print one integer — the maximum possible value of defense plan reliability, i.e. the maximum possible value of minimum defense level if we distribute k additional archers optimally.
Examples
Input
5 0 6
5 4 3 4 9
Output
5
Input
4 2 0
1 2 3 4
Output
6
Input
5 1 1
2 1 2 1 2
Output
3
Submitted Solution:
```
from copy import copy
n, r, k = [100, 0, 1000]
a = [int(el) for el in input().split(" ")]
if n == 1:
print(a[0]+k)
else:
def get_weight(i, radius, ar):
rez = -ar[i]
for d in range(radius+1):
if i-d >= 0:
rez += ar[i-d]
if i+d < len(ar):
rez += ar[i+d]
return rez
def get_mod_array(i, ar):
rez = copy(ar)
rez[i] += 1
return rez
def get_weight_array(ar, radius):
return [get_weight(j, radius, ar) for j in range(len(ar))]
def get_next_step(ar, radius):
rez = None
min_val = min(*get_weight_array(ar, radius))
min_count = None
min_position = ar.index(min(*ar))
left_limit = min_position - radius
if left_limit < 0:
left_limit = 0
right_limit = min_position + radius + 1
if right_limit > len(ar):
right_limit = len(ar)
for i in range(left_limit, right_limit):
temp = get_mod_array(i, ar)
temp_w = get_weight_array(temp, radius)
temp_min_count = temp_w.count(min_val)
if (min_count is None) or (temp_min_count < min_count):
rez = temp
if min_count is None:
min_count = temp_min_count
else:
break
return rez
for i in range(k):
a = get_next_step(a, r)
print(min(*get_weight_array(a, r)))
```
No
| 105,021 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today you are going to lead a group of elven archers to defend the castle that is attacked by an army of angry orcs. Three sides of the castle are protected by impassable mountains and the remaining side is occupied by a long wall that is split into n sections. At this moment there are exactly ai archers located at the i-th section of this wall. You know that archer who stands at section i can shoot orcs that attack section located at distance not exceeding r, that is all such sections j that |i - j| ≤ r. In particular, r = 0 means that archers are only capable of shooting at orcs who attack section i.
Denote as defense level of section i the total number of archers who can shoot at the orcs attacking this section. Reliability of the defense plan is the minimum value of defense level of individual wall section.
There is a little time left till the attack so you can't redistribute archers that are already located at the wall. However, there is a reserve of k archers that you can distribute among wall sections in arbitrary way. You would like to achieve maximum possible reliability of the defence plan.
Input
The first line of the input contains three integers n, r and k (1 ≤ n ≤ 500 000, 0 ≤ r ≤ n, 0 ≤ k ≤ 1018) — the number of sections of the wall, the maximum distance to other section archers can still shoot and the number of archers yet to be distributed along the wall. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the current number of archers at each section.
Output
Print one integer — the maximum possible value of defense plan reliability, i.e. the maximum possible value of minimum defense level if we distribute k additional archers optimally.
Examples
Input
5 0 6
5 4 3 4 9
Output
5
Input
4 2 0
1 2 3 4
Output
6
Input
5 1 1
2 1 2 1 2
Output
3
Submitted Solution:
```
def check(res, x):
sc = [0] * n
cur = 0
for i in range(n):
cur -= sc[i]
if sec[i] + cur < x:
delta = x - sec[i] - cur
if res < delta:
return False
res -= delta
cur += delta
if i + 2 * rd + 1 < n:
sc[i + 2 * rd + 1] = delta
return True
n, rd, k = map(int, input().split())
a = [int(x) for x in input().split()]
sec = [0] * n
for i in range(n):
for j in range(max(0, i - rd), min(n, i + rd + 1)):
sec[j] += a[i]
l = max(min(sec) - 1, 0)
r = k + l + 1
while r - l > 1:
mid = (r + l) // 2
if check(k, mid):
l = mid
else:
r = mid
print(l)
```
No
| 105,022 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today you are going to lead a group of elven archers to defend the castle that is attacked by an army of angry orcs. Three sides of the castle are protected by impassable mountains and the remaining side is occupied by a long wall that is split into n sections. At this moment there are exactly ai archers located at the i-th section of this wall. You know that archer who stands at section i can shoot orcs that attack section located at distance not exceeding r, that is all such sections j that |i - j| ≤ r. In particular, r = 0 means that archers are only capable of shooting at orcs who attack section i.
Denote as defense level of section i the total number of archers who can shoot at the orcs attacking this section. Reliability of the defense plan is the minimum value of defense level of individual wall section.
There is a little time left till the attack so you can't redistribute archers that are already located at the wall. However, there is a reserve of k archers that you can distribute among wall sections in arbitrary way. You would like to achieve maximum possible reliability of the defence plan.
Input
The first line of the input contains three integers n, r and k (1 ≤ n ≤ 500 000, 0 ≤ r ≤ n, 0 ≤ k ≤ 1018) — the number of sections of the wall, the maximum distance to other section archers can still shoot and the number of archers yet to be distributed along the wall. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the current number of archers at each section.
Output
Print one integer — the maximum possible value of defense plan reliability, i.e. the maximum possible value of minimum defense level if we distribute k additional archers optimally.
Examples
Input
5 0 6
5 4 3 4 9
Output
5
Input
4 2 0
1 2 3 4
Output
6
Input
5 1 1
2 1 2 1 2
Output
3
Submitted Solution:
```
import sys
from itertools import accumulate
from collections import Counter
n, r, k = map(int, input().split())
a = list(accumulate([0]+list(map(int, input().split()))))
def solve(level):
minus = Counter()
plus = 0
used = 0
for i in range(1, n+1):
plus += minus[i]
x = a[min(n, i+r)] - a[max(0, i-r-1)] + plus
if x < level:
used += level - x
plus += level - x
minus[i+r+1] -= level - x
return used <= k
ok, ng = min(a), 2*10**18
while abs(ok - ng) > 1:
mid = (ok + ng) >> 1
if solve(mid):
ok = mid
else:
ng = mid
print(ok)
```
No
| 105,023 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Today you are going to lead a group of elven archers to defend the castle that is attacked by an army of angry orcs. Three sides of the castle are protected by impassable mountains and the remaining side is occupied by a long wall that is split into n sections. At this moment there are exactly ai archers located at the i-th section of this wall. You know that archer who stands at section i can shoot orcs that attack section located at distance not exceeding r, that is all such sections j that |i - j| ≤ r. In particular, r = 0 means that archers are only capable of shooting at orcs who attack section i.
Denote as defense level of section i the total number of archers who can shoot at the orcs attacking this section. Reliability of the defense plan is the minimum value of defense level of individual wall section.
There is a little time left till the attack so you can't redistribute archers that are already located at the wall. However, there is a reserve of k archers that you can distribute among wall sections in arbitrary way. You would like to achieve maximum possible reliability of the defence plan.
Input
The first line of the input contains three integers n, r and k (1 ≤ n ≤ 500 000, 0 ≤ r ≤ n, 0 ≤ k ≤ 1018) — the number of sections of the wall, the maximum distance to other section archers can still shoot and the number of archers yet to be distributed along the wall. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the current number of archers at each section.
Output
Print one integer — the maximum possible value of defense plan reliability, i.e. the maximum possible value of minimum defense level if we distribute k additional archers optimally.
Examples
Input
5 0 6
5 4 3 4 9
Output
5
Input
4 2 0
1 2 3 4
Output
6
Input
5 1 1
2 1 2 1 2
Output
3
Submitted Solution:
```
def check(res, x):
sc = [0] * n
cur = 0
for i in range(n):
cur -= sc[i]
if sec[i] + cur < x:
delta = x - sec[i] - cur
if res < delta:
return False
res -= delta
cur += delta
if i + 2 * rd + 1 < n:
sc[i + 2 * rd + 1] = delta
return True
n, rd, k = map(int, input().split())
a = [int(x) for x in input().split()]
sec = [0] * n
for i in range(n):
for j in range(max(0, i - rd), min(n, i + rd + 1)):
sec[j] += a[i]
l = max(min(sec) - 1, 0)
r = k + l
while r - l > 1:
mid = (r + l) // 2
if check(k, mid):
l = mid
else:
r = mid
print(l)
```
No
| 105,024 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a special connected undirected graph where each vertex belongs to at most one simple cycle.
Your task is to remove as many edges as needed to convert this graph into a tree (connected graph with no cycles).
For each node, independently, output the maximum distance between it and a leaf in the resulting tree, assuming you were to remove the edges in a way that minimizes this distance.
Input
The first line of input contains two integers n and m (1 ≤ n ≤ 5⋅ 10^5), the number of nodes and the number of edges, respectively.
Each of the following m lines contains two integers u and v (1 ≤ u,v ≤ n, u ≠ v), and represents an edge connecting the two nodes u and v. Each pair of nodes is connected by at most one edge.
It is guaranteed that the given graph is connected and each vertex belongs to at most one simple cycle.
Output
Print n space-separated integers, the i-th integer represents the maximum distance between node i and a leaf if the removed edges were chosen in a way that minimizes this distance.
Examples
Input
9 10
7 2
9 2
1 6
3 1
4 3
4 7
7 6
9 8
5 8
5 9
Output
5 3 5 4 5 4 3 5 4
Input
4 4
1 2
2 3
3 4
4 1
Output
2 2 2 2
Note
In the first sample, a possible way to minimize the maximum distance from vertex 1 is by removing the marked edges in the following image:
<image>
Note that to minimize the answer for different nodes, you can remove different edges.
Submitted Solution:
```
print("Hello")
```
No
| 105,025 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a special connected undirected graph where each vertex belongs to at most one simple cycle.
Your task is to remove as many edges as needed to convert this graph into a tree (connected graph with no cycles).
For each node, independently, output the maximum distance between it and a leaf in the resulting tree, assuming you were to remove the edges in a way that minimizes this distance.
Input
The first line of input contains two integers n and m (1 ≤ n ≤ 5⋅ 10^5), the number of nodes and the number of edges, respectively.
Each of the following m lines contains two integers u and v (1 ≤ u,v ≤ n, u ≠ v), and represents an edge connecting the two nodes u and v. Each pair of nodes is connected by at most one edge.
It is guaranteed that the given graph is connected and each vertex belongs to at most one simple cycle.
Output
Print n space-separated integers, the i-th integer represents the maximum distance between node i and a leaf if the removed edges were chosen in a way that minimizes this distance.
Examples
Input
9 10
7 2
9 2
1 6
3 1
4 3
4 7
7 6
9 8
5 8
5 9
Output
5 3 5 4 5 4 3 5 4
Input
4 4
1 2
2 3
3 4
4 1
Output
2 2 2 2
Note
In the first sample, a possible way to minimize the maximum distance from vertex 1 is by removing the marked edges in the following image:
<image>
Note that to minimize the answer for different nodes, you can remove different edges.
Submitted Solution:
```
print('5 3 5 4 5 4 3 5 4')
```
No
| 105,026 |
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
"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)
```
| 105,027 |
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
"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])
```
| 105,028 |
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
"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)
```
| 105,029 |
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
"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)
```
| 105,030 |
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
"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)
```
| 105,031 |
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
"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])
```
| 105,032 |
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
"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])
```
| 105,033 |
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
"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)
```
| 105,034 |
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])
```
Yes
| 105,035 |
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)
```
Yes
| 105,036 |
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])
```
Yes
| 105,037 |
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])
```
Yes
| 105,038 |
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)
```
No
| 105,039 |
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])
```
No
| 105,040 |
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])
```
No
| 105,041 |
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)
```
No
| 105,042 |
Provide a correct Python 3 solution for this coding contest problem.
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead.
Constraints
* All values in input are integers between -10^9 and 10^9 (inclusive).
* 1 \leq N, M \leq 1000
* A_i < B_i\ (1 \leq i \leq N)
* E_j < F_j\ (1 \leq j \leq M)
* The point (0, 0) does not lie on any of the given segments.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M
Output
If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.)
Examples
Input
5 6
1 2 0
0 1 1
0 2 2
-3 4 -1
-2 6 3
1 0 1
0 1 2
2 0 2
-1 -4 5
3 -2 4
1 2 4
Output
13
Input
6 1
-3 -1 -2
-3 -1 1
-2 -1 2
1 4 -2
1 4 -1
1 4 1
3 1 4
Output
INF
"Correct Solution:
```
I=lambda:map(int,input().split());F=1e21;r=range;n,m=I();f=[-F,F];X=[0]+f;Y=X[:];R=[(f,F),(f,-F)];H=[(F,f),(-F,f)]
for i in r(n):*a,c=I();R+=[(a,c)];Y+=[c];X+=a
for i in r(m):a,*b=I();H+=[(a,b)];X+=[a];Y+=b
def g(X):s=dict(enumerate(sorted(set(X))));return{s[i]:i for i in s},s,len(s)+1
h,s,K=g(X);w,t,L=g(Y);j=lambda:[[0]*(K+1)for i in r(L+1)];V=j();U=j();v=j()
for(a,b),c in R:U[w[c]][h[a]]+=1;U[w[c]][h[b]]+=-1
for d,(e,f)in H:V[w[e]][h[d]]+=1;V[w[f]][h[d]]+=-1
for i in r(L):
for j in r(K):U[i][j+1]+=U[i][j];V[i+1][j]+=V[i][j]
q=[(h[0],w[0])];v[w[0]][h[0]]=1;a=0
while q:
x,y=q.pop();a+=(s[x]-s[x+1])*(t[y]-t[y+1])
for e,f in[(-1,0),(1,0),(0,1),(0,-1)]:
c=x+e;d=y+f
if(K>c>=0<=d<L)*v[d][c]==0:
if U[(f>0)+y][x]|e==0 or V[y][(e>0)+x]|f==0:q+=[(c,d)];v[d][c]=1
if a>F:a='INF'
print(a)
```
| 105,043 |
Provide a correct Python 3 solution for this coding contest problem.
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead.
Constraints
* All values in input are integers between -10^9 and 10^9 (inclusive).
* 1 \leq N, M \leq 1000
* A_i < B_i\ (1 \leq i \leq N)
* E_j < F_j\ (1 \leq j \leq M)
* The point (0, 0) does not lie on any of the given segments.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M
Output
If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.)
Examples
Input
5 6
1 2 0
0 1 1
0 2 2
-3 4 -1
-2 6 3
1 0 1
0 1 2
2 0 2
-1 -4 5
3 -2 4
1 2 4
Output
13
Input
6 1
-3 -1 -2
-3 -1 1
-2 -1 2
1 4 -2
1 4 -1
1 4 1
3 1 4
Output
INF
"Correct Solution:
```
I=lambda:map(int,input().split());F=1e21;r=range;n,m=I();f=[-F,F];X=set([0]+f);Y=set(X);R=[(f,F),(f,-F)];H=[(F,f),(-F,f)]
for i in r(n):a,b,c=I();R+=[((a,b),c)];Y.add(c);X.add(a);X.add(b)
for i in r(m):a,b,c=I();H+=[(a,(b,c))];X.add(a);Y.add(b);Y.add(c)
s=dict(enumerate(sorted(X)));K=len(s);t=dict(enumerate(sorted(Y)));L=len(t);h=dict(zip(s.values(),s.keys()));w=dict(zip(t.values(),t.keys()));V=[[0]*-~K for i in r(L+1)];U=[i[:]for i in V];v=[i[:]for i in V]
for(a,b),c in R:U[w[c]][h[a]]+=1;U[w[c]][h[b]]+=-1
for i in r(L):
for j in r(K):U[i][j+1]+=U[i][j]
for d,(e,f)in H:V[w[e]][h[d]]+=1;V[w[f]][h[d]]+=-1
for j in r(K):
for i in r(L):V[i+1][j]+=V[i][j]
q=[(h[0],w[0])];v[w[0]][h[0]]=1;a=0
while q:
x,y=q.pop();a+=(s[x]-s[x+1])*(t[y]-t[y+1])
for e,f in[(-1,0),(1,0),(0,1),(0,-1)]:
c=x+e;d=y+f
if(K>c>=0<=d<L)*v[d][c]==0:
if U[(f>0)+y][x]|e==0 or V[y][(e>0)+x]|f==0:q+=[(c,d)];v[d][c]=1
if a>F:a='INF'
print(a)
```
| 105,044 |
Provide a correct Python 3 solution for this coding contest problem.
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead.
Constraints
* All values in input are integers between -10^9 and 10^9 (inclusive).
* 1 \leq N, M \leq 1000
* A_i < B_i\ (1 \leq i \leq N)
* E_j < F_j\ (1 \leq j \leq M)
* The point (0, 0) does not lie on any of the given segments.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M
Output
If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.)
Examples
Input
5 6
1 2 0
0 1 1
0 2 2
-3 4 -1
-2 6 3
1 0 1
0 1 2
2 0 2
-1 -4 5
3 -2 4
1 2 4
Output
13
Input
6 1
-3 -1 -2
-3 -1 1
-2 -1 2
1 4 -2
1 4 -1
1 4 1
3 1 4
Output
INF
"Correct Solution:
```
def main():
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
from bisect import bisect_left, bisect_right
INF = 10**18
n, m = map(int, input().split())
a = [list(map(int, input().split())) for i in range(n)]
b = [list(map(int, input().split())) for i in range(m)]
X = {-INF, INF}
Y = {-INF, INF}
for i in a:
Y.add(i[2])
for i in b:
X.add(i[0])
X = list(sorted(X))
Y = list(sorted(Y))
n = len(X) - 1
m = len(Y) - 1
wallx = [[False] * m for i in range(n)]
wally = [[False] * m for i in range(n)]
for x1, x2, y1 in a:
x1 = bisect_left(X, x1)
y1 = bisect_left(Y, y1)
x2 = bisect_right(X, x2) - 1
for i in range(x1, x2):
wally[i][y1] = True
for x1, y1, y2 in b:
x1 = bisect_left(X, x1)
y1 = bisect_left(Y, y1)
y2 = bisect_right(Y, y2) - 1
for i in range(y1, y2):
wallx[x1][i] = True
cow = [[False] * m for i in range(n)]
cx = bisect_right(X, 0) - 1
cy = bisect_right(Y, 0) - 1
cow[cx][cy] = True
q = [(cx, cy)]
ans = 0
while q:
x, y = q.pop()
if not x or not y:
print("INF")
sys.exit()
ans += (X[x + 1] - X[x]) * (Y[y + 1] - Y[y])
if x and not wallx[x][y] and not cow[x - 1][y]:
cow[x - 1][y] = True
q.append((x - 1, y))
if y and not wally[x][y] and not cow[x][y - 1]:
cow[x][y - 1] = True
q.append((x, y - 1))
if x + 1 < n and not wallx[x + 1][y] and not cow[x + 1][y]:
cow[x + 1][y] = True
q.append((x + 1, y))
if y + 1 < m and not wally[x][y + 1] and not cow[x][y + 1]:
cow[x][y + 1] = True
q.append((x, y + 1))
print(ans)
main()
```
| 105,045 |
Provide a correct Python 3 solution for this coding contest problem.
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead.
Constraints
* All values in input are integers between -10^9 and 10^9 (inclusive).
* 1 \leq N, M \leq 1000
* A_i < B_i\ (1 \leq i \leq N)
* E_j < F_j\ (1 \leq j \leq M)
* The point (0, 0) does not lie on any of the given segments.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M
Output
If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.)
Examples
Input
5 6
1 2 0
0 1 1
0 2 2
-3 4 -1
-2 6 3
1 0 1
0 1 2
2 0 2
-1 -4 5
3 -2 4
1 2 4
Output
13
Input
6 1
-3 -1 -2
-3 -1 1
-2 -1 2
1 4 -2
1 4 -1
1 4 1
3 1 4
Output
INF
"Correct Solution:
```
from collections import deque
def LI():return [int(i) for i in input().split()]
ans=0
inf=1<<65
n,m=LI()
X=[0,inf,-inf]
Y=[0,inf,-inf]
V=[]
H=[]
for i in range(n):
a,b,c=LI()
V.append(((a,b),c))
Y.append(c)
X.append(a)
X.append(b)
n+=2
V.append(((-inf,inf),inf))
V.append(((-inf,inf),-inf))
for i in range(m):
a,b,c=LI()
H.append((a,(b,c)))
X.append(a)
Y.append(b)
Y.append(c)
m+=2
H.append((inf,(-inf,inf)))
H.append((-inf,(-inf,inf)))
X.sort()
xdc={}
c=1
for j in sorted(set(X)):
xdc[c]=j
c+=1
nx=c-1
Y.sort()
ydc={}
c=1
for j in sorted(set(Y)):
ydc[c]=j
c+=1
ny=c-1
xdcr=dict(zip(xdc.values(),xdc.keys()))
ydcr=dict(zip(ydc.values(),ydc.keys()))
mpy=[[0]*(nx+1+1) for i in range(ny+1+1)]
mpx=[i[:]for i in mpy]
for (a,b),c in V:
mpx[ydcr[c]][xdcr[a]]+=1
mpx[ydcr[c]][xdcr[b]]+=-1
for i in range(ny+1):
for j in range(nx):
mpx[i][j+1]+=mpx[i][j]
for d,(e,f) in H:
mpy[ydcr[e]][xdcr[d]]+=1
mpy[ydcr[f]][xdcr[d]]+=-1
for j in range(nx+1):
for i in range(ny):
mpy[i+1][j]+=mpy[i][j]
v=[[0]*(nx+1) for i in range(ny+1)]
q=[(xdcr[0],ydcr[0])]
v[ydcr[0]][xdcr[0]]=1
while q:
cx,cy=q.pop()
ans+=(xdc[cx]-xdc[cx+1])*(ydc[cy]-ydc[cy+1])
for dx,dy in [(-1,0),(1,0),(0,1),(0,-1)]:
nbx=cx+dx
nby=cy+dy
if (0>nbx>=nx)or(0>nby>=ny)or v[nby][nbx]==1:
continue
if dy!=0:
if mpx[-~dy//2+cy][cx]==0:
q.append((nbx,nby))
v[nby][nbx]=1
else:
if mpy[cy][-~dx//2+cx]==0:
q.append((nbx,nby))
v[nby][nbx]=1
if ans>=inf:
ans='INF'
print(ans)
```
| 105,046 |
Provide a correct Python 3 solution for this coding contest problem.
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead.
Constraints
* All values in input are integers between -10^9 and 10^9 (inclusive).
* 1 \leq N, M \leq 1000
* A_i < B_i\ (1 \leq i \leq N)
* E_j < F_j\ (1 \leq j \leq M)
* The point (0, 0) does not lie on any of the given segments.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M
Output
If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.)
Examples
Input
5 6
1 2 0
0 1 1
0 2 2
-3 4 -1
-2 6 3
1 0 1
0 1 2
2 0 2
-1 -4 5
3 -2 4
1 2 4
Output
13
Input
6 1
-3 -1 -2
-3 -1 1
-2 -1 2
1 4 -2
1 4 -1
1 4 1
3 1 4
Output
INF
"Correct Solution:
```
import sys
from typing import Iterable, Tuple, Union
class nd (object):
getter = (
lambda a, i: a,
lambda a, i: a[i[0]],
lambda a, i: a[i[0]][i[1]],
lambda a, i: a[i[0]][i[1]][i[2]],
lambda a, i: a[i[0]][i[1]][i[2]][i[3]],
lambda a, i: a[i[0]][i[1]][i[2]][i[3]][i[4]],
lambda a, i: a[i[0]][i[1]][i[2]][i[3]][i[4]][i[5]],
)
class _setter (object):
def __getitem__(self, n : int):
setter_getter = nd.getter[n-1]
def setter(a, i, v):
setter_getter(a, i[:-1])[i[-1]] = v
return setter
setter = _setter()
initializer = (
lambda s, v: [v] * s,
lambda s, v: [v] * s[0],
lambda s, v: [[v] * s[1] for _ in range(s[0])],
lambda s, v: [[[v] * s[2] for _ in range(s[1])] for _ in range(s[0])],
lambda s, v: [[[[v] * s[3] for _ in range(s[2])] for _ in range(s[1])] for _ in range(s[0])],
lambda s, v: [[[[[v] * s[4] for _ in range(s[3])] for _ in range(s[2])] for _ in range(s[1])] for _ in range(s[0])],
lambda s, v: [[[[[[v] * s[5] for _ in range(s[4])] for _ in range(s[3])] for _ in range(s[2])] for _ in range(s[1])] for _ in range(s[0])],
)
shape_getter = (
lambda a: len(a),
lambda a: (len(a),),
lambda a: (len(a), len(a[0])),
lambda a: (len(a), len(a[0]), len(a[0][0])),
lambda a: (len(a), len(a[0]), len(a[0][0]), len(a[0][0][0])),
lambda a: (len(a), len(a[0]), len(a[0][0]), len(a[0][0][0]), len(a[0][0][0][0])),
lambda a: (len(a), len(a[0]), len(a[0][0]), len(a[0][0][0]), len(a[0][0][0][0]), len(a[0][0][0][0][0])),
)
indices_iterator = (
lambda s: iter(range(s)),
lambda s: ((i,) for i in range(s[0])),
lambda s: ((i, j) for j in range(s[1]) for i in range(s[0])),
lambda s: ((i, j, k) for k in range(s[2]) for j in range(s[1]) for i in range(s[0])),
lambda s: ((i, j, k, l) for l in range(s[3]) for k in range(s[2]) for j in range(s[1]) for i in range(s[0])),
lambda s: ((i, j, k, l, m) for m in range(s[4]) for l in range(s[3]) for k in range(s[2]) for j in range(s[1]) for i in range(s[0])),
lambda s: ((i, j, k, l, m, n) for n in range(s[5]) for m in range(s[4]) for l in range(s[3]) for k in range(s[2]) for j in range(s[1]) for i in range(s[0])),
)
iterable_product = (
lambda s: iter(s),
lambda s: ((i,) for i in s[0]),
lambda s: ((i, j) for j in s[1] for i in s[0]),
lambda s: ((i, j, k) for k in s[2] for j in s[1] for i in s[0]),
lambda s: ((i, j, k, l) for l in s[3] for k in s[2] for j in s[1] for i in s[0]),
lambda s: ((i, j, k, l, m) for m in s[4] for l in s[3] for k in s[2] for j in s[1] for i in s[0]),
lambda s: ((i, j, k, l, m, n) for n in s[5] for m in s[4] for l in s[3] for k in s[2] for j in s[1] for i in s[0]),
)
@classmethod
def full(cls, fill_value, shape : Union[int, Tuple[int], Iterable[int]]):
if isinstance(shape, int):
return cls.initializer[0](shape, fill_value)
elif not isinstance(shape, tuple):
shape = tuple(shape)
return cls.initializer[len(shape)](shape, fill_value)
@classmethod
def fromiter(cls, iterable : Iterable, ndim=1):
if ndim == 1:
return list(iterable)
else:
return list(map(cls.fromiter, iterable))
@classmethod
def nones(cls, shape : Union[int, Tuple[int], Iterable[int]]):
return cls.full(None, shape)
@classmethod
def zeros(cls, shape : Union[int, Tuple[int], Iterable[int]], type=int):
return cls.full(type(0), shape)
@classmethod
def ones(cls, shape : Union[int, Tuple[int], Iterable[int]], type=int):
return cls.full(type(1), shape)
class _range (object):
def __getitem__(self, shape : Union[int, slice, Tuple[Union[int, slice]]]):
if isinstance(shape, int):
return iter(range(shape))
elif isinstance(shape, slice):
return iter(range(shape.stop)[shape])
else:
shape = tuple(range(s.stop)[s] for s in shape)
return nd.iterable_product[len(shape)](shape)
def __call__(self, shape : Union[int, slice, Tuple[Union[int, slice]]]):
return self[shape]
range = _range()
def bytes_to_str(x : bytes):
return x.decode('utf-8')
def inputs(func=bytes_to_str, sep=None, maxsplit=-1):
return map(func, sys.stdin.buffer.readline().split(sep=sep, maxsplit=maxsplit))
def inputs_1d(func=bytes_to_str, **kwargs):
return nd(inputs(func, **kwargs))
def inputs_2d(nrows : int, func=bytes_to_str, **kwargs):
return nd.fromiter(
(inputs(func, **kwargs) for _ in range(nrows)),
ndim=2
)
def inputs_2d_T(nrows : int, func=bytes_to_str, **kwargs):
return nd.fromiter(
zip(*(inputs(func, **kwargs) for _ in range(nrows))),
ndim=2
)
from collections import deque
from typing import Optional
class BreadthFirstSearch (object):
__slots__ = [
'shape',
'pushed',
'_deque',
'_getter',
'_setter'
]
def __init__(self, shape : Union[int, Iterable[int]]):
self.shape = (shape,) if isinstance(shape, int) else tuple(shape)
self.pushed = nd.zeros(self.shape, type=bool)
self._deque = deque()
self._getter = nd.getter[len(self.shape)]
self._setter = nd.setter[len(self.shape)]
def push(self, position : Tuple[int]):
if not self._getter(self.pushed, position):
self._setter(self.pushed, position, True)
self._deque.append(position)
def peek(self) -> Optional[Tuple[int]]:
return self._deque[0] if self._deque else None
def pop(self) -> Optional[Tuple[int]]:
return self._deque.popleft() if self._deque else None
def __bool__(self):
return bool(self._deque)
from bisect import bisect_left, bisect_right
N, M = inputs(int)
A, B, C = inputs_2d_T(N, int)
D, E, F = inputs_2d_T(M, int)
xs = sorted(set(C))
ys = sorted(set(D))
x_guard = nd.zeros((len(xs)+1, len(ys)+1), type=bool)
y_guard = nd.zeros((len(xs)+1, len(ys)+1), type=bool)
for a, b, c in zip(A, B, C):
c = bisect_right(xs, c)
a = bisect_left(ys, a) + 1
b = bisect_right(ys, b)
for y in range(a, b):
x_guard[c][y] = True
for d, e, f in zip(D, E, F):
d = bisect_right(ys, d)
e = bisect_left(xs, e) + 1
f = bisect_right(xs, f)
for x in range(e, f):
y_guard[x][d] = True
cow = (
bisect_right(xs, 0),
bisect_right(ys, 0)
)
bfs = BreadthFirstSearch(shape=(len(xs)+1, len(ys)+1))
bfs.push(cow)
area = 0
while bfs:
xi, yi = bfs.pop()
if 0 < xi < len(xs) and 0 < yi < len(ys):
area += (xs[xi] - xs[xi-1]) * (ys[yi] - ys[yi-1])
if not x_guard[xi][yi]:
bfs.push((xi-1, yi))
if not x_guard[xi+1][yi]:
bfs.push((xi+1, yi))
if not y_guard[xi][yi]:
bfs.push((xi, yi-1))
if not y_guard[xi][yi+1]:
bfs.push((xi, yi+1))
else:
area = 'INF'
break
print(area)
```
| 105,047 |
Provide a correct Python 3 solution for this coding contest problem.
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead.
Constraints
* All values in input are integers between -10^9 and 10^9 (inclusive).
* 1 \leq N, M \leq 1000
* A_i < B_i\ (1 \leq i \leq N)
* E_j < F_j\ (1 \leq j \leq M)
* The point (0, 0) does not lie on any of the given segments.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M
Output
If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.)
Examples
Input
5 6
1 2 0
0 1 1
0 2 2
-3 4 -1
-2 6 3
1 0 1
0 1 2
2 0 2
-1 -4 5
3 -2 4
1 2 4
Output
13
Input
6 1
-3 -1 -2
-3 -1 1
-2 -1 2
1 4 -2
1 4 -1
1 4 1
3 1 4
Output
INF
"Correct Solution:
```
from collections import deque
import bisect
INF = float("inf")
N,M = map(int,input().split())
xtic = {0,-INF,INF}
ytic = {0,-INF,INF}
hor = []
for _ in range(N):
a,b,c = map(int,input().split())
hor.append((c,a,b))
xtic.add(a)
xtic.add(b)
ytic.add(c)
ver = []
for _ in range(M):
d,e,f = map(int,input().split())
ver.append((d,e,f))
xtic.add(d)
ytic.add(e)
ytic.add(f)
xtic = list(xtic)
ytic = list(ytic)
xtic.sort()
ytic.sort()
xdic = {xtic[i]:i+1 for i in range(len(xtic))}
ydic = {ytic[i]:i+1 for i in range(len(ytic))}
gyaku_xdic = {xdic[k]:k for k in xdic}
gyaku_ydic = {ydic[k]:k for k in ydic}
hor.sort()
ver.sort()
hor_dic = {}
ver_dic = {}
now = None
for c,a,b in hor:
c,a,b = ydic[c],xdic[a],xdic[b]
if c != now:
hor_dic[c] = (1<<b) - (1<<a)
else:
hor_dic[c] |= (1<<b) - (1<<a)
now = c
now = None
for d,e,f in ver:
d,e,f = xdic[d],ydic[e],ydic[f]
if d != now:
ver_dic[d] = (1<<f) - (1<<e)
else:
ver_dic[d] |= (1<<f) - (1<<e)
now = d
def is_connected(x,y,dx,dy):
if dx == 0:
if dy > 0:
if (hor_wall[y+1]>>x)&1:
return False
return True
else:
if (hor_wall[y]>>x)&1:
return False
return True
else:
if dx > 0:
if (ver_wall[x+1]>>y)&1:
return False
return True
else:
if (ver_wall[x]>>y)&1:
return False
return True
def calc_area(x,y):
X = gyaku_xdic[x+1] - gyaku_xdic[x]
Y = gyaku_ydic[y+1] - gyaku_ydic[y]
return X*Y
offset = [(1,0),(0,1),(-1,0),(0,-1)]
x0 = bisect.bisect(xtic,0)
y0 = bisect.bisect(ytic,0)
W,H = len(xtic)+1 ,len(ytic)+1
hor_wall = [0 for i in range(H)]
ver_wall = [0 for i in range(W)]
for k in hor_dic:
hor_wall[k] = hor_dic[k]
for k in ver_dic:
ver_wall[k] = ver_dic[k]
d = [[0 for i in range(W)] for j in range(H)]
d[y0][x0] = 1
q = deque([(x0,y0)])
area = 0
while q:
x,y = q.pop()
area += calc_area(x,y)
for dx,dy in offset:
nx,ny = x+dx,y+dy
if 0<=nx<W and 0<=ny<H:
if is_connected(x,y,dx,dy):
if nx == 0 or ny == 0 or nx == W-1 or ny == H-1:
print("INF")
exit()
if d[ny][nx] == 0:
d[ny][nx] = 1
q.append((nx,ny))
print(area)
```
| 105,048 |
Provide a correct Python 3 solution for this coding contest problem.
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead.
Constraints
* All values in input are integers between -10^9 and 10^9 (inclusive).
* 1 \leq N, M \leq 1000
* A_i < B_i\ (1 \leq i \leq N)
* E_j < F_j\ (1 \leq j \leq M)
* The point (0, 0) does not lie on any of the given segments.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M
Output
If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.)
Examples
Input
5 6
1 2 0
0 1 1
0 2 2
-3 4 -1
-2 6 3
1 0 1
0 1 2
2 0 2
-1 -4 5
3 -2 4
1 2 4
Output
13
Input
6 1
-3 -1 -2
-3 -1 1
-2 -1 2
1 4 -2
1 4 -1
1 4 1
3 1 4
Output
INF
"Correct Solution:
```
def f_single_dot():
# https://atcoder.jp/contests/abc168/submissions/13368489
import sys
from collections import deque
input = sys.stdin.readline
N, M = [int(i) for i in input().split()]
X, Y = set([0]), set([0])
vertical_lines = []
for _ in range(N):
a, b, grid = map(int, input().split())
vertical_lines.append((a, b, grid))
X |= {a, b}
Y |= {grid}
horizontal_lines = []
for _ in range(M):
d, e, f = map(int, input().split())
horizontal_lines.append((d, e, f))
X |= {d}
Y |= {e, f}
X = sorted(X)
Y = sorted(Y)
dictx, dicty = {n: i * 2 for i, n in enumerate(X)}, {n: i * 2 for i, n in enumerate(Y)}
LX = [X[i // 2 + 1] - X[i // 2] if i % 2 else 0 for i in range(len(X) * 2 - 1)]
LY = [Y[i // 2 + 1] - Y[i // 2] if i % 2 else 0 for i in range(len(Y) * 2 - 1)]
grid = [[0] * (len(X) * 2 - 1) for _ in range(len(Y) * 2 - 1)]
for a, b, c in vertical_lines:
a, b, c = dictx[a], dictx[b], dicty[c]
for x in range(a, b + 1):
grid[c][x] = 1
for d, e, f in horizontal_lines:
d, e, f = dictx[d], dicty[e], dicty[f]
for y in range(e, f + 1):
grid[y][d] = 1
que = deque()
used = [[0] * len(X) * 2 for _ in range(len(Y) * 2)]
dy = [1, 1, -1, -1]
dx = [1, -1, 1, -1]
for k in range(4):
nny, nnx = dicty[0] + dy[k], dictx[0] + dx[k]
if 1 <= nny < len(Y) * 2 - 1 and 1 <= nnx < len(X) * 2 - 1:
que.append((nny, nnx))
used[nny][nnx] = 1
ans = 0
dy = [1, 0, -1, 0]
dx = [0, 1, 0, -1]
while que:
y, x = que.popleft()
if y % 2 and x % 2:
ans += LY[y] * LX[x]
for k in range(4):
ny, nx = y + dy[k], x + dx[k]
nny, nnx = ny + dy[k], nx + dx[k]
if grid[ny][nx] == 0:
if nny < 0 or nny >= len(Y) * 2 - 1 or nnx < 0 or nnx >= len(X) * 2 - 1:
return 'INF'
if not used[nny][nnx]:
que.append((nny, nnx))
used[nny][nnx] = 1
return ans
print(f_single_dot())
```
| 105,049 |
Provide a correct Python 3 solution for this coding contest problem.
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead.
Constraints
* All values in input are integers between -10^9 and 10^9 (inclusive).
* 1 \leq N, M \leq 1000
* A_i < B_i\ (1 \leq i \leq N)
* E_j < F_j\ (1 \leq j \leq M)
* The point (0, 0) does not lie on any of the given segments.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M
Output
If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.)
Examples
Input
5 6
1 2 0
0 1 1
0 2 2
-3 4 -1
-2 6 3
1 0 1
0 1 2
2 0 2
-1 -4 5
3 -2 4
1 2 4
Output
13
Input
6 1
-3 -1 -2
-3 -1 1
-2 -1 2
1 4 -2
1 4 -1
1 4 1
3 1 4
Output
INF
"Correct Solution:
```
import sys
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]
def main():
n, m = MI()
xx = set([0])
yy = set([0])
vl = []
hl = []
for _ in range(n):
a, b, c = MI()
xx.add(a)
xx.add(b)
yy.add(c)
vl.append((a, b, c))
for _ in range(m):
a, b, c = MI()
xx.add(a)
yy.add(b)
yy.add(c)
hl.append((b, c, a))
dex = list(sorted(xx))
dey = list(sorted(yy))
cox = {x: i for i, x in enumerate(dex)}
coy = {x: i for i, x in enumerate(dey)}
h = len(dex)
w = len(dey)
vlt=[[1]*w for _ in range(h)]
for x0, x1, y in vl:
j = coy[y]
for i in range(cox[x0], cox[x1]):
vlt[i][j]=0
hlt=[[1]*w for _ in range(h)]
for y0, y1, x in hl:
i = cox[x]
for j in range(coy[y0], coy[y1]):
hlt[i][j]=0
#p2D(vlt)
#print()
#p2D(hlt)
tt = [[False] * w for _ in range(h)]
def inf():
print("INF")
exit()
def move(ni, nj):
if tt[ni][nj]: return
tt[ni][nj] = True
stack.append((ni, nj))
si, sj = cox[0], coy[0]
if si==h-1 or sj==w-1:inf()
stack = [(si, sj)]
tt[si][sj] = True
while stack:
i, j = stack.pop()
ni, nj = i, j - 1
if vlt[i][j]:
if nj == -1: inf()
move(ni, nj)
ni, nj = i, j + 1
if vlt[ni][nj]:
if nj == w - 1: inf()
move(ni, nj)
ni, nj = i - 1, j
if hlt[i][j]:
if ni == -1: inf()
move(ni, nj)
ni, nj = i + 1, j
if hlt[ni][nj]:
if ni == h - 1: inf()
move(ni, nj)
#p2D(tt)
ans = 0
for i in range(h - 1):
for j in range(w - 1):
if tt[i][j]: ans += (dex[i + 1] - dex[i]) * (dey[j + 1] - dey[j])
print(ans)
main()
```
| 105,050 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead.
Constraints
* All values in input are integers between -10^9 and 10^9 (inclusive).
* 1 \leq N, M \leq 1000
* A_i < B_i\ (1 \leq i \leq N)
* E_j < F_j\ (1 \leq j \leq M)
* The point (0, 0) does not lie on any of the given segments.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M
Output
If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.)
Examples
Input
5 6
1 2 0
0 1 1
0 2 2
-3 4 -1
-2 6 3
1 0 1
0 1 2
2 0 2
-1 -4 5
3 -2 4
1 2 4
Output
13
Input
6 1
-3 -1 -2
-3 -1 1
-2 -1 2
1 4 -2
1 4 -1
1 4 1
3 1 4
Output
INF
Submitted Solution:
```
n,m,*l = map(int, open(0).read().split())
l=iter(l)
l=list(zip(l,l,l))
l1=l[:n]
l2=l[-m:]
V=set([float('inf'),-float('inf')])
H=set([float('inf'),-float('inf')])
for a,b,c in l1:
V.add(c)
H.add(a)
H.add(b)
for c,a,b in l2:
H.add(c)
V.add(a)
V.add(b)
V=sorted(list(V))
H=sorted(list(H))
Vdic={}
Hdic={}
for i,v in enumerate(V):
Vdic[v]=i
for i,h in enumerate(H):
Hdic[h]=i
checkv=[[0]*3001 for i in range(3001)]
checkh=[[0]*3001 for i in range(3001)]
check=[[0]*3001 for i in range(3001)]
for a,b,c in l1:
c=Vdic[c]
for i in range(Hdic[a],Hdic[b]):
checkh[c][i]=1
for c,a,b in l2:
c=Hdic[c]
for i in range(Vdic[a],Vdic[b]):
checkv[i][c]=1
from bisect import bisect_left
pv=bisect_left(V,0)-1
ph=bisect_left(H,0)-1
ans=0
stack=[(pv,ph)]
check[pv][ph]=1
while stack:
v,h=stack.pop()
ans+=(V[v+1]-V[v])*(H[h+1]-H[h])
if h!=0 and checkv[v][h]==0 and check[v][h-1]==0:
stack.append((v,h-1))
check[v][h-1]=1
if h!=len(H)-2 and checkv[v][h+1]==0 and check[v][h+1]==0:
stack.append((v,h+1))
check[v][h+1]=1
if v!=0 and checkh[v][h]==0 and check[v-1][h]==0:
stack.append((v-1,h))
check[v-1][h]=1
if v!=len(V)-2 and checkh[v+1][h]==0 and check[v+1][h]==0:
stack.append((v+1,h))
check[v+1][h]=1
print("INF" if ans==float('inf') else ans)
```
Yes
| 105,051 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead.
Constraints
* All values in input are integers between -10^9 and 10^9 (inclusive).
* 1 \leq N, M \leq 1000
* A_i < B_i\ (1 \leq i \leq N)
* E_j < F_j\ (1 \leq j \leq M)
* The point (0, 0) does not lie on any of the given segments.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M
Output
If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.)
Examples
Input
5 6
1 2 0
0 1 1
0 2 2
-3 4 -1
-2 6 3
1 0 1
0 1 2
2 0 2
-1 -4 5
3 -2 4
1 2 4
Output
13
Input
6 1
-3 -1 -2
-3 -1 1
-2 -1 2
1 4 -2
1 4 -1
1 4 1
3 1 4
Output
INF
Submitted Solution:
```
import sys
# from itertools import chain, accumulate
n, m, *abcdef = map(int, sys.stdin.buffer.read().split())
ver_lines = []
hor_lines = []
x_list = set()
y_list = set()
n3 = n * 3
for a, b, c in zip(abcdef[0:n3:3], abcdef[1:n3:3], abcdef[2:n3:3]):
y_list.add(a)
y_list.add(b)
x_list.add(c)
ver_lines.append((a, b, c))
for d, e, f in zip(abcdef[n3 + 0::3], abcdef[n3 + 1::3], abcdef[n3 + 2::3]):
y_list.add(d)
x_list.add(e)
x_list.add(f)
hor_lines.append((d, e, f))
x_list.add(0)
y_list.add(0)
x_list = sorted(x_list)
y_list = sorted(y_list)
x_dict = {x: i for i, x in enumerate(x_list, start=1)}
y_dict = {y: i for i, y in enumerate(y_list, start=1)}
row_real = len(x_list)
col_real = len(y_list)
row = row_real + 2
col = col_real + 2
banned_up = [0] * (row * col)
banned_down = [0] * (row * col)
banned_left = [0] * (row * col)
banned_right = [0] * (row * col)
for a, b, c in ver_lines:
if a > b:
a, b = b, a
ai = y_dict[a] * row
bi = y_dict[b] * row
j = x_dict[c]
banned_left[ai + j] += 1
banned_left[bi + j] -= 1
banned_right[ai + j - 1] += 1
banned_right[bi + j - 1] -= 1
for d, e, f in hor_lines:
if e > f:
e, f = f, e
ri = y_dict[d] * row
ej = x_dict[e]
fj = x_dict[f]
banned_up[ri + ej] += 1
banned_up[ri + fj] -= 1
banned_down[ri - row + ej] += 1
banned_down[ri - row + fj] -= 1
for i in range(1, col):
ri0 = row * (i - 1)
ri1 = row * i
for j in range(1, row):
banned_up[ri1 + j] += banned_up[ri1 + j - 1]
banned_down[ri1 + j] += banned_down[ri1 + j - 1]
banned_left[ri1 + j] += banned_left[ri0 + j]
banned_right[ri1 + j] += banned_right[ri0 + j]
# banned_up = list(chain.from_iterable(map(accumulate, banned_up_ij)))
# banned_down = list(chain.from_iterable(map(accumulate, banned_down_ij)))
# banned_left = list(chain.from_iterable(zip(*map(accumulate, banned_left_ij))))
# banned_right = list(chain.from_iterable(zip(*map(accumulate, banned_right_ij))))
# for i in range(col):
# print(walls[i * row:(i + 1) * row])
s = row * y_dict[0] + x_dict[0]
enable = [-1] * row + ([-1] + [0] * (row - 2) + [-1]) * (col - 2) + [-1] * row
# for i in range(col):
# print(enable[i * row:(i + 1) * row])
q = [s]
moves = [(-row, banned_up), (-1, banned_left), (1, banned_right), (row, banned_down)]
while q:
c = q.pop()
if enable[c] == 1:
continue
elif enable[c] == -1:
print('INF')
exit()
enable[c] = 1
for dc, banned in moves:
if banned[c]:
continue
nc = c + dc
if enable[nc] == 1:
continue
q.append(nc)
# for i in range(col):
# print(enable[i * row:(i + 1) * row])
ans = 0
for i in range(col):
ri = i * row
for j in range(row):
if enable[ri + j] != 1:
continue
t = y_list[i - 1]
b = y_list[i]
l = x_list[j - 1]
r = x_list[j]
ans += (b - t) * (r - l)
print(ans)
```
Yes
| 105,052 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead.
Constraints
* All values in input are integers between -10^9 and 10^9 (inclusive).
* 1 \leq N, M \leq 1000
* A_i < B_i\ (1 \leq i \leq N)
* E_j < F_j\ (1 \leq j \leq M)
* The point (0, 0) does not lie on any of the given segments.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M
Output
If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.)
Examples
Input
5 6
1 2 0
0 1 1
0 2 2
-3 4 -1
-2 6 3
1 0 1
0 1 2
2 0 2
-1 -4 5
3 -2 4
1 2 4
Output
13
Input
6 1
-3 -1 -2
-3 -1 1
-2 -1 2
1 4 -2
1 4 -1
1 4 1
3 1 4
Output
INF
Submitted Solution:
```
import sys,queue,math,copy,itertools,bisect,collections,heapq
def main():
INF = 10**9 + 1
MOD = 10**9 + 7
LI = lambda : [int(x) for x in sys.stdin.readline().split()]
N,M = LI()
x = []; y = []
A = []
D = []
for _ in range(N):
a,b,c = LI()
A.append((a,b,c))
x.append(a); x.append(b)
y.append(c); y.append(c)
for _ in range(M):
d,e,f = LI()
D.append((d,e,f))
x.append(d); x.append(d)
y.append(e); y.append(f)
x.append(-INF); x.append(INF); x.append(0)
y.append(-INF); y.append(INF); y.append(0)
x.sort(); y.sort()
lx = len(x); ly = len(y)
fld = [[0] * ly for _ in range(lx)]
for a,b,c in A:
j = bisect.bisect_left(y,c)
for i in range(bisect.bisect_left(x,a),bisect.bisect_left(x,b)):
fld[i][j] = 1
for d,e,f in D:
i = bisect.bisect_left(x,d)
for j in range(bisect.bisect_left(y,e),bisect.bisect_left(y,f)):
fld[i][j] = 1
q = []
i = bisect.bisect_left(x,0)
j = bisect.bisect_left(y,0)
q.append((i,j))
fld[i][j] = 1
ans = 0
while q:
i,j = q.pop()
ans += (x[i+1]-x[i]) * (y[j+1]-y[j])
for di,dj in ((0,1),(1,0),(0,-1),(-1,0)):
if 0 < i+di < lx-1 and 0 < j+dj < ly-1:
if fld[i+di][j+dj] == 0:
fld[i+di][j+dj] = 1
q.append((i+di,j+dj))
else:
print('INF')
exit(0)
print(ans)
if __name__ == '__main__':
main()
```
Yes
| 105,053 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead.
Constraints
* All values in input are integers between -10^9 and 10^9 (inclusive).
* 1 \leq N, M \leq 1000
* A_i < B_i\ (1 \leq i \leq N)
* E_j < F_j\ (1 \leq j \leq M)
* The point (0, 0) does not lie on any of the given segments.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M
Output
If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.)
Examples
Input
5 6
1 2 0
0 1 1
0 2 2
-3 4 -1
-2 6 3
1 0 1
0 1 2
2 0 2
-1 -4 5
3 -2 4
1 2 4
Output
13
Input
6 1
-3 -1 -2
-3 -1 1
-2 -1 2
1 4 -2
1 4 -1
1 4 1
3 1 4
Output
INF
Submitted Solution:
```
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def GI(V,E,ls=None,Directed=False,index=1):
org_inp=[];g=[[] for i in range(V)]
FromStdin=True if ls==None else False
for i in range(E):
if FromStdin:
inp=LI()
org_inp.append(inp)
else:
inp=ls[i]
if len(inp)==2:
a,b=inp;c=1
else:
a,b,c=inp
if index==1:a-=1;b-=1
aa=(a,c);bb=(b,c);g[a].append(bb)
if not Directed:g[b].append(aa)
return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
#h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
mp=[boundary]*(w+2);found={}
for i in range(h):
s=input()
for char in search:
if char in s:
found[char]=((i+1)*(w+2)+s.index(char)+1)
mp_def[char]=mp_def[replacement_of_found]
mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
mp+=[boundary]*(w+2)
return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def bit_combination(n,base=2):
rt=[]
for tb in range(base**n):s=[tb//(base**bt)%base for bt in range(n)];rt+=[s]
return rt
def gcd(x,y):
if y==0:return x
if x%y==0:return y
while x%y!=0:x,y=y,x%y
return y
def show(*inp,end='\n'):
if show_flg:print(*inp,end=end)
YN=['YES','NO'];Yn=['Yes','No']
mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
input=lambda: sys.stdin.readline().rstrip()
class Tree:
def __init__(self,inp_size=None,ls=None,init=True,index=0):
self.LCA_init_stat=False
self.ETtable=[]
if init:
if ls==None:
self.stdin(inp_size,index=index)
else:
self.size=len(ls)+1
self.edges,_=GI(self.size,self.size-1,ls,index=index)
return
def stdin(self,inp_size=None,index=1):
if inp_size==None:
self.size=int(input())
else:
self.size=inp_size
self.edges,_=GI(self.size,self.size-1,index=index)
return
def listin(self,ls,index=0):
self.size=len(ls)+1
self.edges,_=GI(self.size,self.size-1,ls,index=index)
return
def __str__(self):
return str(self.edges)
def dfs(self,x,func=lambda prv,nx,dist:prv+dist,root_v=0):
q=deque()
q.append(x)
v=[-1]*self.size
v[x]=root_v
while q:
c=q.pop()
for nb,d in self.edges[c]:
if v[nb]==-1:
q.append(nb)
v[nb]=func(v[c],nb,d)
return v
def EulerTour(self,x):
q=deque()
q.append(x)
self.depth=[None]*self.size
self.depth[x]=0
self.ETtable=[]
self.ETdepth=[]
self.ETin=[-1]*self.size
self.ETout=[-1]*self.size
cnt=0
while q:
c=q.pop()
if c<0:
ce=~c
else:
ce=c
for nb,d in self.edges[ce]:
if self.depth[nb]==None:
q.append(~ce)
q.append(nb)
self.depth[nb]=self.depth[ce]+1
self.ETtable.append(ce)
self.ETdepth.append(self.depth[ce])
if self.ETin[ce]==-1:
self.ETin[ce]=cnt
else:
self.ETout[ce]=cnt
cnt+=1
return
def LCA_init(self,root):
self.EulerTour(root)
self.st=SparseTable(self.ETdepth,init_func=min,init_idl=inf)
self.LCA_init_stat=True
return
def LCA(self,root,x,y):
if self.LCA_init_stat==False:
self.LCA_init(root)
xin,xout=self.ETin[x],self.ETout[x]
yin,yout=self.ETin[y],self.ETout[y]
a=min(xin,yin)
b=max(xout,yout,xin,yin)
id_of_min_dep_in_et=self.st.query_id(a,b+1)
return self.ETtable[id_of_min_dep_in_et]
class SparseTable: # O(N log N) for init, O(1) for query(l,r)
def __init__(self,ls,init_func=min,init_idl=float('inf')):
self.func=init_func
self.idl=init_idl
self.size=len(ls)
self.N0=self.size.bit_length()
self.table=[ls[:]]
self.index=[list(range(self.size))]
self.lg=[0]*(self.size+1)
for i in range(2,self.size+1):
self.lg[i]=self.lg[i>>1]+1
for i in range(self.N0):
tmp=[self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) for j in range(self.size)]
tmp_id=[self.index[i][j] if self.table[i][j]==self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) else self.index[i][min(j+(1<<i),self.size-1)] for j in range(self.size)]
self.table+=[tmp]
self.index+=[tmp_id]
# return func of [l,r)
def query(self,l,r):
if r>self.size:r=self.size
#N=(r-l).bit_length()-1
N=self.lg[r-l]
return self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))])
# return index of which val[i] = func of v among [l,r)
def query_id(self,l,r):
if r>self.size:r=self.size
#N=(r-l).bit_length()-1
N=self.lg[r-l]
a,b=self.index[N][l],self.index[N][max(0,r-(1<<N))]
if self.table[0][a]==self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))]):
b=a
return b
def __str__(self):
return str(self.table[0])
def print(self):
for i in self.table:
print(*i)
class Comb:
def __init__(self,n,mo=10**9+7):
self.fac=[0]*(n+1)
self.inv=[1]*(n+1)
self.fac[0]=1
self.fact(n)
for i in range(1,n+1):
self.fac[i]=i*self.fac[i-1]%mo
self.inv[n]*=i
self.inv[n]%=mo
self.inv[n]=pow(self.inv[n],mo-2,mo)
for i in range(1,n):
self.inv[n-i]=self.inv[n-i+1]*(n-i+1)%mo
return
def fact(self,n):
return self.fac[n]
def invf(self,n):
return self.inv[n]
def comb(self,x,y):
if y<0 or y>x:
return 0
return self.fac[x]*self.inv[x-y]*self.inv[y]%mo
show_flg=False
show_flg=True
ans=0
inf=1<<65
n,m=LI()
X=[0,inf,-inf]
Y=[0,inf,-inf]
V=[]
H=[]
for i in range(n):
a,b,c=LI()
V.append(((a,b),c))
Y.append(c)
X.append(a)
X.append(b)
n+=2
V.append(((-inf,inf),inf))
V.append(((-inf,inf),-inf))
for i in range(m):
a,b,c=LI()
H.append((a,(b,c)))
X.append(a)
Y.append(b)
Y.append(c)
m+=2
H.append((inf,(-inf,inf)))
H.append((-inf,(-inf,inf)))
X.sort()
xdc={}
c=1
for j in sorted(set(X)):
xdc[c]=j
c+=1
nx=c-1
Y.sort()
ydc={}
c=1
for j in sorted(set(Y)):
ydc[c]=j
c+=1
ny=c-1
xdcr=dict(zip(xdc.values(),xdc.keys()))
ydcr=dict(zip(ydc.values(),ydc.keys()))
mpy=[[0]*(nx+1+1) for i in range(ny+1+1)]
mpx=[[0]*(nx+1+1) for i in range(ny+1+1)]
for (a,b),c in V:
mpx[ydcr[c]][xdcr[a]]+=1
mpx[ydcr[c]][xdcr[b]]+=-1
for i in range(ny+1):
for j in range(nx):
mpx[i][j+1]+=mpx[i][j]
for d,(e,f) in H:
mpy[ydcr[e]][xdcr[d]]+=1
mpy[ydcr[f]][xdcr[d]]+=-1
for j in range(nx+1):
for i in range(ny):
mpy[i+1][j]+=mpy[i][j]
v=[[0]*(nx+1) for i in range(ny+1)]
q=deque()
q.append((xdcr[0],ydcr[0]))
v[ydcr[0]][xdcr[0]]=1
while q:
cx,cy=q.popleft()
ans+=(xdc[cx]-xdc[cx+1])*(ydc[cy]-ydc[cy+1])
for dx,dy in FourNb:
nbx=cx+dx
nby=cy+dy
if (not 0<=nbx<nx) or (not 0<=nby<ny) or v[nby][nbx]==1:
continue
if dy!=0:
if mpx[cy+(dy+1)//2][cx]==0:
q.append((nbx,nby))
v[nby][nbx]=1
else:
if mpy[cy][cx+(dx+1)//2]==0:
q.append((nbx,nby))
v[nby][nbx]=1
if ans>=inf:
ans='INF'
print(ans)
```
Yes
| 105,054 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead.
Constraints
* All values in input are integers between -10^9 and 10^9 (inclusive).
* 1 \leq N, M \leq 1000
* A_i < B_i\ (1 \leq i \leq N)
* E_j < F_j\ (1 \leq j \leq M)
* The point (0, 0) does not lie on any of the given segments.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M
Output
If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.)
Examples
Input
5 6
1 2 0
0 1 1
0 2 2
-3 4 -1
-2 6 3
1 0 1
0 1 2
2 0 2
-1 -4 5
3 -2 4
1 2 4
Output
13
Input
6 1
-3 -1 -2
-3 -1 1
-2 -1 2
1 4 -2
1 4 -1
1 4 1
3 1 4
Output
INF
Submitted Solution:
```
from collections import deque
import bisect
INF = float("inf")
N,M = map(int,input().split())
xtic = {0,-INF,INF}
ytic = {0,-INF,INF}
hor = []
for _ in range(N):
a,b,c = map(int,input().split())
hor.append((c,a,b))
xtic.add(a)
xtic.add(b)
ytic.add(c)
ver = []
for _ in range(M):
d,e,f = map(int,input().split())
ver.append((d,e,f))
xtic.add(d)
ytic.add(e)
ytic.add(f)
xtic = list(xtic)
ytic = list(ytic)
xtic.sort()
ytic.sort()
xdic = {xtic[i]:i+1 for i in range(len(xtic))}
ydic = {ytic[i]:i+1 for i in range(len(ytic))}
gyaku_xdic = {xdic[k]:k for k in xdic}
gyaku_ydic = {ydic[k]:k for k in ydic}
hor.sort()
ver.sort()
hor_dic = {}
ver_dic = {}
now = None
for c,a,b in hor:
c,a,b = ydic[c],xdic[a],xdic[b]
if c != now:
hor_dic[c] = (1<<b) - (1<<a)
else:
hor_dic[c] |= (1<<b) - (1<<a)
now = c
now = None
for d,e,f in ver:
d,e,f = xdic[d],ydic[e],ydic[f]
if d != now:
ver_dic[d] = (1<<f) - (1<<e)
else:
ver_dic[d] |= (1<<f) - (1<<e)
now = d
def is_connected(x,y,dx,dy):
if dx == 0:
if dy > 0:
if hor_wall[y+1][H-1-x]:
return False
return True
else:
if hor_wall[y][H-1-x]:
return False
return True
else:
if dx > 0:
if ver_wall[x+1][W-1-y]:
return False
return True
else:
if ver_wall[x][W-1-y]:
return False
return True
def calc_area(x,y):
X = gyaku_xdic[x+1] - gyaku_xdic[x]
Y = gyaku_ydic[y+1] - gyaku_ydic[y]
return X*Y
offset = [(1,0),(0,1),(-1,0),(0,-1)]
x0 = bisect.bisect(xtic,0)
y0 = bisect.bisect(ytic,0)
W,H = len(xtic)+1 ,len(ytic)+1
gyaku_xdic[0] = -INF
gyaku_ydic[0] = -INF
gyaku_xdic[W] = INF
gyaku_ydic[H] = INF
hor_wall = [0] + [0 for i in range(1,H)]
ver_wall = [0] + [0 for i in range(1,W)]
for k in hor_dic:
hor_wall[k] = hor_dic[k]
for k in ver_dic:
ver_wall[k] = ver_dic[k]
for k in range(len(hor_wall)):
listb = list(map(int,list(bin(hor_wall[k])[2:])))
hor_wall[k] = [0 for j in range(H-len(listb))] + listb
for k in range(len(ver_wall)):
listb = list(map(int,list(bin(ver_wall[k])[2:])))
ver_wall[k] = [0 for j in range(W-len(listb))] + listb
d = [[0 for i in range(W)] for j in range(H)]
d[y0][x0] = 1
q = deque([(x0,y0)])
area = 0
while q:
x,y = q.pop()
area += calc_area(x,y)
for dx,dy in offset:
nx,ny = x+dx,y+dy
if 0<=nx<W and 0<=ny<H:
if is_connected(x,y,dx,dy):
if nx == 0 or ny == 0 or nx == W-1 or ny == H-1:
print("INF")
exit()
if d[ny][nx] == 0:
d[ny][nx] = 1
q.append((nx,ny))
else:
print(area)
```
No
| 105,055 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead.
Constraints
* All values in input are integers between -10^9 and 10^9 (inclusive).
* 1 \leq N, M \leq 1000
* A_i < B_i\ (1 \leq i \leq N)
* E_j < F_j\ (1 \leq j \leq M)
* The point (0, 0) does not lie on any of the given segments.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M
Output
If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.)
Examples
Input
5 6
1 2 0
0 1 1
0 2 2
-3 4 -1
-2 6 3
1 0 1
0 1 2
2 0 2
-1 -4 5
3 -2 4
1 2 4
Output
13
Input
6 1
-3 -1 -2
-3 -1 1
-2 -1 2
1 4 -2
1 4 -1
1 4 1
3 1 4
Output
INF
Submitted Solution:
```
#!/usr/bin/env python3
from collections import defaultdict
from heapq import heappush, heappop
import sys
import bisect
sys.setrecursionlimit(10**6)
input = sys.stdin.buffer.readline
# INF = sys.maxsize
INF = 10 ** 10
# INF = float("inf")
def dp(*x): # debugprint
print(*x)
# f = open(sys.argv[1])
# input = f.buffer.readline
N, M = map(int, input().split())
vlines = defaultdict(list)
hlines = defaultdict(list)
vticks = {0}
hticks = {0}
for i in range(N):
A, B, C = map(int, input().split())
vlines[C].append((A, B))
hticks.add(C)
vticks.update((A, B))
for i in range(M):
D, E, F = map(int, input().split())
hlines[D].append((E, F))
vticks.add(D)
hticks.update((E, F))
vticks = [-INF] + list(sorted(vticks)) + [INF]
hticks = [-INF] + list(sorted(hticks)) + [INF]
def up(y):
return vticks[bisect.bisect_left(vticks, y) - 1]
def down(y):
return vticks[bisect.bisect_left(vticks, y) + 1]
def left(x):
return hticks[bisect.bisect_left(hticks, x) - 1]
def right(x):
return hticks[bisect.bisect_left(hticks, x) + 1]
def area(i, j):
width = hticks[i + 1] - hticks[i]
height = vticks[j + 1] - vticks[j]
return width * height
total_area = 0
visited = set()
def visit(i, j):
global total_area
if (i, j) in visited:
return
# dp("visit: (i,j)", (i, j))
x = hticks[i]
y = vticks[j]
a = area(i, j)
total_area += a
visited.add((i, j))
# visit neighbors
l = i - 1
if (l, j) not in visited:
for a, b in vlines[x]:
if a <= y < b:
# blocked
break
else:
# can move left
to_visit.append((l, j))
u = j - 1
if (i, u) not in visited:
for a, b in hlines[y]:
if a <= x < b:
# blocked
break
else:
# can move up
to_visit.append((i, u))
r = i + 1
if (r, j) not in visited:
for a, b in vlines[hticks[r]]:
if a <= y < b:
# blocked
break
else:
# can move left
to_visit.append((r, j))
d = j + 1
if (i, d) not in visited:
for a, b in hlines[vticks[d]]:
if a <= x < b:
# blocked
break
else:
# can move up
to_visit.append((i, d))
maxH = len(hticks) - 2
maxV = len(vticks) - 2
# dp(": maxH, maxV", maxH, maxV)
i = bisect.bisect_left(hticks, 0)
j = bisect.bisect_left(vticks, 0)
to_visit = [(i, j)]
while to_visit:
i, j = to_visit.pop()
# dp(": (i,j)", (i, j))
if i == 0 or i == maxH or j == 0 or j == maxV:
print("INF")
break
visit(i, j)
# dp(": to_visit", to_visit)
else:
print(total_area)
def _test():
import doctest
doctest.testmod()
```
No
| 105,056 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead.
Constraints
* All values in input are integers between -10^9 and 10^9 (inclusive).
* 1 \leq N, M \leq 1000
* A_i < B_i\ (1 \leq i \leq N)
* E_j < F_j\ (1 \leq j \leq M)
* The point (0, 0) does not lie on any of the given segments.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M
Output
If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.)
Examples
Input
5 6
1 2 0
0 1 1
0 2 2
-3 4 -1
-2 6 3
1 0 1
0 1 2
2 0 2
-1 -4 5
3 -2 4
1 2 4
Output
13
Input
6 1
-3 -1 -2
-3 -1 1
-2 -1 2
1 4 -2
1 4 -1
1 4 1
3 1 4
Output
INF
Submitted Solution:
```
#!usr/bin/env python3
import sys
import bisect
from collections import deque
import numpy as np
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LIR(n):
return np.array([LI() for i in range(n)])
def solve():
n,m = LI()
p = LIR(n)
q = LIR(m)
M = 10**11
M2 = M**2
fx = [-M,0,M]
fy = [-M,0,M]
for i in range(n):
p[i] *= 10
a,b,c = p[i]
fy.append(a)
fy.append(b)
fy.append(b+1)
fx.append(c)
fx.append(c+1)
for i in range(m):
q[i] *= 10
d,e,f = q[i]
fy.append(d)
fy.append(d+1)
fx.append(e)
fx.append(f)
fx.append(f+1)
fy = list(set(fy))
fx = list(set(fx))
fy.sort()
fx.sort()
h = len(fy)+1
w = len(fx)+1
s = np.zeros((h,w))
for a,b,c in p:
ai = bisect.bisect_left(fy,a)
bi = bisect.bisect_left(fy,b)+1
ci = bisect.bisect_left(fx,c)
s[ai][ci] += 1
s[bi][ci] -= 1
s[ai][ci+1] -= 1
s[bi][ci+1] += 1
for d,e,f in q:
di = bisect.bisect_left(fy,d)
ei = bisect.bisect_left(fx,e)
fi = bisect.bisect_left(fx,f)+1
kd = di*w
kdd = kd+w
s[di][ei] += 1
s[di][fi] -= 1
s[di+1][ei] -= 1
s[di+1][fi] += 1
for j in range(len(fx)):
s[:,j+1] += s[:,j]
for i in range(len(fy)):
s[i+1] += s[i]
d = [(1,0),(-1,0),(0,1),(0,-1)]
sx = bisect.bisect_left(fx,0)
sy = bisect.bisect_left(fy,0)
nh,nw = len(fy)-1,len(fx)-1
fx[1] //= 10
fy[1] //= 10
for i in range(1,nw-1):
fx[i+1] = fx[i+1]//10
fx[i] = fx[i+1]-fx[i]
for i in range(1,nh-1):
fy[i+1] = fy[i+1]//10
fy[i] = fy[i+1]-fy[i]
fx[0] = -fx[0]
fy[0] = -fy[0]
ans = fx[sx]*fy[sy]
q = deque()
q.append((sy,sx))
f = [1]*nh*nw
f[sy*nw+sx] = 0
while q:
y,x = q.popleft()
for dy,dx in d:
ny,nx = y+dy,x+dx
if 0 <= ny < nh and 0 <= nx < nw:
ind = ny*nw+nx
if f[ind] and not s[ny][nx]:
k = fx[nx]*fy[ny]
if k >= M2:
print("INF")
return
ans += k
f[ind] = 0
q.append((ny,nx))
print(ans)
return
#Solve
if __name__ == "__main__":
solve()
```
No
| 105,057 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a grass field that stretches infinitely.
In this field, there is a negligibly small cow. Let (x, y) denote the point that is x\ \mathrm{cm} south and y\ \mathrm{cm} east of the point where the cow stands now. The cow itself is standing at (0, 0).
There are also N north-south lines and M east-west lines drawn on the field. The i-th north-south line is the segment connecting the points (A_i, C_i) and (B_i, C_i), and the j-th east-west line is the segment connecting the points (D_j, E_j) and (D_j, F_j).
What is the area of the region the cow can reach when it can move around as long as it does not cross the segments (including the endpoints)? If this area is infinite, print `INF` instead.
Constraints
* All values in input are integers between -10^9 and 10^9 (inclusive).
* 1 \leq N, M \leq 1000
* A_i < B_i\ (1 \leq i \leq N)
* E_j < F_j\ (1 \leq j \leq M)
* The point (0, 0) does not lie on any of the given segments.
Input
Input is given from Standard Input in the following format:
N M
A_1 B_1 C_1
:
A_N B_N C_N
D_1 E_1 F_1
:
D_M E_M F_M
Output
If the area of the region the cow can reach is infinite, print `INF`; otherwise, print an integer representing the area in \mathrm{cm^2}.
(Under the constraints, it can be proved that the area of the region is always an integer if it is not infinite.)
Examples
Input
5 6
1 2 0
0 1 1
0 2 2
-3 4 -1
-2 6 3
1 0 1
0 1 2
2 0 2
-1 -4 5
3 -2 4
1 2 4
Output
13
Input
6 1
-3 -1 -2
-3 -1 1
-2 -1 2
1 4 -2
1 4 -1
1 4 1
3 1 4
Output
INF
Submitted Solution:
```
n,m,*l = map(int, open(0).read().split())
l=iter(l)
l=list(zip(l,l,l))
l1=l[:n]
l2=l[-m:]
V=set([float('inf'),-float('inf')])
H=set([float('inf'),-float('inf')])
for a,b,c in l1:
V.add(c)
H.add(a)
H.add(b)
for c,a,b in l2:
H.add(c)
V.add(a)
V.add(b)
V=sorted(list(V))
H=sorted(list(H))
Vdic={}
Hdic={}
for i,v in enumerate(V):
Vdic[v]=i
for i,h in enumerate(H):
Hdic[h]=i
checkv=[[0]*3001 for i in range(3001)]
checkh=[[0]*3001 for i in range(3001)]
check=[[0]*3001 for i in range(3001)]
for a,b,c in l1:
c=Vdic[c]
for i in range(Hdic[a],Hdic[b]):
checkh[c][i]=1
for c,a,b in l2:
c=Hdic[c]
for i in range(Vdic[a],Vdic[b]):
checkv[i][c]=1
from bisect import bisect_left
pv=bisect_left(V,0)-1
ph=bisect_left(V,0)-1
ans=0
stack=[(pv,ph)]
check[pv][ph]=1
while stack:
v,h=stack.pop()
ans+=(V[v+1]-V[v])*(H[h+1]-H[h])
if h!=0 and checkv[v][h]==0 and check[v][h-1]==0:
stack.append((v,h-1))
check[v][h-1]=1
if h!=len(H)-2 and checkv[v][h+1]==0 and check[v][h+1]==0:
stack.append((v,h+1))
check[v][h+1]=1
if v!=0 and checkh[v][h]==0 and check[v-1][h]==0:
stack.append((v-1,h))
check[v-1][h]=1
if v!=len(V)-2 and checkh[v+1][h]==0 and check[v+1][h]==0:
stack.append((v+1,h))
check[v+1][h]=1
print(ans)
```
No
| 105,058 |
Provide a correct Python 3 solution for this coding contest problem.
There are N children, numbered 1,2,\ldots,N. In the next K days, we will give them some cookies. In the i-th day, we will choose a_i children among the N with equal probability, and give one cookie to each child chosen. (We make these K choices independently.)
Let us define the happiness of the children as c_1 \times c_2 \times \ldots \times c_N, where c_i is the number of cookies received by Child i in the K days. Find the expected happiness multiplied by \binom{N}{a_1} \times \binom{N}{a_2} \times \ldots \times \binom{N}{a_K} (we can show that this value is an integer), modulo (10^{9}+7).
Constraints
* 1 \leq N \leq 1000
* 1 \leq K \leq 20
* 1 \leq a_i \leq N
Input
Input is given from Standard Input in the following format:
N K
a_1 a_2 \ldots a_K
Output
Print the answer.
Examples
Input
3 2
3 2
Output
12
Input
856 16
399 263 665 432 206 61 784 548 422 313 848 478 827 26 398 63
Output
337587117
"Correct Solution:
```
MOD = 10**9 + 7
list_size = 1001
f_list = [1] * list_size
f_r_list = [1] * list_size
for i in range(list_size-1):
f_list[i+1] = (f_list[i] * (i+1)) % MOD
f_r_list[-1] = pow(f_list[-1], MOD - 2, MOD)
for i in range(list_size-2, -1, -1):
f_r_list[i] = (f_r_list[i+1] * (i+1)) % MOD
def comb(n, r):
if n < r or r < 0:
return 0
elif n == 0 or r == 0 or n == r:
return 1
else:
return (f_list[n] * f_r_list[n-r] * f_r_list[r]) % MOD
n, k = map(int, input().split())
a = list(map(int, input().split()))
dp = [[0 for _ in range(n+1)] for _ in range(k+1)]
dp[0][0] = f_list[n]
for i in range(1, k+1):
for j in range(n+1):
for x in range(j+1):
dp[i][j] += dp[i-1][j-x] * comb(n-x, a[i-1]-x) * f_r_list[x]
dp[i][j] %= MOD
print(dp[k][n])
```
| 105,059 |
Provide a correct Python 3 solution for this coding contest problem.
There are N children, numbered 1,2,\ldots,N. In the next K days, we will give them some cookies. In the i-th day, we will choose a_i children among the N with equal probability, and give one cookie to each child chosen. (We make these K choices independently.)
Let us define the happiness of the children as c_1 \times c_2 \times \ldots \times c_N, where c_i is the number of cookies received by Child i in the K days. Find the expected happiness multiplied by \binom{N}{a_1} \times \binom{N}{a_2} \times \ldots \times \binom{N}{a_K} (we can show that this value is an integer), modulo (10^{9}+7).
Constraints
* 1 \leq N \leq 1000
* 1 \leq K \leq 20
* 1 \leq a_i \leq N
Input
Input is given from Standard Input in the following format:
N K
a_1 a_2 \ldots a_K
Output
Print the answer.
Examples
Input
3 2
3 2
Output
12
Input
856 16
399 263 665 432 206 61 784 548 422 313 848 478 827 26 398 63
Output
337587117
"Correct Solution:
```
import sys
readline = sys.stdin.readline
MOD = 10**9+7
def frac(limit):
frac = [1]*limit
for i in range(2,limit):
frac[i] = i * frac[i-1]%MOD
fraci = [None]*limit
fraci[-1] = pow(frac[-1], MOD -2, MOD)
for i in range(-2, -limit-1, -1):
fraci[i] = fraci[i+1] * (limit + i + 1) % MOD
return frac, fraci
frac, fraci = frac(1398)
def comb(a, b):
if not a >= b >= 0:
return 0
return frac[a]*fraci[b]*fraci[a-b]%MOD
N, K = map(int, readline().split())
A = list(map(int, readline().split()))
dp = [0]*(N+1)
dp[0] = 1
for i in range(K):
a = A[i]
dp2 = [0]*(N+1)
for j in range(N+1):
d = dp[j]
if not d:
continue
for k in range(min(a, N-j)+1):
dp2[j+k] = (dp2[j+k] + d*comb(N-j, k)*comb(N-k, a-k)) %MOD
dp = dp2[:]
print(dp[N])
```
| 105,060 |
Provide a correct Python 3 solution for this coding contest problem.
There are N children, numbered 1,2,\ldots,N. In the next K days, we will give them some cookies. In the i-th day, we will choose a_i children among the N with equal probability, and give one cookie to each child chosen. (We make these K choices independently.)
Let us define the happiness of the children as c_1 \times c_2 \times \ldots \times c_N, where c_i is the number of cookies received by Child i in the K days. Find the expected happiness multiplied by \binom{N}{a_1} \times \binom{N}{a_2} \times \ldots \times \binom{N}{a_K} (we can show that this value is an integer), modulo (10^{9}+7).
Constraints
* 1 \leq N \leq 1000
* 1 \leq K \leq 20
* 1 \leq a_i \leq N
Input
Input is given from Standard Input in the following format:
N K
a_1 a_2 \ldots a_K
Output
Print the answer.
Examples
Input
3 2
3 2
Output
12
Input
856 16
399 263 665 432 206 61 784 548 422 313 848 478 827 26 398 63
Output
337587117
"Correct Solution:
```
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
from pprint import pprint
from copy import deepcopy
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from pprint import pprint
sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007
n, k = LI()
fac = [1] * (n + 1)
inv = [1] * (n + 1)
for j in range(1, n + 1):
fac[j] = fac[j-1] * j % mod
inv[n] = pow(fac[n], mod-2, mod)
for j in range(n-1, -1, -1):
inv[j] = inv[j+1] * (j+1) % mod
def comb(n, r):
if r > n or n < 0 or r < 0:
return 0
return fac[n] * inv[n - r] * inv[r] % mod
A = LI()
dp = [[0] * (n + 1) for _ in range(k + 1)]
dp[0][0] = 1
for i in range(k):
for j in range(n + 1):
for l in range(min(n - j, A[i]) + 1):
dp[i + 1][j + l] = (dp[i + 1][j + l] + dp[i][j] * comb(n - j, l) % mod
* comb(n - l, A[i] - l)) % mod
print(dp[k][n])
```
| 105,061 |
Provide a correct Python 3 solution for this coding contest problem.
There are N children, numbered 1,2,\ldots,N. In the next K days, we will give them some cookies. In the i-th day, we will choose a_i children among the N with equal probability, and give one cookie to each child chosen. (We make these K choices independently.)
Let us define the happiness of the children as c_1 \times c_2 \times \ldots \times c_N, where c_i is the number of cookies received by Child i in the K days. Find the expected happiness multiplied by \binom{N}{a_1} \times \binom{N}{a_2} \times \ldots \times \binom{N}{a_K} (we can show that this value is an integer), modulo (10^{9}+7).
Constraints
* 1 \leq N \leq 1000
* 1 \leq K \leq 20
* 1 \leq a_i \leq N
Input
Input is given from Standard Input in the following format:
N K
a_1 a_2 \ldots a_K
Output
Print the answer.
Examples
Input
3 2
3 2
Output
12
Input
856 16
399 263 665 432 206 61 784 548 422 313 848 478 827 26 398 63
Output
337587117
"Correct Solution:
```
SIZE=1001; MOD=10**9+7 #998244353 #ここを変更する
SIZE += 1
inv = [0]*SIZE # inv[j] = j^{-1} mod MOD
fac = [0]*SIZE # fac[j] = j! mod MOD
finv = [0]*SIZE # finv[j] = (j!)^{-1} mod MOD
inv[1] = 1
fac[0] = fac[1] = 1
finv[0] = finv[1] = 1
for i in range(2,SIZE):
inv[i] = MOD - (MOD//i)*inv[MOD%i]%MOD
fac[i] = fac[i-1]*i%MOD
finv[i]= finv[i-1]*inv[i]%MOD
def choose(n,r): # nCk mod MOD の計算
if 0 <= r <= n:
return (fac[n]*finv[r]%MOD)*finv[n-r]%MOD
else:
return 0
# coding: utf-8
# Your code here!
import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
read = sys.stdin.read
n,k = [int(i) for i in readline().split()]
a = [int(i) for i in readline().split()]
def product(p,q):
res = [0]*(n+1)
for i in range(n+1):
for j in range(n-i+1):
res[i+j] += p[i]*q[j]
res[i+j] %= MOD
return res
ans = [1]+[0]*n
for ai in a:
q = [0]*(n+1)
for j in range(n+1):
q[j] = choose(n-j,n-ai)*finv[j]%MOD
ans = product(ans,q)
res = ans[n]
for i in range(1,n+1):
res *= i
res %= MOD
print(res)
```
| 105,062 |
Provide a correct Python 3 solution for this coding contest problem.
There are N children, numbered 1,2,\ldots,N. In the next K days, we will give them some cookies. In the i-th day, we will choose a_i children among the N with equal probability, and give one cookie to each child chosen. (We make these K choices independently.)
Let us define the happiness of the children as c_1 \times c_2 \times \ldots \times c_N, where c_i is the number of cookies received by Child i in the K days. Find the expected happiness multiplied by \binom{N}{a_1} \times \binom{N}{a_2} \times \ldots \times \binom{N}{a_K} (we can show that this value is an integer), modulo (10^{9}+7).
Constraints
* 1 \leq N \leq 1000
* 1 \leq K \leq 20
* 1 \leq a_i \leq N
Input
Input is given from Standard Input in the following format:
N K
a_1 a_2 \ldots a_K
Output
Print the answer.
Examples
Input
3 2
3 2
Output
12
Input
856 16
399 263 665 432 206 61 784 548 422 313 848 478 827 26 398 63
Output
337587117
"Correct Solution:
```
N,K = map(int,input().split())
A = list(map(int,input().split()))
s = sum(A)
if s < N:
print(0)
exit()
MOD = 10**9+7
MAXN = N+5
fac = [1,1] + [0]*MAXN
finv = [1,1] + [0]*MAXN
inv = [0,1] + [0]*MAXN
for i in range(2,MAXN+2):
fac[i] = fac[i-1] * i % MOD
inv[i] = -inv[MOD%i] * (MOD // i) % MOD
finv[i] = finv[i-1] * inv[i] % MOD
def ncr(n,r):
if n < r: return 0
if n < 0 or r < 0: return 0
return fac[n] * (finv[r] * finv[n-r] % MOD) % MOD
dp = [[0]*(N+1) for i in range(K+1)]
dp[0][0] = 1
for i,a in enumerate(A):
for j in range(N+1):
for k in range(j,N+1):
if k-j > a: break
dp[i+1][k] += dp[i][j] * ncr(N-j, k-j) * ncr(N-(k-j), a-(k-j))
dp[i+1][k] %= MOD
print(dp[-1][-1])
```
| 105,063 |
Provide a correct Python 3 solution for this coding contest problem.
There are N children, numbered 1,2,\ldots,N. In the next K days, we will give them some cookies. In the i-th day, we will choose a_i children among the N with equal probability, and give one cookie to each child chosen. (We make these K choices independently.)
Let us define the happiness of the children as c_1 \times c_2 \times \ldots \times c_N, where c_i is the number of cookies received by Child i in the K days. Find the expected happiness multiplied by \binom{N}{a_1} \times \binom{N}{a_2} \times \ldots \times \binom{N}{a_K} (we can show that this value is an integer), modulo (10^{9}+7).
Constraints
* 1 \leq N \leq 1000
* 1 \leq K \leq 20
* 1 \leq a_i \leq N
Input
Input is given from Standard Input in the following format:
N K
a_1 a_2 \ldots a_K
Output
Print the answer.
Examples
Input
3 2
3 2
Output
12
Input
856 16
399 263 665 432 206 61 784 548 422 313 848 478 827 26 398 63
Output
337587117
"Correct Solution:
```
P = 10**9+7
fa = [1]
for i in range(1, 1010): fa.append(fa[-1] * i % P)
fainv = [pow(fa[-1], P-2, P)]
for i in range(1, 1010)[::-1]: fainv.append(fainv[-1] * i % P)
fainv = fainv[::-1]
k = 70
kk = 1<<k
nu = lambda L: int("".join([bin(kk+a)[-k:] for a in L[::-1]]), 2)
st = lambda n: bin(n)[2:] + "0"
li = lambda s: [int(a, 2) % P if len(a) else 0 for a in [s[-(i+1)*k-1:-i*k-1] for i in range(N+1)]]
N, K = map(int, input().split())
A = [int(a) for a in input().split()]
X = [fa[N]] + [0] * N
for a in A:
X = li(st(nu(X) * nu([fainv[i] * fa[N-i] * fainv[a-i] * fainv[N-a] % P if i <= a else 0 for i in range(N+1)])))
print(X[-1])
```
| 105,064 |
Provide a correct Python 3 solution for this coding contest problem.
There are N children, numbered 1,2,\ldots,N. In the next K days, we will give them some cookies. In the i-th day, we will choose a_i children among the N with equal probability, and give one cookie to each child chosen. (We make these K choices independently.)
Let us define the happiness of the children as c_1 \times c_2 \times \ldots \times c_N, where c_i is the number of cookies received by Child i in the K days. Find the expected happiness multiplied by \binom{N}{a_1} \times \binom{N}{a_2} \times \ldots \times \binom{N}{a_K} (we can show that this value is an integer), modulo (10^{9}+7).
Constraints
* 1 \leq N \leq 1000
* 1 \leq K \leq 20
* 1 \leq a_i \leq N
Input
Input is given from Standard Input in the following format:
N K
a_1 a_2 \ldots a_K
Output
Print the answer.
Examples
Input
3 2
3 2
Output
12
Input
856 16
399 263 665 432 206 61 784 548 422 313 848 478 827 26 398 63
Output
337587117
"Correct Solution:
```
# http://drken1215.hatenablog.com/entry/2020/01/12/011700
# 本質的な速度改善の方法は分からない
# dpを二次元配列にするとTLEするので、
# 配列2本で処理した
# 修正点:
# [1]
# enumerate(a) -> a
# 不要なenumerateを消した
# [2]
# counted in range(n + 1) -> enumerate(dp)
# enumerateの方がわずかに速いはず
# [3]
# cmbのif文を消した
def main():
MOD = 10 ** 9 + 7
N, K = map(int, input().split())
*a, = map(int, input().split())
# -+-+-+-prepare combination-+-+-+-
# -+-+-+-START-+-+-+-
fact = [0] * (N + 1)
fact[0] = 1
fact[1] = 1
for x in range(2, N + 1):
fact[x] = x * fact[x - 1] % MOD
invs = [1] * (N + 1)
invs[N] = pow(fact[N], MOD - 2, MOD)
for x in range(N - 1, 0, -1):
invs[x] = invs[x + 1] * (x + 1) % MOD
def cmb(n, r):
return (((invs[r] * invs[n - r]) % MOD) * fact[n]) % MOD
# -+-+-+-END-+-+-+-
dp = [0] * (N + 1)
dp[0] = 1
for ai in a:
ndp = [0] * (N + 1)
for counted, dp_counted in enumerate(dp):
for to_count in range(min(N - counted, ai) + 1):
ndp[counted + to_count] = (
ndp[counted + to_count]
+ dp_counted
* cmb(N - counted, to_count)
* cmb(N - to_count, ai - to_count)
) % MOD
dp = ndp
print(dp[N])
if __name__ == '__main__':
main()
```
| 105,065 |
Provide a correct Python 3 solution for this coding contest problem.
There are N children, numbered 1,2,\ldots,N. In the next K days, we will give them some cookies. In the i-th day, we will choose a_i children among the N with equal probability, and give one cookie to each child chosen. (We make these K choices independently.)
Let us define the happiness of the children as c_1 \times c_2 \times \ldots \times c_N, where c_i is the number of cookies received by Child i in the K days. Find the expected happiness multiplied by \binom{N}{a_1} \times \binom{N}{a_2} \times \ldots \times \binom{N}{a_K} (we can show that this value is an integer), modulo (10^{9}+7).
Constraints
* 1 \leq N \leq 1000
* 1 \leq K \leq 20
* 1 \leq a_i \leq N
Input
Input is given from Standard Input in the following format:
N K
a_1 a_2 \ldots a_K
Output
Print the answer.
Examples
Input
3 2
3 2
Output
12
Input
856 16
399 263 665 432 206 61 784 548 422 313 848 478 827 26 398 63
Output
337587117
"Correct Solution:
```
M=10**9+7;n,k,*A=map(int,open(0).read().split());C=[[0]*(n+1)for _ in"_"*(n+1)]
for i in range(n+1):
for j in range(i+1):C[i][j]=(1,C[i-1][j-1]+C[i-1][j])[j!=0]%M
F=[[0]*(n+1)for _ in"_"*(k+1)];F[0][0]=1
for i in range(k):
for j in range(n+1):
for m in range(j+1):F[i+1][j]+=C[j][m]*F[i][m]*C[n-j+m][A[i]-j+m]
print(F[k][n]%M)
```
| 105,066 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N children, numbered 1,2,\ldots,N. In the next K days, we will give them some cookies. In the i-th day, we will choose a_i children among the N with equal probability, and give one cookie to each child chosen. (We make these K choices independently.)
Let us define the happiness of the children as c_1 \times c_2 \times \ldots \times c_N, where c_i is the number of cookies received by Child i in the K days. Find the expected happiness multiplied by \binom{N}{a_1} \times \binom{N}{a_2} \times \ldots \times \binom{N}{a_K} (we can show that this value is an integer), modulo (10^{9}+7).
Constraints
* 1 \leq N \leq 1000
* 1 \leq K \leq 20
* 1 \leq a_i \leq N
Input
Input is given from Standard Input in the following format:
N K
a_1 a_2 \ldots a_K
Output
Print the answer.
Examples
Input
3 2
3 2
Output
12
Input
856 16
399 263 665 432 206 61 784 548 422 313 848 478 827 26 398 63
Output
337587117
Submitted Solution:
```
nnnnn = 1010
P = 10 ** 9 + 7
fa = [1]
for i in range(1, nnnnn):
fa.append(fa[-1] * i % P)
fainv = [pow(fa[-1], P-2, P)]
for i in range(1, nnnnn)[::-1]:
fainv.append(fainv[-1] * i % P)
fainv = fainv[::-1]
N, K = map(int, input().split())
A = [int(a) for a in input().split()]
def calc(k):
return [fainv[i] * fa[N-i] * fainv[k-i] * fainv[N-k] % P if i <= k else 0 for i in range(N+1)]
def conv(a, b):
L = [0] * (N+1)
for i in range(N+1):
for j in range(N+1):
if i+j <= N: L[i+j] += a[i] * b[j]
return [l % P for l in L]
X = [1] + [0] * N
for a in A:
X = conv(X, calc(a))
print(X[-1] * fa[N] % P)
```
Yes
| 105,067 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N children, numbered 1,2,\ldots,N. In the next K days, we will give them some cookies. In the i-th day, we will choose a_i children among the N with equal probability, and give one cookie to each child chosen. (We make these K choices independently.)
Let us define the happiness of the children as c_1 \times c_2 \times \ldots \times c_N, where c_i is the number of cookies received by Child i in the K days. Find the expected happiness multiplied by \binom{N}{a_1} \times \binom{N}{a_2} \times \ldots \times \binom{N}{a_K} (we can show that this value is an integer), modulo (10^{9}+7).
Constraints
* 1 \leq N \leq 1000
* 1 \leq K \leq 20
* 1 \leq a_i \leq N
Input
Input is given from Standard Input in the following format:
N K
a_1 a_2 \ldots a_K
Output
Print the answer.
Examples
Input
3 2
3 2
Output
12
Input
856 16
399 263 665 432 206 61 784 548 422 313 848 478 827 26 398 63
Output
337587117
Submitted Solution:
```
def inv(a):
m=10**9+7
b=m
(x, lastx) = (0, 1)
(y, lasty) = (1, 0)
while b != 0:
q = a // b
(a, b) = (b, a % b)
(x, lastx) = (lastx - q * x, x)
(y, lasty) = (lasty - q * y, y)
return lastx % m
def main():
MOD=10**9+7
n,k=map(int,input().split())
a=list(map(int,input().split()))
frac=[1]
for i in range(1,n+1):
frac.append(frac[-1]*i%MOD)
fracinv=[inv(frac[i]) for i in range(n+1)]
dp=[[0]*(n+1) for _ in range(k)]
for x in range(a[0]+1):
dp[0][x]=frac[n]*frac[n-x]*fracinv[a[0]-x]%MOD*fracinv[n-a[0]]*fracinv[x]%MOD
for i in range(k-1):
ai=a[i+1]
for j in range(n+1):
for x in range(ai+1):
p=j+x
if p>n: break
tmp=dp[i][j]*frac[n-x]%MOD*fracinv[ai-x]*fracinv[n-ai]%MOD*fracinv[x]
dp[i+1][p]=(dp[i+1][p]+tmp)%MOD
print(dp[k-1][n])
if __name__ == "__main__":
main()
```
Yes
| 105,068 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N children, numbered 1,2,\ldots,N. In the next K days, we will give them some cookies. In the i-th day, we will choose a_i children among the N with equal probability, and give one cookie to each child chosen. (We make these K choices independently.)
Let us define the happiness of the children as c_1 \times c_2 \times \ldots \times c_N, where c_i is the number of cookies received by Child i in the K days. Find the expected happiness multiplied by \binom{N}{a_1} \times \binom{N}{a_2} \times \ldots \times \binom{N}{a_K} (we can show that this value is an integer), modulo (10^{9}+7).
Constraints
* 1 \leq N \leq 1000
* 1 \leq K \leq 20
* 1 \leq a_i \leq N
Input
Input is given from Standard Input in the following format:
N K
a_1 a_2 \ldots a_K
Output
Print the answer.
Examples
Input
3 2
3 2
Output
12
Input
856 16
399 263 665 432 206 61 784 548 422 313 848 478 827 26 398 63
Output
337587117
Submitted Solution:
```
import sys
sys.setrecursionlimit(10 ** 6)
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def main():
def com(com_n, com_r):
return fac[com_n] * inv[com_r] * inv[com_n - com_r] % md
n, k = MI()
aa = LI()
# combinationの準備
md = 10 ** 9 + 7
n_max = n + 3
fac = [1] * (n_max + 1)
inv = [1] * (n_max + 1)
for i in range(2, n_max + 1): fac[i] = fac[i - 1] * i % md
inv[n_max] = pow(fac[n_max], md - 2, md)
for i in range(n_max - 1, 1, -1): inv[i] = inv[i + 1] * (i + 1) % md
dp = [0] * (n + 1)
dp[0] = 1
for a in aa:
for j in range(n, -1, -1):
pre = dp[j]
if pre == 0: continue
dp[j] = 0
for dj in range(a + 1):
nj = j + dj
if nj > n or a - dj < 0 or n - j < dj: break
dp[nj] += pre * com(n - j, dj) * com(n - dj, a - dj)
dp[nj] %= md
# print(dp)
print(dp[n])
main()
```
Yes
| 105,069 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N children, numbered 1,2,\ldots,N. In the next K days, we will give them some cookies. In the i-th day, we will choose a_i children among the N with equal probability, and give one cookie to each child chosen. (We make these K choices independently.)
Let us define the happiness of the children as c_1 \times c_2 \times \ldots \times c_N, where c_i is the number of cookies received by Child i in the K days. Find the expected happiness multiplied by \binom{N}{a_1} \times \binom{N}{a_2} \times \ldots \times \binom{N}{a_K} (we can show that this value is an integer), modulo (10^{9}+7).
Constraints
* 1 \leq N \leq 1000
* 1 \leq K \leq 20
* 1 \leq a_i \leq N
Input
Input is given from Standard Input in the following format:
N K
a_1 a_2 \ldots a_K
Output
Print the answer.
Examples
Input
3 2
3 2
Output
12
Input
856 16
399 263 665 432 206 61 784 548 422 313 848 478 827 26 398 63
Output
337587117
Submitted Solution:
```
import sys
input = sys.stdin.readline
N,K=map(int,input().split())
A=list(map(int,input().split()))
mod=10**9+7
Combi=[[] for i in range(N+1)]
Combi[0]=[1,0]
for i in range(1,N+1):
Combi[i].append(1)
for j in range(i):
Combi[i].append((Combi[i-1][j]+Combi[i-1][j+1])%mod)
Combi[i].append(0)
DP=[0]*(N+1)
DP[0]=1
for k in range(K):
use=A[k]
NDP=[0]*(N+1)
for i in range(N+1):
ANS=0
for j in range(i+1):
if use-(i-j)>=0:
ANS=(ANS+DP[j]*Combi[N-j][i-j]*Combi[N-(i-j)][use-(i-j)])%mod
NDP[i]=ANS
#print(DP)
DP=NDP
print(DP[N])
```
Yes
| 105,070 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N children, numbered 1,2,\ldots,N. In the next K days, we will give them some cookies. In the i-th day, we will choose a_i children among the N with equal probability, and give one cookie to each child chosen. (We make these K choices independently.)
Let us define the happiness of the children as c_1 \times c_2 \times \ldots \times c_N, where c_i is the number of cookies received by Child i in the K days. Find the expected happiness multiplied by \binom{N}{a_1} \times \binom{N}{a_2} \times \ldots \times \binom{N}{a_K} (we can show that this value is an integer), modulo (10^{9}+7).
Constraints
* 1 \leq N \leq 1000
* 1 \leq K \leq 20
* 1 \leq a_i \leq N
Input
Input is given from Standard Input in the following format:
N K
a_1 a_2 \ldots a_K
Output
Print the answer.
Examples
Input
3 2
3 2
Output
12
Input
856 16
399 263 665 432 206 61 784 548 422 313 848 478 827 26 398 63
Output
337587117
Submitted Solution:
```
M=10**9+7;n,k,*A=map(int,open(0).read().split());B=[1];I=[1]*(n+1)
for i in range(1,n+1):B+=[B[-1]*i%M]
for i in range(n+1,0,-1):I[i-1]=pow(B[n],M-2,M)%M if i>n else I[i]*i%M
C=lambda n,k:(B[n]*I[k]*I[n-k],0)[k<0];F=[[0]*(n+1)for _ in"_"*(k+1)];F[0][0]=1
for i in range(k):
for j in range(n+1):
for m in range(j+1):F[i+1][j]+=C(j,m)*F[i][m]*C(n-j+m,A[i]-j+m)%M
print(F[k][n]%M)
```
No
| 105,071 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N children, numbered 1,2,\ldots,N. In the next K days, we will give them some cookies. In the i-th day, we will choose a_i children among the N with equal probability, and give one cookie to each child chosen. (We make these K choices independently.)
Let us define the happiness of the children as c_1 \times c_2 \times \ldots \times c_N, where c_i is the number of cookies received by Child i in the K days. Find the expected happiness multiplied by \binom{N}{a_1} \times \binom{N}{a_2} \times \ldots \times \binom{N}{a_K} (we can show that this value is an integer), modulo (10^{9}+7).
Constraints
* 1 \leq N \leq 1000
* 1 \leq K \leq 20
* 1 \leq a_i \leq N
Input
Input is given from Standard Input in the following format:
N K
a_1 a_2 \ldots a_K
Output
Print the answer.
Examples
Input
3 2
3 2
Output
12
Input
856 16
399 263 665 432 206 61 784 548 422 313 848 478 827 26 398 63
Output
337587117
Submitted Solution:
```
import numpy as np
from math import factorial
D = 10**9+7
N, K = [int(n) for n in input().split()]
C = []
CO = {}
E = []
for i in range(1, N+1):
C.append(i)
CO[i] = 0
a = [int(n) for n in input().split()]
for i in range(K):
R = np.random.choice(C, a[i], replace=False)
E.append(factorial(N)//factorial(a[i]) //factorial(N-a[i]))
for r in R:
CO[r] += 1
h = 1
for v in CO.values():
h *= v
ee = 1
for e in E:
ee *= e
print(h*ee%D)
```
No
| 105,072 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N children, numbered 1,2,\ldots,N. In the next K days, we will give them some cookies. In the i-th day, we will choose a_i children among the N with equal probability, and give one cookie to each child chosen. (We make these K choices independently.)
Let us define the happiness of the children as c_1 \times c_2 \times \ldots \times c_N, where c_i is the number of cookies received by Child i in the K days. Find the expected happiness multiplied by \binom{N}{a_1} \times \binom{N}{a_2} \times \ldots \times \binom{N}{a_K} (we can show that this value is an integer), modulo (10^{9}+7).
Constraints
* 1 \leq N \leq 1000
* 1 \leq K \leq 20
* 1 \leq a_i \leq N
Input
Input is given from Standard Input in the following format:
N K
a_1 a_2 \ldots a_K
Output
Print the answer.
Examples
Input
3 2
3 2
Output
12
Input
856 16
399 263 665 432 206 61 784 548 422 313 848 478 827 26 398 63
Output
337587117
Submitted Solution:
```
n,k = map(int,input().split())
a = tuple(map(int,input().split()))
mod = 10**9+7
rng = 1001
fctr = [1]
finv = [1]
for i in range(1,rng):
fctr.append(fctr[-1]*i%mod)
for i in range(1,rng):
finv.append(pow(fctr[i],mod-2,mod))
def cmb(n,k):
if n<0 or k<0:
return 0
else:
return fctr[n]*finv[n-k]*finv[k]%mod
dp = [[0 for i in range(n+1)] for j in range(k+1)]
dp[0][0] = 1
ans = 0
for i in range(1,k+1):
x = a[i-1]
for j in range(n+1):
for t in range(min(n-j,x)+1):
dp[i][j+t] = (dp[i][j+t]+dp[i-1][j]*cmb(n-j,t)*cmb(n-t,x-t))%mod
print(dp[k][n])
```
No
| 105,073 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N children, numbered 1,2,\ldots,N. In the next K days, we will give them some cookies. In the i-th day, we will choose a_i children among the N with equal probability, and give one cookie to each child chosen. (We make these K choices independently.)
Let us define the happiness of the children as c_1 \times c_2 \times \ldots \times c_N, where c_i is the number of cookies received by Child i in the K days. Find the expected happiness multiplied by \binom{N}{a_1} \times \binom{N}{a_2} \times \ldots \times \binom{N}{a_K} (we can show that this value is an integer), modulo (10^{9}+7).
Constraints
* 1 \leq N \leq 1000
* 1 \leq K \leq 20
* 1 \leq a_i \leq N
Input
Input is given from Standard Input in the following format:
N K
a_1 a_2 \ldots a_K
Output
Print the answer.
Examples
Input
3 2
3 2
Output
12
Input
856 16
399 263 665 432 206 61 784 548 422 313 848 478 827 26 398 63
Output
337587117
Submitted Solution:
```
import sys
input = sys.stdin.readline
N,K=map(int,input().split())
A=list(map(int,input().split()))
mod=10**9+7
FACT=[1]
for i in range(1,2*10**5+1):
FACT.append(FACT[-1]*i%mod)
FACT_INV=[pow(FACT[-1],mod-2,mod)]
for i in range(2*10**5,0,-1):
FACT_INV.append(FACT_INV[-1]*i%mod)
FACT_INV.reverse()
def Combi(a,b):
if 0<=b<=a:
return FACT[a]*FACT_INV[b]*FACT_INV[a-b]%mod
else:
return 0
DP=[0]*(N+1)
DP[0]=1
for k in range(K):
use=A[k]
NDP=[0]*(N+1)
for i in range(N+1):
ANS=0
for j in range(N+1):
ANS=(ANS+DP[j]*Combi(N-j,i-j)*Combi(N-(i-j),use-(i-j)))%mod
NDP[i]=ANS
DP=NDP
print(DP[N])
```
No
| 105,074 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a sequence S of positive integers and positive integers k and l, S is said to belong to level (k,l) when one of the following conditions is satisfied:
* The length of S is 1, and its only element is k.
* There exist sequences T_1,T_2,...,T_m (m \geq l) belonging to level (k-1,l) such that the concatenation of T_1,T_2,...,T_m in this order coincides with S.
Note that the second condition has no effect when k=1, that is, a sequence belongs to level (1,l) only if the first condition is satisfied.
Given are a sequence of positive integers A_1,A_2,...,A_N and a positive integer L. Find the number of subsequences A_i,A_{i+1},...,A_j (1 \leq i \leq j \leq N) that satisfy the following condition:
* There exists a positive integer K such that the sequence A_i,A_{i+1},...,A_j belongs to level (K,L).
Constraints
* 1 \leq N \leq 2 \times 10^5
* 2 \leq L \leq N
* 1 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N L
A_1 A_2 ... A_N
Output
Print the number of subsequences A_i,A_{i+1},...,A_j (1 \leq i \leq j \leq N) that satisfy the condition.
Examples
Input
9 3
2 1 1 1 1 1 1 2 3
Output
22
Input
9 2
2 1 1 1 1 1 1 2 3
Output
41
Input
15 3
4 3 2 1 1 1 2 3 2 2 1 1 1 2 2
Output
31
Submitted Solution:
```
import itertools
N, L = list(map(int,input().strip().split()))
alist = list(map(int,input().strip().split()))
count = N # 1 factor array must satisfy the condition
for x in itertools.combinations(range(N), 2):
i, j = x[0], x[1]
# print(i,j)
# for x in range(1):
# i, j = 1,8
target_list = alist[i:j+1]
maximum = max(target_list)
k = maximum+1 # level
needed_length = L**(k-2)
length = 0
condition = True
count1 = 0
belowlevel = 0
for index in range(len(target_list)):
if target_list[index]==1:
count1 = count1+1
if index==len(target_list)-1:
cluster_num = int(count1/L)
if cluster_num==0:
condition = False
break
else:
length = length+cluster_num
count1 = 0
elif target_list[index+1]!=1:
cluster_num = int(count1/L)
if cluster_num==0:
condition = False
break
else:
length = length+cluster_num
count1 = 0
elif target_list[index]==maximum:
belowlevel= belowlevel+1+int(length/(needed_length/L))
length = 0
else:
length = length+L**(target_list[index]-2)
belowlevel = belowlevel+int(length/(needed_length/L))
if (length!=0) and (length<needed_length/L):
condition = False
if (condition==True) and belowlevel>=3:
count = count+1
# print(i,j)
print(count)
```
No
| 105,075 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a sequence S of positive integers and positive integers k and l, S is said to belong to level (k,l) when one of the following conditions is satisfied:
* The length of S is 1, and its only element is k.
* There exist sequences T_1,T_2,...,T_m (m \geq l) belonging to level (k-1,l) such that the concatenation of T_1,T_2,...,T_m in this order coincides with S.
Note that the second condition has no effect when k=1, that is, a sequence belongs to level (1,l) only if the first condition is satisfied.
Given are a sequence of positive integers A_1,A_2,...,A_N and a positive integer L. Find the number of subsequences A_i,A_{i+1},...,A_j (1 \leq i \leq j \leq N) that satisfy the following condition:
* There exists a positive integer K such that the sequence A_i,A_{i+1},...,A_j belongs to level (K,L).
Constraints
* 1 \leq N \leq 2 \times 10^5
* 2 \leq L \leq N
* 1 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N L
A_1 A_2 ... A_N
Output
Print the number of subsequences A_i,A_{i+1},...,A_j (1 \leq i \leq j \leq N) that satisfy the condition.
Examples
Input
9 3
2 1 1 1 1 1 1 2 3
Output
22
Input
9 2
2 1 1 1 1 1 1 2 3
Output
41
Input
15 3
4 3 2 1 1 1 2 3 2 2 1 1 1 2 2
Output
31
Submitted Solution:
```
import itertools
N, L = list(map(int,input().strip().split()))
alist = list(map(int,input().strip().split()))
count = N # 1 factor array must satisfy the condition
for x in itertools.combinations(range(N), 2):
i, j = x[0], x[1]
# for x in range(1):
# i, j = 0,3
target_list = alist[i:j+1]
maximum = max(target_list)
k = maximum+1 # level
needed_length = L**(k-2)
length = 0
condition = True
count1 = 0
belowlevel = 0
for index in range(len(target_list)):
if target_list[index]==1:
count1 = count1+1
if index==len(target_list)-1:
cluster_num = int(count1/L)
if cluster_num==0:
condition = False
break
else:
length = length+cluster_num
count1 = 0
elif target_list[index+1]!=1:
cluster_num = int(count1/L)
if cluster_num==0:
condition = False
break
else:
length = length+cluster_num
count1 = 0
elif target_list[index]==maximum:
belowlevel= belowlevel+1+int(length/(needed_length/L))
length = 0
else:
length = length+L**(target_list[index]-2)
belowlevel = belowlevel+int(length/(needed_length/L))
if (length!=0) and (length<needed_length/L):
condition = False
if (condition==True) and belowlevel>=L:
count = count+1
# print(i,j)
print(count)
```
No
| 105,076 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a sequence S of positive integers and positive integers k and l, S is said to belong to level (k,l) when one of the following conditions is satisfied:
* The length of S is 1, and its only element is k.
* There exist sequences T_1,T_2,...,T_m (m \geq l) belonging to level (k-1,l) such that the concatenation of T_1,T_2,...,T_m in this order coincides with S.
Note that the second condition has no effect when k=1, that is, a sequence belongs to level (1,l) only if the first condition is satisfied.
Given are a sequence of positive integers A_1,A_2,...,A_N and a positive integer L. Find the number of subsequences A_i,A_{i+1},...,A_j (1 \leq i \leq j \leq N) that satisfy the following condition:
* There exists a positive integer K such that the sequence A_i,A_{i+1},...,A_j belongs to level (K,L).
Constraints
* 1 \leq N \leq 2 \times 10^5
* 2 \leq L \leq N
* 1 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N L
A_1 A_2 ... A_N
Output
Print the number of subsequences A_i,A_{i+1},...,A_j (1 \leq i \leq j \leq N) that satisfy the condition.
Examples
Input
9 3
2 1 1 1 1 1 1 2 3
Output
22
Input
9 2
2 1 1 1 1 1 1 2 3
Output
41
Input
15 3
4 3 2 1 1 1 2 3 2 2 1 1 1 2 2
Output
31
Submitted Solution:
```
import itertools
import numpy as np
import sys
def main():
input = sys.stdin.readline
N, L = list(map(int,input().strip().split()))
alist = list(map(int,input().strip().split()))
count = N # 1 factor array must satisfy the condition
for x in itertools.combinations(range(N), 2):
i, j = x[0], x[1]
# for x in range(1):
# i, j = 0,8
target_list = alist[i:j+1]
maximum = max(target_list)
level_count = np.zeros(maximum, 'int64')
pre_num = maximum
condition = True
for index in range(len(target_list)):
target = target_list[index]
level_count[target-1] = level_count[target-1]+1
if target>pre_num:
for ti in range(target-1):
if level_count[ti]!=0:
moveup = int(level_count[ti]/L)
if moveup==0:
condition = False
break
else:
level_count[ti+1] = level_count[ti+1]+moveup
level_count[ti] = 0
if condition==False:
break
else:
pre_num = target
if condition==True:
for ti in range(maximum-1):
if level_count[ti]!=0:
moveup = int(level_count[ti]/L)
if moveup==0:
condition = False
break
else:
level_count[ti+1] = level_count[ti+1]+moveup
level_count[ti] = 0
if (condition==True) and (level_count[-1]>=L):
count = count+1
# print(i,j)
print(count)
if __name__ == "__main__":
main()
```
No
| 105,077 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a sequence S of positive integers and positive integers k and l, S is said to belong to level (k,l) when one of the following conditions is satisfied:
* The length of S is 1, and its only element is k.
* There exist sequences T_1,T_2,...,T_m (m \geq l) belonging to level (k-1,l) such that the concatenation of T_1,T_2,...,T_m in this order coincides with S.
Note that the second condition has no effect when k=1, that is, a sequence belongs to level (1,l) only if the first condition is satisfied.
Given are a sequence of positive integers A_1,A_2,...,A_N and a positive integer L. Find the number of subsequences A_i,A_{i+1},...,A_j (1 \leq i \leq j \leq N) that satisfy the following condition:
* There exists a positive integer K such that the sequence A_i,A_{i+1},...,A_j belongs to level (K,L).
Constraints
* 1 \leq N \leq 2 \times 10^5
* 2 \leq L \leq N
* 1 \leq A_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N L
A_1 A_2 ... A_N
Output
Print the number of subsequences A_i,A_{i+1},...,A_j (1 \leq i \leq j \leq N) that satisfy the condition.
Examples
Input
9 3
2 1 1 1 1 1 1 2 3
Output
22
Input
9 2
2 1 1 1 1 1 1 2 3
Output
41
Input
15 3
4 3 2 1 1 1 2 3 2 2 1 1 1 2 2
Output
31
Submitted Solution:
```
import itertools
import numpy as np
import sys
def main():
input = sys.stdin.readline
N, L = list(map(int,input().strip().split()))
alist = list(map(int,input().strip().split()))
count = N # 1 factor array must satisfy the condition
for x in itertools.combinations(range(N), 2):
i, j = x[0], x[1]
# for x in range(1):
# i, j = 0,8
target_list = alist[i:j+1]
maximum = max(target_list)
level_count = np.zeros(maximum, 'int64')
pre_num = maximum
condition = True
for index in range(len(target_list)):
target = target_list[index]
level_count[target-1] = level_count[target-1]+1
if target>pre_num:
for i in range(target-1):
if level_count[i]!=0:
moveup = int(level_count[i]/L)
if moveup==0:
condition = False
break
else:
level_count[i+1] = level_count[i+1]+moveup
level_count[i] = 0
if condition==False:
break
else:
pre_num = target
if condition==True:
for i in range(maximum-1):
if level_count[i]!=0:
moveup = int(level_count[i]/L)
if moveup==0:
condition = False
break
else:
level_count[i+1] = level_count[i+1]+moveup
level_count[i] = 0
if (condition==True) and (level_count[-1]>=L):
count = count+1
# print(i,j)
print(count)
if __name__ == "__main__":
main()
```
No
| 105,078 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares numbered 1 to N from left to right. Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.
Snuke cast Q spells to move the golems.
The i-th spell consisted of two characters t_i and d_i, where d_i is `L` or `R`. When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is `L`, and moved to the square adjacent to the right if d_i is `R`.
However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.
Find the number of golems remaining after Snuke cast the Q spells.
Constraints
* 1 \leq N,Q \leq 2 \times 10^{5}
* |s| = N
* s_i and t_i are uppercase English letters.
* d_i is `L` or `R`.
Input
Input is given from Standard Input in the following format:
N Q
s
t_1 d_1
\vdots
t_{Q} d_Q
Output
Print the answer.
Examples
Input
3 4
ABC
A L
B L
B R
A R
Output
2
Input
8 3
AABCBDBA
A L
B R
A R
Output
5
Input
10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L
Output
3
"Correct Solution:
```
n, q = map(int, input().split())
s = "_{}_".format(input())
td = [input().split() for _ in range(q)]
current_l = 0
current_r = len(s) - 1
for t, d in reversed(td):
if current_l + 1 < len(s) - 1 and t == s[current_l + 1] and d == "L":
current_l += 1
elif t == s[current_l] and d == "R":
current_l -= 1
if 0 < current_r - 1 and t == s[current_r - 1] and d == "R":
current_r -= 1
elif t == s[current_r] and d == "L":
current_r += 1
print(max(current_r - current_l - 1, 0))
```
| 105,079 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares numbered 1 to N from left to right. Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.
Snuke cast Q spells to move the golems.
The i-th spell consisted of two characters t_i and d_i, where d_i is `L` or `R`. When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is `L`, and moved to the square adjacent to the right if d_i is `R`.
However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.
Find the number of golems remaining after Snuke cast the Q spells.
Constraints
* 1 \leq N,Q \leq 2 \times 10^{5}
* |s| = N
* s_i and t_i are uppercase English letters.
* d_i is `L` or `R`.
Input
Input is given from Standard Input in the following format:
N Q
s
t_1 d_1
\vdots
t_{Q} d_Q
Output
Print the answer.
Examples
Input
3 4
ABC
A L
B L
B R
A R
Output
2
Input
8 3
AABCBDBA
A L
B R
A R
Output
5
Input
10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L
Output
3
"Correct Solution:
```
#from collections import deque,defaultdict
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl = lambda: list(map(int, input().split()))
inm = lambda: map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 10**18
R = 10**9 + 7
#R = 998244353
def ddprint(x):
if DBG:
print(x)
n,q = inm()
s = ins()
t = []
d = []
for i in range(q):
tt,dd = input().split()
t.append(tt)
d.append(dd)
ltop = 0
for i in range(q-1,-1,-1):
if t[i]==s[ltop] and d[i]=='L':
ltop += 1
if ltop==n:
break
elif ltop>0 and t[i]==s[ltop-1] and d[i]=='R':
ltop -= 1
rtop = n-1
for i in range(q-1,-1,-1):
if t[i]==s[rtop] and d[i]=='R':
rtop -= 1
if rtop == -1:
break
elif rtop<n-1 and t[i]==s[rtop+1] and d[i]=='L':
rtop += 1
print(n-min(n,ltop+n-1-rtop))
```
| 105,080 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares numbered 1 to N from left to right. Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.
Snuke cast Q spells to move the golems.
The i-th spell consisted of two characters t_i and d_i, where d_i is `L` or `R`. When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is `L`, and moved to the square adjacent to the right if d_i is `R`.
However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.
Find the number of golems remaining after Snuke cast the Q spells.
Constraints
* 1 \leq N,Q \leq 2 \times 10^{5}
* |s| = N
* s_i and t_i are uppercase English letters.
* d_i is `L` or `R`.
Input
Input is given from Standard Input in the following format:
N Q
s
t_1 d_1
\vdots
t_{Q} d_Q
Output
Print the answer.
Examples
Input
3 4
ABC
A L
B L
B R
A R
Output
2
Input
8 3
AABCBDBA
A L
B R
A R
Output
5
Input
10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L
Output
3
"Correct Solution:
```
import sys
sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))
N, Q = lr()
S = '-' + sr() + '-'
TD = [sr().split() for _ in range(Q)]
L = 1
for t, d in TD[::-1]:
if d == 'L':
if L <= N and S[L] == t:
L += 1
if d == 'R':
if L >= 1 and S[L-1] == t:
L -= 1
R = N
for t, d in TD[::-1]:
if d == 'L':
if R <= N and S[R+1] == t:
R += 1
if d == 'R':
if R >= 1 and S[R] == t:
R -= 1
answer = max(0, R - L + 1)
print(answer)
# 34
```
| 105,081 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares numbered 1 to N from left to right. Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.
Snuke cast Q spells to move the golems.
The i-th spell consisted of two characters t_i and d_i, where d_i is `L` or `R`. When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is `L`, and moved to the square adjacent to the right if d_i is `R`.
However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.
Find the number of golems remaining after Snuke cast the Q spells.
Constraints
* 1 \leq N,Q \leq 2 \times 10^{5}
* |s| = N
* s_i and t_i are uppercase English letters.
* d_i is `L` or `R`.
Input
Input is given from Standard Input in the following format:
N Q
s
t_1 d_1
\vdots
t_{Q} d_Q
Output
Print the answer.
Examples
Input
3 4
ABC
A L
B L
B R
A R
Output
2
Input
8 3
AABCBDBA
A L
B R
A R
Output
5
Input
10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L
Output
3
"Correct Solution:
```
import sys
input = sys.stdin.readline
n,q = map(int,input().split())
s = input().rstrip()
td = [list(input().rstrip().split()) for i in range(q)]
def judge(x,direction):
if direction == "L":
if x == n:
return True
if x == -1:
return False
jpos = lambda w: True if w>=0 else False
else:
if x == -1:
return True
if x == n:
return False
jpos = lambda w: True if w<n else False
for i in range(q):
if td[i][0] == s[x]:
if td[i][1] == "R":
x += 1
else:
x -= 1
if jpos(x) == False:
return False
if not 0<=x<n:
return True
return True
l = -1
r = n
while l+1<r:
m = (l+r)//2
if judge(m,"L"):
r = m
else:
l = m
ansl = r
l = -1
r = n
while l+1<r:
m = (l+r)//2
if judge(m,"R"):
l = m
else:
r = m
ansr = l
print(max(0,ansr-ansl+1))
```
| 105,082 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares numbered 1 to N from left to right. Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.
Snuke cast Q spells to move the golems.
The i-th spell consisted of two characters t_i and d_i, where d_i is `L` or `R`. When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is `L`, and moved to the square adjacent to the right if d_i is `R`.
However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.
Find the number of golems remaining after Snuke cast the Q spells.
Constraints
* 1 \leq N,Q \leq 2 \times 10^{5}
* |s| = N
* s_i and t_i are uppercase English letters.
* d_i is `L` or `R`.
Input
Input is given from Standard Input in the following format:
N Q
s
t_1 d_1
\vdots
t_{Q} d_Q
Output
Print the answer.
Examples
Input
3 4
ABC
A L
B L
B R
A R
Output
2
Input
8 3
AABCBDBA
A L
B R
A R
Output
5
Input
10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L
Output
3
"Correct Solution:
```
N,Q = map(int,input().split())
s = input()
info = [input().split() for _ in range(Q)]
def biserch(ok,ng,judge):
while abs(ok-ng) > 1:
mid = (ok+ng) // 2
if judge(mid):
ok = mid
else:
ng = mid
return ok
def left_out(i):
now = i
for t, d in info:
if s[now] == t:
if d == "L":
now -= 1
elif d == "R":
now += 1
if now < 0:
return True
elif now > N-1:
return False
return False
def right_out(i):
now = i
for t, d in info:
if s[now] == t:
if d == "L":
now -= 1
elif d == "R":
now += 1
if now > N-1:
return True
elif now < 0:
return False
return False
left = biserch(ok=-1,ng=N,judge=left_out)
right = biserch(ok=N,ng=-1,judge=right_out)
ans = right - (left + 1)
print(ans)
```
| 105,083 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares numbered 1 to N from left to right. Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.
Snuke cast Q spells to move the golems.
The i-th spell consisted of two characters t_i and d_i, where d_i is `L` or `R`. When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is `L`, and moved to the square adjacent to the right if d_i is `R`.
However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.
Find the number of golems remaining after Snuke cast the Q spells.
Constraints
* 1 \leq N,Q \leq 2 \times 10^{5}
* |s| = N
* s_i and t_i are uppercase English letters.
* d_i is `L` or `R`.
Input
Input is given from Standard Input in the following format:
N Q
s
t_1 d_1
\vdots
t_{Q} d_Q
Output
Print the answer.
Examples
Input
3 4
ABC
A L
B L
B R
A R
Output
2
Input
8 3
AABCBDBA
A L
B R
A R
Output
5
Input
10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L
Output
3
"Correct Solution:
```
def inpl(): return list(map(int, input().split()))
N, Q = inpl()
S = input()
T = [""]*(Q)
D = [-1]*(Q)
for i in range(Q):
t, d = input().split()
T[i] = t
D[i] += 2*(d == "R")
def checkL(ix):
for i in range(Q):
if T[i] == S[ix]:
ix += D[i]
if ix == N:
return True
if ix < 0:
return False
return True
def checkR(ix):
for i in range(Q):
if T[i] == S[ix]:
ix += D[i]
if ix == N:
return False
if ix < 0:
return True
return True
OK = N
NG = -1
while abs(OK-NG)>1:
mid = (OK+NG)//2
if checkL(mid):
OK = mid
else:
NG = mid
Lans = OK*1
OK = -1
NG = N
while abs(OK-NG)>1:
mid = (OK+NG)//2
if checkR(mid):
OK = mid
else:
NG = mid
print(max(OK-Lans+1, 0))
```
| 105,084 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares numbered 1 to N from left to right. Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.
Snuke cast Q spells to move the golems.
The i-th spell consisted of two characters t_i and d_i, where d_i is `L` or `R`. When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is `L`, and moved to the square adjacent to the right if d_i is `R`.
However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.
Find the number of golems remaining after Snuke cast the Q spells.
Constraints
* 1 \leq N,Q \leq 2 \times 10^{5}
* |s| = N
* s_i and t_i are uppercase English letters.
* d_i is `L` or `R`.
Input
Input is given from Standard Input in the following format:
N Q
s
t_1 d_1
\vdots
t_{Q} d_Q
Output
Print the answer.
Examples
Input
3 4
ABC
A L
B L
B R
A R
Output
2
Input
8 3
AABCBDBA
A L
B R
A R
Output
5
Input
10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L
Output
3
"Correct Solution:
```
N, Q = (int(i) for i in input().split())
S = input()
L = []
for i in range(Q):
t, d = (i for i in input().split())
L.append((t,d))
def func(k):
now = k
for t, d in L:
if S[now] == t:
if d == "R":
now += 1
else:
now -= 1
if now < 0:
return "l"
elif now >= N:
return "r"
if now < 0:
return "l"
elif now >= N:
return "r"
else:
return None
ans = 0
left = 0
right = N
while True:
if left >= right:
break
opt = (left + right)//2
if func(opt) == "l":
left = opt + 1
else:
right = opt
ans += right
left = 0
right = N
while True:
if left >= right:
break
opt = (left + right)//2
if func(opt) == "r":
right = opt
else:
left = opt + 1
ans += (N - left)
print(N - ans)
```
| 105,085 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares numbered 1 to N from left to right. Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.
Snuke cast Q spells to move the golems.
The i-th spell consisted of two characters t_i and d_i, where d_i is `L` or `R`. When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is `L`, and moved to the square adjacent to the right if d_i is `R`.
However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.
Find the number of golems remaining after Snuke cast the Q spells.
Constraints
* 1 \leq N,Q \leq 2 \times 10^{5}
* |s| = N
* s_i and t_i are uppercase English letters.
* d_i is `L` or `R`.
Input
Input is given from Standard Input in the following format:
N Q
s
t_1 d_1
\vdots
t_{Q} d_Q
Output
Print the answer.
Examples
Input
3 4
ABC
A L
B L
B R
A R
Output
2
Input
8 3
AABCBDBA
A L
B R
A R
Output
5
Input
10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L
Output
3
"Correct Solution:
```
N,Q = map(int, input().split())
s = '_'+input()+'_'
td = [input().split() for _ in range(Q)]
right = N+1
left = 0
for t,d in reversed(td):
if t == s[right-1] and d =='R':
right -= 1
elif t == s[right] and d == 'L':
right += 1
if t == s[left+1] and d == 'L':
left += 1
elif t == s[left] and d == 'R':
left -= 1
print(max(0,right-left-1))
```
| 105,086 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N squares numbered 1 to N from left to right. Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.
Snuke cast Q spells to move the golems.
The i-th spell consisted of two characters t_i and d_i, where d_i is `L` or `R`. When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is `L`, and moved to the square adjacent to the right if d_i is `R`.
However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.
Find the number of golems remaining after Snuke cast the Q spells.
Constraints
* 1 \leq N,Q \leq 2 \times 10^{5}
* |s| = N
* s_i and t_i are uppercase English letters.
* d_i is `L` or `R`.
Input
Input is given from Standard Input in the following format:
N Q
s
t_1 d_1
\vdots
t_{Q} d_Q
Output
Print the answer.
Examples
Input
3 4
ABC
A L
B L
B R
A R
Output
2
Input
8 3
AABCBDBA
A L
B R
A R
Output
5
Input
10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L
Output
3
Submitted Solution:
```
N,Q = map(int, input().split())
S = input()
C = [tuple(map(str, input().split())) for _ in range(Q)]
C = C[::-1]
left = -1
right = N
for (t,d) in C:
if ('L' == d):
if (S[left+1] == t):
left += 1
if (N-1 <= left):
print(0)
exit()
if (right < N):
if (S[right] == t):
right += 1
if (N < right):
right = N
else:
if (S[right-1] == t):
right -= 1
if (right <= 0):
print(0)
exit()
if (-1 < left):
if (S[left] == t):
left -= 1
if (left < -1):
left = -1
print(right - left - 1)
```
Yes
| 105,087 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N squares numbered 1 to N from left to right. Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.
Snuke cast Q spells to move the golems.
The i-th spell consisted of two characters t_i and d_i, where d_i is `L` or `R`. When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is `L`, and moved to the square adjacent to the right if d_i is `R`.
However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.
Find the number of golems remaining after Snuke cast the Q spells.
Constraints
* 1 \leq N,Q \leq 2 \times 10^{5}
* |s| = N
* s_i and t_i are uppercase English letters.
* d_i is `L` or `R`.
Input
Input is given from Standard Input in the following format:
N Q
s
t_1 d_1
\vdots
t_{Q} d_Q
Output
Print the answer.
Examples
Input
3 4
ABC
A L
B L
B R
A R
Output
2
Input
8 3
AABCBDBA
A L
B R
A R
Output
5
Input
10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L
Output
3
Submitted Solution:
```
n,q=map(int,input().split())
s=[0]+list(input())+[0]
a=[input().split()for i in range(q)][::-1]
l,r=0,n+1
for(m,h)in a:
if m==s[l+1]and h=="L":
l+=1
elif m==s[l]and h=="R":
l-=1
if m==s[r-1]and h=="R":
r-=1
elif m==s[r]and h=="L":
r+=1
print(max(0,r-l-1))
```
Yes
| 105,088 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N squares numbered 1 to N from left to right. Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.
Snuke cast Q spells to move the golems.
The i-th spell consisted of two characters t_i and d_i, where d_i is `L` or `R`. When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is `L`, and moved to the square adjacent to the right if d_i is `R`.
However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.
Find the number of golems remaining after Snuke cast the Q spells.
Constraints
* 1 \leq N,Q \leq 2 \times 10^{5}
* |s| = N
* s_i and t_i are uppercase English letters.
* d_i is `L` or `R`.
Input
Input is given from Standard Input in the following format:
N Q
s
t_1 d_1
\vdots
t_{Q} d_Q
Output
Print the answer.
Examples
Input
3 4
ABC
A L
B L
B R
A R
Output
2
Input
8 3
AABCBDBA
A L
B R
A R
Output
5
Input
10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L
Output
3
Submitted Solution:
```
n,q = (int(i) for i in input().split())
s = '#'+input()+'#'
l = 0
r = n+1
a = [list(input().split()) for i in range(q)]
for i in range(q-1, -1, -1):
t,d = a[i]
if s[l+1] == t and d =='L':
l += 1
elif s[l] == t and d == 'R':
l -= 1
if s[r] == t and d == 'L':
r += 1
elif s[r-1] == t and d == 'R':
r -= 1
print(max(0,r-l-1))
```
Yes
| 105,089 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N squares numbered 1 to N from left to right. Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.
Snuke cast Q spells to move the golems.
The i-th spell consisted of two characters t_i and d_i, where d_i is `L` or `R`. When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is `L`, and moved to the square adjacent to the right if d_i is `R`.
However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.
Find the number of golems remaining after Snuke cast the Q spells.
Constraints
* 1 \leq N,Q \leq 2 \times 10^{5}
* |s| = N
* s_i and t_i are uppercase English letters.
* d_i is `L` or `R`.
Input
Input is given from Standard Input in the following format:
N Q
s
t_1 d_1
\vdots
t_{Q} d_Q
Output
Print the answer.
Examples
Input
3 4
ABC
A L
B L
B R
A R
Output
2
Input
8 3
AABCBDBA
A L
B R
A R
Output
5
Input
10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L
Output
3
Submitted Solution:
```
I=input;n,q=map(int,I().split());s=' %s '%I();l,r=0,n+1
for t,_,d in eval('I(),'*q)[::-1]:L=d<'R';R=1-L;l+=(t==s[l+1])*L-(t==s[l])*R;r+=(t==s[r])*L-(t==s[r-1])*R
print(r-l-1)
```
Yes
| 105,090 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N squares numbered 1 to N from left to right. Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.
Snuke cast Q spells to move the golems.
The i-th spell consisted of two characters t_i and d_i, where d_i is `L` or `R`. When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is `L`, and moved to the square adjacent to the right if d_i is `R`.
However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.
Find the number of golems remaining after Snuke cast the Q spells.
Constraints
* 1 \leq N,Q \leq 2 \times 10^{5}
* |s| = N
* s_i and t_i are uppercase English letters.
* d_i is `L` or `R`.
Input
Input is given from Standard Input in the following format:
N Q
s
t_1 d_1
\vdots
t_{Q} d_Q
Output
Print the answer.
Examples
Input
3 4
ABC
A L
B L
B R
A R
Output
2
Input
8 3
AABCBDBA
A L
B R
A R
Output
5
Input
10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L
Output
3
Submitted Solution:
```
N,Q=map(int,input().split())
s=[i for i in input()]
ans=[1 for i in range(N)]
for i in range(Q):
t,d=map(str,input().split())
T=s.copy()
while t in T:
if d=='R' and T.index(t)!=len(T)-1:
ans[T.index(t)+1]+=ans[T.index(t)]
if d=='L' and T.index(t)!=0:
ans[T.index(t)-1]+=ans[T.index(t)]
ans[T.index(t)]=0
T[T.index(t)]='Done'
print(sum(ans))
```
No
| 105,091 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N squares numbered 1 to N from left to right. Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.
Snuke cast Q spells to move the golems.
The i-th spell consisted of two characters t_i and d_i, where d_i is `L` or `R`. When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is `L`, and moved to the square adjacent to the right if d_i is `R`.
However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.
Find the number of golems remaining after Snuke cast the Q spells.
Constraints
* 1 \leq N,Q \leq 2 \times 10^{5}
* |s| = N
* s_i and t_i are uppercase English letters.
* d_i is `L` or `R`.
Input
Input is given from Standard Input in the following format:
N Q
s
t_1 d_1
\vdots
t_{Q} d_Q
Output
Print the answer.
Examples
Input
3 4
ABC
A L
B L
B R
A R
Output
2
Input
8 3
AABCBDBA
A L
B R
A R
Output
5
Input
10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L
Output
3
Submitted Solution:
```
import sys
n,q=map(int,input().split())
s=input()
l=[[i for i in l.split()] for l in sys.stdin]
def right_fallen(x):
stack=x
for i in range(n):
if stack==n:
return True
if stack==-1:
return False
if l[i][0]==s[stack]:
if l[i][1]=='R':
stack+=1
else:
stack-=1
return False
def left_fallen(x):
stack=x
for i in range(n):
if stack==n:
return False
if stack==-1:
return True
if l[i][0]==s[stack]:
if l[i][1]=='R':
stack+=1
else:
stack-=1
return False
def binary_search():
ok=n
ng=-1
while(abs(ok-ng)>1):
mid=(ok+ng)//2
if right_fallen(mid):
ok=mid
else:
ng=mid
return ok
def binary_search2():
ok=-1
ng=n
while(abs(ok-ng)>1):
mid=(ok+ng)//2
if left_fallen(mid):
ok=mid
else:
ng=mid
return ok
print(binary_search()-binary_search2()-1)
```
No
| 105,092 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N squares numbered 1 to N from left to right. Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.
Snuke cast Q spells to move the golems.
The i-th spell consisted of two characters t_i and d_i, where d_i is `L` or `R`. When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is `L`, and moved to the square adjacent to the right if d_i is `R`.
However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.
Find the number of golems remaining after Snuke cast the Q spells.
Constraints
* 1 \leq N,Q \leq 2 \times 10^{5}
* |s| = N
* s_i and t_i are uppercase English letters.
* d_i is `L` or `R`.
Input
Input is given from Standard Input in the following format:
N Q
s
t_1 d_1
\vdots
t_{Q} d_Q
Output
Print the answer.
Examples
Input
3 4
ABC
A L
B L
B R
A R
Output
2
Input
8 3
AABCBDBA
A L
B R
A R
Output
5
Input
10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L
Output
3
Submitted Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N,Q = map(int,readline().split())
S = 'x' + readline().rstrip().decode('utf-8') + 'x'
query = read().decode('utf-8').split()
# ここに居れば左右に落ちない、ぎりぎり
L = 1; R = N
for T,D in zip(query[-2::-1],query[-1::-1]):
if D == 'L':
if S[L] == T:
L += 1
if S[R+1] == T:
R += 1
else:
if S[R] == T:
R -= 1
if S[L-1] == T:
L -= 1
x = R-L+1
if x <= 0:
x = 0
print(x)
```
No
| 105,093 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N squares numbered 1 to N from left to right. Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.
Snuke cast Q spells to move the golems.
The i-th spell consisted of two characters t_i and d_i, where d_i is `L` or `R`. When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is `L`, and moved to the square adjacent to the right if d_i is `R`.
However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.
Find the number of golems remaining after Snuke cast the Q spells.
Constraints
* 1 \leq N,Q \leq 2 \times 10^{5}
* |s| = N
* s_i and t_i are uppercase English letters.
* d_i is `L` or `R`.
Input
Input is given from Standard Input in the following format:
N Q
s
t_1 d_1
\vdots
t_{Q} d_Q
Output
Print the answer.
Examples
Input
3 4
ABC
A L
B L
B R
A R
Output
2
Input
8 3
AABCBDBA
A L
B R
A R
Output
5
Input
10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L
Output
3
Submitted Solution:
```
# coding: utf-8
def main():
N,Q = map(int, input().split())
s = input()
ans = N
command = []
# print(char_list)
for i in range(Q):
# 呪文
t,d = input().split()
command.append([t,d])
# r_ans = N
# l_ans = -1
# for i in range(N):
# if simulation_R(command,s,i,N):
# r_ans = i
# break
# # print(r_ans)
# for i in range(N-1,-1,-1):
# if simulation_L(command,s,i,N):
# l_ans = i
# break
# # print(l_ans)
# ans = N - (N-r_ans) - (l_ans+1)
# print(command)
r = binary_serch_R(command,s,N)
#print(r)
l = binary_serch_L(command,s,N)
#print(l)
ans = ans - (N-r) - (l+1)
print(ans)
def simulation_R(command,s,now,N):
for pair in command:
if pair[0] == s[now]:
if pair[1] == 'L':
now -= 1
elif pair[1] == 'R':
now += 1
if now < 0:
return False
elif now >= N:
return True
return False
def simulation_L(command,s,now,N):
for pair in command:
if pair[0] == s[now]:
if pair[1] == 'L':
now -= 1
elif pair[1] == 'R':
now += 1
if now < 0:
return True
elif now >= N:
return False
return False
def binary_serch_R(command,s,N):
left = 0
right = N-1
if simulation_R(command,s,left,N) :
return -1
if simulation_R(command,s,right,N) == False:
return N
while not simulation_R(command,s,left,N) and simulation_R(command,s,right,N):
mid = int((left+right)/2)
# print(mid)
if right - left == 1:
return right
if simulation_R(command,s,mid,N) :
right = mid
else :
left = mid
return right
def binary_serch_L(command,s,N):
left = 0
right = N-1
if simulation_L(command,s,left,N) == False :
return -1
if simulation_L(command,s,right,N):
return N
while simulation_L(command,s,left,N) and (not simulation_L(command,s,right,N)):
mid = int((left+right)/2)
if right - left == 1:
return left
if not simulation_L(command,s,mid,N) :
right = mid
else :
left = mid
return left
# def simulation(command,s,now,d,N):
# # print("test"+str(now))
# for pair in command:
# if pair[0] == s[now]:
# if pair[1] == 'L':
# now -= 1
# elif pair[1] == 'R':
# now += 1
# if d == 'L' and now < 0 :
# return True
# elif
# elif d == 'R' and now >= N :
# return True
# return False
if __name__ == "__main__":
main()
```
No
| 105,094 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a sequence of N integers: A_1,A_2,...,A_N.
Find the number of permutations p_1,p_2,...,p_N of 1,2,...,N that can be changed to A_1,A_2,...,A_N by performing the following operation some number of times (possibly zero), modulo 998244353:
* For each 1\leq i\leq N, let q_i=min(p_{i-1},p_{i}), where p_0=p_N. Replace the sequence p with the sequence q.
Constraints
* 1 \leq N \leq 3 × 10^5
* 1 \leq A_i \leq N
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1
:
A_N
Output
Print the number of the sequences that satisfy the condition, modulo 998244353.
Examples
Input
3
1
2
1
Output
2
Input
5
3
1
4
1
5
Output
0
Input
8
4
4
4
1
1
1
2
2
Output
24
Input
6
1
1
6
2
2
2
Output
0
"Correct Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
from operator import itemgetter
MOD = 998244353
N,*A = map(int,read().split())
T = A.count(1)
if T == 0:
print(0)
exit()
if T == 1:
answer = 1 if len(set(A)) == N else 0
print(answer)
exit()
if T == N:
answer = 1
for n in range(1,N+1):
answer *= n
answer %= MOD
print(answer)
exit()
n = A.index(1)
while A[n-1] == 1:
n -= 1
A = A[n:] + A[:n]
# assert len(A) == N and A[0] == 1 and A[-1] != 1
L = [0] * (N+1)
R = [-1] * (N+1)
ctr = [0] * (N+1)
nums = []
prev = 0
for i,x in enumerate(A):
ctr[x] += 1
R[x] = i
if prev != x:
nums.append(x)
L[x] = i
prev = x
if any(y - x + 1 != z for x,y,z in zip(L,R,ctr)):
print(0)
exit()
if any(x > T for x in ctr[2:]):
print(0)
exit()
free = [0] * (N+1) # ある数値を書き込んだ時点で、死亡確定になってるマス数
answer = 1
for x,y,z in zip(nums,nums[1:],nums[2:]+[1]):
if x > y < z:
if ctr[y] != T:
answer = 0
break
elif x < y < z:
free[y] += ctr[y] - 1
elif x > y > z:
free[y] += ctr[y] - 1
else:
# x < y > z
answer *= (T + 1 - ctr[y])
answer %= MOD
free[y] += ctr[y] + T - 2
f = 0
for n in range(1,N+1):
if ctr[n] >= 1:
f += free[n]
continue
answer *= f
answer %= MOD
f -= 1
print(answer)
```
| 105,095 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence of N integers: A_1,A_2,...,A_N.
Find the number of permutations p_1,p_2,...,p_N of 1,2,...,N that can be changed to A_1,A_2,...,A_N by performing the following operation some number of times (possibly zero), modulo 998244353:
* For each 1\leq i\leq N, let q_i=min(p_{i-1},p_{i}), where p_0=p_N. Replace the sequence p with the sequence q.
Constraints
* 1 \leq N \leq 3 × 10^5
* 1 \leq A_i \leq N
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1
:
A_N
Output
Print the number of the sequences that satisfy the condition, modulo 998244353.
Examples
Input
3
1
2
1
Output
2
Input
5
3
1
4
1
5
Output
0
Input
8
4
4
4
1
1
1
2
2
Output
24
Input
6
1
1
6
2
2
2
Output
0
Submitted Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
from operator import itemgetter
MOD = 998244353
N,*A = map(int,read().split())
T = A.count(1)
if T == 0:
print(0)
exit()
if T == 1:
answer = 1 if len(set(A)) == N else 0
print(answer)
exit()
if T == N:
answer = 1
for n in range(1,N+1):
answer *= n
answer %= MOD
print(answer)
exit()
n = A.index(1)
while A[n-1] == 1:
n -= 1
A = A[n:] + A[:n]
# assert len(A) == N and A[0] == 1 and A[-1] != 1
L = [0] * (N+1)
R = [-1] * (N+1)
ctr = [0] * (N+1)
nums = []
prev = 0
for i,x in enumerate(A):
ctr[x] += 1
R[x] = i
if prev != x:
nums.append(x)
L[x] = i
prev = x
if any(y - x + 1 != z for x,y,z in zip(L,R,ctr)):
print(0)
exit()
if any(x > T for x in ctr[2:]):
print(0)
exit()
raise Exception
```
No
| 105,096 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence of N integers: A_1,A_2,...,A_N.
Find the number of permutations p_1,p_2,...,p_N of 1,2,...,N that can be changed to A_1,A_2,...,A_N by performing the following operation some number of times (possibly zero), modulo 998244353:
* For each 1\leq i\leq N, let q_i=min(p_{i-1},p_{i}), where p_0=p_N. Replace the sequence p with the sequence q.
Constraints
* 1 \leq N \leq 3 × 10^5
* 1 \leq A_i \leq N
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1
:
A_N
Output
Print the number of the sequences that satisfy the condition, modulo 998244353.
Examples
Input
3
1
2
1
Output
2
Input
5
3
1
4
1
5
Output
0
Input
8
4
4
4
1
1
1
2
2
Output
24
Input
6
1
1
6
2
2
2
Output
0
Submitted Solution:
```
import numpy as np
import sys
M = 998244353
N = int(input())
A = np.empty(N, dtype=np.int64)
for i in range(N):
A[i] = int(input()) - 1
# A[i]: 0,1,...,(N-1)
s=0
if A[0]==A[N-1]:
while (s <= N-1) and (A[s]==A[0]):
s = s+1
if s == N:
if A[0] == 0:
result = 1
for i in range(1,N+1):
result = (result*i) % M
print(result)
else:
print(0)
sys.exit()
lengths = np.zeros(N, dtype=np.int64)
heads = np.zeros(N, dtype=np.int64)
tails = np.zeros(N, dtype=np.int64)
if s > 0:
tail = A[0]
else:
tail = A[N-1]
l = 1
for i in range(s,N):
if (i < N-1) and (A[i+1] == A[i]):
l = l+1
else:
if i < N-1:
if lengths[A[i+1]] > 0:
print(0)
sys.exit()
else:
heads[A[i]] = A[i+1]
else:
heads[A[i]] = A[0]
lengths[A[i]] = l
l=1
tails[A[i]] = tail
tail = A[i]
if s > 0:
heads[A[0]] = A[s]
lengths[A[0]] = lengths[A[0]] + s
k = lengths[0]
if k == 0:
print(0)
sys.exit()
result = 1
killed = 0
for i in range(1,N):
if lengths[i] == 0:
result = (result * killed) % M
killed = killed - 1
elif lengths[i] > k:
print(0)
exit()
elif heads[i] > i and tails[i] > i:
if lengths[i] != k:
print(0)
exit()
elif heads[i] < i and tails[i] < i:
result = (result * (k-lengths[i]+1)) % M
killed = killed + (lengths[i]+k-2)
else:
# head < i and tail > i
# head > i and tail < i
killed = killed + (lengths[i]-1)
print(result)
```
No
| 105,097 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence of N integers: A_1,A_2,...,A_N.
Find the number of permutations p_1,p_2,...,p_N of 1,2,...,N that can be changed to A_1,A_2,...,A_N by performing the following operation some number of times (possibly zero), modulo 998244353:
* For each 1\leq i\leq N, let q_i=min(p_{i-1},p_{i}), where p_0=p_N. Replace the sequence p with the sequence q.
Constraints
* 1 \leq N \leq 3 × 10^5
* 1 \leq A_i \leq N
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1
:
A_N
Output
Print the number of the sequences that satisfy the condition, modulo 998244353.
Examples
Input
3
1
2
1
Output
2
Input
5
3
1
4
1
5
Output
0
Input
8
4
4
4
1
1
1
2
2
Output
24
Input
6
1
1
6
2
2
2
Output
0
Submitted Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
MOD = 998244353
N,*A = map(int,read().split())
T = A.count(1)
if T == 1:
answer = 1 if len(set(A)) == N else 0
print(answer)
exit()
if T == N:
answer = 1
for n in range(1,N+1):
answer *= n
answer %= MOD
print(answer)
exit()
n = A.index(1)
while A[n-1] == 1:
n -= 1
A = A[n:] + A[:n]
assert len(A) == N and A[0] == 1 and A[-1] != 1
print(0)
```
No
| 105,098 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence of N integers: A_1,A_2,...,A_N.
Find the number of permutations p_1,p_2,...,p_N of 1,2,...,N that can be changed to A_1,A_2,...,A_N by performing the following operation some number of times (possibly zero), modulo 998244353:
* For each 1\leq i\leq N, let q_i=min(p_{i-1},p_{i}), where p_0=p_N. Replace the sequence p with the sequence q.
Constraints
* 1 \leq N \leq 3 × 10^5
* 1 \leq A_i \leq N
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1
:
A_N
Output
Print the number of the sequences that satisfy the condition, modulo 998244353.
Examples
Input
3
1
2
1
Output
2
Input
5
3
1
4
1
5
Output
0
Input
8
4
4
4
1
1
1
2
2
Output
24
Input
6
1
1
6
2
2
2
Output
0
Submitted Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
MOD = 998244353
N,*A = map(int,read().split())
T = A.count(1)
if T == 1:
answer = 1 if len(set(A)) == N else 0
print(answer)
exit()
if T == N:
answer = 1
for n in range(1,N+1):
answer *= n
answer %= MOD
print(answer)
exit()
raise
```
No
| 105,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.