message stringlengths 2 19.9k | message_type stringclasses 2
values | message_id int64 0 1 | conversation_id int64 322 108k | cluster float64 15 15 | __index_level_0__ int64 644 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
Input
The first line contains an integer n (1 ≤ n ≤ 300), number of cards.
The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards.
The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.
Output
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
Examples
Input
3
100 99 9900
1 1 1
Output
2
Input
5
10 20 30 40 50
1 1 1 1 1
Output
-1
Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10
Output
6
Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
Output
7237
Note
In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.
In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1.
Submitted Solution:
```
#D
input()
ok = {0:0}
for p, c in zip(list(map(int, input().split())),
list(map(int, input().split()))):
ad = []
for b, u in ok.items():
a = p
while b:
a,b = b, a % b
ad.append((a, u + c))
for a, u in ad:
ok[a] = min(u, ok.get(a, 1000000000))
print(ok.get(1, -1))
``` | instruction | 0 | 77,844 | 15 | 155,688 |
Yes | output | 1 | 77,844 | 15 | 155,689 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
Input
The first line contains an integer n (1 ≤ n ≤ 300), number of cards.
The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards.
The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.
Output
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
Examples
Input
3
100 99 9900
1 1 1
Output
2
Input
5
10 20 30 40 50
1 1 1 1 1
Output
-1
Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10
Output
6
Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
Output
7237
Note
In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.
In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1.
Submitted Solution:
```
def gcd(x, y):
if y == 0:
return x
return gcd(y, x % y)
n = int(input())
a = [int(x) for x in input().split()]
c = [int(x) for x in input().split()]
f = {}
for i in range(n):
h = {}
for x in f:
h[x] = f[x]
for x in f:
tmp = h[x] + c[i]
g = gcd(x, a[i])
h[g] = min(h[g], tmp) if g in h else tmp
f = h
f[a[i]] = min(f[a[i]], c[i]) if a[i] in f else c[i]
if 1 in f:
print(f[1])
else:
print("-1")
``` | instruction | 0 | 77,845 | 15 | 155,690 |
Yes | output | 1 | 77,845 | 15 | 155,691 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
Input
The first line contains an integer n (1 ≤ n ≤ 300), number of cards.
The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards.
The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.
Output
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
Examples
Input
3
100 99 9900
1 1 1
Output
2
Input
5
10 20 30 40 50
1 1 1 1 1
Output
-1
Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10
Output
6
Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
Output
7237
Note
In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.
In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1.
Submitted Solution:
```
import sys
n = int(input())
l = list(map(int,input().split()))
c = list(map(int,input().split()))
def gcd(a, b):
if b == 0: return a
return gcd(b, a % b)
a = {0:0}
for i in range(n):
b = a.copy()
for p in a.items():
d = gcd(p[0], l[i])
cost = p[1] + c[i]
if d not in b: b[d] = cost
elif b[d] > cost: b[d] = cost
a = b
if 1 not in a: a[1] = -1
print(a[1])
``` | instruction | 0 | 77,846 | 15 | 155,692 |
Yes | output | 1 | 77,846 | 15 | 155,693 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
Input
The first line contains an integer n (1 ≤ n ≤ 300), number of cards.
The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards.
The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.
Output
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
Examples
Input
3
100 99 9900
1 1 1
Output
2
Input
5
10 20 30 40 50
1 1 1 1 1
Output
-1
Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10
Output
6
Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
Output
7237
Note
In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.
In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
def ctd(chr): return ord(chr)-ord("a")
mod = 998244353
INF = float('inf')
from math import gcd
# ------------------------------
def main():
n = N()
larr = RLL()
carr = RLL()
dic = {}
dic[0] = 0
for i in range(n):
l, c = larr[i], carr[i]
ndic = dic.copy()
for j in dic:
now = gcd(j, l)
if now not in ndic:
ndic[now] = c+dic[j]
else:
ndic[now] = min(ndic[now], dic[j]+c)
dic = ndic
print(dic.get(1, -1))
if __name__ == "__main__":
main()
``` | instruction | 0 | 77,847 | 15 | 155,694 |
Yes | output | 1 | 77,847 | 15 | 155,695 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
Input
The first line contains an integer n (1 ≤ n ≤ 300), number of cards.
The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards.
The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.
Output
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
Examples
Input
3
100 99 9900
1 1 1
Output
2
Input
5
10 20 30 40 50
1 1 1 1 1
Output
-1
Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10
Output
6
Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
Output
7237
Note
In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.
In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1.
Submitted Solution:
```
from collections import defaultdict, deque
from math import sqrt, gcd
from array import array
n = int(input())
l = [*map(int, input().split())]
c = [*map(int, input().split())]
if n == 1:
if l[0] != 1:
print(-1)
exit()
else:
print(c[0])
exit()
flag = gcd(l[0], l[1])
if n == 2:
if flag != 1:
print(-1)
exit()
else:
print(c[0] + c[1])
for num in l[2:]:
flag = gcd(flag, num)
if flag != 1:
print(-1)
exit()
ml = max(l)
primes_dp = array('L',[2])
for num in range(3,int(sqrt(ml) + 1), 2):
isPrime = True
for prime in primes_dp:
if num % prime == 0:
isPrime = False
break
if isPrime:
primes_dp.append(num)
def distinct_factors(x):
p = set()
if x == 1:
return frozenset(p)
global primes_dp
for prime in primes_dp:
if x % prime == 0:
p.add(prime)
while x % prime == 0:
x //= prime
if x == 1:
break
return frozenset(p)
store = defaultdict(lambda:100000)
for length, cost in zip(l,c):
store[distinct_factors(length)] = min(cost, store[distinct_factors(length)])
store[frozenset()] = min(store[frozenset()], 100000)
queue = deque(store.keys())
while len(store) > 1:
key = queue.popleft()
while key == frozenset() or key not in store:
if key not in store:
key = queue.popleft()
else:
queue.append(key)
key = queue.popleft()
data = store.pop(key)
new_store = store.copy()
for val in store:
new_key = key.intersection(val)
new_store[new_key] = min(new_store[new_key], data + store[val])
queue.append(new_key)
store = new_store
print(store[frozenset()])
``` | instruction | 0 | 77,848 | 15 | 155,696 |
No | output | 1 | 77,848 | 15 | 155,697 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
Input
The first line contains an integer n (1 ≤ n ≤ 300), number of cards.
The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards.
The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.
Output
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
Examples
Input
3
100 99 9900
1 1 1
Output
2
Input
5
10 20 30 40 50
1 1 1 1 1
Output
-1
Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10
Output
6
Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
Output
7237
Note
In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.
In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1.
Submitted Solution:
```
'''
Created on Feb 5, 2015
@author: simonm
'''
from fractions import gcd
import sys
def set_gcd(numbers):
ret = 0
for number in numbers:
ret = gcd(ret, number)
return ret
# solution = (cost, set(cards))
def solve(solution, cards, costs):
# base case
if set_gcd(solution[1]) == 1 : return solution[0]
if solution[1] == set(cards) : return -1
# look for the result recursively
result = -1
for cost, card in zip(costs, cards):
if card not in solution[1] :
s = solve((solution[0] + cost, solution[1].union([card])), cards, costs)
if result == -1 : result = s
elif s != -1 and s < result : result = s
return result
if __name__ == '__main__':
line = sys.stdin.readline()
line = sys.stdin.readline()
line = sys.stdin.readline()
print(line)
# cards = []
# while not cards :
# line = sys.stdin.readline()
# cards = map(int, line.split())
# costs = []
# while not costs :
# line = sys.stdin.readline()
# costs = map(int, line.split())
# print(solve((0, set()), cards, costs))
# cards = [100, 99, 9900]
# costs = [1, 1, 1]
# print(solve((0, set()), cards, costs))
#
# cards = [10, 20, 30, 40, 50]
# costs = [1, 1, 1, 1, 1]
# print(solve((0, set()), cards, costs))
#
# cards = [15015, 10010, 6006, 4290, 2730, 2310, 1]
# costs = [1, 1, 1, 1, 1, 1, 10]
# print(solve((0, set()), cards, costs))
#
# cards = [4264, 4921, 6321, 6984, 2316, 8432, 6120, 1026]
# costs = [4264, 4921, 6321, 6984, 2316, 8432, 6120, 1026]
# print(solve((0, set()), cards, costs))
``` | instruction | 0 | 77,849 | 15 | 155,698 |
No | output | 1 | 77,849 | 15 | 155,699 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
Input
The first line contains an integer n (1 ≤ n ≤ 300), number of cards.
The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards.
The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.
Output
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
Examples
Input
3
100 99 9900
1 1 1
Output
2
Input
5
10 20 30 40 50
1 1 1 1 1
Output
-1
Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10
Output
6
Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
Output
7237
Note
In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.
In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1.
Submitted Solution:
```
def factors(x) :
ret = set()
for f in range(2, int(x**0.5)+5) :
if x % f == 0:
ret.add(f)
while x % f == 0 :
x //= f
if x != 1 :
ret.add(x)
return ret
N = int(input())
L = list(map(int, input().split(' ')))
C = list(map(int, input().split(' ')))
F = []
for i in L :
F.append(factors(i))
D = dict()
DD = dict()
for i in range(N) :
key = str(F[i])
cost = C[i]
if key in D :
D[key] = min(D[key], cost)
else :
D[key] = cost
DD[key] = F[i]
for i in range(5) :
nD = dict()
for k1 in D :
s1 = DD[k1]
for k2 in D :
s2 = DD[k2]
s = s1&s2
k = str(s)
c = D[k1] + D[k2]
nD[k1] = D[k1]
nD[k2] = D[k2]
if k in nD :
nD[k] = min(nD[k], c)
else :
nD[k] = c
DD[k] = s
D = nD
key = 'set()'
if key in D :
print(D['set()'])
else :
print(-1)
``` | instruction | 0 | 77,850 | 15 | 155,700 |
No | output | 1 | 77,850 | 15 | 155,701 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
Input
The first line contains an integer n (1 ≤ n ≤ 300), number of cards.
The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards.
The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.
Output
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
Examples
Input
3
100 99 9900
1 1 1
Output
2
Input
5
10 20 30 40 50
1 1 1 1 1
Output
-1
Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10
Output
6
Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
Output
7237
Note
In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.
In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1.
Submitted Solution:
```
n = int(input())
l = [int(x) for x in input().split()]
c = [int(x) for x in input().split()]
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
gcds = {0: 0}
for i in range(n):
adds = {}
for g in gcds.keys():
x = gcd(g, l[i])
y = gcds.get(x)
u = gcds[g]
if y is not None:
if u + c[i] < y:
t = adds.get(x)
if t and t > u + c[i]:
adds[x] = u + c[i]
else:
t = adds.get(x)
if t and t > u + c[i]:
adds[x] = u + c[i]
gcds.update(adds)
if gcds.get(1):
print(gcds[1])
else:
print(-1)
``` | instruction | 0 | 77,851 | 15 | 155,702 |
No | output | 1 | 77,851 | 15 | 155,703 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW".
Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to <image>.
In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.
Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).
Input
The first line of the input contains one integer n (2 ≤ n ≤ 100, n is even) — the size of the chessboard.
The second line of the input contains <image> integer numbers <image> (1 ≤ pi ≤ n) — initial positions of the pieces. It is guaranteed that all the positions are distinct.
Output
Print one integer — the minimum number of moves you have to make to place all the pieces in the cells of the same color.
Examples
Input
6
1 2 6
Output
2
Input
10
1 2 3 4 5
Output
10
Note
In the first example the only possible strategy is to move the piece at the position 6 to the position 5 and move the piece at the position 2 to the position 3. Notice that if you decide to place the pieces in the white cells the minimum number of moves will be 3.
In the second example the possible strategy is to move <image> in 4 moves, then <image> in 3 moves, <image> in 2 moves and <image> in 1 move. | instruction | 0 | 77,983 | 15 | 155,966 |
Tags: implementation
Correct Solution:
```
n=int(input())
a = [int(x) for x in input().split()]
a.sort()
a1=0
a2=0
for i in range(0,int(n/2)):
a1+=abs(a[i]-(i*2+1))
a2+=abs(a[i]-i*2-2)
print(min(a1,a2))
``` | output | 1 | 77,983 | 15 | 155,967 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW".
Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to <image>.
In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.
Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).
Input
The first line of the input contains one integer n (2 ≤ n ≤ 100, n is even) — the size of the chessboard.
The second line of the input contains <image> integer numbers <image> (1 ≤ pi ≤ n) — initial positions of the pieces. It is guaranteed that all the positions are distinct.
Output
Print one integer — the minimum number of moves you have to make to place all the pieces in the cells of the same color.
Examples
Input
6
1 2 6
Output
2
Input
10
1 2 3 4 5
Output
10
Note
In the first example the only possible strategy is to move the piece at the position 6 to the position 5 and move the piece at the position 2 to the position 3. Notice that if you decide to place the pieces in the white cells the minimum number of moves will be 3.
In the second example the possible strategy is to move <image> in 4 moves, then <image> in 3 moves, <image> in 2 moves and <image> in 1 move. | instruction | 0 | 77,984 | 15 | 155,968 |
Tags: implementation
Correct Solution:
```
#vladprog
n=int(input())
r1,r2=0,0
p=list(map(int,input().split()))
p.sort()
for i in range(n//2):
r1+=abs(2*i+1-p[i])
r2+=abs(2*i+2-p[i])
print(min(r1,r2))
``` | output | 1 | 77,984 | 15 | 155,969 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW".
Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to <image>.
In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.
Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).
Input
The first line of the input contains one integer n (2 ≤ n ≤ 100, n is even) — the size of the chessboard.
The second line of the input contains <image> integer numbers <image> (1 ≤ pi ≤ n) — initial positions of the pieces. It is guaranteed that all the positions are distinct.
Output
Print one integer — the minimum number of moves you have to make to place all the pieces in the cells of the same color.
Examples
Input
6
1 2 6
Output
2
Input
10
1 2 3 4 5
Output
10
Note
In the first example the only possible strategy is to move the piece at the position 6 to the position 5 and move the piece at the position 2 to the position 3. Notice that if you decide to place the pieces in the white cells the minimum number of moves will be 3.
In the second example the possible strategy is to move <image> in 4 moves, then <image> in 3 moves, <image> in 2 moves and <image> in 1 move. | instruction | 0 | 77,985 | 15 | 155,970 |
Tags: implementation
Correct Solution:
```
def get_ints():
return list(map(int, input().split()))
N = int(input())
a = get_ints()
a = sorted(a)
g = sum([abs(a[i]-(2*i+1)) for i in range(N//2)])
h = sum([abs(a[i]-(2*i+2)) for i in range(N//2)])
print(min(g,h))
``` | output | 1 | 77,985 | 15 | 155,971 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW".
Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to <image>.
In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.
Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).
Input
The first line of the input contains one integer n (2 ≤ n ≤ 100, n is even) — the size of the chessboard.
The second line of the input contains <image> integer numbers <image> (1 ≤ pi ≤ n) — initial positions of the pieces. It is guaranteed that all the positions are distinct.
Output
Print one integer — the minimum number of moves you have to make to place all the pieces in the cells of the same color.
Examples
Input
6
1 2 6
Output
2
Input
10
1 2 3 4 5
Output
10
Note
In the first example the only possible strategy is to move the piece at the position 6 to the position 5 and move the piece at the position 2 to the position 3. Notice that if you decide to place the pieces in the white cells the minimum number of moves will be 3.
In the second example the possible strategy is to move <image> in 4 moves, then <image> in 3 moves, <image> in 2 moves and <image> in 1 move. | instruction | 0 | 77,986 | 15 | 155,972 |
Tags: implementation
Correct Solution:
```
n = int(input())
p = list(sorted(map(int, input().split())))
s1 = s2 = 0
for i in range(n // 2):
k = 1 + i * 2
s1 += abs(p[i] - k)
s2 += abs(p[i] - k - 1)
print(min(s1, s2))
``` | output | 1 | 77,986 | 15 | 155,973 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW".
Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to <image>.
In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.
Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).
Input
The first line of the input contains one integer n (2 ≤ n ≤ 100, n is even) — the size of the chessboard.
The second line of the input contains <image> integer numbers <image> (1 ≤ pi ≤ n) — initial positions of the pieces. It is guaranteed that all the positions are distinct.
Output
Print one integer — the minimum number of moves you have to make to place all the pieces in the cells of the same color.
Examples
Input
6
1 2 6
Output
2
Input
10
1 2 3 4 5
Output
10
Note
In the first example the only possible strategy is to move the piece at the position 6 to the position 5 and move the piece at the position 2 to the position 3. Notice that if you decide to place the pieces in the white cells the minimum number of moves will be 3.
In the second example the possible strategy is to move <image> in 4 moves, then <image> in 3 moves, <image> in 2 moves and <image> in 1 move. | instruction | 0 | 77,987 | 15 | 155,974 |
Tags: implementation
Correct Solution:
```
n = int(input())
p = sorted(map(int, input().split()))
ans1 = 0
ans2 = 0
for i, j in enumerate(p):
ans1 += abs((1 + i*2) - j)
ans2 += abs((2 + i*2) - j)
print (min(ans1, ans2))
``` | output | 1 | 77,987 | 15 | 155,975 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW".
Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to <image>.
In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.
Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).
Input
The first line of the input contains one integer n (2 ≤ n ≤ 100, n is even) — the size of the chessboard.
The second line of the input contains <image> integer numbers <image> (1 ≤ pi ≤ n) — initial positions of the pieces. It is guaranteed that all the positions are distinct.
Output
Print one integer — the minimum number of moves you have to make to place all the pieces in the cells of the same color.
Examples
Input
6
1 2 6
Output
2
Input
10
1 2 3 4 5
Output
10
Note
In the first example the only possible strategy is to move the piece at the position 6 to the position 5 and move the piece at the position 2 to the position 3. Notice that if you decide to place the pieces in the white cells the minimum number of moves will be 3.
In the second example the possible strategy is to move <image> in 4 moves, then <image> in 3 moves, <image> in 2 moves and <image> in 1 move. | instruction | 0 | 77,988 | 15 | 155,976 |
Tags: implementation
Correct Solution:
```
n = int(input())
p = list(map(int, input().split()))
white = [x for x in range(1, n+1, 2)]
black = [x for x in range(2, n+1, 2)]
p.sort()
ws = sum([abs(white[i]-p[i]) for i in range(n//2)])
bs = sum([abs(black[i]-p[i]) for i in range(n//2)])
print(min(ws, bs))
``` | output | 1 | 77,988 | 15 | 155,977 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW".
Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to <image>.
In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.
Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).
Input
The first line of the input contains one integer n (2 ≤ n ≤ 100, n is even) — the size of the chessboard.
The second line of the input contains <image> integer numbers <image> (1 ≤ pi ≤ n) — initial positions of the pieces. It is guaranteed that all the positions are distinct.
Output
Print one integer — the minimum number of moves you have to make to place all the pieces in the cells of the same color.
Examples
Input
6
1 2 6
Output
2
Input
10
1 2 3 4 5
Output
10
Note
In the first example the only possible strategy is to move the piece at the position 6 to the position 5 and move the piece at the position 2 to the position 3. Notice that if you decide to place the pieces in the white cells the minimum number of moves will be 3.
In the second example the possible strategy is to move <image> in 4 moves, then <image> in 3 moves, <image> in 2 moves and <image> in 1 move. | instruction | 0 | 77,989 | 15 | 155,978 |
Tags: implementation
Correct Solution:
```
import copy
def chess_min_mov(n, positions):
black_moves = 0
black_positions = copy.copy(positions)
for index in range(1, n+1, 2):
black_moves += abs(index-black_positions.pop(0))
white_moves = 0
for index in range(2, n+1, 2):
white_moves += abs(index-positions.pop(0))
return min(black_moves,white_moves)
n = int(input())
positions = list(map(int, input().split(' ')))
print(chess_min_mov(n, sorted(positions)))
``` | output | 1 | 77,989 | 15 | 155,979 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW".
Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to <image>.
In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.
Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).
Input
The first line of the input contains one integer n (2 ≤ n ≤ 100, n is even) — the size of the chessboard.
The second line of the input contains <image> integer numbers <image> (1 ≤ pi ≤ n) — initial positions of the pieces. It is guaranteed that all the positions are distinct.
Output
Print one integer — the minimum number of moves you have to make to place all the pieces in the cells of the same color.
Examples
Input
6
1 2 6
Output
2
Input
10
1 2 3 4 5
Output
10
Note
In the first example the only possible strategy is to move the piece at the position 6 to the position 5 and move the piece at the position 2 to the position 3. Notice that if you decide to place the pieces in the white cells the minimum number of moves will be 3.
In the second example the possible strategy is to move <image> in 4 moves, then <image> in 3 moves, <image> in 2 moves and <image> in 1 move. | instruction | 0 | 77,990 | 15 | 155,980 |
Tags: implementation
Correct Solution:
```
n=int(input())
pos=list(map(int,input().split()))
pos.sort()
bsum=sum([abs(pos[i]-2*i-1) for i in range(int(n/2))])
wsum=sum([abs(pos[i]-2*i-2) for i in range(int(n/2))])
print (min(bsum,wsum))
``` | output | 1 | 77,990 | 15 | 155,981 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW".
Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to <image>.
In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.
Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).
Input
The first line of the input contains one integer n (2 ≤ n ≤ 100, n is even) — the size of the chessboard.
The second line of the input contains <image> integer numbers <image> (1 ≤ pi ≤ n) — initial positions of the pieces. It is guaranteed that all the positions are distinct.
Output
Print one integer — the minimum number of moves you have to make to place all the pieces in the cells of the same color.
Examples
Input
6
1 2 6
Output
2
Input
10
1 2 3 4 5
Output
10
Note
In the first example the only possible strategy is to move the piece at the position 6 to the position 5 and move the piece at the position 2 to the position 3. Notice that if you decide to place the pieces in the white cells the minimum number of moves will be 3.
In the second example the possible strategy is to move <image> in 4 moves, then <image> in 3 moves, <image> in 2 moves and <image> in 1 move.
Submitted Solution:
```
n=int(input())
v=list(map(int,input().split()))
v.sort()
even=[]
odd=[]
for x in range(1,n+1):
if(x%2):
odd.append(x)
else:
even.append(x)
a=0
b=0
for x in range(0,int(n/2)):
a=a+abs(odd[x]-v[x])
b=b+abs(even[x]-v[x])
if a<b:
print(a)
else:
print(b)
``` | instruction | 0 | 77,991 | 15 | 155,982 |
Yes | output | 1 | 77,991 | 15 | 155,983 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW".
Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to <image>.
In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.
Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).
Input
The first line of the input contains one integer n (2 ≤ n ≤ 100, n is even) — the size of the chessboard.
The second line of the input contains <image> integer numbers <image> (1 ≤ pi ≤ n) — initial positions of the pieces. It is guaranteed that all the positions are distinct.
Output
Print one integer — the minimum number of moves you have to make to place all the pieces in the cells of the same color.
Examples
Input
6
1 2 6
Output
2
Input
10
1 2 3 4 5
Output
10
Note
In the first example the only possible strategy is to move the piece at the position 6 to the position 5 and move the piece at the position 2 to the position 3. Notice that if you decide to place the pieces in the white cells the minimum number of moves will be 3.
In the second example the possible strategy is to move <image> in 4 moves, then <image> in 3 moves, <image> in 2 moves and <image> in 1 move.
Submitted Solution:
```
n = int(input())
m = map(int, input().split())
s1, s2 = 0, 0
for i, v in enumerate(sorted(m)):
s1 += abs(v - 2*i-1)
s2 += abs(v - 2*i-2)
print(min(s1,s2))
``` | instruction | 0 | 77,992 | 15 | 155,984 |
Yes | output | 1 | 77,992 | 15 | 155,985 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW".
Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to <image>.
In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.
Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).
Input
The first line of the input contains one integer n (2 ≤ n ≤ 100, n is even) — the size of the chessboard.
The second line of the input contains <image> integer numbers <image> (1 ≤ pi ≤ n) — initial positions of the pieces. It is guaranteed that all the positions are distinct.
Output
Print one integer — the minimum number of moves you have to make to place all the pieces in the cells of the same color.
Examples
Input
6
1 2 6
Output
2
Input
10
1 2 3 4 5
Output
10
Note
In the first example the only possible strategy is to move the piece at the position 6 to the position 5 and move the piece at the position 2 to the position 3. Notice that if you decide to place the pieces in the white cells the minimum number of moves will be 3.
In the second example the possible strategy is to move <image> in 4 moves, then <image> in 3 moves, <image> in 2 moves and <image> in 1 move.
Submitted Solution:
```
n=int(input())
a=[int(x) for x in input().split()]
a=sorted(a)
l=len(a)
a1=[]
a2=[]
for i in range(1,n,2):
a1.append(i)
for i in range(2,n+1,2):
a2.append(i)
s1=0
s2=0
for i in range(l):
s1=s1+abs(a1[i]-a[i])
for i in range(l):
s2=s2+abs(a2[i]-a[i])
print(min(s1,s2))
``` | instruction | 0 | 77,993 | 15 | 155,986 |
Yes | output | 1 | 77,993 | 15 | 155,987 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW".
Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to <image>.
In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.
Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).
Input
The first line of the input contains one integer n (2 ≤ n ≤ 100, n is even) — the size of the chessboard.
The second line of the input contains <image> integer numbers <image> (1 ≤ pi ≤ n) — initial positions of the pieces. It is guaranteed that all the positions are distinct.
Output
Print one integer — the minimum number of moves you have to make to place all the pieces in the cells of the same color.
Examples
Input
6
1 2 6
Output
2
Input
10
1 2 3 4 5
Output
10
Note
In the first example the only possible strategy is to move the piece at the position 6 to the position 5 and move the piece at the position 2 to the position 3. Notice that if you decide to place the pieces in the white cells the minimum number of moves will be 3.
In the second example the possible strategy is to move <image> in 4 moves, then <image> in 3 moves, <image> in 2 moves and <image> in 1 move.
Submitted Solution:
```
import sys, math
n = int(sys.stdin.readline())
arr = list(map(int, sys.stdin.readline().split()))
arr.sort()
odd = []
even = []
for i in range(1, n + 1, 2):
j = i
temp = []
while j <= n:
temp.append(j)
j += 2
if len(temp) == len(arr):
odd.append(temp)
for i in range(2, n + 1, 2):
j = i
temp = []
while j <= n:
temp.append(j)
j += 2
if len(temp) == len(arr):
even.append(temp)
ans = 9876543210
for i in odd:
temp = 0
for j in range(len(arr)):
temp += abs(i[j] - arr[j])
ans = min(temp, ans)
for i in even:
temp = 0
for j in range(len(arr)):
temp += abs(i[j] - arr[j])
ans = min(temp, ans)
print(ans)
``` | instruction | 0 | 77,994 | 15 | 155,988 |
Yes | output | 1 | 77,994 | 15 | 155,989 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW".
Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to <image>.
In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.
Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).
Input
The first line of the input contains one integer n (2 ≤ n ≤ 100, n is even) — the size of the chessboard.
The second line of the input contains <image> integer numbers <image> (1 ≤ pi ≤ n) — initial positions of the pieces. It is guaranteed that all the positions are distinct.
Output
Print one integer — the minimum number of moves you have to make to place all the pieces in the cells of the same color.
Examples
Input
6
1 2 6
Output
2
Input
10
1 2 3 4 5
Output
10
Note
In the first example the only possible strategy is to move the piece at the position 6 to the position 5 and move the piece at the position 2 to the position 3. Notice that if you decide to place the pieces in the white cells the minimum number of moves will be 3.
In the second example the possible strategy is to move <image> in 4 moves, then <image> in 3 moves, <image> in 2 moves and <image> in 1 move.
Submitted Solution:
```
def cheess(n,p):
a=0
for i in range(n//2):
a+=(abs((p[i]-1)-(i*2)))
return a
n=int(input())
p=[int(x) for x in input().split()]
ap=[51-x for x in p]
print(min(cheess(n,p),cheess(n,ap)))
``` | instruction | 0 | 77,995 | 15 | 155,990 |
No | output | 1 | 77,995 | 15 | 155,991 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW".
Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to <image>.
In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.
Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).
Input
The first line of the input contains one integer n (2 ≤ n ≤ 100, n is even) — the size of the chessboard.
The second line of the input contains <image> integer numbers <image> (1 ≤ pi ≤ n) — initial positions of the pieces. It is guaranteed that all the positions are distinct.
Output
Print one integer — the minimum number of moves you have to make to place all the pieces in the cells of the same color.
Examples
Input
6
1 2 6
Output
2
Input
10
1 2 3 4 5
Output
10
Note
In the first example the only possible strategy is to move the piece at the position 6 to the position 5 and move the piece at the position 2 to the position 3. Notice that if you decide to place the pieces in the white cells the minimum number of moves will be 3.
In the second example the possible strategy is to move <image> in 4 moves, then <image> in 3 moves, <image> in 2 moves and <image> in 1 move.
Submitted Solution:
```
n=int(input())
p=list(map(int,input().split()))
print(min(sum(abs(x-i)for x,i in zip(p,range(s,n+1,2)))for s in(1,2)))
``` | instruction | 0 | 77,996 | 15 | 155,992 |
No | output | 1 | 77,996 | 15 | 155,993 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW".
Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to <image>.
In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.
Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).
Input
The first line of the input contains one integer n (2 ≤ n ≤ 100, n is even) — the size of the chessboard.
The second line of the input contains <image> integer numbers <image> (1 ≤ pi ≤ n) — initial positions of the pieces. It is guaranteed that all the positions are distinct.
Output
Print one integer — the minimum number of moves you have to make to place all the pieces in the cells of the same color.
Examples
Input
6
1 2 6
Output
2
Input
10
1 2 3 4 5
Output
10
Note
In the first example the only possible strategy is to move the piece at the position 6 to the position 5 and move the piece at the position 2 to the position 3. Notice that if you decide to place the pieces in the white cells the minimum number of moves will be 3.
In the second example the possible strategy is to move <image> in 4 moves, then <image> in 3 moves, <image> in 2 moves and <image> in 1 move.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
e,o=0,0
j=(n//2)-1
for i in range(n-1,0,-2):
if a[j]-i<0:
o+=i-a[j]
else:
o+=a[j]-i
j-=1
j=(n//2)-1
for i in range(n,1,-2):
if a[j]-i<0:
e+=i-a[j]
else:
e+=a[j]-i
j-=1
print(min(e,o))
``` | instruction | 0 | 77,997 | 15 | 155,994 |
No | output | 1 | 77,997 | 15 | 155,995 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW".
Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to <image>.
In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.
Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).
Input
The first line of the input contains one integer n (2 ≤ n ≤ 100, n is even) — the size of the chessboard.
The second line of the input contains <image> integer numbers <image> (1 ≤ pi ≤ n) — initial positions of the pieces. It is guaranteed that all the positions are distinct.
Output
Print one integer — the minimum number of moves you have to make to place all the pieces in the cells of the same color.
Examples
Input
6
1 2 6
Output
2
Input
10
1 2 3 4 5
Output
10
Note
In the first example the only possible strategy is to move the piece at the position 6 to the position 5 and move the piece at the position 2 to the position 3. Notice that if you decide to place the pieces in the white cells the minimum number of moves will be 3.
In the second example the possible strategy is to move <image> in 4 moves, then <image> in 3 moves, <image> in 2 moves and <image> in 1 move.
Submitted Solution:
```
n=int(input())
x=[*map(int,input().split())]
ans1,ans2=0,0
for i in range(len(x)):
ans1+=abs(x[i]-(i*2+1))
ans2+=abs(x[i]-((i+1)*2))
print(min(ans1,ans2))
``` | instruction | 0 | 77,998 | 15 | 155,996 |
No | output | 1 | 77,998 | 15 | 155,997 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement. | instruction | 0 | 78,413 | 15 | 156,826 |
Tags: constructive algorithms, dfs and similar, dsu, graphs
Correct Solution:
```
from collections import deque
n, m = map(int, input().split())
a = []
for _ in range(n):
a.append(input())
# n = 1000
# m = 1000
# a = [['#'] * m for _ in range(n)]
used = [[False] * m for _ in range(n)]
used_row = [False] * n
used_col = [False] * m
def build(i, j):
q = deque()
q.append((i, j))
i_min, i_max = (i, i)
j_min, j_max = (j, j)
while len(q) > 0:
i, j = q.popleft()
if i_min > i:
i_min = i
if i_max < i:
i_max = i
if j_min > j:
j_min = j
if j_max < j:
j_max = j
if i != 0 and not used[i - 1][j] and a[i - 1][j] == '#':
used[i - 1][j] = True
q.append((i - 1, j))
if i != n - 1 and not used[i + 1][j] and a[i + 1][j] == '#':
used[i + 1][j] = True
q.append((i + 1, j))
if j != 0 and not used[i][j - 1] and a[i][j - 1] == '#':
used[i][j - 1] = True
q.append((i, j - 1))
if j != m - 1 and not used[i][j + 1] and a[i][j + 1] == '#':
used[i][j + 1] = True
q.append((i, j + 1))
return i_min, i_max, j_min, j_max
def solve1():
res = 0
for i in range(n):
for j in range(m):
if a[i][j] == '#' and not used[i][j]:
res += 1
i_min, i_max, j_min, j_max = build(i, j)
for i_ in range(i_min, i_max + 1):
if used_row[i_]:
return -1
used_row[i_] = True
for j_ in range(j_min, j_max + 1):
if used_col[j_]:
return -1
used_col[j_] = True
if False in used_row or False in used_col:
if False not in used_row or False not in used_col:
return -1
return res
def solve():
for i in range(n):
flag = False
for j in range(m):
if a[i][j] == '#':
if not flag:
flag = True
elif a[i][j - 1] != '#':
return -1
for j in range(m):
flag = False
for i in range(n):
if a[i][j] == '#':
if not flag:
flag = True
elif a[i - 1][j] != '#':
return -1
return 1
if solve() == -1:
print(-1)
else:
print(solve1())
``` | output | 1 | 78,413 | 15 | 156,827 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement. | instruction | 0 | 78,414 | 15 | 156,828 |
Tags: constructive algorithms, dfs and similar, dsu, graphs
Correct Solution:
```
def read_int():
return int(input().strip())
def read_ints():
return list(map(int, input().strip().split(' ')))
def print_table(title, table):
print(title)
for row in table:
print(list(map(int, row)))
def validate(grid):
n, m = len(grid), len(grid[0])
has_left = [[False]*m for _ in range(n)]
has_right = [[False]*m for _ in range(n)]
has_top = [[False]*m for _ in range(n)]
has_bottom = [[False]*m for _ in range(n)]
for i in range(n):
for j in range(m):
if j == 0:
has_left[i][j] = grid[i][j] == '#'
else:
has_left[i][j] = has_left[i][j-1] or grid[i][j] == '#'
if j == 0:
has_right[i][m-1-j] = grid[i][m-1-j] == '#'
else:
has_right[i][m-1-j] = has_right[i][m-j] or grid[i][m-1-j] == '#'
for j in range(m):
for i in range(n):
if i == 0:
has_top[i][j] = grid[i][j] == '#'
else:
has_top[i][j] = has_top[i-1][j] or grid[i][j] == '#'
if i == 0:
has_bottom[n-1-i][j] = grid[n-i-1][j] == '#'
else:
has_bottom[n-1-i][j] = has_bottom[n-i][j] or grid[n-i-1][j] == '#'
for i in range(n):
for j in range(m):
if grid[i][j] == '.' and ((has_left[i][j] and has_right[i][j]) or (has_top[i][j] and has_bottom[i][j])):
return False
for i in range(n):
if not has_right[i][0]:
# check
achievable = False
for j in range(m):
if not has_top[i][j] and not has_bottom[i][j]:
achievable = True
break
if not achievable:
return False
for j in range(m):
if not has_bottom[0][j]:
# check
achievable = False
for i in range(n):
if not has_left[i][j] and not has_right[i][j]:
achievable = True
break
if not achievable:
return False
return True
def solve():
n, m = read_ints()
grid = []
for _ in range(n):
grid.append(list(input().strip()))
if not validate(grid):
return -1
count = 0
for i in range(n):
for j in range(m):
if grid[i][j] == '#':
count += 1
# do dfs
Q = [(i, j)]
while len(Q):
i, j = Q.pop()
for x, y in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]:
if 0 <= x < n and 0 <= y < m and grid[x][y] == '#':
grid[x][y] = '.'
Q.append((x, y))
return count
if __name__ == '__main__':
print(solve())
``` | output | 1 | 78,414 | 15 | 156,829 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement. | instruction | 0 | 78,415 | 15 | 156,830 |
Tags: constructive algorithms, dfs and similar, dsu, graphs
Correct Solution:
```
import sys
input = sys.stdin.readline
def print(val):
sys.stdout.write(str(val) + '\n')
from collections import deque
def find_components(node,graph,n,m,visited):
queue = deque([node])
while queue:
node = queue[-1]
visited.add(node)
neighbors = [(node[0]+1,node[1]),(node[0]-1,node[1]),\
(node[0],node[1]+1),(node[0],node[1]-1)]
had_neighbors = False
for neighbor in neighbors:
i,j = neighbor
if neighbor not in visited and 0<= i < n and 0<= j < m and graph[i][j] == '#':
queue.append(neighbor)
had_neighbors = True
break
if not had_neighbors:
queue.pop()
def yo():
n,m = map(int,input().split())
graph = [input().strip() for i in range(n)]
e_row = 0
e_column = 0
for row in graph:
if row == "."*m:
e_row = 1
break
for j in range(m):
same = True
for i in range(n):
if graph[i][j] != '.':
same = False
break
if same:
e_column = 1
break
if e_row^e_column == 1:
print(-1)
return
for row in graph:
start = m-1
value = '#'
for j in range(m):
if row[j] == '#':
start = j
break
change = False
gap = False
for j in range(start+1,m):
if row[j] != value:
change = True
elif change:
gap = True
if gap:
print(-1)
break
if not gap:
for j in range(m):
start = n-1
value = '#'
for i in range(n):
if graph[i][j] == '#':
start = i
break
change = False
gap = False
for i in range(start+1,n):
if graph[i][j] != value:
change = True
elif change:
gap = True
if gap:
print(-1)
break
if not gap:
visited = set()
num_components = 0
for i in range(n):
for j in range(m):
if (i,j) not in visited and graph[i][j] == '#':
num_components += 1
find_components((i,j),graph,n,m,visited)
print(num_components)
yo()
``` | output | 1 | 78,415 | 15 | 156,831 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement. | instruction | 0 | 78,416 | 15 | 156,832 |
Tags: constructive algorithms, dfs and similar, dsu, graphs
Correct Solution:
```
try:
step=[[0,1],[0,-1],[-1,0],[1,0]]
n,m=list(map(int,input().split()))
vis=[[0 for i in range(1005)] for j in range(1005)]
s=[]
for i in range(n):s.append(input())
def check(i,j):
return i>=0 and i<n and j>=0 and j<m and s[i][j]=='#'
def bfs(x,y):
pos=[(x,y)]
while len(pos):
x,y=pos.pop(0)
for i in range(4):
nxtx=x+step[i][0]
nxty=y+step[i][1]
if(check(nxtx,nxty) and vis[nxtx][nxty]==0):
vis[nxtx][nxty]=1
pos.append((nxtx,nxty))
bx=0
by=0
ok=True
for i in range(n):
sta=-1
end=-2
num=0
for j in range(m):
if s[i][j]=='#':
if sta==-1:
sta=j
end=j
num+=1
if num!=end-sta+1:
ok=False
break
if num==0:
bx+=1
for i in range(m):
sta=-1
end=-2
num=0
for j in range(n):
if s[j][i]=='#':
if sta==-1:
sta=j
end=j
num+=1
if num!=end-sta+1:
ok=False
break
if num==0:
by+=1
if ok==False or (bx==0 and by!=0) or(bx!=0 and by==0):
print("-1")
else:
ans=0
for i in range(n):
for j in range(m):
if vis[i][j]==0 and s[i][j]=='#':
vis[i][j]=1
bfs(i,j)
ans+=1
print(ans)
except Exception as e:
print(str(e))
``` | output | 1 | 78,416 | 15 | 156,833 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement. | instruction | 0 | 78,417 | 15 | 156,834 |
Tags: constructive algorithms, dfs and similar, dsu, graphs
Correct Solution:
```
from sys import exit
n, m = map(int, input().split())
a = [tuple(input()) for i in range(n)]
whiteline = False
whilecolumne = False
howmany = 0
ar = [[0] * m for i in range(n)]
for x in range(n):
lastelem = '.'
shag = 0
for y in range(m):
elem = a[x][y]
if elem == '#':
if lastelem != elem:
newnam = howmany + 1
if x!= 0:
if ar[x-1][y] != 0: newnam = ar[x-1][y]
elif ar[x][y] != 0: newnam = ar[x][y]
else:
howmany += 1
elif ar[x][y] != 0: newnam = ar[x][y]
else:
howmany += 1
x1 = x + 1
y1 = y
ar[x][y] = newnam
if x1 != n:
while y1 != -1 and a[x1][y1] == "#":
ar[x1][y1] = newnam
y1 -= 1
else:
ar[x][y] = ar[x][y-1]
if elem != lastelem:
shag += 1
lastelem = elem
if shag == 0: whiteline = True
if shag > 2:
print(-1)
exit()
for y in range(m):
lastelem = '.'
shag = 0
for x in range(n):
elem = a[x][y]
if elem != lastelem:
shag += 1
lastelem = elem
if shag == 0: whilecolumne = True
if shag > 2:
print(-1)
exit()
if whilecolumne ^ whiteline:
print(-1)
exit()
print(howmany)
``` | output | 1 | 78,417 | 15 | 156,835 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement. | instruction | 0 | 78,418 | 15 | 156,836 |
Tags: constructive algorithms, dfs and similar, dsu, graphs
Correct Solution:
```
from sys import stdin,stdout
from bisect import bisect_left,bisect_right
# stdin = open("input.txt","r")
# stdout = open("output.txt","w")
n,m = stdin.readline().strip().split(' ')
n,m = int(n),int(m)
mtr=[]
for i in range(n):
mtr.append(stdin.readline().strip())
# VALIDATION
emp_col=0;
emp_row=0;
flag=True
if flag:
for i in range(n):
ctr=0
for j in range(m):
if ctr==0:
if mtr[i][j]=='#':
ctr+=1
elif ctr==1:
if mtr[i][j]=='.':
ctr+=1
elif ctr==2:
if mtr[i][j]=='#':
flag=False
break
if ctr == 0:
emp_col+=1
if not flag:
break
if flag:
for j in range(m):
ctr=0
for i in range(n):
if ctr==0:
if mtr[i][j]=='#':
ctr+=1
elif ctr==1:
if mtr[i][j]=='.':
ctr+=1
elif ctr==2:
if mtr[i][j]=='#':
flag=False
break
if ctr == 0:
emp_row+=1
if not flag:
break
if flag:
if (emp_row>0 and emp_col==0) or (emp_row==0 and emp_col>0):
flag=False
if flag:
par=[i for i in range(n*m)]
ppp=[0 for i in range(n*m)]
def union(x,y):
x,y=find(x),find(y)
if x!=y:
if ppp[x]>ppp[y]:
par[y]=x;ppp[x]+=ppp[y]
else:
par[x]=y;ppp[y]+=ppp[x]
def find(x):
if x==par[x]:
return x
par[x]=find(par[x])
return par[x]
for i in range(n):
for j in range(m):
if mtr[i][j]=='#':
if i+1<n:
if mtr[i+1][j]=='#':
union(i*m+j,(i+1)*m+j)
if j+1<m:
if mtr[i][j+1]=='#':
union(i*m+j,i*m+j+1)
t1=set()
for i in range(n):
for j in range(m):
if mtr[i][j]=='#':
t1.add(find(i*m+j))
stdout.write(str(len(t1))+"\n")
# print(t1)
else:
stdout.write("-1\n")
``` | output | 1 | 78,418 | 15 | 156,837 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement. | instruction | 0 | 78,419 | 15 | 156,838 |
Tags: constructive algorithms, dfs and similar, dsu, graphs
Correct Solution:
```
n, m = map(int, input().split())
a = []
for _ in range(n):
a.append(input())
# n = 1000
# m = 1000
# a = [['#'] * m for _ in range(n)]
used = [[False] * m for _ in range(n)]
used_row = [False] * n
used_col = [False] * m
def build(i, j):
q = [(i, j)]
i_min, i_max = (i, i)
j_min, j_max = (j, j)
while len(q) > 0:
i, j = q[0]
q = q[1:]
if i_min > i:
i_min = i
if i_max < i:
i_max = i
if j_min > j:
j_min = j
if j_max < j:
j_max = j
if i != 0 and not used[i-1][j] and a[i-1][j] == '#':
used[i-1][j] = True
q.append((i - 1, j))
if i != n -1 and not used[i + 1][j] and a[i+1][j] == '#':
used[i+1][j] = True
q.append((i + 1, j))
if j != 0 and not used[i ][j - 1] and a[i][j-1] == '#':
used[i][j-1] = True
q.append((i, j - 1))
if j != m - 1 and not used[i][j+1] and a[i][j+1] == '#':
used[i][j+1] = True
q.append((i, j + 1))
return i_min, i_max, j_min, j_max
def solve1():
res = 0
for i in range(n):
for j in range(m):
if a[i][j] == '#' and not used[i][j]:
res += 1
i_min, i_max, j_min, j_max = build(i, j)
for i_ in range(i_min, i_max + 1):
if used_row[i_]:
return -1
used_row[i_] = True
for j_ in range(j_min, j_max + 1):
if used_col[j_]:
return -1
used_col[j_] = True
if False in used_row or False in used_col:
if False not in used_row or False not in used_col:
return -1
return res
def solve():
for i in range(n):
flag = False
for j in range(m):
if a[i][j] == '#':
if not flag:
flag = True
elif a[i][j - 1] != '#':
return -1
for j in range(m):
flag = False
for i in range(n):
if a[i][j] == '#':
if not flag:
flag = True
elif a[i - 1][j] != '#':
return -1
return 1
if solve() == -1:
print(-1)
else:
print(solve1())
``` | output | 1 | 78,419 | 15 | 156,839 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement. | instruction | 0 | 78,420 | 15 | 156,840 |
Tags: constructive algorithms, dfs and similar, dsu, graphs
Correct Solution:
```
from sys import stdin
input=lambda : stdin.readline().strip()
from math import ceil,sqrt,factorial,gcd
def check(z):
c=0
for i in range(len(z)):
if z[i]=='#':
if c==0:
c+=1
else:
if z[i-1]!='#':
return False
return True
n,m=map(int,input().split())
l=[]
emptyrow=0
emptycol=0
for i in range(n):
l.append(list(input()))
if l[i].count('#')==0:
emptyrow+=1
if check(l[i])==False:
print(-1)
exit()
for i in range(m):
f=0
z=[]
for j in range(n):
z.append(l[j][i])
if l[j][i]=='.':
f+=1
if f==n:
emptycol+=1
if check(z)==False:
print(-1)
exit()
if (emptyrow>0 and emptycol>0) or (emptycol==0 and emptyrow==0):
s=[[0 for i in range(m)] for i in range(n)]
count=0
connected=dict()
z=[]
for i in range(n):
for j in range(m):
if l[i][j]=='#':
x=1
connected[(i,j)]=[]
if i>0 and l[i-1][j]=='#':
connected[(i-1,j)].append((i,j))
connected[(i,j)].append((i-1,j))
else:
x+=1
if j>0 and l[i][j-1]=='#':
connected[(i,j-1)].append((i,j))
connected[(i,j)].append((i,j-1))
else:
x+=1
if x==3:
z.append((i,j))
for i in z:
if s[i[0]][i[1]]==0:
stack=[i]
count+=1
while stack:
a=stack.pop()
for j in connected[a]:
if s[j[0]][j[1]]==0:
stack.append(j)
s[j[0]][j[1]]=1
s[a[0]][a[1]]=1
del connected[a]
print(count)
else:
print(-1)
``` | output | 1 | 78,420 | 15 | 156,841 |
Provide tags and a correct Python 2 solution for this coding contest problem.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement. | instruction | 0 | 78,421 | 15 | 156,842 |
Tags: constructive algorithms, dfs and similar, dsu, graphs
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
def fun(x):
return 1*(x=='#')
def in_num():
return int(raw_input())
def in_arr():
return map(fun,raw_input().strip())
def pr_num(n):
stdout.write(str(n)+'\n')
def pr_arr(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
n,m=map(int,raw_input().split())
l=[]
sm=0
for i in range(n):
l.append(in_arr())
sm+=sum(l[-1])
if sm==0:
pr_num(0)
exit()
if n==1 or m==1:
if sm!=n*m:
pr_num(-1)
else:
pr_num(1)
exit()
f1,f2=0,0
for i in range(n):
c=0
sm=l[i][-1]
for j in range(m-1):
if l[i][j]:
c=1
sm+=l[i][j]
if l[i][j]==0 and c and l[i][j+1]:
pr_num(-1)
exit()
if sm==0:
f1=1
for j in range(m):
f=0
sm=l[-1][j]
for i in range(n-1):
sm+=l[i][j]
if l[i][j]==1:
f=1
if l[i][j]==0 and f and l[i+1][j]==1:
pr_num(-1)
exit()
if sm==0:
f2=1
if f1^f2:
pr_num(-1)
exit()
vis=[[0 for i in range(m)] for j in range(n)]
ans=0
move=[(1,0),(-1,0),(0,1),(0,-1)]
f=0
for i in range(n):
for j in range(m):
if l[i][j] and not vis[i][j]:
#print 'x',i,j
vis[i][j]=1
q=[(i,j)]
ans+=1
while q:
x,y=q.pop()
#print x,y
for x1,y1 in move:
x2=x1+x
y2=y1+y
if x2>=0 and x2<n and y2>=0 and y2<m:
if l[x2][y2] and not vis[x2][y2]:
vis[x2][y2]=1
q.append((x2,y2))
pr_num(ans)
``` | output | 1 | 78,421 | 15 | 156,843 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Submitted Solution:
```
n,m=map(int,input().split())
grid=[0]*n
possible=1
bl=0
bc=0
for i in range(n):
s=input()
l=[0]*m
bs=0
be=0
for j in range(m):
if s[j]=='.':
l[j]=1
if bs==1:
be=1
else:
bs=1
if be==1:
possible=0
grid[i]=l
if bs==0:
bl=1
if possible==1:
for j in range(m):
bs=0
be=0
for i in range(n):
if grid[i][j]==1:
if bs==1:
be=1
else:
bs=1
if be==1:
possible=0
if bs==0:
bc=1
if bl+bc==1:
possible=0
if possible==0:
print(-1)
else:
sol=0
grid2=[0]*n
for i in range(n):
l=[0]*m
grid2[i]=l
for i in range(n):
for j in range(m):
if grid[i][j]==0 and grid2[i][j]==0:
sol+=1
tod=[[i,j]]
while len(tod)>0:
x=tod.pop()
i1=x[0]
j1=x[1]
if i1>=0 and i1<n and j1>=0 and j1<m:
if grid[i1][j1]==0 and grid2[i1][j1]==0:
grid2[i1][j1]=1
tod.append([i1,j1+1])
tod.append([i1,j1-1])
tod.append([i1+1,j1])
tod.append([i1-1,j1])
print(sol)
``` | instruction | 0 | 78,422 | 15 | 156,844 |
Yes | output | 1 | 78,422 | 15 | 156,845 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Submitted Solution:
```
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import *
from functools import reduce,cmp_to_key
# import io, os
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import sys
input = sys.stdin.readline
M = mod = 10**9 + 7
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)
def li():return [int(i) for i in input().rstrip('\n').split()]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def li2():return [i for i in input().rstrip('\n')]
def li3():return [int(i) for i in input().rstrip('\n')]
n,m = li()
l = []
cols = [0]*m
rows = [0]*n
dx = [1,-1,0,0]
dy = [0,0,-1,1]
visited = {}
totnorth = 0
def dfs(i,j):
global l,n,m,totnorth,rows,cols
allpoints = []
d = deque()
d.append([i,j])
leftx,rightx,upy,downy = i,i,j,j
totnorth += 1
while d:
x,y = d.popleft()
# print(x,y)
if (x,y) in visited:continue
visited[(x,y)] = 1
allpoints.append([x,y])
leftx = min(leftx,x)
rightx = max(rightx,x)
upy = max(upy,y)
downy = min(downy,y)
for i,j in zip(dx,dy):
if 0<=x+i<n and 0<=y+j<m and l[i+x][y+j] == '#' and (x+i,y+j) not in visited:
d.append([i+x,y+j])
# print(allpoints)
for x,y in allpoints:
rows[x] += 1
cols[y] += 1
has = 0
for i in range(n):
l.append(st())
# print(l)
for i in range(n):
for j in range(m):
if l[i][j] == '#':
has += 1
break
if not has:
print(0)
exit()
# print(l)
rowempty = [0]*n
colempty = [0]*m
for i in range(n):
curr1 = []
for j in range(m):
if l[i][j] == '#':
if curr1 and j - curr1[-1] > 1:
# print('ROW : ',i,j,curr1)
print(-1)
exit()
curr1.append(j)
if not len(curr1):
rowempty[i] = 1
for j in range(m):
curr1 = []
for i in range(n):
if l[i][j] == '#':
if curr1 and i - curr1[-1] > 1:
# print('COL : ',i,j,curr)
print(-1)
exit()
curr1.append(i)
if not len(curr1):
colempty[j] = 1
# print(l)
ma1 = max(rowempty)
ma2 = max(colempty)
for i in range(n):
if rowempty[i] and ma2:rows[i] += 1
for j in range(m):
if colempty[j] and ma1:cols[j] += 1
for i in range(n):
for j in range(m):
if l[i][j] == '#' and (i,j) not in visited:
# print(i,j)
dfs(i,j)
# print(cols,rows)
if min(cols) == 0 or min(rows) == 0:
print(-1)
exit()
print(totnorth)
``` | instruction | 0 | 78,423 | 15 | 156,846 |
Yes | output | 1 | 78,423 | 15 | 156,847 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Submitted Solution:
```
n, m = list(map(int, input().split()))
grid = []
for _ in range(n):
grid.append(input())
ns = 0
column_state = [0]*m
row_state = [0]*n
impossible = 0
for i in range(n):
black_in_next_row = 0
for j in range(m):
if grid[i][j] == '#':
if not black_in_next_row:
if i < n-1 and grid[i+1][j] == '#':
black_in_next_row = 1
elif j == m - 1 or (j < m-1 and grid[i][j + 1] != '#'):
ns += 1
if row_state[i] == 0:
row_state[i] = 1
if row_state[i] == 2:
impossible = 1
break
if column_state[j] == 0:
column_state[j] = 1
if column_state[j] == 2:
impossible = 1
break
else:
if row_state[i] == 1:
row_state[i] = 2
if column_state[j] == 1:
column_state[j] = 2
if impossible == 1:
break
if impossible == 1:
print(-1)
else:
col= 0
row= 0
for c in column_state:
if c == 0:
col = 1
for r in row_state:
if r == 0:
row = 1
if (col == 1 and row != 1) or (row == 1 and col != 1):
print(-1)
else:
print(ns)
``` | instruction | 0 | 78,424 | 15 | 156,848 |
Yes | output | 1 | 78,424 | 15 | 156,849 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Submitted Solution:
```
from bisect import *
from collections import *
from math import gcd,ceil,sqrt,floor,inf
from heapq import *
from itertools import *
#from operator import add,mul,sub,xor,truediv,floordiv
from functools import *
#------------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#------------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
#------------------------------------------------------------------------
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
farr=[1]
ifa=[]
def fact(x,mod=0):
if mod:
while x>=len(farr):
farr.append(farr[-1]*len(farr)%mod)
else:
while x>=len(farr):
farr.append(farr[-1]*len(farr))
return farr[x]
def ifact(x,mod):
global ifa
fact(x,mod)
ifa.append(pow(farr[-1],mod-2,mod))
for i in range(x,0,-1):
ifa.append(ifa[-1]*i%mod)
ifa.reverse()
def per(i,j,mod=0):
if i<j: return 0
if not mod:
return fact(i)//fact(i-j)
return farr[i]*ifa[i-j]%mod
def com(i,j,mod=0):
if i<j: return 0
if not mod:
return per(i,j)//fact(j)
return per(i,j,mod)*ifa[j]%mod
def catalan(n):
return com(2*n,n)//(n+1)
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def lowbit(n):
return n&-n
def inverse(a,m):
a%=m
if a<=1: return a
return ((1-inverse(m,a)*m)//a)%m
class BIT:
def __init__(self,arr):
self.arr=arr
self.n=len(arr)-1
def update(self,x,v):
while x<=self.n:
self.arr[x]+=v
x+=x&-x
def query(self,x):
ans=0
while x:
ans+=self.arr[x]
x&=x-1
return ans
'''
class SMT:
def __init__(self,arr):
self.n=len(arr)-1
self.arr=[0]*(self.n<<2)
self.lazy=[0]*(self.n<<2)
def Build(l,r,rt):
if l==r:
self.arr[rt]=arr[l]
return
m=(l+r)>>1
Build(l,m,rt<<1)
Build(m+1,r,rt<<1|1)
self.pushup(rt)
Build(1,self.n,1)
def pushup(self,rt):
self.arr[rt]=self.arr[rt<<1]+self.arr[rt<<1|1]
def pushdown(self,rt,ln,rn):#lr,rn表区间数字数
if self.lazy[rt]:
self.lazy[rt<<1]+=self.lazy[rt]
self.lazy[rt<<1|1]+=self.lazy[rt]
self.arr[rt<<1]+=self.lazy[rt]*ln
self.arr[rt<<1|1]+=self.lazy[rt]*rn
self.lazy[rt]=0
def update(self,L,R,c,l=1,r=None,rt=1):#L,R表示操作区间
if r==None: r=self.n
if L<=l and r<=R:
self.arr[rt]+=c*(r-l+1)
self.lazy[rt]+=c
return
m=(l+r)>>1
self.pushdown(rt,m-l+1,r-m)
if L<=m: self.update(L,R,c,l,m,rt<<1)
if R>m: self.update(L,R,c,m+1,r,rt<<1|1)
self.pushup(rt)
def query(self,L,R,l=1,r=None,rt=1):
if r==None: r=self.n
#print(L,R,l,r,rt)
if L<=l and R>=r:
return self.arr[rt]
m=(l+r)>>1
self.pushdown(rt,m-l+1,r-m)
ans=0
if L<=m: ans+=self.query(L,R,l,m,rt<<1)
if R>m: ans+=self.query(L,R,m+1,r,rt<<1|1)
return ans
'''
class DSU:#容量+路径压缩
def __init__(self,n):
self.c=[-1]*n
def same(self,x,y):
return self.find(x)==self.find(y)
def find(self,x):
if self.c[x]<0:
return x
self.c[x]=self.find(self.c[x])
return self.c[x]
def union(self,u,v):
u,v=self.find(u),self.find(v)
if u==v:
return False
if self.c[u]>self.c[v]:
u,v=v,u
self.c[u]+=self.c[v]
self.c[v]=u
return True
def size(self,x): return -self.c[self.find(x)]
class UFS:#秩+路径
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
def find(self,x):
if x!=self.parent[x]:
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
pu,pv=self.find(u),self.find(v)
if pu==pv:
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
def Prime(n):
c=0
prime=[]
flag=[0]*(n+1)
for i in range(2,n+1):
if not flag[i]:
prime.append(i)
c+=1
for j in range(c):
if i*prime[j]>n: break
flag[i*prime[j]]=prime[j]
if i%prime[j]==0: break
return prime
def dij(s,graph):
d={}
d[s]=0
heap=[(0,s)]
seen=set()
while heap:
dis,u=heappop(heap)
if u in seen:
continue
seen.add(u)
for v,w in graph[u]:
if v not in d or d[v]>d[u]+w:
d[v]=d[u]+w
heappush(heap,(d[v],v))
return d
def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)]
class DLN:
def __init__(self,val):
self.val=val
self.pre=None
self.next=None
def nb(i,j):
for ni,nj in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]:
if 0<=ni<n and 0<=nj<m:
yield ni,nj
@bootstrap
def gdfs(r,p):
if len(g[r])==1 and p!=-1:
yield None
for ch in g[r]:
if ch!=p:
yield gdfs(ch,r)
yield None
def lcm(a,b):
return a*b//gcd(a,b)
t=1
for i in range(t):
n,m=RL()
a=[]
for i in range(n):
a.append(input())
row=[0]*n
col=[0]*m
for i in range(n):
for j in range(m):
if a[i][j]=='#':
if j and a[i][j-1]=='.' or j==0:
row[i]+=1
if i and a[i-1][j]=='.' or i==0:
col[j]+=1
for i in range(n):
for j in range(m):
if a[i][j]=='.':
if row[i]<=0 and col[j]<=0:
row[i]=-1
col[j]=-1
if any(abs(x)!=1 for x in row) or any(abs(x)!=1 for x in col):
print(-1)
exit()
uf=UFS(n*m)
for i in range(n):
for j in range(m):
if a[i][j]=='#':
for ni,nj in [[i-1,j],[i,j-1]]:
if 0<=ni<n and 0<=nj<m and a[ni][nj]=='#':
uf.union(i*m+j,ni*m+nj)
s=set()
for i in range(n):
for j in range(m):
if a[i][j]=='#':
s.add(uf.find(i*m+j))
print(len(s))
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thread(target=main)
t.start()
t.join()
'''
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thread(target=main)
t.start()
t.join()
'''
``` | instruction | 0 | 78,425 | 15 | 156,850 |
Yes | output | 1 | 78,425 | 15 | 156,851 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Submitted Solution:
```
n, m = map(int, input().split())
array = []
for i in range(n):
array.append(input())
stable = True
for i in range(n):
found = False
for j in range(m):
if array[i][j] == '#':
if found:
stable = False
if j < m - 1 and array[i][j + 1] == '.':
found = True
for j in range(m):
found = False
for i in range(n):
if array[i][j] == '#':
if found:
stable = False
if i < n - 1 and array[i + 1][j] == '.':
found = True
if not stable:
print(-1)
else:
visited = [[False] * m for _ in range(n)]
def dfs(x, y):
if x <= -1 or x >= n or y <= -1 or y >= m:
return 0
if array[x][y] == '#' and not visited[x][y]:
visited[x][y] = True
dfs(x - 1, y)
dfs(x, y - 1)
dfs(x + 1, y)
dfs(x, y + 1)
return 1
return 0
result = 0
for i in range(n):
for j in range(m):
if dfs(i, j) == 1:
result += 1
print(result)
``` | instruction | 0 | 78,426 | 15 | 156,852 |
No | output | 1 | 78,426 | 15 | 156,853 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Submitted Solution:
```
class UnionFind:
def __init__(self, N):
self.parent = [i for i in range(N)]
self.size = [1 for _ in range(N)]
def find(self, x):
if self.parent[x] == x:
return x
else:
return self.find(self.parent[x])
def union(self, x, y):
px = self.find(x)
py = self.find(y)
if px == py:
return
if self.size[px] < self.size[py]:
self.parent[px] = py
self.size[py] += self.size[px]
else:
self.parent[py] = px
self.size[px] += self.size[py]
def same(self, x, y):
return self.find(x) == self.find(y)
N,M = map(int,input().split())
grid=[[v for v in input()] for _ in range(N)]
all_white_row=0
all_white_col=0
for n in range(N):
r=any(v=="#" for v in grid[n])
all_white_row+= 0 if r else 1
for m in range(M):
r= any(grid[i][m]=="#" for i in range(N))
all_white_col+= 0 if r else 1
seq_in_each_row=1
seq_in_each_col=1
for n in range(N):
r= len([v for v in "".join(grid[n]).split(".") if len(v)!=0])
if r==0:
continue
seq_in_each_row*=(r==1)
for m in range(M):
r= len([v for v in "".join([grid[i][m] for i in range(N)]).split(".") if len(v)!=0])
if r==0:
continue
seq_in_each_col*=(r==1)
if seq_in_each_col*seq_in_each_row==0:
print(-1)
exit()
if not((all_white_col==0 and all_white_row==0) or (all_white_row>=1 and all_white_col>=1)):
print(-1)
exit()
UN=UnionFind(N*M)
DX=[0,1]
DY=[1,0]
def isIn(n,m):
return 0<=n<N and 0<=m<M
for n in range(N):
for m in range(M):
if grid[n][m]==".":
continue
for dx,dy in zip(DX,DY):
nn=n+dx
mm=m+dy
if isIn(nn,mm) and grid[nn][mm]=="#":
UN.union(n*M+m,nn*M+mm)
parent=set()
for n in range(N):
for m in range(M):
if grid[n][m]=="#":
parent.add(UN.parent[n*M+m])
print(len(parent))
``` | instruction | 0 | 78,427 | 15 | 156,854 |
No | output | 1 | 78,427 | 15 | 156,855 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Submitted Solution:
```
import sys
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input().strip()
return(list(s[:len(s)]))
def invr():
return(map(int,input().split()))
def from_file(f):
return f.readline
def intersect(a, b, c, d):
return c <= a <= d or a <= c <= b
def solve(n, m, mat):
count = 0
FREE = 0
BLACK = 1
TAKEN = 2
status = [FREE] * m
prev_l = m
prev_r = -1
has_empty_line = False
for row in mat:
l = m
r = -1
has_black = False
for ic, c in enumerate(row):
if c == '#':
has_black = True
if status[ic] == TAKEN:
return -1
l = min(l, ic)
r = max(r, ic)
if c == '.':
if status[ic] == BLACK:
status[ic] = TAKEN
elif c == '#':
status[ic] = BLACK
if has_black:
if prev_l == m or not intersect(prev_l, prev_r, l, r):
count += 1
if l == m:
has_empty_line = True
prev_l = l
prev_r = r
has_empty_col = FREE in status
if has_empty_line ^ has_empty_col:
return -1
return count
# with open('4.txt') as f:
# input = from_file(f)
n, m = invr()
mat = []
for _ in range(n):
mat.append(insr())
print(solve(n, m, mat))
``` | instruction | 0 | 78,428 | 15 | 156,856 |
No | output | 1 | 78,428 | 15 | 156,857 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Submitted Solution:
```
def bfs(i,j):
q=[]
q.append([i,j])
v[i][j]=1
while q:
s=q.pop(0)
a,b=s[0],s[1]
if a-1>=0 and l[a-1][b]=='#' and v[a-1][b]==0:
q.append([a-1,b])
v[a-1][b]=1
if a+1<n and l[a+1][b]=='#' and v[a+1][b]==0:
q.append([a+1,b])
v[a+1][b]=1
if b-1>=0 and l[a][b-1]=='#' and v[a][b-1]==0:
q.append([a,b-1])
v[a][b-1]=1
if b+1<m and l[a][b+1]=='#' and v[a][b+1]==0:
q.append([a,b+1])
v[a][b+1]=1
for _ in range(1):
n,m=map(int,input().split())
l=[]
for i in range(n):
l.append(input())
f1,f2=0,0
fr=0
for i in range(n):
f,z=-1,0
for j in range(m):
if l[i][j]=='#':
if f==-1:
f=j
else:
if j-f>1:
print(-1)
z+=1
fr+=1
break
f=j
if z>0:
break
if f==-1:
f1=1
for j in range(m):
f,z=-1,0
for i in range(n):
if l[i][j]=='#':
if f==-1:
f=i
else:
if i-f>1:
print(-1)
z+=1
fr+=1
break
f=i
if z>0:
break
if f==-1:
f2=1
#print(f1,f2)
if (f1==1 and f2!=1) or (f2==1 and f1!=1):
#print('a')
print(-1)
fr+=1
if fr==0:
#print('a')
cnt=0
v=[]
for i in range(n):
v1=[]
for j in range(m):
v1.append(0)
v.append(v1)
for i in range(n):
for j in range(m):
if l[i][j]=='#' and v[i][j]==0:
cnt+=1
bfs(i,j)
print(cnt)
``` | instruction | 0 | 78,429 | 15 | 156,858 |
No | output | 1 | 78,429 | 15 | 156,859 |
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monopole magnet is a magnet that only has one pole, either north or south. They don't actually exist since real magnets have two poles, but this is a programming contest problem, so we don't care.
There is an n× m grid. Initially, you may place some north magnets and some south magnets into the cells. You are allowed to place as many magnets as you like, even multiple in the same cell.
An operation is performed as follows. Choose a north magnet and a south magnet to activate. If they are in the same row or the same column and they occupy different cells, then the north magnet moves one unit closer to the south magnet. Otherwise, if they occupy the same cell or do not share a row or column, then nothing changes. Note that the south magnets are immovable.
Each cell of the grid is colored black or white. Let's consider ways to place magnets in the cells so that the following conditions are met.
1. There is at least one south magnet in every row and every column.
2. If a cell is colored black, then it is possible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
3. If a cell is colored white, then it is impossible for a north magnet to occupy this cell after some sequence of operations from the initial placement.
Determine if it is possible to place magnets such that these conditions are met. If it is possible, find the minimum number of north magnets required (there are no requirements on the number of south magnets).
Input
The first line contains two integers n and m (1≤ n,m≤ 1000) — the number of rows and the number of columns, respectively.
The next n lines describe the coloring. The i-th of these lines contains a string of length m, where the j-th character denotes the color of the cell in row i and column j. The characters "#" and "." represent black and white, respectively. It is guaranteed, that the string will not contain any other characters.
Output
Output a single integer, the minimum possible number of north magnets required.
If there is no placement of magnets that satisfies all conditions, print a single integer -1.
Examples
Input
3 3
.#.
###
##.
Output
1
Input
4 2
##
.#
.#
##
Output
-1
Input
4 5
....#
####.
.###.
.#...
Output
2
Input
2 1
.
#
Output
-1
Input
3 5
.....
.....
.....
Output
0
Note
In the first test, here is an example placement of magnets:
<image>
In the second test, we can show that no required placement of magnets exists. Here are three example placements that fail to meet the requirements. The first example violates rule 3 since we can move the north magnet down onto a white square. The second example violates rule 2 since we cannot move the north magnet to the bottom-left black square by any sequence of operations. The third example violates rule 1 since there is no south magnet in the first column.
<image>
In the third test, here is an example placement of magnets. We can show that there is no required placement of magnets with fewer north magnets.
<image>
In the fourth test, we can show that no required placement of magnets exists. Here are two example placements that fail to meet the requirements. The first example violates rule 1 since there is no south magnet in the first row. The second example violates rules 1 and 3 since there is no south magnet in the second row and we can move the north magnet up one unit onto a white square.
<image>
In the fifth test, we can put the south magnet in each cell and no north magnets. Because there are no black cells, it will be a correct placement.
Submitted Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
def fun(x):
return 1*(x=='#')
def in_num():
return int(raw_input())
def in_arr():
return map(fun,raw_input().strip())
def pr_num(n):
stdout.write(str(n)+'\n')
def pr_arr(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
n,m=map(int,raw_input().split())
l=[]
sm=0
for i in range(n):
l.append(in_arr())
sm+=sum(l[-1])
if sm==0:
pr_num(0)
exit()
if n==1 or m==1:
if sm!=n*m:
pr_num(-1)
else:
pr_num(1)
exit()
for i in range(n):
c=0
for j in range(m-1):
if l[i][j]:
c=1
if l[i][j]==0 and c and l[i][j+1]:
pr_num(-1)
exit()
for j in range(m):
f=0
for i in range(n-1):
if l[i][j]==1:
f=1
if l[i][j]==0 and f and l[i+1][j]==1:
pr_num(-1)
exit()
vis=[[0 for i in range(m)] for j in range(n)]
ans=0
move=[(1,0),(-1,0),(0,1),(0,-1)]
f=0
for i in range(n):
for j in range(m):
if l[i][j] and not vis[i][j]:
#print 'x',i,j
vis[i][j]=1
q=[(i,j)]
ans+=1
while q:
x,y=q.pop()
#print x,y
for x1,y1 in move:
x2=x1+x
y2=y1+y
if x2>=0 and x2<n and y2>=0 and y2<m:
if l[x2][y2] and not vis[x2][y2]:
vis[x2][y2]=1
q.append((x2,y2))
pr_num(ans)
``` | instruction | 0 | 78,430 | 15 | 156,860 |
No | output | 1 | 78,430 | 15 | 156,861 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Having learned (not without some help from the Codeforces participants) to play the card game from the previous round optimally, Shrek and Donkey (as you may remember, they too live now in the Kingdom of Far Far Away) have decided to quit the boring card games and play with toy soldiers.
The rules of the game are as follows: there is a battlefield, its size equals n × m squares, some squares contain the toy soldiers (the green ones belong to Shrek and the red ones belong to Donkey). Besides, each of the n lines of the area contains not more than two soldiers. During a move a players should select not less than 1 and not more than k soldiers belonging to him and make them either attack or retreat.
An attack is moving all of the selected soldiers along the lines on which they stand in the direction of an enemy soldier, if he is in this line. If this line doesn't have an enemy soldier, then the selected soldier on this line can move in any direction during the player's move. Each selected soldier has to move at least by one cell. Different soldiers can move by a different number of cells. During the attack the soldiers are not allowed to cross the cells where other soldiers stand (or stood immediately before the attack). It is also not allowed to go beyond the battlefield or finish the attack in the cells, where other soldiers stand (or stood immediately before attack).
A retreat is moving all of the selected soldiers along the lines on which they stand in the direction from an enemy soldier, if he is in this line. The other rules repeat the rules of the attack.
For example, let's suppose that the original battlefield had the form (here symbols "G" mark Shrek's green soldiers and symbols "R" mark Donkey's red ones):
-G-R-
-R-G-
Let's suppose that k = 2 and Shrek moves first. If he decides to attack, then after his move the battlefield can look like that:
--GR- --GR- -G-R-
-RG-- -R-G- -RG--
If in the previous example Shrek decides to retreat, then after his move the battlefield can look like that:
G--R- G--R- -G-R-
-R--G -R-G- -R--G
On the other hand, the followings fields cannot result from Shrek's correct move:
G--R- ---RG --GR-
-RG-- -R-G- GR---
Shrek starts the game. To make a move means to attack or to retreat by the rules. A player who cannot make a move loses and his opponent is the winner. Determine the winner of the given toy soldier game if Shrek and Donkey continue to be under the yellow pills from the last rounds' problem. Thus, they always play optimally (that is, they try to win if it is possible, or finish the game in a draw, by ensuring that it lasts forever, if they cannot win).
Input
The first line contains space-separated integers n, m and k (1 ≤ n, m, k ≤ 100). Then n lines contain m characters each. These characters belong to the set {"-", "G", "R"}, denoting, respectively, a battlefield's free cell, a cell occupied by Shrek's soldiers and a cell occupied by Donkey's soldiers.
It is guaranteed that each line contains no more than two soldiers.
Output
Print "First" (without the quotes) if Shrek wins in the given Toy Soldier game. If Donkey wins, print "Second" (without the quotes). If the game continues forever, print "Draw" (also without the quotes).
Examples
Input
2 3 1
R-G
RG-
Output
First
Input
3 3 2
G-R
R-G
G-R
Output
Second
Input
2 3 1
-R-
-G-
Output
Draw
Input
2 5 2
-G-R-
-R-G-
Output
First | instruction | 0 | 78,480 | 15 | 156,960 |
Tags: games
Correct Solution:
```
def get(a):
global m
R = -1
G = -1
mi = -1
for i in range(m):
if a[i] == '-':
mi = i
elif a[i] == "R":
R = i
else:
G = i
return G, R, mi
n, m, k = map(int, input().split())
draw = [0, 0]
t = []
for i in range(n):
G, R, mi = get(input())
if G == -1:
if R != -1 and mi != -1:
draw[1] = 1
elif R == -1:
if mi != -1:
draw[0] = 1
else:
t.append(abs(G - R) - 1)
if not t:
if not draw[0]:
print("Second")
elif not draw[1]:
print("First")
else:
print("Draw")
exit()
winner = 1
for bit in range(7):
tmp = 0
for i in range(len(t)):
tmp += t[i] & 1
t[i] >>= 1
if tmp % (k + 1) != 0:
winner = 0
break
draw[winner] = 0
if draw[1 - winner]:
print("Draw")
else:
print("First" if winner == 0 else "Second")
``` | output | 1 | 78,480 | 15 | 156,961 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Inna loves sweets very much. That's why she decided to play a game called "Sweet Matrix".
Inna sees an n × m matrix and k candies. We'll index the matrix rows from 1 to n and the matrix columns from 1 to m. We'll represent the cell in the i-th row and j-th column as (i, j). Two cells (i, j) and (p, q) of the matrix are adjacent if |i - p| + |j - q| = 1. A path is a sequence of the matrix cells where each pair of neighbouring cells in the sequence is adjacent. We'll call the number of cells in the sequence the path's length.
Each cell of the matrix can have at most one candy. Initiallly, all the cells are empty. Inna is trying to place each of the k candies in the matrix one by one. For each candy Inna chooses cell (i, j) that will contains the candy, and also chooses the path that starts in cell (1, 1) and ends in cell (i, j) and doesn't contain any candies. After that Inna moves the candy along the path from cell (1, 1) to cell (i, j), where the candy stays forever. If at some moment Inna can't choose a path for the candy, she loses. If Inna can place all the candies in the matrix in the described manner, then her penalty equals the sum of lengths of all the paths she has used.
Help Inna to minimize the penalty in the game.
Input
The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 50, 1 ≤ k ≤ n·m).
Output
In the first line print an integer — Inna's minimum penalty in the game.
In the next k lines print the description of the path for each candy. The description of the path of the candy that is placed i-th should follow on the i-th line. The description of a path is a sequence of cells. Each cell must be written in the format (i, j), where i is the number of the row and j is the number of the column. You are allowed to print extra whitespaces in the line. If there are multiple optimal solutions, print any of them.
Please follow the output format strictly! If your program passes the first pretest, then the output format is correct.
Examples
Input
4 4 4
Output
8
(1,1) (2,1) (2,2)
(1,1) (1,2)
(1,1) (2,1)
(1,1)
Note
Note to the sample. Initially the matrix is empty. Then Inna follows her first path, the path penalty equals the number of cells in it — 3. Note that now no path can go through cell (2, 2), as it now contains a candy. The next two candies go to cells (1, 2) and (2, 1). Inna simply leaves the last candy at cell (1, 1), the path contains only this cell. The total penalty is: 3 + 2 + 2 + 1 = 8.
Note that Inna couldn't use cell (1, 1) to place, for instance, the third candy as in this case she couldn't have made the path for the fourth candy. | instruction | 0 | 78,614 | 15 | 157,228 |
Tags: constructive algorithms
Correct Solution:
```
def getCells(n, m, k):
penalty = 0
cells = []
for l in range(2,n+m+1):
iLeft = 1 if l-1 <= m else l-m
iRight = n if l-n > 0 else l-1
for i in range(iLeft, iRight+1):
j = l-i
penalty += l-1
cells.append((i,j))
k -= 1
if k == 0:
return penalty, cells
def getPath(i, j):
path = []
p,q = 1,1
while p < i:
path.append((p,q))
p += 1
while q < j:
path.append((p,q))
q += 1
path.append((i,j))
return path
n, m, k = map(int, input().split())
penalty, cells = getCells(n, m, k)
print(penalty)
for cell in reversed(cells):
print(*getPath(*cell))
``` | output | 1 | 78,614 | 15 | 157,229 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Inna loves sweets very much. That's why she decided to play a game called "Sweet Matrix".
Inna sees an n × m matrix and k candies. We'll index the matrix rows from 1 to n and the matrix columns from 1 to m. We'll represent the cell in the i-th row and j-th column as (i, j). Two cells (i, j) and (p, q) of the matrix are adjacent if |i - p| + |j - q| = 1. A path is a sequence of the matrix cells where each pair of neighbouring cells in the sequence is adjacent. We'll call the number of cells in the sequence the path's length.
Each cell of the matrix can have at most one candy. Initiallly, all the cells are empty. Inna is trying to place each of the k candies in the matrix one by one. For each candy Inna chooses cell (i, j) that will contains the candy, and also chooses the path that starts in cell (1, 1) and ends in cell (i, j) and doesn't contain any candies. After that Inna moves the candy along the path from cell (1, 1) to cell (i, j), where the candy stays forever. If at some moment Inna can't choose a path for the candy, she loses. If Inna can place all the candies in the matrix in the described manner, then her penalty equals the sum of lengths of all the paths she has used.
Help Inna to minimize the penalty in the game.
Input
The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 50, 1 ≤ k ≤ n·m).
Output
In the first line print an integer — Inna's minimum penalty in the game.
In the next k lines print the description of the path for each candy. The description of the path of the candy that is placed i-th should follow on the i-th line. The description of a path is a sequence of cells. Each cell must be written in the format (i, j), where i is the number of the row and j is the number of the column. You are allowed to print extra whitespaces in the line. If there are multiple optimal solutions, print any of them.
Please follow the output format strictly! If your program passes the first pretest, then the output format is correct.
Examples
Input
4 4 4
Output
8
(1,1) (2,1) (2,2)
(1,1) (1,2)
(1,1) (2,1)
(1,1)
Note
Note to the sample. Initially the matrix is empty. Then Inna follows her first path, the path penalty equals the number of cells in it — 3. Note that now no path can go through cell (2, 2), as it now contains a candy. The next two candies go to cells (1, 2) and (2, 1). Inna simply leaves the last candy at cell (1, 1), the path contains only this cell. The total penalty is: 3 + 2 + 2 + 1 = 8.
Note that Inna couldn't use cell (1, 1) to place, for instance, the third candy as in this case she couldn't have made the path for the fourth candy. | instruction | 0 | 78,615 | 15 | 157,230 |
Tags: constructive algorithms
Correct Solution:
```
string = input()
l = string.split(" ")
n, m, k = int(l[0]),int(l[1]),int(l[2])
l = [{(1,1),}]
count = 1
In = 0
while count < k:
s = set()
for i in l[In]:
x = i[0]+1
y = i[1]
if x<=n and y<=m:
t = [0,0]
t[0],t[1] = x, y
s.add(tuple(t))
x = i[0]
y = i[1]+1
if x<=n and y<=m:
t = [0,0]
t[0],t[1] = x, y
s.add(tuple(t))
l.append(s)
In+=1
count+=len(l[In])
l2 = []
Count = 0
flag = 0
for i in l:
for h in i:
if Count==k:
flag = 1
break
l3 = [h]
x,y = h[0],h[1]
while x!=1 or y!=1:
if x>y:
x-=1
l3.append((x,y))
else:
y-=1
l3.append((x,y))
l2.append(l3)
Count+=1
if flag==1:
break
cost = 0
string = ""
for i in range(k):
length = len(l2[k-i-1])
cost+=length
for j in range(length):
t = l2[k-i-1][length - j - 1]
x,y = t[0],t[1]
string += "("+str(x)+","+str(y)+") "
string += "\n"
print(cost)
print(string)
``` | output | 1 | 78,615 | 15 | 157,231 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Inna loves sweets very much. That's why she decided to play a game called "Sweet Matrix".
Inna sees an n × m matrix and k candies. We'll index the matrix rows from 1 to n and the matrix columns from 1 to m. We'll represent the cell in the i-th row and j-th column as (i, j). Two cells (i, j) and (p, q) of the matrix are adjacent if |i - p| + |j - q| = 1. A path is a sequence of the matrix cells where each pair of neighbouring cells in the sequence is adjacent. We'll call the number of cells in the sequence the path's length.
Each cell of the matrix can have at most one candy. Initiallly, all the cells are empty. Inna is trying to place each of the k candies in the matrix one by one. For each candy Inna chooses cell (i, j) that will contains the candy, and also chooses the path that starts in cell (1, 1) and ends in cell (i, j) and doesn't contain any candies. After that Inna moves the candy along the path from cell (1, 1) to cell (i, j), where the candy stays forever. If at some moment Inna can't choose a path for the candy, she loses. If Inna can place all the candies in the matrix in the described manner, then her penalty equals the sum of lengths of all the paths she has used.
Help Inna to minimize the penalty in the game.
Input
The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 50, 1 ≤ k ≤ n·m).
Output
In the first line print an integer — Inna's minimum penalty in the game.
In the next k lines print the description of the path for each candy. The description of the path of the candy that is placed i-th should follow on the i-th line. The description of a path is a sequence of cells. Each cell must be written in the format (i, j), where i is the number of the row and j is the number of the column. You are allowed to print extra whitespaces in the line. If there are multiple optimal solutions, print any of them.
Please follow the output format strictly! If your program passes the first pretest, then the output format is correct.
Examples
Input
4 4 4
Output
8
(1,1) (2,1) (2,2)
(1,1) (1,2)
(1,1) (2,1)
(1,1)
Note
Note to the sample. Initially the matrix is empty. Then Inna follows her first path, the path penalty equals the number of cells in it — 3. Note that now no path can go through cell (2, 2), as it now contains a candy. The next two candies go to cells (1, 2) and (2, 1). Inna simply leaves the last candy at cell (1, 1), the path contains only this cell. The total penalty is: 3 + 2 + 2 + 1 = 8.
Note that Inna couldn't use cell (1, 1) to place, for instance, the third candy as in this case she couldn't have made the path for the fourth candy.
Submitted Solution:
```
string = input()
l = string.split(" ")
n, m, k = int(l[0]),int(l[1]),int(l[2])
l = [{(1,1),}]
count = 1
In = 0
while count < k:
s = set()
for i in l[In]:
x = i[0]+1
y = i[1]
if x<=n and y<=m:
t = [0,0]
t[0],t[1] = x, y
s.add(tuple(t))
x = i[0]
y = i[1]+1
if x<=n and y<=m:
t = [0,0]
t[0],t[1] = x, y
s.add(tuple(t))
l.append(s)
In+=1
count+=len(l[In])
l2 = []
Count = 0
flag = 0
for i in l:
for h in i:
if Count==k:
flag = 1
break
l3 = [h]
x,y = h[0],h[1]
while x!=1 or y!=1:
if x>y:
x-=1
l3.append((x,y))
else:
y-=1
l3.append((x,y))
l2.append(l3)
Count+=1
if flag==1:
break
for i in range(k):
length = len(l2[k-i-1])
string = ""
for j in range(length):
t = l2[k-i-1][length - j - 1]
x,y = t[0],t[1]
string += "("+str(x)+","+str(y)+") "
print(string)
``` | instruction | 0 | 78,616 | 15 | 157,232 |
No | output | 1 | 78,616 | 15 | 157,233 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp and Vasiliy love simple logical games. Today they play a game with infinite chessboard and one pawn for each player. Polycarp and Vasiliy move in turns, Polycarp starts. In each turn Polycarp can move his pawn from cell (x, y) to (x - 1, y) or (x, y - 1). Vasiliy can move his pawn from (x, y) to one of cells: (x - 1, y), (x - 1, y - 1) and (x, y - 1). Both players are also allowed to skip move.
There are some additional restrictions — a player is forbidden to move his pawn to a cell with negative x-coordinate or y-coordinate or to the cell containing opponent's pawn The winner is the first person to reach cell (0, 0).
You are given the starting coordinates of both pawns. Determine who will win if both of them play optimally well.
Input
The first line contains four integers: xp, yp, xv, yv (0 ≤ xp, yp, xv, yv ≤ 105) — Polycarp's and Vasiliy's starting coordinates.
It is guaranteed that in the beginning the pawns are in different cells and none of them is in the cell (0, 0).
Output
Output the name of the winner: "Polycarp" or "Vasiliy".
Examples
Input
2 1 2 2
Output
Polycarp
Input
4 7 7 4
Output
Vasiliy
Note
In the first sample test Polycarp starts in (2, 1) and will move to (1, 1) in the first turn. No matter what his opponent is doing, in the second turn Polycarp can move to (1, 0) and finally to (0, 0) in the third turn. | instruction | 0 | 78,686 | 15 | 157,372 |
Tags: games, greedy, implementation, math
Correct Solution:
```
x1, y1, x2, y2 = map(int, input().split())
if (x1 > x2 or y1 > y2) and x1 + y1 > max(x2, y2):
print("Vasiliy")
else:
print("Polycarp")
``` | output | 1 | 78,686 | 15 | 157,373 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp and Vasiliy love simple logical games. Today they play a game with infinite chessboard and one pawn for each player. Polycarp and Vasiliy move in turns, Polycarp starts. In each turn Polycarp can move his pawn from cell (x, y) to (x - 1, y) or (x, y - 1). Vasiliy can move his pawn from (x, y) to one of cells: (x - 1, y), (x - 1, y - 1) and (x, y - 1). Both players are also allowed to skip move.
There are some additional restrictions — a player is forbidden to move his pawn to a cell with negative x-coordinate or y-coordinate or to the cell containing opponent's pawn The winner is the first person to reach cell (0, 0).
You are given the starting coordinates of both pawns. Determine who will win if both of them play optimally well.
Input
The first line contains four integers: xp, yp, xv, yv (0 ≤ xp, yp, xv, yv ≤ 105) — Polycarp's and Vasiliy's starting coordinates.
It is guaranteed that in the beginning the pawns are in different cells and none of them is in the cell (0, 0).
Output
Output the name of the winner: "Polycarp" or "Vasiliy".
Examples
Input
2 1 2 2
Output
Polycarp
Input
4 7 7 4
Output
Vasiliy
Note
In the first sample test Polycarp starts in (2, 1) and will move to (1, 1) in the first turn. No matter what his opponent is doing, in the second turn Polycarp can move to (1, 0) and finally to (0, 0) in the third turn. | instruction | 0 | 78,687 | 15 | 157,374 |
Tags: games, greedy, implementation, math
Correct Solution:
```
x1, y1, x2, y2 = map(int, input().split())
print("Polycarp" if ((x2 >= x1 and y2 >= y1) or (max(x2, y2) >= x1 + y1)) else "Vasiliy")
``` | output | 1 | 78,687 | 15 | 157,375 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp and Vasiliy love simple logical games. Today they play a game with infinite chessboard and one pawn for each player. Polycarp and Vasiliy move in turns, Polycarp starts. In each turn Polycarp can move his pawn from cell (x, y) to (x - 1, y) or (x, y - 1). Vasiliy can move his pawn from (x, y) to one of cells: (x - 1, y), (x - 1, y - 1) and (x, y - 1). Both players are also allowed to skip move.
There are some additional restrictions — a player is forbidden to move his pawn to a cell with negative x-coordinate or y-coordinate or to the cell containing opponent's pawn The winner is the first person to reach cell (0, 0).
You are given the starting coordinates of both pawns. Determine who will win if both of them play optimally well.
Input
The first line contains four integers: xp, yp, xv, yv (0 ≤ xp, yp, xv, yv ≤ 105) — Polycarp's and Vasiliy's starting coordinates.
It is guaranteed that in the beginning the pawns are in different cells and none of them is in the cell (0, 0).
Output
Output the name of the winner: "Polycarp" or "Vasiliy".
Examples
Input
2 1 2 2
Output
Polycarp
Input
4 7 7 4
Output
Vasiliy
Note
In the first sample test Polycarp starts in (2, 1) and will move to (1, 1) in the first turn. No matter what his opponent is doing, in the second turn Polycarp can move to (1, 0) and finally to (0, 0) in the third turn. | instruction | 0 | 78,688 | 15 | 157,376 |
Tags: games, greedy, implementation, math
Correct Solution:
```
px, py, vx, vy = map(int, input().split())
if (px <= vx and py <= vy) or px+py <= max(vx, vy):
print("Polycarp")
else:
print("Vasiliy")
``` | output | 1 | 78,688 | 15 | 157,377 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp and Vasiliy love simple logical games. Today they play a game with infinite chessboard and one pawn for each player. Polycarp and Vasiliy move in turns, Polycarp starts. In each turn Polycarp can move his pawn from cell (x, y) to (x - 1, y) or (x, y - 1). Vasiliy can move his pawn from (x, y) to one of cells: (x - 1, y), (x - 1, y - 1) and (x, y - 1). Both players are also allowed to skip move.
There are some additional restrictions — a player is forbidden to move his pawn to a cell with negative x-coordinate or y-coordinate or to the cell containing opponent's pawn The winner is the first person to reach cell (0, 0).
You are given the starting coordinates of both pawns. Determine who will win if both of them play optimally well.
Input
The first line contains four integers: xp, yp, xv, yv (0 ≤ xp, yp, xv, yv ≤ 105) — Polycarp's and Vasiliy's starting coordinates.
It is guaranteed that in the beginning the pawns are in different cells and none of them is in the cell (0, 0).
Output
Output the name of the winner: "Polycarp" or "Vasiliy".
Examples
Input
2 1 2 2
Output
Polycarp
Input
4 7 7 4
Output
Vasiliy
Note
In the first sample test Polycarp starts in (2, 1) and will move to (1, 1) in the first turn. No matter what his opponent is doing, in the second turn Polycarp can move to (1, 0) and finally to (0, 0) in the third turn. | instruction | 0 | 78,689 | 15 | 157,378 |
Tags: games, greedy, implementation, math
Correct Solution:
```
x, y, a, b = map(int, input().split())
print('Vasiliy' if a < x and b < x + y or b < y and a < x + y else 'Polycarp')
# Made By Mostafa_Khaled
``` | output | 1 | 78,689 | 15 | 157,379 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.