message stringlengths 2 45.8k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 254 108k | cluster float64 3 3 | __index_level_0__ int64 508 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.
Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other.
You are given the number n, the initial arrangement of children and the number k. You have to find a way for the children to act if they want to finish the process in exactly k seconds. More formally, for each of the k moves, you need to output the numbers of the children who turn left during this move.
For instance, for the configuration shown below and k = 2 children can do the following steps:
<image> At the beginning, two pairs make move: (1, 2) and (3, 4). After that, we receive the following configuration: <image> At the second move pair (2, 3) makes the move. The final configuration is reached. Good job. <image>
It is guaranteed that if the solution exists, it takes not more than n^2 "headturns".
Input
The first line of input contains two integers n and k (2 ≤ n ≤ 3000, 1 ≤ k ≤ 3000000) — the number of children and required number of moves.
The next line contains a string of length n and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right.
Output
If there is no solution, print a single line with number -1.
Otherwise, output k lines. Each line has to start with a number n_i (1≤ n_i ≤ n/2) — the number of pairs of children, who turn at this move. After that print n_i distinct integers — the numbers of the children who will turn left during this move.
After performing all "headturns", there can't be a pair of two neighboring children looking at each other.
If there are many solutions, print any of them.
Examples
Input
2 1
RL
Output
1 1
Input
2 1
LR
Output
-1
Input
4 2
RLRL
Output
2 1 3
1 2
Note
The first sample contains a pair of children who look at each other. After one move, they can finish the process.
In the second sample, children can't make any move. As a result, they can't end in k>0 moves.
The third configuration is described in the statement.
Submitted Solution:
```
def f():
# bubble to inc order
d = {'L': 0, 'R': 1}
n, k = [int(s) for s in input().split()]
A = [d[s] for s in input()]
best = []
notFin = 1
while notFin:
notFin = 0
sec = []
i = 1
while i < n:
if A[i - 1] > A[i]:
sec.append(i - 1)
A[i - 1], A[i] = 0, 1
notFin = 1
i += 1
i += 1
best.append(sec)
best.pop()
maxOp = 0
for p in best:
maxOp += len(p)
if k < len(best) or k > maxOp:
print(-1)
return
ans = list()
rem = k - len(best)
w, p = 0, 0
while rem > 0:
ans.append("1 " + str(best[w][p] + 1) + "\n")
rem -= 1
p += 1
if p == len(best[w]):
p = 0
w += 1
rem += 1
while w < len(best):
ans.append(str(len(best[w]) - p) + " ")
while p < len(best[w]):
ans.append(str(best[w][p] + 1) + " ")
p += 1
ans.append("\n")
w += 1
p = 0
print("".join(ans))
f()
``` | instruction | 0 | 65,730 | 3 | 131,460 |
Yes | output | 1 | 65,730 | 3 | 131,461 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.
Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other.
You are given the number n, the initial arrangement of children and the number k. You have to find a way for the children to act if they want to finish the process in exactly k seconds. More formally, for each of the k moves, you need to output the numbers of the children who turn left during this move.
For instance, for the configuration shown below and k = 2 children can do the following steps:
<image> At the beginning, two pairs make move: (1, 2) and (3, 4). After that, we receive the following configuration: <image> At the second move pair (2, 3) makes the move. The final configuration is reached. Good job. <image>
It is guaranteed that if the solution exists, it takes not more than n^2 "headturns".
Input
The first line of input contains two integers n and k (2 ≤ n ≤ 3000, 1 ≤ k ≤ 3000000) — the number of children and required number of moves.
The next line contains a string of length n and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right.
Output
If there is no solution, print a single line with number -1.
Otherwise, output k lines. Each line has to start with a number n_i (1≤ n_i ≤ n/2) — the number of pairs of children, who turn at this move. After that print n_i distinct integers — the numbers of the children who will turn left during this move.
After performing all "headturns", there can't be a pair of two neighboring children looking at each other.
If there are many solutions, print any of them.
Examples
Input
2 1
RL
Output
1 1
Input
2 1
LR
Output
-1
Input
4 2
RLRL
Output
2 1 3
1 2
Note
The first sample contains a pair of children who look at each other. After one move, they can finish the process.
In the second sample, children can't make any move. As a result, they can't end in k>0 moves.
The third configuration is described in the statement.
Submitted Solution:
```
import sys
from collections import deque
def solve(N, K, S):
levels = deque()
while True:
indices = [i for i, pair in enumerate(zip(S, S[1:])) if pair == ("R", "L")]
if not indices:
break
levels.append(indices)
S = S.replace("RL", "LR")
shortest = len(levels)
longest = sum(len(indices) for indices in levels)
if not (shortest <= K <= longest):
return -1
def formatLine(indices):
return str(len(indices)) + " " + " ".join(str(i + 1) for i in indices)
ans = []
# Move one at a time until we can move level by level
while len(ans) + len(levels) < K:
line = [levels[0].pop()]
if not levels[0]:
levels.popleft()
ans.append(formatLine(line))
for line in levels:
ans.append(formatLine(line))
return "\n".join(ans)
if __name__ == "__main__":
input = sys.stdin.readline
N, K = [int(x) for x in input().split()]
S = input().rstrip()
ans = solve(N, K, S)
print(ans)
``` | instruction | 0 | 65,731 | 3 | 131,462 |
Yes | output | 1 | 65,731 | 3 | 131,463 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.
Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other.
You are given the number n, the initial arrangement of children and the number k. You have to find a way for the children to act if they want to finish the process in exactly k seconds. More formally, for each of the k moves, you need to output the numbers of the children who turn left during this move.
For instance, for the configuration shown below and k = 2 children can do the following steps:
<image> At the beginning, two pairs make move: (1, 2) and (3, 4). After that, we receive the following configuration: <image> At the second move pair (2, 3) makes the move. The final configuration is reached. Good job. <image>
It is guaranteed that if the solution exists, it takes not more than n^2 "headturns".
Input
The first line of input contains two integers n and k (2 ≤ n ≤ 3000, 1 ≤ k ≤ 3000000) — the number of children and required number of moves.
The next line contains a string of length n and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right.
Output
If there is no solution, print a single line with number -1.
Otherwise, output k lines. Each line has to start with a number n_i (1≤ n_i ≤ n/2) — the number of pairs of children, who turn at this move. After that print n_i distinct integers — the numbers of the children who will turn left during this move.
After performing all "headturns", there can't be a pair of two neighboring children looking at each other.
If there are many solutions, print any of them.
Examples
Input
2 1
RL
Output
1 1
Input
2 1
LR
Output
-1
Input
4 2
RLRL
Output
2 1 3
1 2
Note
The first sample contains a pair of children who look at each other. After one move, they can finish the process.
In the second sample, children can't make any move. As a result, they can't end in k>0 moves.
The third configuration is described in the statement.
Submitted Solution:
```
import sys
lines = sys.stdin.readlines()
(n, k) = map(int, lines[0].strip().split(" "))
string = lines[1].strip()
a = [0 for _ in range(n)]
Ls = []
for i in range(n-1, -1, -1):
if string[i] == "R": a[i] = 1
else: Ls.append(i+1)
maxi, mini = 0, 0
cnt = 0
last = -1
for i in range(n-1, -1, -1):
if a[i] == 0: cnt += 1
else:
if cnt == 0: continue
maxi += cnt
mini = max(cnt, last +1)
last = mini
end = 1
if k < mini or k > maxi: print(-1)
else:
while maxi > k:
c = 0
cache = []
for i in range(len(Ls)-1):
if Ls[i+1] != Ls[i] - 1:
c += 1
Ls[i] -= 1
cache.append(Ls[i])
if Ls[-1] != end: Ls[-1] -= 1; cache.append(Ls[-1]); c += 1
if Ls[-1] == end: Ls.pop(); end += 1
if maxi - c >= k-1:
print("{} {}".format(c, " ".join(map(str, cache))))
maxi -= c
k -= 1
else:
tmp = maxi - k+1
print("{} {}".format(tmp, " ".join(map(str, cache[:tmp]))))
for i in range(tmp, c):
print("{} {}".format(1, cache[i]))
break
for l in Ls[::-1]:
for i in range(l-1, end-1, -1):
print("1 {}".format(i))
end += 1
``` | instruction | 0 | 65,732 | 3 | 131,464 |
Yes | output | 1 | 65,732 | 3 | 131,465 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.
Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other.
You are given the number n, the initial arrangement of children and the number k. You have to find a way for the children to act if they want to finish the process in exactly k seconds. More formally, for each of the k moves, you need to output the numbers of the children who turn left during this move.
For instance, for the configuration shown below and k = 2 children can do the following steps:
<image> At the beginning, two pairs make move: (1, 2) and (3, 4). After that, we receive the following configuration: <image> At the second move pair (2, 3) makes the move. The final configuration is reached. Good job. <image>
It is guaranteed that if the solution exists, it takes not more than n^2 "headturns".
Input
The first line of input contains two integers n and k (2 ≤ n ≤ 3000, 1 ≤ k ≤ 3000000) — the number of children and required number of moves.
The next line contains a string of length n and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right.
Output
If there is no solution, print a single line with number -1.
Otherwise, output k lines. Each line has to start with a number n_i (1≤ n_i ≤ n/2) — the number of pairs of children, who turn at this move. After that print n_i distinct integers — the numbers of the children who will turn left during this move.
After performing all "headturns", there can't be a pair of two neighboring children looking at each other.
If there are many solutions, print any of them.
Examples
Input
2 1
RL
Output
1 1
Input
2 1
LR
Output
-1
Input
4 2
RLRL
Output
2 1 3
1 2
Note
The first sample contains a pair of children who look at each other. After one move, they can finish the process.
In the second sample, children can't make any move. As a result, they can't end in k>0 moves.
The third configuration is described in the statement.
Submitted Solution:
```
N, K = map(int, input().split())
S = [1 if a == "R" else 0 for a in input()]
t = 0
a = 0
for s in S:
if s:
a += 1
else:
t += a
if K > t:
print(-1)
exit()
X = []
while True:
Y = [i for i in range(N-1) if S[i] and not S[i+1]]
if not len(Y): break
X.append(Y)
nS = [0] * N
i = N - 1
while i >= 0:
if S[i-1] and not S[i] and i:
nS[i] = 1
i -= 2
elif S[i]:
nS[i] = 1
i -= 1
else:
i -= 1
S = nS
u = len(X)
if K < u:
print(-1)
exit()
p1 = lambda x: [y+1 for y in x]
st = lambda x: " ".join(map(str, x))
ANS = []
K -= u
i = 0
for x in X:
for j, xx in enumerate(x):
if K:
ANS.append(st([1, xx + 1]))
if j < len(x) - 1: K -= 1
else:
ANS.append(st([len(x) - j] + p1(x[j:])))
break
strANS = "\n".join(ANS)
print(strANS)
``` | instruction | 0 | 65,733 | 3 | 131,466 |
Yes | output | 1 | 65,733 | 3 | 131,467 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.
Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other.
You are given the number n, the initial arrangement of children and the number k. You have to find a way for the children to act if they want to finish the process in exactly k seconds. More formally, for each of the k moves, you need to output the numbers of the children who turn left during this move.
For instance, for the configuration shown below and k = 2 children can do the following steps:
<image> At the beginning, two pairs make move: (1, 2) and (3, 4). After that, we receive the following configuration: <image> At the second move pair (2, 3) makes the move. The final configuration is reached. Good job. <image>
It is guaranteed that if the solution exists, it takes not more than n^2 "headturns".
Input
The first line of input contains two integers n and k (2 ≤ n ≤ 3000, 1 ≤ k ≤ 3000000) — the number of children and required number of moves.
The next line contains a string of length n and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right.
Output
If there is no solution, print a single line with number -1.
Otherwise, output k lines. Each line has to start with a number n_i (1≤ n_i ≤ n/2) — the number of pairs of children, who turn at this move. After that print n_i distinct integers — the numbers of the children who will turn left during this move.
After performing all "headturns", there can't be a pair of two neighboring children looking at each other.
If there are many solutions, print any of them.
Examples
Input
2 1
RL
Output
1 1
Input
2 1
LR
Output
-1
Input
4 2
RLRL
Output
2 1 3
1 2
Note
The first sample contains a pair of children who look at each other. After one move, they can finish the process.
In the second sample, children can't make any move. As a result, they can't end in k>0 moves.
The third configuration is described in the statement.
Submitted Solution:
```
def f():
# bubble to inc order
d = {'L': 0, 'R': 1}
n, k = [int(s) for s in input().split()]
A = [d[s] for s in input()]
best = []
notFin = 1
while notFin:
notFin = 0
sec = []
i = 1
while i < n:
if A[i - 1] > A[i]:
sec.append(i - 1)
A[i - 1], A[i] = 0, 1
notFin = 1
i += 1
i += 1
best.append(sec)
best.pop()
maxOp = 0
for p in best:
maxOp += len(p)
if k < len(best) or k > maxOp:
print(-1)
return
ans = []
ok = 0
rem = k - len(best)
if rem == 0:
ok = 1
for sec in best:
if ok:
ans.append('{} '.format(len(sec)))
ans.append(' '.join(str(_ + 1) for _ in sec))
ans.append('\n')
else:
for ind, left in enumerate(sec):
ans.append('1 {}\n'.format(left + 1))
rem -= 1
if rem == 0:
ok = 1
spOpLen = len(sec) - ind - 1
if spOpLen:
ans.append('{} '.format(spOpLen))
ans.append(' '.join(str(_ + 1) for _ in sec[ind + 1:]))
ans.append('\n')
break
print(''.join(ans))
f()
``` | instruction | 0 | 65,734 | 3 | 131,468 |
No | output | 1 | 65,734 | 3 | 131,469 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.
Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other.
You are given the number n, the initial arrangement of children and the number k. You have to find a way for the children to act if they want to finish the process in exactly k seconds. More formally, for each of the k moves, you need to output the numbers of the children who turn left during this move.
For instance, for the configuration shown below and k = 2 children can do the following steps:
<image> At the beginning, two pairs make move: (1, 2) and (3, 4). After that, we receive the following configuration: <image> At the second move pair (2, 3) makes the move. The final configuration is reached. Good job. <image>
It is guaranteed that if the solution exists, it takes not more than n^2 "headturns".
Input
The first line of input contains two integers n and k (2 ≤ n ≤ 3000, 1 ≤ k ≤ 3000000) — the number of children and required number of moves.
The next line contains a string of length n and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right.
Output
If there is no solution, print a single line with number -1.
Otherwise, output k lines. Each line has to start with a number n_i (1≤ n_i ≤ n/2) — the number of pairs of children, who turn at this move. After that print n_i distinct integers — the numbers of the children who will turn left during this move.
After performing all "headturns", there can't be a pair of two neighboring children looking at each other.
If there are many solutions, print any of them.
Examples
Input
2 1
RL
Output
1 1
Input
2 1
LR
Output
-1
Input
4 2
RLRL
Output
2 1 3
1 2
Note
The first sample contains a pair of children who look at each other. After one move, they can finish the process.
In the second sample, children can't make any move. As a result, they can't end in k>0 moves.
The third configuration is described in the statement.
Submitted Solution:
```
from os.path import split
from sys import stdin, stdout
def write(_s):
stdout.write(_s)
def writeint(_s):
stdout.write(str(_s))
def writelist(_l):
stdout.write(" ".join(_l))
def read():
return stdin.readline().strip()
def readlist():
return stdin.readline().strip().split(" ")
def readint():
return int(stdin.readline().strip())
def readints():
return map(int, stdin.readline().strip().split(" "))
n, k = readints()
string = list(read())
def solve():
total_indices = []
for _ in range(k):
indices = []
# search for all RL
i = 1
while i < n:
if string[i - 1] == "R" and string[i] == "L":
string[i], string[i - 1] = string[i - 1], string[i]
indices.append(str(i))
i += 2
else:
i += 1
total_indices.append(indices)
if not total_indices or not total_indices[0]:
writeint(-1)
return
for i in range(1, n):
if string[i - 1] == "R" and string[i] == "L":
writeint(-1)
return
# no RL found
for step in total_indices:
writeint(len(step))
write(" ")
writelist(step)
write("\n")
if __name__ == "__main__":
solve()
``` | instruction | 0 | 65,735 | 3 | 131,470 |
No | output | 1 | 65,735 | 3 | 131,471 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.
Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other.
You are given the number n, the initial arrangement of children and the number k. You have to find a way for the children to act if they want to finish the process in exactly k seconds. More formally, for each of the k moves, you need to output the numbers of the children who turn left during this move.
For instance, for the configuration shown below and k = 2 children can do the following steps:
<image> At the beginning, two pairs make move: (1, 2) and (3, 4). After that, we receive the following configuration: <image> At the second move pair (2, 3) makes the move. The final configuration is reached. Good job. <image>
It is guaranteed that if the solution exists, it takes not more than n^2 "headturns".
Input
The first line of input contains two integers n and k (2 ≤ n ≤ 3000, 1 ≤ k ≤ 3000000) — the number of children and required number of moves.
The next line contains a string of length n and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right.
Output
If there is no solution, print a single line with number -1.
Otherwise, output k lines. Each line has to start with a number n_i (1≤ n_i ≤ n/2) — the number of pairs of children, who turn at this move. After that print n_i distinct integers — the numbers of the children who will turn left during this move.
After performing all "headturns", there can't be a pair of two neighboring children looking at each other.
If there are many solutions, print any of them.
Examples
Input
2 1
RL
Output
1 1
Input
2 1
LR
Output
-1
Input
4 2
RLRL
Output
2 1 3
1 2
Note
The first sample contains a pair of children who look at each other. After one move, they can finish the process.
In the second sample, children can't make any move. As a result, they can't end in k>0 moves.
The third configuration is described in the statement.
Submitted Solution:
```
from sys import stdin, gettrace
import traceback
if not gettrace():
def input():
return next(stdin)[:-1]
# def input():
# return stdin.buffer.readline()
def main():
n ,k = map(int, input().split())
ss = list(input())
turns = []
new_turn = True
run = 0
tcount = 0
while new_turn:
new_turn = False
for i in range(n-1):
if ss[i] == 'R' and ss[i+1] == 'L':
new_turn = True
tcount += 1
turns.append((i+1,run))
ss[i] = 'L'
ss[i+1] = 'R'
run += 1
if run -1 > k or tcount < k:
print(-1)
return
extra = k - run + 1
pos = 0
moves = []
while extra > 0:
moves.append([1, turns[pos][0]])
if pos < tcount-1 and turns[pos][1] == turns[pos+1][1]:
extra -= 1
pos +=1
if pos == tcount:
return
moves.append([0])
while pos < tcount:
moves[-1].append(turns[pos][0])
moves[-1][0] += 1
if pos < tcount-1 and turns[pos][1] != turns[pos+1][1]:
moves.append([0])
pos += 1
for m in moves:
print(' '.join(map(str, m)))
if __name__ == "__main__":
try:
main()
except Exception:
print("Failed")
print(traceback.format_exc())
``` | instruction | 0 | 65,736 | 3 | 131,472 |
No | output | 1 | 65,736 | 3 | 131,473 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.
Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other.
You are given the number n, the initial arrangement of children and the number k. You have to find a way for the children to act if they want to finish the process in exactly k seconds. More formally, for each of the k moves, you need to output the numbers of the children who turn left during this move.
For instance, for the configuration shown below and k = 2 children can do the following steps:
<image> At the beginning, two pairs make move: (1, 2) and (3, 4). After that, we receive the following configuration: <image> At the second move pair (2, 3) makes the move. The final configuration is reached. Good job. <image>
It is guaranteed that if the solution exists, it takes not more than n^2 "headturns".
Input
The first line of input contains two integers n and k (2 ≤ n ≤ 3000, 1 ≤ k ≤ 3000000) — the number of children and required number of moves.
The next line contains a string of length n and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right.
Output
If there is no solution, print a single line with number -1.
Otherwise, output k lines. Each line has to start with a number n_i (1≤ n_i ≤ n/2) — the number of pairs of children, who turn at this move. After that print n_i distinct integers — the numbers of the children who will turn left during this move.
After performing all "headturns", there can't be a pair of two neighboring children looking at each other.
If there are many solutions, print any of them.
Examples
Input
2 1
RL
Output
1 1
Input
2 1
LR
Output
-1
Input
4 2
RLRL
Output
2 1 3
1 2
Note
The first sample contains a pair of children who look at each other. After one move, they can finish the process.
In the second sample, children can't make any move. As a result, they can't end in k>0 moves.
The third configuration is described in the statement.
Submitted Solution:
```
from _collections import deque
import sys
sys.setrecursionlimit(10000)
import math
import heapq
import bisect
# r=int(input())
# t = -1
# def input():
# global t
# t += 1
# return data[t]
# data=sys.stdin.readlines()
#inf=2*10**5
n,k=map(int,input().split())
s=list(input())
def check(i):
if s[i-1]=="R" and s[i]=="L":
return True
else:
return False
def change(i):
s[i],s[i-1]=s[i-1],s[i]
f=True
count=0
com=[]
count1=0
while f:
f=False
changes=[]
for i in range(1,n):
if check(i):
count+=1
changes.append(i)
#change(i)
f=True
if f:
for j in changes:
change(j)
com.append(changes)
count1+=1
#print(count)
if count<k or count1>k:
print(-1)
exit(0)
for i in range(len(com)):
if count>=k:
if count-len(com[i])>=k:
print(len(com[i]), *com[i])
count -= len(com[i])
else:
print(count-k+1,*com[i][:count-k+1])
count=k
else:
for j in com[i]:
print(1,com[i][j])
count-=1
k -= 1
# f1=True
# j=0
# while count-len(com[j])>=k and j<len(com):
# print(len(com[j]),*com[j])
# count -= len(com[j])
# j+=1
# if count>k:
# print(count-k+1,*com[j][:count-k+1])
# for i in com[j][count - k+1 :]:
# print(1,i)
# j+=1
# while j<len(com):
# for i in com[j]:
# print(1,i)
# j+=1
``` | instruction | 0 | 65,737 | 3 | 131,474 |
No | output | 1 | 65,737 | 3 | 131,475 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly.
<image>
An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.
You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7).
Input
The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path.
Output
Print the only integer — the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
2
Output
3
Input
4
Output
21
Note
The required paths in the first sample are:
* D - A - D
* D - B - D
* D - C - D
Submitted Solution:
```
n = int(input())
mod = 10**9 + 7
ans = pow(3,n,mod)
if( n % 2):
ans -= 3
else:
ans += 3
ans = ( ans * pow(4,mod-2,mod) ) % mod
print (ans)
``` | instruction | 0 | 65,843 | 3 | 131,686 |
Yes | output | 1 | 65,843 | 3 | 131,687 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly.
<image>
An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.
You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7).
Input
The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path.
Output
Print the only integer — the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
2
Output
3
Input
4
Output
21
Note
The required paths in the first sample are:
* D - A - D
* D - B - D
* D - C - D
Submitted Solution:
```
n=int(input())
print((pow(3,n,4*10**9+28)+3*(-1)**n)//4)
``` | instruction | 0 | 65,844 | 3 | 131,688 |
Yes | output | 1 | 65,844 | 3 | 131,689 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly.
<image>
An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.
You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7).
Input
The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path.
Output
Print the only integer — the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
2
Output
3
Input
4
Output
21
Note
The required paths in the first sample are:
* D - A - D
* D - B - D
* D - C - D
Submitted Solution:
```
n=int(input())-1
k=1
r=1000000007
dp=0
for i in range(n):
dp=(3*k-dp)
k*=3
k%=r
print(dp%r)
``` | instruction | 0 | 65,845 | 3 | 131,690 |
Yes | output | 1 | 65,845 | 3 | 131,691 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly.
<image>
An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.
You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7).
Input
The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path.
Output
Print the only integer — the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
2
Output
3
Input
4
Output
21
Note
The required paths in the first sample are:
* D - A - D
* D - B - D
* D - C - D
Submitted Solution:
```
from sys import stdin, stdout
n = int(stdin.readline()[:-1])
stdout.write(f"{(pow(3, n, 1000000007) + (-3 if n&1 else 3))*250000002%1000000007}")
``` | instruction | 0 | 65,846 | 3 | 131,692 |
Yes | output | 1 | 65,846 | 3 | 131,693 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly.
<image>
An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.
You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7).
Input
The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path.
Output
Print the only integer — the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
2
Output
3
Input
4
Output
21
Note
The required paths in the first sample are:
* D - A - D
* D - B - D
* D - C - D
Submitted Solution:
```
n=int(input())
m=10**9+7
print(pow(3,n-1,m)-pow(3,n-2,m))
``` | instruction | 0 | 65,847 | 3 | 131,694 |
No | output | 1 | 65,847 | 3 | 131,695 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly.
<image>
An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.
You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7).
Input
The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path.
Output
Print the only integer — the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
2
Output
3
Input
4
Output
21
Note
The required paths in the first sample are:
* D - A - D
* D - B - D
* D - C - D
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()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
n = inp()
'''
fdict = {}
fdict[1] = 0
fdict[2] = 3
def f(n):
if(n in fdict):
return fdict[n]
fdict[n] = 3 * g(n-1)
return fdict[n]
gdict = {}
gdict[0] = 0
gdict[1] = 1
def g(n):
if (n in gdict):
return gdict[n]
gdict[n] = ( f(n-1) + 2 * g(n-1))
return gdict[n]
f = [0,0]
g = [0,1]
for i in range(n+5):
f.append((g[-1]*3)%(10**9+7))
g.append((g[-1]*2+f[-2])%(10**9+7))
'''
print(3*(pow(3,n-1,10**9+7) + (-1)**n)//4)
``` | instruction | 0 | 65,848 | 3 | 131,696 |
No | output | 1 | 65,848 | 3 | 131,697 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly.
<image>
An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.
You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7).
Input
The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path.
Output
Print the only integer — the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
2
Output
3
Input
4
Output
21
Note
The required paths in the first sample are:
* D - A - D
* D - B - D
* D - C - D
Submitted Solution:
```
n=int(input())
m=10**9+7
if n==1:
print(0)
elif n==2:
print(3)
else: print(pow(3,n-1,m)-pow(3,n-2,m)+pow(3,n-3,m))
``` | instruction | 0 | 65,849 | 3 | 131,698 |
No | output | 1 | 65,849 | 3 | 131,699 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly.
<image>
An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.
You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7).
Input
The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path.
Output
Print the only integer — the required number of ways modulo 1000000007 (109 + 7).
Examples
Input
2
Output
3
Input
4
Output
21
Note
The required paths in the first sample are:
* D - A - D
* D - B - D
* D - C - D
Submitted Solution:
```
kMod = 10**9 + 7
def pow(a, n):
if n == 0:
return 1
if n % 2 == 0:
t = pow(a, n // 2) % kMod
return (t * t) % kMod
else:
t = pow(a, n // 2) % kMod
return (a * (t * t % kMod)) % kMod
n = int(input())
if (n % 2 == 0):
print((pow(3, n) + 3) // 4)
else:
print((pow(3, n) - 3) // 4)
``` | instruction | 0 | 65,850 | 3 | 131,700 |
No | output | 1 | 65,850 | 3 | 131,701 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel.
Ari draws a regular convex polygon on the floor and numbers it's vertices 1, 2, ..., n in clockwise order. Then starting from the vertex 1 she draws a ray in the direction of each other vertex. The ray stops when it reaches a vertex or intersects with another ray drawn before. Ari repeats this process for vertex 2, 3, ..., n (in this particular order). And then she puts a walnut in each region inside the polygon.
<image>
Ada the squirrel wants to collect all the walnuts, but she is not allowed to step on the lines drawn by Ari. That means Ada have to perform a small jump if she wants to go from one region to another. Ada can jump from one region P to another region Q if and only if P and Q share a side or a corner.
Assuming that Ada starts from outside of the picture, what is the minimum number of jumps she has to perform in order to collect all the walnuts?
Input
The first and only line of the input contains a single integer n (3 ≤ n ≤ 54321) - the number of vertices of the regular polygon drawn by Ari.
Output
Print the minimum number of jumps Ada should make to collect all the walnuts. Note, that she doesn't need to leave the polygon after.
Examples
Input
5
Output
9
Input
3
Output
1
Note
One of the possible solutions for the first sample is shown on the picture above. | instruction | 0 | 66,034 | 3 | 132,068 |
Tags: math
Correct Solution:
```
import math
from decimal import *
import sys
n=int(input())
print((n-3)*n -(n-3) + 1)
``` | output | 1 | 66,034 | 3 | 132,069 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel.
Ari draws a regular convex polygon on the floor and numbers it's vertices 1, 2, ..., n in clockwise order. Then starting from the vertex 1 she draws a ray in the direction of each other vertex. The ray stops when it reaches a vertex or intersects with another ray drawn before. Ari repeats this process for vertex 2, 3, ..., n (in this particular order). And then she puts a walnut in each region inside the polygon.
<image>
Ada the squirrel wants to collect all the walnuts, but she is not allowed to step on the lines drawn by Ari. That means Ada have to perform a small jump if she wants to go from one region to another. Ada can jump from one region P to another region Q if and only if P and Q share a side or a corner.
Assuming that Ada starts from outside of the picture, what is the minimum number of jumps she has to perform in order to collect all the walnuts?
Input
The first and only line of the input contains a single integer n (3 ≤ n ≤ 54321) - the number of vertices of the regular polygon drawn by Ari.
Output
Print the minimum number of jumps Ada should make to collect all the walnuts. Note, that she doesn't need to leave the polygon after.
Examples
Input
5
Output
9
Input
3
Output
1
Note
One of the possible solutions for the first sample is shown on the picture above.
Submitted Solution:
```
n = int(input())
a = (n - 2) * (n - 2)
print(a)
``` | instruction | 0 | 66,037 | 3 | 132,074 |
Yes | output | 1 | 66,037 | 3 | 132,075 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel.
Ari draws a regular convex polygon on the floor and numbers it's vertices 1, 2, ..., n in clockwise order. Then starting from the vertex 1 she draws a ray in the direction of each other vertex. The ray stops when it reaches a vertex or intersects with another ray drawn before. Ari repeats this process for vertex 2, 3, ..., n (in this particular order). And then she puts a walnut in each region inside the polygon.
<image>
Ada the squirrel wants to collect all the walnuts, but she is not allowed to step on the lines drawn by Ari. That means Ada have to perform a small jump if she wants to go from one region to another. Ada can jump from one region P to another region Q if and only if P and Q share a side or a corner.
Assuming that Ada starts from outside of the picture, what is the minimum number of jumps she has to perform in order to collect all the walnuts?
Input
The first and only line of the input contains a single integer n (3 ≤ n ≤ 54321) - the number of vertices of the regular polygon drawn by Ari.
Output
Print the minimum number of jumps Ada should make to collect all the walnuts. Note, that she doesn't need to leave the polygon after.
Examples
Input
5
Output
9
Input
3
Output
1
Note
One of the possible solutions for the first sample is shown on the picture above.
Submitted Solution:
```
n=int(input())
if n==3:
print(1)
else:
print((n*(n-2)-(n-4)-n))
``` | instruction | 0 | 66,038 | 3 | 132,076 |
Yes | output | 1 | 66,038 | 3 | 132,077 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel.
Ari draws a regular convex polygon on the floor and numbers it's vertices 1, 2, ..., n in clockwise order. Then starting from the vertex 1 she draws a ray in the direction of each other vertex. The ray stops when it reaches a vertex or intersects with another ray drawn before. Ari repeats this process for vertex 2, 3, ..., n (in this particular order). And then she puts a walnut in each region inside the polygon.
<image>
Ada the squirrel wants to collect all the walnuts, but she is not allowed to step on the lines drawn by Ari. That means Ada have to perform a small jump if she wants to go from one region to another. Ada can jump from one region P to another region Q if and only if P and Q share a side or a corner.
Assuming that Ada starts from outside of the picture, what is the minimum number of jumps she has to perform in order to collect all the walnuts?
Input
The first and only line of the input contains a single integer n (3 ≤ n ≤ 54321) - the number of vertices of the regular polygon drawn by Ari.
Output
Print the minimum number of jumps Ada should make to collect all the walnuts. Note, that she doesn't need to leave the polygon after.
Examples
Input
5
Output
9
Input
3
Output
1
Note
One of the possible solutions for the first sample is shown on the picture above.
Submitted Solution:
```
n = int(input())
ans = 1
ans += 3*(n-3)
ans += (n-3)*(n-4)
print(ans)
``` | instruction | 0 | 66,039 | 3 | 132,078 |
Yes | output | 1 | 66,039 | 3 | 132,079 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel.
Ari draws a regular convex polygon on the floor and numbers it's vertices 1, 2, ..., n in clockwise order. Then starting from the vertex 1 she draws a ray in the direction of each other vertex. The ray stops when it reaches a vertex or intersects with another ray drawn before. Ari repeats this process for vertex 2, 3, ..., n (in this particular order). And then she puts a walnut in each region inside the polygon.
<image>
Ada the squirrel wants to collect all the walnuts, but she is not allowed to step on the lines drawn by Ari. That means Ada have to perform a small jump if she wants to go from one region to another. Ada can jump from one region P to another region Q if and only if P and Q share a side or a corner.
Assuming that Ada starts from outside of the picture, what is the minimum number of jumps she has to perform in order to collect all the walnuts?
Input
The first and only line of the input contains a single integer n (3 ≤ n ≤ 54321) - the number of vertices of the regular polygon drawn by Ari.
Output
Print the minimum number of jumps Ada should make to collect all the walnuts. Note, that she doesn't need to leave the polygon after.
Examples
Input
5
Output
9
Input
3
Output
1
Note
One of the possible solutions for the first sample is shown on the picture above.
Submitted Solution:
```
n = int(input())
n-=2
print(n**2)
``` | instruction | 0 | 66,040 | 3 | 132,080 |
Yes | output | 1 | 66,040 | 3 | 132,081 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel.
Ari draws a regular convex polygon on the floor and numbers it's vertices 1, 2, ..., n in clockwise order. Then starting from the vertex 1 she draws a ray in the direction of each other vertex. The ray stops when it reaches a vertex or intersects with another ray drawn before. Ari repeats this process for vertex 2, 3, ..., n (in this particular order). And then she puts a walnut in each region inside the polygon.
<image>
Ada the squirrel wants to collect all the walnuts, but she is not allowed to step on the lines drawn by Ari. That means Ada have to perform a small jump if she wants to go from one region to another. Ada can jump from one region P to another region Q if and only if P and Q share a side or a corner.
Assuming that Ada starts from outside of the picture, what is the minimum number of jumps she has to perform in order to collect all the walnuts?
Input
The first and only line of the input contains a single integer n (3 ≤ n ≤ 54321) - the number of vertices of the regular polygon drawn by Ari.
Output
Print the minimum number of jumps Ada should make to collect all the walnuts. Note, that she doesn't need to leave the polygon after.
Examples
Input
5
Output
9
Input
3
Output
1
Note
One of the possible solutions for the first sample is shown on the picture above.
Submitted Solution:
```
n=int(input());
print(n**2);
``` | instruction | 0 | 66,041 | 3 | 132,082 |
No | output | 1 | 66,041 | 3 | 132,083 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel.
Ari draws a regular convex polygon on the floor and numbers it's vertices 1, 2, ..., n in clockwise order. Then starting from the vertex 1 she draws a ray in the direction of each other vertex. The ray stops when it reaches a vertex or intersects with another ray drawn before. Ari repeats this process for vertex 2, 3, ..., n (in this particular order). And then she puts a walnut in each region inside the polygon.
<image>
Ada the squirrel wants to collect all the walnuts, but she is not allowed to step on the lines drawn by Ari. That means Ada have to perform a small jump if she wants to go from one region to another. Ada can jump from one region P to another region Q if and only if P and Q share a side or a corner.
Assuming that Ada starts from outside of the picture, what is the minimum number of jumps she has to perform in order to collect all the walnuts?
Input
The first and only line of the input contains a single integer n (3 ≤ n ≤ 54321) - the number of vertices of the regular polygon drawn by Ari.
Output
Print the minimum number of jumps Ada should make to collect all the walnuts. Note, that she doesn't need to leave the polygon after.
Examples
Input
5
Output
9
Input
3
Output
1
Note
One of the possible solutions for the first sample is shown on the picture above.
Submitted Solution:
```
print((int(input())-3)*4+1)
``` | instruction | 0 | 66,042 | 3 | 132,084 |
No | output | 1 | 66,042 | 3 | 132,085 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel.
Ari draws a regular convex polygon on the floor and numbers it's vertices 1, 2, ..., n in clockwise order. Then starting from the vertex 1 she draws a ray in the direction of each other vertex. The ray stops when it reaches a vertex or intersects with another ray drawn before. Ari repeats this process for vertex 2, 3, ..., n (in this particular order). And then she puts a walnut in each region inside the polygon.
<image>
Ada the squirrel wants to collect all the walnuts, but she is not allowed to step on the lines drawn by Ari. That means Ada have to perform a small jump if she wants to go from one region to another. Ada can jump from one region P to another region Q if and only if P and Q share a side or a corner.
Assuming that Ada starts from outside of the picture, what is the minimum number of jumps she has to perform in order to collect all the walnuts?
Input
The first and only line of the input contains a single integer n (3 ≤ n ≤ 54321) - the number of vertices of the regular polygon drawn by Ari.
Output
Print the minimum number of jumps Ada should make to collect all the walnuts. Note, that she doesn't need to leave the polygon after.
Examples
Input
5
Output
9
Input
3
Output
1
Note
One of the possible solutions for the first sample is shown on the picture above.
Submitted Solution:
```
import sys
import math
from collections import OrderedDict
def input(): return sys.stdin.readline().strip()
def iinput(): return int(input())
def minput(): return map(int, input().split())
def listinput(): return list(map(int, input().split()))
n=iinput()
print(math.pow(3, n%3))
``` | instruction | 0 | 66,043 | 3 | 132,086 |
No | output | 1 | 66,043 | 3 | 132,087 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel.
Ari draws a regular convex polygon on the floor and numbers it's vertices 1, 2, ..., n in clockwise order. Then starting from the vertex 1 she draws a ray in the direction of each other vertex. The ray stops when it reaches a vertex or intersects with another ray drawn before. Ari repeats this process for vertex 2, 3, ..., n (in this particular order). And then she puts a walnut in each region inside the polygon.
<image>
Ada the squirrel wants to collect all the walnuts, but she is not allowed to step on the lines drawn by Ari. That means Ada have to perform a small jump if she wants to go from one region to another. Ada can jump from one region P to another region Q if and only if P and Q share a side or a corner.
Assuming that Ada starts from outside of the picture, what is the minimum number of jumps she has to perform in order to collect all the walnuts?
Input
The first and only line of the input contains a single integer n (3 ≤ n ≤ 54321) - the number of vertices of the regular polygon drawn by Ari.
Output
Print the minimum number of jumps Ada should make to collect all the walnuts. Note, that she doesn't need to leave the polygon after.
Examples
Input
5
Output
9
Input
3
Output
1
Note
One of the possible solutions for the first sample is shown on the picture above.
Submitted Solution:
```
n=int(input())
if(n==3):
print('1')
else:
cnt=((n-1)*2)+1
print(cnt)
``` | instruction | 0 | 66,044 | 3 | 132,088 |
No | output | 1 | 66,044 | 3 | 132,089 |
Provide a correct Python 3 solution for this coding contest problem.
Do you know Just Odd Inventions? The business of this company is to "just odd inventions". Here, it is abbreviated as JOI.
JOI is conducting research to confine many microorganisms in one petri dish alive. There are N microorganisms to be investigated, and they are numbered 1, 2, ..., N. When each microorganism is trapped in a petri dish, it instantly releases a harmful substance called foo (fatally odd object) into the petri dish. The amount of foo released by each microorganism is known. The foo released by all the microorganisms trapped in the petri dish is evenly ingested by each microorganism in the petri dish. The foo tolerance of each microorganism is known, and if foo is ingested in excess of this amount, the microorganism will die.
The foo release amount of the microorganism i is ai milligrams, and the foo tolerance is bi milligrams. That is, when the microorganisms i1, i2, ..., ik are trapped in the petri dish, each microorganism in the petri dish ingests (ai1 + ai2 + ... + aik) / k milligrams of foo, and the microorganisms in the petri dish ingest. i will die if this intake is greater than bi.
On behalf of JOI, you must keep as many microorganisms alive in the petri dish as possible. However, no microbes in the petri dish should die from ingestion of foo, as carcasses of microorganisms adversely affect the environment in the petri dish.
It is still a mystery how JOI profits from making "just a strange invention", and no one in JOI knows except the president.
input
Read the following input from standard input.
* The integer N is written on the first line, which indicates that there are N microorganisms to be investigated.
* The following N lines contain information on each microorganism. On the first line of i + (1 ≤ i ≤ N), the positive integers ai and bi are written separated by blanks, and the foo emission amount of the microorganism i is ai milligrams and the foo tolerance is bi milligrams. Represent.
output
Output the maximum number of microorganisms that can be confined in one petri dish to the standard output in one line.
Example
Input
6
12 8
5 9
2 4
10 12
6 7
13 9
Output
3 | instruction | 0 | 66,402 | 3 | 132,804 |
"Correct Solution:
```
# AOJ 0564: Bug Party
# Python3 2018.6.30 bal4u
import heapq
tbl = []
N = int(input())
for i in range(N):
a, b = map(int, input().split())
tbl.append((a, b))
tbl.sort()
Q = []
ans = s = sz = 0
for t in tbl:
s += t[0]
heapq.heappush(Q, (t[1], t[0]))
sz += 1
while sz and sz*Q[0][0] < s:
s -= Q[0][1]
heapq.heappop(Q)
sz -= 1
if sz > ans: ans = sz
print(ans)
``` | output | 1 | 66,402 | 3 | 132,805 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Paw the Spider is making a web. Web-making is a real art, Paw has been learning to do it his whole life. Let's consider the structure of the web.
<image>
There are n main threads going from the center of the web. All main threads are located in one plane and divide it into n equal infinite sectors. The sectors are indexed from 1 to n in the clockwise direction. Sectors i and i + 1 are adjacent for every i, 1 ≤ i < n. In addition, sectors 1 and n are also adjacent.
Some sectors have bridge threads. Each bridge connects the two main threads that make up this sector. The points at which the bridge is attached to the main threads will be called attachment points. Both attachment points of a bridge are at the same distance from the center of the web. At each attachment point exactly one bridge is attached. The bridges are adjacent if they are in the same sector, and there are no other bridges between them.
A cell of the web is a trapezoid, which is located in one of the sectors and is bounded by two main threads and two adjacent bridges. You can see that the sides of the cell may have the attachment points of bridges from adjacent sectors. If the number of attachment points on one side of the cell is not equal to the number of attachment points on the other side, it creates an imbalance of pulling forces on this cell and this may eventually destroy the entire web. We'll call such a cell unstable. The perfect web does not contain unstable cells.
Unstable cells are marked red in the figure. Stable cells are marked green.
Paw the Spider isn't a skillful webmaker yet, he is only learning to make perfect webs. Help Paw to determine the number of unstable cells in the web he has just spun.
Input
The first line contains integer n (3 ≤ n ≤ 1000) — the number of main threads.
The i-th of following n lines describe the bridges located in the i-th sector: first it contains integer ki (1 ≤ ki ≤ 105) equal to the number of bridges in the given sector. Then follow ki different integers pij (1 ≤ pij ≤ 105; 1 ≤ j ≤ ki). Number pij equals the distance from the attachment points of the j-th bridge of the i-th sector to the center of the web.
It is guaranteed that any two bridges between adjacent sectors are attached at a different distance from the center of the web. It is guaranteed that the total number of the bridges doesn't exceed 105.
Output
Print a single integer — the number of unstable cells in Paw the Spider's web.
Examples
Input
7
3 1 6 7
4 3 5 2 9
2 8 1
4 3 7 6 4
3 2 5 9
3 6 3 8
3 4 2 9
Output
6 | instruction | 0 | 66,696 | 3 | 133,392 |
Tags: binary search, sortings, two pointers
Correct Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz/'
M=1000000007
EPS=1e-6
def Ceil(a,b): return a//b+int(a%b>0)
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
n=Int()
sector=[]
for i in range(n):
sector.append(sorted(array()[1:]))
# for i in sector: print(*i)
# print()
ans=0
for cur in range(n):
aage=(cur+1)%n
peeche=(cur-1+n)%n
for i in range(1,len(sector[cur])):
l=sector[cur][i-1]
r=sector[cur][i]
left_count= bisect_left(sector[peeche],r) - bisect_right(sector[peeche],l)
right_count= bisect_left(sector[aage],r) - bisect_right(sector[aage],l)
# print(left_count,right_count)
ans+=(left_count!=right_count)
print(ans)
``` | output | 1 | 66,696 | 3 | 133,393 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Group of Berland scientists, with whom you have a close business relationship, makes a research in the area of peaceful nuclear energy. In particular, they found that a group of four nanobots, placed on a surface of a plate, can run a powerful chain reaction under certain conditions.
To be precise, researchers introduced a rectangular Cartesian coordinate system on a flat plate and selected four distinct points with integer coordinates where bots will be placed initially. Next each bot will be assigned with one of the four directions (up, down, left or right) parallel to the coordinate axes. After that, each bot is shifted by an integer distance (which may be different for different bots) along its direction. The chain reaction starts, if the bots are in the corners of a square with positive area with sides parallel to the coordinate axes. Each corner of the square must contain one nanobot. This reaction will be stronger, if bots spend less time to move. We can assume that bots move with unit speed. In other words, the lesser is the maximum length traveled by bot, the stronger is reaction.
Scientists have prepared a set of plates and selected starting position for the bots for each plate. Now they ask you to assign the direction for each bot to move after landing such that the maximum length traveled by bot is as small as possible.
Input
The first line contains an integer number t (1 ≤ t ≤ 50) — the number of plates.
t descriptions of plates follow. A description of each plate consists of four lines. Each line consists of a pair of integers numbers xi, yi ( - 108 ≤ xi, yi ≤ 108) — coordinates of the next bot. All bots are in different locations.
Note, though, the problem can include several records in one test, you can hack other people's submissions only with the test of one plate, i.e. parameter t in a hack test should be equal to 1.
Output
Print answers for all plates separately. First goes a single integer number in a separate line. If scientists have made an unfortunate mistake and nanobots are not able to form the desired square, print -1. Otherwise, print the minimum possible length of the longest bot's path.
If a solution exists, in the next four lines print two integer numbers — positions of each bot after moving. Print bots' positions in the order they are specified in the input data.
If there are multiple solution, you can print any of them.
Examples
Input
2
1 1
1 -1
-1 1
-1 -1
1 1
2 2
4 4
6 6
Output
0
1 1
1 -1
-1 1
-1 -1
-1 | instruction | 0 | 66,864 | 3 | 133,728 |
Tags: brute force, geometry
Correct Solution:
```
import sys
sys.stderr = sys.stdout
from collections import namedtuple
Bot = namedtuple('Bot', ('x', 'y', 'i'))
def yxi(bot):
return bot.y, bot.x, bot.i
def reaction1(B, V):
Bv = sorted(B[i] for i in range(4) if V[i])
Bh = sorted((B[i] for i in range(4) if not V[i]), key=yxi)
S = [None] * 4
if len(Bv) == 0:
if not (Bh[0].y == Bh[1].y < Bh[2].y == Bh[3].y):
return None, None
y0 = Bh[0].y
y1 = Bh[2].y
d = y1 - y0
X = [Bh[0].x, Bh[1].x - d, Bh[2].x, Bh[3].x - d]
Xmin = min(X)
Xmax = max(X)
x0 = (Xmin + Xmax) // 2
l = Xmax - x0
S[Bh[0].i] = x0, y0
S[Bh[1].i] = x0 + d, y0
S[Bh[2].i] = x0, y1
S[Bh[3].i] = x0 + d, y1
return l, S
elif len(Bv) == 1:
if Bh[0].y == Bh[1].y < Bh[2].y:
y0 = Bh[0].y
y1 = Bh[2].y
x0 = Bv[0].x
d = y1 - y0
l0 = abs(Bv[0].y - y1)
l1 = max(abs(x0 - Bh[0].x), abs(x0 + d - Bh[1].x),
l0, abs(x0 + d - Bh[2].x))
l2 = max(abs(x0 - d - Bh[0].x), abs(x0 - Bh[1].x),
abs(x0 - d - Bh[2].x), l0)
if l1 <= l2:
l = l1
S[Bh[0].i] = x0, y0
S[Bh[1].i] = x0 + d, y0
S[Bv[0].i] = x0, y1
S[Bh[2].i] = x0 + d, y1
else:
l = l2
S[Bh[0].i] = x0 - d, y0
S[Bh[1].i] = x0, y0
S[Bh[2].i] = x0 - d, y1
S[Bv[0].i] = x0, y1
return l, S
elif Bh[0].y < Bh[1].y == Bh[2].y:
y0 = Bh[0].y
y1 = Bh[2].y
x0 = Bv[0].x
d = y1 - y0
l0 = abs(Bv[0].y - y0)
l1 = max(l0, abs(x0 + d - Bh[0].x),
abs(x0 - Bh[1].x), abs(x0 + d - Bh[2].x))
l2 = max(abs(x0 - d - Bh[0].x), l0,
abs(x0 - d - Bh[1].x), abs(x0 - Bh[2].x))
if l1 <= l2:
l = l1
S[Bv[0].i] = x0, y0
S[Bh[0].i] = x0 + d, y0
S[Bh[1].i] = x0, y1
S[Bh[2].i] = x0 + d, y1
else:
l = l2
S[Bh[0].i] = x0 - d, y0
S[Bv[0].i] = x0, y0
S[Bh[1].i] = x0 - d, y1
S[Bh[2].i] = x0, y1
return l, S
else:
return None, None
elif len(Bv) == 2:
if Bv[0].x < Bv[1].x and Bh[0].y < Bh[1].y:
x0 = Bv[0].x
x1 = Bv[1].x
y0 = Bh[0].y
y1 = Bh[1].y
if x1 - x0 != y1 - y0:
return None, None
l1 = max(abs(Bh[0].x - x0), abs(Bv[0].y - y1),
abs(Bh[1].x - x1), abs(Bv[1].y - y0))
l2 = max(abs(Bh[0].x - x1), abs(Bv[0].y - y0),
abs(Bh[1].x - x0), abs(Bv[1].y - y1))
S = [None] * 4
if l1 <= l2:
l = l1
S[Bh[0].i] = x0, y0
S[Bh[1].i] = x1, y1
S[Bv[0].i] = x0, y1
S[Bv[1].i] = x1, y0
else:
l = l2
S[Bh[0].i] = x1, y0
S[Bh[1].i] = x0, y1
S[Bv[0].i] = x0, y0
S[Bv[1].i] = x1, y1
return l, S
elif Bv[0].x != Bv[1].x:
x0 = Bv[0].x
x1 = Bv[1].x
y0 = Bh[0].y
d = x1 - x0
lh = max(abs(Bh[0].x - x0), abs(Bh[1].x - x1))
l1 = max(lh, abs(y0 - d - Bv[0].y), abs(y0 - d - Bv[1].y))
l2 = max(lh, abs(y0 + d - Bv[0].y), abs(y0 + d - Bv[1].y))
S = [None] * 4
if l1 <= l2:
l = l1
S[Bh[0].i] = x0, y0
S[Bh[1].i] = x1, y0
S[Bv[0].i] = x0, y0 - d
S[Bv[1].i] = x1, y0 - d
else:
l = l2
S[Bh[0].i] = x0, y0
S[Bh[1].i] = x1, y0
S[Bv[0].i] = x0, y0 + d
S[Bv[1].i] = x1, y0 + d
return l, S
elif Bh[0].y != Bh[1].y:
y0 = Bh[0].y
y1 = Bh[1].y
x0 = Bv[0].x
d = y1 - y0
lh = max(abs(Bv[0].y - y0), abs(Bv[1].y - y1))
l1 = max(lh, abs(x0 - d - Bh[0].x), abs(x0 - d - Bh[1].x))
l2 = max(lh, abs(x0 + d - Bh[0].x), abs(x0 + d - Bh[1].x))
S = [None] * 4
if l1 <= l2:
l = l1
S[Bv[0].i] = x0, y0
S[Bv[1].i] = x0, y1
S[Bh[0].i] = x0 - d, y0
S[Bh[1].i] = x0 - d, y1
else:
l = l2
S[Bv[0].i] = x0, y0
S[Bv[1].i] = x0, y1
S[Bh[0].i] = x0 + d, y0
S[Bh[1].i] = x0 + d, y1
return l, S
else:
return None, None
elif len(Bv) == 3:
if Bv[0].x == Bv[1].x < Bv[2].x:
x0 = Bv[0].x
x1 = Bv[2].x
y0 = Bh[0].y
d = x1 - x0
l0 = abs(Bh[0].x - x1)
l1 = max(abs(y0 - Bv[0].y), abs(y0 + d - Bv[1].y),
l0, abs(y0 + d - Bv[2].y))
l2 = max(abs(y0 - d - Bv[0].y), abs(y0 - Bv[1].y),
abs(y0 - d - Bv[2].y), l0)
if l1 <= l2:
l = l1
S[Bv[0].i] = x0, y0
S[Bv[1].i] = x0, y0 + d
S[Bh[0].i] = x1, y0
S[Bv[2].i] = x1, y0 + d
else:
l = l2
S[Bv[0].i] = x0, y0 - d
S[Bv[1].i] = x0, y0
S[Bv[2].i] = x1, y0 - d
S[Bh[0].i] = x1, y0
return l, S
elif Bv[0].x < Bv[1].x == Bv[2].x:
x0 = Bv[0].x
x1 = Bv[2].x
y0 = Bh[0].y
d = x1 - x0
l0 = abs(Bh[0].x - x0)
l1 = max(l0, abs(y0 + d - Bv[0].y),
abs(y0 - Bv[1].y), abs(y0 + d - Bv[2].y))
l2 = max(abs(y0 - d - Bv[0].y), l0,
abs(y0 - d - Bv[1].y), abs(y0 - Bv[2].y))
if l1 <= l2:
l = l1
S[Bh[0].i] = x0, y0
S[Bv[0].i] = x0, y0 + d
S[Bv[1].i] = x1, y0
S[Bv[2].i] = x1, y0 + d
else:
l = l2
S[Bv[0].i] = x0, y0 - d
S[Bh[0].i] = x0, y0
S[Bv[1].i] = x1, y0 - d
S[Bv[2].i] = x1, y0
return l, S
else:
return None, None
elif len(Bv) == 4:
if not (Bv[0].x == Bv[1].x < Bv[2].x == Bv[3].x):
return None, None
x0 = Bv[0].x
x1 = Bv[2].x
d = x1 - x0
Y = [Bv[0].y, Bv[1].y - d, Bv[2].y, Bv[3].y - d]
Ymin = min(Y)
Ymax = max(Y)
y0 = (Ymin + Ymax) // 2
l = Ymax - y0
S[Bv[0].i] = x0, y0
S[Bv[1].i] = x0, y0 + d
S[Bv[2].i] = x1, y0
S[Bv[3].i] = x1, y0 + d
return l, S
def reaction(B):
l = None
S = None
for v0 in (True, False):
for v1 in (True, False):
for v2 in (True, False):
for v3 in (True, False):
l1, S1 = reaction1(B, (v0, v1, v2, v3))
if l1 is not None and (l is None or l1 < l):
l = l1
S = S1
return l, S
def readb(i):
x, y = readinti()
return Bot(x, y, i)
def main():
t = readint()
L = []
for _ in range(t):
B = [readb(i) for i in range(4)]
l, S = reaction(B)
if l is None:
L.append('-1')
else:
L.append(str(l))
L.extend(f'{b1} {b2}' for b1, b2 in S)
print('\n'.join(L))
##########
def readint():
return int(input())
def readinti():
return map(int, input().split())
def readintt():
return tuple(readinti())
def readintl():
return list(readinti())
def readinttl(k):
return [readintt() for _ in range(k)]
def readintll(k):
return [readintl() for _ in range(k)]
def log(*args, **kwargs):
print(*args, **kwargs, file=sys.__stderr__)
if __name__ == '__main__':
main()
``` | output | 1 | 66,864 | 3 | 133,729 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Group of Berland scientists, with whom you have a close business relationship, makes a research in the area of peaceful nuclear energy. In particular, they found that a group of four nanobots, placed on a surface of a plate, can run a powerful chain reaction under certain conditions.
To be precise, researchers introduced a rectangular Cartesian coordinate system on a flat plate and selected four distinct points with integer coordinates where bots will be placed initially. Next each bot will be assigned with one of the four directions (up, down, left or right) parallel to the coordinate axes. After that, each bot is shifted by an integer distance (which may be different for different bots) along its direction. The chain reaction starts, if the bots are in the corners of a square with positive area with sides parallel to the coordinate axes. Each corner of the square must contain one nanobot. This reaction will be stronger, if bots spend less time to move. We can assume that bots move with unit speed. In other words, the lesser is the maximum length traveled by bot, the stronger is reaction.
Scientists have prepared a set of plates and selected starting position for the bots for each plate. Now they ask you to assign the direction for each bot to move after landing such that the maximum length traveled by bot is as small as possible.
Input
The first line contains an integer number t (1 ≤ t ≤ 50) — the number of plates.
t descriptions of plates follow. A description of each plate consists of four lines. Each line consists of a pair of integers numbers xi, yi ( - 108 ≤ xi, yi ≤ 108) — coordinates of the next bot. All bots are in different locations.
Note, though, the problem can include several records in one test, you can hack other people's submissions only with the test of one plate, i.e. parameter t in a hack test should be equal to 1.
Output
Print answers for all plates separately. First goes a single integer number in a separate line. If scientists have made an unfortunate mistake and nanobots are not able to form the desired square, print -1. Otherwise, print the minimum possible length of the longest bot's path.
If a solution exists, in the next four lines print two integer numbers — positions of each bot after moving. Print bots' positions in the order they are specified in the input data.
If there are multiple solution, you can print any of them.
Examples
Input
2
1 1
1 -1
-1 1
-1 -1
1 1
2 2
4 4
6 6
Output
0
1 1
1 -1
-1 1
-1 -1
-1
Submitted Solution:
```
import sys
sys.stderr = sys.stdout
def flip(b):
return (b[1], b[0], b[2])
def reaction1(B, V):
Bv = sorted(B[i] for i in range(4) if V[i])
Bh = sorted(flip(B[i]) for i in range(4) if not V[i])
if len(Bv) == 0:
if not (Bh[0][0] == Bh[1][0]
and Bh[1][0] != Bh[2][0]
and Bh[2][0] == Bh[3][0]):
return None, None
d = Bh[2][0] - Bh[1][0]
X = [Bh[0][1], Bh[1][1] - d, Bh[2][1], Bh[3][1] - d]
X.sort()
x0 = (X[0] + X[3]) // 2
l = X[3] - x0
S = [None] * 4
for j, (y, x, i) in enumerate(Bh):
x = x0 + (d if j % 2 else 0)
S[i] = (x, y)
return l, S
elif len(Bv) == 1:
if Bh[0][0] == Bh[1][0] and Bh[1][0] != Bh[2][0]:
d = Bh[2][0] - Bh[0][0]
x0 = Bv[0][0]
x1 = Bh[0][1]
x2 = Bh[1][1]
x3 = Bh[2][1]
S = [None] * 4
S[Bv[0][2]] = Bv[0][0], Bh[2][0]
l1 = max(abs(x0 - x1), abs(x0 + d - x2), abs(x0 + d - x3))
l2 = max(abs(x0 - d - x1), abs(x0 - x2), abs(x0 - d - x3))
if l1 <= l2:
l = l1
S[Bh[0][2]] = x0, Bh[0][0]
S[Bh[1][2]] = x0 + d, Bh[1][0]
S[Bh[2][2]] = x0 + d, Bh[2][0]
else:
l = l2
S[Bh[0][2]] = x0 - d, Bh[0][0]
S[Bh[1][2]] = x0, Bh[1][0]
S[Bh[2][2]] = x0 - d, Bh[2][0]
return l, S
elif Bh[0][0] != Bh[1][0] and Bh[1][0] == Bh[2][0]:
d = Bh[2][0] - Bh[0][0]
x0 = Bv[0][0]
x1 = Bh[0][1]
x2 = Bh[1][1]
x3 = Bh[2][1]
S = [None] * 4
S[Bv[0][2]] = Bv[0][0], Bh[0][0]
l1 = max(abs(x0 + d - x1), abs(x0 - x2), abs(x0 + d - x3))
l2 = max(abs(x0 - d - x1), abs(x0 - d - x2), abs(x0 - x3))
if l1 <= l2:
l = l1
S[Bh[0][2]] = x0 + d, Bh[0][0]
S[Bh[1][2]] = x0, Bh[1][0]
S[Bh[2][2]] = x0 + d, Bh[2][0]
else:
l = l2
S[Bh[0][2]] = x0 - d, Bh[0][0]
S[Bh[1][2]] = x0 - d, Bh[1][0]
S[Bh[2][2]] = x0, Bh[2][0]
return l, S
else:
return None, None
elif len(Bv) == 2:
if Bv[0][0] != Bv[1][0] and Bh[0][0] != Bh[1][0]:
x0 = Bv[0][0]
x1 = Bv[1][0]
y0 = Bh[0][0]
y1 = Bh[1][0]
if x1 - x0 != y1 - y0:
return None, None
l1 = max(abs(Bh[0][1] - x0), abs(Bv[0][1] - y1),
abs(Bh[1][1] - x1), abs(Bv[1][1] - y0))
l2 = max(abs(Bh[0][1] - x1), abs(Bv[0][1] - y0),
abs(Bh[1][1] - x0), abs(Bv[1][1] - y1))
S = [None] * 4
if l1 <= l2:
l = l1
S[Bh[0][2]] = x0, y0
S[Bh[1][2]] = x1, y1
S[Bv[0][2]] = x0, y1
S[Bv[1][2]] = x1, y0
else:
l = l2
S[Bh[0][2]] = x1, y0
S[Bh[1][2]] = x0, y1
S[Bv[0][2]] = x0, y0
S[Bv[1][2]] = x1, y1
return l, S
elif Bv[0][0] != Bv[1][0]:
x0 = Bv[0][0]
x1 = Bv[1][0]
y0 = Bh[0][0]
d = x1 - x0
lh = max(abs(Bh[0][1] - x0), abs(Bh[1][1] - x1))
l1 = max(lh, abs(y0 - d - Bv[0][1]), abs(y0 - d - Bv[1][1]))
l2 = max(lh, abs(y0 + d - Bv[0][1]), abs(y0 + d - Bv[1][1]))
S = [None] * 4
if l1 <= l2:
l = l1
S[Bh[0][2]] = x0, y0
S[Bh[1][2]] = x1, y0
S[Bv[0][2]] = x0, y0 - d
S[Bv[1][2]] = x1, y0 - d
else:
l = l2
S[Bh[0][2]] = x0, y0
S[Bh[1][2]] = x1, y0
S[Bv[0][2]] = x0, y0 + d
S[Bv[1][2]] = x1, y0 + d
return l, S
elif Bh[0][0] != Bh[1][0]:
y0 = Bh[0][0]
y1 = Bh[1][0]
x0 = Bv[0][0]
d = y1 - y0
lh = max(abs(Bv[0][1] - y0), abs(Bv[1][1] - y1))
l1 = max(lh, abs(x0 - d - Bh[0][1]), abs(x0 - d - Bh[1][1]))
l2 = max(lh, abs(x0 + d - Bh[0][1]), abs(x0 + d - Bh[1][1]))
S = [None] * 4
if l1 <= l2:
l = l1
S[Bv[0][2]] = x0, y0
S[Bv[1][2]] = x0, y1
S[Bh[0][2]] = x0 - d, y0
S[Bh[1][2]] = x0 - d, y1
else:
l = l2
S[Bv[0][2]] = x0, y0
S[Bv[1][2]] = x0, y1
S[Bh[0][2]] = x0 + d, y0
S[Bh[1][2]] = x0 + d, y1
return l, S
else:
return None, None
elif len(Bv) == 3:
if Bv[0][0] == Bv[1][0] and Bv[1][0] != Bv[2][0]:
d = Bv[2][0] - Bv[0][0]
y0 = Bh[0][0]
y1 = Bv[0][1]
y2 = Bv[1][1]
y3 = Bv[2][1]
S = [None] * 4
S[Bh[0][2]] = Bv[2][0], Bh[0][0]
l1 = max(abs(y0 - y1), abs(y0 + d - y2), abs(y0 + d - y3))
l2 = max(abs(y0 - d - y1), abs(y0 - y2), abs(y0 - d - y3))
if l1 <= l2:
l = l1
S[Bv[0][2]] = Bv[0][0], y0
S[Bv[1][2]] = Bv[1][0], y0 + d
S[Bv[2][2]] = Bv[2][0], y0 + d
else:
l = l2
S[Bv[0][2]] = Bv[0][0], y0 - d
S[Bv[1][2]] = Bv[1][0], y0
S[Bv[2][2]] = Bv[2][0], y0 - d
return l, S
elif Bv[0][0] != Bv[1][0] and Bv[1][0] == Bv[2][0]:
d = Bv[2][0] - Bv[0][0]
y0 = Bh[0][0]
y1 = Bv[0][1]
y2 = Bv[1][1]
y3 = Bv[2][1]
S = [None] * 4
S[Bh[0][2]] = Bv[0][0], Bh[0][0]
l1 = max(abs(y0 + d - y1), abs(y0 - y2), abs(y0 + d - y3))
l2 = max(abs(y0 - d - y1), abs(y0 - d - y2), abs(y0 - y3))
if l1 <= l2:
l = l1
S[Bv[0][2]] = Bv[0][0], y0 + d
S[Bv[1][2]] = Bv[1][0], y0
S[Bv[2][2]] = Bv[2][0], y0 + d
else:
l = l2
S[Bv[0][2]] = Bv[0][0], y0 - d
S[Bv[1][2]] = Bv[1][0], y0 - d
S[Bv[2][2]] = Bv[2][0], y0
return l, S
else:
return None, None
elif len(Bv) == 4:
if not (Bv[0][0] == Bv[1][0]
and Bv[1][0] != Bv[2][0]
and Bv[2][0] == Bv[3][0]):
return None, None
d = Bv[2][0] - Bv[1][0]
Y = [Bv[0][1], Bv[1][1] - d, Bv[2][1], Bv[3][1] - d]
Y.sort()
y0 = (Y[0] + Y[3]) // 2
l = Y[3] - y0
S = [None] * 4
for j, (x, y, i) in enumerate(Bv):
y = y0 + (d if j % 2 else 0)
S[i] = (x, y)
return l, S
def reaction(B):
l = None
S = None
for v0 in (True, False):
for v1 in (True, False):
for v2 in (True, False):
for v3 in (True, False):
l1, S1 = reaction1(B, (v0, v1, v2, v3))
if l1 is not None and (l is None or l1 < l):
l = l1
S = S1
return l, S
def readb(i):
x, y = readinti()
return (x, y, i)
def main():
t = readint()
L = []
for _ in range(t):
B = [readb(i) for i in range(4)]
l, S = reaction(B)
if l is None:
L.append('-1')
else:
L.append(str(l))
L.extend(f'{b1} {b2}' for b1, b2 in S)
print('\n'.join(L))
##########
def readint():
return int(input())
def readinti():
return map(int, input().split())
def readintt():
return tuple(readinti())
def readintl():
return list(readinti())
def readinttl(k):
return [readintt() for _ in range(k)]
def readintll(k):
return [readintl() for _ in range(k)]
def log(*args, **kwargs):
print(*args, **kwargs, file=sys.__stderr__)
if __name__ == '__main__':
main()
``` | instruction | 0 | 66,865 | 3 | 133,730 |
No | output | 1 | 66,865 | 3 | 133,731 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Group of Berland scientists, with whom you have a close business relationship, makes a research in the area of peaceful nuclear energy. In particular, they found that a group of four nanobots, placed on a surface of a plate, can run a powerful chain reaction under certain conditions.
To be precise, researchers introduced a rectangular Cartesian coordinate system on a flat plate and selected four distinct points with integer coordinates where bots will be placed initially. Next each bot will be assigned with one of the four directions (up, down, left or right) parallel to the coordinate axes. After that, each bot is shifted by an integer distance (which may be different for different bots) along its direction. The chain reaction starts, if the bots are in the corners of a square with positive area with sides parallel to the coordinate axes. Each corner of the square must contain one nanobot. This reaction will be stronger, if bots spend less time to move. We can assume that bots move with unit speed. In other words, the lesser is the maximum length traveled by bot, the stronger is reaction.
Scientists have prepared a set of plates and selected starting position for the bots for each plate. Now they ask you to assign the direction for each bot to move after landing such that the maximum length traveled by bot is as small as possible.
Input
The first line contains an integer number t (1 ≤ t ≤ 50) — the number of plates.
t descriptions of plates follow. A description of each plate consists of four lines. Each line consists of a pair of integers numbers xi, yi ( - 108 ≤ xi, yi ≤ 108) — coordinates of the next bot. All bots are in different locations.
Note, though, the problem can include several records in one test, you can hack other people's submissions only with the test of one plate, i.e. parameter t in a hack test should be equal to 1.
Output
Print answers for all plates separately. First goes a single integer number in a separate line. If scientists have made an unfortunate mistake and nanobots are not able to form the desired square, print -1. Otherwise, print the minimum possible length of the longest bot's path.
If a solution exists, in the next four lines print two integer numbers — positions of each bot after moving. Print bots' positions in the order they are specified in the input data.
If there are multiple solution, you can print any of them.
Examples
Input
2
1 1
1 -1
-1 1
-1 -1
1 1
2 2
4 4
6 6
Output
0
1 1
1 -1
-1 1
-1 -1
-1
Submitted Solution:
```
T = int(input())
for i in range(T):
print(0)
for j in range(4):
print(input())
``` | instruction | 0 | 66,866 | 3 | 133,732 |
No | output | 1 | 66,866 | 3 | 133,733 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Group of Berland scientists, with whom you have a close business relationship, makes a research in the area of peaceful nuclear energy. In particular, they found that a group of four nanobots, placed on a surface of a plate, can run a powerful chain reaction under certain conditions.
To be precise, researchers introduced a rectangular Cartesian coordinate system on a flat plate and selected four distinct points with integer coordinates where bots will be placed initially. Next each bot will be assigned with one of the four directions (up, down, left or right) parallel to the coordinate axes. After that, each bot is shifted by an integer distance (which may be different for different bots) along its direction. The chain reaction starts, if the bots are in the corners of a square with positive area with sides parallel to the coordinate axes. Each corner of the square must contain one nanobot. This reaction will be stronger, if bots spend less time to move. We can assume that bots move with unit speed. In other words, the lesser is the maximum length traveled by bot, the stronger is reaction.
Scientists have prepared a set of plates and selected starting position for the bots for each plate. Now they ask you to assign the direction for each bot to move after landing such that the maximum length traveled by bot is as small as possible.
Input
The first line contains an integer number t (1 ≤ t ≤ 50) — the number of plates.
t descriptions of plates follow. A description of each plate consists of four lines. Each line consists of a pair of integers numbers xi, yi ( - 108 ≤ xi, yi ≤ 108) — coordinates of the next bot. All bots are in different locations.
Note, though, the problem can include several records in one test, you can hack other people's submissions only with the test of one plate, i.e. parameter t in a hack test should be equal to 1.
Output
Print answers for all plates separately. First goes a single integer number in a separate line. If scientists have made an unfortunate mistake and nanobots are not able to form the desired square, print -1. Otherwise, print the minimum possible length of the longest bot's path.
If a solution exists, in the next four lines print two integer numbers — positions of each bot after moving. Print bots' positions in the order they are specified in the input data.
If there are multiple solution, you can print any of them.
Examples
Input
2
1 1
1 -1
-1 1
-1 -1
1 1
2 2
4 4
6 6
Output
0
1 1
1 -1
-1 1
-1 -1
-1
Submitted Solution:
```
import sys
sys.stderr = sys.stdout
def flip(b):
return (b[1], b[0], b[2])
def reaction1(B, V):
Bv = sorted(B[i] for i in range(4) if V[i])
Bh = sorted(flip(B[i]) for i in range(4) if not V[i])
if len(Bv) == 0:
if not (Bh[0][0] == Bh[1][0]
and Bh[1][0] != Bh[2][0]
and Bh[2][0] == Bh[3][0]):
return None, None
d = Bh[2][0] - Bh[1][0]
X = [Bh[0][1], Bh[1][1] - d, Bh[2][1], Bh[3][1] - d]
X.sort()
x0 = (X[0] + X[3]) // 2
l = X[3] - x0
S = [None] * 4
for j, (y, x, i) in enumerate(Bh):
x = x0 + (d if j % 2 else 0)
S[i] = (x, y)
return l, S
elif len(Bv) == 1:
if Bh[0][0] == Bh[1][0] and Bh[1][0] != Bh[2][0]:
d = Bh[2][0] - Bh[0][0]
x0 = Bv[0][0]
x1 = Bh[0][1]
x2 = Bh[1][1]
x3 = Bh[2][1]
S = [None] * 4
S[Bv[0][2]] = Bv[0][0], Bh[2][0]
l1 = max(abs(x0 - x1), abs(x0 + d - x2), abs(x0 + d - x3))
l2 = max(abs(x0 - d - x1), abs(x0 - x2), abs(x0 - d - x3))
if l1 <= l2:
l = l1
S[Bh[0][2]] = x0, Bh[0][0]
S[Bh[1][2]] = x0 + d, Bh[1][0]
S[Bh[2][2]] = x0 + d, Bh[2][0]
else:
l = l2
S[Bh[0][2]] = x0 - d, Bh[0][0]
S[Bh[1][2]] = x0, Bh[1][0]
S[Bh[2][2]] = x0 - d, Bh[2][0]
return l, S
elif Bh[0][0] != Bh[1][0] and Bh[1][0] == Bh[2][0]:
d = Bh[2][0] - Bh[0][0]
x0 = Bv[0][0]
x1 = Bh[0][1]
x2 = Bh[1][1]
x3 = Bh[2][1]
S = [None] * 4
S[Bv[0][2]] = Bv[0][0], Bh[0][0]
l1 = max(abs(x0 + d - x1), abs(x0 - x2), abs(x0 + d - x3))
l2 = max(abs(x0 - d - x1), abs(x0 - d - x2), abs(x0 - x3))
if l1 <= l2:
l = l1
S[Bh[0][2]] = x0 + d, Bh[0][0]
S[Bh[1][2]] = x0, Bh[1][0]
S[Bh[2][2]] = x0 + d, Bh[2][0]
else:
l = l2
S[Bh[0][2]] = x0 - d, Bh[0][0]
S[Bh[1][2]] = x0 - d, Bh[1][0]
S[Bh[2][2]] = x0, Bh[2][0]
return l, S
else:
return None, None
elif len(Bv) == 2:
if Bv[0][0] != Bv[1][0] and Bh[0][0] != Bh[1][0]:
x0 = Bv[0][0]
x1 = Bv[1][0]
y0 = Bh[0][0]
y1 = Bh[1][0]
if x1 - x0 != y1 - y0:
return None, None
l1 = max(abs(Bh[0][1] - x0), abs(Bv[0][1] - y1),
abs(Bh[1][1] - x1), abs(Bv[1][1] - y0))
l2 = max(abs(Bh[0][1] - x1), abs(Bv[0][1] - y0),
abs(Bh[1][1] - x0), abs(Bv[1][1] - y1))
S = [None] * 4
if l1 <= l2:
l = l1
S[Bh[0][2]] = x0, y0
S[Bh[1][2]] = x1, y1
S[Bv[0][2]] = x0, y1
S[Bv[1][2]] = x1, y0
else:
l = l2
S[Bh[0][2]] = x1, y0
S[Bh[1][2]] = x0, y1
S[Bv[0][2]] = x0, y0
S[Bv[1][2]] = x1, y1
return l, S
elif Bv[0][0] != Bv[1][0]:
x0 = Bv[0][0]
x1 = Bv[1][0]
y0 = Bh[0][0]
d = x1 - x0
lh = max(abs(Bh[0][1] - x0), abs(Bh[1][1] - x1))
l1 = max(lh, abs(y0 - d - Bv[0][1]), abs(y0 - d - Bv[1][1]))
l2 = max(lh, abs(y0 + d - Bv[0][1]), abs(y0 + d - Bv[1][1]))
S = [None] * 4
if l1 <= l2:
l = l1
S[Bh[0][2]] = x0, y0
S[Bh[1][2]] = x1, y0
S[Bv[0][2]] = x0, y0 - d
S[Bv[1][2]] = x1, y0 - d
else:
l = l2
S[Bh[0][2]] = x0, y0
S[Bh[1][2]] = x1, y0
S[Bv[0][2]] = x0, y0 + d
S[Bv[1][2]] = x1, y0 + d
return l, S
elif Bh[0][0] != Bh[1][0]:
y0 = Bh[0][0]
y1 = Bh[1][0]
x0 = Bv[0][0]
d = y1 - y0
lh = max(abs(Bv[0][1] - y0), abs(Bv[1][1] - y1))
l1 = max(lh, abs(x0 - d - Bh[0][1]), abs(x0 - d - Bh[1][1]))
l2 = max(lh, abs(x0 + d - Bh[0][1]), abs(x0 + d - Bh[1][1]))
S = [None] * 4
if l1 <= l2:
l = l1
S[Bv[0][2]] = x0, y0
S[Bv[1][2]] = x0, y1
S[Bh[0][2]] = x0 - d, y0
S[Bh[1][2]] = x0 - d, y1
else:
l = l2
S[Bv[0][2]] = x0, y0
S[Bv[1][2]] = x0, y1
S[Bh[0][2]] = x0 + d, y0
S[Bh[1][2]] = x0 + d, y1
return l, S
else:
return None, None
elif len(Bv) == 3:
if Bv[0][0] == Bv[1][0] and Bv[1][0] != Bv[2][0]:
d = Bv[2][0] - Bv[0][0]
y0 = Bh[0][0]
y1 = Bv[0][1]
y2 = Bv[1][1]
y3 = Bv[2][1]
S = [None] * 4
S[Bh[0][2]] = Bv[2][0], Bh[0][0]
l1 = max(abs(y0 - y1), abs(y0 + d - y2), abs(y0 + d - y3))
l2 = max(abs(y0 - d - y1), abs(y0 - y2), abs(y0 - d - y3))
if l1 <= l2:
l = l1
S[Bv[0][2]] = Bv[0][0], y0
S[Bv[1][2]] = Bv[1][0], y0 + d
S[Bv[2][2]] = Bv[2][0], y0 + d
else:
l = l2
S[Bv[0][2]] = Bv[0][0], y0 - d
S[Bv[1][2]] = Bv[1][0], y0
S[Bv[2][2]] = Bv[2][0], y0 - d
return l, S
elif Bv[0][0] != Bv[1][0] and Bv[1][0] == Bv[2][0]:
d = Bv[2][0] - Bv[0][0]
y0 = Bh[0][0]
y1 = Bv[0][1]
y2 = Bv[1][1]
y3 = Bv[2][1]
S = [None] * 4
S[Bh[0][2]] = Bv[2][0], Bh[0][0]
l1 = max(abs(y0 + d - y1), abs(y0 - y2), abs(y0 + d - y3))
l2 = max(abs(y0 - d - y1), abs(y0 - d - y2), abs(y0 - y3))
if l1 <= l2:
l = l1
S[Bv[0][2]] = Bv[0][0], y0 + d
S[Bv[1][2]] = Bv[1][0], y0
S[Bv[2][2]] = Bv[2][0], y0 + d
else:
l = l2
S[Bv[0][2]] = Bv[0][0], y0 - d
S[Bv[1][2]] = Bv[1][0], y0 - d
S[Bv[2][2]] = Bv[2][0], y0
return l, S
else:
return None, None
elif len(Bv) == 4:
if not (Bv[0][0] == Bv[1][0]
and Bv[1][0] != Bv[2][0]
and Bv[2][0] == Bv[3][0]):
return None, None
d = Bv[2][0] - Bv[1][0]
Y = [Bv[0][1], Bv[1][1] - d, Bv[2][1], Bv[3][1] - d]
Y.sort()
y0 = (Y[0] + Y[3]) // 2
l = Y[3] - y0
S = [None] * 4
for j, (x, y, i) in enumerate(Bv):
y = y0 + (d if j % 2 else 0)
S[i] = (x, y)
return l, S
def reaction(B):
l = None
S = None
for v0 in (True, False):
for v1 in (True, False):
for v2 in (True, False):
for v3 in (True, False):
l1, S1 = reaction1(B, (v0, v1, v2, v3))
if l1 is not None and (l is None or l1 < l):
l = l1
S = S1
return l, S
def readb(i):
x, y = readinti()
return (x, y, i)
def main():
t = readint()
L = []
for _ in range(t):
B = [readb(i) for i in range(4)]
l, S = reaction(B)
if l is None:
L.append('-1')
else:
L.append(str(l))
L.extend(f'{b1} {b2}' for b1, b2 in S)
print('\n'.join(L))
##########
def readint():
return int(input())
def readinti():
return map(int, input().split())
def readintt():
return tuple(readinti())
def readintl():
return list(readinti())
def readinttl(k):
return [readintt() for _ in range(k)]
def readintll(k):
return [readintl() for _ in range(k)]
def log(*args, **kwargs):
print(*args, **kwargs, file=sys.__stderr__)
if __name__ == '__main__':
main()
``` | instruction | 0 | 66,867 | 3 | 133,734 |
No | output | 1 | 66,867 | 3 | 133,735 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Group of Berland scientists, with whom you have a close business relationship, makes a research in the area of peaceful nuclear energy. In particular, they found that a group of four nanobots, placed on a surface of a plate, can run a powerful chain reaction under certain conditions.
To be precise, researchers introduced a rectangular Cartesian coordinate system on a flat plate and selected four distinct points with integer coordinates where bots will be placed initially. Next each bot will be assigned with one of the four directions (up, down, left or right) parallel to the coordinate axes. After that, each bot is shifted by an integer distance (which may be different for different bots) along its direction. The chain reaction starts, if the bots are in the corners of a square with positive area with sides parallel to the coordinate axes. Each corner of the square must contain one nanobot. This reaction will be stronger, if bots spend less time to move. We can assume that bots move with unit speed. In other words, the lesser is the maximum length traveled by bot, the stronger is reaction.
Scientists have prepared a set of plates and selected starting position for the bots for each plate. Now they ask you to assign the direction for each bot to move after landing such that the maximum length traveled by bot is as small as possible.
Input
The first line contains an integer number t (1 ≤ t ≤ 50) — the number of plates.
t descriptions of plates follow. A description of each plate consists of four lines. Each line consists of a pair of integers numbers xi, yi ( - 108 ≤ xi, yi ≤ 108) — coordinates of the next bot. All bots are in different locations.
Note, though, the problem can include several records in one test, you can hack other people's submissions only with the test of one plate, i.e. parameter t in a hack test should be equal to 1.
Output
Print answers for all plates separately. First goes a single integer number in a separate line. If scientists have made an unfortunate mistake and nanobots are not able to form the desired square, print -1. Otherwise, print the minimum possible length of the longest bot's path.
If a solution exists, in the next four lines print two integer numbers — positions of each bot after moving. Print bots' positions in the order they are specified in the input data.
If there are multiple solution, you can print any of them.
Examples
Input
2
1 1
1 -1
-1 1
-1 -1
1 1
2 2
4 4
6 6
Output
0
1 1
1 -1
-1 1
-1 -1
-1
Submitted Solution:
```
import sys
sys.stderr = sys.stdout
def flip(b):
return (b[1], b[0], b[2])
def reaction1(B, V):
Bv = sorted(B[i] for i in range(4) if V[i])
Bh = sorted(flip(B[i]) for i in range(4) if not V[i])
if len(Bv) == 0:
if not (Bh[0][0] == Bh[1][0]
and Bh[1][0] != Bh[2][0]
and Bh[2][0] == Bh[3][0]):
return None, None
d = Bh[2][0] - Bh[1][0]
X = [Bh[0][1], Bh[1][1] - d, Bh[2][1], Bh[3][1] - d]
X.sort()
x0 = (X[0] + X[3]) // 2
l = X[3] - x0
S = [None] * 4
for j, (y, x, i) in enumerate(Bh):
x = x0 + (d if j % 2 else 0)
S[i] = (x, y)
return l, S
elif len(Bv) == 1:
if Bh[0][0] == Bh[1][0] and Bh[1][0] != Bh[2][0]:
d = Bh[2][0] - Bh[0][0]
x0 = Bv[0][0]
x1 = Bh[0][1]
x2 = Bh[1][1]
x3 = Bh[2][1]
S = [None] * 4
S[Bv[0][2]] = Bv[0][0], Bh[2][0]
l1 = max(abs(x0 - x1), abs(x0 + d - x2), abs(x0 + d - x3))
l2 = max(abs(x0 - d - x1), abs(x0 - x2), abs(x0 - d - x3))
if l1 <= l2:
l = l1
S[Bh[0][2]] = x0, Bh[0][0]
S[Bh[1][2]] = x0 + d, Bh[1][0]
S[Bh[2][2]] = x0 + d, Bh[2][0]
else:
l = l2
S[Bh[0][2]] = x0 - d, Bh[0][0]
S[Bh[1][2]] = x0, Bh[1][0]
S[Bh[2][2]] = x0 - d, Bh[2][0]
return l, S
elif Bh[0][0] != Bh[1][0] and Bh[1][0] == Bh[2][0]:
d = Bh[2][0] - Bh[0][0]
x0 = Bv[0][0]
x1 = Bh[0][1]
x2 = Bh[1][1]
x3 = Bh[2][1]
S = [None] * 4
S[Bv[0][2]] = Bv[0][0], Bh[0][0]
l1 = max(abs(x0 + d - x1), abs(x0 - x2), abs(x0 + d - x3))
l2 = max(abs(x0 - d - x1), abs(x0 - d - x2), abs(x0 - x3))
if l1 <= l2:
l = l1
S[Bh[0][2]] = x0 + d, Bh[0][0]
S[Bh[1][2]] = x0, Bh[1][0]
S[Bh[2][2]] = x0 + d, Bh[2][0]
else:
l = l2
S[Bh[0][2]] = x0 - d, Bh[0][0]
S[Bh[1][2]] = x0 - d, Bh[1][0]
S[Bh[2][2]] = x0, Bh[2][0]
return l, S
else:
return None, None
elif len(Bv) == 2:
if Bv[0][0] != Bv[1][0] and Bh[0][0] != Bh[1][0]:
x0 = Bv[0][0]
x1 = Bv[1][0]
y0 = Bh[0][0]
y1 = Bh[1][0]
if x1 - x0 != y1 - y0:
return None, None
l1 = max(abs(Bh[0][1] - x0), abs(Bv[0][1] - y1),
abs(Bh[1][1] - x1), abs(Bv[1][1] - y0))
l2 = max(abs(Bh[0][1] - x1), abs(Bv[0][1] - y0),
abs(Bh[1][1] - x0), abs(Bv[1][1] - y1))
S = [None] * 4
if l1 <= l2:
l = l1
S[Bh[0][2]] = x0, y0
S[Bh[1][2]] = x1, y1
S[Bv[0][2]] = x0, y1
S[Bv[1][2]] = x1, y0
else:
l = l2
S[Bh[0][2]] = x1, y0
S[Bh[1][2]] = x0, y1
S[Bv[0][2]] = x0, y0
S[Bv[1][2]] = x1, y1
return l, S
elif Bv[0][0] != Bv[1][0]:
x0 = Bv[0][0]
x1 = Bv[1][0]
y0 = Bh[0][0]
d = x1 - x0
lh = max(abs(Bh[0][1] - x0), abs(Bh[1][1] - x1))
l1 = max(lh, abs(y0 - d - Bv[0][0]), abs(y0 - d - Bv[1][0]))
l2 = max(lh, abs(y0 + d - Bv[0][0]), abs(y0 + d - Bv[1][0]))
S = [None] * 4
if l1 <= l2:
l = l1
S[Bh[0][2]] = x0, y0
S[Bh[1][2]] = x1, y0
S[Bv[0][2]] = x0, y0 - d
S[Bv[1][2]] = x1, y0 - d
else:
l = l2
S[Bh[0][2]] = x0, y0
S[Bh[1][2]] = x1, y0
S[Bv[0][2]] = x0, y0 + d
S[Bv[1][2]] = x1, y0 + d
return l, S
elif Bh[0][0] != Bh[1][0]:
y0 = Bh[0][0]
y1 = Bh[1][0]
x0 = Bv[0][0]
d = y1 - y0
lh = max(abs(Bv[0][1] - y0), abs(Bv[1][1] - y1))
l1 = max(lh, abs(x0 - d - Bh[0][0]), abs(x0 - d - Bh[1][0]))
l2 = max(lh, abs(x0 + d - Bh[0][0]), abs(x0 + d - Bh[1][0]))
S = [None] * 4
if l1 <= l2:
l = l1
S[Bv[0][2]] = x0, y0
S[Bv[1][2]] = x0, y1
S[Bh[0][2]] = x0 - d, y0
S[Bh[1][2]] = x0 - d, y1
else:
l = l2
S[Bv[0][2]] = x0, y0
S[Bv[1][2]] = x0, y1
S[Bh[0][2]] = x0 + d, y0
S[Bh[1][2]] = x0 + d, y1
return l, S
else:
return None, None
elif len(Bv) == 3:
if Bv[0][0] == Bv[1][0] and Bv[1][0] != Bv[2][0]:
d = Bv[2][0] - Bv[0][0]
y0 = Bh[0][0]
y1 = Bv[0][1]
y2 = Bv[1][1]
y3 = Bv[2][1]
S = [None] * 4
S[Bh[0][2]] = Bv[2][0], Bh[0][0]
l1 = max(abs(y0 - y1), abs(y0 + d - y2), abs(y0 + d - y3))
l2 = max(abs(y0 - d - y1), abs(y0 - y2), abs(y0 - d - y3))
if l1 <= l2:
l = l1
S[Bv[0][2]] = Bv[0][0], y0
S[Bv[1][2]] = Bv[1][0], y0 + d
S[Bv[2][2]] = Bv[2][0], y0 + d
else:
l = l2
S[Bv[0][2]] = Bv[0][0], y0 - d
S[Bv[1][2]] = Bv[1][0], y0
S[Bv[2][2]] = Bv[2][0], y0 - d
return l, S
elif Bv[0][0] != Bv[1][0] and Bv[1][0] == Bv[2][0]:
d = Bv[2][0] - Bv[0][0]
y0 = Bh[0][0]
y1 = Bv[0][1]
y2 = Bv[1][1]
y3 = Bv[2][1]
S = [None] * 4
S[Bh[0][2]] = Bv[2][0], Bh[0][0]
l1 = max(abs(y0 + d - y1), abs(y0 - y2), abs(y0 + d - y3))
l2 = max(abs(y0 - d - y1), abs(y0 - d - y2), abs(y0 - y3))
if l1 <= l2:
l = l1
S[Bv[0][2]] = Bv[0][0], y0 + d
S[Bv[1][2]] = Bv[1][0], y0
S[Bv[2][2]] = Bv[2][0], y0 + d
else:
l = l2
S[Bv[0][2]] = Bv[0][0], y0 - d
S[Bv[1][2]] = Bv[1][0], y0 - d
S[Bv[2][2]] = Bv[2][0], y0
return l, S
else:
return None, None
elif len(Bv) == 4:
if not (Bv[0][0] == Bv[1][0]
and Bv[1][0] != Bv[2][0]
and Bv[2][0] == Bv[3][0]):
return None, None
d = Bv[2][0] - Bv[1][0]
Y = [Bv[0][1], Bv[1][1] - d, Bv[2][1], Bv[3][1] - d]
Y.sort()
y0 = (Y[0] + Y[3]) // 2
l = Y[3] - y0
S = [None] * 4
for j, (x, y, i) in enumerate(Bv):
y = y0 + (d if j % 2 else 0)
S[i] = (x, y)
return l, S
def reaction(B):
l = None
S = None
for v0 in (True, False):
for v1 in (True, False):
for v2 in (True, False):
for v3 in (True, False):
l1, S1 = reaction1(B, (v0, v1, v2, v3))
if l1 is not None and (l is None or l1 < l):
l = l1
S = S1
return l, S
def readb(i):
x, y = readinti()
return (x, y, i)
def main():
t = readint()
L = []
for _ in range(t):
B = [readb(i) for i in range(4)]
l, S = reaction(B)
if l is None:
L.append('-1')
else:
L.append(str(l))
L.extend(f'{b1} {b2}' for b1, b2 in S)
print('\n'.join(L))
##########
def readint():
return int(input())
def readinti():
return map(int, input().split())
def readintt():
return tuple(readinti())
def readintl():
return list(readinti())
def readinttl(k):
return [readintt() for _ in range(k)]
def readintll(k):
return [readintl() for _ in range(k)]
def log(*args, **kwargs):
print(*args, **kwargs, file=sys.__stderr__)
if __name__ == '__main__':
main()
``` | instruction | 0 | 66,868 | 3 | 133,736 |
No | output | 1 | 66,868 | 3 | 133,737 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Breaking news from zombie neurology! It turns out that – contrary to previous beliefs – every zombie is born with a single brain, and only later it evolves into a complicated brain structure. In fact, whenever a zombie consumes a brain, a new brain appears in its nervous system and gets immediately connected to one of the already existing brains using a single brain connector. Researchers are now interested in monitoring the brain latency of a zombie. Your task is to write a program which, given a history of evolution of a zombie's nervous system, computes its brain latency at every stage.
Input
The first line of the input contains one number n – the number of brains in the final nervous system (2 ≤ n ≤ 200000). In the second line a history of zombie's nervous system evolution is given. For convenience, we number all the brains by 1, 2, ..., n in the same order as they appear in the nervous system (the zombie is born with a single brain, number 1, and subsequently brains 2, 3, ..., n are added). The second line contains n - 1 space-separated numbers p2, p3, ..., pn, meaning that after a new brain k is added to the system, it gets connected to a parent-brain <image>.
Output
Output n - 1 space-separated numbers – the brain latencies after the brain number k is added, for k = 2, 3, ..., n.
Example
Input
6
1
2
2
1
5
Output
1 2 2 3 4
Submitted Solution:
```
n = int(input())
dep = [0] * n
anc = [[0] * 18 for _ in range(n)]
def dist(x, y):
s = dep[x] + dep[y]
if dep[x] > dep[y]:
x, y = y, x
diff = dep[y] - dep[x]
i = 0
while diff > 0:
if diff % 2 == 1:
y = anc[y][i]
diff /= 2
i += 1
if x == y:
return s - dep[x] * 2
for i in range(17, -1, -1):
if anc[x][i] != anc[y][i]:
x, y = anc[x][i], anc[y][i]
return s - (dep[x] - 1) * 2
a, b, d = 0, 0, 0
ans = []
for v in range(1, n):
par = int(input()) - 1
dep[v] = dep[par] + 1
anc[v][0] = par
for i in range(1, 18):
x = anc[v][i - 1]
anc[v][i] = anc[x][i - 1]
cur = dist(a, v)
if cur > d:
a, b, d = a, v, cur
cur = dist(b, v)
if cur > d:
a, b, d = b, v, cur
ans.append(d)
print(' '.join(map(str, ans)))
``` | instruction | 0 | 66,869 | 3 | 133,738 |
No | output | 1 | 66,869 | 3 | 133,739 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Breaking news from zombie neurology! It turns out that – contrary to previous beliefs – every zombie is born with a single brain, and only later it evolves into a complicated brain structure. In fact, whenever a zombie consumes a brain, a new brain appears in its nervous system and gets immediately connected to one of the already existing brains using a single brain connector. Researchers are now interested in monitoring the brain latency of a zombie. Your task is to write a program which, given a history of evolution of a zombie's nervous system, computes its brain latency at every stage.
Input
The first line of the input contains one number n – the number of brains in the final nervous system (2 ≤ n ≤ 200000). In the second line a history of zombie's nervous system evolution is given. For convenience, we number all the brains by 1, 2, ..., n in the same order as they appear in the nervous system (the zombie is born with a single brain, number 1, and subsequently brains 2, 3, ..., n are added). The second line contains n - 1 space-separated numbers p2, p3, ..., pn, meaning that after a new brain k is added to the system, it gets connected to a parent-brain <image>.
Output
Output n - 1 space-separated numbers – the brain latencies after the brain number k is added, for k = 2, 3, ..., n.
Example
Input
6
1
2
2
1
5
Output
1 2 2 3 4
Submitted Solution:
```
class Node:
def __init__(self, value, parent, childid):
self.parent = parent
self.value = value
self.childs = []
# extension
## What index am I in the child array of the parent
self.childid = childid
self.childlatencies = []
def addChild(self, child):
self.childs.append(child)
self.childlatencies.append(0)
def getChilds(self):
return self.childs
class Tree:
def __init__(self):
self.root = Node(1, None, None)
self.nodes = [self.root]
self.numNodes = 1
self.maxLatency = 0
self.lastMaxLatency = 0
self.lastAddedNode = self.root
def addNodeAsChildOf(self, parent):
self.numNodes += 1
pNode = self.nodes[parent-1]
childid = len(pNode.childs)
nNode = Node(self.numNodes, pNode, childid)
pNode.addChild(nNode)
self.nodes.append(nNode)
self.lastAddedNode = nNode
def _maximumLatencyInner(self, node):
childs = node.getChilds()
if len(childs) == 0:
return 1;
max1 = 0
max2 = 0
for c in childs:
l = self._maximumLatencyInner(c)
if l > max1:
max2 = max1
max1 = l
elif l > max2:
max2 = l
maxSum = max1 + max2
if maxSum > self.maxLatency:
self.maxLatency = maxSum
return max1 + 1
def findMaximumLatency(self):
self.maxLatency = 0
self._maximumLatencyInner(self.root)
return self.maxLatency
def _maximumLatencyFastInner(self, node):
max1 = 0
max2 = 0
for l in node.childlatencies:
if l >= max1:
max2 = max1
max1 = l
elif l > max2:
max2 = l
maxSum = max1 + max2
if maxSum > self.maxLatency:
self.maxLatency = maxSum
if node.parent == None:
return
node.parent.childlatencies[node.childid] = max1 + 1
self._maximumLatencyFastInner(node.parent)
def findMaximumLatencyFast(self):
self.lastMaxLatency = self.maxLatency
self.maxLatency = 0
self._maximumLatencyFastInner(self.lastAddedNode)
return max([self.maxLatency, self.lastMaxLatency])
t = Tree()
numNodes = int(input(""))
latencies = []
for i in range(numNodes-1):
parent = int(input(""))
t.addNodeAsChildOf(parent)
latencies.append(t.findMaximumLatencyFast())
for i in latencies:
print(str(i)+" ", end="", flush=True)
``` | instruction | 0 | 66,870 | 3 | 133,740 |
No | output | 1 | 66,870 | 3 | 133,741 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Breaking news from zombie neurology! It turns out that – contrary to previous beliefs – every zombie is born with a single brain, and only later it evolves into a complicated brain structure. In fact, whenever a zombie consumes a brain, a new brain appears in its nervous system and gets immediately connected to one of the already existing brains using a single brain connector. Researchers are now interested in monitoring the brain latency of a zombie. Your task is to write a program which, given a history of evolution of a zombie's nervous system, computes its brain latency at every stage.
Input
The first line of the input contains one number n – the number of brains in the final nervous system (2 ≤ n ≤ 200000). In the second line a history of zombie's nervous system evolution is given. For convenience, we number all the brains by 1, 2, ..., n in the same order as they appear in the nervous system (the zombie is born with a single brain, number 1, and subsequently brains 2, 3, ..., n are added). The second line contains n - 1 space-separated numbers p2, p3, ..., pn, meaning that after a new brain k is added to the system, it gets connected to a parent-brain <image>.
Output
Output n - 1 space-separated numbers – the brain latencies after the brain number k is added, for k = 2, 3, ..., n.
Example
Input
6
1
2
2
1
5
Output
1 2 2 3 4
Submitted Solution:
```
class Node:
def __init__(self, value, parent):
self.parent = parent
self.value = value
self.childs = []
def addChild(self, child):
self.childs.append(child)
def getChilds(self):
return self.childs
class Tree:
def __init__(self):
self.root = Node(1, None)
self.nodes = [self.root]
self.numNodes = 1
self.maxLatency = 0
def addNodeAsChildOf(self, parent):
self.numNodes += 1
pNode = self.nodes[parent-1]
nNode = Node(self.numNodes, pNode)
pNode.addChild(nNode)
self.nodes.append(nNode)
def _maximumLatencyInner(self, node):
childs = node.getChilds()
if len(childs) == 0:
return 1;
latencies = []
for c in childs:
latencies.append(self._maximumLatencyInner(c))
latencies.sort()
maxSum = sum(latencies[-2:])
if maxSum > self.maxLatency:
self.maxLatency = maxSum
return latencies[-1] + 1
def findMaximumLatency(self):
self.maxLatency = 0
self._maximumLatencyInner(self.root)
return self.maxLatency
t = Tree()
numNodes = int(input(""))
latencies = []
for i in range(numNodes-1):
parent = int(input(""))
t.addNodeAsChildOf(parent)
latencies.append(t.findMaximumLatency())
print(latencies)
``` | instruction | 0 | 66,871 | 3 | 133,742 |
No | output | 1 | 66,871 | 3 | 133,743 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Breaking news from zombie neurology! It turns out that – contrary to previous beliefs – every zombie is born with a single brain, and only later it evolves into a complicated brain structure. In fact, whenever a zombie consumes a brain, a new brain appears in its nervous system and gets immediately connected to one of the already existing brains using a single brain connector. Researchers are now interested in monitoring the brain latency of a zombie. Your task is to write a program which, given a history of evolution of a zombie's nervous system, computes its brain latency at every stage.
Input
The first line of the input contains one number n – the number of brains in the final nervous system (2 ≤ n ≤ 200000). In the second line a history of zombie's nervous system evolution is given. For convenience, we number all the brains by 1, 2, ..., n in the same order as they appear in the nervous system (the zombie is born with a single brain, number 1, and subsequently brains 2, 3, ..., n are added). The second line contains n - 1 space-separated numbers p2, p3, ..., pn, meaning that after a new brain k is added to the system, it gets connected to a parent-brain <image>.
Output
Output n - 1 space-separated numbers – the brain latencies after the brain number k is added, for k = 2, 3, ..., n.
Example
Input
6
1
2
2
1
5
Output
1 2 2 3 4
Submitted Solution:
```
from collections import deque
def bfs(s):
q = deque()
dist = [-1 for _ in range(n)]
dist[s] = 0
q.append(s)
res_v = s
while len(q) != 0:
v = q.popleft()
res_v = v
used[v] = True
for u in g[v]:
if dist[u] == -1:
dist[u] = dist[v] + 1
q.append(u)
return res_v, dist
n = int(input())
s = [int(input()) for _ in range(n - 1)]
g = [set() for _ in range(n)]
for i in range(n - 1):
g[s[i] - 1].add(i + 1)
g[i + 1].add(s[i] - 1)
used = [False for _ in range(n)]
v, _ = bfs(0)
_, res = bfs(v)
used[0] = True
used[v] = True
mx = max(res)
for i in range(1, n):
if not used[i]:
v, _ = bfs(i)
_, res = bfs(v)
mx = max(mx, max(res))
print(mx)
``` | instruction | 0 | 66,872 | 3 | 133,744 |
No | output | 1 | 66,872 | 3 | 133,745 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You need to execute several tasks, each associated with number of processors it needs, and the compute power it will consume.
You have sufficient number of analog computers, each with enough processors for any task. Each computer can execute up to one task at a time, and no more than two tasks total. The first task can be any, the second task on each computer must use strictly less power than the first. You will assign between 1 and 2 tasks to each computer. You will then first execute the first task on each computer, wait for all of them to complete, and then execute the second task on each computer that has two tasks assigned.
If the average compute power per utilized processor (the sum of all consumed powers for all tasks presently running divided by the number of utilized processors) across all computers exceeds some unknown threshold during the execution of the first tasks, the entire system will blow up. There is no restriction on the second tasks execution. Find the lowest threshold for which it is possible.
Due to the specifics of the task, you need to print the answer multiplied by 1000 and rounded up.
Input
The first line contains a single integer n (1 ≤ n ≤ 50) — the number of tasks.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 108), where ai represents the amount of power required for the i-th task.
The third line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 100), where bi is the number of processors that i-th task will utilize.
Output
Print a single integer value — the lowest threshold for which it is possible to assign all tasks in such a way that the system will not blow up after the first round of computation, multiplied by 1000 and rounded up.
Examples
Input
6
8 10 9 9 8 10
1 1 1 1 1 1
Output
9000
Input
6
8 10 9 9 8 10
1 10 5 5 1 10
Output
1160
Note
In the first example the best strategy is to run each task on a separate computer, getting average compute per processor during the first round equal to 9.
In the second task it is best to run tasks with compute 10 and 9 on one computer, tasks with compute 10 and 8 on another, and tasks with compute 9 and 8 on the last, averaging (10 + 10 + 9) / (10 + 10 + 5) = 1.16 compute power per processor during the first round. | instruction | 0 | 67,001 | 3 | 134,002 |
Tags: binary search, dp, greedy
Correct Solution:
```
# Codeforces Round #488 by NEAR (Div. 2)
import collections
from functools import cmp_to_key
#key=cmp_to_key(lambda x,y: 1 if x not in y else -1 )
import math
import sys
def getIntList():
return list(map(int, input().split()))
import bisect
def makePair(z):
return [(z[i], z[i+1]) for i in range(0,len(z),2) ]
N, = getIntList()
za = getIntList()
zb = getIntList()
sa = set(za)
xa = list(sa)
xa.sort(reverse = True)
zz = [(t, sorted([zb[i] for i in range(N) if za[i] == t]) ) for t in xa ]
#print(zz)
lastdp = [[] for i in range(52)]
lastdp[0] = [(0,0)]
def addres(z, t):
if len(z) ==0:
z.append(t)
return
i = bisect.bisect_right(z,t)
if i>0 and z[i-1][1] >= t[1]: return
if i<len(z) and t[1] >= z[i][1]:
z[i] = t
return
z.insert(i,t)
for x in zz:
nowdp = [[] for i in range(52)]
for i in range(len(lastdp)):
tz = lastdp[i]
if len( tz ) ==0 : continue
num = len(x[1])
hide = min(i, num )
tb = sum(x[1])
acc =0;
for j in range(hide + 1):
la = x[0] * (num-j)
lb = tb - acc
if j<num: acc += x[1][j]
for t in tz:
# t = (0,0)
tr = (t[0] + la, t[1] + lb)
addres(nowdp[ i -j + num -j] ,tr)
lastdp = nowdp
#print(lastdp)
res = 10 ** 20
for x in lastdp:
for y in x:
t = math.ceil(y[0] *1000 / y[1] )
res = min( res,t)
print(res)
``` | output | 1 | 67,001 | 3 | 134,003 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You need to execute several tasks, each associated with number of processors it needs, and the compute power it will consume.
You have sufficient number of analog computers, each with enough processors for any task. Each computer can execute up to one task at a time, and no more than two tasks total. The first task can be any, the second task on each computer must use strictly less power than the first. You will assign between 1 and 2 tasks to each computer. You will then first execute the first task on each computer, wait for all of them to complete, and then execute the second task on each computer that has two tasks assigned.
If the average compute power per utilized processor (the sum of all consumed powers for all tasks presently running divided by the number of utilized processors) across all computers exceeds some unknown threshold during the execution of the first tasks, the entire system will blow up. There is no restriction on the second tasks execution. Find the lowest threshold for which it is possible.
Due to the specifics of the task, you need to print the answer multiplied by 1000 and rounded up.
Input
The first line contains a single integer n (1 ≤ n ≤ 50) — the number of tasks.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 108), where ai represents the amount of power required for the i-th task.
The third line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 100), where bi is the number of processors that i-th task will utilize.
Output
Print a single integer value — the lowest threshold for which it is possible to assign all tasks in such a way that the system will not blow up after the first round of computation, multiplied by 1000 and rounded up.
Examples
Input
6
8 10 9 9 8 10
1 1 1 1 1 1
Output
9000
Input
6
8 10 9 9 8 10
1 10 5 5 1 10
Output
1160
Note
In the first example the best strategy is to run each task on a separate computer, getting average compute per processor during the first round equal to 9.
In the second task it is best to run tasks with compute 10 and 9 on one computer, tasks with compute 10 and 8 on another, and tasks with compute 9 and 8 on the last, averaging (10 + 10 + 9) / (10 + 10 + 5) = 1.16 compute power per processor during the first round.
Submitted Solution:
```
# Codeforces Round #488 by NEAR (Div. 2)
import collections
from functools import cmp_to_key
#key=cmp_to_key(lambda x,y: 1 if x not in y else -1 )
import math
import sys
def getIntList():
return list(map(int, input().split()))
import bisect
def makePair(z):
return [(z[i], z[i+1]) for i in range(0,len(z),2) ]
N, = getIntList()
za = getIntList()
zb = getIntList()
sa = set(za)
xa = list(sa)
xa.sort(reverse = True)
zz = [(t, sorted([zb[i] for i in range(N) if za[i] == t]) ) for t in xa ]
print(zz)
lastdp = [[] for i in range(52)]
lastdp[0] = [(0,0)]
def addres(z, t):
if len(z) ==0:
z.append(t)
return
i = bisect.bisect_right(z,t)
if i>0 and z[i-1][1] >= t[1]: return
if i<len(z) and t[1] >= z[i][1]:
z[i] = t
return
z.insert(i,t)
for x in zz:
nowdp = [[] for i in range(52)]
for i in range(len(lastdp)):
tz = lastdp[i]
if len( tz ) ==0 : continue
num = len(x[1])
hide = min(i, num )
tb = sum(x[1])
acc =0;
for j in range(hide + 1):
la = x[0] * (num-j)
lb = tb - acc
if j<num: acc += x[1][j]
for t in tz:
# t = (0,0)
tr = (t[0] + la, t[1] + lb)
addres(nowdp[ i -j + num -j] ,tr)
lastdp = nowdp
#print(lastdp)
res = 10 ** 20
for x in lastdp:
for y in x:
t = math.ceil(y[0] *1000 / y[1] )
res = min( res,t)
print(res)
``` | instruction | 0 | 67,002 | 3 | 134,004 |
No | output | 1 | 67,002 | 3 | 134,005 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You need to execute several tasks, each associated with number of processors it needs, and the compute power it will consume.
You have sufficient number of analog computers, each with enough processors for any task. Each computer can execute up to one task at a time, and no more than two tasks total. The first task can be any, the second task on each computer must use strictly less power than the first. You will assign between 1 and 2 tasks to each computer. You will then first execute the first task on each computer, wait for all of them to complete, and then execute the second task on each computer that has two tasks assigned.
If the average compute power per utilized processor (the sum of all consumed powers for all tasks presently running divided by the number of utilized processors) across all computers exceeds some unknown threshold during the execution of the first tasks, the entire system will blow up. There is no restriction on the second tasks execution. Find the lowest threshold for which it is possible.
Due to the specifics of the task, you need to print the answer multiplied by 1000 and rounded up.
Input
The first line contains a single integer n (1 ≤ n ≤ 50) — the number of tasks.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 108), where ai represents the amount of power required for the i-th task.
The third line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 100), where bi is the number of processors that i-th task will utilize.
Output
Print a single integer value — the lowest threshold for which it is possible to assign all tasks in such a way that the system will not blow up after the first round of computation, multiplied by 1000 and rounded up.
Examples
Input
6
8 10 9 9 8 10
1 1 1 1 1 1
Output
9000
Input
6
8 10 9 9 8 10
1 10 5 5 1 10
Output
1160
Note
In the first example the best strategy is to run each task on a separate computer, getting average compute per processor during the first round equal to 9.
In the second task it is best to run tasks with compute 10 and 9 on one computer, tasks with compute 10 and 8 on another, and tasks with compute 9 and 8 on the last, averaging (10 + 10 + 9) / (10 + 10 + 5) = 1.16 compute power per processor during the first round.
Submitted Solution:
```
# Codeforces Round #488 by NEAR (Div. 2)
import collections
from functools import cmp_to_key
#key=cmp_to_key(lambda x,y: 1 if x not in y else -1 )
import math
import sys
def getIntList():
return list(map(int, input().split()))
import bisect
def makePair(z):
return [(z[i], z[i+1]) for i in range(0,len(z),2) ]
N, = getIntList()
za = getIntList()
zb = getIntList()
sa = set(za)
xa = list(sa)
xa.sort(reverse = True)
zz = [(t, sorted([zb[i] for i in range(N) if za[i] == t]) ) for t in xa ]
print(zz)
lastdp = [[] for i in range(52)]
lastdp[0] = [(0,0)]
def addres(z, t):
if len(z) ==0:
z.append(t)
return
i = bisect.bisect_right(z,t)
if i>0 and z[i-1][1] >= t[1]: return
if i<len(z) and t[1] >= z[i][1]:
z[i] = t
return
z.insert(i,t)
for x in zz:
nowdp = [[] for i in range(52)]
for i in range(len(lastdp)):
tz = lastdp[i]
if len( tz ) ==0 : continue
num = len(x[1])
hide = min(i, num )
tb = sum(x[1])
acc =0;
for j in range(hide + 1):
la = x[0] * (num-j)
lb = tb - acc
if j<num: acc += x[1][j]
for t in tz:
# t = (0,0)
tr = (t[0] + la, t[1] + lb)
addres(nowdp[ i -j + num -j] ,tr)
lastdp = nowdp
print(lastdp)
res = 10 ** 20
for x in lastdp:
for y in x:
t = math.ceil(y[0] *1000 / y[1] )
res = min( res,t)
print(res)
``` | instruction | 0 | 67,003 | 3 | 134,006 |
No | output | 1 | 67,003 | 3 | 134,007 |
Provide a correct Python 3 solution for this coding contest problem.
You are a member of the space station engineering team, and are assigned a task in the construction process of the station. You are expected to write a computer program to complete the task.
The space station is made up with a number of units, called cells. All cells are sphere-shaped, but their sizes are not necessarily uniform. Each cell is fixed at its predetermined position shortly after the station is successfully put into its orbit. It is quite strange that two cells may be touching each other, or even may be overlapping. In an extreme case, a cell may be totally enclosing another one. I do not know how such arrangements are possible.
All the cells must be connected, since crew members should be able to walk from any cell to any other cell. They can walk from a cell A to another cell B, if, (1) A and B are touching each other or overlapping, (2) A and B are connected by a `corridor', or (3) there is a cell C such that walking from A to C, and also from B to C are both possible. Note that the condition (3) should be interpreted transitively.
You are expected to design a configuration, namely, which pairs of cells are to be connected with corridors. There is some freedom in the corridor configuration. For example, if there are three cells A, B and C, not touching nor overlapping each other, at least three plans are possible in order to connect all three cells. The first is to build corridors A-B and A-C, the second B-C and B-A, the third C-A and C-B. The cost of building a corridor is proportional to its length. Therefore, you should choose a plan with the shortest total length of the corridors.
You can ignore the width of a corridor. A corridor is built between points on two cells' surfaces. It can be made arbitrarily long, but of course the shortest one is chosen. Even if two corridors A-B and C-D intersect in space, they are not considered to form a connection path between (for example) A and C. In other words, you may consider that two corridors never intersect.
Input
The input consists of multiple data sets. Each data set is given in the following format.
> n
> x1 y1 z1 r1
> x2 y2 z2 r2
> ...
> xn yn zn rn
>
The first line of a data set contains an integer n, which is the number of cells. n is positive, and does not exceed 100.
The following n lines are descriptions of cells. Four values in a line are x-, y- and z-coordinates of the center, and radius (called r in the rest of the problem) of the sphere, in this order. Each value is given by a decimal fraction, with 3 digits after the decimal point. Values are separated by a space character.
Each of x, y, z and r is positive and is less than 100.0.
The end of the input is indicated by a line containing a zero.
Output
For each data set, the shortest total length of the corridors should be printed, each in a separate line. The printed values should have 3 digits after the decimal point. They may not have an error greater than 0.001.
Note that if no corridors are necessary, that is, if all the cells are connected without corridors, the shortest total length of the corridors is 0.000.
Example
Input
3
10.000 10.000 50.000 10.000
40.000 10.000 50.000 10.000
40.000 40.000 50.000 10.000
2
30.000 30.000 30.000 20.000
40.000 40.000 40.000 20.000
5
5.729 15.143 3.996 25.837
6.013 14.372 4.818 10.671
80.115 63.292 84.477 15.120
64.095 80.924 70.029 14.881
39.472 85.116 71.369 5.553
0
Output
20.000
0.000
73.834 | instruction | 0 | 67,179 | 3 | 134,358 |
"Correct Solution:
```
import math
while True:
n=int(input())
if n==0:
break
G=[]
for index in range(n):
x,y,z,r=map(float,input().split())
G.append((x,y,z,r))
def distance(X,Y):
d=(X[0]-Y[0])**2+(X[1]-Y[1])**2+(X[2]-Y[2])**2
Max=X[3]+Y[3]
if Max**2<d:
return math.sqrt(d)-Max
else:
return 0
D=[[0]*n for _ in range(n)]
#隣接行列
for index1 in range(n):
for index2 in range(index1+1,n):
dist=distance(G[index1],G[index2])
D[index1][index2]=dist
D[index2][index1]=dist
def prim(n,cost):
mincost = [float("inf")]*n
used = [False] * n
mincost[0] = 0
res = 0
while True:
v = -1
for i in range(n):
if (not used[i]) and (v == -1 or mincost[i] < mincost[v]):
v = i
if v == -1:
break
used[v] = True
res += mincost[v]
for i in range(n):
mincost[i] = min(mincost[i],cost[v][i])
return res
ans=prim(n,D)
print('{:.3f}'.format(ans))
``` | output | 1 | 67,179 | 3 | 134,359 |
Provide a correct Python 3 solution for this coding contest problem.
You are a member of the space station engineering team, and are assigned a task in the construction process of the station. You are expected to write a computer program to complete the task.
The space station is made up with a number of units, called cells. All cells are sphere-shaped, but their sizes are not necessarily uniform. Each cell is fixed at its predetermined position shortly after the station is successfully put into its orbit. It is quite strange that two cells may be touching each other, or even may be overlapping. In an extreme case, a cell may be totally enclosing another one. I do not know how such arrangements are possible.
All the cells must be connected, since crew members should be able to walk from any cell to any other cell. They can walk from a cell A to another cell B, if, (1) A and B are touching each other or overlapping, (2) A and B are connected by a `corridor', or (3) there is a cell C such that walking from A to C, and also from B to C are both possible. Note that the condition (3) should be interpreted transitively.
You are expected to design a configuration, namely, which pairs of cells are to be connected with corridors. There is some freedom in the corridor configuration. For example, if there are three cells A, B and C, not touching nor overlapping each other, at least three plans are possible in order to connect all three cells. The first is to build corridors A-B and A-C, the second B-C and B-A, the third C-A and C-B. The cost of building a corridor is proportional to its length. Therefore, you should choose a plan with the shortest total length of the corridors.
You can ignore the width of a corridor. A corridor is built between points on two cells' surfaces. It can be made arbitrarily long, but of course the shortest one is chosen. Even if two corridors A-B and C-D intersect in space, they are not considered to form a connection path between (for example) A and C. In other words, you may consider that two corridors never intersect.
Input
The input consists of multiple data sets. Each data set is given in the following format.
> n
> x1 y1 z1 r1
> x2 y2 z2 r2
> ...
> xn yn zn rn
>
The first line of a data set contains an integer n, which is the number of cells. n is positive, and does not exceed 100.
The following n lines are descriptions of cells. Four values in a line are x-, y- and z-coordinates of the center, and radius (called r in the rest of the problem) of the sphere, in this order. Each value is given by a decimal fraction, with 3 digits after the decimal point. Values are separated by a space character.
Each of x, y, z and r is positive and is less than 100.0.
The end of the input is indicated by a line containing a zero.
Output
For each data set, the shortest total length of the corridors should be printed, each in a separate line. The printed values should have 3 digits after the decimal point. They may not have an error greater than 0.001.
Note that if no corridors are necessary, that is, if all the cells are connected without corridors, the shortest total length of the corridors is 0.000.
Example
Input
3
10.000 10.000 50.000 10.000
40.000 10.000 50.000 10.000
40.000 40.000 50.000 10.000
2
30.000 30.000 30.000 20.000
40.000 40.000 40.000 20.000
5
5.729 15.143 3.996 25.837
6.013 14.372 4.818 10.671
80.115 63.292 84.477 15.120
64.095 80.924 70.029 14.881
39.472 85.116 71.369 5.553
0
Output
20.000
0.000
73.834 | instruction | 0 | 67,180 | 3 | 134,360 |
"Correct Solution:
```
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
from itertools import permutations
from math import sqrt
import heapq
while 1:
N = int(input())
if N==0:
break
uf = UnionFind(N)
Vs = [list(map(float, input().split())) for _ in range(N)]
lis = [i for i in range(N)]
Edges = []
for a, b in permutations(lis, 2):
x1, y1, z1, r1 = Vs[a]
x2, y2, z2, r2 = Vs[b]
d = max(0, sqrt((x1-x2)**2+(y1-y2)**2+(z1-z2)**2)-r1-r2)
Edges.append((d, a, b))
heapq.heapify(Edges)
ans = 0
while Edges:
d, a, b = heapq.heappop(Edges)
if not uf.same(a, b):
ans += d
uf.union(a, b)
print('{:.3f}'.format(ans))
``` | output | 1 | 67,180 | 3 | 134,361 |
Provide a correct Python 3 solution for this coding contest problem.
You are a member of the space station engineering team, and are assigned a task in the construction process of the station. You are expected to write a computer program to complete the task.
The space station is made up with a number of units, called cells. All cells are sphere-shaped, but their sizes are not necessarily uniform. Each cell is fixed at its predetermined position shortly after the station is successfully put into its orbit. It is quite strange that two cells may be touching each other, or even may be overlapping. In an extreme case, a cell may be totally enclosing another one. I do not know how such arrangements are possible.
All the cells must be connected, since crew members should be able to walk from any cell to any other cell. They can walk from a cell A to another cell B, if, (1) A and B are touching each other or overlapping, (2) A and B are connected by a `corridor', or (3) there is a cell C such that walking from A to C, and also from B to C are both possible. Note that the condition (3) should be interpreted transitively.
You are expected to design a configuration, namely, which pairs of cells are to be connected with corridors. There is some freedom in the corridor configuration. For example, if there are three cells A, B and C, not touching nor overlapping each other, at least three plans are possible in order to connect all three cells. The first is to build corridors A-B and A-C, the second B-C and B-A, the third C-A and C-B. The cost of building a corridor is proportional to its length. Therefore, you should choose a plan with the shortest total length of the corridors.
You can ignore the width of a corridor. A corridor is built between points on two cells' surfaces. It can be made arbitrarily long, but of course the shortest one is chosen. Even if two corridors A-B and C-D intersect in space, they are not considered to form a connection path between (for example) A and C. In other words, you may consider that two corridors never intersect.
Input
The input consists of multiple data sets. Each data set is given in the following format.
> n
> x1 y1 z1 r1
> x2 y2 z2 r2
> ...
> xn yn zn rn
>
The first line of a data set contains an integer n, which is the number of cells. n is positive, and does not exceed 100.
The following n lines are descriptions of cells. Four values in a line are x-, y- and z-coordinates of the center, and radius (called r in the rest of the problem) of the sphere, in this order. Each value is given by a decimal fraction, with 3 digits after the decimal point. Values are separated by a space character.
Each of x, y, z and r is positive and is less than 100.0.
The end of the input is indicated by a line containing a zero.
Output
For each data set, the shortest total length of the corridors should be printed, each in a separate line. The printed values should have 3 digits after the decimal point. They may not have an error greater than 0.001.
Note that if no corridors are necessary, that is, if all the cells are connected without corridors, the shortest total length of the corridors is 0.000.
Example
Input
3
10.000 10.000 50.000 10.000
40.000 10.000 50.000 10.000
40.000 40.000 50.000 10.000
2
30.000 30.000 30.000 20.000
40.000 40.000 40.000 20.000
5
5.729 15.143 3.996 25.837
6.013 14.372 4.818 10.671
80.115 63.292 84.477 15.120
64.095 80.924 70.029 14.881
39.472 85.116 71.369 5.553
0
Output
20.000
0.000
73.834 | instruction | 0 | 67,181 | 3 | 134,362 |
"Correct Solution:
```
while True:
N = int(input())
if not N:
break
X = [False if i else True for i in range(N)]
ans = 0
V = [list(map(float, input().split())) for i in range(N)]
dp = [[0 for i in range(N)] for j in range(N)]
# とりあえずすべての変の距離を測る
for i in range(N):
for j in range(N):
if i == j:
dp[i][j] = float('inf')
else:
tmp = ((V[i][0] - V[j][0]) ** 2 + (V[i][1] - V[j][1]) ** 2 + (V[i][2] - V[j][2]) ** 2) ** 0.5
dp[i][j] = max(0, tmp - V[i][3] - V[j][3])
# おそらくプリム法
for loop in range(N - 1):
tmpmin = float('inf')
for i in range(N):
for j in range(N):
if X[i] and not X[j]:
if dp[i][j] < tmpmin:
tmpmin = dp[i][j]
tmp = j
ans += tmpmin
X[tmp] = True
print('{0:.3f}'.format(ans))
``` | output | 1 | 67,181 | 3 | 134,363 |
Provide a correct Python 3 solution for this coding contest problem.
You are a member of the space station engineering team, and are assigned a task in the construction process of the station. You are expected to write a computer program to complete the task.
The space station is made up with a number of units, called cells. All cells are sphere-shaped, but their sizes are not necessarily uniform. Each cell is fixed at its predetermined position shortly after the station is successfully put into its orbit. It is quite strange that two cells may be touching each other, or even may be overlapping. In an extreme case, a cell may be totally enclosing another one. I do not know how such arrangements are possible.
All the cells must be connected, since crew members should be able to walk from any cell to any other cell. They can walk from a cell A to another cell B, if, (1) A and B are touching each other or overlapping, (2) A and B are connected by a `corridor', or (3) there is a cell C such that walking from A to C, and also from B to C are both possible. Note that the condition (3) should be interpreted transitively.
You are expected to design a configuration, namely, which pairs of cells are to be connected with corridors. There is some freedom in the corridor configuration. For example, if there are three cells A, B and C, not touching nor overlapping each other, at least three plans are possible in order to connect all three cells. The first is to build corridors A-B and A-C, the second B-C and B-A, the third C-A and C-B. The cost of building a corridor is proportional to its length. Therefore, you should choose a plan with the shortest total length of the corridors.
You can ignore the width of a corridor. A corridor is built between points on two cells' surfaces. It can be made arbitrarily long, but of course the shortest one is chosen. Even if two corridors A-B and C-D intersect in space, they are not considered to form a connection path between (for example) A and C. In other words, you may consider that two corridors never intersect.
Input
The input consists of multiple data sets. Each data set is given in the following format.
> n
> x1 y1 z1 r1
> x2 y2 z2 r2
> ...
> xn yn zn rn
>
The first line of a data set contains an integer n, which is the number of cells. n is positive, and does not exceed 100.
The following n lines are descriptions of cells. Four values in a line are x-, y- and z-coordinates of the center, and radius (called r in the rest of the problem) of the sphere, in this order. Each value is given by a decimal fraction, with 3 digits after the decimal point. Values are separated by a space character.
Each of x, y, z and r is positive and is less than 100.0.
The end of the input is indicated by a line containing a zero.
Output
For each data set, the shortest total length of the corridors should be printed, each in a separate line. The printed values should have 3 digits after the decimal point. They may not have an error greater than 0.001.
Note that if no corridors are necessary, that is, if all the cells are connected without corridors, the shortest total length of the corridors is 0.000.
Example
Input
3
10.000 10.000 50.000 10.000
40.000 10.000 50.000 10.000
40.000 40.000 50.000 10.000
2
30.000 30.000 30.000 20.000
40.000 40.000 40.000 20.000
5
5.729 15.143 3.996 25.837
6.013 14.372 4.818 10.671
80.115 63.292 84.477 15.120
64.095 80.924 70.029 14.881
39.472 85.116 71.369 5.553
0
Output
20.000
0.000
73.834 | instruction | 0 | 67,182 | 3 | 134,364 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(10**6)
from heapq import heappop, heappush
def find(x):
if x == pair_lst[x]:
return x
else:
tmp = find(pair_lst[x])
pair_lst[x] = tmp
return tmp
x=[]
y=[]
z=[]
r=[]
def kr():
que=[]
for i in range(n-1):
for j in range(i+1,n):
wi=((x[i]-x[j])**2+(y[i]-y[j])**2+(z[i]-z[j])**2)**0.5
wi=max(0,wi-r[i]-r[j])
heappush(que,(wi,i,j))
length_sum = 0
while que:
w, s, t = heappop(que)
root_s = find(s)
root_t = find(t)
if root_s != root_t:
pair_lst[root_s] = root_t
length_sum += w
return length_sum
while True:
n=int(input())
x=[0.0]*n
y=[0.0]*n
z=[0.0]*n
r=[0.0]*n
pair_lst = [i for i in range(n)]
if n==0:
sys.exit()
for i in range(n):
x[i],y[i],z[i],r[i]=map(float,input().split())
print("{:.3f}".format(kr()))
``` | output | 1 | 67,182 | 3 | 134,365 |
Provide a correct Python 3 solution for this coding contest problem.
You are a member of the space station engineering team, and are assigned a task in the construction process of the station. You are expected to write a computer program to complete the task.
The space station is made up with a number of units, called cells. All cells are sphere-shaped, but their sizes are not necessarily uniform. Each cell is fixed at its predetermined position shortly after the station is successfully put into its orbit. It is quite strange that two cells may be touching each other, or even may be overlapping. In an extreme case, a cell may be totally enclosing another one. I do not know how such arrangements are possible.
All the cells must be connected, since crew members should be able to walk from any cell to any other cell. They can walk from a cell A to another cell B, if, (1) A and B are touching each other or overlapping, (2) A and B are connected by a `corridor', or (3) there is a cell C such that walking from A to C, and also from B to C are both possible. Note that the condition (3) should be interpreted transitively.
You are expected to design a configuration, namely, which pairs of cells are to be connected with corridors. There is some freedom in the corridor configuration. For example, if there are three cells A, B and C, not touching nor overlapping each other, at least three plans are possible in order to connect all three cells. The first is to build corridors A-B and A-C, the second B-C and B-A, the third C-A and C-B. The cost of building a corridor is proportional to its length. Therefore, you should choose a plan with the shortest total length of the corridors.
You can ignore the width of a corridor. A corridor is built between points on two cells' surfaces. It can be made arbitrarily long, but of course the shortest one is chosen. Even if two corridors A-B and C-D intersect in space, they are not considered to form a connection path between (for example) A and C. In other words, you may consider that two corridors never intersect.
Input
The input consists of multiple data sets. Each data set is given in the following format.
> n
> x1 y1 z1 r1
> x2 y2 z2 r2
> ...
> xn yn zn rn
>
The first line of a data set contains an integer n, which is the number of cells. n is positive, and does not exceed 100.
The following n lines are descriptions of cells. Four values in a line are x-, y- and z-coordinates of the center, and radius (called r in the rest of the problem) of the sphere, in this order. Each value is given by a decimal fraction, with 3 digits after the decimal point. Values are separated by a space character.
Each of x, y, z and r is positive and is less than 100.0.
The end of the input is indicated by a line containing a zero.
Output
For each data set, the shortest total length of the corridors should be printed, each in a separate line. The printed values should have 3 digits after the decimal point. They may not have an error greater than 0.001.
Note that if no corridors are necessary, that is, if all the cells are connected without corridors, the shortest total length of the corridors is 0.000.
Example
Input
3
10.000 10.000 50.000 10.000
40.000 10.000 50.000 10.000
40.000 40.000 50.000 10.000
2
30.000 30.000 30.000 20.000
40.000 40.000 40.000 20.000
5
5.729 15.143 3.996 25.837
6.013 14.372 4.818 10.671
80.115 63.292 84.477 15.120
64.095 80.924 70.029 14.881
39.472 85.116 71.369 5.553
0
Output
20.000
0.000
73.834 | instruction | 0 | 67,183 | 3 | 134,366 |
"Correct Solution:
```
from decimal import Decimal, getcontext
from itertools import combinations
from heapq import *
getcontext().prec = 30
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return False
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
return True
while True:
N = int(input())
if N ==0:
exit()
tree = UnionFind(N)
pos = dict()
for i in range(N):
pos[i] = tuple(map(Decimal, input().split()))
data = []
for a,b in combinations(range(N), 2):
x1,x2,x3,xr = pos[a]
y1,y2,y3,yr = pos[b]
cost = max(((x1-y1)**2 + (x2-y2)**2 + (x3-y3)**2).sqrt() -xr -yr, 0)
data.append((a, b, cost))
res = 0
data.sort(key=lambda x: x[2])
for a, b, cost in data:
if tree.union(a,b):
res += cost
print("{:.03f}".format(res))
``` | output | 1 | 67,183 | 3 | 134,367 |
Provide a correct Python 3 solution for this coding contest problem.
You are a member of the space station engineering team, and are assigned a task in the construction process of the station. You are expected to write a computer program to complete the task.
The space station is made up with a number of units, called cells. All cells are sphere-shaped, but their sizes are not necessarily uniform. Each cell is fixed at its predetermined position shortly after the station is successfully put into its orbit. It is quite strange that two cells may be touching each other, or even may be overlapping. In an extreme case, a cell may be totally enclosing another one. I do not know how such arrangements are possible.
All the cells must be connected, since crew members should be able to walk from any cell to any other cell. They can walk from a cell A to another cell B, if, (1) A and B are touching each other or overlapping, (2) A and B are connected by a `corridor', or (3) there is a cell C such that walking from A to C, and also from B to C are both possible. Note that the condition (3) should be interpreted transitively.
You are expected to design a configuration, namely, which pairs of cells are to be connected with corridors. There is some freedom in the corridor configuration. For example, if there are three cells A, B and C, not touching nor overlapping each other, at least three plans are possible in order to connect all three cells. The first is to build corridors A-B and A-C, the second B-C and B-A, the third C-A and C-B. The cost of building a corridor is proportional to its length. Therefore, you should choose a plan with the shortest total length of the corridors.
You can ignore the width of a corridor. A corridor is built between points on two cells' surfaces. It can be made arbitrarily long, but of course the shortest one is chosen. Even if two corridors A-B and C-D intersect in space, they are not considered to form a connection path between (for example) A and C. In other words, you may consider that two corridors never intersect.
Input
The input consists of multiple data sets. Each data set is given in the following format.
> n
> x1 y1 z1 r1
> x2 y2 z2 r2
> ...
> xn yn zn rn
>
The first line of a data set contains an integer n, which is the number of cells. n is positive, and does not exceed 100.
The following n lines are descriptions of cells. Four values in a line are x-, y- and z-coordinates of the center, and radius (called r in the rest of the problem) of the sphere, in this order. Each value is given by a decimal fraction, with 3 digits after the decimal point. Values are separated by a space character.
Each of x, y, z and r is positive and is less than 100.0.
The end of the input is indicated by a line containing a zero.
Output
For each data set, the shortest total length of the corridors should be printed, each in a separate line. The printed values should have 3 digits after the decimal point. They may not have an error greater than 0.001.
Note that if no corridors are necessary, that is, if all the cells are connected without corridors, the shortest total length of the corridors is 0.000.
Example
Input
3
10.000 10.000 50.000 10.000
40.000 10.000 50.000 10.000
40.000 40.000 50.000 10.000
2
30.000 30.000 30.000 20.000
40.000 40.000 40.000 20.000
5
5.729 15.143 3.996 25.837
6.013 14.372 4.818 10.671
80.115 63.292 84.477 15.120
64.095 80.924 70.029 14.881
39.472 85.116 71.369 5.553
0
Output
20.000
0.000
73.834 | instruction | 0 | 67,184 | 3 | 134,368 |
"Correct Solution:
```
import sys, itertools
input = lambda: sys.stdin.readline().rstrip()
sys.setrecursionlimit(10**7)
INF = 10**10
MOD = 1000000007
def I(): return int(input())
def F(): return float(input())
def S(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LS(): return input().split()
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def same(self, x, y):
return self.find(x) == self.find(y)
def kruskal(es, V):
es.sort(key=lambda x:x[2])
uf = UnionFind(V)
res = 0
for e in es:
if not uf.same(e[0], e[1]):
uf.union(e[0], e[1])
res += e[2]
return res
def resolve():
while True:
n = I()
if n==0:
break
else:
xyzr = [LF() for _ in range(n)]
edge = []
for i, j in itertools.combinations(range(n), 2):
corridor_length = max(sum([(k-m)**2 for k, m in zip(xyzr[i][:3], xyzr[j][:3])])**0.5-(xyzr[i][3]+xyzr[j][3]), 0)
edge.append([i, j, corridor_length])
# print(n, edge)
mst_cost = kruskal(edge, n)
print(f'{mst_cost:.03f}')
if __name__ == '__main__':
resolve()
``` | output | 1 | 67,184 | 3 | 134,369 |
Provide a correct Python 3 solution for this coding contest problem.
You are a member of the space station engineering team, and are assigned a task in the construction process of the station. You are expected to write a computer program to complete the task.
The space station is made up with a number of units, called cells. All cells are sphere-shaped, but their sizes are not necessarily uniform. Each cell is fixed at its predetermined position shortly after the station is successfully put into its orbit. It is quite strange that two cells may be touching each other, or even may be overlapping. In an extreme case, a cell may be totally enclosing another one. I do not know how such arrangements are possible.
All the cells must be connected, since crew members should be able to walk from any cell to any other cell. They can walk from a cell A to another cell B, if, (1) A and B are touching each other or overlapping, (2) A and B are connected by a `corridor', or (3) there is a cell C such that walking from A to C, and also from B to C are both possible. Note that the condition (3) should be interpreted transitively.
You are expected to design a configuration, namely, which pairs of cells are to be connected with corridors. There is some freedom in the corridor configuration. For example, if there are three cells A, B and C, not touching nor overlapping each other, at least three plans are possible in order to connect all three cells. The first is to build corridors A-B and A-C, the second B-C and B-A, the third C-A and C-B. The cost of building a corridor is proportional to its length. Therefore, you should choose a plan with the shortest total length of the corridors.
You can ignore the width of a corridor. A corridor is built between points on two cells' surfaces. It can be made arbitrarily long, but of course the shortest one is chosen. Even if two corridors A-B and C-D intersect in space, they are not considered to form a connection path between (for example) A and C. In other words, you may consider that two corridors never intersect.
Input
The input consists of multiple data sets. Each data set is given in the following format.
> n
> x1 y1 z1 r1
> x2 y2 z2 r2
> ...
> xn yn zn rn
>
The first line of a data set contains an integer n, which is the number of cells. n is positive, and does not exceed 100.
The following n lines are descriptions of cells. Four values in a line are x-, y- and z-coordinates of the center, and radius (called r in the rest of the problem) of the sphere, in this order. Each value is given by a decimal fraction, with 3 digits after the decimal point. Values are separated by a space character.
Each of x, y, z and r is positive and is less than 100.0.
The end of the input is indicated by a line containing a zero.
Output
For each data set, the shortest total length of the corridors should be printed, each in a separate line. The printed values should have 3 digits after the decimal point. They may not have an error greater than 0.001.
Note that if no corridors are necessary, that is, if all the cells are connected without corridors, the shortest total length of the corridors is 0.000.
Example
Input
3
10.000 10.000 50.000 10.000
40.000 10.000 50.000 10.000
40.000 40.000 50.000 10.000
2
30.000 30.000 30.000 20.000
40.000 40.000 40.000 20.000
5
5.729 15.143 3.996 25.837
6.013 14.372 4.818 10.671
80.115 63.292 84.477 15.120
64.095 80.924 70.029 14.881
39.472 85.116 71.369 5.553
0
Output
20.000
0.000
73.834 | instruction | 0 | 67,185 | 3 | 134,370 |
"Correct Solution:
```
import heapq
import math
def dist(xyzr0, xyzr1):
vec = [xyzr0[i] - xyzr1[i] for i in range(3)]
d = math.sqrt(sum([elem*elem for elem in vec]))
return max(0, d - xyzr0[3] - xyzr1[3])
def mst(n, dists):
in_tree = [False] * n
start = 0
in_tree[start] = True
q = [(dists[start][to], start, to) for to in range(n)]
heapq.heapify(q)
ans = 0
cnt = 0
while q and cnt < n-1:
dist, fr, to = heapq.heappop(q)
if in_tree[to]:
continue
in_tree[to] = True
ans += dist
cnt += 1
for to_ in range(n):
heapq.heappush(q, (dists[to][to_], to, to_))
return ans
def solve(n):
XYZR = []
for _ in range(n):
XYZR.append(list(map(float, input().split())))
dists = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
dists[i][j] = dist(XYZR[i], XYZR[j])
ans = mst(n, dists)
print('%.3f' % ans)
while True:
n = int(input())
if n == 0:
break
solve(n)
``` | output | 1 | 67,185 | 3 | 134,371 |
Provide a correct Python 3 solution for this coding contest problem.
You are a member of the space station engineering team, and are assigned a task in the construction process of the station. You are expected to write a computer program to complete the task.
The space station is made up with a number of units, called cells. All cells are sphere-shaped, but their sizes are not necessarily uniform. Each cell is fixed at its predetermined position shortly after the station is successfully put into its orbit. It is quite strange that two cells may be touching each other, or even may be overlapping. In an extreme case, a cell may be totally enclosing another one. I do not know how such arrangements are possible.
All the cells must be connected, since crew members should be able to walk from any cell to any other cell. They can walk from a cell A to another cell B, if, (1) A and B are touching each other or overlapping, (2) A and B are connected by a `corridor', or (3) there is a cell C such that walking from A to C, and also from B to C are both possible. Note that the condition (3) should be interpreted transitively.
You are expected to design a configuration, namely, which pairs of cells are to be connected with corridors. There is some freedom in the corridor configuration. For example, if there are three cells A, B and C, not touching nor overlapping each other, at least three plans are possible in order to connect all three cells. The first is to build corridors A-B and A-C, the second B-C and B-A, the third C-A and C-B. The cost of building a corridor is proportional to its length. Therefore, you should choose a plan with the shortest total length of the corridors.
You can ignore the width of a corridor. A corridor is built between points on two cells' surfaces. It can be made arbitrarily long, but of course the shortest one is chosen. Even if two corridors A-B and C-D intersect in space, they are not considered to form a connection path between (for example) A and C. In other words, you may consider that two corridors never intersect.
Input
The input consists of multiple data sets. Each data set is given in the following format.
> n
> x1 y1 z1 r1
> x2 y2 z2 r2
> ...
> xn yn zn rn
>
The first line of a data set contains an integer n, which is the number of cells. n is positive, and does not exceed 100.
The following n lines are descriptions of cells. Four values in a line are x-, y- and z-coordinates of the center, and radius (called r in the rest of the problem) of the sphere, in this order. Each value is given by a decimal fraction, with 3 digits after the decimal point. Values are separated by a space character.
Each of x, y, z and r is positive and is less than 100.0.
The end of the input is indicated by a line containing a zero.
Output
For each data set, the shortest total length of the corridors should be printed, each in a separate line. The printed values should have 3 digits after the decimal point. They may not have an error greater than 0.001.
Note that if no corridors are necessary, that is, if all the cells are connected without corridors, the shortest total length of the corridors is 0.000.
Example
Input
3
10.000 10.000 50.000 10.000
40.000 10.000 50.000 10.000
40.000 40.000 50.000 10.000
2
30.000 30.000 30.000 20.000
40.000 40.000 40.000 20.000
5
5.729 15.143 3.996 25.837
6.013 14.372 4.818 10.671
80.115 63.292 84.477 15.120
64.095 80.924 70.029 14.881
39.472 85.116 71.369 5.553
0
Output
20.000
0.000
73.834 | instruction | 0 | 67,186 | 3 | 134,372 |
"Correct Solution:
```
# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1127
from decimal import Decimal, getcontext
from itertools import combinations
from heapq import *
getcontext().prec = 30
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return False
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
return True
while True:
N = int(input())
if N ==0:
exit()
tree = UnionFind(N)
pos = dict()
for i in range(N):
pos[i] = tuple(map(Decimal, input().split()))
data = []
for a,b in combinations(range(N), 2):
x1,x2,x3,xr = pos[a]
y1,y2,y3,yr = pos[b]
cost = max(((x1-y1)**2 + (x2-y2)**2 + (x3-y3)**2).sqrt() -xr -yr, 0)
data.append((a, b, cost))
res = 0
data.sort(key=lambda x: x[2])
for a, b, cost in data:
if tree.union(a,b):
res += cost
print("{:.03f}".format(res))
``` | output | 1 | 67,186 | 3 | 134,373 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are a member of the space station engineering team, and are assigned a task in the construction process of the station. You are expected to write a computer program to complete the task.
The space station is made up with a number of units, called cells. All cells are sphere-shaped, but their sizes are not necessarily uniform. Each cell is fixed at its predetermined position shortly after the station is successfully put into its orbit. It is quite strange that two cells may be touching each other, or even may be overlapping. In an extreme case, a cell may be totally enclosing another one. I do not know how such arrangements are possible.
All the cells must be connected, since crew members should be able to walk from any cell to any other cell. They can walk from a cell A to another cell B, if, (1) A and B are touching each other or overlapping, (2) A and B are connected by a `corridor', or (3) there is a cell C such that walking from A to C, and also from B to C are both possible. Note that the condition (3) should be interpreted transitively.
You are expected to design a configuration, namely, which pairs of cells are to be connected with corridors. There is some freedom in the corridor configuration. For example, if there are three cells A, B and C, not touching nor overlapping each other, at least three plans are possible in order to connect all three cells. The first is to build corridors A-B and A-C, the second B-C and B-A, the third C-A and C-B. The cost of building a corridor is proportional to its length. Therefore, you should choose a plan with the shortest total length of the corridors.
You can ignore the width of a corridor. A corridor is built between points on two cells' surfaces. It can be made arbitrarily long, but of course the shortest one is chosen. Even if two corridors A-B and C-D intersect in space, they are not considered to form a connection path between (for example) A and C. In other words, you may consider that two corridors never intersect.
Input
The input consists of multiple data sets. Each data set is given in the following format.
> n
> x1 y1 z1 r1
> x2 y2 z2 r2
> ...
> xn yn zn rn
>
The first line of a data set contains an integer n, which is the number of cells. n is positive, and does not exceed 100.
The following n lines are descriptions of cells. Four values in a line are x-, y- and z-coordinates of the center, and radius (called r in the rest of the problem) of the sphere, in this order. Each value is given by a decimal fraction, with 3 digits after the decimal point. Values are separated by a space character.
Each of x, y, z and r is positive and is less than 100.0.
The end of the input is indicated by a line containing a zero.
Output
For each data set, the shortest total length of the corridors should be printed, each in a separate line. The printed values should have 3 digits after the decimal point. They may not have an error greater than 0.001.
Note that if no corridors are necessary, that is, if all the cells are connected without corridors, the shortest total length of the corridors is 0.000.
Example
Input
3
10.000 10.000 50.000 10.000
40.000 10.000 50.000 10.000
40.000 40.000 50.000 10.000
2
30.000 30.000 30.000 20.000
40.000 40.000 40.000 20.000
5
5.729 15.143 3.996 25.837
6.013 14.372 4.818 10.671
80.115 63.292 84.477 15.120
64.095 80.924 70.029 14.881
39.472 85.116 71.369 5.553
0
Output
20.000
0.000
73.834
Submitted Solution:
```
from math import sqrt
import heapq
# -*- coding: utf-8 *-
# python template for atcoder1
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
class UnionFind:
"""
sizeによる実装
"""
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)
def calc_dist(s1, s2):
dist = sqrt(sum([abs(a-b)**2 for a, b in zip(s1[:-1], s2[:-1])]))
return max(dist-s1[3] - s2[3], 0)
def solve():
N = int(input())
if N == 0:
exit()
spheres = [list(map(float, input().split())) for _ in range(N)]
dists = []
Un = UnionFind(N)
for i in range(N):
for j in range(i+1, N):
tmp = calc_dist(spheres[i], spheres[j])
#dists.append([tmp, i, j])
heapq.heappush(dists, [tmp, i, j])
cost = 0
#dists = sorted(dists, key=lambda x: x[0])
for k in range(len(dists)):
dist, i, j = heapq.heappop(dists)
if Un.same(i, j):
continue
else:
Un.union(i, j)
cost += dist
print("{:.3f}".format(cost))
while True:
solve()
``` | instruction | 0 | 67,187 | 3 | 134,374 |
Yes | output | 1 | 67,187 | 3 | 134,375 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are a member of the space station engineering team, and are assigned a task in the construction process of the station. You are expected to write a computer program to complete the task.
The space station is made up with a number of units, called cells. All cells are sphere-shaped, but their sizes are not necessarily uniform. Each cell is fixed at its predetermined position shortly after the station is successfully put into its orbit. It is quite strange that two cells may be touching each other, or even may be overlapping. In an extreme case, a cell may be totally enclosing another one. I do not know how such arrangements are possible.
All the cells must be connected, since crew members should be able to walk from any cell to any other cell. They can walk from a cell A to another cell B, if, (1) A and B are touching each other or overlapping, (2) A and B are connected by a `corridor', or (3) there is a cell C such that walking from A to C, and also from B to C are both possible. Note that the condition (3) should be interpreted transitively.
You are expected to design a configuration, namely, which pairs of cells are to be connected with corridors. There is some freedom in the corridor configuration. For example, if there are three cells A, B and C, not touching nor overlapping each other, at least three plans are possible in order to connect all three cells. The first is to build corridors A-B and A-C, the second B-C and B-A, the third C-A and C-B. The cost of building a corridor is proportional to its length. Therefore, you should choose a plan with the shortest total length of the corridors.
You can ignore the width of a corridor. A corridor is built between points on two cells' surfaces. It can be made arbitrarily long, but of course the shortest one is chosen. Even if two corridors A-B and C-D intersect in space, they are not considered to form a connection path between (for example) A and C. In other words, you may consider that two corridors never intersect.
Input
The input consists of multiple data sets. Each data set is given in the following format.
> n
> x1 y1 z1 r1
> x2 y2 z2 r2
> ...
> xn yn zn rn
>
The first line of a data set contains an integer n, which is the number of cells. n is positive, and does not exceed 100.
The following n lines are descriptions of cells. Four values in a line are x-, y- and z-coordinates of the center, and radius (called r in the rest of the problem) of the sphere, in this order. Each value is given by a decimal fraction, with 3 digits after the decimal point. Values are separated by a space character.
Each of x, y, z and r is positive and is less than 100.0.
The end of the input is indicated by a line containing a zero.
Output
For each data set, the shortest total length of the corridors should be printed, each in a separate line. The printed values should have 3 digits after the decimal point. They may not have an error greater than 0.001.
Note that if no corridors are necessary, that is, if all the cells are connected without corridors, the shortest total length of the corridors is 0.000.
Example
Input
3
10.000 10.000 50.000 10.000
40.000 10.000 50.000 10.000
40.000 40.000 50.000 10.000
2
30.000 30.000 30.000 20.000
40.000 40.000 40.000 20.000
5
5.729 15.143 3.996 25.837
6.013 14.372 4.818 10.671
80.115 63.292 84.477 15.120
64.095 80.924 70.029 14.881
39.472 85.116 71.369 5.553
0
Output
20.000
0.000
73.834
Submitted Solution:
```
# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1127&lang=en
from math import sqrt
from heapq import heappush, heappop
from collections import defaultdict
class UnionFind(object):
def __init__(self, n):
self.n = n
self.par = [-1] * n
def find(self, x):
if self.par[x] < 0:
return x
else:
self.par[x] = self.find(self.par[x])
return self.par[x]
def unite(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return False
else:
if self.par[x] > self.par[y]:
x, y = y, x
self.par[x] += self.par[y]
self.par[y] = x
return True
def same(self, x, y):
return self.find(x) == self.find(y)
def size(self, x):
return -self.par[self.find(x)]
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.par) if x < 0]
def group_count(self):
return len(self.roots())
while True:
N = int(input())
if N == 0:
break
X, Y, Z, R = [], [], [], []
for _ in range(N):
xi, yi, zi, ri = map(float, input().split())
X.append(xi)
Y.append(yi)
Z.append(zi)
R.append(ri)
# グラフ構造を作成?
# 短いやつをつなげていって,森じゃなくなったらOKかな?
uf = UnionFind(N)
cost = 0.0
edges = []
for i in range(N):
for j in range(i + 1, N):
dx = X[i] - X[j]
dy = Y[i] - Y[j]
dz = Z[i] - Z[j]
dij = sqrt(dx * dx + dy * dy + dz * dz) - R[i] - R[j]
heappush(edges, (dij, i, j))
# Kruskal
while len(edges) > 0:
(w, u, v) = heappop(edges)
if uf.unite(u, v):
if w > 0:
cost += w
print("{:.3f}".format(cost))
``` | instruction | 0 | 67,188 | 3 | 134,376 |
Yes | output | 1 | 67,188 | 3 | 134,377 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are a member of the space station engineering team, and are assigned a task in the construction process of the station. You are expected to write a computer program to complete the task.
The space station is made up with a number of units, called cells. All cells are sphere-shaped, but their sizes are not necessarily uniform. Each cell is fixed at its predetermined position shortly after the station is successfully put into its orbit. It is quite strange that two cells may be touching each other, or even may be overlapping. In an extreme case, a cell may be totally enclosing another one. I do not know how such arrangements are possible.
All the cells must be connected, since crew members should be able to walk from any cell to any other cell. They can walk from a cell A to another cell B, if, (1) A and B are touching each other or overlapping, (2) A and B are connected by a `corridor', or (3) there is a cell C such that walking from A to C, and also from B to C are both possible. Note that the condition (3) should be interpreted transitively.
You are expected to design a configuration, namely, which pairs of cells are to be connected with corridors. There is some freedom in the corridor configuration. For example, if there are three cells A, B and C, not touching nor overlapping each other, at least three plans are possible in order to connect all three cells. The first is to build corridors A-B and A-C, the second B-C and B-A, the third C-A and C-B. The cost of building a corridor is proportional to its length. Therefore, you should choose a plan with the shortest total length of the corridors.
You can ignore the width of a corridor. A corridor is built between points on two cells' surfaces. It can be made arbitrarily long, but of course the shortest one is chosen. Even if two corridors A-B and C-D intersect in space, they are not considered to form a connection path between (for example) A and C. In other words, you may consider that two corridors never intersect.
Input
The input consists of multiple data sets. Each data set is given in the following format.
> n
> x1 y1 z1 r1
> x2 y2 z2 r2
> ...
> xn yn zn rn
>
The first line of a data set contains an integer n, which is the number of cells. n is positive, and does not exceed 100.
The following n lines are descriptions of cells. Four values in a line are x-, y- and z-coordinates of the center, and radius (called r in the rest of the problem) of the sphere, in this order. Each value is given by a decimal fraction, with 3 digits after the decimal point. Values are separated by a space character.
Each of x, y, z and r is positive and is less than 100.0.
The end of the input is indicated by a line containing a zero.
Output
For each data set, the shortest total length of the corridors should be printed, each in a separate line. The printed values should have 3 digits after the decimal point. They may not have an error greater than 0.001.
Note that if no corridors are necessary, that is, if all the cells are connected without corridors, the shortest total length of the corridors is 0.000.
Example
Input
3
10.000 10.000 50.000 10.000
40.000 10.000 50.000 10.000
40.000 40.000 50.000 10.000
2
30.000 30.000 30.000 20.000
40.000 40.000 40.000 20.000
5
5.729 15.143 3.996 25.837
6.013 14.372 4.818 10.671
80.115 63.292 84.477 15.120
64.095 80.924 70.029 14.881
39.472 85.116 71.369 5.553
0
Output
20.000
0.000
73.834
Submitted Solution:
```
import sys
sys.setrecursionlimit(100000)
class UnionFind:
def __init__(self, n):
super().__init__()
self.par = [i for i in range(n + 1)]
self.rank = [0 for i in range(n + 1)]
def root(self, x):
if self.par[x] == x:
return x
else:
return self.root(self.par[x])
def is_same(self, x, y):
return self.root(x) == self.root(y)
def unite(self, x, y):
x = self.root(x)
y = self.root(y)
if x != y:
if self.rank[x] < self.rank[y]:
self.par[x] = y
elif self.rank[x] > self.rank[y]:
self.par[y] = x
else:
self.par[x] = y
self.rank[y] += 1
def distance(cell1, cell2):
c_dis = 0
for i in range(3):
c_dis += (cell1[i] - cell2[i])**2
c_dis = c_dis**(1 / 2) - (cell1[3] + cell2[3])
return c_dis if c_dis > 0 else 0
while True:
n = int(input())
if n == 0:
break
union = UnionFind(n)
cell_list = [list(map(float, input().split())) for i in range(n)]
distance_list = []
for i, b_cell in enumerate(cell_list):
for j, cell in enumerate(cell_list[i + 1:]):
distance_list.append([distance(b_cell, cell), i, i + 1 + j])
distance_list.sort()
total_dis = 0
for dis in distance_list:
if not union.is_same(dis[1], dis[2]):
union.unite(dis[1], dis[2])
total_dis += dis[0]
print(format(total_dis, ".3f"))
``` | instruction | 0 | 67,189 | 3 | 134,378 |
Yes | output | 1 | 67,189 | 3 | 134,379 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.