message stringlengths 2 67k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 463 109k | cluster float64 19 19 | __index_level_0__ int64 926 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.
The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.
You should write a program which will determine how many moves will the game last.
Input
The first line contains two integer numbers n and x (2 ≤ n ≤ 2·105, 2 ≤ x ≤ n).
Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n) — edges of the tree. It is guaranteed that the edges form a valid tree.
Output
Print the total number of moves Alice and Bob will make.
Examples
Input
4 3
1 2
2 3
2 4
Output
4
Input
5 2
1 2
2 3
3 4
2 5
Output
6
Note
In the first example the tree looks like this:
<image>
The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:
B: stay at vertex 3
A: go to vertex 2
B: stay at vertex 3
A: go to vertex 3
In the second example the tree looks like this:
<image>
The moves in the optimal strategy are:
B: go to vertex 3
A: go to vertex 2
B: go to vertex 4
A: go to vertex 3
B: stay at vertex 4
A: go to vertex 4
Submitted Solution:
```
from collections import deque
from sys import stdin
#parser
def parser():
return map(int, stdin.readline().split())
#Algoritmo BFS
def BFS(s):
distance=[-1 for i in range(n)]
distance[s]=0
q=deque()
q.append(s)
while len(q)>0:
v=q.popleft()
for u in adjacents_list[v]:
if distance[u] == -1:
distance[u]=distance[v]+1
q.append(u)
return distance
#Recibiendo los valores de n y x
n,x=parser()
#Armando el arbol
adjacents_list=[[] for i in range(n)]
for i in range(n-1):
v1,v2=parser()
adjacents_list[v1-1].append(v2-1)
adjacents_list[v2-1].append(v1-1)
distance_Alice=BFS(0)
distance_Bob=BFS(x-1)
#Hallando el nodo mas alejado a Alice que puede alcanzar Bob antes que lo alcance Alice
max=0
for i in range(n):
if max<distance_Alice[i] and distance_Bob[i]<distance_Alice[i]:
max=distance_Alice[i]
print(max*2)
``` | instruction | 0 | 463 | 19 | 926 |
Yes | output | 1 | 463 | 19 | 927 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.
The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.
You should write a program which will determine how many moves will the game last.
Input
The first line contains two integer numbers n and x (2 ≤ n ≤ 2·105, 2 ≤ x ≤ n).
Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n) — edges of the tree. It is guaranteed that the edges form a valid tree.
Output
Print the total number of moves Alice and Bob will make.
Examples
Input
4 3
1 2
2 3
2 4
Output
4
Input
5 2
1 2
2 3
3 4
2 5
Output
6
Note
In the first example the tree looks like this:
<image>
The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:
B: stay at vertex 3
A: go to vertex 2
B: stay at vertex 3
A: go to vertex 3
In the second example the tree looks like this:
<image>
The moves in the optimal strategy are:
B: go to vertex 3
A: go to vertex 2
B: go to vertex 4
A: go to vertex 3
B: stay at vertex 4
A: go to vertex 4
Submitted Solution:
```
from collections import deque
from sys import stdin
#Algoritmo BFS
def BFS(s):
if s==0:
distance=distance_Alice
else:
distance=distance_Bob
distance[s]=0
q=deque()
q.append(s)
while len(q)>0:
v=q.popleft()
for u in adjacents_list[v]:
if distance[u] == -1:
distance[u]=distance[v]+1
q.append(u)
#Recibiendo los valores de n y x
n,x=map(int, stdin.readline().split())
#Creando los arrays necesarios para la ejecucion de DFS
#visitados
distance_Alice=[-1 for i in range(n)]
distance_Bob=[-1 for i in range(n)]
#Armando el arbol
adjacents_list=[[] for i in range(n)]
for i in range(n-1):
v1,v2=map(int, stdin.readline().split())
adjacents_list[v1-1].append(v2-1)
adjacents_list[v2-1].append(v1-1)
BFS(0)
BFS(x-1)
#Hallando el nodo mas alejado a Alice que puede alcanzar Bob antes que lo alcance Alice
max=0
for i in range(n):
if max<distance_Alice[i] and distance_Bob[i]<distance_Alice[i]:
max=distance_Alice[i]
print(max*2)
``` | instruction | 0 | 464 | 19 | 928 |
Yes | output | 1 | 464 | 19 | 929 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.
The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.
You should write a program which will determine how many moves will the game last.
Input
The first line contains two integer numbers n and x (2 ≤ n ≤ 2·105, 2 ≤ x ≤ n).
Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n) — edges of the tree. It is guaranteed that the edges form a valid tree.
Output
Print the total number of moves Alice and Bob will make.
Examples
Input
4 3
1 2
2 3
2 4
Output
4
Input
5 2
1 2
2 3
3 4
2 5
Output
6
Note
In the first example the tree looks like this:
<image>
The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:
B: stay at vertex 3
A: go to vertex 2
B: stay at vertex 3
A: go to vertex 3
In the second example the tree looks like this:
<image>
The moves in the optimal strategy are:
B: go to vertex 3
A: go to vertex 2
B: go to vertex 4
A: go to vertex 3
B: stay at vertex 4
A: go to vertex 4
Submitted Solution:
```
from sys import stdin
from collections import deque
def bfs(G, s):
Q = deque()
Q.append(s)
infinite = 10 ** 6
d = [infinite]*n
d[s] = 0
while Q:
u = Q.popleft()
for v in graph[u]:
if d[v] == infinite:
d[v] = d[u] + 1
Q.append(v)
return d
n, x = map(int, stdin.readline().split())
x = x - 1
graph = [[] for i in range(n)]
for i in range(n - 1):
a, b = map(int, stdin.readline().split())
graph[a - 1].append(b - 1)
graph[b - 1].append(a - 1)
d_Alice = bfs(graph, 0)
d_Bob = bfs(graph, x)
resp = d_Alice[x]
for i,v in enumerate(graph):
if len(v) == 1 and d_Alice[i] > d_Bob[i]:
resp = max(resp, d_Alice[i])
print(2*resp)
``` | instruction | 0 | 466 | 19 | 932 |
Yes | output | 1 | 466 | 19 | 933 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.
The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.
You should write a program which will determine how many moves will the game last.
Input
The first line contains two integer numbers n and x (2 ≤ n ≤ 2·105, 2 ≤ x ≤ n).
Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n) — edges of the tree. It is guaranteed that the edges form a valid tree.
Output
Print the total number of moves Alice and Bob will make.
Examples
Input
4 3
1 2
2 3
2 4
Output
4
Input
5 2
1 2
2 3
3 4
2 5
Output
6
Note
In the first example the tree looks like this:
<image>
The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:
B: stay at vertex 3
A: go to vertex 2
B: stay at vertex 3
A: go to vertex 3
In the second example the tree looks like this:
<image>
The moves in the optimal strategy are:
B: go to vertex 3
A: go to vertex 2
B: go to vertex 4
A: go to vertex 3
B: stay at vertex 4
A: go to vertex 4
Submitted Solution:
```
n, x = map(int, input().split())
E = []
WHITE = 0
GREY = 1
BLACK = 2
color = [-1] + [WHITE for i in range(n)]
path = []
max_path = 0
for i in range(n - 1):
E.append(list(map(int, input().split())))
def get_nbs(v):
for e in E:
if e[0] == v:
yield e[1]
elif e[1] == v:
yield e[0]
def dfs(v):
global max_path
color[v] = GREY
path.append(v)
lp = len(path)
if lp >= max_path:
max_path = lp
for u in get_nbs(v):
if color[u] == WHITE:
dfs(u)
elif color[u] == GREY and u in path and u != path[-2]:
e = [u, v] if [u, v] in E else [v, u]
E.remove(e)
path.remove(v)
# print(path)
dfs(1)
print((max_path - 1) * 2)
``` | instruction | 0 | 467 | 19 | 934 |
No | output | 1 | 467 | 19 | 935 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.
The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.
You should write a program which will determine how many moves will the game last.
Input
The first line contains two integer numbers n and x (2 ≤ n ≤ 2·105, 2 ≤ x ≤ n).
Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n) — edges of the tree. It is guaranteed that the edges form a valid tree.
Output
Print the total number of moves Alice and Bob will make.
Examples
Input
4 3
1 2
2 3
2 4
Output
4
Input
5 2
1 2
2 3
3 4
2 5
Output
6
Note
In the first example the tree looks like this:
<image>
The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:
B: stay at vertex 3
A: go to vertex 2
B: stay at vertex 3
A: go to vertex 3
In the second example the tree looks like this:
<image>
The moves in the optimal strategy are:
B: go to vertex 3
A: go to vertex 2
B: go to vertex 4
A: go to vertex 3
B: stay at vertex 4
A: go to vertex 4
Submitted Solution:
```
import sys
from math import *
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
n, x = mints()
e = [[] for i in range(n)]
for i in range(n-1):
a, b = mints()
e[a-1].append(b-1)
e[b-1].append(a-1)
x -= 1
q = [0]*n
d = [0]*n
p = [-1]*n
ql = 0
qr = 1
q[0] = x
d[x] = 1
while ql < qr:
u = q[ql]
ql += 1
for v in e[u]:
if d[v] == 0:
d[v] = d[u] + 1
p[v] = u
q[qr] = v
qr += 1
v = 0
u = 1
while v != -1 and d[v] > u:
d[v] = 0
v = p[v]
u += 1
rv = d.index(max(d))
#print(d, rv)
d = [0]*n
ql = 0
qr = 1
q[0] = 0
d[0] = 1
while ql < qr:
u = q[ql]
ql += 1
for v in e[u]:
if d[v] == 0:
d[v] = d[u] + 1
q[qr] = v
qr += 1
print((d[rv]-1)*2)
``` | instruction | 0 | 468 | 19 | 936 |
No | output | 1 | 468 | 19 | 937 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.
The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.
You should write a program which will determine how many moves will the game last.
Input
The first line contains two integer numbers n and x (2 ≤ n ≤ 2·105, 2 ≤ x ≤ n).
Each of the next n - 1 lines contains two integer numbers a and b (1 ≤ a, b ≤ n) — edges of the tree. It is guaranteed that the edges form a valid tree.
Output
Print the total number of moves Alice and Bob will make.
Examples
Input
4 3
1 2
2 3
2 4
Output
4
Input
5 2
1 2
2 3
3 4
2 5
Output
6
Note
In the first example the tree looks like this:
<image>
The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:
B: stay at vertex 3
A: go to vertex 2
B: stay at vertex 3
A: go to vertex 3
In the second example the tree looks like this:
<image>
The moves in the optimal strategy are:
B: go to vertex 3
A: go to vertex 2
B: go to vertex 4
A: go to vertex 3
B: stay at vertex 4
A: go to vertex 4
Submitted Solution:
```
'''n=int(input())
a=list(map(int,input().split()))
m=int(input())
per=[]
tt=sum(a)
f=0
for _ in range(m):
l,r=map(int,input().split())
#print(l,r,tt)
if l<=tt and tt<=r:
print(tt)
f=1
break
elif l>tt and f==0:
print(l)
f=1
break
if f==0:
print(-1)
'''
def bottomm(x):
if len(dic[x])==0:
return 0
h=0
for i in dic[x]:
h= max(1+bottomm(i),h)
return h
def getheight(x,dic,ph):
if x in dic[ph]:
return 1
else:
h=0
for j in dic[ph]:
h=1+getheight(x,dic,j)
return h
n,x=map(int,input().split())
dic={}
par={}
for i in range(n):
dic[i+1]=[]
par[i+1]=[]
for _ in range(n-1):
a,b=map(int,input().split())
dic[a].append(b)
par[b]=a
pos_a=1
pos_b=x
ha=1
hb=getheight(x,dic,1)
ans=0
f=0
if hb==2:
if len(dic[pos_b])==0:
ans=4
f=1
elif f==0:
uptil=hb//2
maxh=bottomm(x)
k=1
while(uptil!=0):
node=par[pos_b]
pos_b=node
uptil-=1
maxh=max(maxh,bottomm(node)+k)
k+=1
ans=2*(maxh+hb)
print(ans)
``` | instruction | 0 | 470 | 19 | 940 |
No | output | 1 | 470 | 19 | 941 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ivan has n different boxes. The first of them contains some balls of n different colors.
Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≤ i ≤ n) i-th box will contain all balls with color i.
In order to do this, Ivan will make some turns. Each turn he does the following:
1. Ivan chooses any non-empty box and takes all balls from this box;
2. Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either k = 2 or k = 3.
The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.
Help Ivan to determine the minimum possible penalty of the game!
Input
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of boxes and colors.
The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the number of balls with color i.
Output
Print one number — the minimum possible penalty of the game.
Examples
Input
3
1 2 3
Output
6
Input
4
2 3 4 5
Output
19
Note
In the first example you take all the balls from the first box, choose k = 3 and sort all colors to corresponding boxes. Penalty is 6.
In the second example you make two turns:
1. Take all the balls from the first box, choose k = 3, put balls of color 3 to the third box, of color 4 — to the fourth box and the rest put back into the first box. Penalty is 14;
2. Take all the balls from the first box, choose k = 2, put balls of color 1 to the first box, of color 2 — to the second box. Penalty is 5.
Total penalty is 19. | instruction | 0 | 492 | 19 | 984 |
Tags: data structures, greedy
Correct Solution:
```
import heapq
n = int(input())
resp=0
test = [int(i) for i in input().split()]
test.sort()
if(n%2==0):
test = [0]+test
n+=1
while n!=1:
c = heapq.heappop(test) + heapq.heappop(test) + heapq.heappop(test)
resp+=c
heapq.heappush(test,c)
n-=2
print(resp)
``` | output | 1 | 492 | 19 | 985 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ivan has n different boxes. The first of them contains some balls of n different colors.
Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≤ i ≤ n) i-th box will contain all balls with color i.
In order to do this, Ivan will make some turns. Each turn he does the following:
1. Ivan chooses any non-empty box and takes all balls from this box;
2. Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either k = 2 or k = 3.
The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.
Help Ivan to determine the minimum possible penalty of the game!
Input
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of boxes and colors.
The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the number of balls with color i.
Output
Print one number — the minimum possible penalty of the game.
Examples
Input
3
1 2 3
Output
6
Input
4
2 3 4 5
Output
19
Note
In the first example you take all the balls from the first box, choose k = 3 and sort all colors to corresponding boxes. Penalty is 6.
In the second example you make two turns:
1. Take all the balls from the first box, choose k = 3, put balls of color 3 to the third box, of color 4 — to the fourth box and the rest put back into the first box. Penalty is 14;
2. Take all the balls from the first box, choose k = 2, put balls of color 1 to the first box, of color 2 — to the second box. Penalty is 5.
Total penalty is 19. | instruction | 0 | 493 | 19 | 986 |
Tags: data structures, greedy
Correct Solution:
```
import heapq
n = int(input())
colors_lens = list(map(int, input().split()))
if len(colors_lens) % 2 == 0:
colors_lens.append(0)
heapq.heapify(colors_lens)
ans = 0
l = len(colors_lens)
while l > 1:
su = 0
su += heapq.heappop(colors_lens)
su += heapq.heappop(colors_lens)
su += heapq.heappop(colors_lens)
ans += su
heapq.heappush(colors_lens, su)
l -= 2
print(ans)
``` | output | 1 | 493 | 19 | 987 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ivan has n different boxes. The first of them contains some balls of n different colors.
Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≤ i ≤ n) i-th box will contain all balls with color i.
In order to do this, Ivan will make some turns. Each turn he does the following:
1. Ivan chooses any non-empty box and takes all balls from this box;
2. Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either k = 2 or k = 3.
The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.
Help Ivan to determine the minimum possible penalty of the game!
Input
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of boxes and colors.
The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the number of balls with color i.
Output
Print one number — the minimum possible penalty of the game.
Examples
Input
3
1 2 3
Output
6
Input
4
2 3 4 5
Output
19
Note
In the first example you take all the balls from the first box, choose k = 3 and sort all colors to corresponding boxes. Penalty is 6.
In the second example you make two turns:
1. Take all the balls from the first box, choose k = 3, put balls of color 3 to the third box, of color 4 — to the fourth box and the rest put back into the first box. Penalty is 14;
2. Take all the balls from the first box, choose k = 2, put balls of color 1 to the first box, of color 2 — to the second box. Penalty is 5.
Total penalty is 19. | instruction | 0 | 494 | 19 | 988 |
Tags: data structures, greedy
Correct Solution:
```
import heapq
N=int(input())
colors=list(map(int,input().split()))
if (N%2==0):
colors.append(0)
penalty=0
heapq.heapify(colors)
while (len(colors)>2):
a = heapq.heappop(colors)
b = heapq.heappop(colors)
c = heapq.heappop(colors)
penalty+=a+b+c
heapq.heappush(colors,a+b+c)
print(penalty)
``` | output | 1 | 494 | 19 | 989 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ivan has n different boxes. The first of them contains some balls of n different colors.
Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≤ i ≤ n) i-th box will contain all balls with color i.
In order to do this, Ivan will make some turns. Each turn he does the following:
1. Ivan chooses any non-empty box and takes all balls from this box;
2. Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either k = 2 or k = 3.
The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.
Help Ivan to determine the minimum possible penalty of the game!
Input
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of boxes and colors.
The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the number of balls with color i.
Output
Print one number — the minimum possible penalty of the game.
Examples
Input
3
1 2 3
Output
6
Input
4
2 3 4 5
Output
19
Note
In the first example you take all the balls from the first box, choose k = 3 and sort all colors to corresponding boxes. Penalty is 6.
In the second example you make two turns:
1. Take all the balls from the first box, choose k = 3, put balls of color 3 to the third box, of color 4 — to the fourth box and the rest put back into the first box. Penalty is 14;
2. Take all the balls from the first box, choose k = 2, put balls of color 1 to the first box, of color 2 — to the second box. Penalty is 5.
Total penalty is 19. | instruction | 0 | 495 | 19 | 990 |
Tags: data structures, greedy
Correct Solution:
```
import heapq
n = int(input())
lst = list(map(int, input().strip().split()))
if n%2 == 0:
lst.append(0)
penalty = 0
heapq.heapify(lst)
while(len(lst) > 1):
a = heapq.heappop(lst)
b = heapq.heappop(lst)
c = heapq.heappop(lst)
penalty += a+b+c
heapq.heappush(lst, a+b+c)
print(penalty)
``` | output | 1 | 495 | 19 | 991 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ivan has n different boxes. The first of them contains some balls of n different colors.
Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≤ i ≤ n) i-th box will contain all balls with color i.
In order to do this, Ivan will make some turns. Each turn he does the following:
1. Ivan chooses any non-empty box and takes all balls from this box;
2. Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either k = 2 or k = 3.
The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.
Help Ivan to determine the minimum possible penalty of the game!
Input
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of boxes and colors.
The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the number of balls with color i.
Output
Print one number — the minimum possible penalty of the game.
Examples
Input
3
1 2 3
Output
6
Input
4
2 3 4 5
Output
19
Note
In the first example you take all the balls from the first box, choose k = 3 and sort all colors to corresponding boxes. Penalty is 6.
In the second example you make two turns:
1. Take all the balls from the first box, choose k = 3, put balls of color 3 to the third box, of color 4 — to the fourth box and the rest put back into the first box. Penalty is 14;
2. Take all the balls from the first box, choose k = 2, put balls of color 1 to the first box, of color 2 — to the second box. Penalty is 5.
Total penalty is 19. | instruction | 0 | 496 | 19 | 992 |
Tags: data structures, greedy
Correct Solution:
```
import heapq
N = int(input())
colors = list(map(int,input().strip().split()))
# if N%2:
# colors.append(0)
# heapq.heapify(colors)
# while (len(colors) > 2):
# a = heapq.heappop(colors)
# b = heapq.heappop(colors)
# c = heapq.heappop(colors)
# panalty += a + b + c
# heapq.heappush(colors,a+b+c)
# print(penalty)
heapq.heapify(colors)
if(len(colors) % 2 == 0):
colors.append(0)
ans = 0
while(len(colors) > 2):
a = heapq.heappop(colors)
b = heapq.heappop(colors)
c = heapq.heappop(colors)
heapq.heappush(colors,a+b+c)
ans += a+b+c
print(ans)
``` | output | 1 | 496 | 19 | 993 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ivan has n different boxes. The first of them contains some balls of n different colors.
Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≤ i ≤ n) i-th box will contain all balls with color i.
In order to do this, Ivan will make some turns. Each turn he does the following:
1. Ivan chooses any non-empty box and takes all balls from this box;
2. Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either k = 2 or k = 3.
The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.
Help Ivan to determine the minimum possible penalty of the game!
Input
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of boxes and colors.
The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the number of balls with color i.
Output
Print one number — the minimum possible penalty of the game.
Examples
Input
3
1 2 3
Output
6
Input
4
2 3 4 5
Output
19
Note
In the first example you take all the balls from the first box, choose k = 3 and sort all colors to corresponding boxes. Penalty is 6.
In the second example you make two turns:
1. Take all the balls from the first box, choose k = 3, put balls of color 3 to the third box, of color 4 — to the fourth box and the rest put back into the first box. Penalty is 14;
2. Take all the balls from the first box, choose k = 2, put balls of color 1 to the first box, of color 2 — to the second box. Penalty is 5.
Total penalty is 19. | instruction | 0 | 497 | 19 | 994 |
Tags: data structures, greedy
Correct Solution:
```
import heapq
N = int(input())
colors = list(map(int,input().strip().split()))
if N%2 == 0:
colors.append(0)
penalty = 0
heapq.heapify(colors)
# while (len(colors) > 2):
# a = heapq.heappop(colors)
# b = heapq.heappop(colors)
# c = heapq.heappop(colors)
# panalty += a + b + c
# heapq.heappush(colors,a+b+c)
while(len(colors) > 2):
a = heapq.heappop(colors)
b = heapq.heappop(colors)
c = heapq.heappop(colors)
heapq.heappush(colors,a+b+c)
penalty += a+b+c
print(penalty)
``` | output | 1 | 497 | 19 | 995 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ivan has n different boxes. The first of them contains some balls of n different colors.
Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≤ i ≤ n) i-th box will contain all balls with color i.
In order to do this, Ivan will make some turns. Each turn he does the following:
1. Ivan chooses any non-empty box and takes all balls from this box;
2. Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either k = 2 or k = 3.
The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.
Help Ivan to determine the minimum possible penalty of the game!
Input
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of boxes and colors.
The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the number of balls with color i.
Output
Print one number — the minimum possible penalty of the game.
Examples
Input
3
1 2 3
Output
6
Input
4
2 3 4 5
Output
19
Note
In the first example you take all the balls from the first box, choose k = 3 and sort all colors to corresponding boxes. Penalty is 6.
In the second example you make two turns:
1. Take all the balls from the first box, choose k = 3, put balls of color 3 to the third box, of color 4 — to the fourth box and the rest put back into the first box. Penalty is 14;
2. Take all the balls from the first box, choose k = 2, put balls of color 1 to the first box, of color 2 — to the second box. Penalty is 5.
Total penalty is 19. | instruction | 0 | 498 | 19 | 996 |
Tags: data structures, greedy
Correct Solution:
```
import heapq
N = int(input())
colors = list(map(int,input().strip().split()))
if N%2 == 0:
colors.append(0)
penalty = 0
heapq.heapify(colors)
while (len(colors) > 2):
# a = heapq.heappop(colors)
# b = heapq.heappop(colors)
# c = heapq.heappop(colors)
# panalty += a + b + c
# heapq.heappush(colors,a+b+c)
# while(len(colors) > 2):
a = heapq.heappop(colors)
b = heapq.heappop(colors)
c = heapq.heappop(colors)
heapq.heappush(colors,a+b+c)
penalty += a+b+c
print(penalty)
``` | output | 1 | 498 | 19 | 997 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ivan has n different boxes. The first of them contains some balls of n different colors.
Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≤ i ≤ n) i-th box will contain all balls with color i.
In order to do this, Ivan will make some turns. Each turn he does the following:
1. Ivan chooses any non-empty box and takes all balls from this box;
2. Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either k = 2 or k = 3.
The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.
Help Ivan to determine the minimum possible penalty of the game!
Input
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of boxes and colors.
The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the number of balls with color i.
Output
Print one number — the minimum possible penalty of the game.
Examples
Input
3
1 2 3
Output
6
Input
4
2 3 4 5
Output
19
Note
In the first example you take all the balls from the first box, choose k = 3 and sort all colors to corresponding boxes. Penalty is 6.
In the second example you make two turns:
1. Take all the balls from the first box, choose k = 3, put balls of color 3 to the third box, of color 4 — to the fourth box and the rest put back into the first box. Penalty is 14;
2. Take all the balls from the first box, choose k = 2, put balls of color 1 to the first box, of color 2 — to the second box. Penalty is 5.
Total penalty is 19. | instruction | 0 | 499 | 19 | 998 |
Tags: data structures, greedy
Correct Solution:
```
import heapq
input()
heap = [int(i) for i in input().split()]
heapq.heapify(heap)
cost = 0
while len(heap) > 1:
amountToMerge = 3
if len(heap) % 2 == 0:
amountToMerge = 2
mergedPileSize = 0
for _ in range(amountToMerge):
mergedPileSize += heapq.heappop(heap)
cost += mergedPileSize
heapq.heappush(heap, mergedPileSize)
print(cost)
``` | output | 1 | 499 | 19 | 999 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ivan has n different boxes. The first of them contains some balls of n different colors.
Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≤ i ≤ n) i-th box will contain all balls with color i.
In order to do this, Ivan will make some turns. Each turn he does the following:
1. Ivan chooses any non-empty box and takes all balls from this box;
2. Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either k = 2 or k = 3.
The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.
Help Ivan to determine the minimum possible penalty of the game!
Input
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of boxes and colors.
The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the number of balls with color i.
Output
Print one number — the minimum possible penalty of the game.
Examples
Input
3
1 2 3
Output
6
Input
4
2 3 4 5
Output
19
Note
In the first example you take all the balls from the first box, choose k = 3 and sort all colors to corresponding boxes. Penalty is 6.
In the second example you make two turns:
1. Take all the balls from the first box, choose k = 3, put balls of color 3 to the third box, of color 4 — to the fourth box and the rest put back into the first box. Penalty is 14;
2. Take all the balls from the first box, choose k = 2, put balls of color 1 to the first box, of color 2 — to the second box. Penalty is 5.
Total penalty is 19.
Submitted Solution:
```
n=int(input())
import heapq
a=[int(i) for i in input().split()]+[[0],[]][n&1]
heapq.heapify(a)
k=0
while len(a)>1:
s=heapq.heappop(a)+heapq.heappop(a)+heapq.heappop(a)
k+=s
heapq.heappush(a,s)
print(k)
``` | instruction | 0 | 500 | 19 | 1,000 |
Yes | output | 1 | 500 | 19 | 1,001 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ivan has n different boxes. The first of them contains some balls of n different colors.
Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≤ i ≤ n) i-th box will contain all balls with color i.
In order to do this, Ivan will make some turns. Each turn he does the following:
1. Ivan chooses any non-empty box and takes all balls from this box;
2. Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either k = 2 or k = 3.
The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.
Help Ivan to determine the minimum possible penalty of the game!
Input
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of boxes and colors.
The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the number of balls with color i.
Output
Print one number — the minimum possible penalty of the game.
Examples
Input
3
1 2 3
Output
6
Input
4
2 3 4 5
Output
19
Note
In the first example you take all the balls from the first box, choose k = 3 and sort all colors to corresponding boxes. Penalty is 6.
In the second example you make two turns:
1. Take all the balls from the first box, choose k = 3, put balls of color 3 to the third box, of color 4 — to the fourth box and the rest put back into the first box. Penalty is 14;
2. Take all the balls from the first box, choose k = 2, put balls of color 1 to the first box, of color 2 — to the second box. Penalty is 5.
Total penalty is 19.
Submitted Solution:
```
class heap:
def __init__(self, maxn):
self.a = [0] * maxn
self.size = 0
def shift_down(self, i):
while 2 * i + 1 < self.size:
l = 2 * i + 1
r = 2 * i + 2
j = l
if r < self.size and self.a[r] < self.a[l]:
j = r
if self.a[i] <= self.a[j]:
break
self.a[i], self.a[j] = self.a[j], self.a[i]
i = j
def shift_up(self, i):
while i and self.a[i] < self.a[(i - 1) // 2]:
self.a[i], self.a[(i - 1) // 2] = self.a[(i - 1) // 2], self.a[i]
i = (i - 1) // 2
def erase_min(self):
mn = self.a[0]
self.a[0] = self.a[self.size - 1]
self.size -= 1
self.shift_down(0)
return mn
def insert(self, val):
self.size += 1
self.a[self.size - 1] = val
self.shift_up(self.size - 1)
n = int(input())
ans = 0
s = heap(400000 + 100)
for i in [int(j) for j in input().split()]:
s.insert(i)
if s.size % 2 == 0:
s.insert(0)
while s.size > 1:
t = s.erase_min() + s.erase_min()
if s.size:
t += s.erase_min()
ans += t
s.insert(t)
print(ans)
``` | instruction | 0 | 501 | 19 | 1,002 |
Yes | output | 1 | 501 | 19 | 1,003 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ivan has n different boxes. The first of them contains some balls of n different colors.
Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≤ i ≤ n) i-th box will contain all balls with color i.
In order to do this, Ivan will make some turns. Each turn he does the following:
1. Ivan chooses any non-empty box and takes all balls from this box;
2. Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either k = 2 or k = 3.
The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.
Help Ivan to determine the minimum possible penalty of the game!
Input
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of boxes and colors.
The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the number of balls with color i.
Output
Print one number — the minimum possible penalty of the game.
Examples
Input
3
1 2 3
Output
6
Input
4
2 3 4 5
Output
19
Note
In the first example you take all the balls from the first box, choose k = 3 and sort all colors to corresponding boxes. Penalty is 6.
In the second example you make two turns:
1. Take all the balls from the first box, choose k = 3, put balls of color 3 to the third box, of color 4 — to the fourth box and the rest put back into the first box. Penalty is 14;
2. Take all the balls from the first box, choose k = 2, put balls of color 1 to the first box, of color 2 — to the second box. Penalty is 5.
Total penalty is 19.
Submitted Solution:
```
import heapq as h
n=int(input())
a=[int(x) for x in input().split()]
if len(a)%2==0:
a.append(0)
h.heapify(a)
ans=0
while len(a)>1:
a1=h.heappop(a)
a2=h.heappop(a)
a3=h.heappop(a)
ans+=a1+a2+a3
h.heappush(a,a1+a2+a3)
print(ans)
``` | instruction | 0 | 502 | 19 | 1,004 |
Yes | output | 1 | 502 | 19 | 1,005 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ivan has n different boxes. The first of them contains some balls of n different colors.
Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≤ i ≤ n) i-th box will contain all balls with color i.
In order to do this, Ivan will make some turns. Each turn he does the following:
1. Ivan chooses any non-empty box and takes all balls from this box;
2. Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either k = 2 or k = 3.
The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.
Help Ivan to determine the minimum possible penalty of the game!
Input
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of boxes and colors.
The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the number of balls with color i.
Output
Print one number — the minimum possible penalty of the game.
Examples
Input
3
1 2 3
Output
6
Input
4
2 3 4 5
Output
19
Note
In the first example you take all the balls from the first box, choose k = 3 and sort all colors to corresponding boxes. Penalty is 6.
In the second example you make two turns:
1. Take all the balls from the first box, choose k = 3, put balls of color 3 to the third box, of color 4 — to the fourth box and the rest put back into the first box. Penalty is 14;
2. Take all the balls from the first box, choose k = 2, put balls of color 1 to the first box, of color 2 — to the second box. Penalty is 5.
Total penalty is 19.
Submitted Solution:
```
import heapq
n = int(input())
l = [int(i) for i in input().split()]
if n % 2 == 0:
l = [0] + l
result = 0
heapq.heapify(l)
while len(l) > 1:
x = heapq.heappop(l)
y = heapq.heappop(l)
z = heapq.heappop(l)
result += x + y + z
heapq.heappush(l, x + y + z)
print(result)
``` | instruction | 0 | 503 | 19 | 1,006 |
Yes | output | 1 | 503 | 19 | 1,007 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ivan has n different boxes. The first of them contains some balls of n different colors.
Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≤ i ≤ n) i-th box will contain all balls with color i.
In order to do this, Ivan will make some turns. Each turn he does the following:
1. Ivan chooses any non-empty box and takes all balls from this box;
2. Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either k = 2 or k = 3.
The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.
Help Ivan to determine the minimum possible penalty of the game!
Input
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of boxes and colors.
The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the number of balls with color i.
Output
Print one number — the minimum possible penalty of the game.
Examples
Input
3
1 2 3
Output
6
Input
4
2 3 4 5
Output
19
Note
In the first example you take all the balls from the first box, choose k = 3 and sort all colors to corresponding boxes. Penalty is 6.
In the second example you make two turns:
1. Take all the balls from the first box, choose k = 3, put balls of color 3 to the third box, of color 4 — to the fourth box and the rest put back into the first box. Penalty is 14;
2. Take all the balls from the first box, choose k = 2, put balls of color 1 to the first box, of color 2 — to the second box. Penalty is 5.
Total penalty is 19.
Submitted Solution:
```
import heapq
n = input()
A = list(map(int, input().split()))
if (len(A) % 2 == 0):
A.append(0)
st = 0
heapq.heapify(A)
while (len(A) > 1):
abc = 0
a = heapq.heappop(A) # Удаляет и возвращает наименьший элемент кучи A
b = heapq.heappop(A)
c = heapq.heappop(A)
abc = a + b + c
st = st + abc
heapq.heappush(A, abc) #Добавляет значение объекта abc в кучу A
print(A)
print(st)
``` | instruction | 0 | 504 | 19 | 1,008 |
No | output | 1 | 504 | 19 | 1,009 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ivan has n different boxes. The first of them contains some balls of n different colors.
Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≤ i ≤ n) i-th box will contain all balls with color i.
In order to do this, Ivan will make some turns. Each turn he does the following:
1. Ivan chooses any non-empty box and takes all balls from this box;
2. Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either k = 2 or k = 3.
The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.
Help Ivan to determine the minimum possible penalty of the game!
Input
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of boxes and colors.
The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the number of balls with color i.
Output
Print one number — the minimum possible penalty of the game.
Examples
Input
3
1 2 3
Output
6
Input
4
2 3 4 5
Output
19
Note
In the first example you take all the balls from the first box, choose k = 3 and sort all colors to corresponding boxes. Penalty is 6.
In the second example you make two turns:
1. Take all the balls from the first box, choose k = 3, put balls of color 3 to the third box, of color 4 — to the fourth box and the rest put back into the first box. Penalty is 14;
2. Take all the balls from the first box, choose k = 2, put balls of color 1 to the first box, of color 2 — to the second box. Penalty is 5.
Total penalty is 19.
Submitted Solution:
```
import heapq
n = int(input())
arr = list(map(int,input().split()))
sorted(arr)
val = sum(arr)
#print(arr)
num = 0
while(len(arr)> 0 ):
num += val
if(len(arr) == 3):
val -= arr.pop()+arr.pop()+arr.pop()
elif (len(arr) >= 2):
val -= arr.pop()+arr.pop()
else:
val -= arr.pop()
print(num)
``` | instruction | 0 | 505 | 19 | 1,010 |
No | output | 1 | 505 | 19 | 1,011 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ivan has n different boxes. The first of them contains some balls of n different colors.
Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≤ i ≤ n) i-th box will contain all balls with color i.
In order to do this, Ivan will make some turns. Each turn he does the following:
1. Ivan chooses any non-empty box and takes all balls from this box;
2. Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either k = 2 or k = 3.
The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.
Help Ivan to determine the minimum possible penalty of the game!
Input
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of boxes and colors.
The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the number of balls with color i.
Output
Print one number — the minimum possible penalty of the game.
Examples
Input
3
1 2 3
Output
6
Input
4
2 3 4 5
Output
19
Note
In the first example you take all the balls from the first box, choose k = 3 and sort all colors to corresponding boxes. Penalty is 6.
In the second example you make two turns:
1. Take all the balls from the first box, choose k = 3, put balls of color 3 to the third box, of color 4 — to the fourth box and the rest put back into the first box. Penalty is 14;
2. Take all the balls from the first box, choose k = 2, put balls of color 1 to the first box, of color 2 — to the second box. Penalty is 5.
Total penalty is 19.
Submitted Solution:
```
n=int(input())
array=input().split()
fin=[]
for i in array:
fin.append(int(i))
fin.sort()
sums=0
for i in fin:
sums+=i
if(len(fin)<=3):
print(sums)
else:
prev=sums
while(len(fin)>3):
a=fin.pop()
b=fin.pop()
prev=prev-a-b
sums+=prev
print(sums)
``` | instruction | 0 | 506 | 19 | 1,012 |
No | output | 1 | 506 | 19 | 1,013 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ivan has n different boxes. The first of them contains some balls of n different colors.
Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≤ i ≤ n) i-th box will contain all balls with color i.
In order to do this, Ivan will make some turns. Each turn he does the following:
1. Ivan chooses any non-empty box and takes all balls from this box;
2. Then Ivan chooses any k empty boxes (the box from the first step becomes empty, and Ivan is allowed to choose it), separates the balls he took on the previous step into k non-empty groups and puts each group into one of the boxes. He should put each group into a separate box. He can choose either k = 2 or k = 3.
The penalty of the turn is the number of balls Ivan takes from the box during the first step of the turn. And penalty of the game is the total penalty of turns made by Ivan until he distributes all balls to corresponding boxes.
Help Ivan to determine the minimum possible penalty of the game!
Input
The first line contains one integer number n (1 ≤ n ≤ 200000) — the number of boxes and colors.
The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the number of balls with color i.
Output
Print one number — the minimum possible penalty of the game.
Examples
Input
3
1 2 3
Output
6
Input
4
2 3 4 5
Output
19
Note
In the first example you take all the balls from the first box, choose k = 3 and sort all colors to corresponding boxes. Penalty is 6.
In the second example you make two turns:
1. Take all the balls from the first box, choose k = 3, put balls of color 3 to the third box, of color 4 — to the fourth box and the rest put back into the first box. Penalty is 14;
2. Take all the balls from the first box, choose k = 2, put balls of color 1 to the first box, of color 2 — to the second box. Penalty is 5.
Total penalty is 19.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
a.sort()
ans=0
s=sum(a)
ans+=s
if(n==1 or n==2 or n==3):
print(ans)
else:
if(n%2==0):
while(len(a)!=2):
ans+=s
ans-=a[-1]
ans-=a[-2]
a=a[:-2]
else:
while(len(a)!=5):
ans+=s
ans-=a[-1]
ans-=a[-2]
a=a[:-2]
a=a[:-2]
ans+=sum(a)
print(ans)
``` | instruction | 0 | 507 | 19 | 1,014 |
No | output | 1 | 507 | 19 | 1,015 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Rebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted – the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how the first one looks.
Heidi is presented with a screen that shows her a sequence of integers A and a positive integer p. She knows that the encryption code is a single number S, which is defined as follows:
Define the score of X to be the sum of the elements of X modulo p.
Heidi is given a sequence A that consists of N integers, and also given an integer p. She needs to split A into 2 parts such that:
* Each part contains at least 1 element of A, and each part consists of contiguous elements of A.
* The two parts do not overlap.
* The total sum S of the scores of those two parts is maximized. This is the encryption code.
Output the sum S, which is the encryption code.
Input
The first line of the input contains two space-separated integer N and p (2 ≤ N ≤ 100 000, 2 ≤ p ≤ 10 000) – the number of elements in A, and the modulo for computing scores, respectively.
The second line contains N space-separated integers which are the elements of A. Each integer is from the interval [1, 1 000 000].
Output
Output the number S as described in the problem statement.
Examples
Input
4 10
3 4 7 2
Output
16
Input
10 12
16 3 24 13 9 8 7 5 12 12
Output
13
Note
In the first example, the score is maximized if the input sequence is split into two parts as (3, 4), (7, 2). It gives the total score of <image>.
In the second example, the score is maximized if the first part consists of the first three elements, and the second part consists of the rest. Then, the score is <image>. | instruction | 0 | 526 | 19 | 1,052 |
Tags: brute force
Correct Solution:
```
n, p = map(int, input().split())
seq = list(map(int, input().split()))
p1 = 0
p2 = 0
seqSum = sum(seq)
Sums = []
for i in range(n):
p1 += seq[i]
p2 = seqSum - p1
Sums.append((p1%p)+(p2%p))
print(max(Sums))
``` | output | 1 | 526 | 19 | 1,053 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Rebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted – the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how the first one looks.
Heidi is presented with a screen that shows her a sequence of integers A and a positive integer p. She knows that the encryption code is a single number S, which is defined as follows:
Define the score of X to be the sum of the elements of X modulo p.
Heidi is given a sequence A that consists of N integers, and also given an integer p. She needs to split A into 2 parts such that:
* Each part contains at least 1 element of A, and each part consists of contiguous elements of A.
* The two parts do not overlap.
* The total sum S of the scores of those two parts is maximized. This is the encryption code.
Output the sum S, which is the encryption code.
Input
The first line of the input contains two space-separated integer N and p (2 ≤ N ≤ 100 000, 2 ≤ p ≤ 10 000) – the number of elements in A, and the modulo for computing scores, respectively.
The second line contains N space-separated integers which are the elements of A. Each integer is from the interval [1, 1 000 000].
Output
Output the number S as described in the problem statement.
Examples
Input
4 10
3 4 7 2
Output
16
Input
10 12
16 3 24 13 9 8 7 5 12 12
Output
13
Note
In the first example, the score is maximized if the input sequence is split into two parts as (3, 4), (7, 2). It gives the total score of <image>.
In the second example, the score is maximized if the first part consists of the first three elements, and the second part consists of the rest. Then, the score is <image>. | instruction | 0 | 527 | 19 | 1,054 |
Tags: brute force
Correct Solution:
```
line = input().split()
n = int(line[0])
p = int(line[1])
a = input().split()
suma = 0
for i in range(n):
a[i] = int(a[i])
suma += a[i]
Max = 0
sum = 0
for i in range(n-1):
sum += a[i]
total = (sum % p) + ((suma-sum) % p)
if (total>Max):
Max = total
print(Max)
``` | output | 1 | 527 | 19 | 1,055 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Rebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted – the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how the first one looks.
Heidi is presented with a screen that shows her a sequence of integers A and a positive integer p. She knows that the encryption code is a single number S, which is defined as follows:
Define the score of X to be the sum of the elements of X modulo p.
Heidi is given a sequence A that consists of N integers, and also given an integer p. She needs to split A into 2 parts such that:
* Each part contains at least 1 element of A, and each part consists of contiguous elements of A.
* The two parts do not overlap.
* The total sum S of the scores of those two parts is maximized. This is the encryption code.
Output the sum S, which is the encryption code.
Input
The first line of the input contains two space-separated integer N and p (2 ≤ N ≤ 100 000, 2 ≤ p ≤ 10 000) – the number of elements in A, and the modulo for computing scores, respectively.
The second line contains N space-separated integers which are the elements of A. Each integer is from the interval [1, 1 000 000].
Output
Output the number S as described in the problem statement.
Examples
Input
4 10
3 4 7 2
Output
16
Input
10 12
16 3 24 13 9 8 7 5 12 12
Output
13
Note
In the first example, the score is maximized if the input sequence is split into two parts as (3, 4), (7, 2). It gives the total score of <image>.
In the second example, the score is maximized if the first part consists of the first three elements, and the second part consists of the rest. Then, the score is <image>. | instruction | 0 | 528 | 19 | 1,056 |
Tags: brute force
Correct Solution:
```
def main():
n,p = map(int,input().split())
a = [int(x) for x in input().split()]
prefix = [a[0]]
for i in range(1,n):
prefix.append((prefix[-1] + a[i]))
max_sum = -1
for i in range(n-1):
temp = ((prefix[i])%p + (prefix[n-1]-prefix[i])%p)
if max_sum == -1:
max_sum = temp
elif max_sum < temp:
max_sum = temp
print(max_sum)
if __name__ == '__main__':
main()
``` | output | 1 | 528 | 19 | 1,057 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Rebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted – the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how the first one looks.
Heidi is presented with a screen that shows her a sequence of integers A and a positive integer p. She knows that the encryption code is a single number S, which is defined as follows:
Define the score of X to be the sum of the elements of X modulo p.
Heidi is given a sequence A that consists of N integers, and also given an integer p. She needs to split A into 2 parts such that:
* Each part contains at least 1 element of A, and each part consists of contiguous elements of A.
* The two parts do not overlap.
* The total sum S of the scores of those two parts is maximized. This is the encryption code.
Output the sum S, which is the encryption code.
Input
The first line of the input contains two space-separated integer N and p (2 ≤ N ≤ 100 000, 2 ≤ p ≤ 10 000) – the number of elements in A, and the modulo for computing scores, respectively.
The second line contains N space-separated integers which are the elements of A. Each integer is from the interval [1, 1 000 000].
Output
Output the number S as described in the problem statement.
Examples
Input
4 10
3 4 7 2
Output
16
Input
10 12
16 3 24 13 9 8 7 5 12 12
Output
13
Note
In the first example, the score is maximized if the input sequence is split into two parts as (3, 4), (7, 2). It gives the total score of <image>.
In the second example, the score is maximized if the first part consists of the first three elements, and the second part consists of the rest. Then, the score is <image>. | instruction | 0 | 529 | 19 | 1,058 |
Tags: brute force
Correct Solution:
```
n, p = map(int, input().split())
a = list(map(int, input().split()))
resp = -1
aux = 0
tot = sum(a)
for x in a:
aux += x
resp = max(resp, aux%p + (tot - aux) % p)
print(resp)
# 1534609590348
``` | output | 1 | 529 | 19 | 1,059 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Rebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted – the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how the first one looks.
Heidi is presented with a screen that shows her a sequence of integers A and a positive integer p. She knows that the encryption code is a single number S, which is defined as follows:
Define the score of X to be the sum of the elements of X modulo p.
Heidi is given a sequence A that consists of N integers, and also given an integer p. She needs to split A into 2 parts such that:
* Each part contains at least 1 element of A, and each part consists of contiguous elements of A.
* The two parts do not overlap.
* The total sum S of the scores of those two parts is maximized. This is the encryption code.
Output the sum S, which is the encryption code.
Input
The first line of the input contains two space-separated integer N and p (2 ≤ N ≤ 100 000, 2 ≤ p ≤ 10 000) – the number of elements in A, and the modulo for computing scores, respectively.
The second line contains N space-separated integers which are the elements of A. Each integer is from the interval [1, 1 000 000].
Output
Output the number S as described in the problem statement.
Examples
Input
4 10
3 4 7 2
Output
16
Input
10 12
16 3 24 13 9 8 7 5 12 12
Output
13
Note
In the first example, the score is maximized if the input sequence is split into two parts as (3, 4), (7, 2). It gives the total score of <image>.
In the second example, the score is maximized if the first part consists of the first three elements, and the second part consists of the rest. Then, the score is <image>. | instruction | 0 | 530 | 19 | 1,060 |
Tags: brute force
Correct Solution:
```
line1=list(map(int,input().split()))
nums=list(map(int,input().split()))
n,p=line1[0],line1[1]
sum_all=sum(nums)
sum_left=nums[0]
sum_right=sum_all-sum_left
res=sum_left%p + sum_right%p
for i in range(1,n-1):
sum_left+=nums[i]
sum_right-=nums[i]
temp=sum_left%p + sum_right%p
res=max(res,temp)
print(res)
``` | output | 1 | 530 | 19 | 1,061 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Rebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted – the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how the first one looks.
Heidi is presented with a screen that shows her a sequence of integers A and a positive integer p. She knows that the encryption code is a single number S, which is defined as follows:
Define the score of X to be the sum of the elements of X modulo p.
Heidi is given a sequence A that consists of N integers, and also given an integer p. She needs to split A into 2 parts such that:
* Each part contains at least 1 element of A, and each part consists of contiguous elements of A.
* The two parts do not overlap.
* The total sum S of the scores of those two parts is maximized. This is the encryption code.
Output the sum S, which is the encryption code.
Input
The first line of the input contains two space-separated integer N and p (2 ≤ N ≤ 100 000, 2 ≤ p ≤ 10 000) – the number of elements in A, and the modulo for computing scores, respectively.
The second line contains N space-separated integers which are the elements of A. Each integer is from the interval [1, 1 000 000].
Output
Output the number S as described in the problem statement.
Examples
Input
4 10
3 4 7 2
Output
16
Input
10 12
16 3 24 13 9 8 7 5 12 12
Output
13
Note
In the first example, the score is maximized if the input sequence is split into two parts as (3, 4), (7, 2). It gives the total score of <image>.
In the second example, the score is maximized if the first part consists of the first three elements, and the second part consists of the rest. Then, the score is <image>. | instruction | 0 | 531 | 19 | 1,062 |
Tags: brute force
Correct Solution:
```
n, x = map(int, input().split())
a = [int(i) for i in input().split()]
prefix_sums = []
for ind, a_i in enumerate(a):
if ind != 0:
prefix_sums.append(prefix_sums[ind - 1] + a_i)
else:
prefix_sums.append(a_i)
max_sum = 0
for prefix_sum in prefix_sums:
max_sum = max(max_sum, prefix_sum % x + (prefix_sums[-1] - prefix_sum) % x)
print(max_sum)
``` | output | 1 | 531 | 19 | 1,063 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Rebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted – the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how the first one looks.
Heidi is presented with a screen that shows her a sequence of integers A and a positive integer p. She knows that the encryption code is a single number S, which is defined as follows:
Define the score of X to be the sum of the elements of X modulo p.
Heidi is given a sequence A that consists of N integers, and also given an integer p. She needs to split A into 2 parts such that:
* Each part contains at least 1 element of A, and each part consists of contiguous elements of A.
* The two parts do not overlap.
* The total sum S of the scores of those two parts is maximized. This is the encryption code.
Output the sum S, which is the encryption code.
Input
The first line of the input contains two space-separated integer N and p (2 ≤ N ≤ 100 000, 2 ≤ p ≤ 10 000) – the number of elements in A, and the modulo for computing scores, respectively.
The second line contains N space-separated integers which are the elements of A. Each integer is from the interval [1, 1 000 000].
Output
Output the number S as described in the problem statement.
Examples
Input
4 10
3 4 7 2
Output
16
Input
10 12
16 3 24 13 9 8 7 5 12 12
Output
13
Note
In the first example, the score is maximized if the input sequence is split into two parts as (3, 4), (7, 2). It gives the total score of <image>.
In the second example, the score is maximized if the first part consists of the first three elements, and the second part consists of the rest. Then, the score is <image>. | instruction | 0 | 532 | 19 | 1,064 |
Tags: brute force
Correct Solution:
```
n,k = map(int, input().strip().split(' '))
lst = list(map(int, input().strip().split(' ')))
s=sum(lst)
s2=0
m=0
for i in range(n-1):
s2+=lst[i]
s-=lst[i]
if (s2%k)+(s%k)>m:
m=(s2%k)+(s%k)
print(m)
``` | output | 1 | 532 | 19 | 1,065 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Rebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted – the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how the first one looks.
Heidi is presented with a screen that shows her a sequence of integers A and a positive integer p. She knows that the encryption code is a single number S, which is defined as follows:
Define the score of X to be the sum of the elements of X modulo p.
Heidi is given a sequence A that consists of N integers, and also given an integer p. She needs to split A into 2 parts such that:
* Each part contains at least 1 element of A, and each part consists of contiguous elements of A.
* The two parts do not overlap.
* The total sum S of the scores of those two parts is maximized. This is the encryption code.
Output the sum S, which is the encryption code.
Input
The first line of the input contains two space-separated integer N and p (2 ≤ N ≤ 100 000, 2 ≤ p ≤ 10 000) – the number of elements in A, and the modulo for computing scores, respectively.
The second line contains N space-separated integers which are the elements of A. Each integer is from the interval [1, 1 000 000].
Output
Output the number S as described in the problem statement.
Examples
Input
4 10
3 4 7 2
Output
16
Input
10 12
16 3 24 13 9 8 7 5 12 12
Output
13
Note
In the first example, the score is maximized if the input sequence is split into two parts as (3, 4), (7, 2). It gives the total score of <image>.
In the second example, the score is maximized if the first part consists of the first three elements, and the second part consists of the rest. Then, the score is <image>. | instruction | 0 | 533 | 19 | 1,066 |
Tags: brute force
Correct Solution:
```
n, p = map(int, input().split())
seq = list(map(int, input().split()))
del1 = 0
del2 = 0
record = 0
seqSum = sum(seq)
lst = []
lst = []
for i in range(n):
del1 += seq[i]
del2 = seqSum - del1
lst.append((del1%p)+(del2%p))
print(max(lst))
``` | output | 1 | 533 | 19 | 1,067 |
Provide a correct Python 3 solution for this coding contest problem.
The 7 puzzle consists of 8 square cards and a frame that fits them snugly. Each card is numbered 0, 1, 2, ..., 7 to distinguish them from each other. You can arrange two cards vertically and four cards horizontally in the frame.
7 When you start the puzzle, first put all the cards in the frame. Only 0 cards in the frame can be swapped with adjacent cards on the top, bottom, left, and right. For example, when the frame state is shown in Figure (a), if you exchange the position with the 7 card adjacent to the right of the 0 card, you will get the state shown in Figure (b). Alternatively, the state shown in Fig. (A) can be changed to the state shown in Fig. (C) by exchanging the position with the adjacent 2 card under the 0 card. In the state shown in Fig. (A), the cards with 0 and the cards adjacent to the top, bottom, left, and right are only the cards 7 and 2, so other positions cannot be swapped.
The purpose of the game is to arrange the cards neatly so that they are in the state shown in Figure (d). Create a program that takes the initial state as input and outputs the minimum number of steps required to align the cards neatly. However, it is possible to move from the state of the entered card to the state shown in Fig. (D).
The input data is given eight numbers per line, separated by blanks. These represent the initial sequence of cards. For example, the number representation in Figure (a) is 0 7 3 4 2 5 1 6 and Figure (c) is 2 7 3 4 0 5 1 6.
<image> | <image>
--- | ---
Figure (a) 0 7 3 4 2 5 1 6 | Figure (b) 7 0 3 4 2 5 1 6
<image> | <image>
--- | ---
Figure (c) 2 7 3 4 0 5 1 6 | Figure (d) 0 1 2 3 4 5 6 7 (final state)
Input
Multiple puzzles are given in the above format. Please process until the end of the input. No more than 1,000 puzzles will be given.
Output
For each puzzle, output the minimum number of steps to move to the final state on one line.
Example
Input
0 1 2 3 4 5 6 7
1 0 2 3 4 5 6 7
7 6 5 4 3 2 1 0
Output
0
1
28 | instruction | 0 | 687 | 19 | 1,374 |
"Correct Solution:
```
results = {"01234567": 0}
def main():
while True:
try:
tmp = input().replace(' ', '')
print(results[tmp])
except EOFError:
break
def swap(field, a, b):
tmp = list(field)
tmp[b], tmp[a] = tmp[a], tmp[b]
return "".join(tmp)
def convert_matrix_index(index):
return index % 4, int(index / 4)
def convert_array_index(x, y):
return x + y * 4
def bfs(results):
q = [["01234567", 0]]
while len(q) is not 0:
field, res = q.pop(0)
x, y = convert_matrix_index(field.find('0'))
for dx, dy in zip([0, 0, -1, 1], [1, -1, 0, 0]):
nx = x + dx
ny = y + dy
if nx < 0 or ny < 0 or nx >= 4 or ny >= 2:
continue
next_field = swap(field, convert_array_index(x, y), convert_array_index(nx, ny))
if next_field not in results:
results[next_field] = res + 1
q.append([next_field, res + 1])
return results
if __name__ == '__main__':
results = bfs(results)
main()
``` | output | 1 | 687 | 19 | 1,375 |
Provide a correct Python 3 solution for this coding contest problem.
The 7 puzzle consists of 8 square cards and a frame that fits them snugly. Each card is numbered 0, 1, 2, ..., 7 to distinguish them from each other. You can arrange two cards vertically and four cards horizontally in the frame.
7 When you start the puzzle, first put all the cards in the frame. Only 0 cards in the frame can be swapped with adjacent cards on the top, bottom, left, and right. For example, when the frame state is shown in Figure (a), if you exchange the position with the 7 card adjacent to the right of the 0 card, you will get the state shown in Figure (b). Alternatively, the state shown in Fig. (A) can be changed to the state shown in Fig. (C) by exchanging the position with the adjacent 2 card under the 0 card. In the state shown in Fig. (A), the cards with 0 and the cards adjacent to the top, bottom, left, and right are only the cards 7 and 2, so other positions cannot be swapped.
The purpose of the game is to arrange the cards neatly so that they are in the state shown in Figure (d). Create a program that takes the initial state as input and outputs the minimum number of steps required to align the cards neatly. However, it is possible to move from the state of the entered card to the state shown in Fig. (D).
The input data is given eight numbers per line, separated by blanks. These represent the initial sequence of cards. For example, the number representation in Figure (a) is 0 7 3 4 2 5 1 6 and Figure (c) is 2 7 3 4 0 5 1 6.
<image> | <image>
--- | ---
Figure (a) 0 7 3 4 2 5 1 6 | Figure (b) 7 0 3 4 2 5 1 6
<image> | <image>
--- | ---
Figure (c) 2 7 3 4 0 5 1 6 | Figure (d) 0 1 2 3 4 5 6 7 (final state)
Input
Multiple puzzles are given in the above format. Please process until the end of the input. No more than 1,000 puzzles will be given.
Output
For each puzzle, output the minimum number of steps to move to the final state on one line.
Example
Input
0 1 2 3 4 5 6 7
1 0 2 3 4 5 6 7
7 6 5 4 3 2 1 0
Output
0
1
28 | instruction | 0 | 688 | 19 | 1,376 |
"Correct Solution:
```
# AOJ 0121
from collections import deque
score = {}
score[tuple(range(8))] = 0
queue = deque()
queue.append(tuple(range(8)))
move = ((1, 4), (0, 2, 5), (1, 3, 6), (2, 7), (0, 5), (1, 4, 6), (2, 5, 7), (3, 6))
while queue:
puz = queue.popleft()
pos = puz.index(0)
for npos in move[pos]:
npuz = list(puz)
npuz[pos], npuz[npos] = npuz[npos], 0
npuz = tuple(npuz)
if npuz not in score:
queue.append(npuz)
score[npuz] = score[puz] + 1
while True:
try:
puzzle = tuple(map(int, input().split()))
print(score[puzzle])
except EOFError:
break
``` | output | 1 | 688 | 19 | 1,377 |
Provide a correct Python 3 solution for this coding contest problem.
The 7 puzzle consists of 8 square cards and a frame that fits them snugly. Each card is numbered 0, 1, 2, ..., 7 to distinguish them from each other. You can arrange two cards vertically and four cards horizontally in the frame.
7 When you start the puzzle, first put all the cards in the frame. Only 0 cards in the frame can be swapped with adjacent cards on the top, bottom, left, and right. For example, when the frame state is shown in Figure (a), if you exchange the position with the 7 card adjacent to the right of the 0 card, you will get the state shown in Figure (b). Alternatively, the state shown in Fig. (A) can be changed to the state shown in Fig. (C) by exchanging the position with the adjacent 2 card under the 0 card. In the state shown in Fig. (A), the cards with 0 and the cards adjacent to the top, bottom, left, and right are only the cards 7 and 2, so other positions cannot be swapped.
The purpose of the game is to arrange the cards neatly so that they are in the state shown in Figure (d). Create a program that takes the initial state as input and outputs the minimum number of steps required to align the cards neatly. However, it is possible to move from the state of the entered card to the state shown in Fig. (D).
The input data is given eight numbers per line, separated by blanks. These represent the initial sequence of cards. For example, the number representation in Figure (a) is 0 7 3 4 2 5 1 6 and Figure (c) is 2 7 3 4 0 5 1 6.
<image> | <image>
--- | ---
Figure (a) 0 7 3 4 2 5 1 6 | Figure (b) 7 0 3 4 2 5 1 6
<image> | <image>
--- | ---
Figure (c) 2 7 3 4 0 5 1 6 | Figure (d) 0 1 2 3 4 5 6 7 (final state)
Input
Multiple puzzles are given in the above format. Please process until the end of the input. No more than 1,000 puzzles will be given.
Output
For each puzzle, output the minimum number of steps to move to the final state on one line.
Example
Input
0 1 2 3 4 5 6 7
1 0 2 3 4 5 6 7
7 6 5 4 3 2 1 0
Output
0
1
28 | instruction | 0 | 689 | 19 | 1,378 |
"Correct Solution:
```
from collections import deque
from itertools import permutations
from itertools import combinations
puz = [0,1,2,3,4,5,6,7]
puzper = list(permutations(puz))
dic = {}
for i in range(40320):
dic[puzper[i]] = -1
queue = deque([(0,1,2,3,4,5,6,7)])
dic[(0,1,2,3,4,5,6,7)] = 0
while queue:
a = queue.popleft()
poszero = a.index(0)
yy = (poszero) // 4
xx = (poszero) % 4
dydx = [[1,0],[-1,0],[0,1],[0,-1]]
for j,k in dydx:
newy,newx = yy+j,xx+k
if (0 <= newy <2) and (0 <= newx < 4):
newp = newy*4 + newx
lisa = list(a)
lisa[poszero],lisa[newp] = lisa[newp],lisa[poszero]
newper = tuple(lisa)
if (dic[newper] == -1):
dic[newper] = dic[a] + 1
queue.append(newper)
while True:
try:
inp = list(map(int, input().split()))
print(dic[tuple(inp)])
except:
break
``` | output | 1 | 689 | 19 | 1,379 |
Provide a correct Python 3 solution for this coding contest problem.
The 7 puzzle consists of 8 square cards and a frame that fits them snugly. Each card is numbered 0, 1, 2, ..., 7 to distinguish them from each other. You can arrange two cards vertically and four cards horizontally in the frame.
7 When you start the puzzle, first put all the cards in the frame. Only 0 cards in the frame can be swapped with adjacent cards on the top, bottom, left, and right. For example, when the frame state is shown in Figure (a), if you exchange the position with the 7 card adjacent to the right of the 0 card, you will get the state shown in Figure (b). Alternatively, the state shown in Fig. (A) can be changed to the state shown in Fig. (C) by exchanging the position with the adjacent 2 card under the 0 card. In the state shown in Fig. (A), the cards with 0 and the cards adjacent to the top, bottom, left, and right are only the cards 7 and 2, so other positions cannot be swapped.
The purpose of the game is to arrange the cards neatly so that they are in the state shown in Figure (d). Create a program that takes the initial state as input and outputs the minimum number of steps required to align the cards neatly. However, it is possible to move from the state of the entered card to the state shown in Fig. (D).
The input data is given eight numbers per line, separated by blanks. These represent the initial sequence of cards. For example, the number representation in Figure (a) is 0 7 3 4 2 5 1 6 and Figure (c) is 2 7 3 4 0 5 1 6.
<image> | <image>
--- | ---
Figure (a) 0 7 3 4 2 5 1 6 | Figure (b) 7 0 3 4 2 5 1 6
<image> | <image>
--- | ---
Figure (c) 2 7 3 4 0 5 1 6 | Figure (d) 0 1 2 3 4 5 6 7 (final state)
Input
Multiple puzzles are given in the above format. Please process until the end of the input. No more than 1,000 puzzles will be given.
Output
For each puzzle, output the minimum number of steps to move to the final state on one line.
Example
Input
0 1 2 3 4 5 6 7
1 0 2 3 4 5 6 7
7 6 5 4 3 2 1 0
Output
0
1
28 | instruction | 0 | 690 | 19 | 1,380 |
"Correct Solution:
```
from collections import deque
dic = {}
dic[(0,1,2,3,4,5,6,7)] = 0
swap_dic = {0:(1, 4), 1:(0, 2, 5), 2:(1, 3, 6), 3:(2, 7),
4:(0, 5), 5:(1, 4, 6), 6:(2, 5, 7), 7:(3, 6)}
def swap(puz, i, j):
new = [k for k in puz]
new[i], new[j] = new[j], new[i]
return tuple(new)
que = deque()
que.append((0, (0,1,2,3,4,5,6,7)))
while que:
score, puz = que.popleft()
score += 1
z_ind = puz.index(0)
for swap_ind in swap_dic[z_ind]:
new_puz = swap(puz, z_ind, swap_ind)
if not new_puz in dic:
dic[new_puz] = score
que.append((score, new_puz))
while True:
try:
print(dic[tuple(map(int, input().split()))])
except EOFError:
break
``` | output | 1 | 690 | 19 | 1,381 |
Provide a correct Python 3 solution for this coding contest problem.
The 7 puzzle consists of 8 square cards and a frame that fits them snugly. Each card is numbered 0, 1, 2, ..., 7 to distinguish them from each other. You can arrange two cards vertically and four cards horizontally in the frame.
7 When you start the puzzle, first put all the cards in the frame. Only 0 cards in the frame can be swapped with adjacent cards on the top, bottom, left, and right. For example, when the frame state is shown in Figure (a), if you exchange the position with the 7 card adjacent to the right of the 0 card, you will get the state shown in Figure (b). Alternatively, the state shown in Fig. (A) can be changed to the state shown in Fig. (C) by exchanging the position with the adjacent 2 card under the 0 card. In the state shown in Fig. (A), the cards with 0 and the cards adjacent to the top, bottom, left, and right are only the cards 7 and 2, so other positions cannot be swapped.
The purpose of the game is to arrange the cards neatly so that they are in the state shown in Figure (d). Create a program that takes the initial state as input and outputs the minimum number of steps required to align the cards neatly. However, it is possible to move from the state of the entered card to the state shown in Fig. (D).
The input data is given eight numbers per line, separated by blanks. These represent the initial sequence of cards. For example, the number representation in Figure (a) is 0 7 3 4 2 5 1 6 and Figure (c) is 2 7 3 4 0 5 1 6.
<image> | <image>
--- | ---
Figure (a) 0 7 3 4 2 5 1 6 | Figure (b) 7 0 3 4 2 5 1 6
<image> | <image>
--- | ---
Figure (c) 2 7 3 4 0 5 1 6 | Figure (d) 0 1 2 3 4 5 6 7 (final state)
Input
Multiple puzzles are given in the above format. Please process until the end of the input. No more than 1,000 puzzles will be given.
Output
For each puzzle, output the minimum number of steps to move to the final state on one line.
Example
Input
0 1 2 3 4 5 6 7
1 0 2 3 4 5 6 7
7 6 5 4 3 2 1 0
Output
0
1
28 | instruction | 0 | 691 | 19 | 1,382 |
"Correct Solution:
```
import itertools
import collections
INF = 10 ** 9
def Z(): return int(input())
def ZZ(): return [int(_) for _ in input().split()]
def main():
p = collections.defaultdict(int)
q = collections.defaultdict(list)
for i, v in enumerate(itertools.permutations(range(8))):
p[v] = i
q[i] = list(v)
dist = [INF] * (40325)
dist[0] = 0
que = collections.deque()
que.append(0)
def change(i, j, l):
d = dist[p[tuple(l)]]
l[i], l[j] = l[j], l[i]
if dist[p[tuple(l)]] == INF:
dist[p[tuple(l)]] = d + 1
que.append(p[tuple(l)])
l[i], l[j] = l[j], l[i]
return
while que:
v = que.popleft()
ll = q[v]
i = ll.index(0)
if i in {0, 4}: change(i, i+1, ll)
elif i in {3, 7}: change(i-1, i, ll)
else:
change(i, i+1, ll)
change(i-1, i, ll)
change(i, (i+4)%8, ll)
while True:
try:
A = ZZ()
print(dist[p[tuple(A)]])
except:
break
return
if __name__ == '__main__':
main()
``` | output | 1 | 691 | 19 | 1,383 |
Provide a correct Python 3 solution for this coding contest problem.
The 7 puzzle consists of 8 square cards and a frame that fits them snugly. Each card is numbered 0, 1, 2, ..., 7 to distinguish them from each other. You can arrange two cards vertically and four cards horizontally in the frame.
7 When you start the puzzle, first put all the cards in the frame. Only 0 cards in the frame can be swapped with adjacent cards on the top, bottom, left, and right. For example, when the frame state is shown in Figure (a), if you exchange the position with the 7 card adjacent to the right of the 0 card, you will get the state shown in Figure (b). Alternatively, the state shown in Fig. (A) can be changed to the state shown in Fig. (C) by exchanging the position with the adjacent 2 card under the 0 card. In the state shown in Fig. (A), the cards with 0 and the cards adjacent to the top, bottom, left, and right are only the cards 7 and 2, so other positions cannot be swapped.
The purpose of the game is to arrange the cards neatly so that they are in the state shown in Figure (d). Create a program that takes the initial state as input and outputs the minimum number of steps required to align the cards neatly. However, it is possible to move from the state of the entered card to the state shown in Fig. (D).
The input data is given eight numbers per line, separated by blanks. These represent the initial sequence of cards. For example, the number representation in Figure (a) is 0 7 3 4 2 5 1 6 and Figure (c) is 2 7 3 4 0 5 1 6.
<image> | <image>
--- | ---
Figure (a) 0 7 3 4 2 5 1 6 | Figure (b) 7 0 3 4 2 5 1 6
<image> | <image>
--- | ---
Figure (c) 2 7 3 4 0 5 1 6 | Figure (d) 0 1 2 3 4 5 6 7 (final state)
Input
Multiple puzzles are given in the above format. Please process until the end of the input. No more than 1,000 puzzles will be given.
Output
For each puzzle, output the minimum number of steps to move to the final state on one line.
Example
Input
0 1 2 3 4 5 6 7
1 0 2 3 4 5 6 7
7 6 5 4 3 2 1 0
Output
0
1
28 | instruction | 0 | 692 | 19 | 1,384 |
"Correct Solution:
```
from __future__ import division
import sys
if sys.version_info[0]>=3: raw_input=input
X=4
Y=2
i=0
m={}
prev={}
v=[]
for i in range(X*Y): v.append(str(i))
m[''.join(v)]=[0,0]
prev[''.join(v)]=[''.join(v),None]
q=[v]
while len(q)>0:
v=q.pop(0)
coor=m[''.join(v)][0]
x=coor%X
y=coor//X
depth=m[''.join(v)][1]
nextstr=''.join(v)
if 0<x:
v[coor],v[coor-1]=v[coor-1],v[coor]
if ''.join(v) not in m:
m[''.join(v)]=[coor-1,depth+1]
q.append(v[:])
prev[''.join(v)]=[nextstr,'R']
v[coor],v[coor-1]=v[coor-1],v[coor]
if x<X-1:
v[coor],v[coor+1]=v[coor+1],v[coor]
if ''.join(v) not in m:
m[''.join(v)]=[coor+1,depth+1]
q.append(v[:])
prev[''.join(v)]=[nextstr,'L']
v[coor],v[coor+1]=v[coor+1],v[coor]
if 0<y:
v[coor],v[coor-X]=v[coor-X],v[coor]
if ''.join(v) not in m:
m[''.join(v)]=[coor-X,depth+1]
q.append(v[:])
prev[''.join(v)]=[nextstr,'D']
v[coor],v[coor-X]=v[coor-X],v[coor]
if y<Y-1:
v[coor],v[coor+X]=v[coor+X],v[coor]
if ''.join(v) not in m:
m[''.join(v)]=[coor+X,depth+1]
q.append(v[:])
prev[''.join(v)]=[nextstr,'U']
v[coor],v[coor+X]=v[coor+X],v[coor]
try:
while True:
v=raw_input().split()
print(m[''.join(v)][1])
except EOFError:
pass
``` | output | 1 | 692 | 19 | 1,385 |
Provide a correct Python 3 solution for this coding contest problem.
The 7 puzzle consists of 8 square cards and a frame that fits them snugly. Each card is numbered 0, 1, 2, ..., 7 to distinguish them from each other. You can arrange two cards vertically and four cards horizontally in the frame.
7 When you start the puzzle, first put all the cards in the frame. Only 0 cards in the frame can be swapped with adjacent cards on the top, bottom, left, and right. For example, when the frame state is shown in Figure (a), if you exchange the position with the 7 card adjacent to the right of the 0 card, you will get the state shown in Figure (b). Alternatively, the state shown in Fig. (A) can be changed to the state shown in Fig. (C) by exchanging the position with the adjacent 2 card under the 0 card. In the state shown in Fig. (A), the cards with 0 and the cards adjacent to the top, bottom, left, and right are only the cards 7 and 2, so other positions cannot be swapped.
The purpose of the game is to arrange the cards neatly so that they are in the state shown in Figure (d). Create a program that takes the initial state as input and outputs the minimum number of steps required to align the cards neatly. However, it is possible to move from the state of the entered card to the state shown in Fig. (D).
The input data is given eight numbers per line, separated by blanks. These represent the initial sequence of cards. For example, the number representation in Figure (a) is 0 7 3 4 2 5 1 6 and Figure (c) is 2 7 3 4 0 5 1 6.
<image> | <image>
--- | ---
Figure (a) 0 7 3 4 2 5 1 6 | Figure (b) 7 0 3 4 2 5 1 6
<image> | <image>
--- | ---
Figure (c) 2 7 3 4 0 5 1 6 | Figure (d) 0 1 2 3 4 5 6 7 (final state)
Input
Multiple puzzles are given in the above format. Please process until the end of the input. No more than 1,000 puzzles will be given.
Output
For each puzzle, output the minimum number of steps to move to the final state on one line.
Example
Input
0 1 2 3 4 5 6 7
1 0 2 3 4 5 6 7
7 6 5 4 3 2 1 0
Output
0
1
28 | instruction | 0 | 693 | 19 | 1,386 |
"Correct Solution:
```
from collections import deque
swap = [[1, 4], [0, 2, 5], [1, 3, 6], [2, 7], [0, 5], [1, 4, 6], [2, 5, 7], [3, 6]]
def bfs():
ia = list(range(8))
count = {
str(ia): 0
}
q = deque()
q.append([ia, 0])
while q:
a, c = q.popleft()
i = a.index(0)
for j in swap[i]:
na = a.copy()
na[i], na[j] = na[j], na[i]
if str(na) not in count:
count[str(na)] = c + 1
q.append([na, c+1])
return count
if __name__ == '__main__':
count = bfs()
while True:
try:
a = list(map(int, input().split()))
print(count[str(a)])
except:
break
``` | output | 1 | 693 | 19 | 1,387 |
Provide a correct Python 3 solution for this coding contest problem.
The 7 puzzle consists of 8 square cards and a frame that fits them snugly. Each card is numbered 0, 1, 2, ..., 7 to distinguish them from each other. You can arrange two cards vertically and four cards horizontally in the frame.
7 When you start the puzzle, first put all the cards in the frame. Only 0 cards in the frame can be swapped with adjacent cards on the top, bottom, left, and right. For example, when the frame state is shown in Figure (a), if you exchange the position with the 7 card adjacent to the right of the 0 card, you will get the state shown in Figure (b). Alternatively, the state shown in Fig. (A) can be changed to the state shown in Fig. (C) by exchanging the position with the adjacent 2 card under the 0 card. In the state shown in Fig. (A), the cards with 0 and the cards adjacent to the top, bottom, left, and right are only the cards 7 and 2, so other positions cannot be swapped.
The purpose of the game is to arrange the cards neatly so that they are in the state shown in Figure (d). Create a program that takes the initial state as input and outputs the minimum number of steps required to align the cards neatly. However, it is possible to move from the state of the entered card to the state shown in Fig. (D).
The input data is given eight numbers per line, separated by blanks. These represent the initial sequence of cards. For example, the number representation in Figure (a) is 0 7 3 4 2 5 1 6 and Figure (c) is 2 7 3 4 0 5 1 6.
<image> | <image>
--- | ---
Figure (a) 0 7 3 4 2 5 1 6 | Figure (b) 7 0 3 4 2 5 1 6
<image> | <image>
--- | ---
Figure (c) 2 7 3 4 0 5 1 6 | Figure (d) 0 1 2 3 4 5 6 7 (final state)
Input
Multiple puzzles are given in the above format. Please process until the end of the input. No more than 1,000 puzzles will be given.
Output
For each puzzle, output the minimum number of steps to move to the final state on one line.
Example
Input
0 1 2 3 4 5 6 7
1 0 2 3 4 5 6 7
7 6 5 4 3 2 1 0
Output
0
1
28 | instruction | 0 | 694 | 19 | 1,388 |
"Correct Solution:
```
from collections import deque
import copy
swap = [[1, 4], [0, 2, 5], [1, 3, 6], [2, 7], [0, 5], [1, 4, 6], [2, 5, 7], [3, 6]]
def bfs():
ia = list(range(8))
count = {str(ia): 0}
que = deque()
que.append((ia, 0))
while len(que) != 0:
state, cnt = que.popleft()
# pos:0?????????
pos = state.index(0)
swap_target = swap[pos]
for i in swap_target:
tmp_state = copy.copy(state)
tmp_state[i], tmp_state[pos] = tmp_state[pos], tmp_state[i]
if str(tmp_state) not in count:
count[str(tmp_state)] = cnt + 1
que.append((tmp_state, cnt + 1))
return count
if __name__ == '__main__':
count = bfs()
while True:
try:
prob = list(map(int, input().split()))
print(count[str(prob)])
except:
break
``` | output | 1 | 694 | 19 | 1,389 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The 7 puzzle consists of 8 square cards and a frame that fits them snugly. Each card is numbered 0, 1, 2, ..., 7 to distinguish them from each other. You can arrange two cards vertically and four cards horizontally in the frame.
7 When you start the puzzle, first put all the cards in the frame. Only 0 cards in the frame can be swapped with adjacent cards on the top, bottom, left, and right. For example, when the frame state is shown in Figure (a), if you exchange the position with the 7 card adjacent to the right of the 0 card, you will get the state shown in Figure (b). Alternatively, the state shown in Fig. (A) can be changed to the state shown in Fig. (C) by exchanging the position with the adjacent 2 card under the 0 card. In the state shown in Fig. (A), the cards with 0 and the cards adjacent to the top, bottom, left, and right are only the cards 7 and 2, so other positions cannot be swapped.
The purpose of the game is to arrange the cards neatly so that they are in the state shown in Figure (d). Create a program that takes the initial state as input and outputs the minimum number of steps required to align the cards neatly. However, it is possible to move from the state of the entered card to the state shown in Fig. (D).
The input data is given eight numbers per line, separated by blanks. These represent the initial sequence of cards. For example, the number representation in Figure (a) is 0 7 3 4 2 5 1 6 and Figure (c) is 2 7 3 4 0 5 1 6.
<image> | <image>
--- | ---
Figure (a) 0 7 3 4 2 5 1 6 | Figure (b) 7 0 3 4 2 5 1 6
<image> | <image>
--- | ---
Figure (c) 2 7 3 4 0 5 1 6 | Figure (d) 0 1 2 3 4 5 6 7 (final state)
Input
Multiple puzzles are given in the above format. Please process until the end of the input. No more than 1,000 puzzles will be given.
Output
For each puzzle, output the minimum number of steps to move to the final state on one line.
Example
Input
0 1 2 3 4 5 6 7
1 0 2 3 4 5 6 7
7 6 5 4 3 2 1 0
Output
0
1
28
Submitted Solution:
```
# AOJ 0121 Seven Puzzle
# Python 2017.6.23 bal4u
def swap(state, x, y):
s = list(state)
s[x], s[y] = s[y], s[x]
return tuple(s)
from collections import deque
MAGIC = 37
move = ((1,4), (0,2,5), (1,3,6), (2,7), (0,5), (1,4,6), (2,5,7), (3,6))
Q = deque()
Q.append(((0,1,2,3,4,5,6,7), 0))
hash = {}
hash[(0,1,2,3,4,5,6,7)] = 0
while Q:
state, x = Q.popleft()
step = hash[state]+1
if step > MAGIC: continue
for y in move[x]:
nstate = swap(state, x, y)
if nstate not in hash: nstep = 100
else: nstep = hash[nstate]
if step < nstep:
Q.append((nstate, y))
hash[nstate] = step
while 1:
try: state = tuple(map(int, input().split()))
except: break
print(hash[state])
``` | instruction | 0 | 695 | 19 | 1,390 |
Yes | output | 1 | 695 | 19 | 1,391 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The 7 puzzle consists of 8 square cards and a frame that fits them snugly. Each card is numbered 0, 1, 2, ..., 7 to distinguish them from each other. You can arrange two cards vertically and four cards horizontally in the frame.
7 When you start the puzzle, first put all the cards in the frame. Only 0 cards in the frame can be swapped with adjacent cards on the top, bottom, left, and right. For example, when the frame state is shown in Figure (a), if you exchange the position with the 7 card adjacent to the right of the 0 card, you will get the state shown in Figure (b). Alternatively, the state shown in Fig. (A) can be changed to the state shown in Fig. (C) by exchanging the position with the adjacent 2 card under the 0 card. In the state shown in Fig. (A), the cards with 0 and the cards adjacent to the top, bottom, left, and right are only the cards 7 and 2, so other positions cannot be swapped.
The purpose of the game is to arrange the cards neatly so that they are in the state shown in Figure (d). Create a program that takes the initial state as input and outputs the minimum number of steps required to align the cards neatly. However, it is possible to move from the state of the entered card to the state shown in Fig. (D).
The input data is given eight numbers per line, separated by blanks. These represent the initial sequence of cards. For example, the number representation in Figure (a) is 0 7 3 4 2 5 1 6 and Figure (c) is 2 7 3 4 0 5 1 6.
<image> | <image>
--- | ---
Figure (a) 0 7 3 4 2 5 1 6 | Figure (b) 7 0 3 4 2 5 1 6
<image> | <image>
--- | ---
Figure (c) 2 7 3 4 0 5 1 6 | Figure (d) 0 1 2 3 4 5 6 7 (final state)
Input
Multiple puzzles are given in the above format. Please process until the end of the input. No more than 1,000 puzzles will be given.
Output
For each puzzle, output the minimum number of steps to move to the final state on one line.
Example
Input
0 1 2 3 4 5 6 7
1 0 2 3 4 5 6 7
7 6 5 4 3 2 1 0
Output
0
1
28
Submitted Solution:
```
# -*- coding: utf-8 -*-
def main():
line = input().strip()
while line!='':
print(0)
line = input().strip()
if __name__=='__main__':
main()
``` | instruction | 0 | 696 | 19 | 1,392 |
No | output | 1 | 696 | 19 | 1,393 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The 7 puzzle consists of 8 square cards and a frame that fits them snugly. Each card is numbered 0, 1, 2, ..., 7 to distinguish them from each other. You can arrange two cards vertically and four cards horizontally in the frame.
7 When you start the puzzle, first put all the cards in the frame. Only 0 cards in the frame can be swapped with adjacent cards on the top, bottom, left, and right. For example, when the frame state is shown in Figure (a), if you exchange the position with the 7 card adjacent to the right of the 0 card, you will get the state shown in Figure (b). Alternatively, the state shown in Fig. (A) can be changed to the state shown in Fig. (C) by exchanging the position with the adjacent 2 card under the 0 card. In the state shown in Fig. (A), the cards with 0 and the cards adjacent to the top, bottom, left, and right are only the cards 7 and 2, so other positions cannot be swapped.
The purpose of the game is to arrange the cards neatly so that they are in the state shown in Figure (d). Create a program that takes the initial state as input and outputs the minimum number of steps required to align the cards neatly. However, it is possible to move from the state of the entered card to the state shown in Fig. (D).
The input data is given eight numbers per line, separated by blanks. These represent the initial sequence of cards. For example, the number representation in Figure (a) is 0 7 3 4 2 5 1 6 and Figure (c) is 2 7 3 4 0 5 1 6.
<image> | <image>
--- | ---
Figure (a) 0 7 3 4 2 5 1 6 | Figure (b) 7 0 3 4 2 5 1 6
<image> | <image>
--- | ---
Figure (c) 2 7 3 4 0 5 1 6 | Figure (d) 0 1 2 3 4 5 6 7 (final state)
Input
Multiple puzzles are given in the above format. Please process until the end of the input. No more than 1,000 puzzles will be given.
Output
For each puzzle, output the minimum number of steps to move to the final state on one line.
Example
Input
0 1 2 3 4 5 6 7
1 0 2 3 4 5 6 7
7 6 5 4 3 2 1 0
Output
0
1
28
Submitted Solution:
```
# -*- coding: utf-8 -*-
line = input().strip()
while line!='':
print(0)
line = input().strip()
``` | instruction | 0 | 697 | 19 | 1,394 |
No | output | 1 | 697 | 19 | 1,395 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The 7 puzzle consists of 8 square cards and a frame that fits them snugly. Each card is numbered 0, 1, 2, ..., 7 to distinguish them from each other. You can arrange two cards vertically and four cards horizontally in the frame.
7 When you start the puzzle, first put all the cards in the frame. Only 0 cards in the frame can be swapped with adjacent cards on the top, bottom, left, and right. For example, when the frame state is shown in Figure (a), if you exchange the position with the 7 card adjacent to the right of the 0 card, you will get the state shown in Figure (b). Alternatively, the state shown in Fig. (A) can be changed to the state shown in Fig. (C) by exchanging the position with the adjacent 2 card under the 0 card. In the state shown in Fig. (A), the cards with 0 and the cards adjacent to the top, bottom, left, and right are only the cards 7 and 2, so other positions cannot be swapped.
The purpose of the game is to arrange the cards neatly so that they are in the state shown in Figure (d). Create a program that takes the initial state as input and outputs the minimum number of steps required to align the cards neatly. However, it is possible to move from the state of the entered card to the state shown in Fig. (D).
The input data is given eight numbers per line, separated by blanks. These represent the initial sequence of cards. For example, the number representation in Figure (a) is 0 7 3 4 2 5 1 6 and Figure (c) is 2 7 3 4 0 5 1 6.
<image> | <image>
--- | ---
Figure (a) 0 7 3 4 2 5 1 6 | Figure (b) 7 0 3 4 2 5 1 6
<image> | <image>
--- | ---
Figure (c) 2 7 3 4 0 5 1 6 | Figure (d) 0 1 2 3 4 5 6 7 (final state)
Input
Multiple puzzles are given in the above format. Please process until the end of the input. No more than 1,000 puzzles will be given.
Output
For each puzzle, output the minimum number of steps to move to the final state on one line.
Example
Input
0 1 2 3 4 5 6 7
1 0 2 3 4 5 6 7
7 6 5 4 3 2 1 0
Output
0
1
28
Submitted Solution:
```
# -*- coding: utf-8 -*-
import copy,sys
def solve(pieace):
history,frontier = set(),set()
frontier.add(tuple(pieace))
target_list = list(range(8))
step = 0
while True:
next_frontier = set()
for pieace in frontier:
if all(x==y for x,y in zip(pieace,target_list)):
# print([(x,y) for x,y in zip(pieace,target_list)])
return step
zero_position = pieace.index(0)
relative = zero_position%4
new_peiace = list(copy.deepcopy(pieace))
new_peiace[relative],new_peiace[relative+4] = new_peiace[relative+4],new_peiace[relative]
new_peiace = tuple(new_peiace)
if new_peiace not in history:
next_frontier.add(new_peiace)
if relative in [0,1,2]:
new_peiace = list(copy.deepcopy(pieace))
new_peiace[zero_position],new_peiace[zero_position+1] = new_peiace[zero_position+1],new_peiace[zero_position]
new_peiace = tuple(new_peiace)
if new_peiace not in history:
next_frontier.add(new_peiace)
if relative in [1,2,3]:
new_peiace = list(copy.deepcopy(pieace))
new_peiace[zero_position],new_peiace[zero_position-1] = new_peiace[zero_position-1],new_peiace[zero_position]
new_peiace = tuple(new_peiace)
if new_peiace not in history:
next_frontier.add(new_peiace)
history |= frontier
frontier = next_frontier
step += 1
def main():
line = input().strip()
while line!='':
pieace = list(map(int,line.split(' ')))
print(solve(pieace))
line = input().strip()
if __name__=='__main__':
main()
``` | instruction | 0 | 698 | 19 | 1,396 |
No | output | 1 | 698 | 19 | 1,397 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The 7 puzzle consists of 8 square cards and a frame that fits them snugly. Each card is numbered 0, 1, 2, ..., 7 to distinguish them from each other. You can arrange two cards vertically and four cards horizontally in the frame.
7 When you start the puzzle, first put all the cards in the frame. Only 0 cards in the frame can be swapped with adjacent cards on the top, bottom, left, and right. For example, when the frame state is shown in Figure (a), if you exchange the position with the 7 card adjacent to the right of the 0 card, you will get the state shown in Figure (b). Alternatively, the state shown in Fig. (A) can be changed to the state shown in Fig. (C) by exchanging the position with the adjacent 2 card under the 0 card. In the state shown in Fig. (A), the cards with 0 and the cards adjacent to the top, bottom, left, and right are only the cards 7 and 2, so other positions cannot be swapped.
The purpose of the game is to arrange the cards neatly so that they are in the state shown in Figure (d). Create a program that takes the initial state as input and outputs the minimum number of steps required to align the cards neatly. However, it is possible to move from the state of the entered card to the state shown in Fig. (D).
The input data is given eight numbers per line, separated by blanks. These represent the initial sequence of cards. For example, the number representation in Figure (a) is 0 7 3 4 2 5 1 6 and Figure (c) is 2 7 3 4 0 5 1 6.
<image> | <image>
--- | ---
Figure (a) 0 7 3 4 2 5 1 6 | Figure (b) 7 0 3 4 2 5 1 6
<image> | <image>
--- | ---
Figure (c) 2 7 3 4 0 5 1 6 | Figure (d) 0 1 2 3 4 5 6 7 (final state)
Input
Multiple puzzles are given in the above format. Please process until the end of the input. No more than 1,000 puzzles will be given.
Output
For each puzzle, output the minimum number of steps to move to the final state on one line.
Example
Input
0 1 2 3 4 5 6 7
1 0 2 3 4 5 6 7
7 6 5 4 3 2 1 0
Output
0
1
28
Submitted Solution:
```
while True:
line = input().strip()
if len(line)==0:break
print(0)
"""
/*
0 1 2 3 4 5 6 7
1 0 2 3 4 5 6 7
7 6 5 4 3 2 1 0
0
1
28
*/
"""
``` | instruction | 0 | 699 | 19 | 1,398 |
No | output | 1 | 699 | 19 | 1,399 |
Provide a correct Python 3 solution for this coding contest problem.
problem
There are n cards with one integer from 1 to n and one blank card. Of these n + 1 cards, k cards are given, but 1 ≤ k ≤ n. You can write one integer from 1 to n on a blank card. I want to make a continuous sequence of integers as long as possible with just a given card.
Write a program that outputs the maximum length of a contiguous sequence of integers that can be made from a given card when the given card is entered.
input
The input consists of multiple datasets. Each dataset is given in the following format. The input ends on a line containing two zeros.
On the first line, two integers n (1 ≤ n ≤ 100000) and k (1 ≤ k ≤ n) are written in this order, separated by one blank. The following k line contains one integer. Written one by one, representing the integers written on the given k cards. Blank cards are represented by 0.
Of the scoring data, 40% of the points are 1 ≤ n ≤ 1000, 1 ≤ k ≤ 500, 20% of the points are 1 ≤ n ≤ 60000, 1 ≤ k ≤ 50000. Satisfy 1 ≤ n ≤ 100000, 1 ≤ k ≤ 100000.
The number of datasets does not exceed 5.
output
Outputs an integer on one line for each dataset.
Examples
Input
7 5
6
2
4
7
1
7 5
6
2
0
4
7
0 0
Output
2
4
Input
None
Output
None | instruction | 0 | 716 | 19 | 1,432 |
"Correct Solution:
```
while True:
try:
n,k = map(int,input().split())
if n == 0 and k == 0: break
lst = [0 for _ in range(n)]
lst2 = []
flag = 0
for _ in range(k):
i = int(input())
if not i:
flag = 1
else:
lst[i - 1] = 1
l = -1
r = -1
for i in range(n):
if lst[i] == 0:
if r != -1:
lst2.append((l,r))
l = -1
r = -1
else:
if l == -1:
l = i
r = i
else:
r += 1
else:
if r != -1:
lst2.append((l,r))
ans = 0
# print(lst)
# print(lst2)
if not flag:
for t in lst2:
ans = max(ans,t[1] - t[0] + 1)
else:
for i in range(len(lst2)):
if i == 0:
ans = max(ans,lst2[0][1] - lst2[0][0] + 1)
elif lst2[i][0] - lst2[i - 1][1] == 2:
ans = max(ans,lst2[i][1] - lst2[i - 1][0] + 1)
else:
ans = max(ans,lst2[i][1] - lst2[i][0] + 1)
print(ans)
except EOFError:
break
``` | output | 1 | 716 | 19 | 1,433 |
Provide a correct Python 3 solution for this coding contest problem.
problem
There are n cards with one integer from 1 to n and one blank card. Of these n + 1 cards, k cards are given, but 1 ≤ k ≤ n. You can write one integer from 1 to n on a blank card. I want to make a continuous sequence of integers as long as possible with just a given card.
Write a program that outputs the maximum length of a contiguous sequence of integers that can be made from a given card when the given card is entered.
input
The input consists of multiple datasets. Each dataset is given in the following format. The input ends on a line containing two zeros.
On the first line, two integers n (1 ≤ n ≤ 100000) and k (1 ≤ k ≤ n) are written in this order, separated by one blank. The following k line contains one integer. Written one by one, representing the integers written on the given k cards. Blank cards are represented by 0.
Of the scoring data, 40% of the points are 1 ≤ n ≤ 1000, 1 ≤ k ≤ 500, 20% of the points are 1 ≤ n ≤ 60000, 1 ≤ k ≤ 50000. Satisfy 1 ≤ n ≤ 100000, 1 ≤ k ≤ 100000.
The number of datasets does not exceed 5.
output
Outputs an integer on one line for each dataset.
Examples
Input
7 5
6
2
4
7
1
7 5
6
2
0
4
7
0 0
Output
2
4
Input
None
Output
None | instruction | 0 | 717 | 19 | 1,434 |
"Correct Solution:
```
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict, deque, OrderedDict
from copy import deepcopy
from fractions import gcd
from functools import lru_cache, reduce
from math import ceil, floor
from sys import setrecursionlimit
import heapq
import itertools
import operator
# globals
inf = float('inf')
N, K = [], []
C = []
def set_inputs():
global N, K, C
while True:
n, k = get_li()
if n == k == 0:
break
N.append(n)
K.append(k)
c = get_data(k, [int])
C.append(c)
return
def sgn(n):
if n == 0:
return 0
if n > 0:
return 1
return -1
def main():
setrecursionlimit(100000)
set_inputs()
# ----------MAIN----------
for n, k, c in zip(N, K, C):
c.sort()
ans = 0
if c[0] == 0:
tmp = 1
for v1, v2 in zip(c[1:], c[2:]):
if v2 - v1 == 1:
tmp += 1 * sgn(tmp)
if abs(tmp) > abs(ans):
ans = tmp
elif v2 - v1 == 2:
if tmp > 0:
tmp = -tmp - 2
else:
tmp = -3
else:
tmp = 1
if ans > 0:
ans += 1
ans = abs(ans)
else:
tmp = 1
for v1, v2 in zip(c, c[1:]):
if v2 - v1 == 1:
tmp += 1
ans = max(ans, tmp)
else:
tmp = 1
print(ans)
return
def get_int():
return int(input())
def get_float():
return float(input())
def get_str():
return input().strip()
def get_li():
return [int(i) for i in input().split()]
def get_lf():
return [float(f) for f in input().split()]
def get_lc():
return list(input().strip())
def get_data(n, types, sep=None):
if len(types) == 1:
return [types[0](input()) for _ in range(n)]
return list(zip(*(
[t(x) for t, x in zip(types, input().split(sep=sep))]
for _ in range(n)
)))
if __name__ == '__main__':
main()
``` | output | 1 | 717 | 19 | 1,435 |
Provide a correct Python 3 solution for this coding contest problem.
problem
There are n cards with one integer from 1 to n and one blank card. Of these n + 1 cards, k cards are given, but 1 ≤ k ≤ n. You can write one integer from 1 to n on a blank card. I want to make a continuous sequence of integers as long as possible with just a given card.
Write a program that outputs the maximum length of a contiguous sequence of integers that can be made from a given card when the given card is entered.
input
The input consists of multiple datasets. Each dataset is given in the following format. The input ends on a line containing two zeros.
On the first line, two integers n (1 ≤ n ≤ 100000) and k (1 ≤ k ≤ n) are written in this order, separated by one blank. The following k line contains one integer. Written one by one, representing the integers written on the given k cards. Blank cards are represented by 0.
Of the scoring data, 40% of the points are 1 ≤ n ≤ 1000, 1 ≤ k ≤ 500, 20% of the points are 1 ≤ n ≤ 60000, 1 ≤ k ≤ 50000. Satisfy 1 ≤ n ≤ 100000, 1 ≤ k ≤ 100000.
The number of datasets does not exceed 5.
output
Outputs an integer on one line for each dataset.
Examples
Input
7 5
6
2
4
7
1
7 5
6
2
0
4
7
0 0
Output
2
4
Input
None
Output
None | instruction | 0 | 718 | 19 | 1,436 |
"Correct Solution:
```
# -*- coding: utf-8 -*-
"""
Longest Steps
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0517
"""
import sys
def solve(cards):
if len(cards) == 1:
return 1
has_white = True if cards[0] == 0 else False
res = []
t = []
prev = cards[has_white] - 1
for c in cards[has_white:]:
if c == prev + 1:
t.append(c)
else:
res.append(t)
t = [c]
prev = c
res.append(t)
ans = max(len(r) + has_white for r in res)
if has_white:
for a, b in zip(res, res[1:]):
if a[-1] + 2 == b[0]:
ans = max(ans, len(a)+len(b)+1)
return ans
def main(args):
while True:
n, k = map(int, input().split())
if n == 0 and k == 0:
break
cards = sorted([int(input()) for _ in range(k)])
ans = solve(cards)
print(ans)
if __name__ == '__main__':
main(sys.argv[1:])
``` | output | 1 | 718 | 19 | 1,437 |
Provide a correct Python 3 solution for this coding contest problem.
problem
There are n cards with one integer from 1 to n and one blank card. Of these n + 1 cards, k cards are given, but 1 ≤ k ≤ n. You can write one integer from 1 to n on a blank card. I want to make a continuous sequence of integers as long as possible with just a given card.
Write a program that outputs the maximum length of a contiguous sequence of integers that can be made from a given card when the given card is entered.
input
The input consists of multiple datasets. Each dataset is given in the following format. The input ends on a line containing two zeros.
On the first line, two integers n (1 ≤ n ≤ 100000) and k (1 ≤ k ≤ n) are written in this order, separated by one blank. The following k line contains one integer. Written one by one, representing the integers written on the given k cards. Blank cards are represented by 0.
Of the scoring data, 40% of the points are 1 ≤ n ≤ 1000, 1 ≤ k ≤ 500, 20% of the points are 1 ≤ n ≤ 60000, 1 ≤ k ≤ 50000. Satisfy 1 ≤ n ≤ 100000, 1 ≤ k ≤ 100000.
The number of datasets does not exceed 5.
output
Outputs an integer on one line for each dataset.
Examples
Input
7 5
6
2
4
7
1
7 5
6
2
0
4
7
0 0
Output
2
4
Input
None
Output
None | instruction | 0 | 719 | 19 | 1,438 |
"Correct Solution:
```
anss = []
flag = False
def main():
N, K = [int(i) for i in input().split()]
if N == K == 0:
global flag
flag = True
return
A = [int(input()) for _ in range(K)]
A.sort()
zero = False
if A[0] == 0:
zero = True
prev = -1
last_island = -1
current_streak = 0
ans = 0
for a in A:
if prev == -1 or a == prev + 1:
current_streak += 1
elif zero == True and a == prev + 2:
last_island = current_streak
current_streak = 1
else:
last_island = -1
current_streak = 1
ans = max(current_streak + last_island + 1, ans)
prev = a
global anss
anss.append(ans)
while not flag:
main()
for a in anss:
print(a)
``` | output | 1 | 719 | 19 | 1,439 |
Provide a correct Python 3 solution for this coding contest problem.
problem
There are n cards with one integer from 1 to n and one blank card. Of these n + 1 cards, k cards are given, but 1 ≤ k ≤ n. You can write one integer from 1 to n on a blank card. I want to make a continuous sequence of integers as long as possible with just a given card.
Write a program that outputs the maximum length of a contiguous sequence of integers that can be made from a given card when the given card is entered.
input
The input consists of multiple datasets. Each dataset is given in the following format. The input ends on a line containing two zeros.
On the first line, two integers n (1 ≤ n ≤ 100000) and k (1 ≤ k ≤ n) are written in this order, separated by one blank. The following k line contains one integer. Written one by one, representing the integers written on the given k cards. Blank cards are represented by 0.
Of the scoring data, 40% of the points are 1 ≤ n ≤ 1000, 1 ≤ k ≤ 500, 20% of the points are 1 ≤ n ≤ 60000, 1 ≤ k ≤ 50000. Satisfy 1 ≤ n ≤ 100000, 1 ≤ k ≤ 100000.
The number of datasets does not exceed 5.
output
Outputs an integer on one line for each dataset.
Examples
Input
7 5
6
2
4
7
1
7 5
6
2
0
4
7
0 0
Output
2
4
Input
None
Output
None | instruction | 0 | 720 | 19 | 1,440 |
"Correct Solution:
```
while True:
n, k = map(int, input().split())
if not n:
break
cards = [int(input()) for _ in range(k)]
cards.sort(reverse=True)
white = False
if not cards[-1]:
white = True
cards.pop()
if not cards:
print(1)
continue
prev, cnt, precnt = cards.pop(), 1, 0
ans = 1
while cards:
cur = cards.pop()
diff = cur - prev
if diff == 1:
cnt += 1
else:
ans = max(ans, precnt + cnt)
precnt = (cnt + 1) if white and diff == 2 else 0
cnt = 1
prev = cur
ans = max(ans, precnt + cnt)
print(ans)
``` | output | 1 | 720 | 19 | 1,441 |
Provide a correct Python 3 solution for this coding contest problem.
problem
There are n cards with one integer from 1 to n and one blank card. Of these n + 1 cards, k cards are given, but 1 ≤ k ≤ n. You can write one integer from 1 to n on a blank card. I want to make a continuous sequence of integers as long as possible with just a given card.
Write a program that outputs the maximum length of a contiguous sequence of integers that can be made from a given card when the given card is entered.
input
The input consists of multiple datasets. Each dataset is given in the following format. The input ends on a line containing two zeros.
On the first line, two integers n (1 ≤ n ≤ 100000) and k (1 ≤ k ≤ n) are written in this order, separated by one blank. The following k line contains one integer. Written one by one, representing the integers written on the given k cards. Blank cards are represented by 0.
Of the scoring data, 40% of the points are 1 ≤ n ≤ 1000, 1 ≤ k ≤ 500, 20% of the points are 1 ≤ n ≤ 60000, 1 ≤ k ≤ 50000. Satisfy 1 ≤ n ≤ 100000, 1 ≤ k ≤ 100000.
The number of datasets does not exceed 5.
output
Outputs an integer on one line for each dataset.
Examples
Input
7 5
6
2
4
7
1
7 5
6
2
0
4
7
0 0
Output
2
4
Input
None
Output
None | instruction | 0 | 721 | 19 | 1,442 |
"Correct Solution:
```
import sys
input=sys.stdin.readline
while True:
a=[]
n,k=map(int,input().split())
if n==k==0:
break
zero=False
for i in range(k):
p=int(input())
if p==0:
zero=True
continue
a.append(p)
a.sort()
if zero==False:
r=a[0]-1
ans=0
ans_kari=0
for i in range(k):
if a[i]==r+1:
r=a[i]
ans_kari+=1
else:
ans=max(ans,ans_kari)
ans_kari=1
r=a[i]
print(ans)
else:
sa=[]
for i in range(k-2):
sa.append(a[i+1]-a[i])
ans=l=r=0
for i in range(len(sa)):
if sa[i]==1:
r+=1
elif sa[i]==2:
l=r
r=1
else:
l=0
r=1
ans=max(ans,l+r+1)
print(ans)
``` | output | 1 | 721 | 19 | 1,443 |
Provide a correct Python 3 solution for this coding contest problem.
problem
There are n cards with one integer from 1 to n and one blank card. Of these n + 1 cards, k cards are given, but 1 ≤ k ≤ n. You can write one integer from 1 to n on a blank card. I want to make a continuous sequence of integers as long as possible with just a given card.
Write a program that outputs the maximum length of a contiguous sequence of integers that can be made from a given card when the given card is entered.
input
The input consists of multiple datasets. Each dataset is given in the following format. The input ends on a line containing two zeros.
On the first line, two integers n (1 ≤ n ≤ 100000) and k (1 ≤ k ≤ n) are written in this order, separated by one blank. The following k line contains one integer. Written one by one, representing the integers written on the given k cards. Blank cards are represented by 0.
Of the scoring data, 40% of the points are 1 ≤ n ≤ 1000, 1 ≤ k ≤ 500, 20% of the points are 1 ≤ n ≤ 60000, 1 ≤ k ≤ 50000. Satisfy 1 ≤ n ≤ 100000, 1 ≤ k ≤ 100000.
The number of datasets does not exceed 5.
output
Outputs an integer on one line for each dataset.
Examples
Input
7 5
6
2
4
7
1
7 5
6
2
0
4
7
0 0
Output
2
4
Input
None
Output
None | instruction | 0 | 722 | 19 | 1,444 |
"Correct Solution:
```
while True:
n,k=[int(s)for s in input().split(" ")]
if n==k==0:break
card=sorted([int(input())for i in range(k)])
blank=card[0]==0
if blank:card.pop(0)
lens=[]
con=[]
tl=1
i=0
while i<len(card)-1:
if card[i+1]==card[i]+1:tl+=1
else:
if card[i+1]==card[i]+2:con.append(True)
else:con.append(False)
lens.append(tl)
tl=1
i+=1
lens.append(tl)
if not blank:print(max(lens))
else:
l=0
for i in range(len(con)):
if con[i]:
l=max((l,lens[i]+lens[i+1]+1))
print(l)
``` | output | 1 | 722 | 19 | 1,445 |
End of preview. Expand
in Data Studio
- Downloads last month
- 9