text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are A slimes lining up in a row. Initially, the sizes of the slimes are all 1.
Snuke can repeatedly perform the following operation.
* Choose a positive even number M. Then, select M consecutive slimes and form M / 2 pairs from those slimes as follows: pair the 1-st and 2-nd of them from the left, the 3-rd and 4-th of them, ..., the (M-1)-th and M-th of them. Combine each pair of slimes into one larger slime. Here, the size of a combined slime is the sum of the individual slimes before combination. The order of the M / 2 combined slimes remain the same as the M / 2 pairs of slimes before combination.
Snuke wants to get to the situation where there are exactly N slimes, and the size of the i-th (1 β€ i β€ N) slime from the left is a_i. Find the minimum number of operations required to achieve his goal.
Note that A is not directly given as input. Assume A = a_1 + a_2 + ... + a_N.
Constraints
* 1 β€ N β€ 10^5
* a_i is an integer.
* 1 β€ a_i β€ 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the minimum number of operations required to achieve Snuke's goal.
Examples
Input
2
3 3
Output
2
Input
4
2 1 2 2
Output
2
Input
1
1
Output
0
Input
10
3 1 4 1 5 9 2 6 5 3
Output
10
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
counter = 0
current = 0
uneven = 0
unevenOld = 0
while current < len(a):
unevenOld = uneven
uneven = 0
while a[current] > 1:
nex = current + 1
uneven = 0
while nex < n and uneven < 1:
if a[nex] % 2 == 1:
uneven = 1
if a[nex] == 1:
break
a[nex] = (a[nex] + 1) // 2
nex += 1
if a[current] % 2 == 0:
if unevenOld > 0:
unevenOld -= 1
counter -= 1
else:
uneven += 1
a[current] = (a[current]+1) // 2
counter += 1
#print(" ".join(list(map(str, a))))
current += 1
print(counter)
```
No
| 102,800 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Input Format
The input format is following:
n m q
a_1 a_2 ... a_q
Output Format
Print the number of connected part in one line.
Constraints
* n β€ 10^{12}
* 7n is divisible by m.
* 1 β€ q β€ m β€ 10^5
* 0 β€ a_1 < a_2 < ... < a_q < m
Scoring
Subtask 1 [100 points]
* n β€ 100000.
Subtask 2 [90 points]
* m is divisible by 7.
* a_{i + 1} - a_i = 1.
Subtask 3 [200 points]
* m is divisible by 7.
Subtask 4 [110 points]
* There are no additional constraints.
Sample Input 1
7 7 3
1 3 5
Sample Output 1
4
The calendar looks like this:
<image>
Sample Input 2
10 14 8
5 6 7 8 9 10 11 12
Sample Output 2
10
The calendar looks like this:
<image>
Output Format
Print the number of connected part in one line.
Constraints
* n β€ 10^{12}
* 7n is divisible by m.
* 1 β€ q β€ m β€ 10^5
* 0 β€ a_1 < a_2 < ... < a_q < m
Scoring
Subtask 1 [100 points]
* n β€ 100000.
Subtask 2 [90 points]
* m is divisible by 7.
* a_{i + 1} - a_i = 1.
Subtask 3 [200 points]
* m is divisible by 7.
Subtask 4 [110 points]
* There are no additional constraints.
Input Format
The input format is following:
n m q
a_1 a_2 ... a_q
Examples
Input
7 7 3
1 3 5
Output
4
Input
10 14 8
5 6 7 8 9 10 11 12
Output
10
Submitted Solution:
```
from queue import Queue
n,m,q=map(int,input().split())
a=list(map(int,input().split()))
def count_group(size):
cc = [False]*size
for i in range(q):
j = 0
while a[i]+m*j < size:
cc[a[i]+m*j] = True
j += 1
gg = [0]*size
ox = [-1, 0, 1, 0]
oy = [0, -7, 0, 7]
def bfs(i, g):
qq = Queue()
qq.put(i, False)
while not qq.empty():
ii = qq.get(False)
gg[ii] = g
for t in range(4):
if ii % 7 == 0 and ox[t] == -1: continue
if (ii+1) % 7 == 0 and ox[t] == 1: continue
j = ii+ox[t]+oy[t]
if 0 <= j < size:
if cc[j] or gg[j] != 0: continue
qq.put(j, False)
maxg = 0
for i in range(size):
if not cc[i] and gg[i] == 0:
maxg += 1
bfs(i, maxg)
return maxg
block = (m+7)//7*7*7
if n*7 <= block:
print(count_group(n*7))
exit(0)
c1 = count_group(block)
c2 = count_group(block*2)
c3 = count_group(block+((n*7)%block))
print(c1 + ((n*7-block)//block)*(c2-c1) + (c3-c1))
```
No
| 102,801 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Input Format
The input format is following:
n m q
a_1 a_2 ... a_q
Output Format
Print the number of connected part in one line.
Constraints
* n β€ 10^{12}
* 7n is divisible by m.
* 1 β€ q β€ m β€ 10^5
* 0 β€ a_1 < a_2 < ... < a_q < m
Scoring
Subtask 1 [100 points]
* n β€ 100000.
Subtask 2 [90 points]
* m is divisible by 7.
* a_{i + 1} - a_i = 1.
Subtask 3 [200 points]
* m is divisible by 7.
Subtask 4 [110 points]
* There are no additional constraints.
Sample Input 1
7 7 3
1 3 5
Sample Output 1
4
The calendar looks like this:
<image>
Sample Input 2
10 14 8
5 6 7 8 9 10 11 12
Sample Output 2
10
The calendar looks like this:
<image>
Output Format
Print the number of connected part in one line.
Constraints
* n β€ 10^{12}
* 7n is divisible by m.
* 1 β€ q β€ m β€ 10^5
* 0 β€ a_1 < a_2 < ... < a_q < m
Scoring
Subtask 1 [100 points]
* n β€ 100000.
Subtask 2 [90 points]
* m is divisible by 7.
* a_{i + 1} - a_i = 1.
Subtask 3 [200 points]
* m is divisible by 7.
Subtask 4 [110 points]
* There are no additional constraints.
Input Format
The input format is following:
n m q
a_1 a_2 ... a_q
Examples
Input
7 7 3
1 3 5
Output
4
Input
10 14 8
5 6 7 8 9 10 11 12
Output
10
Submitted Solution:
```
n,m,q=map(int,input().split())
a=list(map(int,input().split()))
def count_group(size):
cc = [False]*size
for i in range(q):
j = 0
while a[i]+m*j < size:
cc[a[i]+m*j] = True
j += 1
gg = [0]*size
ox = [-1, 0, 1, 0]
oy = [0, -7, 0, 7]
def dfs(i, g):
if cc[i] or gg[i] != 0: return
gg[i] = g
for t in range(4):
if i % 7 == 0 and ox[t] == -1: continue
if (i+1) % 7 == 0 and ox[t] == 1: continue
j = i+ox[t]+oy[t]
if 0 <= j < size:
dfs(j, g)
maxg = 0
for i in range(size):
if not cc[i] and gg[i] == 0:
maxg += 1
dfs(i, maxg)
return maxg
block = (m+7)//7*7*7
if n <= block:
print(count_group(n*7))
exit(0)
c1 = count_group(block)
c2 = count_group(block*2)
c3 = count_group(block+((n*7)%block))
print(c1 + ((n*7-block)//block)*(c2-c1) + (c3-c1))
```
No
| 102,802 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which replace all the lower-case letters of a given text with the corresponding captital letters.
Input
A text including lower-case letters, periods, and space is given in a line. The number of characters in the text is less than or equal to 200.
Output
Print the converted text.
Example
Input
this is a pen.
Output
THIS IS A PEN.
"Correct Solution:
```
str=input()
print(str.upper())
```
| 102,803 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which replace all the lower-case letters of a given text with the corresponding captital letters.
Input
A text including lower-case letters, periods, and space is given in a line. The number of characters in the text is less than or equal to 200.
Output
Print the converted text.
Example
Input
this is a pen.
Output
THIS IS A PEN.
"Correct Solution:
```
print(''.join(list(map(lambda i: i.upper(),input()))))
```
| 102,804 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which replace all the lower-case letters of a given text with the corresponding captital letters.
Input
A text including lower-case letters, periods, and space is given in a line. The number of characters in the text is less than or equal to 200.
Output
Print the converted text.
Example
Input
this is a pen.
Output
THIS IS A PEN.
"Correct Solution:
```
from functools import reduce
from operator import add
print(reduce(add, map(str.capitalize, input()[:]), ''))
```
| 102,805 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which replace all the lower-case letters of a given text with the corresponding captital letters.
Input
A text including lower-case letters, periods, and space is given in a line. The number of characters in the text is less than or equal to 200.
Output
Print the converted text.
Example
Input
this is a pen.
Output
THIS IS A PEN.
"Correct Solution:
```
import math
def run():
text = input().strip()
print(text.upper())
if __name__ == '__main__':
run()
```
| 102,806 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which replace all the lower-case letters of a given text with the corresponding captital letters.
Input
A text including lower-case letters, periods, and space is given in a line. The number of characters in the text is less than or equal to 200.
Output
Print the converted text.
Example
Input
this is a pen.
Output
THIS IS A PEN.
"Correct Solution:
```
a=input()
a=str.upper(a)
print(a)
```
| 102,807 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which replace all the lower-case letters of a given text with the corresponding captital letters.
Input
A text including lower-case letters, periods, and space is given in a line. The number of characters in the text is less than or equal to 200.
Output
Print the converted text.
Example
Input
this is a pen.
Output
THIS IS A PEN.
"Correct Solution:
```
l = str(input())
print(str.upper(l))
```
| 102,808 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which replace all the lower-case letters of a given text with the corresponding captital letters.
Input
A text including lower-case letters, periods, and space is given in a line. The number of characters in the text is less than or equal to 200.
Output
Print the converted text.
Example
Input
this is a pen.
Output
THIS IS A PEN.
"Correct Solution:
```
a=str(input())
b=str.upper(a)
print(b)
```
| 102,809 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which replace all the lower-case letters of a given text with the corresponding captital letters.
Input
A text including lower-case letters, periods, and space is given in a line. The number of characters in the text is less than or equal to 200.
Output
Print the converted text.
Example
Input
this is a pen.
Output
THIS IS A PEN.
"Correct Solution:
```
A=input()
print(A.upper())
```
| 102,810 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which replace all the lower-case letters of a given text with the corresponding captital letters.
Input
A text including lower-case letters, periods, and space is given in a line. The number of characters in the text is less than or equal to 200.
Output
Print the converted text.
Example
Input
this is a pen.
Output
THIS IS A PEN.
Submitted Solution:
```
L = list(input())
LL = []
for i in L:
LL.append(i.upper())
print( "".join(LL) )
```
Yes
| 102,811 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which replace all the lower-case letters of a given text with the corresponding captital letters.
Input
A text including lower-case letters, periods, and space is given in a line. The number of characters in the text is less than or equal to 200.
Output
Print the converted text.
Example
Input
this is a pen.
Output
THIS IS A PEN.
Submitted Solution:
```
import sys
a = 'abcdefghijklmnopqrstuvwxyz'
b = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for s in sys.stdin:
t= s[:-1].translate(str.maketrans(a,b))
print(t)
```
Yes
| 102,812 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which replace all the lower-case letters of a given text with the corresponding captital letters.
Input
A text including lower-case letters, periods, and space is given in a line. The number of characters in the text is less than or equal to 200.
Output
Print the converted text.
Example
Input
this is a pen.
Output
THIS IS A PEN.
Submitted Solution:
```
strings = input()
print(strings.upper())
```
Yes
| 102,813 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which replace all the lower-case letters of a given text with the corresponding captital letters.
Input
A text including lower-case letters, periods, and space is given in a line. The number of characters in the text is less than or equal to 200.
Output
Print the converted text.
Example
Input
this is a pen.
Output
THIS IS A PEN.
Submitted Solution:
```
s = str(input())
print(s.upper())
```
Yes
| 102,814 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which replace all the lower-case letters of a given text with the corresponding captital letters.
Input
A text including lower-case letters, periods, and space is given in a line. The number of characters in the text is less than or equal to 200.
Output
Print the converted text.
Example
Input
this is a pen.
Output
THIS IS A PEN.
Submitted Solution:
```
print(' '.join(list(map(lambda i: i.upper(),input().split()))))
```
No
| 102,815 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which replace all the lower-case letters of a given text with the corresponding captital letters.
Input
A text including lower-case letters, periods, and space is given in a line. The number of characters in the text is less than or equal to 200.
Output
Print the converted text.
Example
Input
this is a pen.
Output
THIS IS A PEN.
Submitted Solution:
```
# coding=utf-8
sentence = input()
sentence.upper()
print(sentence)
```
No
| 102,816 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which replace all the lower-case letters of a given text with the corresponding captital letters.
Input
A text including lower-case letters, periods, and space is given in a line. The number of characters in the text is less than or equal to 200.
Output
Print the converted text.
Example
Input
this is a pen.
Output
THIS IS A PEN.
Submitted Solution:
```
def Capitalize():
for i in sys.stdin:
print(i.upper())
```
No
| 102,817 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which replace all the lower-case letters of a given text with the corresponding captital letters.
Input
A text including lower-case letters, periods, and space is given in a line. The number of characters in the text is less than or equal to 200.
Output
Print the converted text.
Example
Input
this is a pen.
Output
THIS IS A PEN.
Submitted Solution:
```
# -*- coding: utf-8 -*-
def main(_text: str):
print(_text.upper(), end='')
while True:
try:
text = input()
except:
break
main(text)
```
No
| 102,818 |
Provide a correct Python 3 solution for this coding contest problem.
There is a n Γ n grid D where each cell contains either 1 or 0.
Your task is to create a program that takes the gird data as input and computes the greatest number of consecutive 1s in either vertical, horizontal, or diagonal direction.
For example, the consecutive 1s with greatest number in the figure below is circled by the dashed-line.
<image>
The size of the grid n is an integer where 2 β€ n β€ 255.
Input
The input is a sequence of datasets. The end of the input is indicated by a line containing one zero. Each dataset is formatted as follows:
n
D11 D12 ... D1n
D21 D22 ... D2n
.
.
Dn1 Dn2 ... Dnn
Output
For each dataset, print the greatest number of consecutive 1s.
Example
Input
5
00011
00101
01000
10101
00010
8
11000001
10110111
01100111
01111010
11111111
01011010
10100010
10000001
2
01
00
3
000
000
000
0
Output
4
8
1
0
"Correct Solution:
```
while 1:
n = int(input())
if n == 0:
break
L = [input() for i in range(n)]
ans = 0
for i in range(n):
cnt = 0
for j in range(n):
if L[i][j] == '1':
cnt += 1
else:
if ans < cnt:
ans = cnt
cnt = 0
if ans < cnt:
ans = cnt
cnt = 0
for j in range(n):
if L[j][i] == '1':
cnt += 1
else:
if ans < cnt:
ans = cnt
cnt = 0
if ans < cnt:
ans = cnt
for i in range(n):
cnt = 0
for j in range(n-i):
if L[i+j][j] == '1':
cnt += 1
else:
if ans < cnt:
ans = cnt
cnt = 0
if ans < cnt:
ans = cnt
cnt = 0
for j in range(n-i):
if L[j][i+j] == '1':
cnt += 1
else:
if ans < cnt:
ans = cnt
cnt = 0
if ans < cnt:
ans = cnt
cnt = 0
for j in range(i+1):
if L[i-j][j] == '1':
cnt += 1
else:
if ans < cnt:
ans = cnt
cnt = 0
if ans < cnt:
ans = cnt
cnt = 0
for j in range(n-i):
if L[i+j][n-1-j] == '1':
cnt += 1
else:
if ans < cnt:
ans = cnt
cnt = 0
if ans < cnt:
ans = cnt
print(ans)
```
| 102,819 |
Provide a correct Python 3 solution for this coding contest problem.
There is a n Γ n grid D where each cell contains either 1 or 0.
Your task is to create a program that takes the gird data as input and computes the greatest number of consecutive 1s in either vertical, horizontal, or diagonal direction.
For example, the consecutive 1s with greatest number in the figure below is circled by the dashed-line.
<image>
The size of the grid n is an integer where 2 β€ n β€ 255.
Input
The input is a sequence of datasets. The end of the input is indicated by a line containing one zero. Each dataset is formatted as follows:
n
D11 D12 ... D1n
D21 D22 ... D2n
.
.
Dn1 Dn2 ... Dnn
Output
For each dataset, print the greatest number of consecutive 1s.
Example
Input
5
00011
00101
01000
10101
00010
8
11000001
10110111
01100111
01111010
11111111
01011010
10100010
10000001
2
01
00
3
000
000
000
0
Output
4
8
1
0
"Correct Solution:
```
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0151&lang=jp
"""
import sys
from sys import stdin
input = stdin.readline
def main(args):
while True:
n = int(input())
if n == 0:
break
data = [list(map(int, list(input().strip('\n')))) for _ in range(n)]
# ???(North)??????(West)?????????(NorthWest)?????????(NorthEast) ????????????????????????1???????????Β£?ΒΆ???????????????????????????????
N = [[0] * n for _ in range(n)]
W = [[0] * n for _ in range(n)]
NW = [[0] * n for _ in range(n)]
NE = [[0] * n for _ in range(n)]
N_max = 0 # ???????????????????????Β§?????Β£?ΒΆ???????1????????Β§?????Β°
W_max = 0
NW_max = 0
NE_max = 0
for i in range(n):
for j in range(n):
c = data[i][j] # ????????????data[i][j]?????????????????Β§???????????Β§?????????????Β¨???ΒΆ
# North??????
ni = i - 1
if ni < 0:
N[i][j] = c
if N[i][j] > N_max:
N_max = N[i][j]
else:
if c == 1:
N[i][j] = N[ni][j] + 1
if N[i][j] > N_max:
N_max = N[i][j]
else:
N[i][j] = 0
# West??????
nj = j - 1
if nj < 0:
W[i][j] = c
if W[i][j] > W_max:
W_max = W[i][j]
else:
if c == 1:
W[i][j] = W[i][nj] + 1
if W[i][j] > W_max:
W_max = W[i][j]
else:
W[i][j] = 0
# North West??????
ni = i - 1
nj = j - 1
if ni < 0 or nj < 0:
NW[i][j] = c
if NW[i][j] > NW_max:
NW_max = NW[i][j]
else:
if c == 1:
NW[i][j] = NW[ni][nj] + 1
if NW[i][j] > NW_max:
NW_max = NW[i][j]
else:
NW[i][j] = 0
# North East??????
ni = i - 1
nj = j + 1
if ni < 0 or nj >= n:
NE[i][j] = c
if NE[i][j] > NE_max:
NE_max = NE[i][j]
else:
if c == 1:
NE[i][j] = NE[ni][nj] + 1
if NE[i][j] > NE_max:
NE_max = NE[i][j]
else:
NE[i][j] = 0
print(max(N_max, W_max, NW_max, NE_max))
if __name__ == '__main__':
main(sys.argv[1:])
```
| 102,820 |
Provide a correct Python 3 solution for this coding contest problem.
There is a n Γ n grid D where each cell contains either 1 or 0.
Your task is to create a program that takes the gird data as input and computes the greatest number of consecutive 1s in either vertical, horizontal, or diagonal direction.
For example, the consecutive 1s with greatest number in the figure below is circled by the dashed-line.
<image>
The size of the grid n is an integer where 2 β€ n β€ 255.
Input
The input is a sequence of datasets. The end of the input is indicated by a line containing one zero. Each dataset is formatted as follows:
n
D11 D12 ... D1n
D21 D22 ... D2n
.
.
Dn1 Dn2 ... Dnn
Output
For each dataset, print the greatest number of consecutive 1s.
Example
Input
5
00011
00101
01000
10101
00010
8
11000001
10110111
01100111
01111010
11111111
01011010
10100010
10000001
2
01
00
3
000
000
000
0
Output
4
8
1
0
"Correct Solution:
```
def scanning_area(grid, length, point_list, stride_x, stride_y):
area = [[0 for _ in range(length + 1)] for __ in range(length + 1)]
max_length = 0
for row, col in point_list:
if grid[row][col] == "1":
area[row + stride_y][col + stride_x] = area[row][col] + 1
max_length = max(max_length, area[row + stride_y][col + stride_x])
return max_length
def create_point_list(length):
points = []
for count, r in enumerate(range(length - 1, 0, -1), 1):
row = r
for col in range(0, count, 1):
points.append((row, col))
row += 1
for index in range(0, length):
points.append((index, index))
for lp in range(1, length):
row = 0
for col in range(lp, length):
points.append((row, col))
row += 1
return points
while True:
length = int(input())
if length == 0:
break
grid = [input() for _ in range(length)]
point_list = [[row, col] for row in range(length) for col in range(length)]
line_length1 = scanning_area(grid, length, point_list, 1, 0)
line_length2 = scanning_area(grid, length, point_list, 0, 1)
point_list = create_point_list(length)
line_length3 = scanning_area(grid, length, point_list, 1, 1)
point_list.reverse()
line_length4 = scanning_area(grid, length, point_list, -1, 1)
max_length = max(line_length1, line_length2, line_length3, line_length4)
print(max_length)
```
| 102,821 |
Provide a correct Python 3 solution for this coding contest problem.
There is a n Γ n grid D where each cell contains either 1 or 0.
Your task is to create a program that takes the gird data as input and computes the greatest number of consecutive 1s in either vertical, horizontal, or diagonal direction.
For example, the consecutive 1s with greatest number in the figure below is circled by the dashed-line.
<image>
The size of the grid n is an integer where 2 β€ n β€ 255.
Input
The input is a sequence of datasets. The end of the input is indicated by a line containing one zero. Each dataset is formatted as follows:
n
D11 D12 ... D1n
D21 D22 ... D2n
.
.
Dn1 Dn2 ... Dnn
Output
For each dataset, print the greatest number of consecutive 1s.
Example
Input
5
00011
00101
01000
10101
00010
8
11000001
10110111
01100111
01111010
11111111
01011010
10100010
10000001
2
01
00
3
000
000
000
0
Output
4
8
1
0
"Correct Solution:
```
# coding: utf-8
# Your code here!
while True:
n = int(input())
if n == 0:
break
table = [[0 for i in range(n)] for j in range(n)]
for l in range(n):
line = input()
for m in range(n):
table[l][m] = int(line[m])
t = 0
ans = 0
for i in range(n):
for j in range(n):
if table[i][j] > 0:
t += 1
else:
ans = max(t, ans)
t = 0
ans = max(t, ans)
t = 0
for i in range(n):
for j in range(n):
if table[j][i] > 0:
t += 1
else:
ans = max(t, ans)
t = 0
ans = max(t, ans)
t = 0
for c in range(n):
for j in range(c+1):
if table[c-j][j] > 0:
t += 1
else:
ans = max(t, ans)
t = 0
ans = max(t, ans)
t = 0
for c in range(n):
for j in range(c+1):
if table[n-1-(c-j)][n-1-j] > 0:
t += 1
else:
ans = max(t, ans)
t = 0
ans = max(t, ans)
t = 0
for c in range(n):
for j in range(c+1):
if table[n-1-(c-j)][j] > 0:
t += 1
else:
ans = max(t, ans)
t = 0
ans = max(t, ans)
t = 0
for c in range(n):
for j in range(c+1):
if table[c-j][n-1-j] > 0:
t += 1
else:
ans = max(t, ans)
t = 0
ans = max(t, ans)
t = 0
print(ans)
```
| 102,822 |
Provide a correct Python 3 solution for this coding contest problem.
There is a n Γ n grid D where each cell contains either 1 or 0.
Your task is to create a program that takes the gird data as input and computes the greatest number of consecutive 1s in either vertical, horizontal, or diagonal direction.
For example, the consecutive 1s with greatest number in the figure below is circled by the dashed-line.
<image>
The size of the grid n is an integer where 2 β€ n β€ 255.
Input
The input is a sequence of datasets. The end of the input is indicated by a line containing one zero. Each dataset is formatted as follows:
n
D11 D12 ... D1n
D21 D22 ... D2n
.
.
Dn1 Dn2 ... Dnn
Output
For each dataset, print the greatest number of consecutive 1s.
Example
Input
5
00011
00101
01000
10101
00010
8
11000001
10110111
01100111
01111010
11111111
01011010
10100010
10000001
2
01
00
3
000
000
000
0
Output
4
8
1
0
"Correct Solution:
```
# Aizu Problem 00151: Grid
#
import sys, math, os, bisect
# read input:
PYDEV = os.environ.get('PYDEV')
if PYDEV=="True":
sys.stdin = open("sample-input.txt", "rt")
def grid_length(n, grid):
L = 0
for row in grid:
L = max(L, max([len(_) for _ in row.split('0')]))
for c in range(n):
col = ''.join([grid[r][c] for r in range(n)])
L = max(L, max([len(_) for _ in col.split('0')]))
for row in range(-n, 2 * n):
diag = ''.join([grid[row+c][c] for c in range(n) if 0 <= row + c < n])
L = max(L, max([len(_) for _ in diag.split('0')]))
diag = ''.join([grid[row-c][c] for c in range(n) if 0 <= row - c < n])
L = max(L, max([len(_) for _ in diag.split('0')]))
return L
while True:
n = int(input())
if n == 0:
break
grid = [input().strip() for _ in range(n)]
print(grid_length(n, grid))
```
| 102,823 |
Provide a correct Python 3 solution for this coding contest problem.
There is a n Γ n grid D where each cell contains either 1 or 0.
Your task is to create a program that takes the gird data as input and computes the greatest number of consecutive 1s in either vertical, horizontal, or diagonal direction.
For example, the consecutive 1s with greatest number in the figure below is circled by the dashed-line.
<image>
The size of the grid n is an integer where 2 β€ n β€ 255.
Input
The input is a sequence of datasets. The end of the input is indicated by a line containing one zero. Each dataset is formatted as follows:
n
D11 D12 ... D1n
D21 D22 ... D2n
.
.
Dn1 Dn2 ... Dnn
Output
For each dataset, print the greatest number of consecutive 1s.
Example
Input
5
00011
00101
01000
10101
00010
8
11000001
10110111
01100111
01111010
11111111
01011010
10100010
10000001
2
01
00
3
000
000
000
0
Output
4
8
1
0
"Correct Solution:
```
def main():
while True:
n = int(input())
if n == 0:
break
mp = ["0" + input() + "0" for _ in range(n)]
mp.insert(0, "0" * (n + 2))
mp.append("0" * (n + 2))
score = [[[0] * 4 for _ in range(n + 2)] for _ in range(n + 2)]
max_score = 0
for i in range(1, n + 1):
for j in range(1, n + 1):
if mp[i][j] == "1":
score[i][j][0] = score[i - 1][j][0] + 1
score[i][j][1] = score[i][j - 1][1] + 1
score[i][j][2] = score[i - 1][j - 1][2] + 1
score[i][j][3] = score[i - 1][j + 1][3] + 1
max_score = max(max_score, score[i][j][0], score[i][j][1], score[i][j][2], score[i][j][3])
else:
for k in range(4):
score[i][j][k] = 0
print(max_score)
main()
```
| 102,824 |
Provide a correct Python 3 solution for this coding contest problem.
There is a n Γ n grid D where each cell contains either 1 or 0.
Your task is to create a program that takes the gird data as input and computes the greatest number of consecutive 1s in either vertical, horizontal, or diagonal direction.
For example, the consecutive 1s with greatest number in the figure below is circled by the dashed-line.
<image>
The size of the grid n is an integer where 2 β€ n β€ 255.
Input
The input is a sequence of datasets. The end of the input is indicated by a line containing one zero. Each dataset is formatted as follows:
n
D11 D12 ... D1n
D21 D22 ... D2n
.
.
Dn1 Dn2 ... Dnn
Output
For each dataset, print the greatest number of consecutive 1s.
Example
Input
5
00011
00101
01000
10101
00010
8
11000001
10110111
01100111
01111010
11111111
01011010
10100010
10000001
2
01
00
3
000
000
000
0
Output
4
8
1
0
"Correct Solution:
```
def main():
while True:
n = int(input())
if n == 0:
break
mp = ["0" + input() + "0" for _ in range(n)]
mp.insert(0, "0" * (n + 2))
mp.append("0" * (n + 2))
score = [[[0] * 4 for _ in range(n + 2)] for _ in range(n + 2)]
max_score = 0
for i in range(1, n + 1):
for j in range(1, n + 1):
if mp[i][j] == "1":
score[i][j][0] = score[i - 1][j][0] + 1
score[i][j][1] = score[i][j - 1][1] + 1
score[i][j][2] = score[i - 1][j - 1][2] + 1
score[i][j][3] = score[i - 1][j + 1][3] + 1
max_score = max(max_score, score[i][j][0], score[i][j][1], score[i][j][2], score[i][j][3])
print(max_score)
main()
```
| 102,825 |
Provide a correct Python 3 solution for this coding contest problem.
There is a n Γ n grid D where each cell contains either 1 or 0.
Your task is to create a program that takes the gird data as input and computes the greatest number of consecutive 1s in either vertical, horizontal, or diagonal direction.
For example, the consecutive 1s with greatest number in the figure below is circled by the dashed-line.
<image>
The size of the grid n is an integer where 2 β€ n β€ 255.
Input
The input is a sequence of datasets. The end of the input is indicated by a line containing one zero. Each dataset is formatted as follows:
n
D11 D12 ... D1n
D21 D22 ... D2n
.
.
Dn1 Dn2 ... Dnn
Output
For each dataset, print the greatest number of consecutive 1s.
Example
Input
5
00011
00101
01000
10101
00010
8
11000001
10110111
01100111
01111010
11111111
01011010
10100010
10000001
2
01
00
3
000
000
000
0
Output
4
8
1
0
"Correct Solution:
```
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0151&lang=jp
"""
import sys
from sys import stdin
input = stdin.readline
def main(args):
while True:
n = int(input())
if n == 0:
break
data = [list(map(int, list(input().strip('\n')))) for _ in range(n)]
if n == 1: # ????????????1?????????????????????
print(data[0][0])
continue
# ???(North)??????(West)?????????(NorthWest)?????????(NorthEast) ????????????????????????1???????????Β£?ΒΆ???????????????????????????????
N = [[0] * n for _ in range(n)]
W = [[0] * n for _ in range(n)]
NW = [[0] * n for _ in range(n)]
NE = [[0] * n for _ in range(n)]
N_max = 0 # ???????????????????????Β§?????Β£?ΒΆ???????1????????Β§?????Β°
W_max = 0
NW_max = 0
NE_max = 0
for i in range(n):
for j in range(n):
c = data[i][j] # ????????????data[i][j]?????????????????Β§???????????Β§?????????????Β¨???ΒΆ
# North??????
ni = i - 1
if ni < 0:
N[i][j] = c
if N[i][j] > N_max:
N_max = N[i][j]
else:
if c == 1:
N[i][j] = N[ni][j] + 1
if N[i][j] > N_max:
N_max = N[i][j]
else:
N[i][j] = 0
# West??????
nj = j - 1
if nj < 0:
W[i][j] = c
if W[i][j] > W_max:
W_max = W[i][j]
else:
if c == 1:
W[i][j] = W[i][nj] + 1
if W[i][j] > W_max:
W_max = W[i][j]
else:
W[i][j] = 0
# North West??????
ni = i - 1
nj = j - 1
if ni < 0 or nj < 0:
NW[i][j] = c
if NW[i][j] > NW_max:
NW_max = NW[i][j]
else:
if c == 1:
NW[i][j] = NW[ni][nj] + 1
if NW[i][j] > NW_max:
NW_max = NW[i][j]
else:
NW[i][j] = 0
# North East??????
ni = i - 1
nj = j + 1
if ni < 0 or nj >= n:
NE[i][j] = c
if NE[i][j] > NE_max:
NE_max = NE[i][j]
else:
if c == 1:
NE[i][j] = NE[ni][nj] + 1
if NE[i][j] > NE_max:
NE_max = NE[i][j]
else:
NE[i][j] = 0
print(max(N_max, W_max, NW_max, NE_max))
if __name__ == '__main__':
main(sys.argv[1:])
```
| 102,826 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a n Γ n grid D where each cell contains either 1 or 0.
Your task is to create a program that takes the gird data as input and computes the greatest number of consecutive 1s in either vertical, horizontal, or diagonal direction.
For example, the consecutive 1s with greatest number in the figure below is circled by the dashed-line.
<image>
The size of the grid n is an integer where 2 β€ n β€ 255.
Input
The input is a sequence of datasets. The end of the input is indicated by a line containing one zero. Each dataset is formatted as follows:
n
D11 D12 ... D1n
D21 D22 ... D2n
.
.
Dn1 Dn2 ... Dnn
Output
For each dataset, print the greatest number of consecutive 1s.
Example
Input
5
00011
00101
01000
10101
00010
8
11000001
10110111
01100111
01111010
11111111
01011010
10100010
10000001
2
01
00
3
000
000
000
0
Output
4
8
1
0
Submitted Solution:
```
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0151&lang=jp
"""
import sys
from sys import stdin
input = stdin.readline
def main(args):
while True:
n = int(input())
if n == 0:
break
data = [list(map(int, list(input().strip()))) for _ in range(n)]
# ???(North)??????(West)?????????(NorthWest)?????????(NorthEast) ????????????????????????1???????????Β£?ΒΆ???????????????????????????????
N = [[0] * n for _ in range(n)]
W = [[0] * n for _ in range(n)]
NW = [[0] * n for _ in range(n)]
NE = [[0] * n for _ in range(n)]
N_max = 0 # ???????????????????????Β§?????Β£?ΒΆ???????1????????Β§?????Β°
W_max = 0
NW_max = 0
NE_max = 0
for i in range(n):
for j in range(n):
c = data[i][j] # ????????????data[i][j]?????????????????Β§???????????Β§?????????????Β¨???ΒΆ
# North??????
ni = i - 1
if ni < 0:
N[i][j] = c
else:
if c == 1:
N[i][j] = N[ni][j] + 1
if N[i][j] > N_max:
N_max = N[i][j]
else:
N[i][j] = 0
# West??????
nj = j - 1
if nj < 0:
W[i][j] = c
else:
if c == 1:
W[i][j] = W[i][nj] + 1
if W[i][j] > W_max:
W_max = W[i][j]
else:
W[i][j] = 0
# North West??????
ni = i - 1
nj = j - 1
if ni < 0 or nj < 0:
NW[i][j] = c
else:
if c == 1:
NW[i][j] = NW[ni][nj] + 1
if NW[i][j] > NW_max:
NW_max = NW[i][j]
else:
NW[i][j] = 0
# North East??????
ni = i - 1
nj = j + 1
if ni < 0 or nj >= n:
NE[i][j] = c
else:
if c == 1:
NE[i][j] = NE[ni][nj] + 1
if NE[i][j] > NE_max:
NE_max = NE[i][j]
else:
NE[i][j] = 0
print(max(N_max, W_max, NW_max, NE_max))
if __name__ == '__main__':
main(sys.argv[1:])
```
No
| 102,827 |
Provide a correct Python 3 solution for this coding contest problem.
problem
You are a traveler traveling on the JOI Highway. The JOI Highway is a road that extends straight from east to west, and there are n post towns on the JOI Highway. Numbered. The westernmost post town on the JOI highway is post town 1, and the easternmost post town is post town n.
You have decided to depart from post town 1 and embark on an m-day journey. Your itinerary is determined according to the sequence a1, a2, ..., am as follows. It is a non-zero integer that represents how to move the eyes. If the post town you depart on day i is post town k, then on day i you move straight from post town k to post town k + ai. Means to do.
The number of post towns n, the number of days of travel m, the information on the distance between post towns, and the sequence a1, a2, ... Create a program that finds the remainder by dividing the sum by 100000 = 105.
Diagram corresponding to the input / output example
<image>
output
The output consists of one line containing the remainder of your total distance traveled in the m-day journey divided by 100000 = 105.
Input / output example
Input example 1
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output example 1
18
On the first day you move from post town 1 to post town 3. On the second day you move from post town 3 to post town 2. And on the third day you move from post town 2 to post town 5. Move, move from post town 5 to post town 7 on the 4th day, move from post town 7 to post town 4 on the 5th day. Your total travel distance in a 5-day trip is 18.
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
input
The integers n and m are separated by blanks on the first line. N (2 β€ n β€ 100000 = 105) is the number of post towns on the JOI highway, and m (1 β€ m β€ 100000 = 105) is Represents the number of days of travel.
The following n β 1 line represents the distance between post towns on the JOI highway. I + 1st line (1 β€ i β€ n β 1) is a positive integer si that represents the distance between post town i and post town i + 1. (1 β€ si β€ 100) is written.
The following m line contains a sequence of movements for m days. Line i + n (1 β€ i β€ m) contains a non-zero integer ai that represents your movement method for day i. Has been.
In the scoring data, it does not move west of post town 1 or east of post town n.
Of the scoring data, 50% of the points are satisfied with n β€ 100 and m β€ 100.
Example
Input
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output
18
"Correct Solution:
```
def solve():
n,m = map(int,input().split())
lst = [0]
for i in range(n - 1):
lst.append(lst[-1] + int(input()))
ans = 0
num = 0
for i in range(m):
a = int(input())
ans += abs(lst[num] - lst[num + a])
num += a
print(ans % 100000)
solve()
```
| 102,828 |
Provide a correct Python 3 solution for this coding contest problem.
problem
You are a traveler traveling on the JOI Highway. The JOI Highway is a road that extends straight from east to west, and there are n post towns on the JOI Highway. Numbered. The westernmost post town on the JOI highway is post town 1, and the easternmost post town is post town n.
You have decided to depart from post town 1 and embark on an m-day journey. Your itinerary is determined according to the sequence a1, a2, ..., am as follows. It is a non-zero integer that represents how to move the eyes. If the post town you depart on day i is post town k, then on day i you move straight from post town k to post town k + ai. Means to do.
The number of post towns n, the number of days of travel m, the information on the distance between post towns, and the sequence a1, a2, ... Create a program that finds the remainder by dividing the sum by 100000 = 105.
Diagram corresponding to the input / output example
<image>
output
The output consists of one line containing the remainder of your total distance traveled in the m-day journey divided by 100000 = 105.
Input / output example
Input example 1
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output example 1
18
On the first day you move from post town 1 to post town 3. On the second day you move from post town 3 to post town 2. And on the third day you move from post town 2 to post town 5. Move, move from post town 5 to post town 7 on the 4th day, move from post town 7 to post town 4 on the 5th day. Your total travel distance in a 5-day trip is 18.
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
input
The integers n and m are separated by blanks on the first line. N (2 β€ n β€ 100000 = 105) is the number of post towns on the JOI highway, and m (1 β€ m β€ 100000 = 105) is Represents the number of days of travel.
The following n β 1 line represents the distance between post towns on the JOI highway. I + 1st line (1 β€ i β€ n β 1) is a positive integer si that represents the distance between post town i and post town i + 1. (1 β€ si β€ 100) is written.
The following m line contains a sequence of movements for m days. Line i + n (1 β€ i β€ m) contains a non-zero integer ai that represents your movement method for day i. Has been.
In the scoring data, it does not move west of post town 1 or east of post town n.
Of the scoring data, 50% of the points are satisfied with n β€ 100 and m β€ 100.
Example
Input
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output
18
"Correct Solution:
```
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0549
AC
"""
import sys
from sys import stdin
from itertools import accumulate
input = stdin.readline
import array
def main(args):
n, m = map(int, input().split())
distances = [int(input()) for _ in range(n-1)]
inns = list(accumulate(distances))
moves = [int(input()) for _ in range(m)]
inns.insert(0, 0)
pos = 0
total_distance = 0
for m in moves:
new_pos = pos + m
total_distance += abs(inns[new_pos] - inns[pos])
pos = new_pos
print(total_distance % 100000)
def main2(args):
n, m = map(int, input().split())
pos = 0
inns = array.array('Q', [0])
for _ in range(n-1):
pos += int(input())
inns.append(pos)
moves = [int(input()) for _ in range(m)]
pos = 0
total_distance = 0
for m in moves:
new_pos = pos + m
total_distance += abs(inns[new_pos] - inns[pos])
pos = new_pos
print(total_distance % 100000)
def main3(args):
n, m = map(int, input().split())
pos = 0
inns = {0: 0}
for i in range(n-1):
pos += int(input())
inns[i+1] = pos
moves = [int(input()) for _ in range(m)]
pos = 0
total_distance = 0
for m in moves:
new_pos = pos + m
total_distance += abs(inns[new_pos] - inns[pos])
pos = new_pos
print(total_distance % 100000)
if __name__ == '__main__':
main3(sys.argv[1:])
```
| 102,829 |
Provide a correct Python 3 solution for this coding contest problem.
problem
You are a traveler traveling on the JOI Highway. The JOI Highway is a road that extends straight from east to west, and there are n post towns on the JOI Highway. Numbered. The westernmost post town on the JOI highway is post town 1, and the easternmost post town is post town n.
You have decided to depart from post town 1 and embark on an m-day journey. Your itinerary is determined according to the sequence a1, a2, ..., am as follows. It is a non-zero integer that represents how to move the eyes. If the post town you depart on day i is post town k, then on day i you move straight from post town k to post town k + ai. Means to do.
The number of post towns n, the number of days of travel m, the information on the distance between post towns, and the sequence a1, a2, ... Create a program that finds the remainder by dividing the sum by 100000 = 105.
Diagram corresponding to the input / output example
<image>
output
The output consists of one line containing the remainder of your total distance traveled in the m-day journey divided by 100000 = 105.
Input / output example
Input example 1
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output example 1
18
On the first day you move from post town 1 to post town 3. On the second day you move from post town 3 to post town 2. And on the third day you move from post town 2 to post town 5. Move, move from post town 5 to post town 7 on the 4th day, move from post town 7 to post town 4 on the 5th day. Your total travel distance in a 5-day trip is 18.
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
input
The integers n and m are separated by blanks on the first line. N (2 β€ n β€ 100000 = 105) is the number of post towns on the JOI highway, and m (1 β€ m β€ 100000 = 105) is Represents the number of days of travel.
The following n β 1 line represents the distance between post towns on the JOI highway. I + 1st line (1 β€ i β€ n β 1) is a positive integer si that represents the distance between post town i and post town i + 1. (1 β€ si β€ 100) is written.
The following m line contains a sequence of movements for m days. Line i + n (1 β€ i β€ m) contains a non-zero integer ai that represents your movement method for day i. Has been.
In the scoring data, it does not move west of post town 1 or east of post town n.
Of the scoring data, 50% of the points are satisfied with n β€ 100 and m β€ 100.
Example
Input
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output
18
"Correct Solution:
```
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0549
AC
"""
import sys
from sys import stdin
from itertools import accumulate
input = stdin.readline
import array
def main(args):
n, m = map(int, input().split())
distances = [int(input()) for _ in range(n-1)]
inns = list(accumulate(distances))
moves = [int(input()) for _ in range(m)]
inns.insert(0, 0)
pos = 0
total_distance = 0
for m in moves:
new_pos = pos + m
total_distance += abs(inns[new_pos] - inns[pos])
pos = new_pos
print(total_distance % 100000)
def main2(args):
n, m = map(int, input().split())
pos = 0
inns = array.array('Q', [0])
for _ in range(n-1):
pos += int(input())
inns.append(pos)
moves = [int(input()) for _ in range(m)]
pos = 0
total_distance = 0
for m in moves:
new_pos = pos + m
total_distance += abs(inns[new_pos] - inns[pos])
pos = new_pos
print(total_distance % 100000)
if __name__ == '__main__':
main2(sys.argv[1:])
```
| 102,830 |
Provide a correct Python 3 solution for this coding contest problem.
problem
You are a traveler traveling on the JOI Highway. The JOI Highway is a road that extends straight from east to west, and there are n post towns on the JOI Highway. Numbered. The westernmost post town on the JOI highway is post town 1, and the easternmost post town is post town n.
You have decided to depart from post town 1 and embark on an m-day journey. Your itinerary is determined according to the sequence a1, a2, ..., am as follows. It is a non-zero integer that represents how to move the eyes. If the post town you depart on day i is post town k, then on day i you move straight from post town k to post town k + ai. Means to do.
The number of post towns n, the number of days of travel m, the information on the distance between post towns, and the sequence a1, a2, ... Create a program that finds the remainder by dividing the sum by 100000 = 105.
Diagram corresponding to the input / output example
<image>
output
The output consists of one line containing the remainder of your total distance traveled in the m-day journey divided by 100000 = 105.
Input / output example
Input example 1
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output example 1
18
On the first day you move from post town 1 to post town 3. On the second day you move from post town 3 to post town 2. And on the third day you move from post town 2 to post town 5. Move, move from post town 5 to post town 7 on the 4th day, move from post town 7 to post town 4 on the 5th day. Your total travel distance in a 5-day trip is 18.
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
input
The integers n and m are separated by blanks on the first line. N (2 β€ n β€ 100000 = 105) is the number of post towns on the JOI highway, and m (1 β€ m β€ 100000 = 105) is Represents the number of days of travel.
The following n β 1 line represents the distance between post towns on the JOI highway. I + 1st line (1 β€ i β€ n β 1) is a positive integer si that represents the distance between post town i and post town i + 1. (1 β€ si β€ 100) is written.
The following m line contains a sequence of movements for m days. Line i + n (1 β€ i β€ m) contains a non-zero integer ai that represents your movement method for day i. Has been.
In the scoring data, it does not move west of post town 1 or east of post town n.
Of the scoring data, 50% of the points are satisfied with n β€ 100 and m β€ 100.
Example
Input
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output
18
"Correct Solution:
```
n, m = map(int, input().split())
kyori = [0 for _ in range(n + 1)]
cum_k = [0 for _ in range(n + 1)]
for ni in range(1, n):
si = int(input())
kyori[ni] = si
cum_k[ni + 1] = cum_k[ni] + si
# print(kyori)
# print(cum_k)
ans, pos = 0, 1
for mi in range(m):
nex = pos + int(input())
ans += abs(cum_k[nex] - cum_k[pos])
pos = nex
print(ans % 100000)
```
| 102,831 |
Provide a correct Python 3 solution for this coding contest problem.
problem
You are a traveler traveling on the JOI Highway. The JOI Highway is a road that extends straight from east to west, and there are n post towns on the JOI Highway. Numbered. The westernmost post town on the JOI highway is post town 1, and the easternmost post town is post town n.
You have decided to depart from post town 1 and embark on an m-day journey. Your itinerary is determined according to the sequence a1, a2, ..., am as follows. It is a non-zero integer that represents how to move the eyes. If the post town you depart on day i is post town k, then on day i you move straight from post town k to post town k + ai. Means to do.
The number of post towns n, the number of days of travel m, the information on the distance between post towns, and the sequence a1, a2, ... Create a program that finds the remainder by dividing the sum by 100000 = 105.
Diagram corresponding to the input / output example
<image>
output
The output consists of one line containing the remainder of your total distance traveled in the m-day journey divided by 100000 = 105.
Input / output example
Input example 1
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output example 1
18
On the first day you move from post town 1 to post town 3. On the second day you move from post town 3 to post town 2. And on the third day you move from post town 2 to post town 5. Move, move from post town 5 to post town 7 on the 4th day, move from post town 7 to post town 4 on the 5th day. Your total travel distance in a 5-day trip is 18.
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
input
The integers n and m are separated by blanks on the first line. N (2 β€ n β€ 100000 = 105) is the number of post towns on the JOI highway, and m (1 β€ m β€ 100000 = 105) is Represents the number of days of travel.
The following n β 1 line represents the distance between post towns on the JOI highway. I + 1st line (1 β€ i β€ n β 1) is a positive integer si that represents the distance between post town i and post town i + 1. (1 β€ si β€ 100) is written.
The following m line contains a sequence of movements for m days. Line i + n (1 β€ i β€ m) contains a non-zero integer ai that represents your movement method for day i. Has been.
In the scoring data, it does not move west of post town 1 or east of post town n.
Of the scoring data, 50% of the points are satisfied with n β€ 100 and m β€ 100.
Example
Input
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output
18
"Correct Solution:
```
NM=input().split()
N=int(NM[0])
M=int(NM[1])
s=[]
a=[]
for i in range(N-1):
s.append(int(input()))
Sum=0
TotalS=[0]
for i in range(N-1):
Sum+=s[i]
TotalS.append(Sum)
position=0
TD=0#TraveledDistance
for i in range(M):
a=int(input())
TD+=abs(TotalS[position]-TotalS[position+a])
position+=a
TD%=100000
print(TD)
```
| 102,832 |
Provide a correct Python 3 solution for this coding contest problem.
problem
You are a traveler traveling on the JOI Highway. The JOI Highway is a road that extends straight from east to west, and there are n post towns on the JOI Highway. Numbered. The westernmost post town on the JOI highway is post town 1, and the easternmost post town is post town n.
You have decided to depart from post town 1 and embark on an m-day journey. Your itinerary is determined according to the sequence a1, a2, ..., am as follows. It is a non-zero integer that represents how to move the eyes. If the post town you depart on day i is post town k, then on day i you move straight from post town k to post town k + ai. Means to do.
The number of post towns n, the number of days of travel m, the information on the distance between post towns, and the sequence a1, a2, ... Create a program that finds the remainder by dividing the sum by 100000 = 105.
Diagram corresponding to the input / output example
<image>
output
The output consists of one line containing the remainder of your total distance traveled in the m-day journey divided by 100000 = 105.
Input / output example
Input example 1
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output example 1
18
On the first day you move from post town 1 to post town 3. On the second day you move from post town 3 to post town 2. And on the third day you move from post town 2 to post town 5. Move, move from post town 5 to post town 7 on the 4th day, move from post town 7 to post town 4 on the 5th day. Your total travel distance in a 5-day trip is 18.
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
input
The integers n and m are separated by blanks on the first line. N (2 β€ n β€ 100000 = 105) is the number of post towns on the JOI highway, and m (1 β€ m β€ 100000 = 105) is Represents the number of days of travel.
The following n β 1 line represents the distance between post towns on the JOI highway. I + 1st line (1 β€ i β€ n β 1) is a positive integer si that represents the distance between post town i and post town i + 1. (1 β€ si β€ 100) is written.
The following m line contains a sequence of movements for m days. Line i + n (1 β€ i β€ m) contains a non-zero integer ai that represents your movement method for day i. Has been.
In the scoring data, it does not move west of post town 1 or east of post town n.
Of the scoring data, 50% of the points are satisfied with n β€ 100 and m β€ 100.
Example
Input
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output
18
"Correct Solution:
```
n,m = map(int,input().split())
lst = [0]
for i in range(n - 1):
lst.append(lst[-1] + int(input()))
ans = 0
num = 0
for i in range(m):
a = int(input())
ans += abs(lst[num] - lst[num + a])
ans %= 100000
num += a
print(ans)
```
| 102,833 |
Provide a correct Python 3 solution for this coding contest problem.
problem
You are a traveler traveling on the JOI Highway. The JOI Highway is a road that extends straight from east to west, and there are n post towns on the JOI Highway. Numbered. The westernmost post town on the JOI highway is post town 1, and the easternmost post town is post town n.
You have decided to depart from post town 1 and embark on an m-day journey. Your itinerary is determined according to the sequence a1, a2, ..., am as follows. It is a non-zero integer that represents how to move the eyes. If the post town you depart on day i is post town k, then on day i you move straight from post town k to post town k + ai. Means to do.
The number of post towns n, the number of days of travel m, the information on the distance between post towns, and the sequence a1, a2, ... Create a program that finds the remainder by dividing the sum by 100000 = 105.
Diagram corresponding to the input / output example
<image>
output
The output consists of one line containing the remainder of your total distance traveled in the m-day journey divided by 100000 = 105.
Input / output example
Input example 1
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output example 1
18
On the first day you move from post town 1 to post town 3. On the second day you move from post town 3 to post town 2. And on the third day you move from post town 2 to post town 5. Move, move from post town 5 to post town 7 on the 4th day, move from post town 7 to post town 4 on the 5th day. Your total travel distance in a 5-day trip is 18.
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
input
The integers n and m are separated by blanks on the first line. N (2 β€ n β€ 100000 = 105) is the number of post towns on the JOI highway, and m (1 β€ m β€ 100000 = 105) is Represents the number of days of travel.
The following n β 1 line represents the distance between post towns on the JOI highway. I + 1st line (1 β€ i β€ n β 1) is a positive integer si that represents the distance between post town i and post town i + 1. (1 β€ si β€ 100) is written.
The following m line contains a sequence of movements for m days. Line i + n (1 β€ i β€ m) contains a non-zero integer ai that represents your movement method for day i. Has been.
In the scoring data, it does not move west of post town 1 or east of post town n.
Of the scoring data, 50% of the points are satisfied with n β€ 100 and m β€ 100.
Example
Input
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output
18
"Correct Solution:
```
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0549
AC
"""
import sys
from sys import stdin
from itertools import accumulate
input = stdin.readline
import array
def main(args):
# list
n, m = map(int, input().split())
distances = [int(input()) for _ in range(n-1)]
inns = list(accumulate(distances))
moves = [int(input()) for _ in range(m)]
inns.insert(0, 0)
pos = 0
total_distance = 0
for m in moves:
new_pos = pos + m
total_distance += abs(inns[new_pos] - inns[pos])
pos = new_pos
print(total_distance % 100000)
def main2(args):
# array
n, m = map(int, input().split())
pos = 0
inns = array.array('L', [0])
for _ in range(n-1):
pos += int(input())
inns.append(pos)
moves = [int(input()) for _ in range(m)]
pos = 0
total_distance = 0
for m in moves:
new_pos = pos + m
total_distance += abs(inns[new_pos] - inns[pos])
pos = new_pos
print(total_distance % 100000)
def main3(args):
# dict
n, m = map(int, input().split())
pos = 0
inns = {0: 0}
for i in range(n-1):
pos += int(input())
inns[i+1] = pos
moves = [int(input()) for _ in range(m)]
pos = 0
total_distance = 0
for m in moves:
new_pos = pos + m
total_distance += abs(inns[new_pos] - inns[pos])
pos = new_pos
print(total_distance % 100000)
if __name__ == '__main__':
main2(sys.argv[1:])
```
| 102,834 |
Provide a correct Python 3 solution for this coding contest problem.
problem
You are a traveler traveling on the JOI Highway. The JOI Highway is a road that extends straight from east to west, and there are n post towns on the JOI Highway. Numbered. The westernmost post town on the JOI highway is post town 1, and the easternmost post town is post town n.
You have decided to depart from post town 1 and embark on an m-day journey. Your itinerary is determined according to the sequence a1, a2, ..., am as follows. It is a non-zero integer that represents how to move the eyes. If the post town you depart on day i is post town k, then on day i you move straight from post town k to post town k + ai. Means to do.
The number of post towns n, the number of days of travel m, the information on the distance between post towns, and the sequence a1, a2, ... Create a program that finds the remainder by dividing the sum by 100000 = 105.
Diagram corresponding to the input / output example
<image>
output
The output consists of one line containing the remainder of your total distance traveled in the m-day journey divided by 100000 = 105.
Input / output example
Input example 1
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output example 1
18
On the first day you move from post town 1 to post town 3. On the second day you move from post town 3 to post town 2. And on the third day you move from post town 2 to post town 5. Move, move from post town 5 to post town 7 on the 4th day, move from post town 7 to post town 4 on the 5th day. Your total travel distance in a 5-day trip is 18.
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
input
The integers n and m are separated by blanks on the first line. N (2 β€ n β€ 100000 = 105) is the number of post towns on the JOI highway, and m (1 β€ m β€ 100000 = 105) is Represents the number of days of travel.
The following n β 1 line represents the distance between post towns on the JOI highway. I + 1st line (1 β€ i β€ n β 1) is a positive integer si that represents the distance between post town i and post town i + 1. (1 β€ si β€ 100) is written.
The following m line contains a sequence of movements for m days. Line i + n (1 β€ i β€ m) contains a non-zero integer ai that represents your movement method for day i. Has been.
In the scoring data, it does not move west of post town 1 or east of post town n.
Of the scoring data, 50% of the points are satisfied with n β€ 100 and m β€ 100.
Example
Input
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output
18
"Correct Solution:
```
# -*- coding: utf-8 -*-
# !/usr/bin/env python
# vim: set fileencoding=utf-8 :
"""
#
# Author: Noname
# URL: https://github.com/pettan0818
# License: MIT License
# Created: ζ¨ 11/ 9 19:01:14 2017
# Usage
#
"""
from itertools import accumulate
def data_req():
n_yado, m_ryotei = [int(i) for i in input().split(" ")]
yado_distance = []
ryotei = []
for _ in range(n_yado - 1):
yado_distance.append(int(input()))
for _ in range(m_ryotei):
ryotei.append(int(input()))
return yado_distance, ryotei
def search(distance, ryotei):
"""search.
>>> search([2, 1, 1, 3, 2, 1], [2, -1, 3, 2, -3])
18
"""
acc = [0] + list(accumulate(distance, lambda x, y: x+y))
ryotei_index = [0] + list(accumulate(ryotei, lambda x, y: x+y))
# print(ryotei_index)
res = []
for index in enumerate(ryotei_index):
if index[0] == 0:
continue
index = index[0]
# print(index)
# print(ryotei_index[index])
# print(ryotei_index[index - 1])
dist = abs(acc[ryotei_index[index]] - acc[ryotei_index[index - 1]])
res.append(dist)
# print(sum(res))
# his = []
#
# for index in range(len(ryotei_index)):
# his.append(acc[ryotei_index[index + 1]] - acc[ryotei_index[index]])
#
# return sum(his)
return sum(res)
if __name__ == '__main__':
dis, ryotei = data_req()
print(search(dis, ryotei) % 100000)
```
| 102,835 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
problem
You are a traveler traveling on the JOI Highway. The JOI Highway is a road that extends straight from east to west, and there are n post towns on the JOI Highway. Numbered. The westernmost post town on the JOI highway is post town 1, and the easternmost post town is post town n.
You have decided to depart from post town 1 and embark on an m-day journey. Your itinerary is determined according to the sequence a1, a2, ..., am as follows. It is a non-zero integer that represents how to move the eyes. If the post town you depart on day i is post town k, then on day i you move straight from post town k to post town k + ai. Means to do.
The number of post towns n, the number of days of travel m, the information on the distance between post towns, and the sequence a1, a2, ... Create a program that finds the remainder by dividing the sum by 100000 = 105.
Diagram corresponding to the input / output example
<image>
output
The output consists of one line containing the remainder of your total distance traveled in the m-day journey divided by 100000 = 105.
Input / output example
Input example 1
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output example 1
18
On the first day you move from post town 1 to post town 3. On the second day you move from post town 3 to post town 2. And on the third day you move from post town 2 to post town 5. Move, move from post town 5 to post town 7 on the 4th day, move from post town 7 to post town 4 on the 5th day. Your total travel distance in a 5-day trip is 18.
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
input
The integers n and m are separated by blanks on the first line. N (2 β€ n β€ 100000 = 105) is the number of post towns on the JOI highway, and m (1 β€ m β€ 100000 = 105) is Represents the number of days of travel.
The following n β 1 line represents the distance between post towns on the JOI highway. I + 1st line (1 β€ i β€ n β 1) is a positive integer si that represents the distance between post town i and post town i + 1. (1 β€ si β€ 100) is written.
The following m line contains a sequence of movements for m days. Line i + n (1 β€ i β€ m) contains a non-zero integer ai that represents your movement method for day i. Has been.
In the scoring data, it does not move west of post town 1 or east of post town n.
Of the scoring data, 50% of the points are satisfied with n β€ 100 and m β€ 100.
Example
Input
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output
18
Submitted Solution:
```
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0549
"""
import sys
from sys import stdin
from itertools import accumulate
input = stdin.readline
def main(args):
n, m = map(int, input().split())
distances = [int(input()) for _ in range(n-1)]
inns = list(accumulate(distances))
moves = [int(input()) for _ in range(m)]
inns.insert(0, 0)
pos = 0
total_distance = 0
for m in moves:
new_pos = pos + m
total_distance += abs(inns[new_pos] - inns[pos])
pos = new_pos
print(total_distance % 100000)
if __name__ == '__main__':
main(sys.argv[1:])
```
Yes
| 102,836 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
problem
You are a traveler traveling on the JOI Highway. The JOI Highway is a road that extends straight from east to west, and there are n post towns on the JOI Highway. Numbered. The westernmost post town on the JOI highway is post town 1, and the easternmost post town is post town n.
You have decided to depart from post town 1 and embark on an m-day journey. Your itinerary is determined according to the sequence a1, a2, ..., am as follows. It is a non-zero integer that represents how to move the eyes. If the post town you depart on day i is post town k, then on day i you move straight from post town k to post town k + ai. Means to do.
The number of post towns n, the number of days of travel m, the information on the distance between post towns, and the sequence a1, a2, ... Create a program that finds the remainder by dividing the sum by 100000 = 105.
Diagram corresponding to the input / output example
<image>
output
The output consists of one line containing the remainder of your total distance traveled in the m-day journey divided by 100000 = 105.
Input / output example
Input example 1
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output example 1
18
On the first day you move from post town 1 to post town 3. On the second day you move from post town 3 to post town 2. And on the third day you move from post town 2 to post town 5. Move, move from post town 5 to post town 7 on the 4th day, move from post town 7 to post town 4 on the 5th day. Your total travel distance in a 5-day trip is 18.
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
input
The integers n and m are separated by blanks on the first line. N (2 β€ n β€ 100000 = 105) is the number of post towns on the JOI highway, and m (1 β€ m β€ 100000 = 105) is Represents the number of days of travel.
The following n β 1 line represents the distance between post towns on the JOI highway. I + 1st line (1 β€ i β€ n β 1) is a positive integer si that represents the distance between post town i and post town i + 1. (1 β€ si β€ 100) is written.
The following m line contains a sequence of movements for m days. Line i + n (1 β€ i β€ m) contains a non-zero integer ai that represents your movement method for day i. Has been.
In the scoring data, it does not move west of post town 1 or east of post town n.
Of the scoring data, 50% of the points are satisfied with n β€ 100 and m β€ 100.
Example
Input
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output
18
Submitted Solution:
```
# AOJ 0549: A Traveler
# Python3 2018.7.1 bal4u
import sys
from sys import stdin
input = stdin.readline
M, BigM = 100000, 1000000000
n, m = map(int, input().split())
s = [0]*(n+1)
for i in range(2, n+1): s[i] = s[i-1] + int(input())
ans, p1 = 0, 1
for i in range(m):
p2 = p1 + int(input())
x = s[p2] - s[p1]
if x >= 0: ans += x
else: ans -= x
if ans >= BigM: ans %= M
p1 = p2;
print(ans % M)
```
Yes
| 102,837 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
problem
You are a traveler traveling on the JOI Highway. The JOI Highway is a road that extends straight from east to west, and there are n post towns on the JOI Highway. Numbered. The westernmost post town on the JOI highway is post town 1, and the easternmost post town is post town n.
You have decided to depart from post town 1 and embark on an m-day journey. Your itinerary is determined according to the sequence a1, a2, ..., am as follows. It is a non-zero integer that represents how to move the eyes. If the post town you depart on day i is post town k, then on day i you move straight from post town k to post town k + ai. Means to do.
The number of post towns n, the number of days of travel m, the information on the distance between post towns, and the sequence a1, a2, ... Create a program that finds the remainder by dividing the sum by 100000 = 105.
Diagram corresponding to the input / output example
<image>
output
The output consists of one line containing the remainder of your total distance traveled in the m-day journey divided by 100000 = 105.
Input / output example
Input example 1
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output example 1
18
On the first day you move from post town 1 to post town 3. On the second day you move from post town 3 to post town 2. And on the third day you move from post town 2 to post town 5. Move, move from post town 5 to post town 7 on the 4th day, move from post town 7 to post town 4 on the 5th day. Your total travel distance in a 5-day trip is 18.
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
input
The integers n and m are separated by blanks on the first line. N (2 β€ n β€ 100000 = 105) is the number of post towns on the JOI highway, and m (1 β€ m β€ 100000 = 105) is Represents the number of days of travel.
The following n β 1 line represents the distance between post towns on the JOI highway. I + 1st line (1 β€ i β€ n β 1) is a positive integer si that represents the distance between post town i and post town i + 1. (1 β€ si β€ 100) is written.
The following m line contains a sequence of movements for m days. Line i + n (1 β€ i β€ m) contains a non-zero integer ai that represents your movement method for day i. Has been.
In the scoring data, it does not move west of post town 1 or east of post town n.
Of the scoring data, 50% of the points are satisfied with n β€ 100 and m β€ 100.
Example
Input
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output
18
Submitted Solution:
```
n,m = map(int,input().split())
lng = [0]
for _ in range(n-1):
lng.append(lng[-1] + int(input()))
i = 0
sm = 0
for _ in range(m):
j = i+int(input())
sm += abs(lng[i]-lng[j])
sm %= 100000
i = j
print(sm)
```
Yes
| 102,838 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
problem
You are a traveler traveling on the JOI Highway. The JOI Highway is a road that extends straight from east to west, and there are n post towns on the JOI Highway. Numbered. The westernmost post town on the JOI highway is post town 1, and the easternmost post town is post town n.
You have decided to depart from post town 1 and embark on an m-day journey. Your itinerary is determined according to the sequence a1, a2, ..., am as follows. It is a non-zero integer that represents how to move the eyes. If the post town you depart on day i is post town k, then on day i you move straight from post town k to post town k + ai. Means to do.
The number of post towns n, the number of days of travel m, the information on the distance between post towns, and the sequence a1, a2, ... Create a program that finds the remainder by dividing the sum by 100000 = 105.
Diagram corresponding to the input / output example
<image>
output
The output consists of one line containing the remainder of your total distance traveled in the m-day journey divided by 100000 = 105.
Input / output example
Input example 1
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output example 1
18
On the first day you move from post town 1 to post town 3. On the second day you move from post town 3 to post town 2. And on the third day you move from post town 2 to post town 5. Move, move from post town 5 to post town 7 on the 4th day, move from post town 7 to post town 4 on the 5th day. Your total travel distance in a 5-day trip is 18.
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
input
The integers n and m are separated by blanks on the first line. N (2 β€ n β€ 100000 = 105) is the number of post towns on the JOI highway, and m (1 β€ m β€ 100000 = 105) is Represents the number of days of travel.
The following n β 1 line represents the distance between post towns on the JOI highway. I + 1st line (1 β€ i β€ n β 1) is a positive integer si that represents the distance between post town i and post town i + 1. (1 β€ si β€ 100) is written.
The following m line contains a sequence of movements for m days. Line i + n (1 β€ i β€ m) contains a non-zero integer ai that represents your movement method for day i. Has been.
In the scoring data, it does not move west of post town 1 or east of post town n.
Of the scoring data, 50% of the points are satisfied with n β€ 100 and m β€ 100.
Example
Input
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output
18
Submitted Solution:
```
n, m = map(int, input().split())
accums = [0]
for i in range(n - 1):
accums.append(accums[-1] + int(input()))
result = 0
k = 0
for i in range(m):
a = int(input())
result = (result + abs(accums[k + a] - accums[k])) % 100000
k += a
print(result)
```
Yes
| 102,839 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
problem
You are a traveler traveling on the JOI Highway. The JOI Highway is a road that extends straight from east to west, and there are n post towns on the JOI Highway. Numbered. The westernmost post town on the JOI highway is post town 1, and the easternmost post town is post town n.
You have decided to depart from post town 1 and embark on an m-day journey. Your itinerary is determined according to the sequence a1, a2, ..., am as follows. It is a non-zero integer that represents how to move the eyes. If the post town you depart on day i is post town k, then on day i you move straight from post town k to post town k + ai. Means to do.
The number of post towns n, the number of days of travel m, the information on the distance between post towns, and the sequence a1, a2, ... Create a program that finds the remainder by dividing the sum by 100000 = 105.
Diagram corresponding to the input / output example
<image>
output
The output consists of one line containing the remainder of your total distance traveled in the m-day journey divided by 100000 = 105.
Input / output example
Input example 1
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output example 1
18
On the first day you move from post town 1 to post town 3. On the second day you move from post town 3 to post town 2. And on the third day you move from post town 2 to post town 5. Move, move from post town 5 to post town 7 on the 4th day, move from post town 7 to post town 4 on the 5th day. Your total travel distance in a 5-day trip is 18.
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
input
The integers n and m are separated by blanks on the first line. N (2 β€ n β€ 100000 = 105) is the number of post towns on the JOI highway, and m (1 β€ m β€ 100000 = 105) is Represents the number of days of travel.
The following n β 1 line represents the distance between post towns on the JOI highway. I + 1st line (1 β€ i β€ n β 1) is a positive integer si that represents the distance between post town i and post town i + 1. (1 β€ si β€ 100) is written.
The following m line contains a sequence of movements for m days. Line i + n (1 β€ i β€ m) contains a non-zero integer ai that represents your movement method for day i. Has been.
In the scoring data, it does not move west of post town 1 or east of post town n.
Of the scoring data, 50% of the points are satisfied with n β€ 100 and m β€ 100.
Example
Input
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output
18
Submitted Solution:
```
n,m = map(int,input().split())
lng = []
for _ in range(n-1):
lng.append(int(input()))
i = 0
sm = 0
for _ in range(m):
j = i+int(input())
mv = sum(lng[i:j]) if j > i else sum(lng[j:i])
sm += mv
sm %= 100000
i = j
print(sm)
```
No
| 102,840 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
problem
You are a traveler traveling on the JOI Highway. The JOI Highway is a road that extends straight from east to west, and there are n post towns on the JOI Highway. Numbered. The westernmost post town on the JOI highway is post town 1, and the easternmost post town is post town n.
You have decided to depart from post town 1 and embark on an m-day journey. Your itinerary is determined according to the sequence a1, a2, ..., am as follows. It is a non-zero integer that represents how to move the eyes. If the post town you depart on day i is post town k, then on day i you move straight from post town k to post town k + ai. Means to do.
The number of post towns n, the number of days of travel m, the information on the distance between post towns, and the sequence a1, a2, ... Create a program that finds the remainder by dividing the sum by 100000 = 105.
Diagram corresponding to the input / output example
<image>
output
The output consists of one line containing the remainder of your total distance traveled in the m-day journey divided by 100000 = 105.
Input / output example
Input example 1
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output example 1
18
On the first day you move from post town 1 to post town 3. On the second day you move from post town 3 to post town 2. And on the third day you move from post town 2 to post town 5. Move, move from post town 5 to post town 7 on the 4th day, move from post town 7 to post town 4 on the 5th day. Your total travel distance in a 5-day trip is 18.
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
input
The integers n and m are separated by blanks on the first line. N (2 β€ n β€ 100000 = 105) is the number of post towns on the JOI highway, and m (1 β€ m β€ 100000 = 105) is Represents the number of days of travel.
The following n β 1 line represents the distance between post towns on the JOI highway. I + 1st line (1 β€ i β€ n β 1) is a positive integer si that represents the distance between post town i and post town i + 1. (1 β€ si β€ 100) is written.
The following m line contains a sequence of movements for m days. Line i + n (1 β€ i β€ m) contains a non-zero integer ai that represents your movement method for day i. Has been.
In the scoring data, it does not move west of post town 1 or east of post town n.
Of the scoring data, 50% of the points are satisfied with n β€ 100 and m β€ 100.
Example
Input
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output
18
Submitted Solution:
```
n,m = map(int,input().split())
lng = []
for _ in range(n-1):
lng.append(int(input()))
i = 0
sm = 0
for _ in range(m):
j = i+int(input())
mv = sum(lng[i:j]) if j > i else sum(lng[j:i])
sm += mv
i = j
print(sm%100000)
```
No
| 102,841 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
problem
You are a traveler traveling on the JOI Highway. The JOI Highway is a road that extends straight from east to west, and there are n post towns on the JOI Highway. Numbered. The westernmost post town on the JOI highway is post town 1, and the easternmost post town is post town n.
You have decided to depart from post town 1 and embark on an m-day journey. Your itinerary is determined according to the sequence a1, a2, ..., am as follows. It is a non-zero integer that represents how to move the eyes. If the post town you depart on day i is post town k, then on day i you move straight from post town k to post town k + ai. Means to do.
The number of post towns n, the number of days of travel m, the information on the distance between post towns, and the sequence a1, a2, ... Create a program that finds the remainder by dividing the sum by 100000 = 105.
Diagram corresponding to the input / output example
<image>
output
The output consists of one line containing the remainder of your total distance traveled in the m-day journey divided by 100000 = 105.
Input / output example
Input example 1
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output example 1
18
On the first day you move from post town 1 to post town 3. On the second day you move from post town 3 to post town 2. And on the third day you move from post town 2 to post town 5. Move, move from post town 5 to post town 7 on the 4th day, move from post town 7 to post town 4 on the 5th day. Your total travel distance in a 5-day trip is 18.
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
input
The integers n and m are separated by blanks on the first line. N (2 β€ n β€ 100000 = 105) is the number of post towns on the JOI highway, and m (1 β€ m β€ 100000 = 105) is Represents the number of days of travel.
The following n β 1 line represents the distance between post towns on the JOI highway. I + 1st line (1 β€ i β€ n β 1) is a positive integer si that represents the distance between post town i and post town i + 1. (1 β€ si β€ 100) is written.
The following m line contains a sequence of movements for m days. Line i + n (1 β€ i β€ m) contains a non-zero integer ai that represents your movement method for day i. Has been.
In the scoring data, it does not move west of post town 1 or east of post town n.
Of the scoring data, 50% of the points are satisfied with n β€ 100 and m β€ 100.
Example
Input
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output
18
Submitted Solution:
```
NM=input().split()
N=int(NM[0])
M=int(NM[1])
s=[]
a=[]
for i in range(N-1):
s.append(int(input()))
Sum=0
TotalS=[0]
for i in range(N-1):
Sum+=s[i]
TotalS.append(Sum)
position=0
TD=0
for i in range(M):
a=int(input())
TD+=abs(TotalS[position]-TotalS[position+a])
position+=a
print(TD)
```
No
| 102,842 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
problem
You are a traveler traveling on the JOI Highway. The JOI Highway is a road that extends straight from east to west, and there are n post towns on the JOI Highway. Numbered. The westernmost post town on the JOI highway is post town 1, and the easternmost post town is post town n.
You have decided to depart from post town 1 and embark on an m-day journey. Your itinerary is determined according to the sequence a1, a2, ..., am as follows. It is a non-zero integer that represents how to move the eyes. If the post town you depart on day i is post town k, then on day i you move straight from post town k to post town k + ai. Means to do.
The number of post towns n, the number of days of travel m, the information on the distance between post towns, and the sequence a1, a2, ... Create a program that finds the remainder by dividing the sum by 100000 = 105.
Diagram corresponding to the input / output example
<image>
output
The output consists of one line containing the remainder of your total distance traveled in the m-day journey divided by 100000 = 105.
Input / output example
Input example 1
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output example 1
18
On the first day you move from post town 1 to post town 3. On the second day you move from post town 3 to post town 2. And on the third day you move from post town 2 to post town 5. Move, move from post town 5 to post town 7 on the 4th day, move from post town 7 to post town 4 on the 5th day. Your total travel distance in a 5-day trip is 18.
The above question sentences and the data used for the automatic referee are the question sentences created and published by the Japan Committee for Information Olympics and the test data for scoring.
input
The integers n and m are separated by blanks on the first line. N (2 β€ n β€ 100000 = 105) is the number of post towns on the JOI highway, and m (1 β€ m β€ 100000 = 105) is Represents the number of days of travel.
The following n β 1 line represents the distance between post towns on the JOI highway. I + 1st line (1 β€ i β€ n β 1) is a positive integer si that represents the distance between post town i and post town i + 1. (1 β€ si β€ 100) is written.
The following m line contains a sequence of movements for m days. Line i + n (1 β€ i β€ m) contains a non-zero integer ai that represents your movement method for day i. Has been.
In the scoring data, it does not move west of post town 1 or east of post town n.
Of the scoring data, 50% of the points are satisfied with n β€ 100 and m β€ 100.
Example
Input
7 5
2
1
1
3
2
1
2
-1
3
2
-3
Output
18
Submitted Solution:
```
# -*- coding: utf-8 -*-
# !/usr/bin/env python
# vim: set fileencoding=utf-8 :
"""
#
# Author: Noname
# URL: https://github.com/pettan0818
# License: MIT License
# Created: ζ¨ 11/ 9 19:01:14 2017
# Usage
#
"""
from itertools import accumulate
def data_req():
n_yado, m_ryotei = [int(i) for i in input().split(" ")]
yado_distance = []
ryotei = []
for _ in range(n_yado - 1):
yado_distance.append(int(input()))
for _ in range(m_ryotei):
ryotei.append(int(input()))
return yado_distance, ryotei
def search(distance, ryotei):
"""search.
>>> search([2, 1, 1, 3, 2, 1], [2, -1, 3, 2, -3])
18
"""
acc = [0] + list(accumulate(distance, lambda x, y: x+y))
ryotei_index = [0] + list(accumulate(ryotei, lambda x, y: x+y))
# print(ryotei_index)
res = []
for index in enumerate(ryotei_index):
if index[0] == 0:
continue
index = index[0]
# print(index)
# print(ryotei_index[index])
# print(ryotei_index[index - 1])
dist = abs(acc[ryotei_index[index]] - acc[ryotei_index[index - 1]])
res.append(dist)
# print(sum(res))
# his = []
#
# for index in range(len(ryotei_index)):
# his.append(acc[ryotei_index[index + 1]] - acc[ryotei_index[index]])
#
# return sum(his)
return sum(res)
if __name__ == '__main__':
dis, ryotei = data_req()
search(dis, ryotei)
```
No
| 102,843 |
Provide a correct Python 3 solution for this coding contest problem.
Cosmic market, commonly known as Kozumike, is the largest coterie spot sale in the universe. Doujin lovers of all genres gather at Kozumike. In recent years, the number of visitors to Kozumike has been increasing. If everyone can enter from the beginning, it will be very crowded and dangerous, so admission is restricted immediately after the opening. Only a certain number of people can enter at the same time as the opening. Others have to wait for a while before entering.
However, if you decide to enter the venue on a first-come, first-served basis, some people will line up all night from the day before. Many of Kozumike's participants are minors, and there are security issues, so it is not very good to decide on a first-come, first-served basis. For that reason, Kozumike can play some kind of game among the participants, and the person who survives the game gets the right to enter first. To be fair, we use highly random games every year.
I plan to participate in Kozumike again this time. I have a douujinshi that I really want to get at this Kozumike. A doujinshi distributed by a popular circle, which deals with the magical girl anime that became a hot topic this spring. However, this circle is very popular and its distribution ends immediately every time. It would be almost impossible to get it if you couldn't enter at the same time as the opening. Of course, there is no doubt that it will be available at douujin shops at a later date. But I can't put up with it until then. I have to get it on the day of Kozumike with any hand. Unfortunately, I've never been the first to enter Kozumike.
According to Kozumike's catalog, this time we will select the first person to enter in the following games. First, the first r Γ c of the participants sit in any of the seats arranged like the r Γ c grid. You can choose the location on a first-come, first-served basis, so there are many options if you go early. The game starts when r Γ c people sit down. In this game, all people in a seat in a row (row) are instructed to sit or stand a certain number of times. If a person who is already seated is instructed to sit down, just wait. The same is true for those who are standing up. The column (row) to which this instruction is issued and the content of the instruction are randomly determined by roulette. Only those who stand up after a certain number of instructions will be able to enter the venue first. Participants are not informed of the number of instructions, so they do not know when the game will end. So at some point neither standing nor sitting knows if they can enter first. That's why the catalog emphasizes that you can enjoy the thrill.
At 1:00 pm the day before Kozumike, I got all the data about this year's game. According to the information I got, the number of times this instruction, q, has already been decided. On the contrary, all the instructions for q times have already been decided. It is said that it has a high degree of randomness, but that was a lie. I don't know why it was decided in advance. But this information seems to me a godsend.
If the game is played according to this data, you will know all the seating locations where you can enter first. In the worst case, let's say all the participants except me had this information. Even in such a case, you should know the number of arrivals at the latest to enter the venue first. However, it seems impossible to analyze this instruction by hand from now on because it is too much. No matter how hard I try, I can't make it in time for Kozumike.
So I decided to leave this calculation to you. You often participate in programming contests and you should be good at writing math programs like this. Of course I wouldn't ask you to do it for free. According to the catalog, this year's Kozumike will be attended by a circle that publishes a doujinshi about programming contests. If I can enter at the same time as the opening, I will get the douujinshi as a reward and give it to you. Well, I'll take a nap for about 5 hours from now on. In the meantime, I believe you will give me an answer.
Input
The input consists of multiple cases. Each case is given in the following format.
r c q
A0 B0 order0
A1 B1 order1
..
..
..
Aq-1 Bq-1 orderq-1
When Ai = 0, the orderi instruction is executed for the Bi line.
When Ai = 1, the orderi instruction is executed for the Bi column.
When orderi = 0, all people in the specified row or column are seated.
When orderi = 1, make everyone stand in the specified row or column.
The end of the input is given by r = 0 c = 0 q = 0.
The input value satisfies the following conditions.
1 β€ r β€ 50,000
1 β€ c β€ 50,000
1 β€ q β€ 50,000
orderi = 0 or 1
When Ai = 0
0 β€ Bi <r
When Ai = 1
0 β€ Bi <c
The number of test cases does not exceed 100
Output
In the worst case, print out in one line how many times you should arrive to get the right to enter the venue first.
Example
Input
5 5 5
0 0 1
0 0 0
0 2 0
1 2 1
0 0 0
5 5 5
1 4 0
0 1 1
0 4 1
1 3 0
0 3 1
5 5 5
1 0 0
0 3 0
1 2 1
0 4 0
0 1 1
0 0 0
Output
4
13
8
"Correct Solution:
```
while True:
r, c, q = map(int, input().split())
if r == 0: break
querys = [list(map(int, input().split())) for _ in range(q)]
querys.reverse()
r_used = [False] * r
c_used = [False] * c
r_cnt = c
c_cnt = r
ans = 0
for a, b, o in querys:
if a == 0:
if not r_used[b]:
r_used[b] = True
c_cnt -= 1
if o:
ans += r_cnt
else:
if not c_used[b]:
c_used[b] = True
r_cnt -= 1
if o:
ans += c_cnt
print(ans)
```
| 102,844 |
Provide a correct Python 3 solution for this coding contest problem.
Example
Input
2 10 6
4 4 E
6 4 W
Output
2
"Correct Solution:
```
# from (x,y) to SW (0,0) by (-1,-1)
def raySW(x,y):
return x - y
n,w,d=map(int,input().split())
def toRange(xyf):
sx,sy,f = xyf
x=int(sx)
y=int(sy)
if f == 'S':
s = raySW(x,y)
t = w - raySW(w-x,y) # flip in X
return (s,t)
if f == 'E':
s = w - raySW(w-x,y) # flip in X
t = w + d + raySW(w-x,d-y) # flip in both X and Y
return (s,t)
if f == 'N':
s = w + d + raySW(w-x,d-y) # flip in both X and Y
t = w + d + w - raySW(x,d-y) # flip in Y
return (s,t)
if f == 'W':
s = w + d + w - raySW(x,d-y) # flip in Y
t = w + d + w + d + raySW(x,y)
return (s,t) if t <= w+d+w+d else (s-w-w-d-d,t-w-w-d-d)
exit(-1)
xyfs=[input().split() for _ in range(n)]
def swap(xy):
x,y=xy
return (y,x)
stso=list(map(swap,list(map(toRange,xyfs))))
sts=sorted(stso)
def contains(s,t,r):
if t <= r <= s: return True
if t <= r+d+d+w+w <= s: return True
if t <= r-d-d-w-w <= s: return True
return False
def findMin(sts):
c = 0
r = w+w+d+d+w+w+d+d+w+w+d+d
for s,t in sts:
if not contains(s,t,r): # put a new clock at t
c += 1
r = s
return c
# stupid concat?
mins=[findMin(sts[i:] + sts[:i]) for i in range(n)]
print(min(mins))
```
| 102,845 |
Provide a correct Python 3 solution for this coding contest problem.
Example
Input
2 10 6
4 4 E
6 4 W
Output
2
"Correct Solution:
```
N, W, D = map(int, input().split())
def calc(x0, y0, dx, dy):
s = min(W - x0 if dx >= 0 else x0, D - y0 if dy >= 0 else y0)
x = x0 + dx*s; y = y0 + dy*s
assert x in [0, W] or y in [0, D], (x, y)
if y == 0:
return x
if x == W:
return W+y
if y == D:
return 2*W+D-x
return 2*W+2*D-y
S = []
for i in range(N):
x, y, f = input().split(); x = int(x); y = int(y)
if f == 'N':
t1 = calc(x, y, 1, 1)
t2 = calc(x, y, -1, 1)
elif f == 'E':
t1 = calc(x, y, 1, -1)
t2 = calc(x, y, 1, 1)
elif f == 'S':
t1 = calc(x, y, -1, -1)
t2 = calc(x, y, 1, -1)
else:
t1 = calc(x, y, -1, 1)
t2 = calc(x, y, -1, -1)
if t1 >= t2:
t1 -= 2*(W+D)
S.append((t1, t2))
S.sort(key=lambda x: x[1])
ans = N
INF = 10**9
for i in range(N):
r = 0
cur = -INF
base = 0
for j in range(N):
a, b = S[(i+j) % N]
if (i+j) % N == 0:
base += 2*(W+D)
if a + base <= cur:
continue
cur = b + base
r += 1
ans = min(r, ans)
print(ans)
```
| 102,846 |
Provide a correct Python 3 solution for this coding contest problem.
Nicholas Y. Alford was a cat lover. He had a garden in a village and kept many cats in his garden. The cats were so cute that people in the village also loved them.
One day, an evil witch visited the village. She envied the cats for being loved by everyone. She drove magical piles in his garden and enclosed the cats with magical fences running between the piles. She said βYour cats are shut away in the fences until they become ugly old cats.β like a curse and went away.
Nicholas tried to break the fences with a hummer, but the fences are impregnable against his effort. He went to a church and asked a priest help. The priest looked for how to destroy the magical fences in books and found they could be destroyed by holy water. The Required amount of the holy water to destroy a fence was proportional to the length of the fence. The holy water was, however, fairly expensive. So he decided to buy exactly the minimum amount of the holy water required to save all his cats. How much holy water would be required?
Input
The input has the following format:
N M
x1 y1 .
.
.
xN yN p1 q1
.
.
.
pM qM
The first line of the input contains two integers N (2 β€ N β€ 10000) and M (1 β€ M). N indicates the number of magical piles and M indicates the number of magical fences. The following N lines describe the coordinates of the piles. Each line contains two integers xi and yi (-10000 β€ xi, yi β€ 10000). The following M lines describe the both ends of the fences. Each line contains two integers pj and qj (1 β€ pj, qj β€ N). It indicates a fence runs between the pj-th pile and the qj-th pile.
You can assume the following:
* No Piles have the same coordinates.
* A pile doesnβt lie on the middle of fence.
* No Fences cross each other.
* There is at least one cat in each enclosed area.
* It is impossible to destroy a fence partially.
* A unit of holy water is required to destroy a unit length of magical fence.
Output
Output a line containing the minimum amount of the holy water required to save all his cats. Your program may output an arbitrary number of digits after the decimal point. However, the absolute error should be 0.001 or less.
Examples
Input
3 3
0 0
3 0
0 4
1 2
2 3
3 1
Output
3.000
Input
4 3
0 0
-100 0
100 0
0 100
1 2
1 3
1 4
Output
0.000
Input
6 7
2 0
6 0
8 2
6 3
0 5
1 7
1 2
2 3
3 4
4 1
5 1
5 4
5 6
Output
7.236
Input
6 6
0 0
0 1
1 0
30 0
0 40
30 40
1 2
2 3
3 1
4 5
5 6
6 4
Output
31.000
"Correct Solution:
```
class UnionFind:
def __init__(self, n):
self.data=[-1 for i in range(n)]
def root(self,x):
if self.data[x]<0:
return x
else:
self.data[x]=self.root(self.data[x])
return self.data[x]
def uni(self,x,y):
x=self.root(x)
y=self.root(y)
if(x==y):
return
if self.data[y]<self.data[x]:
x,y=y,x
self.data[x]+= self.data[y]
self.data[y] = x
def same(self,x,y):
return self.root(x)==self.root(y)
def size(self,x):
return -self.data[self.root(x)]
n,m=map(int,input().split())
uf=UnionFind(n)
cd=[]
g=[[] for i in range(n)]
sm=0.0
for i in range(n):
cd.append(tuple(map(int,input().split())))
f=0
for j in range(m):
p,q=map(int,input().split())
p,q=p-1,q-1
uf.uni(p,q)
f=p
g[p].append((-((cd[p][0]-cd[q][0])**2+(cd[p][1]-cd[q][1])**2)**0.50,q))
g[q].append((-((cd[p][0]-cd[q][0])**2+(cd[p][1]-cd[q][1])**2)**0.50,p))
sm+=((cd[p][0]-cd[q][0])**2+(cd[p][1]-cd[q][1])**2)**0.50
from heapq import heappush, heappop, heapify
used = [0 for i in range(n)]
ans = 0
for i in range(n):
if uf.data[i]>=0:
continue
que = [(c, w) for c, w in g[i]]
used[i] = 1
heapify(que)
while que:
cv, v = heappop(que)
if used[v]:
continue
used[v] = 1
ans -= cv
for c, w in g[v]:
if used[w]:
continue
heappush(que, (c, w))
print(sm-ans)
```
| 102,847 |
Provide a correct Python 3 solution for this coding contest problem.
Nicholas Y. Alford was a cat lover. He had a garden in a village and kept many cats in his garden. The cats were so cute that people in the village also loved them.
One day, an evil witch visited the village. She envied the cats for being loved by everyone. She drove magical piles in his garden and enclosed the cats with magical fences running between the piles. She said βYour cats are shut away in the fences until they become ugly old cats.β like a curse and went away.
Nicholas tried to break the fences with a hummer, but the fences are impregnable against his effort. He went to a church and asked a priest help. The priest looked for how to destroy the magical fences in books and found they could be destroyed by holy water. The Required amount of the holy water to destroy a fence was proportional to the length of the fence. The holy water was, however, fairly expensive. So he decided to buy exactly the minimum amount of the holy water required to save all his cats. How much holy water would be required?
Input
The input has the following format:
N M
x1 y1 .
.
.
xN yN p1 q1
.
.
.
pM qM
The first line of the input contains two integers N (2 β€ N β€ 10000) and M (1 β€ M). N indicates the number of magical piles and M indicates the number of magical fences. The following N lines describe the coordinates of the piles. Each line contains two integers xi and yi (-10000 β€ xi, yi β€ 10000). The following M lines describe the both ends of the fences. Each line contains two integers pj and qj (1 β€ pj, qj β€ N). It indicates a fence runs between the pj-th pile and the qj-th pile.
You can assume the following:
* No Piles have the same coordinates.
* A pile doesnβt lie on the middle of fence.
* No Fences cross each other.
* There is at least one cat in each enclosed area.
* It is impossible to destroy a fence partially.
* A unit of holy water is required to destroy a unit length of magical fence.
Output
Output a line containing the minimum amount of the holy water required to save all his cats. Your program may output an arbitrary number of digits after the decimal point. However, the absolute error should be 0.001 or less.
Examples
Input
3 3
0 0
3 0
0 4
1 2
2 3
3 1
Output
3.000
Input
4 3
0 0
-100 0
100 0
0 100
1 2
1 3
1 4
Output
0.000
Input
6 7
2 0
6 0
8 2
6 3
0 5
1 7
1 2
2 3
3 4
4 1
5 1
5 4
5 6
Output
7.236
Input
6 6
0 0
0 1
1 0
30 0
0 40
30 40
1 2
2 3
3 1
4 5
5 6
6 4
Output
31.000
"Correct Solution:
```
def dist(c1, c2):
return ((c1[0]-c2[0])**2+(c1[1]-c2[1])**2)**.5
def kruskal(edges, size):
uf = UnionFind(size)
edges = sorted(edges, key=lambda e: e[2])[::-1]
ret = 0
for u, v, weight in edges:
if not uf.same(u, v):
uf.unite(u, v)
ret += weight
return ret
class UnionFind:
def __init__(self, size):
self.parent = list(range(size))
self.rank = [0] * size
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def unite(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.rank[x] < self.rank[y]:
self.parent[x] = y
else:
self.parent[y] = x
if self.rank[x] == self.rank[y]:
self.rank[x] += 1
def same(self, x, y):
return self.find(x) == self.find(y)
N, M = map(int, input().split())
coords = [tuple(map(int, input().split())) for i in range(N)]
edges = []
for i in range(M):
p, q = map(lambda x: int(x) - 1, input().split())
edges.append((p, q, dist(coords[p], coords[q])))
print(sum(e[2] for e in edges) - kruskal(edges, N))
```
| 102,848 |
Provide a correct Python 3 solution for this coding contest problem.
Nicholas Y. Alford was a cat lover. He had a garden in a village and kept many cats in his garden. The cats were so cute that people in the village also loved them.
One day, an evil witch visited the village. She envied the cats for being loved by everyone. She drove magical piles in his garden and enclosed the cats with magical fences running between the piles. She said βYour cats are shut away in the fences until they become ugly old cats.β like a curse and went away.
Nicholas tried to break the fences with a hummer, but the fences are impregnable against his effort. He went to a church and asked a priest help. The priest looked for how to destroy the magical fences in books and found they could be destroyed by holy water. The Required amount of the holy water to destroy a fence was proportional to the length of the fence. The holy water was, however, fairly expensive. So he decided to buy exactly the minimum amount of the holy water required to save all his cats. How much holy water would be required?
Input
The input has the following format:
N M
x1 y1 .
.
.
xN yN p1 q1
.
.
.
pM qM
The first line of the input contains two integers N (2 β€ N β€ 10000) and M (1 β€ M). N indicates the number of magical piles and M indicates the number of magical fences. The following N lines describe the coordinates of the piles. Each line contains two integers xi and yi (-10000 β€ xi, yi β€ 10000). The following M lines describe the both ends of the fences. Each line contains two integers pj and qj (1 β€ pj, qj β€ N). It indicates a fence runs between the pj-th pile and the qj-th pile.
You can assume the following:
* No Piles have the same coordinates.
* A pile doesnβt lie on the middle of fence.
* No Fences cross each other.
* There is at least one cat in each enclosed area.
* It is impossible to destroy a fence partially.
* A unit of holy water is required to destroy a unit length of magical fence.
Output
Output a line containing the minimum amount of the holy water required to save all his cats. Your program may output an arbitrary number of digits after the decimal point. However, the absolute error should be 0.001 or less.
Examples
Input
3 3
0 0
3 0
0 4
1 2
2 3
3 1
Output
3.000
Input
4 3
0 0
-100 0
100 0
0 100
1 2
1 3
1 4
Output
0.000
Input
6 7
2 0
6 0
8 2
6 3
0 5
1 7
1 2
2 3
3 4
4 1
5 1
5 4
5 6
Output
7.236
Input
6 6
0 0
0 1
1 0
30 0
0 40
30 40
1 2
2 3
3 1
4 5
5 6
6 4
Output
31.000
"Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**13
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
class UnionFind:
def __init__(self, size):
self.table = [-1 for _ in range(size)]
def find(self, x):
if self.table[x] < 0:
return x
else:
self.table[x] = self.find(self.table[x])
return self.table[x]
def union(self, x, y):
s1 = self.find(x)
s2 = self.find(y)
if s1 != s2:
if self.table[s1] <= self.table[s2]:
self.table[s1] += self.table[s2]
self.table[s2] = s1
else:
self.table[s2] += self.table[s1]
self.table[s1] = s2
return True
return False
def subsetall(self):
a = []
for i in range(len(self.table)):
if self.table[i] < 0:
a.append((i, -self.table[i]))
return a
def ky2(a,b):
return pow(a[0]-b[0], 2) + pow(a[1]-b[1], 2)
def main():
rr = []
def f(n,m):
global fr
a = [LI() for _ in range(n)]
es = []
for _ in range(m):
b,c = LI_()
es.append([ky2(a[b],a[c]), b, c])
es.sort(reverse=True)
r = 0
uf = UnionFind(n)
for k,b,c in es:
if uf.union(b,c):
continue
r += pow(k,0.5)
return '{:0.3f}'.format(r)
while 1:
n,m = LI()
if n == 0 and m == 0:
break
rr.append(f(n,m))
break
# print('rr', rr[-1])
return '\n'.join(map(str,rr))
print(main())
```
| 102,849 |
Provide a correct Python 3 solution for this coding contest problem.
Nicholas Y. Alford was a cat lover. He had a garden in a village and kept many cats in his garden. The cats were so cute that people in the village also loved them.
One day, an evil witch visited the village. She envied the cats for being loved by everyone. She drove magical piles in his garden and enclosed the cats with magical fences running between the piles. She said βYour cats are shut away in the fences until they become ugly old cats.β like a curse and went away.
Nicholas tried to break the fences with a hummer, but the fences are impregnable against his effort. He went to a church and asked a priest help. The priest looked for how to destroy the magical fences in books and found they could be destroyed by holy water. The Required amount of the holy water to destroy a fence was proportional to the length of the fence. The holy water was, however, fairly expensive. So he decided to buy exactly the minimum amount of the holy water required to save all his cats. How much holy water would be required?
Input
The input has the following format:
N M
x1 y1 .
.
.
xN yN p1 q1
.
.
.
pM qM
The first line of the input contains two integers N (2 β€ N β€ 10000) and M (1 β€ M). N indicates the number of magical piles and M indicates the number of magical fences. The following N lines describe the coordinates of the piles. Each line contains two integers xi and yi (-10000 β€ xi, yi β€ 10000). The following M lines describe the both ends of the fences. Each line contains two integers pj and qj (1 β€ pj, qj β€ N). It indicates a fence runs between the pj-th pile and the qj-th pile.
You can assume the following:
* No Piles have the same coordinates.
* A pile doesnβt lie on the middle of fence.
* No Fences cross each other.
* There is at least one cat in each enclosed area.
* It is impossible to destroy a fence partially.
* A unit of holy water is required to destroy a unit length of magical fence.
Output
Output a line containing the minimum amount of the holy water required to save all his cats. Your program may output an arbitrary number of digits after the decimal point. However, the absolute error should be 0.001 or less.
Examples
Input
3 3
0 0
3 0
0 4
1 2
2 3
3 1
Output
3.000
Input
4 3
0 0
-100 0
100 0
0 100
1 2
1 3
1 4
Output
0.000
Input
6 7
2 0
6 0
8 2
6 3
0 5
1 7
1 2
2 3
3 4
4 1
5 1
5 4
5 6
Output
7.236
Input
6 6
0 0
0 1
1 0
30 0
0 40
30 40
1 2
2 3
3 1
4 5
5 6
6 4
Output
31.000
"Correct Solution:
```
class UnionFind:
def __init__(self, size):
self.table = [-1] * size
def find(self, x):
while self.table[x] >= 0:
x = self.table[x]
return x
def union(self, x, y):
x_root = self.find(x)
y_root = self.find(y)
if x_root != y_root:
if self.table[x_root] < self.table[y_root]:
self.table[x_root] += self.table[y_root]
self.table[y_root] = x_root
else:
self.table[y_root] += self.table[x_root]
self.table[x_root] = y_root
def isDisjoint(self, x, y):
return self.find(x) != self.find(y)
def solve():
import sys
file_input = sys.stdin
N, M = map(int, file_input.readline().split())
piles = [tuple(map(int, file_input.readline().split())) for i in range(N)]
fences = []
for i in range(M):
p, q = map(int, file_input.readline().split())
p -= 1
q -= 1
px, py = piles[p]
qx, qy = piles[q]
fence_len = ((px - qx) ** 2 + (py - qy) ** 2) ** 0.5
fences.append((fence_len, p, q))
fences.sort(reverse=True)
S = UnionFind(N)
fences_len = 0
for f_len, p1, p2 in fences:
if S.isDisjoint(p1, p2):
S.union(p1, p2)
else:
fences_len += f_len
print(fences_len)
solve()
```
| 102,850 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nicholas Y. Alford was a cat lover. He had a garden in a village and kept many cats in his garden. The cats were so cute that people in the village also loved them.
One day, an evil witch visited the village. She envied the cats for being loved by everyone. She drove magical piles in his garden and enclosed the cats with magical fences running between the piles. She said βYour cats are shut away in the fences until they become ugly old cats.β like a curse and went away.
Nicholas tried to break the fences with a hummer, but the fences are impregnable against his effort. He went to a church and asked a priest help. The priest looked for how to destroy the magical fences in books and found they could be destroyed by holy water. The Required amount of the holy water to destroy a fence was proportional to the length of the fence. The holy water was, however, fairly expensive. So he decided to buy exactly the minimum amount of the holy water required to save all his cats. How much holy water would be required?
Input
The input has the following format:
N M
x1 y1 .
.
.
xN yN p1 q1
.
.
.
pM qM
The first line of the input contains two integers N (2 β€ N β€ 10000) and M (1 β€ M). N indicates the number of magical piles and M indicates the number of magical fences. The following N lines describe the coordinates of the piles. Each line contains two integers xi and yi (-10000 β€ xi, yi β€ 10000). The following M lines describe the both ends of the fences. Each line contains two integers pj and qj (1 β€ pj, qj β€ N). It indicates a fence runs between the pj-th pile and the qj-th pile.
You can assume the following:
* No Piles have the same coordinates.
* A pile doesnβt lie on the middle of fence.
* No Fences cross each other.
* There is at least one cat in each enclosed area.
* It is impossible to destroy a fence partially.
* A unit of holy water is required to destroy a unit length of magical fence.
Output
Output a line containing the minimum amount of the holy water required to save all his cats. Your program may output an arbitrary number of digits after the decimal point. However, the absolute error should be 0.001 or less.
Examples
Input
3 3
0 0
3 0
0 4
1 2
2 3
3 1
Output
3.000
Input
4 3
0 0
-100 0
100 0
0 100
1 2
1 3
1 4
Output
0.000
Input
6 7
2 0
6 0
8 2
6 3
0 5
1 7
1 2
2 3
3 4
4 1
5 1
5 4
5 6
Output
7.236
Input
6 6
0 0
0 1
1 0
30 0
0 40
30 40
1 2
2 3
3 1
4 5
5 6
6 4
Output
31.000
Submitted Solution:
```
N,M = map(int,input().rstrip().split())
pileDict = {}
for i in range(N):
prow,pcol = map(lambda x: int(x),input().rstrip().split())
pileDict[i] = [prow,pcol]
edgeDict = {}
for i in range(M):
fs,fe = map(lambda x: int(x),input().rstrip().split())
edgeDict[i] = [fs,fe]
print("test")
```
No
| 102,851 |
Provide a correct Python 3 solution for this coding contest problem.
Problem Statement
You are now participating in the Summer Training Camp for Programming Contests with your friend Jiro, who is an enthusiast of the ramen chain SIRO. Since every SIRO restaurant has its own tasteful ramen, he wants to try them at as many different restaurants as possible in the night. He doesn't have plenty of time tonight, however, because he has to get up early in the morning tomorrow to join a training session. So he asked you to find the maximum number of different restaurants to which he would be able to go to eat ramen in the limited time.
There are $n$ railway stations in the city, which are numbered $1$ through $n$. The station $s$ is the nearest to the camp venue. $m$ pairs of stations are directly connected by the railway: you can move between the stations $a_i$ and $b_i$ in $c_i$ minutes in the both directions. Among the stations, there are $l$ stations where a SIRO restaurant is located nearby. There is at most one SIRO restaurant around each of the stations, and there are no restaurants near the station $s$. It takes $e_i$ minutes for Jiro to eat ramen at the restaurant near the station $j_i$.
It takes only a negligibly short time to go back and forth between a station and its nearby SIRO restaurant. You can also assume that Jiro doesn't have to wait for the ramen to be served in the restaurants.
Jiro is now at the station $s$ and have to come back to the station in $t$ minutes. How many different SIRO's can he taste?
Input
The input is a sequence of datasets. The number of the datasets does not exceed $100$. Each dataset is formatted as follows:
> $n$ $m$ $l$ $s$ $t$
> $a_1$ $b_1$ $c_1$
> :
> :
> $a_m$ $b_m$ $c_m$
> $j_1$ $e_1$
> :
> :
> $j_l$ $e_l$
The first line of each dataset contains five integers:
* $n$ for the number of stations,
* $m$ for the number of directly connected pairs of stations,
* $l$ for the number of SIRO restaurants,
* $s$ for the starting-point station, and
* $t$ for the time limit for Jiro.
Each of the following $m$ lines contains three integers:
* $a_i$ and $b_i$ for the connected stations, and
* $c_i$ for the time it takes to move between the two stations.
Each of the following $l$ lines contains two integers:
* $j_i$ for the station where a SIRO restaurant is located, and
* $e_i$ for the time it takes for Jiro to eat at the restaurant.
The end of the input is indicated by a line with five zeros, which is not included in the datasets.
The datasets satisfy the following constraints:
* $2 \le n \le 300$
* $1 \le m \le 5{,}000$
* $1 \le l \le 16$
* $1 \le s \le n$
* $1 \le t \le 100{,}000$
* $1 \le a_i, b_i \le n$
* $1 \le c_i \le 1{,}000$
* $1 \le j_i \le n$
* $1 \le e_i \le 15$
* $s \ne j_i$
* $j_i$'s are distinct.
* $a_i \ne b_i$
* $(a_i, b_i) \ne (a_j, b_j)$ and $(a_i, b_i) \ne (b_j, a_j)$ for any $i \ne j$
Note that there may be some stations not reachable from the starting point $s$.
Output
For each data set, output the maximum number of different restaurants where Jiro can go within the time limit.
Sample Input
2 1 1 1 10
1 2 3
2 4
2 1 1 1 9
1 2 3
2 4
4 2 2 4 50
1 2 5
3 4 5
2 15
3 15
4 6 3 1 29
1 2 20
3 2 10
4 1 5
3 1 5
2 4 3
3 4 4
2 1
4 5
3 3
0 0 0 0 0
Output for the Sample Input
1
0
1
3
Example
Input
2 1 1 1 10
1 2 3
2 4
2 1 1 1 9
1 2 3
2 4
4 2 2 4 50
1 2 5
3 4 5
2 15
3 15
4 6 3 1 29
1 2 20
3 2 10
4 1 5
3 1 5
2 4 3
3 4 4
2 1
4 5
3 3
0 0 0 0 0
Output
1
0
1
3
"Correct Solution:
```
from heapq import heappush, heappop
import sys
def main():
readline = sys.stdin.readline
write = sys.stdout.write
L2 = 1 << 16
bc = [0]*L2
for i in range(1, L2):
bc[i] = bc[i ^ (i & -i)] + 1
INF = 10**18
def solve():
N, M, L, s, T = map(int, readline().split())
if N == M == 0:
return False
G = [[] for i in range(N)]
for i in range(M):
a, b, c = map(int, readline().split()); a -= 1; b -= 1
G[a].append((b, c))
G[b].append((a, c))
def dijkstra(s):
dist = [INF]*N
dist[s] = 0
que = [(0, s)]
while que:
cost, v = heappop(que)
if dist[v] < cost:
continue
for w, d in G[v]:
if cost + d < dist[w]:
dist[w] = cost + d
heappush(que, (cost + d, w))
return dist
G0 = [[] for i in range(L)]
RS = []
BS = [0]*L
for i in range(L):
j, e = map(int, readline().split()); j -= 1
d0 = dijkstra(j)
for k, p in enumerate(RS):
v = d0[p]
if v+BS[k] <= T:
G0[i].append((k, v+BS[k], 1 << k))
if v+e <= T:
G0[k].append((i, v+e, 1 << i))
RS.append(j)
BS[i] = e
ans = 0
ds = dijkstra(s-1)
que = []
Q = [[{} for j in range(L)] for i in range(L+1)]
L2 = 1 << L
dw = [0]*L
for i in range(L):
d = ds[RS[i]]
r = d + BS[i]
dw[i] = T - d + 1
if r < dw[i]:
Q[1][i][1 << i] = r
ans = 1
for k in range(1, L):
qs = Q[k]
qs1 = Q[k+1]
if any(qs):
ans = k
for v in range(L):
qsv = qs[v]
for w, d, b in G0[v]:
dww = dw[w]
qs1w = qs1[w]
for state, cost in qsv.items():
if state & b:
continue
r = cost + d
if r < qs1w.get(state | b, dww):
qs1w[state | b] = r
if any(Q[L]):
ans = L
write("%d\n" % ans)
return True
while solve():
...
main()
```
| 102,852 |
Provide a correct Python 3 solution for this coding contest problem.
The goal of the 8 puzzle problem is to complete pieces on $3 \times 3$ cells where one of the cells is empty space.
In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below.
1 3 0
4 2 5
7 8 6
You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps).
1 2 3
4 5 6
7 8 0
Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.
Constraints
* There is a solution.
Input
The $3 \times 3$ integers denoting the pieces or space are given.
Output
Print the fewest steps in a line.
Example
Input
1 3 0
4 2 5
7 8 6
Output
4
"Correct Solution:
```
from collections import deque
N = 3
N2 = 9
dx = [-1, 0, 1, 0]
dy = [0, -1, 0, 1]
dirc = ['u', 'l', 'd', 'r']
class Puzzle:
def __init__(self, f=None, space=None, path=None):
if f is None:
self.f = []
else:
self.f = f
self.space = space
self.path = path
def __lt__(self, p):
for i in range(N2):
if self.f[i] == p.f[i]:
continue
return self.f[i] > p.f[i]
return False
def isTarget(p):
for i in range(N2):
if p.f[i] != (i + 1):
return False
return True
def bfs(s):
q = deque()
dic = {}
s.path = ''
q.append(s)
dic[tuple(s.f)] = True
while len(q) != 0:
u = q.popleft()
if isTarget(u):
return u.path
sx = u.space // N
sy = u.space % N
for r in range(4):
tx = sx + dx[r]
ty = sy + dy[r]
if tx < 0 or ty < 0 or tx >= N or ty >= N:
continue
v = Puzzle(u.f[:], u.space, u.path)
v.f[u.space], v.f[tx * N + ty] = v.f[tx * N + ty], v.f[u.space]
v.space = tx * N + ty
key = tuple(v.f)
if key not in dic:
dic[key] = True
v.path += dirc[r]
q.append(v)
return 'unsolvable'
if __name__ == '__main__':
p = Puzzle()
for i in range(N):
line = [int(v) for v in input().split()]
for j in range(N):
if line[j] == 0:
line[j] = N2
p.space = i * N + j
p.f.extend(line)
ans = bfs(p)
print(len(ans))
```
| 102,853 |
Provide a correct Python 3 solution for this coding contest problem.
The goal of the 8 puzzle problem is to complete pieces on $3 \times 3$ cells where one of the cells is empty space.
In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below.
1 3 0
4 2 5
7 8 6
You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps).
1 2 3
4 5 6
7 8 0
Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.
Constraints
* There is a solution.
Input
The $3 \times 3$ integers denoting the pieces or space are given.
Output
Print the fewest steps in a line.
Example
Input
1 3 0
4 2 5
7 8 6
Output
4
"Correct Solution:
```
from collections import deque
board = [int(s) for _ in range(3) for s in input().split()]
end = [1, 2, 3, 4, 5, 6, 7, 8, 0]
table = set()
def print_board(board):
for i in range(0, 9, 3):
print(*board[i:i + 3])
def swap(q, step_q, step, board):
key = tuple(board)
if key in table:
return
else:
table.add(key)
empty = board.index(0)
def _swap(q, step_q, step, board, k, s):
b = board.copy()
b[k], b[s] = b[s], b[k]
q.append(b)
step_q.append(step + 1)
if empty % 3 != 2:
_swap(q, step_q, step, board, empty, empty + 1)
if empty % 3 != 0:
_swap(q, step_q, step, board, empty, empty - 1)
if empty // 3 < 2:
_swap(q, step_q, step, board, empty, empty + 3)
if empty // 3 > 0:
_swap(q, step_q, step, board, empty, empty - 3)
q = deque([board])
step_q = deque([0])
# print_board(board)
while q[0] != end:
b = q.popleft()
step = step_q.popleft()
swap(q, step_q, step, b)
# print_board(q.popleft())
print(step_q.popleft())
```
| 102,854 |
Provide a correct Python 3 solution for this coding contest problem.
The goal of the 8 puzzle problem is to complete pieces on $3 \times 3$ cells where one of the cells is empty space.
In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below.
1 3 0
4 2 5
7 8 6
You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps).
1 2 3
4 5 6
7 8 0
Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.
Constraints
* There is a solution.
Input
The $3 \times 3$ integers denoting the pieces or space are given.
Output
Print the fewest steps in a line.
Example
Input
1 3 0
4 2 5
7 8 6
Output
4
"Correct Solution:
```
import sys, collections
input = lambda: sys.stdin.readline().rstrip()
sys.setrecursionlimit(10**7)
INF = 10**10
def I(): return int(input())
def F(): return float(input())
def SS(): 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 LSS(): return input().split()
def resolve():
S = []
SOLVED = (1, 2, 3, 4, 5, 6, 7, 8, 0)
for _ in range(3):
S += LI()
neighbor = (
(1, 3),
(0, 2, 4),
(1, 5),
(0, 4, 6),
(1, 3, 5, 7),
(2, 4, 8),
(3, 7),
(4, 6, 8),
(5, 7)
)
dist = dict()
que = collections.deque()
S = tuple(S)
que.append((S, S.index(0)))
dist[S] = 0
while que:
c, idx_0 = que.popleft()
if c == SOLVED:
break
for i in neighbor[idx_0]:
c_l = list(c)
c_l[idx_0], c_l[i] = c_l[i], c_l[idx_0]
n = tuple(c_l)
if not n in dist:
que.append((n, i))
dist[n] = dist[c] + 1
print(dist[SOLVED])
if __name__ == '__main__':
resolve()
```
| 102,855 |
Provide a correct Python 3 solution for this coding contest problem.
The goal of the 8 puzzle problem is to complete pieces on $3 \times 3$ cells where one of the cells is empty space.
In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below.
1 3 0
4 2 5
7 8 6
You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps).
1 2 3
4 5 6
7 8 0
Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.
Constraints
* There is a solution.
Input
The $3 \times 3$ integers denoting the pieces or space are given.
Output
Print the fewest steps in a line.
Example
Input
1 3 0
4 2 5
7 8 6
Output
4
"Correct Solution:
```
goal = ((1, 2, 3), (4, 5, 6), (7, 8, 0))
parents = {}
total = {}
flag = True
initial = []
position = []
for i in range(3):
a, b, c = map(int, input().split())
if a == 0:
position.extend([i, 0])
elif b == 0:
position.extend([i, 1])
elif c == 0:
position.extend([i, 2])
initial.append( (a, b, c) )
parents[tuple(initial)] = position
total[tuple(initial)] = 1
count = 0
if tuple(initial) == goal:
flag = False
while flag:
count += 1
children = {}
for par_key in parents.keys():
position = parents[par_key]
if position[0] < 2:
child = [list(par_key[0]), list(par_key[1]), list(par_key[2])]
child[position[0]][position[1]] = child[position[0]+1][position[1]]
child[position[0]+1][position[1]] = 0
child_tuple = (tuple(child[0]), tuple(child[1]), tuple(child[2]))
if child_tuple == goal:
flag = False
break
elif child_tuple not in total:
children[child_tuple] = [position[0]+1, position[1]]
total[child_tuple] = 1
if position[0] > 0:
child = [list(par_key[0]), list(par_key[1]), list(par_key[2])]
child[position[0]][position[1]] = child[position[0]-1][position[1]]
child[position[0]-1][position[1]] = 0
child_tuple = (tuple(child[0]), tuple(child[1]), tuple(child[2]))
if child_tuple == goal:
flag = False
break
elif child_tuple not in total:
children[child_tuple] = [position[0]-1, position[1]]
total[child_tuple] = 1
if position[1] < 2:
child = [list(par_key[0]), list(par_key[1]), list(par_key[2])]
child[position[0]][position[1]] = child[position[0]][position[1]+1]
child[position[0]][position[1]+1] = 0
child_tuple = (tuple(child[0]), tuple(child[1]), tuple(child[2]))
if child_tuple == goal:
flag = False
break
elif child_tuple not in total:
children[child_tuple] = [position[0], position[1]+1]
total[child_tuple] = 1
if position[1] > 0:
child = [list(par_key[0]), list(par_key[1]), list(par_key[2])]
child[position[0]][position[1]] = child[position[0]][position[1]-1]
child[position[0]][position[1]-1] = 0
child_tuple = (tuple(child[0]), tuple(child[1]), tuple(child[2]))
if child_tuple == goal:
flag = False
break
elif child_tuple not in total:
children[child_tuple] = [position[0], position[1]-1]
total[child_tuple] = 1
parents = children
print(count)
```
| 102,856 |
Provide a correct Python 3 solution for this coding contest problem.
The goal of the 8 puzzle problem is to complete pieces on $3 \times 3$ cells where one of the cells is empty space.
In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below.
1 3 0
4 2 5
7 8 6
You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps).
1 2 3
4 5 6
7 8 0
Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.
Constraints
* There is a solution.
Input
The $3 \times 3$ integers denoting the pieces or space are given.
Output
Print the fewest steps in a line.
Example
Input
1 3 0
4 2 5
7 8 6
Output
4
"Correct Solution:
```
import sys;
import heapq
def iterative(i,j):
q = []
heapq.heappush(q,(sumcost,(0,i,j,0,puz)))
global finding
while len(q):
cost, items = heapq.heappop(q)
c_depth = items[0]
_i = items[1]
_j = items[2]
prev_move = items[3]
c_puz = items[4]
_sum_cost = cost - c_depth
if(_sum_cost == 0):
finding = 1
print(c_depth)
break
if(cost > depth):
continue
c_cost = HS(_i,_j,c_puz[_i*3+_j])
if(_i != 0 and prev_move != 1):
swap_puz = swapPuz(c_puz[0:],_i,_j,_i-1,_j)
n_cost = cost+1+checkCost(c_cost,HS(_i-1,_j,c_puz[(_i-1)*3+_j]),HS(_i,_j,swap_puz[_i*3+_j]),HS(_i-1,_j,swap_puz[(_i-1)*3+_j]))
if(n_cost <= depth):
heapq.heappush(q,(n_cost,(c_depth+1,_i-1,_j,2,swap_puz)))
if(_i != 2 and prev_move != 2):
swap_puz = swapPuz(c_puz[0:],_i,_j,_i+1,_j)
n_cost = cost+1+checkCost(c_cost,HS(_i+1,_j,c_puz[(_i+1)*3+_j]),HS(_i,_j,swap_puz[_i*3+_j]),HS(_i+1,_j,swap_puz[(_i+1)*3+_j]))
if(n_cost <= depth):
heapq.heappush(q,(n_cost,(c_depth+1,_i+1,_j,1,swap_puz,)))
if(_j != 0 and prev_move != 3):
swap_puz = swapPuz(c_puz[0:],_i,_j,_i,_j-1)
n_cost = cost+1+checkCost(c_cost,HS(_i,_j-1,c_puz[_i*3+_j-1]),HS(_i,_j,swap_puz[_i*3+_j]),HS(_i,_j-1,swap_puz[_i*3+_j-1]))
if(n_cost <= depth):
heapq.heappush(q,(n_cost,(c_depth+1,_i,_j-1,4,swap_puz)))
if(_j != 2 and prev_move != 4):
swap_puz = swapPuz(c_puz[0:],_i,_j,_i,_j+1)
n_cost = cost+1+checkCost(c_cost,HS(_i,_j+1,c_puz[_i*3+_j+1]),HS(_i,_j,swap_puz[_i*3+_j]),HS(_i,_j+1,swap_puz[_i*3+_j+1]))
if(n_cost <= depth):
heapq.heappush(q,(n_cost,(c_depth+1,_i,_j+1,3,swap_puz)))
def checkCost(c_cost,m_cost,c2_cost,m2_cost):
return c2_cost - c_cost + m2_cost - m_cost
def sumCost(puz):
value = 0
for i in range(3):
value += HS(i,0,puz[i*3])
value += HS(i,1,puz[i*3+1])
value += HS(i,2,puz[i*3+2])
return value
def HS(i,j,num):
if(num != 0):
k = num-1
else:
k = 8
ki = (int)(k/3)
kj = k - ki*3
value = abs(i-ki)+abs(j-kj)
return value
def swapPuz(c_puz, i, j, i2,j2):
c_puz[i2*3+j2],c_puz[i*3+j] = c_puz[i*3+j],c_puz[i2*3+j2]
return c_puz
correctPuz = [i+1 for i in range(9)]
correctPuz[8] = 0
puz = [0 for i in range(9)]
i_start = 0
j_start = 0
for i in range(3):
puz[i*3],puz[i*3+1],puz[i*3+2] = map(int, input().split());
if(puz[i*3] == 0):
i_start,j_start = i,0
elif(puz[i*3+1] == 0):
i_start,j_start = i,1
elif(puz[i*3+2] == 0):
i_start,j_start = i,2
sumcost = sumCost(puz)
finding = 0
depth = 0
while True:
if(finding == 1):
break
iterative(i_start,j_start)
depth+=1
```
| 102,857 |
Provide a correct Python 3 solution for this coding contest problem.
The goal of the 8 puzzle problem is to complete pieces on $3 \times 3$ cells where one of the cells is empty space.
In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below.
1 3 0
4 2 5
7 8 6
You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps).
1 2 3
4 5 6
7 8 0
Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.
Constraints
* There is a solution.
Input
The $3 \times 3$ integers denoting the pieces or space are given.
Output
Print the fewest steps in a line.
Example
Input
1 3 0
4 2 5
7 8 6
Output
4
"Correct Solution:
```
adjacent = (
(1, 3), # 0
(0, 2, 4), # 1
(1, 5), # 2
(0, 4, 6), # 3
(1, 3, 5, 7), # 4
(2, 4, 8), # 5
(3, 7), # 6
(4, 6, 8), # 7
(5, 7) # 8
)
GOAL = [1, 2, 3, 4, 5, 6, 7, 8, 0]
# Bidirectional search using breadth-first search
def solve(start):
if start == GOAL:
return 0
# 0: forward, 1: backward
generated_state = {tuple(start): 0, tuple(GOAL): 1}
step = {tuple(start): 0, tuple(GOAL): 0}
s = 0
state1 = [(start, 0), (GOAL, 1)]
while state1:
state2 = state1[:]
state1 = []
s += 1
for s2, d in state2:
i = s2.index(0)
for p in adjacent[i]:
s1 = s2[:]
s1[i], s1[p] = s1[p], 0
key = tuple(s1)
if key in generated_state:
if generated_state[key] != d:
return s + step[key]
continue
state1.append((s1, d))
generated_state[key] = d
step[key] = s
import sys
start = list(map(int, sys.stdin.read().split()))
print(solve(start))
```
| 102,858 |
Provide a correct Python 3 solution for this coding contest problem.
The goal of the 8 puzzle problem is to complete pieces on $3 \times 3$ cells where one of the cells is empty space.
In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below.
1 3 0
4 2 5
7 8 6
You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps).
1 2 3
4 5 6
7 8 0
Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.
Constraints
* There is a solution.
Input
The $3 \times 3$ integers denoting the pieces or space are given.
Output
Print the fewest steps in a line.
Example
Input
1 3 0
4 2 5
7 8 6
Output
4
"Correct Solution:
```
N = 3
#f = [input().split() for _ in range(3)]
f = input().split()
f += input().split()
f += input().split()
dd = [[-1, 0], [0, -1], [1, 0], [0, 1]]
Q = [[f, f.index("0"), 0]]
#T = {f: True}
T = set(f)
while len(Q) > 0:
board = Q.pop(0)
if board[0] == ["1", "2", "3", "4", "5", "6", "7", "8", "0"]:
break
x, y = int(board[1]/N), board[1]%N
for dx, dy in dd:
tx, ty = x+dx, y+dy
if tx<0 or ty<0 or tx>=N or ty>=N:
continue
new = board[:]
n1, n2 = board[1], tx*N+ty
new[1] = n2
# swap
if n1 > n2:
n1, n2 = n2, n1
# swaped string
new[0] = new[0][0:n1] + list(new[0][n2]) + new[0][n1+1:n2] + list(new[0][n1]) + new[0][n2+1:]
hashstr = "".join(new[0])
if hashstr not in T:
#T[new[0]] = True
T.add(hashstr)
new[2] += 1
Q.append(new)
print(board[2])
```
| 102,859 |
Provide a correct Python 3 solution for this coding contest problem.
The goal of the 8 puzzle problem is to complete pieces on $3 \times 3$ cells where one of the cells is empty space.
In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below.
1 3 0
4 2 5
7 8 6
You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps).
1 2 3
4 5 6
7 8 0
Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.
Constraints
* There is a solution.
Input
The $3 \times 3$ integers denoting the pieces or space are given.
Output
Print the fewest steps in a line.
Example
Input
1 3 0
4 2 5
7 8 6
Output
4
"Correct Solution:
```
import queue
adjacent=((1,3), (0,2,4), (1,5), (0,4,6), (1,3,5,7), (2,4,8), (3,7), (4,6,8), (5,7))
class State:
def __init__(self, board, space, prev):
self.board = board
self.space = space
self.prev = prev
def bf_search(start, GOAL):
q = queue.Queue()
q.put(State(start, start.index(0), None))
table = {}
table[tuple(start)] = True
while not q.empty():
a = q.get()
for x in adjacent[a.space]:
b = a.board[:]
b[a.space] = b[x]
b[x] = 0
key = tuple(b)
if key in table: continue
c = State(b,x,a)
if b == GOAL:
return print_answer(c)
q.put(c)
table[key] = True
cnt = -1
def print_answer(x):
global cnt
if x is not None:
cnt += 1
print_answer(x.prev)
return str(cnt)
GOAL = [1,2,3,4,5,6,7,8,0]
start = []
for i in range(3):
x,y,z = map(int, input().split())
start += [x,y,z]
if start == GOAL:
print("0")
else:
print(bf_search(start, GOAL))
```
| 102,860 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The goal of the 8 puzzle problem is to complete pieces on $3 \times 3$ cells where one of the cells is empty space.
In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below.
1 3 0
4 2 5
7 8 6
You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps).
1 2 3
4 5 6
7 8 0
Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.
Constraints
* There is a solution.
Input
The $3 \times 3$ integers denoting the pieces or space are given.
Output
Print the fewest steps in a line.
Example
Input
1 3 0
4 2 5
7 8 6
Output
4
Submitted Solution:
```
# 8 Puzzle
import copy
[N, d] = [3, 0]
start = []
goal = [[i + j*N for i in range(1, N + 1)] for j in range(N)]
goal[2][2] = 0
for i in range(N):
start.append(list(map(int, input().split())))
def manhattan(value, pairs):
h = 0
if value == 1:
h = (pairs[0] + pairs[1])
if value == 2:
h = (pairs[0] + abs(pairs[1] - 1))
if value == 3:
h = (pairs[0] + abs(pairs[1] - 2))
if value == 4:
h = (abs(pairs[0] - 1) + pairs[1])
if value == 5:
h = (abs(pairs[0] - 1) + abs(pairs[1] - 1))
if value == 6:
h = (abs(pairs[0] - 1) + abs(pairs[1] - 2))
if value == 7:
h = (abs(pairs[0] - 2) + pairs[1])
if value == 8:
h = (abs(pairs[0] - 2) + abs(pairs[1] - 1))
return h
s_h = 0
for i in range(N):
for j in range(N):
s_h += manhattan(start[i][j], [i, j])
for i in range(N):
check = start[i].count(0)
if check != 0:
[s_r, s_c] = [i, start[i].index(0)]
break
if i == 3:
print("Error")
while True:
d += 1
flag = 0
queue = [[s_h, start, 0, [s_r, s_c], flag]]
while len(queue) != 0:
short_n = queue.pop(0)
h = short_n[0] - short_n[2]
state = short_n[1]
g = short_n[2]
[r, c] = short_n[3]
flag = short_n[4]
if h == 0:
print(short_n[2])
break
if r - 1 >= 0 and flag != 3:
temp = copy.deepcopy(state)
h = short_n[0] - short_n[2] - manhattan(temp[r - 1][c], [r - 1, c]) + manhattan(temp[r - 1][c], [r, c])
[temp[r][c], temp[r - 1][c]] = [temp[r - 1][c], temp[r][c]]
if g + 1 + h <= d:
queue.append([h + g + 1, temp, g + 1, [r - 1, c], 1])
if c + 1 < N and flag != 4:
temp = copy.deepcopy(state)
h = short_n[0] - short_n[2] - manhattan(temp[r][c + 1], [r, c + 1]) + manhattan(temp[r][c + 1], [r, c])
[temp[r][c], temp[r][c + 1]] = [temp[r][c + 1], temp[r][c]]
if g + 1 + h <= d:
queue.append([h + g + 1, temp, g + 1, [r, c + 1], 2])
if r + 1 < N and flag != 1:
temp = copy.deepcopy(state)
h = short_n[0] - short_n[2] - manhattan(temp[r + 1][c], [r + 1, c]) + manhattan(temp[r + 1][c], [r, c])
[temp[r][c], temp[r + 1][c]] = [temp[r + 1][c], temp[r][c]]
if g + 1 + h <= d:
queue.append([h + g + 1, temp, g + 1, [r + 1, c], 3])
if c - 1 >= 0 and flag != 2:
temp = copy.deepcopy(state)
h = short_n[0] - short_n[2] - manhattan(temp[r][c - 1], [r, c - 1]) + manhattan(temp[r][c - 1], [r, c])
[temp[r][c], temp[r][c - 1]] = [temp[r][c - 1], temp[r][c]]
if g + 1 + h <= d:
queue.append([h + g + 1, temp, g + 1, [r, c - 1], 4])
queue.sort(key = lambda data:data[0])
queue.sort(key = lambda data:data[2], reverse = True)
data = []
g_data = []
if state == goal:
break
```
Yes
| 102,861 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The goal of the 8 puzzle problem is to complete pieces on $3 \times 3$ cells where one of the cells is empty space.
In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below.
1 3 0
4 2 5
7 8 6
You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps).
1 2 3
4 5 6
7 8 0
Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.
Constraints
* There is a solution.
Input
The $3 \times 3$ integers denoting the pieces or space are given.
Output
Print the fewest steps in a line.
Example
Input
1 3 0
4 2 5
7 8 6
Output
4
Submitted Solution:
```
import sys
import queue
N = 3
f= ''.join(sys.stdin.readline().split())
f+= ''.join(sys.stdin.readline().split())
f+= ''.join(sys.stdin.readline().split())
dd = [[-1, 0], [0, -1], [1, 0], [0, 1]]
Q = queue.Queue()
V = dict()
Q.put([f,f.index('0'),0])
V[f] = True
while not Q.empty():
u = Q.get()
if u[0] == '123456780': break
sx, sy = u[1]//N, u[1]%N
for dx, dy in dd:
tx, ty = sx+dx, sy+dy
if tx<0 or ty<0 or tx>=N or ty>=N: continue
v = u[:]
n1, n2 = u[1], tx*N+ty
v[1] = n2
if n1>n2: n1, n2 = n2, n1
v[0] = v[0][0:n1]+v[0][n2]+v[0][n1+1:n2]+v[0][n1]+v[0][n2+1:]
if not V.get(v[0], False):
V[v[0]] = True
v[2] += 1
Q.put(v)
print(u[2])
```
Yes
| 102,862 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The goal of the 8 puzzle problem is to complete pieces on $3 \times 3$ cells where one of the cells is empty space.
In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below.
1 3 0
4 2 5
7 8 6
You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps).
1 2 3
4 5 6
7 8 0
Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.
Constraints
* There is a solution.
Input
The $3 \times 3$ integers denoting the pieces or space are given.
Output
Print the fewest steps in a line.
Example
Input
1 3 0
4 2 5
7 8 6
Output
4
Submitted Solution:
```
from collections import deque
N = 3
m = {8: {7, 5}, 7: {8, 6, 4}, 6: {7, 3}, 5: {8, 4, 2}, 4: {7, 5, 3, 1}, 3: {6, 4, 0}, 2: {5, 1}, 1: {4, 2, 0},
0: {3, 1}}
goal = 123456780
def g(i, j, a):
t = a // (10 ** j) % 10
return a - t * (10 ** j) + t * (10 ** i)
def solve():
MAP = "".join(input().replace(" ", "") for _ in range(N))
start = 8 - MAP.find("0")
MAP = int(MAP)
if MAP == goal:
return 0
dp = deque([(0, start, MAP)])
LOG = {MAP}
while dp:
cnt, yx, M = dp.popleft()
if M == goal:
return cnt
cnt += 1
for nyx in m[yx]:
CM = g(yx, nyx, M)
if not CM in LOG:
dp.append((cnt, nyx, CM))
LOG.add(CM)
def MAIN():
print(solve())
MAIN()
```
Yes
| 102,863 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The goal of the 8 puzzle problem is to complete pieces on $3 \times 3$ cells where one of the cells is empty space.
In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below.
1 3 0
4 2 5
7 8 6
You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps).
1 2 3
4 5 6
7 8 0
Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.
Constraints
* There is a solution.
Input
The $3 \times 3$ integers denoting the pieces or space are given.
Output
Print the fewest steps in a line.
Example
Input
1 3 0
4 2 5
7 8 6
Output
4
Submitted Solution:
```
from collections import deque, OrderedDict
class Puzzle:
def __init__(self, field=None, path=''):
self.f = field
self.space = None
for i in range(9):
if self.f[i] == 9:
self.space = i
self.path = path
def __lt__(self, pzl): # <
for i in range(9):
if self.f[i] == pzl.f[i]:
continue
return self.f[i] > pzl.f[i]
return False
def __gt__(self, pzl): # >
for i in range(9):
if self.f[i] == pzl.f[i]:
continue
return self.f[i] < pzl.f[i]
return False
dx = [-1, 0, 1, 0]
dy = [0, -1, 0, 1]
dir = ['u', 'l', 'd', 'r']
def is_target(pzl):
for i in range(9):
if pzl.f[i] != i+1:
return False
return True
def bfs(pzl):
queue = deque([])
V = {}
pzl.path = ''
queue.append(pzl)
V[str(pzl.f)] = True
if is_target(pzl): return pzl.path
while len(queue) != 0:
u = queue.popleft()
sx, sy = u.space//3, u.space%3
for r in range(4):
tx, ty = sx + dx[r], sy + dy[r]
if tx < 0 or ty < 0 or tx >= 3 or ty >= 3:
continue
v = Puzzle(field=[u.f[i] for i in range(9)], path=u.path)
v.f[u.space], v.f[tx*3+ty] = v.f[tx*3+ty], v.f[u.space]
v.space = tx*3 + ty
if str(v.f) not in V:
V[str(v.f)] = True
v.path += dir[r]
if is_target(v): return v.path
queue.append(v)
return 'unsolvable'
field = []
for i in range(3):
field.extend(list(map(int, input().split(' '))))
for i in range(9):
if field[i] == 0: field[i] = 9
pzl = Puzzle(field=field)
ans= bfs(pzl)
print(len(ans))
```
Yes
| 102,864 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The goal of the 8 puzzle problem is to complete pieces on $3 \times 3$ cells where one of the cells is empty space.
In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below.
1 3 0
4 2 5
7 8 6
You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps).
1 2 3
4 5 6
7 8 0
Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.
Constraints
* There is a solution.
Input
The $3 \times 3$ integers denoting the pieces or space are given.
Output
Print the fewest steps in a line.
Example
Input
1 3 0
4 2 5
7 8 6
Output
4
Submitted Solution:
```
# 8 Puzzle
import copy
z = 0
[N, d] = [3, 0]
check_flag = [[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
[2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1],
[3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2],
[4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3],
[3, 2, 1, 4, 3, 2, 1, 4, 3, 2, 1, 4],
[2, 1, 4, 3, 2, 1, 4, 3, 2, 1, 4, 3],
[1, 4, 3, 2, 1, 4, 3, 2, 1, 4, 3, 2],
[4, 3, 2, 1, 4, 3, 2, 1, 4, 3, 2, 1]]
start = []
goal = [[i + j*N for i in range(1, N + 1)] for j in range(N)]
goal[2][2] = 0
for i in range(N):
start.append(list(map(int, input().split())))
def manhattan(value, pairs):
h = 0
if value == 1:
h = (pairs[0] + pairs[1])
if value == 2:
h = (pairs[0] + abs(pairs[1] - 1))
if value == 3:
h = (pairs[0] + abs(pairs[1] - 2))
if value == 4:
h = (abs(pairs[0] - 1) + pairs[1])
if value == 5:
h = (abs(pairs[0] - 1) + abs(pairs[1] - 1))
if value == 6:
h = (abs(pairs[0] - 1) + abs(pairs[1] - 2))
if value == 7:
h = (abs(pairs[0] - 2) + pairs[1])
if value == 8:
h = (abs(pairs[0] - 2) + abs(pairs[1] - 1))
return h
def flag_array(flag, input):
flag.pop(0)
flag.append(input)
return flag
s_h = 0
for i in range(N):
for j in range(N):
s_h += manhattan(start[i][j], [i, j])
# print(s_h)
for i in range(N):
check = start[i].count(0)
if check != 0:
[s_r, s_c] = [i, start[i].index(0)]
break
if i == 3:
print("Error")
while True:
d += 1
queue = []
flag = [0 for i in range(12)]
queue.append([s_h, start, 0, [s_r, s_c], flag])
#while True:
while len(queue) != 0:
#print("Q: ", len(queue), "depth: ", d)
short_n = queue.pop(0)
h = short_n[0] - short_n[2]
state = short_n[1]
g = short_n[2]
[r, c] = short_n[3]
flag = short_n[4]
print("left_Q: ", len(queue), "depth: ", d, "h: ", h, "g: ", g, "state: ", state, "g+h: ", short_n[0], "flag: ", flag[len(flag) - 1])
#print("left_Q: ", len(queue), "depth: ", d, "h: ", h, "g: ", g, "flag: ", flag, "g+h: ", short_n[0])
#if d == 1:
#print(short_n[0])
#print(state)
#print(g)
if h == 0:
print(short_n[2])
print(z)
break
"""
if flag in check_flag:
z += 1
continue
"""
if r - 1 >= 0 and flag[len(flag) - 1] != 3:
[temp, temp_array] = [copy.deepcopy(state), flag[:]]
h = short_n[0] - short_n[2] - manhattan(temp[r - 1][c], [r - 1, c]) + manhattan(temp[r - 1][c], [r, c])
[temp[r][c], temp[r - 1][c]] = [temp[r - 1][c], temp[r][c]]
#if temp[r][c] != goal[r][c]:
#[r, c] = [r - 1, c]
#if temp
#h = manhattan(temp)
#print("1: ", h, temp)
if g + 1 + h <= d:
queue.append([h + g + 1, temp, g + 1, [r - 1, c], flag_array(temp_array, 1)])
if c + 1 < N and flag[len(flag) - 1] != 4:
#print("2: ")
[temp, temp_array] = [copy.deepcopy(state), flag[:]]
#temp_array = copy.deepcopy(flag)
h = short_n[0] - short_n[2] - manhattan(temp[r][c + 1], [r, c + 1]) + manhattan(temp[r][c + 1], [r, c])
[temp[r][c], temp[r][c + 1]] = [temp[r][c + 1], temp[r][c]]
#queue.append(calculate(temp, g + 1))
#print("2: ", h, temp)
if g + 1 + h <= d:
queue.append([h + g + 1, temp, g + 1, [r, c + 1], flag_array(temp_array, 2)])
if r + 1 < N and flag[len(flag) - 1] != 1:
#print("3: ")
[temp, temp_array] = [copy.deepcopy(state), flag[:]]
#temp_array = copy.deepcopy(flag)
h = short_n[0] - short_n[2] - manhattan(temp[r + 1][c], [r + 1, c]) + manhattan(temp[r + 1][c], [r, c])
[temp[r][c], temp[r + 1][c]] = [temp[r + 1][c], temp[r][c]]
#queue.append(calculate(temp, g + 1))
#print("3: ", h, temp)
if g + 1 + h <= d:
queue.append([h + g + 1, temp, g + 1, [r + 1, c], flag_array(temp_array, 3)])
if c - 1 >= 0 and flag[len(flag) - 1] != 2:
#print("4: ")
[temp, temp_array] = [copy.deepcopy(state), flag[:]]
h = short_n[0] - short_n[2] - manhattan(temp[r][c - 1], [r, c - 1]) + manhattan(temp[r][c - 1], [r, c])
[temp[r][c], temp[r][c - 1]] = [temp[r][c - 1], temp[r][c]]
if g + 1 + h <= d:
queue.append([h + g + 1, temp, g + 1, [r, c - 1], flag_array(temp_array, 4)])
queue.sort(key = lambda data:data[0])
queue.sort(key = lambda data:data[2], reverse = True)
data = []
g_data = []
#print(queue)
"""
for i in range(len(queue)):
data.append(str(queue[i][0]))
g_data.append(str(queue[i][2]))
#print(queue[i])
print("g+h: ",' '.join(data))
print("g: ",' '.join(g_data))
"""
#if d == 1:
#print(len(queue))
if state == goal:
break
```
No
| 102,865 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The goal of the 8 puzzle problem is to complete pieces on $3 \times 3$ cells where one of the cells is empty space.
In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below.
1 3 0
4 2 5
7 8 6
You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps).
1 2 3
4 5 6
7 8 0
Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.
Constraints
* There is a solution.
Input
The $3 \times 3$ integers denoting the pieces or space are given.
Output
Print the fewest steps in a line.
Example
Input
1 3 0
4 2 5
7 8 6
Output
4
Submitted Solution:
```
import sys
import queue
N = 3
f= ''.join(sys.stdin.readline().split())
f+= ''.join(sys.stdin.readline().split())
f+= ''.join(sys.stdin.readline().split())
dd = [[-1, 0], [0, -1], [1, 0], [0, 1]]
Q = queue.Queue()
V = dict()
Q.put([f,f.index('0'),0])
V[f] = True
while not Q.empty():
u = Q.get()
if u[0] == '123456780': break
sx, sy = u[1]//N, u[1]%N
for dx, dy in dd:
tx, ty = sx+dx, sy+dy
if tx<0 or ty<0 or tx>=N or ty>=N: continue
v = u[:]
n1, n2 = u[1], tx*N+ty
v[1] = n2
if n1>n2: n1, n2 = n2, n1
v[0] = v[0][0:n1]+v[0][n2]+v[0][n1+1:n2]+v[0][n1]+v[0][n2+1:]
if not V.get(v[0], False):
V[v[0]] = True
v[2] += 1 # dir[r]
Q.put(v)
print(u[2])
```
No
| 102,866 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The goal of the 8 puzzle problem is to complete pieces on $3 \times 3$ cells where one of the cells is empty space.
In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below.
1 3 0
4 2 5
7 8 6
You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps).
1 2 3
4 5 6
7 8 0
Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.
Constraints
* There is a solution.
Input
The $3 \times 3$ integers denoting the pieces or space are given.
Output
Print the fewest steps in a line.
Example
Input
1 3 0
4 2 5
7 8 6
Output
4
Submitted Solution:
```
import sys;
import queue;
def iterative(i,j,c_depth,c_puz):
if(puzzleCheck(c_puz)):
global finding
finding = 1
print(c_depth)
if(finding == 1 or (c_depth+HS(c_puz)) > depth or (c_depth+simpleHS(c_puz)) > depth):
return
if(i != 0 and finding != 1):
iterative(i-1,j,c_depth+1,swapPuz(c_puz[0:],i,j,i-1,j))
if(i != 2 and finding != 1):
iterative(i+1,j,c_depth+1,swapPuz(c_puz[0:],i,j,i+1,j))
if(j != 0 and finding != 1):
iterative(i,j-1,c_depth+1,swapPuz(c_puz[0:],i,j,i,j-1))
if(j != 2 and finding != 1):
iterative(i,j+1,c_depth+1,swapPuz(c_puz[0:],i,j,i,j+1))
def simpleHS(c_puz):
count = 0
for i in range(len(correctPuz)):
if(correctPuz[i] != c_puz[i]):
count+=1
return count
def HS(c_puz):
value = 0
for i in range(len(c_puz)):
k = correctPuz.index(c_puz[i])
_i = (int)(i/3)
_j = i - _i
ki = (int)(k/3)
kj = k - ki
value = abs(_i-ki)+abs(_j-kj)
return value
def swapPuz(c_puz, i, j, i2,j2):
swap = c_puz[i*3+j]
c_puz[i*3+j] = c_puz[i2*3+j2]
c_puz[i2*3+j2] = swap
return c_puz
def puzzleCheck(c_puz):
if(c_puz[8] == 0):
for i in range(len(correctPuz)):
if(correctPuz[i] != c_puz[i]):
return False
return True
return False
correctPuz = [i+1 for i in range(9)]
correctPuz[8] = 0
puz = [0 for i in range(9)]
i_start = 0
j_start = 0
for i in range(3):
puz[i*3],puz[i*3+1],puz[i*3+2] = map(int, input().split());
if(puz[i*3] == 0):
i_start,j_start = i,0
elif(puz[i*3+1] == 0):
i_start,j_start = i,1
elif(puz[i*3+2] == 0):
i_start,j_start = i,2
finding = 0
depth = 0
while True:
if(finding == 1):
break
iterative(i_start,j_start,0,puz[0:])
depth+=1
```
No
| 102,867 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The goal of the 8 puzzle problem is to complete pieces on $3 \times 3$ cells where one of the cells is empty space.
In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below.
1 3 0
4 2 5
7 8 6
You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps).
1 2 3
4 5 6
7 8 0
Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.
Constraints
* There is a solution.
Input
The $3 \times 3$ integers denoting the pieces or space are given.
Output
Print the fewest steps in a line.
Example
Input
1 3 0
4 2 5
7 8 6
Output
4
Submitted Solution:
```
import sys;
import heapq
def iterative(i,j):
q = []
heapq.heappush(q,(0,i,j,0,puz,costs))
global finding
while len(q):
items = heapq.heappop(q)
c_depth = items[0]
_i = items[1]
_j = items[2]
prev_move = items[3]
c_puz = items[4]
_costs = items[5]
if(puzzleCheck(c_puz)):
finding = 1
print(c_depth)
break
if((c_depth+sumCost(_costs)) >= depth or (c_depth+simpleHS(c_puz) >= depth)):
continue
if(_i != 0 and prev_move != 1):
swap_puz = swapPuz(c_puz[0:],_i,_j,_i-1,_j)
swap_cost = _costs[0:]
swap_cost[_i*3+_j] = HS(_i,_j,swap_puz[_i*3+_j])
swap_cost[(_i-1)*3+_j] = HS(_i-1,_j,swap_puz[(_i-1)*3+_j])
heapq.heappush(q,(c_depth+1,_i-1,_j,2,swap_puz,swap_cost))
if(_i != 2 and prev_move != 2):
swap_puz = swapPuz(c_puz[0:],_i,_j,_i+1,_j)
swap_cost = _costs[0:]
swap_cost[_i*3+_j] = HS(_i,_j,swap_puz[_i*3+_j])
swap_cost[(_i+1)*3+_j] = HS(_i+1,_j,swap_puz[(_i+1)*3+_j])
heapq.heappush(q,(c_depth+1,_i+1,_j,1,swap_puz,swap_cost))
if(_j != 0 and prev_move != 3):
swap_puz = swapPuz(c_puz[0:],_i,_j,_i,_j-1)
swap_cost = _costs[0:]
swap_cost[_i*3+_j] = HS(_i,_j,swap_puz[_i*3+_j])
swap_cost[_i*3+_j-1] = HS(_i,_j-1,swap_puz[_i*3+_j-1])
heapq.heappush(q,(c_depth+1,_i,_j-1,4,swap_puz,swap_cost))
if(_j != 2 and prev_move != 4):
swap_puz = swapPuz(c_puz[0:],_i,_j,_i,_j+1)
swap_cost = _costs[0:]
swap_cost[_i*3+_j] = HS(_i,_j,swap_puz[_i*3+_j])
swap_cost[_i*3+_j+1] = HS(_i,_j+1,swap_puz[_i*3+_j+1])
heapq.heappush(q,(c_depth+1,_i,_j+1,3,swap_puz,swap_cost))
def sumCost(costs):
value = 0
for i in range(len(costs)):
value += costs[i]
return value
def simpleHS(c_puz):
count = 0
for i in range(len(correctPuz)):
if(correctPuz[i] != c_puz[i]):
count+=1
return count
def HS(i,j,num):
k = correctPuz.index(num)
ki = (int)(k/3)
kj = k - ki*3
value = abs(_i-ki)+abs(_j-kj)
return value
def swapPuz(c_puz, i, j, i2,j2):
c_puz[i2*3+j2],c_puz[i*3+j] = c_puz[i*3+j],c_puz[i2*3+j2]
return c_puz
def puzzleCheck(c_puz):
if(c_puz[8] == 0):
for i in range(len(correctPuz)):
if(correctPuz[i] != c_puz[i]):
return False
return True
return False
correctPuz = [i+1 for i in range(9)]
correctPuz[8] = 0
puz = [0 for i in range(9)]
costs = [0 for i in range(9)]
i_start = 0
j_start = 0
for i in range(3):
puz[i*3],puz[i*3+1],puz[i*3+2] = map(int, input().split());
if(puz[i*3] == 0):
i_start,j_start = i,0
elif(puz[i*3+1] == 0):
i_start,j_start = i,1
elif(puz[i*3+2] == 0):
i_start,j_start = i,2
for i in range(len(costs)):
_i = (int)(i/3)
_j = i - _i*3
costs[i] = HS(_i,_j,puz[i])
finding = 0
depth = 0
while True:
if(finding == 1):
break
iterative(i_start,j_start)
depth+=1
```
No
| 102,868 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which prints small/large/equal relation of given two integers a and b.
Constraints
* -1000 β€ a, b β€ 1000
Input
Two integers a and b separated by a single space are given in a line.
Output
For given two integers a and b, print
a < b
if a is less than b,
a > b
if a is greater than b, and
a == b
if a equals to b.
Examples
Input
1 2
Output
a
Input
4 3
Output
a > b
Input
5 5
Output
a == b
"Correct Solution:
```
a,b = list(map(int,input().split()))
if a > b:
print("a > b")
elif a == b:
print("a == b")
else:
print("a < b")
```
| 102,869 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which prints small/large/equal relation of given two integers a and b.
Constraints
* -1000 β€ a, b β€ 1000
Input
Two integers a and b separated by a single space are given in a line.
Output
For given two integers a and b, print
a < b
if a is less than b,
a > b
if a is greater than b, and
a == b
if a equals to b.
Examples
Input
1 2
Output
a
Input
4 3
Output
a > b
Input
5 5
Output
a == b
"Correct Solution:
```
a, b = map(int, input().split())
c = "=="
if a < b:
c = '<'
elif a > b:
c = '>'
print ('a', c, 'b')
```
| 102,870 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which prints small/large/equal relation of given two integers a and b.
Constraints
* -1000 β€ a, b β€ 1000
Input
Two integers a and b separated by a single space are given in a line.
Output
For given two integers a and b, print
a < b
if a is less than b,
a > b
if a is greater than b, and
a == b
if a equals to b.
Examples
Input
1 2
Output
a
Input
4 3
Output
a > b
Input
5 5
Output
a == b
"Correct Solution:
```
a,b=map(int,input().split())
print('a','<'if a<b else'>'if a>b else'==','b')
```
| 102,871 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which prints small/large/equal relation of given two integers a and b.
Constraints
* -1000 β€ a, b β€ 1000
Input
Two integers a and b separated by a single space are given in a line.
Output
For given two integers a and b, print
a < b
if a is less than b,
a > b
if a is greater than b, and
a == b
if a equals to b.
Examples
Input
1 2
Output
a
Input
4 3
Output
a > b
Input
5 5
Output
a == b
"Correct Solution:
```
a,b = list(map(int, input().split()))
if (a < b):
print("a < b")
elif (a > b):
print("a > b")
else :
print("a == b")
```
| 102,872 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which prints small/large/equal relation of given two integers a and b.
Constraints
* -1000 β€ a, b β€ 1000
Input
Two integers a and b separated by a single space are given in a line.
Output
For given two integers a and b, print
a < b
if a is less than b,
a > b
if a is greater than b, and
a == b
if a equals to b.
Examples
Input
1 2
Output
a
Input
4 3
Output
a > b
Input
5 5
Output
a == b
"Correct Solution:
```
a,b=map(int,input().split())
if(a>b):
print('a > b')
elif(a<b):
print('a < b')
else:
print("a == b")
```
| 102,873 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which prints small/large/equal relation of given two integers a and b.
Constraints
* -1000 β€ a, b β€ 1000
Input
Two integers a and b separated by a single space are given in a line.
Output
For given two integers a and b, print
a < b
if a is less than b,
a > b
if a is greater than b, and
a == b
if a equals to b.
Examples
Input
1 2
Output
a
Input
4 3
Output
a > b
Input
5 5
Output
a == b
"Correct Solution:
```
a, b = map(int, input().split())
if (a > b):
print('a > b')
elif (a < b):
print('a < b')
else:
print('a == b')
```
| 102,874 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which prints small/large/equal relation of given two integers a and b.
Constraints
* -1000 β€ a, b β€ 1000
Input
Two integers a and b separated by a single space are given in a line.
Output
For given two integers a and b, print
a < b
if a is less than b,
a > b
if a is greater than b, and
a == b
if a equals to b.
Examples
Input
1 2
Output
a
Input
4 3
Output
a > b
Input
5 5
Output
a == b
"Correct Solution:
```
a, b = map(int, input().split())
print("a {} b".format('<' if a < b else '>' if a > b else '=='))
```
| 102,875 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which prints small/large/equal relation of given two integers a and b.
Constraints
* -1000 β€ a, b β€ 1000
Input
Two integers a and b separated by a single space are given in a line.
Output
For given two integers a and b, print
a < b
if a is less than b,
a > b
if a is greater than b, and
a == b
if a equals to b.
Examples
Input
1 2
Output
a
Input
4 3
Output
a > b
Input
5 5
Output
a == b
"Correct Solution:
```
a,b= map(int,(input().split()))
if(a==b):
print("a == b")
elif(a<b):
print("a < b")
elif(a>b):
print("a > b")
```
| 102,876 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which prints small/large/equal relation of given two integers a and b.
Constraints
* -1000 β€ a, b β€ 1000
Input
Two integers a and b separated by a single space are given in a line.
Output
For given two integers a and b, print
a < b
if a is less than b,
a > b
if a is greater than b, and
a == b
if a equals to b.
Examples
Input
1 2
Output
a
Input
4 3
Output
a > b
Input
5 5
Output
a == b
Submitted Solution:
```
a,b = map(int,input().split())
if a == b:
print("a == b")
if a > b:
print("a > b")
if a < b:
print("a < b")
```
Yes
| 102,877 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which prints small/large/equal relation of given two integers a and b.
Constraints
* -1000 β€ a, b β€ 1000
Input
Two integers a and b separated by a single space are given in a line.
Output
For given two integers a and b, print
a < b
if a is less than b,
a > b
if a is greater than b, and
a == b
if a equals to b.
Examples
Input
1 2
Output
a
Input
4 3
Output
a > b
Input
5 5
Output
a == b
Submitted Solution:
```
a,b=map(float,input().split())
if a<b:
print("a < b")
elif a>b:
print("a > b")
else:
print("a == b")
```
Yes
| 102,878 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which prints small/large/equal relation of given two integers a and b.
Constraints
* -1000 β€ a, b β€ 1000
Input
Two integers a and b separated by a single space are given in a line.
Output
For given two integers a and b, print
a < b
if a is less than b,
a > b
if a is greater than b, and
a == b
if a equals to b.
Examples
Input
1 2
Output
a
Input
4 3
Output
a > b
Input
5 5
Output
a == b
Submitted Solution:
```
a,b=map(int,input().split());print("a "+("<"if a<b else">"if a>b else"==")+" b")
```
Yes
| 102,879 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which prints small/large/equal relation of given two integers a and b.
Constraints
* -1000 β€ a, b β€ 1000
Input
Two integers a and b separated by a single space are given in a line.
Output
For given two integers a and b, print
a < b
if a is less than b,
a > b
if a is greater than b, and
a == b
if a equals to b.
Examples
Input
1 2
Output
a
Input
4 3
Output
a > b
Input
5 5
Output
a == b
Submitted Solution:
```
a,b = map(int,input().split())
x = ''
if a < b:
x = ' < '
elif a > b:
x = ' > '
else:
x = ' == '
print('a'+x+'b')
```
Yes
| 102,880 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which prints small/large/equal relation of given two integers a and b.
Constraints
* -1000 β€ a, b β€ 1000
Input
Two integers a and b separated by a single space are given in a line.
Output
For given two integers a and b, print
a < b
if a is less than b,
a > b
if a is greater than b, and
a == b
if a equals to b.
Examples
Input
1 2
Output
a
Input
4 3
Output
a > b
Input
5 5
Output
a == b
Submitted Solution:
```
a,b = map(int,input().split())
if a < b:
print("a < b")
elif a > b:
print("a > b")
else a == b:
print("a == b")
```
No
| 102,881 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which prints small/large/equal relation of given two integers a and b.
Constraints
* -1000 β€ a, b β€ 1000
Input
Two integers a and b separated by a single space are given in a line.
Output
For given two integers a and b, print
a < b
if a is less than b,
a > b
if a is greater than b, and
a == b
if a equals to b.
Examples
Input
1 2
Output
a
Input
4 3
Output
a > b
Input
5 5
Output
a == b
Submitted Solution:
```
a = input()
b = input()
if a > b:
print("a > b")
if a < b:
print("a < b")
if a == b:
print("a == b")
```
No
| 102,882 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which prints small/large/equal relation of given two integers a and b.
Constraints
* -1000 β€ a, b β€ 1000
Input
Two integers a and b separated by a single space are given in a line.
Output
For given two integers a and b, print
a < b
if a is less than b,
a > b
if a is greater than b, and
a == b
if a equals to b.
Examples
Input
1 2
Output
a
Input
4 3
Output
a > b
Input
5 5
Output
a == b
Submitted Solution:
```
import sys
data = sys.stdin.readline().strip()
a, b = data.split(' ')
if a > b:
print('a > b')
elif a < b:
print('a < b')
else:
print('a == b')
```
No
| 102,883 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which prints small/large/equal relation of given two integers a and b.
Constraints
* -1000 β€ a, b β€ 1000
Input
Two integers a and b separated by a single space are given in a line.
Output
For given two integers a and b, print
a < b
if a is less than b,
a > b
if a is greater than b, and
a == b
if a equals to b.
Examples
Input
1 2
Output
a
Input
4 3
Output
a > b
Input
5 5
Output
a == b
Submitted Solution:
```
#!usr/bin/env python3
def string_number_spliter():
a, b = [int(i) for i in input().split()]
return a, b
def main():
a, b = string_number_spliter()
if (a < b):
print(str(a) + " < " + str(b))
elif (a < b):
print(str(a) + " > " + str(b))
else:
print(str(a) + " == " + str(b))
if __name__ == '__main__':
main()
```
No
| 102,884 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
* "010210" β "100210";
* "010210" β "001210";
* "010210" β "010120";
* "010210" β "010201".
Note than you cannot swap "02" β "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String a is lexicographically less than string b (if strings a and b have the same length) if there exists some position i (1 β€ i β€ |a|, where |s| is the length of the string s) such that for every j < i holds a_j = b_j, and a_i < b_i.
Input
The first line of the input contains the string s consisting only of characters '0', '1' and '2', its length is between 1 and 10^5 (inclusive).
Output
Print a single string β the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).
Examples
Input
100210
Output
001120
Input
11222121
Output
11112222
Input
20
Output
20
Tags: greedy, implementation
Correct Solution:
```
a = input()
s = ""
final = ""
count = 0
for i in a:
if i=='1':
count+=1
else:
s+=i
s+='2'
i = s.find('2')
print(s[:i] + '1'*count + s[i:-1])
```
| 102,885 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
* "010210" β "100210";
* "010210" β "001210";
* "010210" β "010120";
* "010210" β "010201".
Note than you cannot swap "02" β "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String a is lexicographically less than string b (if strings a and b have the same length) if there exists some position i (1 β€ i β€ |a|, where |s| is the length of the string s) such that for every j < i holds a_j = b_j, and a_i < b_i.
Input
The first line of the input contains the string s consisting only of characters '0', '1' and '2', its length is between 1 and 10^5 (inclusive).
Output
Print a single string β the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).
Examples
Input
100210
Output
001120
Input
11222121
Output
11112222
Input
20
Output
20
Tags: greedy, implementation
Correct Solution:
```
a = input()
b = ''
i0 = 0
i1 = 0
i2 = 0
tmpi0 = 0
c = []
flag = False
for i in range(len(a)):
if a[i] == '1':
i1 += 1
elif i0 != 0 and a[i] == '2':
b += '0'*i0
i0 = 0
elif i2 != 0 and a[i] == '0':
b += '2'*i2
i2 = 0
if a[i] == '2':
i2 +=1
if a[i] == '0':
i0 += 1
b += '0'*i0 +'2'*i2
flag = True
for i in range(len(b)):
if flag and b[i] == '2':
flag = False
print('1'*i1+'2', end='')
i1 = 0
else:
print(b[i], end='')
print('1'*i1, end='')
```
| 102,886 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
* "010210" β "100210";
* "010210" β "001210";
* "010210" β "010120";
* "010210" β "010201".
Note than you cannot swap "02" β "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String a is lexicographically less than string b (if strings a and b have the same length) if there exists some position i (1 β€ i β€ |a|, where |s| is the length of the string s) such that for every j < i holds a_j = b_j, and a_i < b_i.
Input
The first line of the input contains the string s consisting only of characters '0', '1' and '2', its length is between 1 and 10^5 (inclusive).
Output
Print a single string β the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).
Examples
Input
100210
Output
001120
Input
11222121
Output
11112222
Input
20
Output
20
Tags: greedy, implementation
Correct Solution:
```
s=input()
one=s.count("1")
if one==0:print(s);exit()
ind=s.find("2")
ans=""
for i in range(len(s)):
if i==ind:ans+="1"*one
if s[i]=="1":continue
ans+=s[i]
if ind==-1:ans+="1"*one
print(ans)
```
| 102,887 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
* "010210" β "100210";
* "010210" β "001210";
* "010210" β "010120";
* "010210" β "010201".
Note than you cannot swap "02" β "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String a is lexicographically less than string b (if strings a and b have the same length) if there exists some position i (1 β€ i β€ |a|, where |s| is the length of the string s) such that for every j < i holds a_j = b_j, and a_i < b_i.
Input
The first line of the input contains the string s consisting only of characters '0', '1' and '2', its length is between 1 and 10^5 (inclusive).
Output
Print a single string β the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).
Examples
Input
100210
Output
001120
Input
11222121
Output
11112222
Input
20
Output
20
Tags: greedy, implementation
Correct Solution:
```
s=input()
l=len(s)
i=0
while(i<l and s[i]!='2'):
i+=1
a=sorted(s[0:i])
fir=[]
sec=[]
while(i<l):
if(s[i]=='1'):
fir+=[s[i]]
else:
sec+=[s[i]]
i+=1
r=a+fir+sec
print(''.join(r))
```
| 102,888 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
* "010210" β "100210";
* "010210" β "001210";
* "010210" β "010120";
* "010210" β "010201".
Note than you cannot swap "02" β "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String a is lexicographically less than string b (if strings a and b have the same length) if there exists some position i (1 β€ i β€ |a|, where |s| is the length of the string s) such that for every j < i holds a_j = b_j, and a_i < b_i.
Input
The first line of the input contains the string s consisting only of characters '0', '1' and '2', its length is between 1 and 10^5 (inclusive).
Output
Print a single string β the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).
Examples
Input
100210
Output
001120
Input
11222121
Output
11112222
Input
20
Output
20
Tags: greedy, implementation
Correct Solution:
```
def scanf(obj=list, type=int):
return obj(map(type, input().split()))
s = input()[-1::-1]
ans = ''
z = on = 0
for i in range(len(s)):
if s[i] == '0': z += 1
if s[i] == '1': on += 1
if s[i] == '2':
ans += '0' * z + '2'
z = 0
ans += '1' * on + '0' * z
print(ans[-1::-1])
```
| 102,889 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
* "010210" β "100210";
* "010210" β "001210";
* "010210" β "010120";
* "010210" β "010201".
Note than you cannot swap "02" β "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String a is lexicographically less than string b (if strings a and b have the same length) if there exists some position i (1 β€ i β€ |a|, where |s| is the length of the string s) such that for every j < i holds a_j = b_j, and a_i < b_i.
Input
The first line of the input contains the string s consisting only of characters '0', '1' and '2', its length is between 1 and 10^5 (inclusive).
Output
Print a single string β the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).
Examples
Input
100210
Output
001120
Input
11222121
Output
11112222
Input
20
Output
20
Tags: greedy, implementation
Correct Solution:
```
s=list(input())
s.append('2')
l=[]
c=s.count('1')
f=0
for i in range(len(s)):
if s[i]=='2' and f==0:
for j in range(c):
l.append('1')
f=1
l.append('2')
elif s[i]!='1':
l.append(s[i])
l=l[:len(s)-1]
print(''.join(l))
```
| 102,890 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
* "010210" β "100210";
* "010210" β "001210";
* "010210" β "010120";
* "010210" β "010201".
Note than you cannot swap "02" β "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String a is lexicographically less than string b (if strings a and b have the same length) if there exists some position i (1 β€ i β€ |a|, where |s| is the length of the string s) such that for every j < i holds a_j = b_j, and a_i < b_i.
Input
The first line of the input contains the string s consisting only of characters '0', '1' and '2', its length is between 1 and 10^5 (inclusive).
Output
Print a single string β the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).
Examples
Input
100210
Output
001120
Input
11222121
Output
11112222
Input
20
Output
20
Tags: greedy, implementation
Correct Solution:
```
s = list(input())
for i in range(len(s)):
s[i] = int(s[i])
n = len(s)
ans = [i for i in s if i == 0 or i == 2]
c1 = sum([1 for i in s if i == 1])
f2 = n
for i in range(len(ans)):
if ans[i] == 2:
f2 = i
break
ans1 = ans[:f2] +[1 for i in range(c1)] + ans[f2:]
print(''.join([str(i) for i in ans1]))
```
| 102,891 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
* "010210" β "100210";
* "010210" β "001210";
* "010210" β "010120";
* "010210" β "010201".
Note than you cannot swap "02" β "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String a is lexicographically less than string b (if strings a and b have the same length) if there exists some position i (1 β€ i β€ |a|, where |s| is the length of the string s) such that for every j < i holds a_j = b_j, and a_i < b_i.
Input
The first line of the input contains the string s consisting only of characters '0', '1' and '2', its length is between 1 and 10^5 (inclusive).
Output
Print a single string β the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).
Examples
Input
100210
Output
001120
Input
11222121
Output
11112222
Input
20
Output
20
Tags: greedy, implementation
Correct Solution:
```
s = input()
s = s + "2"
t = s.replace("1", '')
i = t.find("2")
print(t[:i] + "1"*s.count("1")+t[i:-1])
```
| 102,892 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
* "010210" β "100210";
* "010210" β "001210";
* "010210" β "010120";
* "010210" β "010201".
Note than you cannot swap "02" β "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String a is lexicographically less than string b (if strings a and b have the same length) if there exists some position i (1 β€ i β€ |a|, where |s| is the length of the string s) such that for every j < i holds a_j = b_j, and a_i < b_i.
Input
The first line of the input contains the string s consisting only of characters '0', '1' and '2', its length is between 1 and 10^5 (inclusive).
Output
Print a single string β the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).
Examples
Input
100210
Output
001120
Input
11222121
Output
11112222
Input
20
Output
20
Submitted Solution:
```
s = input("")
num = 0
flag = False
for numero in s:
if numero == '1':
num += 1
if ('2' not in s or '0' not in s):
s = ''.join(sorted(s));
print(s)
quit()
for elemento in s:
if elemento == '0':
print('0', end='')
elif elemento == '2' and not flag == True:
for i in range(num):
print('1', end='')
flag = True
print('2', end='')
else:
if elemento == '1':
continue
if elemento == '2':
print('2', end='')
print("")
```
Yes
| 102,893 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
* "010210" β "100210";
* "010210" β "001210";
* "010210" β "010120";
* "010210" β "010201".
Note than you cannot swap "02" β "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String a is lexicographically less than string b (if strings a and b have the same length) if there exists some position i (1 β€ i β€ |a|, where |s| is the length of the string s) such that for every j < i holds a_j = b_j, and a_i < b_i.
Input
The first line of the input contains the string s consisting only of characters '0', '1' and '2', its length is between 1 and 10^5 (inclusive).
Output
Print a single string β the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).
Examples
Input
100210
Output
001120
Input
11222121
Output
11112222
Input
20
Output
20
Submitted Solution:
```
from sys import stdin
from collections import deque
mod = 10**9 + 7
# def rl():
# return [int(w) for w in stdin.readline().split()]
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt,factorial,gcd,log2,inf,ceil
# map(int,input().split())
# # l = list(map(int,input().split()))
# from itertools import permutations
import heapq
# la = []
s = input()
n = len(s)
s+='2'
z = s.count('1')
ans = []
flag = 0
for i in range(len(s)):
if s[i] == '2' and flag == 0:
for j in range(z):
ans.append('1')
flag = 1
ans.append('2')
else:
if s[i]!='1':
ans.append(s[i])
ans = ans[:n]
print(''.join(ans))
```
Yes
| 102,894 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
* "010210" β "100210";
* "010210" β "001210";
* "010210" β "010120";
* "010210" β "010201".
Note than you cannot swap "02" β "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String a is lexicographically less than string b (if strings a and b have the same length) if there exists some position i (1 β€ i β€ |a|, where |s| is the length of the string s) such that for every j < i holds a_j = b_j, and a_i < b_i.
Input
The first line of the input contains the string s consisting only of characters '0', '1' and '2', its length is between 1 and 10^5 (inclusive).
Output
Print a single string β the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).
Examples
Input
100210
Output
001120
Input
11222121
Output
11112222
Input
20
Output
20
Submitted Solution:
```
#J - Minimum Ternary String
def writeRestOfString(TS, result, indexOfFirstTwo):
size = len(TS)
for num in TS[indexOfFirstTwo:size]:
result += str(num)
return result
def removeAllOnesAfterFirstTwo(TS, indexOfFirstTwo):
i = indexOfFirstTwo
size = len(TS)
beginOfTS = TS[0:indexOfFirstTwo]
restOfTS = ""
while i < size:
if TS[i] != '1': restOfTS += str(TS[i])
i += 1
return beginOfTS + restOfTS
def countZerosAndOnes(TS, limit):
i = 0
zeros = 0
ones = 0
while i < limit:
if TS[i] == 1: ones += 1
else: zeros += 1
i += 1
return (zeros, ones)
def countOnes(TS, limit):
i = 0
ones = 0
while i < limit:
if TS[i] == 1: ones += 1
i += 1
return ones
def countZeros(TS, limit):
i = 0
zeros = 0
while i< limit:
if TS[i] == 0: zeros += 1
i += 1
return zeros
def writeZeros(result, zeros):
i = 1
while i <= zeros:
result += str(0)
i += 1
return result
def writeOnes(result, ones):
i = 1
while i <= ones:
result += str(1)
i += 1
return result
def checkForFirstTwo(TS):
i = 0
size = len(TS)
while(i < size):
if TS[i] == 2 or TS[i] == '2': return i
i += 1
return None
def changeStringWithOnlyOnesAndZeros(TS):
size = len(TS)
result = ""
(zeros, ones) = countZerosAndOnes(TS, size)
result = writeZeros(result,zeros)
result = writeOnes(result,ones)
return result
def changeString(TS, indexOfFirstTwo):
result = ""
size = len(TS)
zeros = countZeros(TS, indexOfFirstTwo)
ones = countOnes(TS, size)
result = writeZeros(result,zeros)
result = writeOnes(result,ones)
result = writeRestOfString(TS,result,indexOfFirstTwo)
indexOfFirstTwo = checkForFirstTwo(result)
result = removeAllOnesAfterFirstTwo(result, indexOfFirstTwo)
return result
def splitString(string):
characters = []
size = len(string)
i = 0
while(i < size):
characters.append(int(string[i]))
i += 1
return characters
ternaryString = input()
#print(ternaryString)
TSArray = splitString(ternaryString)
indexOfFirstTwo = checkForFirstTwo(TSArray)
if indexOfFirstTwo != None:
print(changeString(TSArray, indexOfFirstTwo))
else:
print(changeStringWithOnlyOnesAndZeros(TSArray))
```
Yes
| 102,895 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
* "010210" β "100210";
* "010210" β "001210";
* "010210" β "010120";
* "010210" β "010201".
Note than you cannot swap "02" β "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String a is lexicographically less than string b (if strings a and b have the same length) if there exists some position i (1 β€ i β€ |a|, where |s| is the length of the string s) such that for every j < i holds a_j = b_j, and a_i < b_i.
Input
The first line of the input contains the string s consisting only of characters '0', '1' and '2', its length is between 1 and 10^5 (inclusive).
Output
Print a single string β the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).
Examples
Input
100210
Output
001120
Input
11222121
Output
11112222
Input
20
Output
20
Submitted Solution:
```
n=list(map(str,list(input())))
a=''
b=''
for i in n:
if i=='1':
a+='1'
else:
b+=i
n=b.find('2')
if n==-1:
print(b+a)
else:
print(b[:n]+a+b[n:])
```
Yes
| 102,896 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
* "010210" β "100210";
* "010210" β "001210";
* "010210" β "010120";
* "010210" β "010201".
Note than you cannot swap "02" β "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String a is lexicographically less than string b (if strings a and b have the same length) if there exists some position i (1 β€ i β€ |a|, where |s| is the length of the string s) such that for every j < i holds a_j = b_j, and a_i < b_i.
Input
The first line of the input contains the string s consisting only of characters '0', '1' and '2', its length is between 1 and 10^5 (inclusive).
Output
Print a single string β the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).
Examples
Input
100210
Output
001120
Input
11222121
Output
11112222
Input
20
Output
20
Submitted Solution:
```
N = list(input())
N = [int(i) for i in N]
n = len(N)
for i in range(n-1,-1,-1):
if N[i]==2:
ones=0
j = i+1
while j<n and N[j]!=2:
if(N[j]==1):
ones+=1
j+=1
for aux in range(i,j):
if aux-i<ones:
N[aux]=1
else:
if aux == ones+i:
N[aux]=2
else:
N[aux]=0
print(N)
ones=0
for i in range(n):
if N[i]==2 or i == n-1:
for j in range(i-1,-1,-1):
if ones>0:
N[j]=1
ones-=1
else:
N[j]=0
break;
else:
if(N[i]==1):
ones+=1
N = [str(i) for i in N]
print(''.join(N))
```
No
| 102,897 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
* "010210" β "100210";
* "010210" β "001210";
* "010210" β "010120";
* "010210" β "010201".
Note than you cannot swap "02" β "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String a is lexicographically less than string b (if strings a and b have the same length) if there exists some position i (1 β€ i β€ |a|, where |s| is the length of the string s) such that for every j < i holds a_j = b_j, and a_i < b_i.
Input
The first line of the input contains the string s consisting only of characters '0', '1' and '2', its length is between 1 and 10^5 (inclusive).
Output
Print a single string β the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).
Examples
Input
100210
Output
001120
Input
11222121
Output
11112222
Input
20
Output
20
Submitted Solution:
```
if __name__ == '__main__':
s=input()
len1=s.count('1')
index2=s.find('2')
temp=s[:index2]
zero=temp.count('0')
result='0'*zero+'1'*len1+s[index2:].replace('1','')
print(result)
```
No
| 102,898 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
* "010210" β "100210";
* "010210" β "001210";
* "010210" β "010120";
* "010210" β "010201".
Note than you cannot swap "02" β "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String a is lexicographically less than string b (if strings a and b have the same length) if there exists some position i (1 β€ i β€ |a|, where |s| is the length of the string s) such that for every j < i holds a_j = b_j, and a_i < b_i.
Input
The first line of the input contains the string s consisting only of characters '0', '1' and '2', its length is between 1 and 10^5 (inclusive).
Output
Print a single string β the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).
Examples
Input
100210
Output
001120
Input
11222121
Output
11112222
Input
20
Output
20
Submitted Solution:
```
s = list(map(int, list(input())))
c = [0, 0, 0]
ans = list()
f = True
for el in s:
if el == 0 and c[2] > 0:
ans.append('0' * c[0])
if f:
ans.append('1' * s.count(1))
f = False
ans.append('2' * c[2])
c = [0, 0, 0]
if el != 1:
c[el] += 1
ans.append('0' * c[0])
ans.append('2' * c[2])
if f:
ans.insert(0, '1' * s.count(1))
f = False
print(''.join(ans))
```
No
| 102,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.