message stringlengths 2 28.7k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 21 109k | cluster float64 7 7 | __index_level_0__ int64 42 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's Petya's birthday party and his friends have presented him a brand new "Electrician-n" construction set, which they are sure he will enjoy as he always does with weird puzzles they give him.
Construction set "Electrician-n" consists of 2n - 1 wires and 2n light bulbs. Each bulb has its own unique index that is an integer from 1 to 2n, while all wires look the same and are indistinguishable. In order to complete this construction set one has to use each of the wires to connect two distinct bulbs. We define a chain in a completed construction set as a sequence of distinct bulbs of length at least two, such that every two consecutive bulbs in this sequence are directly connected by a wire. Completed construction set configuration is said to be correct if a resulting network of bulbs and wires has a tree structure, i.e. any two distinct bulbs are the endpoints of some chain.
Petya was assembling different configurations for several days, and he noticed that sometimes some of the bulbs turn on. After a series of experiments he came up with a conclusion that bulbs indexed 2i and 2i - 1 turn on if the chain connecting them consists of exactly d_i wires. Moreover, the following important condition holds: the value of d_i is never greater than n.
Petya did his best but was not able to find a configuration that makes all bulbs to turn on, so he seeks your assistance. Please, find out a configuration that makes all bulbs shine. It is guaranteed that such configuration always exists.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the parameter of a construction set that defines the number of bulbs and the number of wires.
Next line contains n integers d_1, d_2, β¦, d_n (1 β€ d_i β€ n), where d_i stands for the number of wires the chain between bulbs 2i and 2i - 1 should consist of.
Output
Print 2n - 1 lines. The i-th of them should contain two distinct integers a_i and b_i (1 β€ a_i, b_i β€ 2n, a_i β b_i) β indices of bulbs connected by a wire.
If there are several possible valid answer you can print any of them.
Examples
Input
3
2 2 2
Output
1 6
2 6
3 5
3 6
4 5
Input
4
2 2 2 1
Output
1 6
1 7
2 6
3 5
3 6
4 5
7 8
Input
6
2 2 2 2 2 2
Output
1 3
2 3
3 5
4 5
5 7
6 7
7 12
8 12
9 11
9 12
10 11
Input
2
1 1
Output
1 2
1 4
3 4
Note
<image> Answer for the first sample test. <image> Answer for the second sample test.
Submitted Solution:
```
n = int(input())
v = list(map(int, input().split()))
v = sorted([(v[i], i * 2 + 1) for i in range(n)], reverse=True)
print('\n'.join([str(v[i][1]) + ' ' + str(v[i + 1][1]) for i in range(n - 1)]))
r = [i[1] for i in v]
for i in range(n):
print(v[i][1] + 1, r[v[i][0] + i - 1])
if v[i][0] + i == len(r):
r.append(v[i][1])
``` | instruction | 0 | 95,381 | 7 | 190,762 |
No | output | 1 | 95,381 | 7 | 190,763 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's Petya's birthday party and his friends have presented him a brand new "Electrician-n" construction set, which they are sure he will enjoy as he always does with weird puzzles they give him.
Construction set "Electrician-n" consists of 2n - 1 wires and 2n light bulbs. Each bulb has its own unique index that is an integer from 1 to 2n, while all wires look the same and are indistinguishable. In order to complete this construction set one has to use each of the wires to connect two distinct bulbs. We define a chain in a completed construction set as a sequence of distinct bulbs of length at least two, such that every two consecutive bulbs in this sequence are directly connected by a wire. Completed construction set configuration is said to be correct if a resulting network of bulbs and wires has a tree structure, i.e. any two distinct bulbs are the endpoints of some chain.
Petya was assembling different configurations for several days, and he noticed that sometimes some of the bulbs turn on. After a series of experiments he came up with a conclusion that bulbs indexed 2i and 2i - 1 turn on if the chain connecting them consists of exactly d_i wires. Moreover, the following important condition holds: the value of d_i is never greater than n.
Petya did his best but was not able to find a configuration that makes all bulbs to turn on, so he seeks your assistance. Please, find out a configuration that makes all bulbs shine. It is guaranteed that such configuration always exists.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the parameter of a construction set that defines the number of bulbs and the number of wires.
Next line contains n integers d_1, d_2, β¦, d_n (1 β€ d_i β€ n), where d_i stands for the number of wires the chain between bulbs 2i and 2i - 1 should consist of.
Output
Print 2n - 1 lines. The i-th of them should contain two distinct integers a_i and b_i (1 β€ a_i, b_i β€ 2n, a_i β b_i) β indices of bulbs connected by a wire.
If there are several possible valid answer you can print any of them.
Examples
Input
3
2 2 2
Output
1 6
2 6
3 5
3 6
4 5
Input
4
2 2 2 1
Output
1 6
1 7
2 6
3 5
3 6
4 5
7 8
Input
6
2 2 2 2 2 2
Output
1 3
2 3
3 5
4 5
5 7
6 7
7 12
8 12
9 11
9 12
10 11
Input
2
1 1
Output
1 2
1 4
3 4
Note
<image> Answer for the first sample test. <image> Answer for the second sample test.
Submitted Solution:
```
import sys
input = sys.stdin.readline
n=int(input())
d=[int(i) for i in input().split(' ')]
v=[2*i+1 for i in range(n)]
v.sort(key = lambda x:-d[x//2])
for i in range(n-1):print(v[i],v[i+1])
currlen = len(v) #len of v
for i in range(n):
if d[v[i]//2] + i == currlen:
v.append(v[i] + 1)
currlen += 1
print(v[-1],v[i] + 1)
else:
print(v[ d[v[i]//2] + i - 1],v[i]+1)
``` | instruction | 0 | 95,382 | 7 | 190,764 |
No | output | 1 | 95,382 | 7 | 190,765 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Rick and Morty want to find MR. PBH and they can't do it alone. So they need of Mr. Meeseeks. They Have generated n Mr. Meeseeks, standing in a line numbered from 1 to n. Each of them has his own color. i-th Mr. Meeseeks' color is ai.
Rick and Morty are gathering their army and they want to divide Mr. Meeseeks into some squads. They don't want their squads to be too colorful, so each squad should have Mr. Meeseeks of at most k different colors. Also each squad should be a continuous subarray of Mr. Meeseeks in the line. Meaning that for each 1 β€ i β€ e β€ j β€ n, if Mr. Meeseeks number i and Mr. Meeseeks number j are in the same squad then Mr. Meeseeks number e should be in that same squad.
<image>
Also, each squad needs its own presidio, and building a presidio needs money, so they want the total number of squads to be minimized.
Rick and Morty haven't finalized the exact value of k, so in order to choose it, for each k between 1 and n (inclusive) need to know the minimum number of presidios needed.
Input
The first line of input contains a single integer n (1 β€ n β€ 105) β number of Mr. Meeseeks.
The second line contains n integers a1, a2, ..., an separated by spaces (1 β€ ai β€ n) β colors of Mr. Meeseeks in order they standing in a line.
Output
In the first and only line of input print n integers separated by spaces. i-th integer should be the minimum number of presidios needed if the value of k is i.
Examples
Input
5
1 3 4 3 3
Output
4 2 1 1 1
Input
8
1 5 7 8 1 7 6 1
Output
8 4 3 2 1 1 1 1
Note
For the first sample testcase, some optimal ways of dividing army into squads for each k are:
1. [1], [3], [4], [3, 3]
2. [1], [3, 4, 3, 3]
3. [1, 3, 4, 3, 3]
4. [1, 3, 4, 3, 3]
5. [1, 3, 4, 3, 3]
For the second testcase, some optimal ways of dividing army into squads for each k are:
1. [1], [5], [7], [8], [1], [7], [6], [1]
2. [1, 5], [7, 8], [1, 7], [6, 1]
3. [1, 5, 7], [8], [1, 7, 6, 1]
4. [1, 5, 7, 8], [1, 7, 6, 1]
5. [1, 5, 7, 8, 1, 7, 6, 1]
6. [1, 5, 7, 8, 1, 7, 6, 1]
7. [1, 5, 7, 8, 1, 7, 6, 1]
8. [1, 5, 7, 8, 1, 7, 6, 1]
Submitted Solution:
```
n=int(input())
import math
a=input().split()
t=1
r=[]
w=1
d=a[0]
for i in range(1,n+1):
p=[]
z=0
while(z<n):
if(not(a[z] in p)):
p=p+[a[z]]
if(len(p)>i):
p=[a[z]]
if(z!=n-1):w+=1
z+=1
r=r+[w]
w=1
for i in r:
print(i,end=" ")
``` | instruction | 0 | 95,763 | 7 | 191,526 |
No | output | 1 | 95,763 | 7 | 191,527 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In the game of Mastermind, there are two players β Alice and Bob. Alice has a secret code, which Bob tries to guess. Here, a code is defined as a sequence of n colors. There are exactly n+1 colors in the entire universe, numbered from 1 to n+1 inclusive.
When Bob guesses a code, Alice tells him some information about how good of a guess it is, in the form of two integers x and y.
The first integer x is the number of indices where Bob's guess correctly matches Alice's code. The second integer y is the size of the intersection of the two codes as multisets. That is, if Bob were to change the order of the colors in his guess, y is the maximum number of indices he could get correct.
For example, suppose n=5, Alice's code is [3,1,6,1,2], and Bob's guess is [3,1,1,2,5]. At indices 1 and 2 colors are equal, while in the other indices they are not equal. So x=2. And the two codes have the four colors 1,1,2,3 in common, so y=4.
<image> Solid lines denote a matched color for the same index. Dashed lines denote a matched color at a different index. x is the number of solid lines, and y is the total number of lines.
You are given Bob's guess and two values x and y. Can you find one possibility of Alice's code so that the values of x and y are correct?
Input
The first line contains a single integer t (1β€ tβ€ 1000) β the number of test cases. Next 2t lines contain descriptions of test cases.
The first line of each test case contains three integers n,x,y (1β€ nβ€ 10^5, 0β€ xβ€ yβ€ n) β the length of the codes, and two values Alice responds with.
The second line of each test case contains n integers b_1,β¦,b_n (1β€ b_iβ€ n+1) β Bob's guess, where b_i is the i-th color of the guess.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, on the first line, output "YES" if there is a solution, or "NO" if there is no possible secret code consistent with the described situation. You can print each character in any case (upper or lower).
If the answer is "YES", on the next line output n integers a_1,β¦,a_n (1β€ a_iβ€ n+1) β Alice's secret code, where a_i is the i-th color of the code.
If there are multiple solutions, output any.
Example
Input
7
5 2 4
3 1 1 2 5
5 3 4
1 1 2 1 2
4 0 4
5 5 3 3
4 1 4
2 3 2 3
6 1 2
3 2 1 1 1 1
6 2 4
3 3 2 1 1 1
6 2 6
1 1 3 2 1 1
Output
YES
3 1 6 1 2
YES
3 1 1 1 2
YES
3 3 5 5
NO
YES
4 4 4 4 3 1
YES
3 1 3 1 7 7
YES
2 3 1 1 1 1
Note
The first test case is described in the statement.
In the second test case, x=3 because the colors are equal at indices 2,4,5. And y=4 because they share the colors 1,1,1,2.
In the third test case, x=0 because there is no index where the colors are the same. But y=4 because they share the colors 3,3,5,5.
In the fourth test case, it can be proved that no solution exists. | instruction | 0 | 96,292 | 7 | 192,584 |
Tags: constructive algorithms, graph matchings, greedy, implementation, sortings, two pointers
Correct Solution:
```
from sys import stdin, stdout
from collections import defaultdict
from heapq import heapify, heappop, heappush
def solve():
n, s, y = map(int, stdin.readline().split())
a = stdin.readline().split()
d = defaultdict(list)
for i, x in enumerate(a):
d[x].append(i)
for i in range(1, n + 2):
e = str(i)
if e not in d:
break
q = [(-len(d[x]), x) for x in d.keys()]
heapify(q)
ans = [0] * n
for i in range(s):
l, x = heappop(q)
ans[d[x].pop()] = x
l += 1
if l:
heappush(q, (l, x))
p = []
while q:
l, x = heappop(q)
p.extend(d[x])
if p:
h = (n - s) // 2
y = n - y
q = p[h:] + p[:h]
for x, z in zip(p, q):
if a[x] == a[z]:
if y:
ans[x] = e
y -= 1
else:
stdout.write("NO\n")
return
else:
ans[x] = a[z]
for i in range(n - s):
if y and ans[p[i]] != e:
ans[p[i]] = e
y -= 1
stdout.write("YES\n")
stdout.write(' '.join(ans))
stdout.write("\n")
T = int(stdin.readline())
for t in range(T):
solve()
``` | output | 1 | 96,292 | 7 | 192,585 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In the game of Mastermind, there are two players β Alice and Bob. Alice has a secret code, which Bob tries to guess. Here, a code is defined as a sequence of n colors. There are exactly n+1 colors in the entire universe, numbered from 1 to n+1 inclusive.
When Bob guesses a code, Alice tells him some information about how good of a guess it is, in the form of two integers x and y.
The first integer x is the number of indices where Bob's guess correctly matches Alice's code. The second integer y is the size of the intersection of the two codes as multisets. That is, if Bob were to change the order of the colors in his guess, y is the maximum number of indices he could get correct.
For example, suppose n=5, Alice's code is [3,1,6,1,2], and Bob's guess is [3,1,1,2,5]. At indices 1 and 2 colors are equal, while in the other indices they are not equal. So x=2. And the two codes have the four colors 1,1,2,3 in common, so y=4.
<image> Solid lines denote a matched color for the same index. Dashed lines denote a matched color at a different index. x is the number of solid lines, and y is the total number of lines.
You are given Bob's guess and two values x and y. Can you find one possibility of Alice's code so that the values of x and y are correct?
Input
The first line contains a single integer t (1β€ tβ€ 1000) β the number of test cases. Next 2t lines contain descriptions of test cases.
The first line of each test case contains three integers n,x,y (1β€ nβ€ 10^5, 0β€ xβ€ yβ€ n) β the length of the codes, and two values Alice responds with.
The second line of each test case contains n integers b_1,β¦,b_n (1β€ b_iβ€ n+1) β Bob's guess, where b_i is the i-th color of the guess.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, on the first line, output "YES" if there is a solution, or "NO" if there is no possible secret code consistent with the described situation. You can print each character in any case (upper or lower).
If the answer is "YES", on the next line output n integers a_1,β¦,a_n (1β€ a_iβ€ n+1) β Alice's secret code, where a_i is the i-th color of the code.
If there are multiple solutions, output any.
Example
Input
7
5 2 4
3 1 1 2 5
5 3 4
1 1 2 1 2
4 0 4
5 5 3 3
4 1 4
2 3 2 3
6 1 2
3 2 1 1 1 1
6 2 4
3 3 2 1 1 1
6 2 6
1 1 3 2 1 1
Output
YES
3 1 6 1 2
YES
3 1 1 1 2
YES
3 3 5 5
NO
YES
4 4 4 4 3 1
YES
3 1 3 1 7 7
YES
2 3 1 1 1 1
Note
The first test case is described in the statement.
In the second test case, x=3 because the colors are equal at indices 2,4,5. And y=4 because they share the colors 1,1,1,2.
In the third test case, x=0 because there is no index where the colors are the same. But y=4 because they share the colors 3,3,5,5.
In the fourth test case, it can be proved that no solution exists. | instruction | 0 | 96,293 | 7 | 192,586 |
Tags: constructive algorithms, graph matchings, greedy, implementation, sortings, two pointers
Correct Solution:
```
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
#from decimal import Decimal
from fractions import Fraction
#sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1e9)+7
for t in range(int(data())):
n,x,y=mdata()
a=mdata()
d=dd(list)
for i in range(n):
d[a[i]].append(i)
q=[]
for i in d.keys():
heappush(q,[-len(d[i]),i])
ind=1
while d[ind]:
ind+=1
ans=[ind]*n
for i in range(x):
j,k=heappop(q)
i=d[k].pop()
ans[i]=a[i]
heappush(q, [-len(d[k]), k])
l1=[]
while q:
j, k = heappop(q)
l1+=d[k]
ind=0
flag=True
y-=x
n-=x
l1=l1[::-1]
while ind<y:
if a[l1[ind]]==a[l1[(n//2+ind)%n]]:
flag=False
break
ans[l1[ind]]=a[l1[(n//2+ind)%n]]
y-=1
if ind>=y:
break
ans[l1[ind+n//2+n%2]]=a[l1[ind]]
ind+=1
if flag==True:
out("YES")
outl(ans)
else:
out("NO")
``` | output | 1 | 96,293 | 7 | 192,587 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In the game of Mastermind, there are two players β Alice and Bob. Alice has a secret code, which Bob tries to guess. Here, a code is defined as a sequence of n colors. There are exactly n+1 colors in the entire universe, numbered from 1 to n+1 inclusive.
When Bob guesses a code, Alice tells him some information about how good of a guess it is, in the form of two integers x and y.
The first integer x is the number of indices where Bob's guess correctly matches Alice's code. The second integer y is the size of the intersection of the two codes as multisets. That is, if Bob were to change the order of the colors in his guess, y is the maximum number of indices he could get correct.
For example, suppose n=5, Alice's code is [3,1,6,1,2], and Bob's guess is [3,1,1,2,5]. At indices 1 and 2 colors are equal, while in the other indices they are not equal. So x=2. And the two codes have the four colors 1,1,2,3 in common, so y=4.
<image> Solid lines denote a matched color for the same index. Dashed lines denote a matched color at a different index. x is the number of solid lines, and y is the total number of lines.
You are given Bob's guess and two values x and y. Can you find one possibility of Alice's code so that the values of x and y are correct?
Input
The first line contains a single integer t (1β€ tβ€ 1000) β the number of test cases. Next 2t lines contain descriptions of test cases.
The first line of each test case contains three integers n,x,y (1β€ nβ€ 10^5, 0β€ xβ€ yβ€ n) β the length of the codes, and two values Alice responds with.
The second line of each test case contains n integers b_1,β¦,b_n (1β€ b_iβ€ n+1) β Bob's guess, where b_i is the i-th color of the guess.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, on the first line, output "YES" if there is a solution, or "NO" if there is no possible secret code consistent with the described situation. You can print each character in any case (upper or lower).
If the answer is "YES", on the next line output n integers a_1,β¦,a_n (1β€ a_iβ€ n+1) β Alice's secret code, where a_i is the i-th color of the code.
If there are multiple solutions, output any.
Example
Input
7
5 2 4
3 1 1 2 5
5 3 4
1 1 2 1 2
4 0 4
5 5 3 3
4 1 4
2 3 2 3
6 1 2
3 2 1 1 1 1
6 2 4
3 3 2 1 1 1
6 2 6
1 1 3 2 1 1
Output
YES
3 1 6 1 2
YES
3 1 1 1 2
YES
3 3 5 5
NO
YES
4 4 4 4 3 1
YES
3 1 3 1 7 7
YES
2 3 1 1 1 1
Note
The first test case is described in the statement.
In the second test case, x=3 because the colors are equal at indices 2,4,5. And y=4 because they share the colors 1,1,1,2.
In the third test case, x=0 because there is no index where the colors are the same. But y=4 because they share the colors 3,3,5,5.
In the fourth test case, it can be proved that no solution exists. | instruction | 0 | 96,294 | 7 | 192,588 |
Tags: constructive algorithms, graph matchings, greedy, implementation, sortings, two pointers
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
import heapq
t = int(stdin.readline())
for _ in range(t):
n, x, y = map(int, stdin.readline().split())
a = list(map(int, stdin.readline().split()))
unused = set(list(range(1, n+2))) - set(a)
r = list(unused)[0]
ans = [r]*n
c = Counter(a)
h = []
ilist = defaultdict(list)
for i, k in enumerate(a):
ilist[k].append(i)
for k in c:
v = c[k]
heapq.heappush(h, (-v, k))
for _ in range(x):
v, k = heapq.heappop(h)
idx = ilist[k].pop()
ans[idx] = k
if v+1 < 0:
heapq.heappush(h, (v+1, k))
todo = y-x
while todo > 0:
v1, k1 = heapq.heappop(h)
idx1 = ilist[k1].pop()
if not h:
if todo == 1:
for i in range(n):
if ans[i] != r and ans[i] != a[i] and ans[i] != k1:
ans[i], ans[idx1] = k1, ans[i]
if ans[i] == a[i] or ans[idx1] == a[idx1]:
ans[i], ans[idx1] = ans[idx1], ans[i]
continue
todo -= 1
break
break
v2, k2 = heapq.heappop(h)
idx2 = ilist[k2].pop()
if todo > 1:
ans[idx1], ans[idx2] = k2, k1
if v1+1 < 0:
heapq.heappush(h, (v1+1, k1))
if v2+1 < 0:
heapq.heappush(h, (v2+1, k2))
todo -= 2
else:
ans[idx1] = k2
todo -= 1
if todo > 0:
print("NO")
continue
print("YES")
print(" ".join(map(str, ans)))
``` | output | 1 | 96,294 | 7 | 192,589 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In the game of Mastermind, there are two players β Alice and Bob. Alice has a secret code, which Bob tries to guess. Here, a code is defined as a sequence of n colors. There are exactly n+1 colors in the entire universe, numbered from 1 to n+1 inclusive.
When Bob guesses a code, Alice tells him some information about how good of a guess it is, in the form of two integers x and y.
The first integer x is the number of indices where Bob's guess correctly matches Alice's code. The second integer y is the size of the intersection of the two codes as multisets. That is, if Bob were to change the order of the colors in his guess, y is the maximum number of indices he could get correct.
For example, suppose n=5, Alice's code is [3,1,6,1,2], and Bob's guess is [3,1,1,2,5]. At indices 1 and 2 colors are equal, while in the other indices they are not equal. So x=2. And the two codes have the four colors 1,1,2,3 in common, so y=4.
<image> Solid lines denote a matched color for the same index. Dashed lines denote a matched color at a different index. x is the number of solid lines, and y is the total number of lines.
You are given Bob's guess and two values x and y. Can you find one possibility of Alice's code so that the values of x and y are correct?
Input
The first line contains a single integer t (1β€ tβ€ 1000) β the number of test cases. Next 2t lines contain descriptions of test cases.
The first line of each test case contains three integers n,x,y (1β€ nβ€ 10^5, 0β€ xβ€ yβ€ n) β the length of the codes, and two values Alice responds with.
The second line of each test case contains n integers b_1,β¦,b_n (1β€ b_iβ€ n+1) β Bob's guess, where b_i is the i-th color of the guess.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, on the first line, output "YES" if there is a solution, or "NO" if there is no possible secret code consistent with the described situation. You can print each character in any case (upper or lower).
If the answer is "YES", on the next line output n integers a_1,β¦,a_n (1β€ a_iβ€ n+1) β Alice's secret code, where a_i is the i-th color of the code.
If there are multiple solutions, output any.
Example
Input
7
5 2 4
3 1 1 2 5
5 3 4
1 1 2 1 2
4 0 4
5 5 3 3
4 1 4
2 3 2 3
6 1 2
3 2 1 1 1 1
6 2 4
3 3 2 1 1 1
6 2 6
1 1 3 2 1 1
Output
YES
3 1 6 1 2
YES
3 1 1 1 2
YES
3 3 5 5
NO
YES
4 4 4 4 3 1
YES
3 1 3 1 7 7
YES
2 3 1 1 1 1
Note
The first test case is described in the statement.
In the second test case, x=3 because the colors are equal at indices 2,4,5. And y=4 because they share the colors 1,1,1,2.
In the third test case, x=0 because there is no index where the colors are the same. But y=4 because they share the colors 3,3,5,5.
In the fourth test case, it can be proved that no solution exists. | instruction | 0 | 96,295 | 7 | 192,590 |
Tags: constructive algorithms, graph matchings, greedy, implementation, sortings, two pointers
Correct Solution:
```
from sys import stdin
from collections import deque
from itertools import chain
input = stdin.readline
def getint(): return int(input())
def getints(): return list(map(int, input().split()))
def getint1(): return list(map(lambda x : int(x) - 1, input().split()))
def getstr(): return input()[:-1]
def solve():
n, x, y = getints()
a = getints()
# table = [[] for _ in range(n + 1)]
ind = [[] for _ in range(n + 2)]
for i, color in enumerate(a):
ind[color].append(i)
not_seen = 0
for i in range(1, n + 2):
if len(ind[i]) == 0:
not_seen = i
break
max_cnt = max(len(g) for g in ind)
# print(max_cnt)
table = [[] for _ in range(max_cnt + 1)]
for i, col in enumerate(ind[1:], 1):
if len(col) > 0:
table[len(col)].append(i)
# for t in table:
# print(t)
ans = [0] * n
for _ in range(x):
assert len(table[max_cnt]) > 0
color = table[max_cnt].pop()
assert len(ind[color]) > 0
i = ind[color].pop()
ans[i] = color
if max_cnt > 1:
table[max_cnt - 1].append(color)
if len(table[max_cnt]) == 0:
max_cnt -= 1
if 2 * max_cnt > 2 * n - x - y:
print("NO")
return
rest = list(chain(*ind))
to_change, offset, m = n - y, (n - x) >> 1, n - x
for i in range(m):
ans[rest[i]] = a[rest[(i + offset) % m]]
if ans[rest[i]] == a[rest[i]]:
ans[rest[i]] = not_seen
to_change -= 1
i = 0
while to_change > 0:
if ans[rest[i]] != not_seen:
ans[rest[i]] = not_seen
to_change -= 1
i += 1
print("YES")
print(*ans)
if __name__ == "__main__":
# solve()
# for t in range(getint()):
# print('Case #', t + 1, ': ', sep='')
# solve()
for _ in range(getint()):
solve()
``` | output | 1 | 96,295 | 7 | 192,591 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In the game of Mastermind, there are two players β Alice and Bob. Alice has a secret code, which Bob tries to guess. Here, a code is defined as a sequence of n colors. There are exactly n+1 colors in the entire universe, numbered from 1 to n+1 inclusive.
When Bob guesses a code, Alice tells him some information about how good of a guess it is, in the form of two integers x and y.
The first integer x is the number of indices where Bob's guess correctly matches Alice's code. The second integer y is the size of the intersection of the two codes as multisets. That is, if Bob were to change the order of the colors in his guess, y is the maximum number of indices he could get correct.
For example, suppose n=5, Alice's code is [3,1,6,1,2], and Bob's guess is [3,1,1,2,5]. At indices 1 and 2 colors are equal, while in the other indices they are not equal. So x=2. And the two codes have the four colors 1,1,2,3 in common, so y=4.
<image> Solid lines denote a matched color for the same index. Dashed lines denote a matched color at a different index. x is the number of solid lines, and y is the total number of lines.
You are given Bob's guess and two values x and y. Can you find one possibility of Alice's code so that the values of x and y are correct?
Input
The first line contains a single integer t (1β€ tβ€ 1000) β the number of test cases. Next 2t lines contain descriptions of test cases.
The first line of each test case contains three integers n,x,y (1β€ nβ€ 10^5, 0β€ xβ€ yβ€ n) β the length of the codes, and two values Alice responds with.
The second line of each test case contains n integers b_1,β¦,b_n (1β€ b_iβ€ n+1) β Bob's guess, where b_i is the i-th color of the guess.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, on the first line, output "YES" if there is a solution, or "NO" if there is no possible secret code consistent with the described situation. You can print each character in any case (upper or lower).
If the answer is "YES", on the next line output n integers a_1,β¦,a_n (1β€ a_iβ€ n+1) β Alice's secret code, where a_i is the i-th color of the code.
If there are multiple solutions, output any.
Example
Input
7
5 2 4
3 1 1 2 5
5 3 4
1 1 2 1 2
4 0 4
5 5 3 3
4 1 4
2 3 2 3
6 1 2
3 2 1 1 1 1
6 2 4
3 3 2 1 1 1
6 2 6
1 1 3 2 1 1
Output
YES
3 1 6 1 2
YES
3 1 1 1 2
YES
3 3 5 5
NO
YES
4 4 4 4 3 1
YES
3 1 3 1 7 7
YES
2 3 1 1 1 1
Note
The first test case is described in the statement.
In the second test case, x=3 because the colors are equal at indices 2,4,5. And y=4 because they share the colors 1,1,1,2.
In the third test case, x=0 because there is no index where the colors are the same. But y=4 because they share the colors 3,3,5,5.
In the fourth test case, it can be proved that no solution exists. | instruction | 0 | 96,296 | 7 | 192,592 |
Tags: constructive algorithms, graph matchings, greedy, implementation, sortings, two pointers
Correct Solution:
```
import collections
t = int(input())
for _ in range(t):
# print('time', _)
n, x, y = map(int, input().split())
b = [int(i) for i in input().split()]
if x == n:
print("YES")
for i in b:
print(i, end = ' ')
print()
continue
setB = set(b)
noin = 1
while noin in setB:
noin += 1
cnt = collections.deque([i, j] for i, j in collections.Counter(b).most_common())
cnt2 = collections.deque()
pos = [set() for _ in range(n + 2)]
for i in range(len(b)):
pos[b[i]].add(i)
res=[-1] * n
l = x
while l > 0:
i = cnt.popleft()
i[1] -= 1
if i[1] != 0:
cnt2.appendleft(i)
while not cnt or cnt2 and cnt2[0][1] >= cnt[0][1]:
cnt.appendleft(cnt2.popleft())
p = pos[i[0]].pop()
res[p] = i[0]
l -= 1
ml = cnt[0][1]
remain = []
while cnt:
i, j = cnt.popleft()
remain += [i] * j
while cnt2:
i, j =cnt2.popleft()
remain += [i] * j
if y - x > (len(remain) - ml) * 2 :
print('No')
continue
i = 0
match = [0] * len(remain)
for i in range(ml, ml + y - x):
match[i % len(remain)] = remain[(i + ml) % len(remain)]
for i in range(ml + y - x, ml + len(remain)):
match[i % len(remain)] = noin
# print(match, remain)
for i in range(len(match)):
p = pos[remain[i]].pop()
res[p] = match[i]
if l == 0:
print("YES")
for i in res:
print(i, end=' ')
print()
else:
print("No")
``` | output | 1 | 96,296 | 7 | 192,593 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In the game of Mastermind, there are two players β Alice and Bob. Alice has a secret code, which Bob tries to guess. Here, a code is defined as a sequence of n colors. There are exactly n+1 colors in the entire universe, numbered from 1 to n+1 inclusive.
When Bob guesses a code, Alice tells him some information about how good of a guess it is, in the form of two integers x and y.
The first integer x is the number of indices where Bob's guess correctly matches Alice's code. The second integer y is the size of the intersection of the two codes as multisets. That is, if Bob were to change the order of the colors in his guess, y is the maximum number of indices he could get correct.
For example, suppose n=5, Alice's code is [3,1,6,1,2], and Bob's guess is [3,1,1,2,5]. At indices 1 and 2 colors are equal, while in the other indices they are not equal. So x=2. And the two codes have the four colors 1,1,2,3 in common, so y=4.
<image> Solid lines denote a matched color for the same index. Dashed lines denote a matched color at a different index. x is the number of solid lines, and y is the total number of lines.
You are given Bob's guess and two values x and y. Can you find one possibility of Alice's code so that the values of x and y are correct?
Input
The first line contains a single integer t (1β€ tβ€ 1000) β the number of test cases. Next 2t lines contain descriptions of test cases.
The first line of each test case contains three integers n,x,y (1β€ nβ€ 10^5, 0β€ xβ€ yβ€ n) β the length of the codes, and two values Alice responds with.
The second line of each test case contains n integers b_1,β¦,b_n (1β€ b_iβ€ n+1) β Bob's guess, where b_i is the i-th color of the guess.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, on the first line, output "YES" if there is a solution, or "NO" if there is no possible secret code consistent with the described situation. You can print each character in any case (upper or lower).
If the answer is "YES", on the next line output n integers a_1,β¦,a_n (1β€ a_iβ€ n+1) β Alice's secret code, where a_i is the i-th color of the code.
If there are multiple solutions, output any.
Example
Input
7
5 2 4
3 1 1 2 5
5 3 4
1 1 2 1 2
4 0 4
5 5 3 3
4 1 4
2 3 2 3
6 1 2
3 2 1 1 1 1
6 2 4
3 3 2 1 1 1
6 2 6
1 1 3 2 1 1
Output
YES
3 1 6 1 2
YES
3 1 1 1 2
YES
3 3 5 5
NO
YES
4 4 4 4 3 1
YES
3 1 3 1 7 7
YES
2 3 1 1 1 1
Note
The first test case is described in the statement.
In the second test case, x=3 because the colors are equal at indices 2,4,5. And y=4 because they share the colors 1,1,1,2.
In the third test case, x=0 because there is no index where the colors are the same. But y=4 because they share the colors 3,3,5,5.
In the fourth test case, it can be proved that no solution exists. | instruction | 0 | 96,297 | 7 | 192,594 |
Tags: constructive algorithms, graph matchings, greedy, implementation, sortings, two pointers
Correct Solution:
```
from sys import stdin, stdout
import heapq
# 5 3 4
# 1 1 2 1 2
# 3 1 1 1 2
# 1 1 2 1 2
# 4 1 4
# 2 3 2 3
# 2 2 3 3
# 1 2 1 2
# 0 2 1 3
# 1 3 0 2
def Mastermind(n, x, y, b_a):
ans = [-1] * n
# find mex
b_s = set(b_a)
mex = 1
while mex in b_s:
mex += 1
#print(mex)
# get frequency
fq_d = {}
for i in range(len(b_a)):
if b_a[i] not in fq_d:
fq_d[b_a[i]] = []
fq_d[b_a[i]].append(i)
fq_h = []
for key in fq_d:
heapq.heappush(fq_h, (-len(fq_d[key]), key, fq_d[key]))
#print(fq_h)
for _ in range(x):
l, v, f_a = heapq.heappop(fq_h)
ans[f_a.pop()] = v
l += 1
if l < 0:
heapq.heappush(fq_h, (l, v, f_a))
#print(ans)
if x == n:
return ans
z = n - y
shift_a = []
for fq in fq_h:
for idx in fq[2]:
shift_a.append([idx, fq[1]])
#print(shift_a)
offset = -fq_h[0][0]
#print(offset)
idx_a = []
for i in range(len(shift_a)):
shift = shift_a[i]
nidx = (i + offset) % (n - x)
#print(shift[1])
#print(shift_a[nidx][0])
nv = shift_a[nidx][1]
if shift[1] == nv:
if z == 0:
return []
z -= 1
ans[shift_a[nidx][0]] = mex
else:
idx_a.append(shift_a[nidx][0])
ans[shift_a[nidx][0]] = shift[1]
while z > 0:
if not idx_a:
return []
ans[idx_a.pop()] = mex
z -= 1
return ans
t = int(stdin.readline())
for _ in range(t):
n, x, y = map(int, stdin.readline().split())
b_a = list(map(int, stdin.readline().split()))
ans = Mastermind(n, x, y, b_a)
if ans:
stdout.write('Yes\n')
stdout.write(' '.join(map(str, ans)) + '\n')
else:
stdout.write('No\n')
``` | output | 1 | 96,297 | 7 | 192,595 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In the game of Mastermind, there are two players β Alice and Bob. Alice has a secret code, which Bob tries to guess. Here, a code is defined as a sequence of n colors. There are exactly n+1 colors in the entire universe, numbered from 1 to n+1 inclusive.
When Bob guesses a code, Alice tells him some information about how good of a guess it is, in the form of two integers x and y.
The first integer x is the number of indices where Bob's guess correctly matches Alice's code. The second integer y is the size of the intersection of the two codes as multisets. That is, if Bob were to change the order of the colors in his guess, y is the maximum number of indices he could get correct.
For example, suppose n=5, Alice's code is [3,1,6,1,2], and Bob's guess is [3,1,1,2,5]. At indices 1 and 2 colors are equal, while in the other indices they are not equal. So x=2. And the two codes have the four colors 1,1,2,3 in common, so y=4.
<image> Solid lines denote a matched color for the same index. Dashed lines denote a matched color at a different index. x is the number of solid lines, and y is the total number of lines.
You are given Bob's guess and two values x and y. Can you find one possibility of Alice's code so that the values of x and y are correct?
Input
The first line contains a single integer t (1β€ tβ€ 1000) β the number of test cases. Next 2t lines contain descriptions of test cases.
The first line of each test case contains three integers n,x,y (1β€ nβ€ 10^5, 0β€ xβ€ yβ€ n) β the length of the codes, and two values Alice responds with.
The second line of each test case contains n integers b_1,β¦,b_n (1β€ b_iβ€ n+1) β Bob's guess, where b_i is the i-th color of the guess.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, on the first line, output "YES" if there is a solution, or "NO" if there is no possible secret code consistent with the described situation. You can print each character in any case (upper or lower).
If the answer is "YES", on the next line output n integers a_1,β¦,a_n (1β€ a_iβ€ n+1) β Alice's secret code, where a_i is the i-th color of the code.
If there are multiple solutions, output any.
Example
Input
7
5 2 4
3 1 1 2 5
5 3 4
1 1 2 1 2
4 0 4
5 5 3 3
4 1 4
2 3 2 3
6 1 2
3 2 1 1 1 1
6 2 4
3 3 2 1 1 1
6 2 6
1 1 3 2 1 1
Output
YES
3 1 6 1 2
YES
3 1 1 1 2
YES
3 3 5 5
NO
YES
4 4 4 4 3 1
YES
3 1 3 1 7 7
YES
2 3 1 1 1 1
Note
The first test case is described in the statement.
In the second test case, x=3 because the colors are equal at indices 2,4,5. And y=4 because they share the colors 1,1,1,2.
In the third test case, x=0 because there is no index where the colors are the same. But y=4 because they share the colors 3,3,5,5.
In the fourth test case, it can be proved that no solution exists. | instruction | 0 | 96,298 | 7 | 192,596 |
Tags: constructive algorithms, graph matchings, greedy, implementation, sortings, two pointers
Correct Solution:
```
from heapq import *
from collections import Counter
import sys
sys.setrecursionlimit(10 ** 5)
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]
for _ in range(II()):
ng=False
n,x,y=MI()
bb=LI()
use=[False]*(n+1)
for b in bb:use[b-1]=True
unuse=0
for b in range(1,n+2):
if use[b-1]==False:
unuse=b
break
aa=[unuse]*n
cnt=[[] for _ in range(n+2)]
for i,b in enumerate(bb):
cnt[b].append(i)
#print(cnt)
hp=[]
for b,ii in enumerate(cnt):
if not ii:continue
heappush(hp,[-len(ii)]+[b]+ii)
#print(hp)
if (y-x)%2:
if len(hp)>2 and y-x>2:
ii0=heappop(hp)
ii1=heappop(hp)
ii2=heappop(hp)
b0=ii0[1]
b1=ii1[1]
b2=ii2[1]
i0=ii0.pop()
i1=ii1.pop()
i2=ii2.pop()
ii0[0]+=1
ii1[0]+=1
ii2[0]+=1
if ii0[0]<0:heappush(hp,ii0)
if ii1[0]<0:heappush(hp,ii1)
if ii2[0]<0:heappush(hp,ii2)
aa[i0]=b1
aa[i1]=b2
aa[i2]=b0
y-=3
elif len(hp)>1:
ii0=heappop(hp)
ii1=heappop(hp)
b0=ii0[1]
b1=ii1[1]
i0=ii0.pop()
i1=ii1.pop()
ii0[0]+=1
ii1[0]+=1
if ii0[0]<0:heappush(hp,ii0)
if ii1[0]<0:heappush(hp,ii1)
aa[i0]=b1
y-=1
else:
print("NO")
continue
for _ in range((y-x)//2):
if len(hp)<2:
ng=True
break
ii0 = heappop(hp)
ii1 = heappop(hp)
b0 = ii0[1]
b1 = ii1[1]
i0 = ii0.pop()
i1 = ii1.pop()
ii0[0] += 1
ii1[0] += 1
if ii0[0] < 0: heappush(hp, ii0)
if ii1[0] < 0: heappush(hp, ii1)
aa[i0] = b1
aa[i1] = b0
if ng:
print("NO")
continue
ii0=[]
for _ in range(x):
if len(ii0)<3:
if not hp:
ng=True
break
else:
ii0 = heappop(hp)
b0 = ii0[1]
i0 = ii0.pop()
aa[i0] = b0
if ng:
print("NO")
continue
print("YES")
print(*aa)
``` | output | 1 | 96,298 | 7 | 192,597 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In the game of Mastermind, there are two players β Alice and Bob. Alice has a secret code, which Bob tries to guess. Here, a code is defined as a sequence of n colors. There are exactly n+1 colors in the entire universe, numbered from 1 to n+1 inclusive.
When Bob guesses a code, Alice tells him some information about how good of a guess it is, in the form of two integers x and y.
The first integer x is the number of indices where Bob's guess correctly matches Alice's code. The second integer y is the size of the intersection of the two codes as multisets. That is, if Bob were to change the order of the colors in his guess, y is the maximum number of indices he could get correct.
For example, suppose n=5, Alice's code is [3,1,6,1,2], and Bob's guess is [3,1,1,2,5]. At indices 1 and 2 colors are equal, while in the other indices they are not equal. So x=2. And the two codes have the four colors 1,1,2,3 in common, so y=4.
<image> Solid lines denote a matched color for the same index. Dashed lines denote a matched color at a different index. x is the number of solid lines, and y is the total number of lines.
You are given Bob's guess and two values x and y. Can you find one possibility of Alice's code so that the values of x and y are correct?
Input
The first line contains a single integer t (1β€ tβ€ 1000) β the number of test cases. Next 2t lines contain descriptions of test cases.
The first line of each test case contains three integers n,x,y (1β€ nβ€ 10^5, 0β€ xβ€ yβ€ n) β the length of the codes, and two values Alice responds with.
The second line of each test case contains n integers b_1,β¦,b_n (1β€ b_iβ€ n+1) β Bob's guess, where b_i is the i-th color of the guess.
It is guaranteed that the sum of n across all test cases does not exceed 10^5.
Output
For each test case, on the first line, output "YES" if there is a solution, or "NO" if there is no possible secret code consistent with the described situation. You can print each character in any case (upper or lower).
If the answer is "YES", on the next line output n integers a_1,β¦,a_n (1β€ a_iβ€ n+1) β Alice's secret code, where a_i is the i-th color of the code.
If there are multiple solutions, output any.
Example
Input
7
5 2 4
3 1 1 2 5
5 3 4
1 1 2 1 2
4 0 4
5 5 3 3
4 1 4
2 3 2 3
6 1 2
3 2 1 1 1 1
6 2 4
3 3 2 1 1 1
6 2 6
1 1 3 2 1 1
Output
YES
3 1 6 1 2
YES
3 1 1 1 2
YES
3 3 5 5
NO
YES
4 4 4 4 3 1
YES
3 1 3 1 7 7
YES
2 3 1 1 1 1
Note
The first test case is described in the statement.
In the second test case, x=3 because the colors are equal at indices 2,4,5. And y=4 because they share the colors 1,1,1,2.
In the third test case, x=0 because there is no index where the colors are the same. But y=4 because they share the colors 3,3,5,5.
In the fourth test case, it can be proved that no solution exists. | instruction | 0 | 96,299 | 7 | 192,598 |
Tags: constructive algorithms, graph matchings, greedy, implementation, sortings, two pointers
Correct Solution:
```
from collections import defaultdict
from heapq import heapify, heappop, heappush
def solve():
n, s, y = map(int, input().split())
a = input().split()
d = defaultdict(list)
for i, x in enumerate(a):
d[x].append(i)
for i in range(1, n + 2):
e = str(i)
if e not in d:
break
q = [(-len(d[x]), x) for x in d.keys()]
heapify(q)
ans = [0] * n
for i in range(s):
l, x = heappop(q)
ans[d[x].pop()] = x
l += 1
if l:
heappush(q, (l, x))
p = []
while q:
l, x = heappop(q)
p.extend(d[x])
if p:
h = (n - s) // 2
y = n - y
q = p[h:] + p[:h]
for x, z in zip(p, q):
if a[x] == a[z]:
if y:ans[x] = e;y -= 1
else:print("NO");return
else:ans[x] = a[z]
for i in range(n - s):
if y and ans[p[i]] != e:ans[p[i]] = e;y -= 1
print("YES");print(' '.join(ans))
for t in range(int(input())):solve()
``` | output | 1 | 96,299 | 7 | 192,599 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've gotten an n Γ m sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as A. Set A is connected. Your task is to find the minimum number of squares that we can delete from set A to make it not connected.
A set of painted squares is called connected, if for every two squares a and b from this set there is a sequence of squares from the set, beginning in a and ending in b, such that in this sequence any square, except for the last one, shares a common side with the square that follows next in the sequence. An empty set and a set consisting of exactly one square are connected by definition.
Input
The first input line contains two space-separated integers n and m (1 β€ n, m β€ 50) β the sizes of the sheet of paper.
Each of the next n lines contains m characters β the description of the sheet of paper: the j-th character of the i-th line equals either "#", if the corresponding square is painted (belongs to set A), or equals "." if the corresponding square is not painted (does not belong to set A). It is guaranteed that the set of all painted squares A is connected and isn't empty.
Output
On the first line print the minimum number of squares that need to be deleted to make set A not connected. If it is impossible, print -1.
Examples
Input
5 4
####
#..#
#..#
#..#
####
Output
2
Input
5 5
#####
#...#
#####
#...#
#####
Output
2
Note
In the first sample you can delete any two squares that do not share a side. After that the set of painted squares is not connected anymore.
The note to the second sample is shown on the figure below. To the left there is a picture of the initial set of squares. To the right there is a set with deleted squares. The deleted squares are marked with crosses.
<image> | instruction | 0 | 96,388 | 7 | 192,776 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
n, m = map(int, input().split())
a = [list(input()) for i in range(n)]
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
def valid(x, y):
return 0 <= x < n and 0 <= y < m
def d():
cnt, p = 0, -1
for i in range(n):
for j in range(m):
if a[i][j] == '#':
cnt += 1
p = (i, j)
if p == -1:
return False
vis = [[0]*m for _ in range(n)]
vis[p[0]][p[1]] = 1
cnt_vis = 1
stk = [(p[0], p[1])]
while stk:
x, y = stk.pop()
for dx, dy in dirs:
nx = x + dx
ny = y + dy
if valid(nx, ny) and not vis[nx][ny] and a[nx][ny] == '#':
vis[nx][ny] = 1
cnt_vis += 1
stk.append((nx, ny))
return cnt_vis != cnt
cnt, flag = 0, 0
f = False
for i in range(n):
for j in range(m):
if a[i][j] == '.':
continue
cnt += 1
a[i][j] = '.'
if d(): flag = True
a[i][j] = '#'
if cnt <= 2:
print(-1)
elif flag:
print(1)
else:
print(2)
``` | output | 1 | 96,388 | 7 | 192,777 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've gotten an n Γ m sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as A. Set A is connected. Your task is to find the minimum number of squares that we can delete from set A to make it not connected.
A set of painted squares is called connected, if for every two squares a and b from this set there is a sequence of squares from the set, beginning in a and ending in b, such that in this sequence any square, except for the last one, shares a common side with the square that follows next in the sequence. An empty set and a set consisting of exactly one square are connected by definition.
Input
The first input line contains two space-separated integers n and m (1 β€ n, m β€ 50) β the sizes of the sheet of paper.
Each of the next n lines contains m characters β the description of the sheet of paper: the j-th character of the i-th line equals either "#", if the corresponding square is painted (belongs to set A), or equals "." if the corresponding square is not painted (does not belong to set A). It is guaranteed that the set of all painted squares A is connected and isn't empty.
Output
On the first line print the minimum number of squares that need to be deleted to make set A not connected. If it is impossible, print -1.
Examples
Input
5 4
####
#..#
#..#
#..#
####
Output
2
Input
5 5
#####
#...#
#####
#...#
#####
Output
2
Note
In the first sample you can delete any two squares that do not share a side. After that the set of painted squares is not connected anymore.
The note to the second sample is shown on the figure below. To the left there is a picture of the initial set of squares. To the right there is a set with deleted squares. The deleted squares are marked with crosses.
<image> | instruction | 0 | 96,389 | 7 | 192,778 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
def add(vertex,neighbour):
if vertex in graph:
graph[vertex].append(neighbour)
else:
graph[vertex]=[neighbour]
if neighbour in graph: #####for undirected part remove to get directed
graph[neighbour].append(vertex)
else:
graph[neighbour]=[vertex]
def dfs(graph,n,currnode):
visited=[False for x in range(n+1)]
stack=[currnode]
ans=[]
while stack:
currnode=stack[-1]
if visited[currnode]==False:
visited[currnode]=True
ans.append(currnode)
if currnode in graph1:
for neighbour in graph[currnode]:
if visited[neighbour]==False:
visited[neighbour]=True
stack.append(neighbour)
ans.append(neighbour)
break #####if we remove break it becomes bfs
else:
stack.pop() ####we are backtracking to previous node which is in our stack
else:
stack.pop()
return ans
n,m=[int(x) for x in input().split()]
nodes=n*m
arr=[None for i in range(nodes)]
for i in range(n):
s=input()
for j in range(m):
arr[i*m+j]=s[j]
graph={}
for i in range(m,nodes):
if i%m!=0 and arr[i]=="#":
if arr[i-1]=="#":
add(i,i-1)
r=i//m;c=i%m
if arr[(r-1)*m+c]=="#":
add(i,(r-1)*m+c)
elif i%m==0 and arr[i]=="#":
#if arr[i+1]=="#":
#add(i,i+1)
r=i//m
if arr[(r-1)*m]=="#":
add((r-1)*m,i)
for i in range(1,m):
if arr[i]=="#" and arr[i-1]=="#":
add(i,i-1)
for i in range(nodes):
if arr[i]=="#" and i not in graph:
graph[i]=[]
graph1=graph.copy()
if len(graph)<3:
print(-1)
else:
found=False
firstnode=[];secondnnode=[]
for key,val in graph.items():
if len(firstnode)==0:
firstnode=[key,val]
d=len(dfs(graph,nodes,firstnode[0]))
elif len(secondnnode)==0:
secondnnode=[key,val]
else:
del graph1[key]
if len(dfs(graph1,nodes,firstnode[0]))-1!=d-1:
found=True
break
graph1[key]=val
else:
del graph1[firstnode[0]]
if len(dfs(graph1,nodes,secondnnode[0]))-1!=d-1:
found=True
graph1[firstnode[0]]=firstnode[1]
del graph1[secondnnode[0]]
if len(dfs(graph1,nodes,firstnode[0]))-1!=d-1:
found=True
graph1[secondnnode[0]]=secondnnode[1]
if found==True:
print(1)
else:
print(2)
``` | output | 1 | 96,389 | 7 | 192,779 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've gotten an n Γ m sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as A. Set A is connected. Your task is to find the minimum number of squares that we can delete from set A to make it not connected.
A set of painted squares is called connected, if for every two squares a and b from this set there is a sequence of squares from the set, beginning in a and ending in b, such that in this sequence any square, except for the last one, shares a common side with the square that follows next in the sequence. An empty set and a set consisting of exactly one square are connected by definition.
Input
The first input line contains two space-separated integers n and m (1 β€ n, m β€ 50) β the sizes of the sheet of paper.
Each of the next n lines contains m characters β the description of the sheet of paper: the j-th character of the i-th line equals either "#", if the corresponding square is painted (belongs to set A), or equals "." if the corresponding square is not painted (does not belong to set A). It is guaranteed that the set of all painted squares A is connected and isn't empty.
Output
On the first line print the minimum number of squares that need to be deleted to make set A not connected. If it is impossible, print -1.
Examples
Input
5 4
####
#..#
#..#
#..#
####
Output
2
Input
5 5
#####
#...#
#####
#...#
#####
Output
2
Note
In the first sample you can delete any two squares that do not share a side. After that the set of painted squares is not connected anymore.
The note to the second sample is shown on the figure below. To the left there is a picture of the initial set of squares. To the right there is a set with deleted squares. The deleted squares are marked with crosses.
<image> | instruction | 0 | 96,390 | 7 | 192,780 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
n, m = map(int, input().split())
p, s = [], {}
for i in range(n):
t = [j for j, q in enumerate(input()) if q == '#']
for j in t:
s[(i, j)] = x = len(s)
p += [[]]
for q in [(i, j - 1), (i - 1, j)]:
if q in s:
y = s[q]
p[x] += [y]
p[y] += [x]
k = len(p)
if k < 3:
print(-1)
exit()
for j in range(k):
d = [1] * k
d[j] = 0
s = [p[j][0]]
while s:
j = s.pop()
if not d[j]: continue
d[j] = 0
for i in p[j]:
if d[i]: s.append(i)
if 1 in d:
print(1)
exit()
print(2)
``` | output | 1 | 96,390 | 7 | 192,781 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've gotten an n Γ m sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as A. Set A is connected. Your task is to find the minimum number of squares that we can delete from set A to make it not connected.
A set of painted squares is called connected, if for every two squares a and b from this set there is a sequence of squares from the set, beginning in a and ending in b, such that in this sequence any square, except for the last one, shares a common side with the square that follows next in the sequence. An empty set and a set consisting of exactly one square are connected by definition.
Input
The first input line contains two space-separated integers n and m (1 β€ n, m β€ 50) β the sizes of the sheet of paper.
Each of the next n lines contains m characters β the description of the sheet of paper: the j-th character of the i-th line equals either "#", if the corresponding square is painted (belongs to set A), or equals "." if the corresponding square is not painted (does not belong to set A). It is guaranteed that the set of all painted squares A is connected and isn't empty.
Output
On the first line print the minimum number of squares that need to be deleted to make set A not connected. If it is impossible, print -1.
Examples
Input
5 4
####
#..#
#..#
#..#
####
Output
2
Input
5 5
#####
#...#
#####
#...#
#####
Output
2
Note
In the first sample you can delete any two squares that do not share a side. After that the set of painted squares is not connected anymore.
The note to the second sample is shown on the figure below. To the left there is a picture of the initial set of squares. To the right there is a set with deleted squares. The deleted squares are marked with crosses.
<image> | instruction | 0 | 96,391 | 7 | 192,782 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
from sys import stdin, stdout
n, m = map(int, stdin.readline().split())
step = [(-1, 0), (1, 0), (0, -1), (0, 1)]
ans = float('inf')
challengers = []
counting = 0
maps = []
def check(s, c):
return n > s >= 0 and m > c >= 0 and maps[s][c] == '#'
def checkfirst():
for i in range(min(len(challengers), 1000)):
visit = [[0 for j in range(m)] for i in range(n)]
s, c = challengers[i]
maps[s][c] = '.'
if i != 0:
visit[challengers[0][0]][challengers[0][1]] = 1
queue = []
queue.append(challengers[0])
else:
visit[challengers[1][0]][challengers[1][1]] = 1
queue = []
queue.append(challengers[1])
h, t = 0, 1
while h != t:
s, c = queue[h]
h += 1
for a, b in step:
if check(s + a, c + b) and not visit[s + a][c + b]:
visit[s + a][c + b] = 1
queue.append((s + a, c + b))
t += 1
for i1 in range(n):
for j1 in range(m):
if maps[i1][j1] == '#' and not visit[i1][j1]:
return 1
s, c = challengers[i]
maps[s][c] = '#'
else:
return 0
for i in range(n):
maps.append(list(stdin.readline().strip()))
counting += maps[-1].count('#')
for j in range(m):
if maps[i][j] == '#':
challengers.append((i, j))
if counting < 3:
stdout.write('-1')
else:
if checkfirst():
stdout.write('1')
else:
stdout.write('2')
``` | output | 1 | 96,391 | 7 | 192,783 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've gotten an n Γ m sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as A. Set A is connected. Your task is to find the minimum number of squares that we can delete from set A to make it not connected.
A set of painted squares is called connected, if for every two squares a and b from this set there is a sequence of squares from the set, beginning in a and ending in b, such that in this sequence any square, except for the last one, shares a common side with the square that follows next in the sequence. An empty set and a set consisting of exactly one square are connected by definition.
Input
The first input line contains two space-separated integers n and m (1 β€ n, m β€ 50) β the sizes of the sheet of paper.
Each of the next n lines contains m characters β the description of the sheet of paper: the j-th character of the i-th line equals either "#", if the corresponding square is painted (belongs to set A), or equals "." if the corresponding square is not painted (does not belong to set A). It is guaranteed that the set of all painted squares A is connected and isn't empty.
Output
On the first line print the minimum number of squares that need to be deleted to make set A not connected. If it is impossible, print -1.
Examples
Input
5 4
####
#..#
#..#
#..#
####
Output
2
Input
5 5
#####
#...#
#####
#...#
#####
Output
2
Note
In the first sample you can delete any two squares that do not share a side. After that the set of painted squares is not connected anymore.
The note to the second sample is shown on the figure below. To the left there is a picture of the initial set of squares. To the right there is a set with deleted squares. The deleted squares are marked with crosses.
<image> | instruction | 0 | 96,392 | 7 | 192,784 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
n, m = map(int, input().split())
p, s = [], {}
x = 0
for i in range(n):
for j, q in enumerate(input()):
if q != '#': continue
s[(i, j)] = x
p.append([])
if (i, j - 1) in s:
p[x] += [x - 1]
p[x - 1] += [x]
if (i - 1, j) in s:
y = s[(i - 1, j)]
p[x] += [y]
p[y] += [x]
x += 1
k = len(p)
if k < 3:
print(-1)
exit()
for j in range(k):
d = [1] * k
d[j] = 0
s = [p[j][0]]
while s:
j = s.pop()
if not d[j]: continue
d[j] = 0
for i in p[j]:
if d[i]: s.append(i)
if 1 in d:
print(1)
break
else:
print(2)
``` | output | 1 | 96,392 | 7 | 192,785 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've gotten an n Γ m sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as A. Set A is connected. Your task is to find the minimum number of squares that we can delete from set A to make it not connected.
A set of painted squares is called connected, if for every two squares a and b from this set there is a sequence of squares from the set, beginning in a and ending in b, such that in this sequence any square, except for the last one, shares a common side with the square that follows next in the sequence. An empty set and a set consisting of exactly one square are connected by definition.
Input
The first input line contains two space-separated integers n and m (1 β€ n, m β€ 50) β the sizes of the sheet of paper.
Each of the next n lines contains m characters β the description of the sheet of paper: the j-th character of the i-th line equals either "#", if the corresponding square is painted (belongs to set A), or equals "." if the corresponding square is not painted (does not belong to set A). It is guaranteed that the set of all painted squares A is connected and isn't empty.
Output
On the first line print the minimum number of squares that need to be deleted to make set A not connected. If it is impossible, print -1.
Examples
Input
5 4
####
#..#
#..#
#..#
####
Output
2
Input
5 5
#####
#...#
#####
#...#
#####
Output
2
Note
In the first sample you can delete any two squares that do not share a side. After that the set of painted squares is not connected anymore.
The note to the second sample is shown on the figure below. To the left there is a picture of the initial set of squares. To the right there is a set with deleted squares. The deleted squares are marked with crosses.
<image> | instruction | 0 | 96,393 | 7 | 192,786 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
n, m = map(int, input().split())
a = [list(input()) for i in range(n)]
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
def valid(x, y):
return 0 <= x < n and 0 <= y < m
def dfs():
cnt, p = 0, -1
for i in range(n):
for j in range(m):
if a[i][j] == '#':
cnt += 1
p = (i, j)
if p == -1:
return False
vis = [[0]*m for _ in range(n)]
vis[p[0]][p[1]] = 1
cnt_vis = 1
stk = [(p[0], p[1])]
while stk:
x, y = stk.pop()
for dx, dy in dirs:
nx = x + dx
ny = y + dy
if valid(nx, ny) and not vis[nx][ny] and a[nx][ny] == '#':
vis[nx][ny] = 1
cnt_vis += 1
stk.append((nx, ny))
return cnt_vis != cnt
cnt, flag = 0, 0
f = False
for i in range(n):
for j in range(m):
if a[i][j] == '.':
continue
cnt += 1
a[i][j] = '.'
if dfs(): flag = True
a[i][j] = '#'
if cnt <= 2:
print(-1)
elif flag:
print(1)
else:
print(2)
``` | output | 1 | 96,393 | 7 | 192,787 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've gotten an n Γ m sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as A. Set A is connected. Your task is to find the minimum number of squares that we can delete from set A to make it not connected.
A set of painted squares is called connected, if for every two squares a and b from this set there is a sequence of squares from the set, beginning in a and ending in b, such that in this sequence any square, except for the last one, shares a common side with the square that follows next in the sequence. An empty set and a set consisting of exactly one square are connected by definition.
Input
The first input line contains two space-separated integers n and m (1 β€ n, m β€ 50) β the sizes of the sheet of paper.
Each of the next n lines contains m characters β the description of the sheet of paper: the j-th character of the i-th line equals either "#", if the corresponding square is painted (belongs to set A), or equals "." if the corresponding square is not painted (does not belong to set A). It is guaranteed that the set of all painted squares A is connected and isn't empty.
Output
On the first line print the minimum number of squares that need to be deleted to make set A not connected. If it is impossible, print -1.
Examples
Input
5 4
####
#..#
#..#
#..#
####
Output
2
Input
5 5
#####
#...#
#####
#...#
#####
Output
2
Note
In the first sample you can delete any two squares that do not share a side. After that the set of painted squares is not connected anymore.
The note to the second sample is shown on the figure below. To the left there is a picture of the initial set of squares. To the right there is a set with deleted squares. The deleted squares are marked with crosses.
<image> | instruction | 0 | 96,394 | 7 | 192,788 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
import os,io
from sys import stdout
import collections
import random
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import sys
sys.setrecursionlimit(10000)
def binomial_coefficient(n, k):
if 0 <= k <= n:
ntok = 1
ktok = 1
for t in range(1, min(k, n - k) + 1):
ntok *= n
ktok *= t
n -= 1
return ntok // ktok
else:
return 0
def powerOfK(k, max):
if k == 1:
return [1]
if k == -1:
return [-1, 1]
result = []
n = 1
while n <= max:
result.append(n)
n *= k
return result
def prefixSum(arr):
for i in range(1, len(arr)):
arr[i] = arr[i] + arr[i-1]
return arr
def moves():
x = [0, 0, 1, -1]
y = [1, -1, 0, 0]
return list(zip(x, y))
n, m = list(map(int, input().split()))
grid = []
for _ in range(n):
grid.append(list(input().strip().decode("utf-8")))
def shortestPath(grid, nx1, ny1, nx2, ny2):
queue = [(nx1, ny1)]
visited = set()
while len(queue):
c = queue.pop(0)
if c in visited:
continue
visited.add(c)
if c == (nx2, ny2):
return True
for x, y in moves():
nx = x + c[0]
ny = y + c[1]
if nx >= 0 and nx < n and ny >= 0 and ny <m and grid[nx][ny] == '#':
queue.append((nx, ny))
return False
def hasPath(grid, i, j, n , m):
for x1, y1 in moves():
nx1, ny1 = x1+i, y1+j
if not(nx1 >= 0 and nx1 < n and ny1 >= 0 and ny1 <m):
continue
for x2, y2 in moves():
nx2, ny2 = x2+i, y2+j
if not(nx2 >= 0 and nx2 < n and ny2 >= 0 and ny2 <m):
continue
if (nx1, ny1) != (nx2, ny2) and grid[nx1][ny1] == '#' and grid[nx2][ny2] == '#':
if not shortestPath(grid, nx1, ny1, nx2, ny2):
return False
return True
def oneDeletion(grid, n, m):
for i in range(n):
for j in range(m):
if grid[i][j] == '#':
grid[i][j] = '.'
if not hasPath(grid, i, j, n, m):
return True
grid[i][j] = '#'
return False
hash = 0
for i in range(n):
for j in range(m):
if grid[i][j] == '#':
hash+=1
if hash <= 2:
print(-1)
elif oneDeletion(grid, n, m):
print(1)
else:
print(2)
``` | output | 1 | 96,394 | 7 | 192,789 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've gotten an n Γ m sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as A. Set A is connected. Your task is to find the minimum number of squares that we can delete from set A to make it not connected.
A set of painted squares is called connected, if for every two squares a and b from this set there is a sequence of squares from the set, beginning in a and ending in b, such that in this sequence any square, except for the last one, shares a common side with the square that follows next in the sequence. An empty set and a set consisting of exactly one square are connected by definition.
Input
The first input line contains two space-separated integers n and m (1 β€ n, m β€ 50) β the sizes of the sheet of paper.
Each of the next n lines contains m characters β the description of the sheet of paper: the j-th character of the i-th line equals either "#", if the corresponding square is painted (belongs to set A), or equals "." if the corresponding square is not painted (does not belong to set A). It is guaranteed that the set of all painted squares A is connected and isn't empty.
Output
On the first line print the minimum number of squares that need to be deleted to make set A not connected. If it is impossible, print -1.
Examples
Input
5 4
####
#..#
#..#
#..#
####
Output
2
Input
5 5
#####
#...#
#####
#...#
#####
Output
2
Note
In the first sample you can delete any two squares that do not share a side. After that the set of painted squares is not connected anymore.
The note to the second sample is shown on the figure below. To the left there is a picture of the initial set of squares. To the right there is a set with deleted squares. The deleted squares are marked with crosses.
<image> | instruction | 0 | 96,395 | 7 | 192,790 |
Tags: constructive algorithms, graphs, trees
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
from collections import deque
def func(lst,st,po,n,m):
dirs = [(0,1),(0,-1),(1,0),(-1,0)]
x = (st[0] if st[0]!=po else st[1])
curr,se,cnt = deque([x]),[[0]*m for _ in range(n)],0
while len(curr):
y = curr.popleft()
for i in dirs:
z = (y[0]+i[0],y[1]+i[1])
if (0 <= z[0] < n and 0 <= z[1] < m and
lst[z[0]][z[1]] == '#' and not se[z[0]][z[1]]):
curr.append(z)
se[z[0]][z[1]] = 1
cnt += 1
return cnt!=len(st)-1
def main():
n,m = map(int,input().split())
lst = [list(input().strip()) for _ in range(n)]
st = []
for i in range(n):
for j in range(m):
if lst[i][j] == '#':
st.append((i,j))
if len(st) < 3:
print(-1)
return
for i in range(n):
for j in range(m):
if lst[i][j] == '#':
lst[i][j] = '.'
if func(lst,st,(i,j),n,m):
print(1)
return
lst[i][j] = '#'
print(2)
#Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == '__main__':
main()
``` | output | 1 | 96,395 | 7 | 192,791 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You've gotten an n Γ m sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as A. Set A is connected. Your task is to find the minimum number of squares that we can delete from set A to make it not connected.
A set of painted squares is called connected, if for every two squares a and b from this set there is a sequence of squares from the set, beginning in a and ending in b, such that in this sequence any square, except for the last one, shares a common side with the square that follows next in the sequence. An empty set and a set consisting of exactly one square are connected by definition.
Input
The first input line contains two space-separated integers n and m (1 β€ n, m β€ 50) β the sizes of the sheet of paper.
Each of the next n lines contains m characters β the description of the sheet of paper: the j-th character of the i-th line equals either "#", if the corresponding square is painted (belongs to set A), or equals "." if the corresponding square is not painted (does not belong to set A). It is guaranteed that the set of all painted squares A is connected and isn't empty.
Output
On the first line print the minimum number of squares that need to be deleted to make set A not connected. If it is impossible, print -1.
Examples
Input
5 4
####
#..#
#..#
#..#
####
Output
2
Input
5 5
#####
#...#
#####
#...#
#####
Output
2
Note
In the first sample you can delete any two squares that do not share a side. After that the set of painted squares is not connected anymore.
The note to the second sample is shown on the figure below. To the left there is a picture of the initial set of squares. To the right there is a set with deleted squares. The deleted squares are marked with crosses.
<image>
Submitted Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz/'
M=1000000007
EPS=1e-6
def Ceil(a,b): return a//b+int(a%b>0)
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
n,m=value()
a=[]
tot=0
ans=inf
for i in range(n):
s=input()
tot+=s.count('#')
a.append(s)
for i in range(n):
for j in range(m):
if(a[i][j]=='.'): continue
here=0
for dx,dy in [ (1,0),(-1,0),(0,1),(0,-1) ] :
if(0<=i+dx<n and 0<=j+dy<m):
here+=a[i+dx][j+dy]=='#'
if(tot-here-1): ans=min(here,ans)
if(ans in (inf,0)): ans=-1
print(ans)
``` | instruction | 0 | 96,396 | 7 | 192,792 |
No | output | 1 | 96,396 | 7 | 192,793 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You've gotten an n Γ m sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as A. Set A is connected. Your task is to find the minimum number of squares that we can delete from set A to make it not connected.
A set of painted squares is called connected, if for every two squares a and b from this set there is a sequence of squares from the set, beginning in a and ending in b, such that in this sequence any square, except for the last one, shares a common side with the square that follows next in the sequence. An empty set and a set consisting of exactly one square are connected by definition.
Input
The first input line contains two space-separated integers n and m (1 β€ n, m β€ 50) β the sizes of the sheet of paper.
Each of the next n lines contains m characters β the description of the sheet of paper: the j-th character of the i-th line equals either "#", if the corresponding square is painted (belongs to set A), or equals "." if the corresponding square is not painted (does not belong to set A). It is guaranteed that the set of all painted squares A is connected and isn't empty.
Output
On the first line print the minimum number of squares that need to be deleted to make set A not connected. If it is impossible, print -1.
Examples
Input
5 4
####
#..#
#..#
#..#
####
Output
2
Input
5 5
#####
#...#
#####
#...#
#####
Output
2
Note
In the first sample you can delete any two squares that do not share a side. After that the set of painted squares is not connected anymore.
The note to the second sample is shown on the figure below. To the left there is a picture of the initial set of squares. To the right there is a set with deleted squares. The deleted squares are marked with crosses.
<image>
Submitted Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz/'
M=1000000007
EPS=1e-6
def Ceil(a,b): return a//b+int(a%b>0)
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
n,m=value()
a=[]
for i in range(n): a.append(input())
ans=inf
for i in range(n):
for j in range(m):
if(a[i][j]=='.'): continue
here=0
for dx,dy in [ (1,0),(-1,0),(0,1),(0,-1) ] :
if(0<=i+dx<n and 0<=j+dy<m):
here+=a[i+dx][j+dy]=='#'
ans=min(here,ans)
if(ans==inf): ans=0
print(ans)
``` | instruction | 0 | 96,397 | 7 | 192,794 |
No | output | 1 | 96,397 | 7 | 192,795 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You've gotten an n Γ m sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as A. Set A is connected. Your task is to find the minimum number of squares that we can delete from set A to make it not connected.
A set of painted squares is called connected, if for every two squares a and b from this set there is a sequence of squares from the set, beginning in a and ending in b, such that in this sequence any square, except for the last one, shares a common side with the square that follows next in the sequence. An empty set and a set consisting of exactly one square are connected by definition.
Input
The first input line contains two space-separated integers n and m (1 β€ n, m β€ 50) β the sizes of the sheet of paper.
Each of the next n lines contains m characters β the description of the sheet of paper: the j-th character of the i-th line equals either "#", if the corresponding square is painted (belongs to set A), or equals "." if the corresponding square is not painted (does not belong to set A). It is guaranteed that the set of all painted squares A is connected and isn't empty.
Output
On the first line print the minimum number of squares that need to be deleted to make set A not connected. If it is impossible, print -1.
Examples
Input
5 4
####
#..#
#..#
#..#
####
Output
2
Input
5 5
#####
#...#
#####
#...#
#####
Output
2
Note
In the first sample you can delete any two squares that do not share a side. After that the set of painted squares is not connected anymore.
The note to the second sample is shown on the figure below. To the left there is a picture of the initial set of squares. To the right there is a set with deleted squares. The deleted squares are marked with crosses.
<image>
Submitted Solution:
```
import os,io
from sys import stdout
import collections
import random
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import sys
sys.setrecursionlimit(10000)
def binomial_coefficient(n, k):
if 0 <= k <= n:
ntok = 1
ktok = 1
for t in range(1, min(k, n - k) + 1):
ntok *= n
ktok *= t
n -= 1
return ntok // ktok
else:
return 0
def powerOfK(k, max):
if k == 1:
return [1]
if k == -1:
return [-1, 1]
result = []
n = 1
while n <= max:
result.append(n)
n *= k
return result
def prefixSum(arr):
for i in range(1, len(arr)):
arr[i] = arr[i] + arr[i-1]
return arr
def moves():
x = [0, 0, 1, -1]
y = [1, -1, 0, 0]
return list(zip(x, y))
n, m = list(map(int, input().split()))
grid = []
for _ in range(n):
grid.append(list(input().strip().decode("utf-8")))
def shortestPath(grid, nx1, ny1, nx2, ny2):
queue = [(nx1, ny1)]
visited = set()
while len(queue):
c = queue.pop(0)
if c in visited:
continue
visited.add(c)
if c == (nx2, ny2):
return True
for x, y in moves():
nx = x + c[0]
ny = y + c[1]
if nx >= 0 and nx < n and ny >= 0 and ny <m and grid[nx][ny] == '#':
queue.append((nx, ny))
print("cant ")
print(nx1, ny1, nx2, ny2)
return False
def hasPath(grid, i, j, n , m):
for x1, y1 in moves():
nx1, ny1 = x1+i, y1+j
if not(nx1 >= 0 and nx1 < n and ny1 >= 0 and ny1 <m):
continue
for x2, y2 in moves():
nx2, ny2 = x2+i, y2+j
if not(nx2 >= 0 and nx2 < n and ny2 >= 0 and ny2 <m):
continue
if (nx1, ny1) != (nx2, ny2) and grid[nx1][ny1] == '#' and grid[nx2][ny2] == '#':
if not shortestPath(grid, nx1, ny1, nx2, ny2):
return False
return True
def oneDeletion(grid, n, m):
for i in range(n):
for j in range(m):
if grid[i][j] == '#':
grid[i][j] = '.'
if not hasPath(grid, i, j, n, m):
return True
grid[i][j] = '#'
return False
hash = 0
for i in range(n):
for j in range(m):
if grid[i][j] == '#':
hash+=1
if hash <= 2:
print(-1)
elif oneDeletion(grid, n, m):
print(1)
else:
print(2)
``` | instruction | 0 | 96,398 | 7 | 192,796 |
No | output | 1 | 96,398 | 7 | 192,797 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You've gotten an n Γ m sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as A. Set A is connected. Your task is to find the minimum number of squares that we can delete from set A to make it not connected.
A set of painted squares is called connected, if for every two squares a and b from this set there is a sequence of squares from the set, beginning in a and ending in b, such that in this sequence any square, except for the last one, shares a common side with the square that follows next in the sequence. An empty set and a set consisting of exactly one square are connected by definition.
Input
The first input line contains two space-separated integers n and m (1 β€ n, m β€ 50) β the sizes of the sheet of paper.
Each of the next n lines contains m characters β the description of the sheet of paper: the j-th character of the i-th line equals either "#", if the corresponding square is painted (belongs to set A), or equals "." if the corresponding square is not painted (does not belong to set A). It is guaranteed that the set of all painted squares A is connected and isn't empty.
Output
On the first line print the minimum number of squares that need to be deleted to make set A not connected. If it is impossible, print -1.
Examples
Input
5 4
####
#..#
#..#
#..#
####
Output
2
Input
5 5
#####
#...#
#####
#...#
#####
Output
2
Note
In the first sample you can delete any two squares that do not share a side. After that the set of painted squares is not connected anymore.
The note to the second sample is shown on the figure below. To the left there is a picture of the initial set of squares. To the right there is a set with deleted squares. The deleted squares are marked with crosses.
<image>
Submitted Solution:
```
def f(t):
t = [i for i in t if i]
return len(t) > 2 and 1 in t[1: -1]
n, m = map(int, input().split())
t = [input() for i in range(n)]
p = ''.join(t)
if p.count('#') < 3: print(-1)
elif f([i.count('#') for i in t]) or \
f([i.count('#') for i in zip(*t)]) or \
f([p[i :: m + 1].count('#') for i in range(m, n * m, m)][:: -1] + \
[p[i: (n - i) * m: m + 1].count('#') for i in range(m)]) or \
f([p[i: i * m + 1: m - 1].count('#') for i in range(m)] + \
[p[i :: m - 1].count('#') for i in range(2 * m - 1, m * n, m)]): print(1)
else: print(2)
``` | instruction | 0 | 96,399 | 7 | 192,798 |
No | output | 1 | 96,399 | 7 | 192,799 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2). | instruction | 0 | 97,036 | 7 | 194,072 |
Tags: brute force, data structures, dp, implementation, two pointers
Correct Solution:
```
from sys import stdin
from sys import setrecursionlimit as SRL; SRL(10**7)
rd = stdin.readline
rrd = lambda: map(int, rd().strip().split())
n,k = rrd()
s = []
cal = [[0]*(n+10) for _i in range(n+10)]
for i in range(n):
s.append(str(rd()))
ans = 0
for i in range(n):
j = 0
while j < n and s[i][j] == 'W':
j += 1
l = j
if j >= n:
ans += 1
continue
j = n-1
while j >= 0 and s[i][j] == 'W':
j -= 1
r = j
if r - l + 1 > k:
continue
l1 = max(0,i - k + 1)
r1 = i + 1
l2 = max(0,r - k + 1)
r2 = l + 1
cal[l1][l2] += 1
cal[r1][l2] -= 1
cal[l1][r2] -= 1
cal[r1][r2] += 1
for i in range(n):
j = 0
while j < n and s[j][i] == 'W':
j += 1
l = j
if j >= n:
ans += 1
continue
j = n-1
while j >= 0 and s[j][i] == 'W':
j -= 1
r = j
if r-l+1 > k:
continue
l1 = max(0,i - k + 1)
r1 = i + 1
l2 = max(0,r - k + 1)
r2 = l + 1
cal[l2][l1] += 1
cal[l2][r1] -= 1
cal[r2][l1] -= 1
cal[r2][r1] += 1
for i in range(n):
for j in range(n):
if j:
cal[i][j] += cal[i][j-1]
pans = 0
for j in range(n):
for i in range(n):
if i:
cal[i][j] += cal[i-1][j]
pans = max(pans,cal[i][j])
print(ans+pans)
``` | output | 1 | 97,036 | 7 | 194,073 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2). | instruction | 0 | 97,037 | 7 | 194,074 |
Tags: brute force, data structures, dp, implementation, two pointers
Correct Solution:
```
from sys import stdin, stdout
from collections import *
from array import *
def iarr(delim = " "): return map(int, input().split(delim))
def mat(n, m, v = None): return [[v]*m for _ in range(n)]
n, k, *_ = iarr()
lc = [-1]*n
rc = [n]*n
tr = [-1]*n
br = [n]*n
b = [input() for _ in range(n)]
ans = mat(n, n, 0)
pre, post = 0, 0
for i, r in enumerate(b):
for j, c in enumerate(r):
if c == 'B':
rc[i], br[j] = j, i
if lc[i] == -1: lc[i] = j
if tr[j] == -1: tr[j] = i
for i in range(n):
if tr[i] == -1 and br[i] == n: pre += 1
if lc[i] == -1 and rc[i] == n: pre += 1
for col in range(n-k+1):
tot = 0
for row in range(k):
if lc[row] >= col and rc[row] < col+k: tot += 1
ans[0][col] = tot
for row in range(1, n-k+1):
if lc[row-1] >= col and rc[row-1] < col+k: tot -= 1
if lc[row+k-1] >= col and rc[row+k-1] < col+k: tot += 1
ans[row][col] = tot
for row in range(n-k+1):
tot = 0
for col in range(k):
tot += 1 if tr[col] >= row and br[col] < row+k else 0
post = max(post, ans[row][0]+tot)
for col in range(1, n-k+1):
if tr[col-1] >= row and br[col-1] < row+k: tot -= 1
if tr[col+k-1] >= row and br[col+k-1] < row+k: tot += 1
post = max(post, ans[row][col]+tot)
print(pre+post)
``` | output | 1 | 97,037 | 7 | 194,075 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2). | instruction | 0 | 97,038 | 7 | 194,076 |
Tags: brute force, data structures, dp, implementation, two pointers
Correct Solution:
```
import sys
def count(n, k, field):
blank = 0
cnt = [[0] * (n - k + 1) for _ in range(n)]
for i, row in enumerate(field):
l = row.find('B')
r = row.rfind('B')
if l == r == -1:
blank += 1
continue
if r - l + 1 > k:
continue
kl = max(0, r - k + 1)
kr = min(l + 1, n - k + 1)
cnt[i][kl:kr] = [1] * (kr - kl)
acc = [[0] * (n - k + 1) for _ in range(n - k + 1)]
t_cnt = list(zip(*cnt))
for i, col in enumerate(t_cnt):
aci = acc[i]
tmp = sum(col[n - k:])
aci[n - k] = tmp
for j in range(n - k - 1, -1, -1):
tmp += col[j]
tmp -= col[j + k]
aci[j] = tmp
return blank, acc
n, k = map(int, input().split())
field = [line.strip() for line in sys.stdin]
bh, hor = count(n, k, field)
t_field = [''.join(col) for col in zip(*field)]
bv, t_var = count(n, k, t_field)
var = list(zip(*t_var))
print(bh + bv + max(h + v for (rh, rv) in zip(hor, var) for (h, v) in zip(rh, rv)))
``` | output | 1 | 97,038 | 7 | 194,077 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2). | instruction | 0 | 97,039 | 7 | 194,078 |
Tags: brute force, data structures, dp, implementation, two pointers
Correct Solution:
```
n, k = map(int ,input().split())
c_p1 = [[-1] * 2001 for x in range(2001)]
c_p2 = [[-1] * 2001 for x in range(2001)]
r_p1 = [[-1] * 2001 for x in range(2001)]
r_p2 = [[-1] * 2001 for x in range(2001)]
cells = []
for i in range(n):
cells.append(input())
bonus = 0
for y in range(n):
earliest = -1
latest = -1
for x in range(n):
if cells[y][x] == "B":
earliest = x
break
for x in range(n):
if cells[y][n - x - 1] == "B":
latest = n - x - 1
break
if earliest == -1:
bonus += 1
for x in range(n - k + 1):
r_p1[y][x] = int(earliest >= x and x + k - 1 >= latest)
for x in range(n - k + 1):
sum = 0
for y in range(n):
sum += r_p1[y][x]
if y - k >= 0:
sum -= r_p1[y - k][x]
if y - k + 1 >= 0:
r_p2[y - k + 1][x] = sum
for x in range(n):
earliest = -1
latest = -1
for y in range(n):
if cells[y][x] == "B":
earliest = y
break
for y in range(n):
if cells[n - y - 1][x] == "B":
latest = n - y - 1
break
if earliest == -1:
bonus += 1
for y in range(n - k + 1):
c_p1[y][x] = int(earliest >= y and y + k - 1 >= latest)
for y in range(n - k + 1):
sum = 0
for x in range(n):
sum += c_p1[y][x]
if x - k >= 0:
sum -= c_p1[y][x - k]
if x - k + 1 >= 0:
c_p2[y][x - k + 1] = sum
ans = 0
for y in range(n - k + 1):
for x in range(n - k + 1):
ans = max(ans, c_p2[y][x] + r_p2[y][x])
print(ans + bonus)
``` | output | 1 | 97,039 | 7 | 194,079 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2). | instruction | 0 | 97,040 | 7 | 194,080 |
Tags: brute force, data structures, dp, implementation, two pointers
Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().strip()
n, k = map(int, input().split())
arr = []
for i in range(n):
arr.append(list(input()))
extra = 0
res = []
for i in range(n-k+1):
res.append([])
for j in range(n-k+1):
res[-1].append(0)
# ROWS
l = {}
r = {}
for i in range(n):
for j in range(n):
if arr[i][j]=='B': l[i] = j; break
for j in range(n-1, -1, -1):
if arr[i][j]=='B': r[i] = j; break
else: l[i] = None; r[i] = None; extra+=1
for j in range(n-k+1):
tmp = 0
for i in range(k):
if l[i] is not None and l[i]>=j and r[i]<=j+k-1:
tmp+=1
res[0][j]+=tmp
for i in range(1, n-k+1):
if l[i-1] is not None and l[i-1]>=j and r[i-1]<=j+k-1:
tmp-=1
if l[i+k-1] is not None and l[i+k-1]>=j and r[i+k-1]<=j+k-1:
tmp+=1
res[i][j]+=tmp
# COLUMNS
l = {}
r = {}
for j in range(n):
for i in range(n):
if arr[i][j]=='B': l[j] = i; break
for i in range(n-1, -1, -1):
if arr[i][j]=='B': r[j] = i; break
else: l[j] = None; r[j] = None; extra+=1
for i in range(n-k+1):
tmp = 0
for j in range(k):
if l[j] is not None and l[j]>=i and r[j]<=i+k-1:
tmp+=1
res[i][0]+=tmp
for j in range(1, n-k+1):
if l[j-1] is not None and l[j-1]>=i and r[j-1]<=i+k-1:
tmp-=1
if l[j+k-1] is not None and l[j+k-1]>=i and r[j+k-1]<=i+k-1:
tmp+=1
res[i][j]+=tmp
print(max(max(i) for i in res)+extra)
``` | output | 1 | 97,040 | 7 | 194,081 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2). | instruction | 0 | 97,041 | 7 | 194,082 |
Tags: brute force, data structures, dp, implementation, two pointers
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
mod = 10 ** 9 + 7
mod1 = 998244353
#sys.setrecursionlimit(300000)
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
#sys.setrecursionlimit(300000)
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
# -----------------------------------------------binary seacrh tree---------------------------------------
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n,k=map(int,input().split())
m=n
l=[]
ans=0
for i in range(n):
l.append(input())
whi=[0 for i in range(n)]
ran=[[-1 for j in range(2)] for i in range(n)]
for i in range(n):
st=2001
end=-1
for j in range(m):
if l[i][j]=='B':
st=min(st,j)
end=max(end,j)
if end==-1:
whi[i]=1
else:
ran[i][0]=st
ran[i][1]=end
ans1=sum(whi)
a=[[0 for i in range(m)]for j in range(n)]
for j in range(m):
cur=0
last=[0]*n
for i in range(k):
if whi[i]==1:
continue
if ran[i][0]>=j and ran[i][1]<=j+k-1:
cur+=1
last[i]=1
a[0][j]=cur
for i in range(k,n):
if last[i-k]==1:
cur-=1
if whi[i]==1:
continue
if ran[i][0]>=j and ran[i][1]<=j+k-1:
cur+=1
last[i]=1
a[i-k+1][j]=cur
whi=[0 for i in range(n)]
ran=[[-1for j in range(2)] for i in range(n)]
for i in range(n):
st=2001
end=-1
for j in range(m):
if l[j][i]=='B':
st=min(st,j)
end=max(end,j)
if end==-1:
whi[i]=1
else:
ran[i][0]=st
ran[i][1]=end
b=[[0 for i in range(m)]for j in range(n)]
for j in range(n):
cur=0
last=[0]*n
for i in range(k):
if whi[i]==1:
continue
if ran[i][0]>=j and ran[i][1]<=j+k-1:
cur+=1
last[i]=1
b[j][0]=cur
for i in range(k,m):
if last[i-k]==1:
cur-=1
if whi[i]==1:
continue
if ran[i][0]>=j and ran[i][1]<=j+k-1:
cur+=1
last[i]=1
b[j][i-k+1]=cur
for i in range(n):
for j in range(m):
ans=max(ans,a[i][j]+b[i][j])
print(ans+sum(whi)+ans1)
``` | output | 1 | 97,041 | 7 | 194,083 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2). | instruction | 0 | 97,042 | 7 | 194,084 |
Tags: brute force, data structures, dp, implementation, two pointers
Correct Solution:
```
# pypy 3.6
import re
from collections import deque
from functools import reduce
from fractions import gcd # ~py3.4
from heapq import *
from itertools import permutations
from math import pi
from operator import itemgetter
from operator import mul
from operator import xor
from os import linesep
from sys import stdin
def rline() -> str:
return stdin.readline().rstrip()
def fmatr(matrix, lnsep: str = linesep, fieldsep: str = ' ') -> str:
return lnsep.join(map(lambda row: fieldsep.join(map(str, row)), matrix))
def fbool(boolval: int) -> str:
return ['No', 'Yes'][boolval]
def gcd(a: int, b: int) -> int:
a, b = max([a, b]), min([a, b])
if b == 0:
return a
return gcd(b, a % b)
def solve() -> None:
# read here
n, k = map(int, rline().split())
s = [rline() for i in range(n)]
# solve here
# tb[j], bb[j] = top,bottom black in the column c
# lb[i], rb[i] = leftmost,rightmost black in the row r
tb, bb, lb, rb = [[-1] * n for i in range(4)]
for a in range(n):
hor = s[a]
lb[a] = hor.find('B')
rb[a] = hor.rfind('B')
ver = ''.join(list(map(itemgetter(a), s)))
tb[a] = ver.find('B')
bb[a] = ver.rfind('B')
# print(tb, bb, lb, rb)
ans = 0
df = tb.count(-1)+lb.count(-1)
l4r, r4l = [[{} for i in range(n)] for j in range(2)]
for y in range(k):
l, r = lb[y], rb[y]
if l == -1:
continue
l4r[r][l] = 1 + l4r[r].get(l, 0)
r4l[l][r] = 1 + r4l[l].get(r, 0)
for top in range(n-k+1):
subans = df
btm = top + k # excl.
# erase (0,top)-(k-1,btm-1)
for y in range(top, btm):
if 0 <= lb[y] <= rb[y] < k:
subans += 1
for x in range(k):
if top <= tb[x] <= bb[x] < btm:
subans += 1
ans = max([ans, subans])
# move the eraser right by 1 column
for rm in range(n-k):
ad = rm+k
# remove column
if top <= tb[rm] <= bb[rm] < btm:
subans -= 1
# add column
if top <= tb[ad] <= bb[ad] < btm:
subans += 1
# remove rows
subans -= sum(map(
lambda r: r4l[rm][r] if r < ad else 0, r4l[rm].keys()))
# add rows
subans += sum(map(
lambda l: l4r[ad][l] if l > rm else 0, l4r[ad].keys()))
ans = max([ans, subans])
# print(subans, top, rm)
# udpate r4l, l4r
if rb[top] != -1:
l4r[rb[top]][lb[top]] -= 1
if l4r[rb[top]][lb[top]] == 0:
l4r[rb[top]].pop(lb[top])
r4l[lb[top]][rb[top]] -= 1
if r4l[lb[top]][rb[top]] == 0:
r4l[lb[top]].pop(rb[top])
if btm < n and rb[btm] != -1:
l4r[rb[btm]][lb[btm]] = 1 + l4r[rb[btm]].get(lb[btm], 0)
r4l[lb[btm]][rb[btm]] = 1 + r4l[lb[btm]].get(rb[btm], 0)
# print here
print(ans)
if __name__ == '__main__':
solve()
``` | output | 1 | 97,042 | 7 | 194,085 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2). | instruction | 0 | 97,043 | 7 | 194,086 |
Tags: brute force, data structures, dp, implementation, two pointers
Correct Solution:
```
n,k=map(int,input().split())
it=[[0]*n for i in range(n)]
t=[[-1,-1] for i in range(n)]
tt=[[-1,-1] for i in range(n)]
for i in range(n):
s=input()
c=-1
cc=-1
for j,ii in enumerate(s):
if ii=="B":
it[i][j]=1
if c==-1:
c=j
cc=j
t[i]=[c,cc]
for i in range(n):
p=[it[j][i] for j in range(n)]
c=-1
cc=-1
for j in range(n):
if p[j]:
if c==-1:
c=j
cc=j
tt[i]=[c,cc]
row_max=[[0]*(n-k+1) for i in range(n-k+1)]
col_max=[[0]*(n-k+1) for i in range(n-k+1)]
for col in range(n-k+1):
s=[0]*n
co=0
for i in range(k):
if t[i]!=[-1,-1]:
if t[i][0]>=col and t[i][0]<=col+k-1 and t[i][1]>=col and t[i][1]<=col+k-1:
co+=1
s[i]=1
row_max[col][0]=co
for row in range(1,n-k+1):
if s[row-1]:
co-=1
i=row+k-1
if t[i]!=[-1,-1]:
if t[i][0]>=col and t[i][0]<=col+k-1 and t[i][1]>=col and t[i][1]<=col+k-1:
co+=1
s[i]=1
row_max[col][row]=co
for row in range(n-k+1):
s=[0]*n
co=0
for i in range(k):
if tt[i]!=[-1,-1]:
if tt[i][0]>=row and tt[i][0]<=row+k-1 and tt[i][1]>=row and tt[i][1]<=row+k-1:
co+=1
s[i]=1
col_max[0][row]=co
for col in range(1,n-k+1):
if s[col-1]:
co-=1
i=col+k-1
if tt[i]!=[-1,-1]:
if tt[i][0]>=row and tt[i][0]<=row+k-1 and tt[i][1]>=row and tt[i][1]<=row+k-1:
co+=1
s[i]=1
col_max[col][row]=co
ma=0
for i in range(n-k+1):
for j in range(n-k+1):
ma=max(ma,row_max[i][j]+col_max[i][j])
ma+=t.count([-1,-1])
ma+=tt.count([-1,-1])
print(ma)
``` | output | 1 | 97,043 | 7 | 194,087 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Submitted Solution:
```
def main():
n, k = map(int, input().split())
ss = []
tate = [[0 for _ in range(n+1)] for _ in range(n+1)]
yoko = [[0 for _ in range(n+1)] for _ in range(n+1)]
for i in range(n):
s = input().strip()
for j, _s in enumerate(s):
tate[i+1][j+1] = tate[i][j+1] + (1 if _s == 'B' else 0)
yoko[i+1][j+1] = yoko[i+1][j] + (1 if _s == 'B' else 0)
lc = 0
for i in range(n):
if tate[n][i+1] == 0:
lc += 1
if yoko[i+1][n] == 0:
lc += 1
yans = [[0 for _ in range(n+1)] for _ in range(n+1)]
tans = [[0 for _ in range(n+1)] for _ in range(n+1)]
for i in range(n):
l, r = 0, k
while r <= n:
yans[i+1][l+1] = yans[i][l+1]
if yoko[i+1][n] != 0 and yoko[i+1][r] - yoko[i+1][l] == yoko[i+1][n]:
yans[i+1][l+1] += 1
l += 1
r += 1
for i in range(n):
l, r = 0, k
while r <= n:
tans[l+1][i+1] = tans[l+1][i]
if tate[n][i+1] != 0 and tate[r][i+1] - tate[l][i+1] == tate[n][i+1]:
tans[l+1][i+1] += 1
l += 1
r += 1
ans = lc
for i in range(n-k+1):
for j in range(n-k+1):
ans = max(ans, lc+yans[i+k][j+1]-yans[i][j+1]+tans[i+1][j+k]-tans[i+1][j])
# print(*tate, sep='\n')
# print()
# print(*yoko, sep='\n')
# print()
# print(*tans, sep='\n')
# print()
# print(*yans, sep='\n')
# print()
print(ans)
if __name__ == '__main__':
main()
``` | instruction | 0 | 97,044 | 7 | 194,088 |
Yes | output | 1 | 97,044 | 7 | 194,089 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Submitted Solution:
```
import sys
input = sys.stdin.readline
n,k=map(int,input().split())
MAP=[input().strip() for i in range(n)]
MINR=[1<<30]*n
MAXR=[-1]*n
MINC=[1<<30]*n
MAXC=[-1]*n
for i in range(n):
for j in range(n):
if MAP[i][j]=="B":
MINR[i]=min(MINR[i],j)
MAXR[i]=max(MAXR[i],j)
MINC[j]=min(MINC[j],i)
MAXC[j]=max(MAXC[j],i)
ALWAYS=0
for i in range(n):
if MINR[i]==1<<30 and MAXR[i]==-1:
ALWAYS+=1
if MINC[i]==1<<30 and MAXC[i]==-1:
ALWAYS+=1
ANS=[[0]*(n-k+1) for i in range(n-k+1)]
for j in range(n-k+1):
NOW=0
for i in range(k):
if j<=MINR[i] and j+k-1>=MAXR[i] and MINR[i]!=1<<30 and MAXR[i]!=-1:
NOW+=1
ANS[0][j]+=NOW
for i in range(n-k):
if j<=MINR[i] and j+k-1>=MAXR[i] and MINR[i]!=1<<30 and MAXR[i]!=-1:
NOW-=1
if j<=MINR[i+k] and j+k-1>=MAXR[i+k] and MINR[i+k]!=1<<30 and MAXR[i+k]!=-1:
NOW+=1
ANS[i+1][j]+=NOW
for i in range(n-k+1):
NOW=0
for j in range(k):
if i<=MINC[j] and i+k-1>=MAXC[j] and MINC[j]!=1<<30 and MAXC[j]!=-1:
NOW+=1
ANS[i][0]+=NOW
for j in range(n-k):
if i<=MINC[j] and i+k-1>=MAXC[j] and MINC[j]!=1<<30 and MAXC[j]!=-1:
NOW-=1
if i<=MINC[j+k] and i+k-1>=MAXC[j+k] and MINC[j+k]!=1<<30 and MAXC[j+k]!=-1:
NOW+=1
ANS[i][j+1]+=NOW
print(max([max(a) for a in ANS])+ALWAYS)
``` | instruction | 0 | 97,045 | 7 | 194,090 |
Yes | output | 1 | 97,045 | 7 | 194,091 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Submitted Solution:
```
import sys
import math,bisect
sys.setrecursionlimit(10 ** 5)
from itertools import groupby,accumulate
from heapq import heapify,heappop,heappush
from collections import deque,Counter,defaultdict
def I(): return int(sys.stdin.readline())
def neo(): return map(int, sys.stdin.readline().split())
def Neo(): return list(map(int, sys.stdin.readline().split()))
N, K = neo()
G = [[1 if s == 'B' else 0 for s in sys.stdin.readline().strip()] for _ in range(N)]
Ans = [[0]*(N+1) for _ in range(N+1)]
ans = 0
for i in range(N):
g = G[i]
if 1 not in g:
ans += 1
continue
r = g.index(1)
l = max(0, N - K - g[::-1].index(1))
j = max(0, i-K+1)
if l <= r:
Ans[j][l] += 1
Ans[j][r+1] -= 1
Ans[i+1][l] -= 1
Ans[i+1][r+1] += 1
G = list(map(list, zip(*G)))
Ans = list(map(list, zip(*Ans)))
for i in range(N):
g = G[i]
if 1 not in g:
ans += 1
continue
r = g.index(1)
l = max(0, N - K - g[::-1].index(1))
j = max(0, i-K+1)
if l <= r:
Ans[j][l] += 1
Ans[j][r+1] -= 1
Ans[i+1][l] -= 1
Ans[i+1][r+1] += 1
Ans = [list(accumulate(g))[::-1] for g in Ans]
Ans = list(map(list, zip(*Ans)))
Ans = [list(accumulate(g))[::-1] for g in Ans]
print(ans + max(max(g) for g in Ans))
``` | instruction | 0 | 97,046 | 7 | 194,092 |
Yes | output | 1 | 97,046 | 7 | 194,093 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Submitted Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------------------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a+b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SegmentTree1:
def __init__(self, data, default=10**6, func=lambda a, b: min(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
MOD=10**9+7
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(10)]
pp=[0]*10
def SieveOfEratosthenes(n=10):
p = 2
c=0
while (p * p <= n):
if (prime[p] == True):
c+=1
for i in range(p, n+1, p):
pp[i]+=1
prime[i] = False
p += 1
#---------------------------------Binary Search------------------------------------------
def binarySearch(arr, n, key):
left = 0
right = n-1
mid = 0
res=arr[n-1]
while (left <= right):
mid = (right + left)//2
if (arr[mid] >= key):
res=arr[mid]
right = mid-1
else:
left = mid + 1
return res
def binarySearch1(arr, n, key):
left = 0
right = n-1
mid = 0
res=arr[0]
while (left <= right):
mid = (right + left)//2
if (arr[mid] > key):
right = mid-1
else:
res=arr[mid]
left = mid + 1
return res
#---------------------------------running code------------------------------------------
n,k=map(int,input().split())
m=n
l=[]
ans=0
for i in range(n):
l.append(input())
whi=[0 for i in range(n)]
ran=[[-1 for j in range(2)] for i in range(n)]
for i in range(n):
st=2001
end=-1
for j in range(m):
if l[i][j]=='B':
st=min(st,j)
end=max(end,j)
if end==-1:
whi[i]=1
else:
ran[i][0]=st
ran[i][1]=end
ans1=sum(whi)
a=[[0 for i in range(m)]for j in range(n)]
for j in range(m):
cur=0
last=[0]*n
for i in range(k):
if whi[i]==1:
continue
if ran[i][0]>=j and ran[i][1]<=j+k-1:
cur+=1
last[i]=1
a[0][j]=cur
for i in range(k,n):
if last[i-k]==1:
cur-=1
if whi[i]==1:
continue
if ran[i][0]>=j and ran[i][1]<=j+k-1:
cur+=1
last[i]=1
a[i-k+1][j]=cur
whi=[0 for i in range(n)]
ran=[[-1for j in range(2)] for i in range(n)]
for i in range(n):
st=2001
end=-1
for j in range(m):
if l[j][i]=='B':
st=min(st,j)
end=max(end,j)
if end==-1:
whi[i]=1
else:
ran[i][0]=st
ran[i][1]=end
b=[[0 for i in range(m)]for j in range(n)]
for j in range(n):
cur=0
last=[0]*n
for i in range(k):
if whi[i]==1:
continue
if ran[i][0]>=j and ran[i][1]<=j+k-1:
cur+=1
last[i]=1
b[j][0]=cur
for i in range(k,m):
if last[i-k]==1:
cur-=1
if whi[i]==1:
continue
if ran[i][0]>=j and ran[i][1]<=j+k-1:
cur+=1
last[i]=1
b[j][i-k+1]=cur
for i in range(n):
for j in range(m):
ans=max(ans,a[i][j]+b[i][j])
print(ans+sum(whi)+ans1)
``` | instruction | 0 | 97,047 | 7 | 194,094 |
Yes | output | 1 | 97,047 | 7 | 194,095 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Submitted Solution:
```
n, k = map(int, input().split())
s = [input() for _ in range(n)]
g_row = [[] for _ in range(n)]
g_col = [[] for _ in range(n)]
already_white_line_nums = 0
for i in range(n):
for j in range(n):
if s[i][j] == 'B':
g_row[i].append(j)
g_col[j].append(i)
for i in range(n):
if len(g_row[i]) == 0:
already_white_line_nums += 1
if len(g_col[i]) == 0:
already_white_line_nums += 1
r = already_white_line_nums
for i in range(n - k + 1):
for j in range(n - k + 1):
new_white_line_nums = 0
if len(g_row[i]) == 0 or len(g_col[i]) == 0:
continue
for l in range(i, i + k):
if len(g_row[l]) != 0 and j <= g_row[l][0] and g_row[l][-1] < j + k:
new_white_line_nums += 1
for l in range(j, j + k):
if len(g_col[l]) != 0 and i <= g_col[l][0] and g_col[l][-1] < i + k:
new_white_line_nums += 1
r = max(r, already_white_line_nums + new_white_line_nums)
print(r)
``` | instruction | 0 | 97,048 | 7 | 194,096 |
No | output | 1 | 97,048 | 7 | 194,097 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Submitted Solution:
```
import math
# helpful:
# r,g,b=map(int,input().split())
# arr = [[0 for x in range(columns)] for y in range(rows)]
class BIT():
def __init__(self, n):
self.n = n
self.arr = [0]*(n+1)
def update(self, index, val):
while(index <= self.n):
self.arr[index] += val
index += (index & -index)
def cumul(self, index):
if(index == 0):
return 0
total = self.arr[index]
index -= (index & -index)
while(index > 0):
total += self.arr[index]
index -= (index & -index)
return total
def __str__(self):
string = ""
for i in range(self.n):
string += "in spot " + str(i) + ": " + str(self.arr[i]) + "\n"
return string
def get(self, index):
total = self.arr[index]
x = index - (index & -index)
index -= 1
while(index != x):
total -= self.arr[index]
index -= (index & -index)
return total
n,k=map(int,input().split())
arr = [[-1 for x in range(n-k+3)] for y in range(2*n)] # last two cols track smallest and biggest index
for i in range(n):
string = input()
for j in range(n):
if(string[j] == 'B'):
if(arr[i][n-k+1] == -1): # no black ones yet
arr[i][n-k+1] = j
arr[i][n-k+2] = j
elif(arr[i][n-k+1] > j):
arr[i][n-k+1] = j
elif(arr[i][n-k+2] < j):
arr[i][n-k+2] = j
if(arr[n+j][n-k+1] == -1): # no black ones yet
arr[n+j][n-k+1] = i
arr[n+j][n-k+2] = i
elif(arr[n+j][n-k+1] > i):
arr[n+j][n-k+1] = i
elif(arr[n+j][n-k+2] < i):
arr[n+j][n-k+2] = i
for i in range(2*n):
for j in range(n-k+1):
#if(arr[i][n-k+1] == -1):
# arr[i][j] = 1
if(arr[i][n-k+1] >= j and arr[i][n-k+2] <= j+k-1):
arr[i][j] = 1
else:
arr[i][j] = 0
realArr = [BIT(n+2) for x in range(2*n)]
for i in range(2*n):
for j in range(n-k+1):
realArr[i].update(j+1, arr[i][j])
bestOvr = 0
for i in range(n-k+1):
for j in range(n-k+1):
overall = 0
overall += realArr[i].cumul(j+k) - realArr[i].cumul(j)
overall += realArr[n+j].cumul(i+k) - realArr[n+j].cumul(i)
if(overall > bestOvr):
bestOvr = overall
for i in range(2*n):
if(arr[i][n-k+1] == 0):
bestOvr += 1
print(bestOvr)
``` | instruction | 0 | 97,049 | 7 | 194,098 |
No | output | 1 | 97,049 | 7 | 194,099 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Submitted Solution:
```
n, k = [int(i) for i in input().split()]
sz = n - k + 1
cnt = []
for i in range(sz+1):
cnt.append([0]*(sz+1))
data = []
extra = 0
for i in range(n):
data.append(input())
for r in range(n):
row = data[r]
li = row.find("B") + 1
if li == 0:
extra += 1
continue
ri = row.rfind("B") + 1
for i in range(max(ri - k,1), min(li+1, sz+1)):#??????????????
for j in range(max(1, r+2-k), min(sz+1, r+2)):
cnt[j][i] += 1
# b = []
# b.rindex(1)
for c in range(n):
row = "".join([data[c][i] for i in range(n)])
li = row.find("B") + 1
if li == 0:
extra += 1
continue
ri = row.rfind("B") + 1
for i in range(max(ri - k,1), min(li+1, sz+1)):
for j in range(max(1, c+2-k), min(sz+1, c+2)):
cnt[i][j] += 1
mx = 0
for i in range(1, sz+1):
for j in range(1, sz+1):
if cnt[i][j] > mx:
mx = cnt[i][j]
print(mx+extra)
``` | instruction | 0 | 97,050 | 7 | 194,100 |
No | output | 1 | 97,050 | 7 | 194,101 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is represented as (r, c). There are only two colors for the cells in cfpaint β black and white.
There is a tool named eraser in cfpaint. The eraser has an integer size k (1 β€ k β€ n). To use the eraser, Gildong needs to click on a cell (i, j) where 1 β€ i, j β€ n - k + 1. When a cell (i, j) is clicked, all of the cells (i', j') where i β€ i' β€ i + k - 1 and j β€ j' β€ j + k - 1 become white. In other words, a square with side equal to k cells and top left corner at (i, j) is colored white.
A white line is a row or a column without any black cells.
Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.
Input
The first line contains two integers n and k (1 β€ k β€ n β€ 2000) β the number of rows and columns, and the size of the eraser.
The next n lines contain n characters each without spaces. The j-th character in the i-th line represents the cell at (i,j). Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.
Output
Print one integer: the maximum number of white lines after using the eraser exactly once.
Examples
Input
4 2
BWWW
WBBW
WBBW
WWWB
Output
4
Input
3 1
BWB
WWB
BWB
Output
2
Input
5 3
BWBBB
BWBBB
BBBBB
BBBBB
WBBBW
Output
2
Input
2 2
BW
WB
Output
4
Input
2 1
WW
WW
Output
4
Note
In the first example, Gildong can click the cell (2, 2), then the working screen becomes:
BWWW
WWWW
WWWW
WWWB
Then there are four white lines β the 2-nd and 3-rd row, and the 2-nd and 3-rd column.
In the second example, clicking the cell (2, 3) makes the 2-nd row a white line.
In the third example, both the 2-nd column and 5-th row become white lines by clicking the cell (3, 2).
Submitted Solution:
```
import sys
input = sys.stdin.readline
def getInt(): return int(input())
def getVars(): return map(int, input().split())
def getArr(): return list(map(int, input().split()))
def getStr(): return input().strip()
## -------------------------------
N, K = getVars()
res = N
rows = {}
cols = {}
for i in range(N):
s = getStr()
row = [s.find('B'), s.rfind('B')]
if row[0] == -1:
res += 1
elif row[1] - row[0] < K:
rows[i] = row
for j in range(N):
if s[j] == 'B':
if j not in cols:
cols[j] = [i, i]
res -= 1
else:
cols[j][1] = i
if cols[j][1] - cols[j][0] >= K:
del cols[j]
##print(res)
##print(rows)
##print(cols)
lastiki = {}
for ir in rows:
r = rows[ir]
for lc in range(max(0, r[1] - K + 1), r[0]+1):
for lr in range(max(0, ir-K+1), min(ir+1, N-K+1)):
if lr not in lastiki:
lastiki[lr] = {}
if lc not in lastiki[lr]:
lastiki[lr][lc] = 0
lastiki[lr][lc] += 1
##print(lastiki)
for ic in cols:
c = cols[ic]
for lr in range(max(0, c[1] - K + 1), c[0]+1):
for lc in range(max(0, ic-K+1), min(ic+1, N-K+1)):
if lr not in lastiki:
lastiki[lr] = {}
if lc not in lastiki[lr]:
lastiki[lr][lc] = 0
lastiki[lr][lc] += 1
##print(lastiki)
res1 = 0
for r in lastiki:
res1 = max(res1, max(list(lastiki[r].values())))
print(res+res1)
##
##RES1 = 0
##for lr in range(N-K+1):
## for lc in range(N-K+1):
## res1 = 0
## for ir in range(0, K):
## r = rows[lr + ir]
## if r[0] >= lc and lc + K > r[1]:
#### print('row: ', lr, lc, lr+ir)
## res1 += 1
#### print(lr, lc, res1)
## for ic in range(0, K):
## c = cols[lc + ic]
## if c[0] >= lr and lr + K > c[1]:
## res1 += 1
#### print('col: ', lr, lc, lc+ic)
#### print(lr, lc, res1)
##
## RES1 = max(RES1, res1)
##
##print(res + RES1)
``` | instruction | 0 | 97,051 | 7 | 194,102 |
No | output | 1 | 97,051 | 7 | 194,103 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider an n Γ m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path.
<image>
You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid.
It's guaranteed that the grid has at least one black cell.
Output
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
Examples
Input
3 4
WWBW
BWWW
WWWB
Output
NO
Input
3 1
B
B
W
Output
YES | instruction | 0 | 97,283 | 7 | 194,566 |
Tags: constructive algorithms, implementation
Correct Solution:
```
#author: riyan
def solve(n, m):
grid = []
for i in range(n):
grid.append(input().strip())
cnt = 0
for j in range(1, m):
if grid[i][j] != grid[i][j - 1]:
cnt += 1
if (cnt > 2) or (cnt == 2 and grid[i][0] == 'B'):
#print('row2 check, cnt = ', cnt)
return False
for j in range(m):
cnt = 0
for i in range(1, n):
#print(i, j, grid[i][j])
if grid[i][j] != grid[i - 1][j]:
cnt += 1
if (cnt > 2) or (cnt == 2 and grid[0][j] == 'B'):
#print('col2 check, cnt = ', cnt)
return False
bps = []
for i in range(n):
for j in range(m):
if grid[i][j] == 'B':
bp1 = (i, j)
for k in range(len(bps)):
bp2 = bps[k]
if not ( (grid[bp1[0]][bp2[1]] == 'B') or (grid[bp2[0]][bp1[1]] == 'B') ):
#print(bp1, bp2)
return False
bps.append((i, j))
return True
if __name__ == '__main__':
n, m = map(int, input().strip().split())
ans = solve(n, m)
if ans:
print('YES')
else:
print('NO')
``` | output | 1 | 97,283 | 7 | 194,567 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider an n Γ m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path.
<image>
You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid.
It's guaranteed that the grid has at least one black cell.
Output
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
Examples
Input
3 4
WWBW
BWWW
WWWB
Output
NO
Input
3 1
B
B
W
Output
YES | instruction | 0 | 97,284 | 7 | 194,568 |
Tags: constructive algorithms, implementation
Correct Solution:
```
import sys
def exi():
print("NO")
sys.exit()
I=lambda:list(map(int,input().split()))
g=[]
n,m=I()
for i in range(n):
g.append(list(input()))
for i in range(n):
temp=0
for j in range(1,m):
if g[i][j-1]!=g[i][j]:
temp+=1
#print(temp)
if temp>2 or temp==2 and g[i][0]=='B':exi()
for j in range(m):
temp=0
for i in range(1,n):
if g[i-1][j]!=g[i][j]:
temp+=1
if temp>2 or temp==2 and g[0][j]=='B':exi()
for i1 in range(n):
for j1 in range(m):
if g[i1][j1]=='B':
for i2 in range(n):
for j2 in range(m):
if g[i2][j2]=='B':
if g[i1][j2]=='W' and g[i2][j1]=='W':exi()
print("YES")
``` | output | 1 | 97,284 | 7 | 194,569 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider an n Γ m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path.
<image>
You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid.
It's guaranteed that the grid has at least one black cell.
Output
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
Examples
Input
3 4
WWBW
BWWW
WWWB
Output
NO
Input
3 1
B
B
W
Output
YES | instruction | 0 | 97,285 | 7 | 194,570 |
Tags: constructive algorithms, implementation
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
from collections import Counter
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def gcd(a, b):
if a == 0:
return b
return gcd(b % a, a)
def lcm(a, b):
return (a * b) / gcd(a, b)
def main():
n, m = map(int, input().split())
a = []
for i in range(n):
t = input()
k = []
for j in t:
if j == 'W':
k.append(0)
if j == 'B':
k.append(1)
a.append(k)
reach1 = [[] for i in range(2600)]
blacks=[]
for i in range(n):
for j in range(m):
if a[i][j]:
blacks.append(i*m+j)
t = i
while t >= 0 and a[t][j]:
reach1[i*m+j].append(t*m+j)
t -= 1
t=i+1
while t<n and a[t][j]:
reach1[i * m + j].append(t * m + j)
t +=1
t=j-1
while t >= 0 and a[i][t]:
reach1[i*m+j].append(i*m+t)
t -= 1
t=j+1
while t<m and a[i][t]:
reach1[i * m + j].append(i* m + t)
t+=1
f=1
#print(blacks)
# print(reach1)
for i in blacks:
k=set(reach1[i])
#print(reach1[i])
k.add(i)
for j in reach1[i]:
if j!=i:
for m in reach1[j]:
k.add(m)
for m in blacks:
if m not in k:
f=0
break
if f==0:
break
if f:
print('YES')
else:
print('NO')
return
if __name__ == "__main__":
main()
``` | output | 1 | 97,285 | 7 | 194,571 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider an n Γ m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path.
<image>
You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid.
It's guaranteed that the grid has at least one black cell.
Output
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
Examples
Input
3 4
WWBW
BWWW
WWWB
Output
NO
Input
3 1
B
B
W
Output
YES | instruction | 0 | 97,286 | 7 | 194,572 |
Tags: constructive algorithms, implementation
Correct Solution:
```
def f():
n, m = map(int, input().split())
t = [input() for j in range(n)]
p = [''.join(i) for i in zip(*t)]
if h(p): return 1
i = 0
while i < n and not 'B' in t[i]: i += 1
while i < n:
a = t[i].find('B')
if a < 0:
i += 1
break
b = t[i].rfind('B')
if 'W' in t[i][a: b + 1]: return 1
for j in range(i + 1, n):
if a > 0 and t[j][a - 1] == 'B' and t[j][b] == 'W': return 1
if b < m - 1 and t[j][b + 1] == 'B' and t[j][a] == 'W': return 1
i += 1
while i < n:
if 'B' in t[i]: return 1
i += 1
return 0
def h(t):
i, n = 0, len(t)
while i < n and not 'B' in t[i]: i += 1
while i < n:
a = t[i].find('B')
if a < 0:
i += 1
break
b = t[i].rfind('B')
if 'W' in t[i][a: b + 1]: return 1
i += 1
while i < n:
if 'B' in t[i]: return 1
i += 1
return 0
print('YNEOS'[f():: 2])
``` | output | 1 | 97,286 | 7 | 194,573 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider an n Γ m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path.
<image>
You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid.
It's guaranteed that the grid has at least one black cell.
Output
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
Examples
Input
3 4
WWBW
BWWW
WWWB
Output
NO
Input
3 1
B
B
W
Output
YES | instruction | 0 | 97,287 | 7 | 194,574 |
Tags: constructive algorithms, implementation
Correct Solution:
```
def f():
n, m = map(int, input().split())
t = [input() for j in range(n)]
p = [''.join(i) for i in zip(*t)]
if h(p): return 1
i = 0
while i < n and not 'B' in t[i]: i += 1
while i < n:
a = t[i].find('B')
if a < 0:
i += 1
break
b = t[i].rfind('B')
if 'W' in t[i][a: b + 1]: return 1
for j in range(i + 1, n):
if a > 0 and t[j][a - 1] == 'B' and t[j][b] == 'W': return 1
if b < m - 1 and t[j][b + 1] == 'B' and t[j][a] == 'W': return 1
i += 1
while i < n:
if 'B' in t[i]: return 1
i += 1
return 0
def h(t):
i, n = 0, len(t)
while i < n and not 'B' in t[i]: i += 1
while i < n:
a = t[i].find('B')
if a < 0:
i += 1
break
b = t[i].rfind('B')
if 'W' in t[i][a: b + 1]: return 1
i += 1
while i < n:
if 'B' in t[i]: return 1
i += 1
return 0
print('YNEOS'[f():: 2])
# Made By Mostafa_Khaled
``` | output | 1 | 97,287 | 7 | 194,575 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider an n Γ m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path.
<image>
You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid.
It's guaranteed that the grid has at least one black cell.
Output
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
Examples
Input
3 4
WWBW
BWWW
WWWB
Output
NO
Input
3 1
B
B
W
Output
YES | instruction | 0 | 97,288 | 7 | 194,576 |
Tags: constructive algorithms, implementation
Correct Solution:
```
n, m = map(int, input().split())
z = [[] for i in range(n+1)]
for i in range(n):
a = input()
for j in a:
z[i].append(j)
def solve(n, m):
for i in range(n):
cnt = 0
for j in range(1, m):
if z[i][j] != z[i][j - 1]:
cnt += 1
if cnt > 2:
return 1
if cnt == 2 and z[i][0] == 'B':
return 1
for j in range(m):
cnt = 0
for i in range(1, n):
if z[i][j] != z[i-1][j]:
cnt += 1
if cnt > 2:
return 1
if cnt == 2 and z[0][j] == 'B':
return 1
for i in range(n):
for j in range(m):
if z[i][j] == 'B':
for x in range(i, n):
for y in range(m):
if z[x][y] == 'B':
if z[i][y]=='W' and z[x][j]=='W':
return 1
return 0
print(['YES','NO'][solve(n, m)])
``` | output | 1 | 97,288 | 7 | 194,577 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider an n Γ m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path.
<image>
You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid.
It's guaranteed that the grid has at least one black cell.
Output
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
Examples
Input
3 4
WWBW
BWWW
WWWB
Output
NO
Input
3 1
B
B
W
Output
YES | instruction | 0 | 97,289 | 7 | 194,578 |
Tags: constructive algorithms, implementation
Correct Solution:
```
n,m = map(int, input().split())
row, col_sum, row_sum, black = [], [], [], []
for i in range(n):
row.append(input())
t = [0]
for j in range(m):
t += [t[j] + (row[i][j] == 'B')]
row_sum += [t]
d = [[0,1], [1,0], [-1,0], [0,-1]]
for i in range(n):
for j in range(m):
if row[i][j] is 'W':
continue
w = 0
for di in d:
x = i + di[0]
y = j + di[1]
if x < 0 or y < 0 or x >= n or y >= m:
w += 1 ; continue
if row[x][y] is 'W':
w += 1
if w > 0: black.append((i,j))
for i in range(m):
t = [0]
for j in range(n):
t += [t[j] + (row[j][i] == 'B')]
col_sum += [t]
def row_check(r, s, e):
if s > e: e, s = s, e
return row_sum[r][e + 1] - row_sum[r][s] == e - s + 1
def col_check(c, s, e):
if s > e: e,s = s,e
return col_sum[c][e + 1] - col_sum[c][s] == e - s + 1
res = True
for i in black:
for j in black:
if i <= j:
continue
a = row_check(i[0], i[1], j[1]) and col_check(j[1], i[0], j[0])
b = row_check(j[0], i[1], j[1]) and col_check(i[1], i[0], j[0])
res = res and (a or b)
print('YES' if res else 'NO')
``` | output | 1 | 97,289 | 7 | 194,579 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider an n Γ m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path.
<image>
You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid.
It's guaranteed that the grid has at least one black cell.
Output
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
Examples
Input
3 4
WWBW
BWWW
WWWB
Output
NO
Input
3 1
B
B
W
Output
YES | instruction | 0 | 97,290 | 7 | 194,580 |
Tags: constructive algorithms, implementation
Correct Solution:
```
n, m = map(int, input().split())
grid = []
ans = True
for i in range(n):
grid.append(input())
black = False
change = False
for j in range(m):
if grid[i][j] == "W" and black:
change = True
elif grid[i][j] == "B":
if change and black:
ans = False
black = True
if not ans:
print("NO")
exit()
for j in range(m):
black = False
change = False
for i in range(n):
if grid[i][j] == "W" and black:
change = True
elif grid[i][j] == "B":
if change and black:
print("NO")
exit()
black = True
for i in range(n):
for j in range(m):
if grid[i][j] == "B":
for i_2 in range(n):
for j_2 in range(m):
if grid[i_2][j_2] == "B" and grid[i][j_2] == "W" and grid[i_2][j] == "W":
print("NO")
exit()
print("YES")
``` | output | 1 | 97,290 | 7 | 194,581 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider an n Γ m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path.
<image>
You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid.
It's guaranteed that the grid has at least one black cell.
Output
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
Examples
Input
3 4
WWBW
BWWW
WWWB
Output
NO
Input
3 1
B
B
W
Output
YES
Submitted Solution:
```
n, m = map(int, input().split())
c = [input() for _ in ' ' * n]
def sol(n, m):
for i in range(n):
count = 0
for j in range(1, m):
if c[i][j] != c[i][j - 1]:
count += 1
if count > 2:
return False
if count == 2 and c[i][0]=='B':
return False
for j in range(m):
count = 0
for i in range(1, n):
if c[i][j] != c[i - 1][j]:
count += 1
if count > 2:
return False
if count == 2 and c[0][j]=='B':
return False
for i in range(n):
for j in range(m):
if c[i][j] == 'B':
for x in range(i, n):
for y in range(m):
if c[x][y] == 'B':
if c[i][y] == 'W' and c[x][j] == 'W':
return False
return True
print('NYOE S'[sol(n, m)::2])
``` | instruction | 0 | 97,291 | 7 | 194,582 |
Yes | output | 1 | 97,291 | 7 | 194,583 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider an n Γ m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path.
<image>
You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid.
It's guaranteed that the grid has at least one black cell.
Output
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
Examples
Input
3 4
WWBW
BWWW
WWWB
Output
NO
Input
3 1
B
B
W
Output
YES
Submitted Solution:
```
import sys
input = sys.stdin.readline
def check(x, y):
for i in range(min(x[0], y[0]), max(x[0], y[0]) + 1):
if not plan[i][x[1]] == "B":
return False
for i in range(min(x[1], y[1]), max(x[1], y[1]) + 1):
if not plan[y[0]][i] == "B":
return False
return True
n, m = map(int, input().split())
plan = tuple(tuple(i for i in input().strip()) for j in range(n))
start = [(i, j) for i in range(n) for j in range(m) if plan[i][j] == "B"]
for i in range(len(start)):
for j in range(i + 1, len(start)):
if not check(start[i], start[j]) and not check(start[j], start[i]):
print("NO")
sys.exit()
print("YES")
``` | instruction | 0 | 97,292 | 7 | 194,584 |
Yes | output | 1 | 97,292 | 7 | 194,585 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider an n Γ m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path.
<image>
You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
Input
The first line of the input contains two integers n and m (1 β€ n, m β€ 50) β the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid.
It's guaranteed that the grid has at least one black cell.
Output
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
Examples
Input
3 4
WWBW
BWWW
WWWB
Output
NO
Input
3 1
B
B
W
Output
YES
Submitted Solution:
```
import sys
input=sys.stdin.readline
def exi():
print("NO")
sys.exit()
I=lambda:list(map(int,input().split()))
g=[]
n,m=I()
for i in range(n):
g.append(list(input()))
for i in range(n):
temp=0
for j in range(1,m):
if g[i][j-1]!=g[i][j]:
temp+=1
#print(temp)
if temp>2 or temp==2 and g[i][0]=='B':exi()
for j in range(m):
temp=0
for i in range(1,n):
if g[i-1][j]!=g[i][j]:
temp+=1
if temp>2 or temp==2 and g[0][j]=='B':exi()
for i1 in range(n):
for j1 in range(m):
if g[i1][j1]=='B':
for i2 in range(n):
for j2 in range(m):
if g[i2][j2]=='B':
if g[i1][j2]=='W' and g[i2][j1]=='W':exi()
print("YES")
``` | instruction | 0 | 97,293 | 7 | 194,586 |
Yes | output | 1 | 97,293 | 7 | 194,587 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.