text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Jeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence p1, p2, ..., pn for his birthday.
Jeff hates inversions in sequences. An inversion in sequence a1, a2, ..., an is a pair of indexes i, j (1 β€ i < j β€ n), such that an inequality ai > aj holds.
Jeff can multiply some numbers of the sequence p by -1. At that, he wants the number of inversions in the sequence to be minimum. Help Jeff and find the minimum number of inversions he manages to get.
Input
The first line contains integer n (1 β€ n β€ 2000). The next line contains n integers β sequence p1, p2, ..., pn (|pi| β€ 105). The numbers are separated by spaces.
Output
In a single line print the answer to the problem β the minimum number of inversions Jeff can get.
Examples
Input
2
2 1
Output
0
Input
9
-2 0 -1 0 -1 2 1 0 -1
Output
6
Submitted Solution:
```
print("QUE TE CACHEN PROBLEMA E(DIV1)")
print("By: GUillermo Montanez Sosa - Guillermo_0114")
```
No
| 102,400 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Jeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence p1, p2, ..., pn for his birthday.
Jeff hates inversions in sequences. An inversion in sequence a1, a2, ..., an is a pair of indexes i, j (1 β€ i < j β€ n), such that an inequality ai > aj holds.
Jeff can multiply some numbers of the sequence p by -1. At that, he wants the number of inversions in the sequence to be minimum. Help Jeff and find the minimum number of inversions he manages to get.
Input
The first line contains integer n (1 β€ n β€ 2000). The next line contains n integers β sequence p1, p2, ..., pn (|pi| β€ 105). The numbers are separated by spaces.
Output
In a single line print the answer to the problem β the minimum number of inversions Jeff can get.
Examples
Input
2
2 1
Output
0
Input
9
-2 0 -1 0 -1 2 1 0 -1
Output
6
Submitted Solution:
```
n = int(input())
inp = input()
seq = inp.split(' ')
seq = [ abs(int(x)) for x in seq ]
Max = max(seq)
nxt = [0] * n
cnt = [0] * n
pos = [n] * (Max+1)
for i in range(n-1, -1, -1):
nxt[i] = pos[seq[i]]
pos[seq[i]] = i
for i in range(0, Max+1):
j = pos[i]
while(j<n):
front = sum(cnt[0:j])
back = sum(cnt[j+1:n])
if(front < back):
seq[j] = 0 - seq[j]
cnt[j] = 1
j = nxt[j]
#for i in range(0, n-1):
# print(seq[i], sep=' ')
#print(seq[n-1])
inv = 0
for i in range(len(seq)):
for j in range(i+1, len(seq)):
if(seq[i] > seq[j]):
inv += 1
print(inv)
```
No
| 102,401 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Tags: implementation, math
Correct Solution:
```
s1, s2 = map(str, input().split('^'))
l1, l2 = 0, 0
for i in range(len(s1)):
if s1[i].isdigit():
l1 += int(s1[i]) * (len(s1) - i)
for i in range(len(s2)):
if s2[i].isdigit():
l2 += int(s2[i]) * (i + 1)
if l1 == l2:
print('balance')
elif l1 > l2:
print('left')
else:
print('right')
```
| 102,402 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Tags: implementation, math
Correct Solution:
```
s = input()
pivot = s.find('^')
value = 0
for i in range(len(s)):
if s[i].isdigit():
value += int(s[i]) * (i - pivot)
if value < 0:
print('left')
elif value == 0:
print('balance')
else:
print('right')
```
| 102,403 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Tags: implementation, math
Correct Solution:
```
s = input().strip()
n = len(s)
i = s.find('^')
left = 0
right = 0
l = i - 1
r = i + 1
while l >= 0 or r < n:
if l >= 0 and s[l] != '=':
left += int(s[l])*(i - l)
l -= 1
else:
l -= 1
if r < n and s[r] != '=':
right += int(s[r]) * (r - i)
r += 1
else:
r += 1
if left == right:
print("balance")
elif left > right:
print("left")
else:
print("right")
```
| 102,404 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Tags: implementation, math
Correct Solution:
```
a=input()
p=a.index('^')
c=sum((i-p)*int(y) for i,y in enumerate(a) if y.isdigit())
print([['balance','right'][c>0],'left'][c<0])
```
| 102,405 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Tags: implementation, math
Correct Solution:
```
s = input()
p = s.index('^')
f = 0
for i in range(len(s)):
if s[i]=='1':
f = f-((p-i)*1)
elif s[i]=='2':
f = f - ((p-i)*2)
elif s[i]=='3':
f = f - ((p-i)*3)
elif s[i]=='4':
f = f - ((p-i)*4)
elif s[i]=='5':
f = f - ((p-i)*5)
elif s[i]=='6':
f = f - ((p-i)*6)
elif s[i]=='7':
f = f - ((p-i)*7)
elif s[i]=='8':
f = f - ((p-i)*8)
elif s[i]=='9':
f = f - ((p-i)*9)
if f<0:
print("left")
elif f>0:
print("right")
else:
print("balance")
```
| 102,406 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Tags: implementation, math
Correct Solution:
```
s=[n for n in input()]
k=s.index('^')
a=s[:k][::-1]
b=s[k+1:]
m=0
for n in range(len(a)):
if ord('0')<=ord(a[n])<=ord('9'):
m+=int(a[n])*(n+1)
p=0
for n in range(len(b)):
if ord('0')<=ord(b[n])<=ord('9'):
p+=int(b[n])*(n+1)
if m==p:
print('balance')
elif m>p:
print('left')
elif m<p:
print('right')
```
| 102,407 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Tags: implementation, math
Correct Solution:
```
a = input()
i = 0
r = 0
l = 0
while(a[i] != "^"):
i = i+1
k = i
for j in range(i):
if(a[j]!= "="):
l = l +k*int(a[j])
k = k-1
k = 1
i +=1
while(i<len(a)):
if(a[i]!= "="):
r = r+k*int(a[i])
i = i+1
k = k+1
if(r==l):
print("balance")
elif(l>r):
print("left")
else:
print("right")
```
| 102,408 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Tags: implementation, math
Correct Solution:
```
# -*- coding: utf-8 -*-
s1, s2 = input().split('^')
s1 = s1[::-1]
l1 = sum([(i+1) * int(s1[i]) for i in range(len(s1)) if s1[i] != '='])
l2 = sum([(i+1) * int(s2[i]) for i in range(len(s2)) if s2[i] != '='])
print('balance' if l1==l2 else 'left' if l1>l2 else 'right')
```
| 102,409 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Submitted Solution:
```
s=input()
z=s.find('^')
a=s[:z]
b=s[z+1:]
x='123456789'
s1=0
s2=0
if set(a)==set(b) and set(a)=={'='}:
print("balance")
else:
for i in range(len(a)):
if a[i] in x:
s1+=int(a[i])*(len(a)-i)
for j in range(len(b)):
if b[j] in x:
s2+=int(b[j])*(j+1)
if s1==s2:
print("balance")
elif s1>s2:
print("left")
else:
print("right")
```
Yes
| 102,410 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Submitted Solution:
```
s = str(input())
l = s[:s.find("^")]
r = s[s.find("^")+1:]
r = r[::-1]
lw = 0
rw = 0
for i in range(len(l)):
if l[i] != "=":
lw+=int(l[i])*len(l[i:])
for i in range(len(r)):
if r[i] != "=":
rw+=int(r[i])*len(r[i:])
if rw>lw: print("right")
elif rw<lw: print("left")
else: print("balance")
```
Yes
| 102,411 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Submitted Solution:
```
s = str(input())
for cont in range(0,len(s)):
if s[cont] == '^':
pos = cont
break
left = 0
right = 0
for d in range(0, pos):
if s[d].isdigit():
left += int(s[d])*(pos-d)
for d in range(pos+1,len(s)):
if s[d].isdigit():
right += int(s[d])*(d-pos)
if left == right:
print('balance')
elif right> left:
print('right')
else:
print('left')
```
Yes
| 102,412 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Submitted Solution:
```
# Made By Mostafa_Khaled
bot = True
l = input()
p = l.index('^')
b = sum((i - p) * int(x) for i, x in enumerate(l) if x.isdigit())
if b != 0:
b //= abs(b)
print(['left', 'balance', 'right'][b + 1])
# Made By Mostafa_Khaled
```
Yes
| 102,413 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Submitted Solution:
```
s = input()
sm = 0
for i in range(len(s)):
if s[i] == '^':
ind = i
break
if s[i] != '=':
sm += int(s[i])
for i in range(ind + 1, len(s)):
if s[i] != '=':
sm -= int(s[i])
if sm == 0: print("balance")
elif sm > 0: print("left")
else: print("right")
```
No
| 102,414 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Submitted Solution:
```
from sys import stdout, stdin, setrecursionlimit
from io import BytesIO, IOBase
from collections import *
from itertools import *
from random import *
from bisect import *
from string import *
from queue import *
from heapq import *
from math import *
from re import *
from os import *
####################################---fast-input-output----#########################################
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = read(self._fd, max(fstat(self._fd).st_size, 8192))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = read(self._fd, max(fstat(self._fd).st_size, 8192))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
stdin, stdout = IOWrapper(stdin), IOWrapper(stdout)
graph, mod, szzz = {}, 10**9 + 7, lambda: sorted(zzz())
def getInt(): return int(input())
def listStr(): return list(input())
def getStrs(): return input().split()
def isInt(s): return '0' <= s[0] <= '9'
def input(): return stdin.readline().strip()
def zzz(): return [int(i) for i in input().split()]
def output(answer, end='\n'): stdout.write(str(answer) + end)
def lcd(xnum1, xnum2): return (xnum1 * xnum2 // gcd(xnum1, xnum2))
dx = [-1, 1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, 1, -1, 1, -1, -1, 1]
daysInMounth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
#################################################---Some Rule For Me To Follow---#################################
"""
--instants of Reading problem continuously try to understand them.
--If you Know some-one , Then you probably don't know him !
--Try & again try
"""
##################################################---START-CODING---###############################################
l,r = input().split('^')
l=l[::-1]
left=0
right=0
for i in range(len(l)):
if isInt(l[i]):
left+=(i*1)*int(l[i])
for i in range(len(r)):
if isInt(r[i]):
right+=(i+1)*int(r[i])
if right>left:
print('right')
elif right<left:
print('left')
else:
print('balance')
# s=input()
# r=s.index("^")
# sum=0
# for i in range(len(s)):
# if s[i]!="=" and s[i]!="^":
# sum+=int(s[i])*(i-r)
# if sum<0:
# print("left")
# elif sum>0:
# print("right")
# else:
# print("balance")
#
```
No
| 102,415 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Submitted Solution:
```
s = input()
left = 0
right = 0
ind = s.find('^')
for i in range(ind):
#print("right: ",right," ele: ",i)
if(s[i]=='='):
left-=1
else:
left+=int(s[i])
for i in range(ind+1,len(s)):
if(s[i]=='='):
right-=1
else:
right+=int(s[i])
#print(left,right)
if(right<0):
right = 0
if(left<0):
left = 0
if(left==right):
print("balance")
elif(left>right):
print("left")
else:
print("right")
```
No
| 102,416 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is given below.
* If the i-th character of the string equals "^", that means that at coordinate i there is the pivot under the bar.
* If the i-th character of the string equals "=", that means that at coordinate i there is nothing lying on the bar.
* If the i-th character of the string equals digit c (1-9), that means that at coordinate i there is a weight of mass c on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
Input
The first line contains the lever description as a non-empty string s (3 β€ |s| β€ 106), consisting of digits (1-9) and characters "^" and "=". It is guaranteed that the line contains exactly one character "^". It is guaranteed that the pivot of the lever isn't located in any end of the lever bar.
To solve the problem you may need 64-bit integer numbers. Please, do not forget to use them in your programs.
Output
Print "left" if the given lever tilts to the left, "right" if it tilts to the right and "balance", if it is in balance.
Examples
Input
=^==
Output
balance
Input
9===^==1
Output
left
Input
2==^7==
Output
right
Input
41^52==
Output
balance
Note
As you solve the problem, you may find the following link useful to better understand how a lever functions: http://en.wikipedia.org/wiki/Lever.
The pictures to the examples:
<image> <image> <image> <image>
Submitted Solution:
```
s = input()
m = s.find('^')
res = [(int(x)*s.find(x)+1)*(m-s.find(x)+1) for x in s if x.isdigit()]
if sum(res) == 0: print('balance')
elif sum(res) < 0: print('left')
else: print('right')
```
No
| 102,417 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble.
The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble.
But the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts:
* each cup contains a mark β a number from 1 to n; all marks on the cups are distinct;
* the magician shuffles the cups in m operations, each operation looks like that: take a cup marked xi, sitting at position yi in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position).
When the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist.
Input
The first line contains integers n and m (1 β€ n, m β€ 106). Each of the next m lines contains a couple of integers. The i-th line contains integers xi, yi (1 β€ xi, yi β€ n) β the description of the i-th operation of the magician. Note that the operations are given in the order in which the magician made them and the coder wants to make them in the same order.
Output
If the described permutation doesn't exist (the programmer remembered wrong operations), print -1. Otherwise, print n distinct integers, each from 1 to n: the i-th number should represent the mark on the cup that initially is in the row in position i.
If there are multiple correct answers, you should print the lexicographically minimum one.
Examples
Input
2 1
2 1
Output
2 1
Input
3 2
1 2
1 1
Output
2 1 3
Input
3 3
1 3
2 3
1 3
Output
-1
Tags: data structures
Correct Solution:
```
import io
import os
# List with O(n^1/3) (for n=10**6) get/set/insert/delete based on: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
class UnsortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i : i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
# self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
# _mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
# _mins[pos] = _lists[pos][0]
pass
else:
del _lists[pos]
del _list_lens[pos]
# del _mins[pos]
self._rebuild = True
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __setitem__(self, index, value):
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._lists[pos][idx] = value
def insert(self, index, value):
_load = self._load
_lists = self._lists
_list_lens = self._list_lens
if _lists:
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_list_lens.append(1)
self._rebuild = True
self._len += 1
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return "SortedList({0})".format(list(self))
def solve(N, M, queries):
idToMark = [-1 for i in range(N)]
cups = UnsortedList([i for i in range(N)])
for mark, pos in queries:
pos -= 1 # 0-indexed
cupId = cups[pos]
del cups[pos]
cups.insert(0, cupId)
if idToMark[cupId] == -1:
idToMark[cupId] = mark
elif idToMark[cupId] != mark:
return b"-1"
markToCounts = [0 for i in range(N + 1)]
for cupId, mark in enumerate(idToMark):
if mark != -1:
markToCounts[mark] += 1
if markToCounts[mark] > 1:
return b"-1"
j = 1
ans = []
for cupId, mark in enumerate(idToMark):
if mark != -1:
ans.append(mark)
else:
while markToCounts[j] > 0:
j += 1
ans.append(j)
j += 1
return b" ".join(str(x).encode("ascii") for x in ans)
if False:
N, M = 10 ** 6, 10 ** 6
queries = [[N // 2 + (i % (N // 2)), N // 2] for i in range(M)]
ans = solve(N, M, queries)
# print(ans)
assert ans != b"-1"
exit()
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
queries = ((int(x) for x in input().split()) for i in range(M))
ans = solve(N, M, queries)
os.write(1, ans)
```
| 102,418 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble.
The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble.
But the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts:
* each cup contains a mark β a number from 1 to n; all marks on the cups are distinct;
* the magician shuffles the cups in m operations, each operation looks like that: take a cup marked xi, sitting at position yi in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position).
When the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist.
Input
The first line contains integers n and m (1 β€ n, m β€ 106). Each of the next m lines contains a couple of integers. The i-th line contains integers xi, yi (1 β€ xi, yi β€ n) β the description of the i-th operation of the magician. Note that the operations are given in the order in which the magician made them and the coder wants to make them in the same order.
Output
If the described permutation doesn't exist (the programmer remembered wrong operations), print -1. Otherwise, print n distinct integers, each from 1 to n: the i-th number should represent the mark on the cup that initially is in the row in position i.
If there are multiple correct answers, you should print the lexicographically minimum one.
Examples
Input
2 1
2 1
Output
2 1
Input
3 2
1 2
1 1
Output
2 1 3
Input
3 3
1 3
2 3
1 3
Output
-1
Tags: data structures
Correct Solution:
```
import io
import os
# List with O(n^1/3) (for n=10**6) get/set/insert/delete based on: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
class UnsortedList:
def __init__(self, iterable=[], _load=600):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i : i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
# self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
# _mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
# _mins[pos] = _lists[pos][0]
pass
else:
del _lists[pos]
del _list_lens[pos]
# del _mins[pos]
self._rebuild = True
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __setitem__(self, index, value):
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._lists[pos][idx] = value
def insert(self, index, value):
_load = self._load
_lists = self._lists
_list_lens = self._list_lens
if _lists:
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_list_lens.append(1)
self._rebuild = True
self._len += 1
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return "SortedList({0})".format(list(self))
def solve(N, M, queries):
idToMark = [-1 for i in range(N)]
cups = UnsortedList([i for i in range(N)])
for mark, pos in queries:
pos -= 1 # 0-indexed
cupId = cups[pos]
del cups[pos]
cups.insert(0, cupId)
if idToMark[cupId] == -1:
idToMark[cupId] = mark
elif idToMark[cupId] != mark:
return b"-1"
markToCounts = [0 for i in range(N + 1)]
for cupId, mark in enumerate(idToMark):
if mark != -1:
markToCounts[mark] += 1
if markToCounts[mark] > 1:
return b"-1"
j = 1
ans = []
for cupId, mark in enumerate(idToMark):
if mark != -1:
ans.append(mark)
else:
while markToCounts[j] > 0:
j += 1
ans.append(j)
j += 1
return b" ".join(str(x).encode("ascii") for x in ans)
if False:
N, M = 10 ** 6, 10 ** 6
queries = [[N // 2 + (i % (N // 2)), N // 2] for i in range(M)]
ans = solve(N, M, queries)
# print(ans)
assert ans != b"-1"
exit()
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
queries = ((int(x) for x in input().split()) for i in range(M))
ans = solve(N, M, queries)
os.write(1, ans)
```
| 102,419 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble.
The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble.
But the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts:
* each cup contains a mark β a number from 1 to n; all marks on the cups are distinct;
* the magician shuffles the cups in m operations, each operation looks like that: take a cup marked xi, sitting at position yi in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position).
When the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist.
Input
The first line contains integers n and m (1 β€ n, m β€ 106). Each of the next m lines contains a couple of integers. The i-th line contains integers xi, yi (1 β€ xi, yi β€ n) β the description of the i-th operation of the magician. Note that the operations are given in the order in which the magician made them and the coder wants to make them in the same order.
Output
If the described permutation doesn't exist (the programmer remembered wrong operations), print -1. Otherwise, print n distinct integers, each from 1 to n: the i-th number should represent the mark on the cup that initially is in the row in position i.
If there are multiple correct answers, you should print the lexicographically minimum one.
Examples
Input
2 1
2 1
Output
2 1
Input
3 2
1 2
1 1
Output
2 1 3
Input
3 3
1 3
2 3
1 3
Output
-1
Tags: data structures
Correct Solution:
```
import io
import os
# List with O(n^1/3) (for n=10**6) get/set/insert/delete based on: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
class UnsortedList:
def __init__(self, iterable=[], _load=400):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i : i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
# self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
# _mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
# _mins[pos] = _lists[pos][0]
pass
else:
del _lists[pos]
del _list_lens[pos]
# del _mins[pos]
self._rebuild = True
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __setitem__(self, index, value):
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._lists[pos][idx] = value
def insert(self, index, value):
_load = self._load
_lists = self._lists
_list_lens = self._list_lens
if _lists:
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_list_lens.append(1)
self._rebuild = True
self._len += 1
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return "SortedList({0})".format(list(self))
def solve(N, M, queries):
idToMark = [-1 for i in range(N)]
cups = UnsortedList([i for i in range(N)])
for mark, pos in queries:
pos -= 1 # 0-indexed
cupId = cups[pos]
del cups[pos]
cups.insert(0, cupId)
if idToMark[cupId] == -1:
idToMark[cupId] = mark
elif idToMark[cupId] != mark:
return b"-1"
markToCounts = [0 for i in range(N + 1)]
for cupId, mark in enumerate(idToMark):
if mark != -1:
markToCounts[mark] += 1
if markToCounts[mark] > 1:
return b"-1"
j = 1
ans = []
for cupId, mark in enumerate(idToMark):
if mark != -1:
ans.append(mark)
else:
while markToCounts[j] > 0:
j += 1
ans.append(j)
j += 1
return b" ".join(str(x).encode("ascii") for x in ans)
if False:
N, M = 10 ** 6, 10 ** 6
queries = [[N // 2 + (i % (N // 2)), N // 2] for i in range(M)]
ans = solve(N, M, queries)
# print(ans)
assert ans != b"-1"
exit()
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
queries = ((int(x) for x in input().split()) for i in range(M))
ans = solve(N, M, queries)
os.write(1, ans)
```
| 102,420 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble.
The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble.
But the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts:
* each cup contains a mark β a number from 1 to n; all marks on the cups are distinct;
* the magician shuffles the cups in m operations, each operation looks like that: take a cup marked xi, sitting at position yi in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position).
When the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist.
Input
The first line contains integers n and m (1 β€ n, m β€ 106). Each of the next m lines contains a couple of integers. The i-th line contains integers xi, yi (1 β€ xi, yi β€ n) β the description of the i-th operation of the magician. Note that the operations are given in the order in which the magician made them and the coder wants to make them in the same order.
Output
If the described permutation doesn't exist (the programmer remembered wrong operations), print -1. Otherwise, print n distinct integers, each from 1 to n: the i-th number should represent the mark on the cup that initially is in the row in position i.
If there are multiple correct answers, you should print the lexicographically minimum one.
Examples
Input
2 1
2 1
Output
2 1
Input
3 2
1 2
1 1
Output
2 1 3
Input
3 3
1 3
2 3
1 3
Output
-1
Tags: data structures
Correct Solution:
```
import io
import os
# List with O(n^1/3) (for n=10**6) get/set/insert/delete based on: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
class UnsortedList:
def __init__(self, iterable=[], _load=1000):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i : i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
# self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
# _mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
# _mins[pos] = _lists[pos][0]
pass
else:
del _lists[pos]
del _list_lens[pos]
# del _mins[pos]
self._rebuild = True
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __setitem__(self, index, value):
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._lists[pos][idx] = value
def insert(self, index, value):
_load = self._load
_lists = self._lists
_list_lens = self._list_lens
if _lists:
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_list_lens.append(1)
self._rebuild = True
self._len += 1
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return "SortedList({0})".format(list(self))
def solve(N, M, queries):
idToMark = [-1 for i in range(N)]
cups = UnsortedList([i for i in range(N)])
for mark, pos in queries:
pos -= 1 # 0-indexed
cupId = cups[pos]
del cups[pos]
cups.insert(0, cupId)
if idToMark[cupId] == -1:
idToMark[cupId] = mark
elif idToMark[cupId] != mark:
return b"-1"
markToCounts = [0 for i in range(N + 1)]
for cupId, mark in enumerate(idToMark):
if mark != -1:
markToCounts[mark] += 1
if markToCounts[mark] > 1:
return b"-1"
j = 1
ans = []
for cupId, mark in enumerate(idToMark):
if mark != -1:
ans.append(mark)
else:
while markToCounts[j] > 0:
j += 1
ans.append(j)
j += 1
return b" ".join(str(x).encode("ascii") for x in ans)
if False:
N, M = 10 ** 6, 10 ** 6
queries = [[N // 2 + (i % (N // 2)), N // 2] for i in range(M)]
ans = solve(N, M, queries)
# print(ans)
assert ans != b"-1"
exit()
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
queries = ((int(x) for x in input().split()) for i in range(M))
ans = solve(N, M, queries)
os.write(1, ans)
```
| 102,421 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble.
The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble.
But the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts:
* each cup contains a mark β a number from 1 to n; all marks on the cups are distinct;
* the magician shuffles the cups in m operations, each operation looks like that: take a cup marked xi, sitting at position yi in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position).
When the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist.
Input
The first line contains integers n and m (1 β€ n, m β€ 106). Each of the next m lines contains a couple of integers. The i-th line contains integers xi, yi (1 β€ xi, yi β€ n) β the description of the i-th operation of the magician. Note that the operations are given in the order in which the magician made them and the coder wants to make them in the same order.
Output
If the described permutation doesn't exist (the programmer remembered wrong operations), print -1. Otherwise, print n distinct integers, each from 1 to n: the i-th number should represent the mark on the cup that initially is in the row in position i.
If there are multiple correct answers, you should print the lexicographically minimum one.
Examples
Input
2 1
2 1
Output
2 1
Input
3 2
1 2
1 1
Output
2 1 3
Input
3 3
1 3
2 3
1 3
Output
-1
Tags: data structures
Correct Solution:
```
import io
import os
# List with O(n^1/3) (for n=10**6) get/set/insert/delete based on: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
class UnsortedList:
def __init__(self, iterable=[], _load=100):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i : i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
# self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
# _mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
# _mins[pos] = _lists[pos][0]
pass
else:
del _lists[pos]
del _list_lens[pos]
# del _mins[pos]
self._rebuild = True
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __setitem__(self, index, value):
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._lists[pos][idx] = value
def insert(self, index, value):
_load = self._load
_lists = self._lists
_list_lens = self._list_lens
if _lists:
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_list_lens.append(1)
self._rebuild = True
self._len += 1
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return "SortedList({0})".format(list(self))
def solve(N, M, queries):
idToMark = [-1 for i in range(N)]
cups = UnsortedList([i for i in range(N)])
for mark, pos in queries:
pos -= 1 # 0-indexed
cupId = cups[pos]
del cups[pos]
cups.insert(0, cupId)
if idToMark[cupId] == -1:
idToMark[cupId] = mark
elif idToMark[cupId] != mark:
return b"-1"
markToCounts = [0 for i in range(N + 1)]
for cupId, mark in enumerate(idToMark):
if mark != -1:
markToCounts[mark] += 1
if markToCounts[mark] > 1:
return b"-1"
j = 1
ans = []
for cupId, mark in enumerate(idToMark):
if mark != -1:
ans.append(mark)
else:
while markToCounts[j] > 0:
j += 1
ans.append(j)
j += 1
return b" ".join(str(x).encode("ascii") for x in ans)
if False:
N, M = 10 ** 6, 10 ** 6
queries = [[N // 2 + (i % (N // 2)), N // 2] for i in range(M)]
ans = solve(N, M, queries)
# print(ans)
assert ans != b"-1"
exit()
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
queries = ((int(x) for x in input().split()) for i in range(M))
ans = solve(N, M, queries)
os.write(1, ans)
```
| 102,422 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble.
The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble.
But the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts:
* each cup contains a mark β a number from 1 to n; all marks on the cups are distinct;
* the magician shuffles the cups in m operations, each operation looks like that: take a cup marked xi, sitting at position yi in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position).
When the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist.
Input
The first line contains integers n and m (1 β€ n, m β€ 106). Each of the next m lines contains a couple of integers. The i-th line contains integers xi, yi (1 β€ xi, yi β€ n) β the description of the i-th operation of the magician. Note that the operations are given in the order in which the magician made them and the coder wants to make them in the same order.
Output
If the described permutation doesn't exist (the programmer remembered wrong operations), print -1. Otherwise, print n distinct integers, each from 1 to n: the i-th number should represent the mark on the cup that initially is in the row in position i.
If there are multiple correct answers, you should print the lexicographically minimum one.
Examples
Input
2 1
2 1
Output
2 1
Input
3 2
1 2
1 1
Output
2 1 3
Input
3 3
1 3
2 3
1 3
Output
-1
Submitted Solution:
```
import io
import os
import random
# Based on https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/Treap.py
WITH_QUERY = False
if WITH_QUERY:
default = float("inf")
def mapVal(x):
return x
def combine(x, y):
return min(x, y)
class TreapList(object):
root = 0
size = 0
def __init__(self, data=None):
if data:
self.root = treap_builder(data)
self.size = len(data)
def insert(self, index, value):
self.root = treap_insert(self.root, index, value)
self.size += 1
def __delitem__(self, index):
self.root = treap_erase(self.root, index)
self.size -= 1
def __setitem__(self, index, value):
self.__delitem__(index)
self.insert(index, value)
def __getitem__(self, index):
return treap_find_kth(self.root, index)
def query(self, start, end):
assert WITH_QUERY
return treap_query(self.root, start, end)
def bisect_left(self, value):
return treap_bisect_left(self.root, value) # list must be sorted
def bisect_right(self, value):
return treap_bisect_right(self.root, value) # list must be sorted
def __len__(self):
return self.size
def __nonzero__(self):
return bool(self.root)
__bool__ = __nonzero__
def __repr__(self):
return "TreapMultiSet({})".format(list(self))
def __iter__(self):
if not self.root:
return iter([])
out = []
stack = [self.root]
while stack:
node = stack.pop()
if node > 0:
if right_child[node]:
stack.append(right_child[node])
stack.append(~node)
if left_child[node]:
stack.append(left_child[node])
else:
out.append(treap_keys[~node])
return iter(out)
left_child = [0]
right_child = [0]
subtree_size = [0]
if WITH_QUERY:
subtree_query = [default]
treap_keys = [0]
treap_prior = [0.0]
def treap_builder(data):
"""Build a treap in O(n) time"""
def build(begin, end):
if begin == end:
return 0
mid = (begin + end) // 2
root = treap_create_node(data[mid])
lc = build(begin, mid)
rc = build(mid + 1, end)
left_child[root] = lc
right_child[root] = rc
subtree_size[root] = subtree_size[lc] + 1 + subtree_size[rc]
if WITH_QUERY:
subtree_query[root] = combine(
combine(subtree_query[lc], mapVal(treap_keys[mid])), subtree_query[rc]
)
# sift down the priorities
ind = root
while True:
lc = left_child[ind]
rc = right_child[ind]
if lc and treap_prior[lc] > treap_prior[ind]:
if rc and treap_prior[rc] > treap_prior[rc]:
treap_prior[ind], treap_prior[rc] = (
treap_prior[rc],
treap_prior[ind],
)
ind = rc
else:
treap_prior[ind], treap_prior[lc] = (
treap_prior[lc],
treap_prior[ind],
)
ind = lc
elif rc and treap_prior[rc] > treap_prior[ind]:
treap_prior[ind], treap_prior[rc] = treap_prior[rc], treap_prior[ind]
ind = rc
else:
break
return root
return build(0, len(data))
def treap_create_node(key):
treap_keys.append(key)
treap_prior.append(random.random())
left_child.append(0)
right_child.append(0)
subtree_size.append(1)
if WITH_QUERY:
subtree_query.append(mapVal(key))
return len(treap_keys) - 1
def treap_split(root, index):
if index == 0:
return 0, root
if index == subtree_size[root]:
return root, 0
left_pos = right_pos = 0
stack = []
while root:
left_size = subtree_size[left_child[root]]
if left_size >= index:
left_child[right_pos] = right_pos = root
root = left_child[root]
stack.append(right_pos)
else:
right_child[left_pos] = left_pos = root
root = right_child[root]
stack.append(left_pos)
index -= left_size + 1
left, right = right_child[0], left_child[0]
right_child[left_pos] = left_child[right_pos] = right_child[0] = left_child[0] = 0
treap_update(stack)
check_invariant(left)
check_invariant(right)
return left, right
def treap_merge(left, right):
where, pos = left_child, 0
stack = []
while left and right:
if treap_prior[left] > treap_prior[right]:
where[pos] = pos = left
where = right_child
left = right_child[left]
else:
where[pos] = pos = right
where = left_child
right = left_child[right]
stack.append(pos)
where[pos] = left or right
node = left_child[0]
left_child[0] = 0
treap_update(stack)
check_invariant(node)
return node
def treap_insert(root, index, value):
if not root:
return treap_create_node(value)
left, right = treap_split(root, index)
return treap_merge(treap_merge(left, treap_create_node(value)), right)
def treap_erase(root, index):
if not root:
raise KeyError(index)
if subtree_size[left_child[root]] == index:
return treap_merge(left_child[root], right_child[root])
node = root
stack = [root]
while root:
left_size = subtree_size[left_child[root]]
if left_size > index:
parent = root
root = left_child[root]
elif left_size == index:
break
else:
parent = root
root = right_child[root]
index -= left_size + 1
stack.append(root)
if not root:
raise KeyError(index)
if root == left_child[parent]:
left_child[parent] = treap_merge(left_child[root], right_child[root])
else:
right_child[parent] = treap_merge(left_child[root], right_child[root])
treap_update(stack)
check_invariant(node)
return node
def treap_first(root):
if not root:
raise ValueError("min on empty treap")
while left_child[root]:
root = left_child[root]
return root
def treap_last(root):
if not root:
raise ValueError("max on empty treap")
while right_child[root]:
root = right_child[root]
return root
def treap_update(path):
for node in reversed(path):
assert node != 0 # ensure subtree_size[nullptr] == 0
lc = left_child[node]
rc = right_child[node]
subtree_size[node] = subtree_size[lc] + 1 + subtree_size[rc]
if WITH_QUERY:
subtree_query[node] = combine(
combine(subtree_query[lc], mapVal(treap_keys[node])), subtree_query[rc]
)
def check_invariant(node):
return
if node == 0:
assert subtree_size[0] == 0
return 0
lc = left_child[node]
rc = right_child[node]
assert subtree_size[node] == subtree_size[lc] + 1 + subtree_size[rc]
assert subtree_query[node] == combine(
combine(subtree_query[lc], mapVal(treap_keys[node])), subtree_query[rc]
)
check_invariant(lc)
check_invariant(rc)
def treap_find_kth(root, k):
if not root or not (0 <= k < subtree_size[root]):
raise IndexError("treap index out of range")
while True:
lc = left_child[root]
left_size = subtree_size[lc]
if k < left_size:
root = lc
continue
k -= left_size
if k == 0:
return treap_keys[root]
k -= 1
rc = right_child[root]
# assert k < subtree_size[rc]
root = rc
def treap_bisect_left(root, key):
index = 0
while root:
if treap_keys[root] < key:
index += subtree_size[left_child[root]] + 1
root = right_child[root]
else:
root = left_child[root]
return index
def treap_bisect_right(root, key):
index = 0
while root:
if treap_keys[root] <= key:
index += subtree_size[left_child[root]] + 1
root = right_child[root]
else:
root = left_child[root]
return index
def treap_query(root, start, end):
if not root or start == end:
return default
assert start < end
if start == 0 and end == subtree_size[root]:
return subtree_query[root]
res = default
# Find branching point
right_node = right_start = left_node = left_start = -1
node = root
node_start = 0
while node:
# Current node's (left, key, mid) covers:
# [node_start, node_start + left_size)
# [node_start + left_size, node_start + left_size + 1)
# [node_start + left_size + 1, node_start + left_size + 1 + right_size)
lc = left_child[node]
rc = right_child[node]
left_size = subtree_size[lc]
right_size = subtree_size[rc]
node_end = node_start + subtree_size[node]
assert node_start <= start < end <= node_end
if end <= node_start + left_size:
# [start, end) is in entirely in left child
node = lc
continue
if node_start + left_size + 1 <= start:
# [start, end) is in entirely in right child
node_start += left_size + 1
node = rc
continue
# [start, end) covers some suffix of left, entire mid, and some prefix of right
left_node = lc
left_start = node_start
res = combine(res, mapVal(treap_keys[node]))
right_node = rc
right_start = node_start + left_size + 1
break
# Go down right
node = right_node
node_start = right_start
node_end = right_start + subtree_size[node]
if node_start < end:
while node:
lc = left_child[node]
rc = right_child[node]
left_size = subtree_size[lc]
right_size = subtree_size[rc]
node_end = node_start + subtree_size[node]
assert start <= node_start < end <= node_end
if node_start + left_size <= end:
res = combine(res, subtree_query[lc])
node_start += left_size
else:
node = lc
continue
if node_start + 1 <= end:
res = combine(res, mapVal(treap_keys[node]))
node_start += 1
if node_start + right_size == end:
res = combine(res, subtree_query[rc])
node_start += right_size
if node_start == end:
break
node = rc
# Go down left
node = left_node
node_start = left_start
node_end = node_start + subtree_size[node]
if start < node_end:
while node:
lc = left_child[node]
rc = right_child[node]
left_size = subtree_size[lc]
right_size = subtree_size[rc]
node_start = node_end - subtree_size[node]
assert node_start <= start < node_end <= end
if start <= node_end - right_size:
res = combine(subtree_query[rc], res)
node_end -= right_size
else:
node = rc
continue
if start <= node_end - 1:
res = combine(mapVal(treap_keys[node]), res)
node_end -= 1
if start <= node_end - left_size:
res = combine(subtree_query[lc], res)
node_end -= left_size
if start == node_end:
break
node = lc
return res
# End treap copy and paste
def solve(N, M, queries):
mark = {}
unusedMarks = set(range(1, N + 1))
cups = TreapList([i for i in range(N)])
for x, y in queries:
y -= 1
cupId = cups[y]
if cupId not in mark:
if x not in unusedMarks:
return -1
mark[cupId] = x
unusedMarks.remove(x)
else:
if mark[cupId] != x:
return -1
del cups[y]
cups.insert(0, cupId)
ans = []
for i in range(N):
if i in mark:
ans.append(mark[i])
else:
ans.append(unusedMarks.pop())
return " ".join(map(str, ans))
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
queries = [[int(x) for x in input().split()] for i in range(M)]
ans = solve(N, M, queries)
print(ans)
```
No
| 102,423 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble.
The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble under one cup and shuffles the cups. Then the spectator should guess which cup hides the marble.
But the head coder of the F company isn't easy to trick. When he saw the performance, he noticed several important facts:
* each cup contains a mark β a number from 1 to n; all marks on the cups are distinct;
* the magician shuffles the cups in m operations, each operation looks like that: take a cup marked xi, sitting at position yi in the row of cups (the positions are numbered from left to right, starting from 1) and shift it to the very beginning of the cup row (on the first position).
When the head coder came home after work he wanted to re-do the trick. Unfortunately, he didn't remember the starting or the final position of the cups. He only remembered which operations the magician performed. Help the coder: given the operations in the order they were made find at least one initial permutation of the cups that can go through the described operations in the given order. Otherwise, state that such permutation doesn't exist.
Input
The first line contains integers n and m (1 β€ n, m β€ 106). Each of the next m lines contains a couple of integers. The i-th line contains integers xi, yi (1 β€ xi, yi β€ n) β the description of the i-th operation of the magician. Note that the operations are given in the order in which the magician made them and the coder wants to make them in the same order.
Output
If the described permutation doesn't exist (the programmer remembered wrong operations), print -1. Otherwise, print n distinct integers, each from 1 to n: the i-th number should represent the mark on the cup that initially is in the row in position i.
If there are multiple correct answers, you should print the lexicographically minimum one.
Examples
Input
2 1
2 1
Output
2 1
Input
3 2
1 2
1 1
Output
2 1 3
Input
3 3
1 3
2 3
1 3
Output
-1
Submitted Solution:
```
import io
import os
# List with O(n^1/3) (for n=10**6) get/set/insert/delete based on: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
class UnsortedList:
def __init__(self, iterable=[], _load=1000):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i : i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
# self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
# _mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
# _mins[pos] = _lists[pos][0]
pass
else:
del _lists[pos]
del _list_lens[pos]
# del _mins[pos]
self._rebuild = True
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __setitem__(self, index, value):
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._lists[pos][idx] = value
def insert(self, index, value):
_load = self._load
_lists = self._lists
_list_lens = self._list_lens
if _lists:
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_list_lens.append(1)
self._rebuild = True
self._len += 1
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return "SortedList({0})".format(list(self))
def solve(N, M, queries):
idToMark = [-1 for i in range(N)]
cups = UnsortedList([i for i in range(N)])
for mark, pos in queries:
pos -= 1 # 0-indexed
cupId = cups[pos]
del cups[pos]
cups.insert(0, cupId)
if idToMark[cupId] == -1:
idToMark[cupId] = mark
elif idToMark[cupId] != mark:
return b"-1"
markToCounts = [0 for i in range(N + 1)]
for cupId, mark in enumerate(idToMark):
if mark != -1:
markToCounts[mark] += 1
if markToCounts[mark] > 1:
return b"-1"
j = 1
ans = []
for cupId, mark in enumerate(idToMark):
if mark != -1:
ans.append(mark)
else:
while markToCounts[j] > 0:
j += 1
ans.append(j)
j += 1
return b" ".join(str(x).encode("ascii") for x in ans)
if True:
N, M = 10 ** 6, 10 ** 6
queries = [[N // 2 + (i % (N // 2)), N // 2] for i in range(M)]
ans = solve(N, M, queries)
# print(ans)
assert ans != b"-1"
exit()
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M = [int(x) for x in input().split()]
queries = ((int(x) for x in input().split()) for i in range(M))
ans = solve(N, M, queries)
os.write(1, ans)
```
No
| 102,424 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where
<image>
Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
Input
The first line contains a single string s (1 β€ |s| β€ 103).
The second line contains a single integer k (0 β€ k β€ 103).
The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.
Output
Print a single integer β the largest possible value of the resulting string DZY could get.
Examples
Input
abc
3
1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output
41
Note
In the test sample DZY can obtain "abcbbc", value = 1Β·1 + 2Β·2 + 3Β·2 + 4Β·2 + 5Β·2 + 6Β·2 = 41.
Tags: greedy, implementation
Correct Solution:
```
S = input()
N = int(input())
X = list(map(int, input().split()))
MAX = max(X)
SUM = 0
for i in range(len(S)):
SUM += X[ord(S[i]) - 97] * (i + 1)
for i in range(1, N + 1):
SUM += (len(S) + i) * MAX
print(SUM)
```
| 102,425 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where
<image>
Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
Input
The first line contains a single string s (1 β€ |s| β€ 103).
The second line contains a single integer k (0 β€ k β€ 103).
The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.
Output
Print a single integer β the largest possible value of the resulting string DZY could get.
Examples
Input
abc
3
1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output
41
Note
In the test sample DZY can obtain "abcbbc", value = 1Β·1 + 2Β·2 + 3Β·2 + 4Β·2 + 5Β·2 + 6Β·2 = 41.
Tags: greedy, implementation
Correct Solution:
```
s=input()
k=int(input())
n=len(s)
l=list(map(int,input().split()))
m=max(l)
c=0
for i in range(n):
x=ord(s[i])-97
c=c+l[x]*(i+1)
for i in range(n+1,n+k+1):
c=c+(i*m)
print(c)
```
| 102,426 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where
<image>
Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
Input
The first line contains a single string s (1 β€ |s| β€ 103).
The second line contains a single integer k (0 β€ k β€ 103).
The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.
Output
Print a single integer β the largest possible value of the resulting string DZY could get.
Examples
Input
abc
3
1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output
41
Note
In the test sample DZY can obtain "abcbbc", value = 1Β·1 + 2Β·2 + 3Β·2 + 4Β·2 + 5Β·2 + 6Β·2 = 41.
Tags: greedy, implementation
Correct Solution:
```
a=input()
n=int(input())
l=list(map(int,input().split()))
letters='abcdefghijklmnopqrstuvwxyz'
b=l.index(max(l))
a+=n*letters[b]
t=[]
for i in a:
t.append(l[letters.index(i)])
s=0
for i in range(1,len(a)+1):
s+=i*t[i-1]
print(s)
```
| 102,427 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where
<image>
Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
Input
The first line contains a single string s (1 β€ |s| β€ 103).
The second line contains a single integer k (0 β€ k β€ 103).
The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.
Output
Print a single integer β the largest possible value of the resulting string DZY could get.
Examples
Input
abc
3
1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output
41
Note
In the test sample DZY can obtain "abcbbc", value = 1Β·1 + 2Β·2 + 3Β·2 + 4Β·2 + 5Β·2 + 6Β·2 = 41.
Tags: greedy, implementation
Correct Solution:
```
str = list(input())
N = int(input())
A = list(map(int, input().split()))
total = 0
maxu = max(A)
for i in range(len(str)):
total += (i+1) * (A[ord(str[i]) - 97])
for j in range(N):
total += (j+len(str)+1)*maxu
print(total)
```
| 102,428 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where
<image>
Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
Input
The first line contains a single string s (1 β€ |s| β€ 103).
The second line contains a single integer k (0 β€ k β€ 103).
The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.
Output
Print a single integer β the largest possible value of the resulting string DZY could get.
Examples
Input
abc
3
1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output
41
Note
In the test sample DZY can obtain "abcbbc", value = 1Β·1 + 2Β·2 + 3Β·2 + 4Β·2 + 5Β·2 + 6Β·2 = 41.
Tags: greedy, implementation
Correct Solution:
```
s=str(input())
k=int(input())
wlist=[int(w) for w in input().split()]
letter=max(wlist)
alphabet='abcdefghijklmnopqrstuvwxyz'
summ=0
for i in range(len(s)):
summ+=wlist[alphabet.index(s[i])]*(i+1)
print(summ+letter*(k*len(s)+(k+k**2)//2))
```
| 102,429 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where
<image>
Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
Input
The first line contains a single string s (1 β€ |s| β€ 103).
The second line contains a single integer k (0 β€ k β€ 103).
The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.
Output
Print a single integer β the largest possible value of the resulting string DZY could get.
Examples
Input
abc
3
1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output
41
Note
In the test sample DZY can obtain "abcbbc", value = 1Β·1 + 2Β·2 + 3Β·2 + 4Β·2 + 5Β·2 + 6Β·2 = 41.
Tags: greedy, implementation
Correct Solution:
```
import sys
import math
def fn(s,k,w):
l = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
x = [[0]*2]*26
for i in range(len(x)):
x[i] = [l[i],int(w[i])]
y = x.copy()
x.sort(key = lambda x: x[1], reverse = True)
s = list(s)
sum=0
first_tuple_elements = []
second_tuple_elements = []
for a_tuple in y:
first_tuple_elements.append(a_tuple[0])
for b in y:
second_tuple_elements.append(b[1])
for i in range(len(s)):
sum = sum + (i+1)*int(second_tuple_elements[first_tuple_elements.index(s[i])])
z = x[0][1]
sum1 = sum + (k*(k+1)/2 + k*len(s))*z
return int(sum1)
if __name__ == '__main__':
input = sys.stdin.read()
data = list(map(str, input.split()))
s = data[0]
k = int(data[1])
w = (data[2:])
print(fn(s,k,w))
```
| 102,430 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where
<image>
Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
Input
The first line contains a single string s (1 β€ |s| β€ 103).
The second line contains a single integer k (0 β€ k β€ 103).
The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.
Output
Print a single integer β the largest possible value of the resulting string DZY could get.
Examples
Input
abc
3
1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output
41
Note
In the test sample DZY can obtain "abcbbc", value = 1Β·1 + 2Β·2 + 3Β·2 + 4Β·2 + 5Β·2 + 6Β·2 = 41.
Tags: greedy, implementation
Correct Solution:
```
# Description of the problem can be found at http://codeforces.com/problemset/problem/447/B
s = input()
k = int(input())
l_n = list(map(int, input().split()))
m = max(l_n)
t = 0
for i in range(len(s)):
t += (i + 1)*l_n[ord(s[i]) - ord('a')]
print(m * ((len(s) + k) * (len(s) + k + 1) // 2 - len(s)*(len(s) + 1) // 2) + t)
```
| 102,431 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where
<image>
Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
Input
The first line contains a single string s (1 β€ |s| β€ 103).
The second line contains a single integer k (0 β€ k β€ 103).
The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.
Output
Print a single integer β the largest possible value of the resulting string DZY could get.
Examples
Input
abc
3
1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output
41
Note
In the test sample DZY can obtain "abcbbc", value = 1Β·1 + 2Β·2 + 3Β·2 + 4Β·2 + 5Β·2 + 6Β·2 = 41.
Tags: greedy, implementation
Correct Solution:
```
s = input()
n = eval(input())
value = list(map(eval,input().split()))
ans = 0
for i in range(len(s)):
ans += value[ord(s[i])-ord('a')]*(i+1)
maxn = max(map(lambda x:x,value))
ans += (len(s)*2+n+1)*n*maxn/2
print(int(ans))
```
| 102,432 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where
<image>
Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
Input
The first line contains a single string s (1 β€ |s| β€ 103).
The second line contains a single integer k (0 β€ k β€ 103).
The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.
Output
Print a single integer β the largest possible value of the resulting string DZY could get.
Examples
Input
abc
3
1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output
41
Note
In the test sample DZY can obtain "abcbbc", value = 1Β·1 + 2Β·2 + 3Β·2 + 4Β·2 + 5Β·2 + 6Β·2 = 41.
Submitted Solution:
```
# Aditya Morankar
# lsta = list(map(int,input().split()))
def main():
string = input()
k = int(input())
wgt = list(map(int, input().split()))
ans= 0
for i,char in enumerate(string):
ans += (i+1)*wgt[ord(char)-97]
maxw = max(wgt)
n = len(string)+1
for i in range(k):
ans += n*maxw
n+=1
print(ans)
if __name__ == '__main__':
t = 1
while t!=0:
main()
t-=1
```
Yes
| 102,433 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where
<image>
Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
Input
The first line contains a single string s (1 β€ |s| β€ 103).
The second line contains a single integer k (0 β€ k β€ 103).
The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.
Output
Print a single integer β the largest possible value of the resulting string DZY could get.
Examples
Input
abc
3
1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output
41
Note
In the test sample DZY can obtain "abcbbc", value = 1Β·1 + 2Β·2 + 3Β·2 + 4Β·2 + 5Β·2 + 6Β·2 = 41.
Submitted Solution:
```
s, k = input(), int(input())
w = dict(zip('abcdefghijklmnopqrstuvwxyz', map(int,input().split())))
print(sum(i * w[ch] for i, ch in enumerate(s, 1)) +
max(w.values()) * k * (2 * len(s) + k + 1) // 2)
```
Yes
| 102,434 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where
<image>
Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
Input
The first line contains a single string s (1 β€ |s| β€ 103).
The second line contains a single integer k (0 β€ k β€ 103).
The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.
Output
Print a single integer β the largest possible value of the resulting string DZY could get.
Examples
Input
abc
3
1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output
41
Note
In the test sample DZY can obtain "abcbbc", value = 1Β·1 + 2Β·2 + 3Β·2 + 4Β·2 + 5Β·2 + 6Β·2 = 41.
Submitted Solution:
```
s = input().strip()
k = int(input().strip())
arr = list(map(int, input().strip().split()))
n = len(s)
x = max(arr)
ans = 0
for i in range(1, n+1):
ans += i*arr[ord(s[i-1])-97]
for i in range(n+1, n+k+1):
ans += i*x
print(ans)
```
Yes
| 102,435 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where
<image>
Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
Input
The first line contains a single string s (1 β€ |s| β€ 103).
The second line contains a single integer k (0 β€ k β€ 103).
The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.
Output
Print a single integer β the largest possible value of the resulting string DZY could get.
Examples
Input
abc
3
1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output
41
Note
In the test sample DZY can obtain "abcbbc", value = 1Β·1 + 2Β·2 + 3Β·2 + 4Β·2 + 5Β·2 + 6Β·2 = 41.
Submitted Solution:
```
S = list(map(lambda x: ord(x) - ord('a'), list(input())))
N = int(input())
W = list(map(int, input().split()))
S = S + [W.index(max(W))] * N
print(sum([(i + 1) * W[v] for i, v in enumerate(S)]))
```
Yes
| 102,436 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where
<image>
Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
Input
The first line contains a single string s (1 β€ |s| β€ 103).
The second line contains a single integer k (0 β€ k β€ 103).
The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.
Output
Print a single integer β the largest possible value of the resulting string DZY could get.
Examples
Input
abc
3
1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output
41
Note
In the test sample DZY can obtain "abcbbc", value = 1Β·1 + 2Β·2 + 3Β·2 + 4Β·2 + 5Β·2 + 6Β·2 = 41.
Submitted Solution:
```
a=input();b=int(input());z=0;s=0;q=dict();f=97;o=1
for i in map(int,input().split()):q[chr(f)]=i;f+=1
for i in a:s+=(o*q[i]);o+=1;z=max(q.values());print(s+sum(i*z for i in range(o,o+b)))
```
No
| 102,437 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where
<image>
Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
Input
The first line contains a single string s (1 β€ |s| β€ 103).
The second line contains a single integer k (0 β€ k β€ 103).
The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.
Output
Print a single integer β the largest possible value of the resulting string DZY could get.
Examples
Input
abc
3
1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output
41
Note
In the test sample DZY can obtain "abcbbc", value = 1Β·1 + 2Β·2 + 3Β·2 + 4Β·2 + 5Β·2 + 6Β·2 = 41.
Submitted Solution:
```
s=input()
k=int(input())
w=input()
#needed values
L=len(s)
sum=0
x=[]
wi=w.split()
for i in range(L):
x.append(wi[ord(s[i])-97])
sum+=int(x[i])*(i+1)
#needed values.
n=int(max(wi))
for i in range(k):
sum+=n*(i+L+1)
print(sum)
```
No
| 102,438 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where
<image>
Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
Input
The first line contains a single string s (1 β€ |s| β€ 103).
The second line contains a single integer k (0 β€ k β€ 103).
The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.
Output
Print a single integer β the largest possible value of the resulting string DZY could get.
Examples
Input
abc
3
1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output
41
Note
In the test sample DZY can obtain "abcbbc", value = 1Β·1 + 2Β·2 + 3Β·2 + 4Β·2 + 5Β·2 + 6Β·2 = 41.
Submitted Solution:
```
letters = list(input())
l = len(letters)
k = int(input())
w = [int(x) for x in input().split()]
res = 0
maxW = max(w)
for i in range (l):
res += (i + 1) * w[ord(letters[i]) - ord('a')]
for i in range (k):
res += (k + i + 1) * maxW
print(res)
```
No
| 102,439 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where
<image>
Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
Input
The first line contains a single string s (1 β€ |s| β€ 103).
The second line contains a single integer k (0 β€ k β€ 103).
The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.
Output
Print a single integer β the largest possible value of the resulting string DZY could get.
Examples
Input
abc
3
1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Output
41
Note
In the test sample DZY can obtain "abcbbc", value = 1Β·1 + 2Β·2 + 3Β·2 + 4Β·2 + 5Β·2 + 6Β·2 = 41.
Submitted Solution:
```
s = input()
k = int(input())
vals = list(map(int,input().split()))
alphabets = "abcdefghijklmnopqrstuvwxyz"
ss=alphabets[vals.index(max(vals))]
print(s+ss*k)
```
No
| 102,440 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.
Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a Γ b.
After n - 1 steps there is only one number left. Can you make this number equal to 24?
Input
The first line contains a single integer n (1 β€ n β€ 105).
Output
If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes).
If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces.
If there are multiple valid answers, you may print any of them.
Examples
Input
1
Output
NO
Input
8
Output
YES
8 * 7 = 56
6 * 5 = 30
3 - 4 = -1
1 - 2 = -1
30 - -1 = 31
56 - 31 = 25
25 + -1 = 24
Tags: constructive algorithms, greedy, math
Correct Solution:
```
n = int(input())
if n < 4: print("NO")
else:
print("YES")
while n > 5:
a = str(n)
b = str(n-1)
print(a + " - " + b + " = 1 ")
print("1 * 1 = 1")
n -= 2
if n == 4: print("4 * 3 = 12\n12 * 2 = 24\n24 * 1 = 24")
else: print("5 - 2 = 3\n3 - 1 = 2\n2 * 3 = 6\n6 * 4 = 24")
# Made By Mostafa_Khaled
```
| 102,441 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.
Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a Γ b.
After n - 1 steps there is only one number left. Can you make this number equal to 24?
Input
The first line contains a single integer n (1 β€ n β€ 105).
Output
If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes).
If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces.
If there are multiple valid answers, you may print any of them.
Examples
Input
1
Output
NO
Input
8
Output
YES
8 * 7 = 56
6 * 5 = 30
3 - 4 = -1
1 - 2 = -1
30 - -1 = 31
56 - 31 = 25
25 + -1 = 24
Tags: constructive algorithms, greedy, math
Correct Solution:
```
#------------------------template--------------------------#
import os
import sys
# from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=10**9+7
EPS=1e-6
def Ceil(a,b): return a//b+int(a%b>0)
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
n=Int()
if(n<4):
print("NO")
exit()
print("YES")
if(n==4):
print("3 * 4 = 12")
print("12 * 2 = 24")
print("24 * 1 = 24")
elif(n==5):
print("5 * 4 = 20")
print("2 - 1 = 1")
print("3 + 1 = 4")
print("20 + 4 = 24")
else:
print("3 - 2 = 1")
print("1 - 1 = 0")
for i in range(7,n+1):
print("{} * 0 = 0".format(i))
print("5 * 0 = 0")
print("4 * 6 = 24")
print("24 + 0 = 24")
```
| 102,442 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.
Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a Γ b.
After n - 1 steps there is only one number left. Can you make this number equal to 24?
Input
The first line contains a single integer n (1 β€ n β€ 105).
Output
If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes).
If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces.
If there are multiple valid answers, you may print any of them.
Examples
Input
1
Output
NO
Input
8
Output
YES
8 * 7 = 56
6 * 5 = 30
3 - 4 = -1
1 - 2 = -1
30 - -1 = 31
56 - 31 = 25
25 + -1 = 24
Tags: constructive algorithms, greedy, math
Correct Solution:
```
def logs(n):
if n == 4: return [(1,1,2), (1,2,3), (1,6,4)]
if n == 5: return [(2,5,4), (2,9,3), (1,12,2), (1,24,1)]
ans = [(3,i+1,i) for i in range(n-1, 4, -2)]
ans.extend(logs(4 + n%2))
ans += [(1,24,1) for i in range(n-1-len(ans))]
return ans
n = int(input())
if n < 4:
print('NO')
else:
print('YES')
for note in logs(n):
if note[0] == 1:
print('{0} * {1} = {2}'.format(note[1], note[2], note[1]*note[2]))
elif note[0] == 2:
print('{0} + {1} = {2}'.format(note[1], note[2], note[1]+note[2]))
else:
print('{0} - {1} = {2}'.format(note[1], note[2], note[1]-note[2]))
```
| 102,443 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.
Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a Γ b.
After n - 1 steps there is only one number left. Can you make this number equal to 24?
Input
The first line contains a single integer n (1 β€ n β€ 105).
Output
If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes).
If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces.
If there are multiple valid answers, you may print any of them.
Examples
Input
1
Output
NO
Input
8
Output
YES
8 * 7 = 56
6 * 5 = 30
3 - 4 = -1
1 - 2 = -1
30 - -1 = 31
56 - 31 = 25
25 + -1 = 24
Tags: constructive algorithms, greedy, math
Correct Solution:
```
a = int(input())
if a<=3:
print("NO")
elif a%2==0:
print("YES")
print('4 * 3 = 12')
print('12 * 2 = 24')
print('24 * 1 = 24')
for i in range(6, a+1, 2):
print(str(i), '-', str(i-1), '= 1')
print('24 * 1 = 24')
elif a%2==1:
print("YES")
print('4 - 2 = 2')
print('2 + 1 = 3')
print('3 + 5 = 8')
print('3 * 8 = 24')
for i in range(7, a+1, 2):
print(str(i), '-', str(i-1), '= 1')
print('24 * 1 = 24')
```
| 102,444 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.
Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a Γ b.
After n - 1 steps there is only one number left. Can you make this number equal to 24?
Input
The first line contains a single integer n (1 β€ n β€ 105).
Output
If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes).
If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces.
If there are multiple valid answers, you may print any of them.
Examples
Input
1
Output
NO
Input
8
Output
YES
8 * 7 = 56
6 * 5 = 30
3 - 4 = -1
1 - 2 = -1
30 - -1 = 31
56 - 31 = 25
25 + -1 = 24
Tags: constructive algorithms, greedy, math
Correct Solution:
```
n = int(input())
if n < 4:
print('NO')
elif n == 4:
print('YES')
print('1 * 2 = 2')
print('2 * 3 = 6')
print('6 * 4 = 24')
elif n == 5:
print('YES')
print('4 * 5 = 20')
print('3 - 1 = 2')
print('20 + 2 = 22')
print('22 + 2 = 24')
else:
print('YES')
print('2 * 3 = 6')
print('6 * 4 = 24')
print('6 - 1 = 5')
print('5 - 5 = 0')
for i in range(7, n + 1):
print('0 * {} = 0'.format(i))
print('24 + 0 = 24')
# 24
```
| 102,445 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.
Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a Γ b.
After n - 1 steps there is only one number left. Can you make this number equal to 24?
Input
The first line contains a single integer n (1 β€ n β€ 105).
Output
If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes).
If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces.
If there are multiple valid answers, you may print any of them.
Examples
Input
1
Output
NO
Input
8
Output
YES
8 * 7 = 56
6 * 5 = 30
3 - 4 = -1
1 - 2 = -1
30 - -1 = 31
56 - 31 = 25
25 + -1 = 24
Tags: constructive algorithms, greedy, math
Correct Solution:
```
n = int(input())
if n >= 4:
print("YES")
moves = 0
for i in range(5 + (0 if n % 2 == 0 else 1), n, 2):
print(str(i+1) + ' - ' + str(i) + ' = ' + str(1))
moves += 1
if n % 2 == 0:
print('2 * 3 = 6')
print('6 * 4 = 24')
moves += 2
else:
print('2 + 1 = 3')
print('5 - 3 = 2')
print('3 * 2 = 6')
print('6 * 4 = 24')
moves += 4
while moves < n-1:
moves += 1
print('1 * 24 = 24')
else:
print('NO')
```
| 102,446 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.
Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a Γ b.
After n - 1 steps there is only one number left. Can you make this number equal to 24?
Input
The first line contains a single integer n (1 β€ n β€ 105).
Output
If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes).
If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces.
If there are multiple valid answers, you may print any of them.
Examples
Input
1
Output
NO
Input
8
Output
YES
8 * 7 = 56
6 * 5 = 30
3 - 4 = -1
1 - 2 = -1
30 - -1 = 31
56 - 31 = 25
25 + -1 = 24
Tags: constructive algorithms, greedy, math
Correct Solution:
```
n = int(input())
if n<=3:
print("NO")
else:
print("YES")
if n%2==0:
for i in range(5,n,2):
print(i+1,'-' ,i,'=',1)
print(1,'*',2,'=',2)
print(2,'*',3,'=',6)
print(6,'*',4,'=',24)
for i in range((n-4)//2):
print(24,'*',1,'=',24)
else:
print(5,'+',1,'=',6)
print(3,'-',2,'=',1)
print(4,'*',6,'=',24)
print(1,'*',24,'=',24)
for i in range(6,n,2):
print(i+1,'-',i,'=',1)
for i in range((n-5)//2):
print(24,'*',1,'=',24)
```
| 102,447 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.
Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a Γ b.
After n - 1 steps there is only one number left. Can you make this number equal to 24?
Input
The first line contains a single integer n (1 β€ n β€ 105).
Output
If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes).
If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces.
If there are multiple valid answers, you may print any of them.
Examples
Input
1
Output
NO
Input
8
Output
YES
8 * 7 = 56
6 * 5 = 30
3 - 4 = -1
1 - 2 = -1
30 - -1 = 31
56 - 31 = 25
25 + -1 = 24
Tags: constructive algorithms, greedy, math
Correct Solution:
```
n=int(input())
if (n==1 or n==2 or n==3):
print ("NO")
exit(0)
else:
print ("YES")
if (n%2==0):
print ("1 * 2 = 2")
print ("2 * 3 = 6")
print ("6 * 4 = 24")
for i in range(5,n+1,2):
print (i+1,"-",i,"= 1")
for i in range((n-4)//2):
print ("24 * 1 = 24")
else:
print ("5 - 2 = 3")
print ("3 - 1 = 2")
print ("2 * 3 = 6")
print ("6 * 4 = 24")
for i in range(6,n+1,2):
print (i+1,"-",i,"= 1")
for i in range((n-5)//2):
print ("24 * 1 = 24")
```
| 102,448 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.
Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a Γ b.
After n - 1 steps there is only one number left. Can you make this number equal to 24?
Input
The first line contains a single integer n (1 β€ n β€ 105).
Output
If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes).
If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces.
If there are multiple valid answers, you may print any of them.
Examples
Input
1
Output
NO
Input
8
Output
YES
8 * 7 = 56
6 * 5 = 30
3 - 4 = -1
1 - 2 = -1
30 - -1 = 31
56 - 31 = 25
25 + -1 = 24
Submitted Solution:
```
n=int(input())
if n<4: print("NO")
elif n&1:
print("YES\n5 - 3 = 2\n2 + 1 = 3\n2 * 3 = 6\n4 * 6 = 24")
for i in range(6,n,2):
print(i+1, "-", i, "=", 1)
print("24 * 1 = 24")
else:
print("YES\n1 * 2 = 2\n2 * 3 = 6\n6 * 4 = 24")
for i in range(5,n,2):
print(i+1, "-", i, "=", 1)
print("24 * 1 = 24")
```
Yes
| 102,449 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.
Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a Γ b.
After n - 1 steps there is only one number left. Can you make this number equal to 24?
Input
The first line contains a single integer n (1 β€ n β€ 105).
Output
If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes).
If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces.
If there are multiple valid answers, you may print any of them.
Examples
Input
1
Output
NO
Input
8
Output
YES
8 * 7 = 56
6 * 5 = 30
3 - 4 = -1
1 - 2 = -1
30 - -1 = 31
56 - 31 = 25
25 + -1 = 24
Submitted Solution:
```
from collections import *
import os, sys
from io import BytesIO, IOBase
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
BUFSIZE = 8192
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
rstr = lambda: input().strip()
rstrs = lambda: [str(x) for x in input().split()]
rstr_2d = lambda n: [rstr() for _ in range(n)]
rint = lambda: int(input())
rints = lambda: [int(x) for x in input().split()]
rint_2d = lambda n: [rint() for _ in range(n)]
rints_2d = lambda n: [rints() for _ in range(n)]
ceil1 = lambda a, b: (a + b - 1) // b
n = rint()
if n < 4:
exit(print('NO'))
print('YES')
if n == 5:
print('1 + 5 = 6\n3 - 2 = 1\n 1 * 4 = 4\n4 * 6 = 24')
elif n & 1:
print('4 - 2 = 2')
tem, cur = (1, 2, 3, 5, 6, 7), 1
for i in range(1, len(tem)):
print(f'{cur} + {tem[i]} = {cur + tem[i]}')
cur += tem[i]
for i in range(8, n, 2):
print(f'{i + 1} - {i} = 1\n24 * 1 = 24')
else:
cur = 1
for i in range(1, 4):
print(f'{cur} * {i + 1} = {cur * (i + 1)}')
cur *= i + 1
for i in range(5, n, 2):
print(f'{i + 1} - {i} = 1\n24 * 1 = 24')
```
Yes
| 102,450 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.
Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a Γ b.
After n - 1 steps there is only one number left. Can you make this number equal to 24?
Input
The first line contains a single integer n (1 β€ n β€ 105).
Output
If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes).
If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces.
If there are multiple valid answers, you may print any of them.
Examples
Input
1
Output
NO
Input
8
Output
YES
8 * 7 = 56
6 * 5 = 30
3 - 4 = -1
1 - 2 = -1
30 - -1 = 31
56 - 31 = 25
25 + -1 = 24
Submitted Solution:
```
n = int(input())
if n <= 3:
print('NO')
else:
print('YES')
if n % 2 == 0:
print('2 * 1 = 2')
print('2 * 3 = 6')
print('6 * 4 = 24')
for i in range(6, n+1, 2):
print('{} - {} = 1'.format(i, i-1))
print('24 * 1 = 24')
else:
print('2 - 1 = 1')
print('3 + 1 = 4')
print('4 * 5 = 20')
print('20 + 4 = 24')
for i in range(7, n+1, 2):
print('{} - {} = 1'.format(i, i-1))
print('24 * 1 = 24')
```
Yes
| 102,451 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.
Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a Γ b.
After n - 1 steps there is only one number left. Can you make this number equal to 24?
Input
The first line contains a single integer n (1 β€ n β€ 105).
Output
If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes).
If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces.
If there are multiple valid answers, you may print any of them.
Examples
Input
1
Output
NO
Input
8
Output
YES
8 * 7 = 56
6 * 5 = 30
3 - 4 = -1
1 - 2 = -1
30 - -1 = 31
56 - 31 = 25
25 + -1 = 24
Submitted Solution:
```
n = int(input())
if n < 4:
print('NO')
elif n == 4:
print('YES')
print('3 * 4 = 12')
print('2 * 1 = 2')
print('12 * 2 = 24')
elif n == 5:
print('YES')
print('5 - 3 = 2')
print('2 + 1 = 3')
print('3 * 4 = 12')
print('12 * 2 = 24')
else:
print('YES')
print(str(n) + ' - ' + str(n - 1) + ' = 1')
print('1 - 1 = 0')
for i in range(5, 5 + n - 6):
print(str(i) + ' * 0 = 0' )
print('2 * 3 = 6')
print('4 * 6 = 24')
print('24 + 0 = 24')
```
Yes
| 102,452 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.
Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a Γ b.
After n - 1 steps there is only one number left. Can you make this number equal to 24?
Input
The first line contains a single integer n (1 β€ n β€ 105).
Output
If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes).
If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces.
If there are multiple valid answers, you may print any of them.
Examples
Input
1
Output
NO
Input
8
Output
YES
8 * 7 = 56
6 * 5 = 30
3 - 4 = -1
1 - 2 = -1
30 - -1 = 31
56 - 31 = 25
25 + -1 = 24
Submitted Solution:
```
a = int(input())
if a<=3:
print("NO")
elif a%2==0:
print('4 * 3 = 12')
print('12 * 2 = 24')
print('24 * 1 = 24')
for i in range(6, a+1, 2):
print(str(i), '-', str(i-1), '= 1')
print('24 * 1 = 24')
elif a%2==1:
print('4 - 2 = 2')
print('2 + 1 = 3')
print('3 + 5 = 8')
print('3 * 8 = 24')
for i in range(7, a+1, 2):
print(str(i), '-', str(i-1), '= 1')
print('24 * 1 = 24')
```
No
| 102,453 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.
Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a Γ b.
After n - 1 steps there is only one number left. Can you make this number equal to 24?
Input
The first line contains a single integer n (1 β€ n β€ 105).
Output
If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes).
If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces.
If there are multiple valid answers, you may print any of them.
Examples
Input
1
Output
NO
Input
8
Output
YES
8 * 7 = 56
6 * 5 = 30
3 - 4 = -1
1 - 2 = -1
30 - -1 = 31
56 - 31 = 25
25 + -1 = 24
Submitted Solution:
```
n = int(input())
if n < 4: print("NO")
else:
print("YES")
while n > 5:
a = str(n+1)
b = str(n)
print(a + " - " + b + " = 1 ")
print("1 * 1 = 1")
n -= 2
if n == 4: print("4 * 3 = 12\n12 * 2 = 24\n24 * 1 = 24")
else: print("5 - 2 = 3\n3 - 1 = 2\n2 * 3 = 6\n6 * 4 = 24")
```
No
| 102,454 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.
Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a Γ b.
After n - 1 steps there is only one number left. Can you make this number equal to 24?
Input
The first line contains a single integer n (1 β€ n β€ 105).
Output
If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes).
If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces.
If there are multiple valid answers, you may print any of them.
Examples
Input
1
Output
NO
Input
8
Output
YES
8 * 7 = 56
6 * 5 = 30
3 - 4 = -1
1 - 2 = -1
30 - -1 = 31
56 - 31 = 25
25 + -1 = 24
Submitted Solution:
```
n = int(input())
if n < 4:
print('NO')
elif n == 5:
print('YES')
print('5 * 4 = 20')
print('20 + 3 = 23')
print('23 + 2 = 25')
print('25 - 1 = 24')
elif n == 4:
print('YES')
print('1 * 2 = 2')
print('2 * 3 = 6')
print('6 + 4 = 24')
else:
if ((n - 4) % 2) == 0:
print('YES')
for i in range(n, 4, -2):
print('%s - %s = %s' %(i, i-1, 1))
print('1 * 2 = 2')
print('2 * 3 = 6')
print('6 + 4 = 24')
for i in range(n, 4, -2):
print('1 * 24 = 24')
else:
print('YES')
print('%s - 1 = %s' % (n, n-1))
print('%s - %s = 0' % (n-1, n-1))
for i in range(n - 2, 4, -1):
print('%s * 0 = 0' %(i))
print('2 * 3 = 6')
print('6 + 4 = 24')
print('24 + 0 = 24')
```
No
| 102,455 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.
Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a Γ b.
After n - 1 steps there is only one number left. Can you make this number equal to 24?
Input
The first line contains a single integer n (1 β€ n β€ 105).
Output
If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes).
If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces.
If there are multiple valid answers, you may print any of them.
Examples
Input
1
Output
NO
Input
8
Output
YES
8 * 7 = 56
6 * 5 = 30
3 - 4 = -1
1 - 2 = -1
30 - -1 = 31
56 - 31 = 25
25 + -1 = 24
Submitted Solution:
```
from collections import *
import os, sys
from io import BytesIO, IOBase
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
BUFSIZE = 8192
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
rstr = lambda: input().strip()
rstrs = lambda: [str(x) for x in input().split()]
rstr_2d = lambda n: [rstr() for _ in range(n)]
rint = lambda: int(input())
rints = lambda: [int(x) for x in input().split()]
rint_2d = lambda n: [rint() for _ in range(n)]
rints_2d = lambda n: [rints() for _ in range(n)]
ceil1 = lambda a, b: (a + b - 1) // b
n = rint()
if n < 4:
print('NO')
elif n == 5:
print('1 + 5 = 6\n3 - 2 = 1\n 1 * 4 = 4\n4 * 6 = 24')
elif n & 1:
print('4 - 2 = 2')
tem, cur = (1, 2, 3, 5, 6, 7), 1
for i in range(1, len(tem)):
print(f'{cur} + {tem[i]} = {cur + tem[i]}')
cur += tem[i]
for i in range(8, n, 2):
print(f'{i + 1} - {i} = 1\n24 * 1 = 24')
else:
cur = 1
for i in range(1, 4):
print(f'{cur} * {i + 1} = {cur * (i + 1)}')
cur *= i + 1
for i in range(5, n, 2):
print(f'{i + 1} - {i} = 1\n24 * 1 = 24')
```
No
| 102,456 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Think of New York as a rectangular grid consisting of N vertical avenues numerated from 1 to N and M horizontal streets numerated 1 to M. C friends are staying at C hotels located at some street-avenue crossings. They are going to celebrate birthday of one of them in the one of H restaurants also located at some street-avenue crossings. They also want that the maximum distance covered by one of them while traveling to the restaurant to be minimum possible. Help friends choose optimal restaurant for a celebration.
Suppose that the distance between neighboring crossings are all the same equal to one kilometer.
Input
The first line contains two integers N ΠΈ M β size of the city (1 β€ N, M β€ 109). In the next line there is a single integer C (1 β€ C β€ 105) β the number of hotels friends stayed at. Following C lines contain descriptions of hotels, each consisting of two coordinates x and y (1 β€ x β€ N, 1 β€ y β€ M). The next line contains an integer H β the number of restaurants (1 β€ H β€ 105). Following H lines contain descriptions of restaurants in the same format.
Several restaurants and hotels may be located near the same crossing.
Output
In the first line output the optimal distance. In the next line output index of a restaurant that produces this optimal distance. If there are several possibilities, you are allowed to output any of them.
Examples
Input
10 10
2
1 1
3 3
2
1 10
4 4
Output
6
2
Tags: greedy, math
Correct Solution:
```
import sys
input = sys.stdin.readline
N, M = input().split()
a, b, c, d = [int(1e10) for _ in range(4)]
for i in range(int(input())):
x, y = list(map(int, input().split()))
a, b, c, d = min(a, x + y), min(b, x - y), min(c, - x + y), min(d, - x - y)
res, pos = int(1e10), 0
for i in range(int(input())):
x, y = list(map(int, input().split()))
ans = max(max(x + y - a, x - y - b), max( - x + y - c, - x - y - d))
if ans < res:
pos = i + 1
res = ans
print(res, pos, sep = '\n')
```
| 102,457 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Think of New York as a rectangular grid consisting of N vertical avenues numerated from 1 to N and M horizontal streets numerated 1 to M. C friends are staying at C hotels located at some street-avenue crossings. They are going to celebrate birthday of one of them in the one of H restaurants also located at some street-avenue crossings. They also want that the maximum distance covered by one of them while traveling to the restaurant to be minimum possible. Help friends choose optimal restaurant for a celebration.
Suppose that the distance between neighboring crossings are all the same equal to one kilometer.
Input
The first line contains two integers N ΠΈ M β size of the city (1 β€ N, M β€ 109). In the next line there is a single integer C (1 β€ C β€ 105) β the number of hotels friends stayed at. Following C lines contain descriptions of hotels, each consisting of two coordinates x and y (1 β€ x β€ N, 1 β€ y β€ M). The next line contains an integer H β the number of restaurants (1 β€ H β€ 105). Following H lines contain descriptions of restaurants in the same format.
Several restaurants and hotels may be located near the same crossing.
Output
In the first line output the optimal distance. In the next line output index of a restaurant that produces this optimal distance. If there are several possibilities, you are allowed to output any of them.
Examples
Input
10 10
2
1 1
3 3
2
1 10
4 4
Output
6
2
Tags: greedy, math
Correct Solution:
```
#!/usr/bin/env python3
n, m = map(int, input().split())
minx = miny = n + m
maxx = maxy = - minx
dist = n + m + 1
c = int(input())
for _ in range(c):
x, y = map(int, input().split())
minx = min(minx, x - y)
miny = min(miny, x + y)
maxx = max(maxx, x - y)
maxy = max(maxy, x + y)
h = int(input())
for i in range(h):
a, b = map(int, input().split())
x = a - b
y = a + b
maxxy = max(
max(abs(minx - x), abs(maxx - x)),
max(abs(miny - y), abs(maxy - y))
)
if maxxy < dist:
dist = maxxy
res = i + 1
print(dist)
print(res)
```
| 102,458 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Think of New York as a rectangular grid consisting of N vertical avenues numerated from 1 to N and M horizontal streets numerated 1 to M. C friends are staying at C hotels located at some street-avenue crossings. They are going to celebrate birthday of one of them in the one of H restaurants also located at some street-avenue crossings. They also want that the maximum distance covered by one of them while traveling to the restaurant to be minimum possible. Help friends choose optimal restaurant for a celebration.
Suppose that the distance between neighboring crossings are all the same equal to one kilometer.
Input
The first line contains two integers N ΠΈ M β size of the city (1 β€ N, M β€ 109). In the next line there is a single integer C (1 β€ C β€ 105) β the number of hotels friends stayed at. Following C lines contain descriptions of hotels, each consisting of two coordinates x and y (1 β€ x β€ N, 1 β€ y β€ M). The next line contains an integer H β the number of restaurants (1 β€ H β€ 105). Following H lines contain descriptions of restaurants in the same format.
Several restaurants and hotels may be located near the same crossing.
Output
In the first line output the optimal distance. In the next line output index of a restaurant that produces this optimal distance. If there are several possibilities, you are allowed to output any of them.
Examples
Input
10 10
2
1 1
3 3
2
1 10
4 4
Output
6
2
Tags: greedy, math
Correct Solution:
```
N, M = input().split()
a, b, c, d = [int(1e10) for _ in range(4)]
for i in range(int(input())):
x, y = list(map(int, input().split()))
a, b, c, d = min(a, x + y), min(b, x - y), min(c, - x + y), min(d, - x - y)
res, pos = int(1e10), 0
for i in range(int(input())):
x, y = list(map(int, input().split()))
ans = max(max(x + y - a, x - y - b), max( - x + y - c, - x - y - d))
if ans < res:
pos = i + 1
res = ans
print(res, pos, sep = '\n')
```
| 102,459 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Think of New York as a rectangular grid consisting of N vertical avenues numerated from 1 to N and M horizontal streets numerated 1 to M. C friends are staying at C hotels located at some street-avenue crossings. They are going to celebrate birthday of one of them in the one of H restaurants also located at some street-avenue crossings. They also want that the maximum distance covered by one of them while traveling to the restaurant to be minimum possible. Help friends choose optimal restaurant for a celebration.
Suppose that the distance between neighboring crossings are all the same equal to one kilometer.
Input
The first line contains two integers N ΠΈ M β size of the city (1 β€ N, M β€ 109). In the next line there is a single integer C (1 β€ C β€ 105) β the number of hotels friends stayed at. Following C lines contain descriptions of hotels, each consisting of two coordinates x and y (1 β€ x β€ N, 1 β€ y β€ M). The next line contains an integer H β the number of restaurants (1 β€ H β€ 105). Following H lines contain descriptions of restaurants in the same format.
Several restaurants and hotels may be located near the same crossing.
Output
In the first line output the optimal distance. In the next line output index of a restaurant that produces this optimal distance. If there are several possibilities, you are allowed to output any of them.
Examples
Input
10 10
2
1 1
3 3
2
1 10
4 4
Output
6
2
Submitted Solution:
```
print(1)
print(1)
```
No
| 102,460 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Think of New York as a rectangular grid consisting of N vertical avenues numerated from 1 to N and M horizontal streets numerated 1 to M. C friends are staying at C hotels located at some street-avenue crossings. They are going to celebrate birthday of one of them in the one of H restaurants also located at some street-avenue crossings. They also want that the maximum distance covered by one of them while traveling to the restaurant to be minimum possible. Help friends choose optimal restaurant for a celebration.
Suppose that the distance between neighboring crossings are all the same equal to one kilometer.
Input
The first line contains two integers N ΠΈ M β size of the city (1 β€ N, M β€ 109). In the next line there is a single integer C (1 β€ C β€ 105) β the number of hotels friends stayed at. Following C lines contain descriptions of hotels, each consisting of two coordinates x and y (1 β€ x β€ N, 1 β€ y β€ M). The next line contains an integer H β the number of restaurants (1 β€ H β€ 105). Following H lines contain descriptions of restaurants in the same format.
Several restaurants and hotels may be located near the same crossing.
Output
In the first line output the optimal distance. In the next line output index of a restaurant that produces this optimal distance. If there are several possibilities, you are allowed to output any of them.
Examples
Input
10 10
2
1 1
3 3
2
1 10
4 4
Output
6
2
Submitted Solution:
```
l1=[]
l2=[]
a, b = map(int, input().split(' '))
i = int(input())
for x in range(i):
l1.append(list(map(int, input().split(' '))))
j = int(input())
for x in range(j):
l2.append(list(map(int, input().split(' '))))
minlist = []
for i in range(min(len(l2), 50)):
minf = 0
for j in range(min(len(l1), 50)):
minf = max(minf, abs(l1[j][1]-l2[i][1])+abs(l1[j][0]-l2[i][0]))
minlist.append([minf, i])
bad = min(minlist)
print(bad[0])
print(bad[1]+1)
```
No
| 102,461 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Think of New York as a rectangular grid consisting of N vertical avenues numerated from 1 to N and M horizontal streets numerated 1 to M. C friends are staying at C hotels located at some street-avenue crossings. They are going to celebrate birthday of one of them in the one of H restaurants also located at some street-avenue crossings. They also want that the maximum distance covered by one of them while traveling to the restaurant to be minimum possible. Help friends choose optimal restaurant for a celebration.
Suppose that the distance between neighboring crossings are all the same equal to one kilometer.
Input
The first line contains two integers N ΠΈ M β size of the city (1 β€ N, M β€ 109). In the next line there is a single integer C (1 β€ C β€ 105) β the number of hotels friends stayed at. Following C lines contain descriptions of hotels, each consisting of two coordinates x and y (1 β€ x β€ N, 1 β€ y β€ M). The next line contains an integer H β the number of restaurants (1 β€ H β€ 105). Following H lines contain descriptions of restaurants in the same format.
Several restaurants and hotels may be located near the same crossing.
Output
In the first line output the optimal distance. In the next line output index of a restaurant that produces this optimal distance. If there are several possibilities, you are allowed to output any of them.
Examples
Input
10 10
2
1 1
3 3
2
1 10
4 4
Output
6
2
Submitted Solution:
```
N,M = map(int,input().split())
C = int(input())
Ci = [list(map(int,input().split())) for i in range(C)]
H = int(input())
Hi = [list(map(int,input().split())) for i in range(H)]
xi = 0
yi = 0
for y in range(2):
for x in range(C):
if y == 0:
xi += x
else:
yi += x
xi //= C
yi //= C
minimum = 10000000000
nmin = 0
for y in range(H):
z = Hi[y][0] + Hi[y][1]
if z < minimum:
minimum = z
nmin = y
maximum = 0
for x in range(C):
e = abs(Ci[x][0]-Hi[nmin][0]) + abs(Ci[x][1]-Hi[nmin][1])
if e > maximum:
maximum = e
print(maximum)
print(nmin+1)
```
No
| 102,462 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Think of New York as a rectangular grid consisting of N vertical avenues numerated from 1 to N and M horizontal streets numerated 1 to M. C friends are staying at C hotels located at some street-avenue crossings. They are going to celebrate birthday of one of them in the one of H restaurants also located at some street-avenue crossings. They also want that the maximum distance covered by one of them while traveling to the restaurant to be minimum possible. Help friends choose optimal restaurant for a celebration.
Suppose that the distance between neighboring crossings are all the same equal to one kilometer.
Input
The first line contains two integers N ΠΈ M β size of the city (1 β€ N, M β€ 109). In the next line there is a single integer C (1 β€ C β€ 105) β the number of hotels friends stayed at. Following C lines contain descriptions of hotels, each consisting of two coordinates x and y (1 β€ x β€ N, 1 β€ y β€ M). The next line contains an integer H β the number of restaurants (1 β€ H β€ 105). Following H lines contain descriptions of restaurants in the same format.
Several restaurants and hotels may be located near the same crossing.
Output
In the first line output the optimal distance. In the next line output index of a restaurant that produces this optimal distance. If there are several possibilities, you are allowed to output any of them.
Examples
Input
10 10
2
1 1
3 3
2
1 10
4 4
Output
6
2
Submitted Solution:
```
#!/usr/bin/env python3
n, m = map(int, input().split())
minx = miny = n + m
maxx = maxy = - minx
dist = n + m + 1
c = int(input())
for _ in range(c):
x, y = map(int, input().split())
minx = min(minx, x - y)
miny = min(miny, x + y)
maxx = max(maxx, x - y)
maxy = max(maxy, x + y)
h = int(input())
for i in range(h):
a, b = map(int, input().split())
x = a - b
y = a + b
maxxy = max(
max(abs(minx - x), abs(maxx - x)),
max(abs(miny - y), abs(maxy - y))
)
if maxxy < dist:
dist = maxxy
res = i
print(dist)
print(res)
```
No
| 102,463 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number x satisfying following two conditions:
1. x doesn't contain neither digit 0 nor digit 1.
2. <image> = <image>.
Help friends find such number.
Input
The first line contains an integer n (1 β€ n β€ 15) β the number of digits in a.
The second line contains n digits of a. There is at least one digit in a that is larger than 1. Number a may possibly contain leading zeroes.
Output
Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation.
Examples
Input
4
1234
Output
33222
Input
3
555
Output
555
Note
In the first case, <image>
Tags: greedy, math, sortings
Correct Solution:
```
n = int(input())
a = input()
arr = []
t=0
for i in a:
if int(i)!=1 and int(i)!=0:
arr.append(int(i))
t+=1
final = []
for i in range(t):
if arr[i]==2:
final.append(2)
elif arr[i]==3:
final.append(3)
elif arr[i]==4:
final.append(3)
final.append(2)
final.append(2)
elif arr[i]==5:
final.append(5)
elif arr[i]==6:
final.append(5)
final.append(3)
elif arr[i]==7:
final.append(7)
elif arr[i]==8:
final.append(7)
final.append(2)
final.append(2)
final.append(2)
elif arr[i]==9:
final.append(7)
final.append(3)
final.append(3)
final.append(2)
final.sort()
final1 = ''
for i in range(-1,-(len(final)+1),-1):
final1+=str(final[i])
print(final1)
```
| 102,464 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number x satisfying following two conditions:
1. x doesn't contain neither digit 0 nor digit 1.
2. <image> = <image>.
Help friends find such number.
Input
The first line contains an integer n (1 β€ n β€ 15) β the number of digits in a.
The second line contains n digits of a. There is at least one digit in a that is larger than 1. Number a may possibly contain leading zeroes.
Output
Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation.
Examples
Input
4
1234
Output
33222
Input
3
555
Output
555
Note
In the first case, <image>
Tags: greedy, math, sortings
Correct Solution:
```
## necessary imports
import sys
input = sys.stdin.readline
from math import log2, log, ceil
# swap_array function
def swaparr(arr, a,b):
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp
## gcd function
def gcd(a,b):
if a == 0:
return b
return gcd(b%a, a)
## nCr function efficient using Binomial Cofficient
def nCr(n, k):
if(k > n - k):
k = n - k
res = 1
for i in range(k):
res = res * (n - i)
res = res / (i + 1)
return res
## upper bound function code -- such that e in a[:i] e < x;
def upper_bound(a, x, lo=0):
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if a[mid] < x:
lo = mid+1
else:
hi = mid
return lo
## prime factorization
def primefs(n):
## if n == 1 ## calculating primes
primes = {}
while(n%2 == 0):
primes[2] = primes.get(2, 0) + 1
n = n//2
for i in range(3, int(n**0.5)+2, 2):
while(n%i == 0):
primes[i] = primes.get(i, 0) + 1
n = n//i
if n > 2:
primes[n] = primes.get(n, 0) + 1
## prime factoriazation of n is stored in dictionary
## primes and can be accesed. O(sqrt n)
return primes
## MODULAR EXPONENTIATION FUNCTION
def power(x, y, p):
res = 1
x = x % p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) :
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
temp = a
a = b
b = temp
return a,b
# find function
def find(x, link):
while(x != link[x]):
x = link[x]
return x
# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, link, size):
x = find(x, link)
y = find(y, link)
if size[x] < size[y]:
x,y = swap(x,y)
if x != y:
size[x] += size[y]
link[y] = x
## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e6 + 5)
def spf_sieve():
spf[1] = 1;
for i in range(2, MAXN):
spf[i] = i;
for i in range(4, MAXN, 2):
spf[i] = 2;
for i in range(3, ceil(MAXN ** 0.5), 2):
if spf[i] == i:
for j in range(i*i, MAXN, i):
if spf[j] == j:
spf[j] = i;
## function for storing smallest prime factors (spf) in the array
################## un-comment below 2 lines when using factorization #################
# spf = [0 for i in range(MAXN)]
# spf_sieve()
def factoriazation(x):
ret = {};
while x != 1:
ret[spf[x]] = ret.get(spf[x], 0) + 1;
x = x//spf[x]
return ret
## this function is useful for multiple queries only, o/w use
## primefs function above. complexity O(log n)
## taking integer array input
def int_array():
return list(map(int, input().strip().split()))
## taking string array input
def str_array():
return input().strip().split();
#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');
################### ---------------- TEMPLATE ENDS HERE ---------------- ###################
n = int(input()); string = input().strip(); ans = '';
k = 1;
for i in string:
if i not in '10':
for j in range(int(i),1,-1):
k *= j
while(k % 5040 == 0 and k > 0):
print('7',end='');
k //= 5040
while(k % 120 == 0 and k > 0):
print('5',end='');
k //= 120
while(k % 6 == 0 and k > 0):
print('3',end='');
k //= 6
while(k % 2 == 0 and k > 0):
print('2',end='');
k //= 2
print(ans);
```
| 102,465 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number x satisfying following two conditions:
1. x doesn't contain neither digit 0 nor digit 1.
2. <image> = <image>.
Help friends find such number.
Input
The first line contains an integer n (1 β€ n β€ 15) β the number of digits in a.
The second line contains n digits of a. There is at least one digit in a that is larger than 1. Number a may possibly contain leading zeroes.
Output
Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation.
Examples
Input
4
1234
Output
33222
Input
3
555
Output
555
Note
In the first case, <image>
Tags: greedy, math, sortings
Correct Solution:
```
n = int(input())
a = input()
A = []
for i in a:
i = int(i)
if i == 2:
A.append(2)
elif i == 3:
A.append(3)
elif i == 4:
A.append(2)
A.append(2)
A.append(3)
elif i == 5:
A.append(5)
elif i == 6:
A.append(3)
A.append(5)
elif i == 7:
A.append(7)
elif i == 8:
A.append(2)
A.append(2)
A.append(2)
A.append(7)
elif i == 9:
A.append(3)
A.append(3)
A.append(2)
A.append(7)
A.sort(key=None, reverse=True)
#print(A)
s = ''
for k in A:
s = s+str(k)
print(s)
```
| 102,466 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number x satisfying following two conditions:
1. x doesn't contain neither digit 0 nor digit 1.
2. <image> = <image>.
Help friends find such number.
Input
The first line contains an integer n (1 β€ n β€ 15) β the number of digits in a.
The second line contains n digits of a. There is at least one digit in a that is larger than 1. Number a may possibly contain leading zeroes.
Output
Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation.
Examples
Input
4
1234
Output
33222
Input
3
555
Output
555
Note
In the first case, <image>
Tags: greedy, math, sortings
Correct Solution:
```
'''input
3
555
'''
n = int(input())
s = input()
d = {7:0, 5:0, 3:0, 2:0}
for x in s:
if x == '2':
d[2] += 1
elif x == '3':
d[3] += 1
elif x == '4':
d[3] += 1
d[2] += 2
elif x == '5':
d[5] += 1
elif x == '6':
d[5] += 1
d[3] += 1
elif x == '7':
d[7] += 1
elif x == '8':
d[7] += 1
d[2] += 3
elif x == '9':
d[7] += 1
d[3] += 2
d[2] += 1
for x in [7, 5, 3, 2]:
print(str(x) * d[x], end = "")
```
| 102,467 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number x satisfying following two conditions:
1. x doesn't contain neither digit 0 nor digit 1.
2. <image> = <image>.
Help friends find such number.
Input
The first line contains an integer n (1 β€ n β€ 15) β the number of digits in a.
The second line contains n digits of a. There is at least one digit in a that is larger than 1. Number a may possibly contain leading zeroes.
Output
Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation.
Examples
Input
4
1234
Output
33222
Input
3
555
Output
555
Note
In the first case, <image>
Tags: greedy, math, sortings
Correct Solution:
```
n = int(input())
a = list(map(int, input()))
m = ['', '', '2', '3', '322', '5', '53', '7', '7222', '7332']
print(''.join(sorted((''.join(m[t] for t in a)), reverse=True)))
```
| 102,468 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number x satisfying following two conditions:
1. x doesn't contain neither digit 0 nor digit 1.
2. <image> = <image>.
Help friends find such number.
Input
The first line contains an integer n (1 β€ n β€ 15) β the number of digits in a.
The second line contains n digits of a. There is at least one digit in a that is larger than 1. Number a may possibly contain leading zeroes.
Output
Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation.
Examples
Input
4
1234
Output
33222
Input
3
555
Output
555
Note
In the first case, <image>
Tags: greedy, math, sortings
Correct Solution:
```
input()
a=input()
b=['','','2','3','223','5','35','7','2227','2337']
print(''.join(sorted(''.join([b[int(i)]for i in a]),reverse=True)))
```
| 102,469 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number x satisfying following two conditions:
1. x doesn't contain neither digit 0 nor digit 1.
2. <image> = <image>.
Help friends find such number.
Input
The first line contains an integer n (1 β€ n β€ 15) β the number of digits in a.
The second line contains n digits of a. There is at least one digit in a that is larger than 1. Number a may possibly contain leading zeroes.
Output
Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation.
Examples
Input
4
1234
Output
33222
Input
3
555
Output
555
Note
In the first case, <image>
Tags: greedy, math, sortings
Correct Solution:
```
n=int(input())
s=list(input())
d={
'2': '2',
'3': '3',
'4': '322',
'5': '5',
'6': '35',
'7': '7',
'8': '2227',
'9': '2337'
}
ans=''
for i in s:
if i>'1':
ans+=d[i]
print(''.join(sorted(list(ans),reverse=True)))
```
| 102,470 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number x satisfying following two conditions:
1. x doesn't contain neither digit 0 nor digit 1.
2. <image> = <image>.
Help friends find such number.
Input
The first line contains an integer n (1 β€ n β€ 15) β the number of digits in a.
The second line contains n digits of a. There is at least one digit in a that is larger than 1. Number a may possibly contain leading zeroes.
Output
Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation.
Examples
Input
4
1234
Output
33222
Input
3
555
Output
555
Note
In the first case, <image>
Tags: greedy, math, sortings
Correct Solution:
```
import sys
lines = sys.stdin.readlines()
N = int(lines[0].strip())
num = lines[1].strip()
factor = {2:{2:1}, 3: {3:1}, 4:{2:2}, 5:{5:1}, 6:{2:1, 3:1}, 7:{7:1}, 8:{2:3}, 9:{3:2}}
factorial = [{}, {}]
tmp = {}
for i in range(2, 10):
for k in factor[i].keys():
if k not in tmp: tmp[k] = 0
tmp[k] += factor[i][k]
factorial.append(tmp.copy())
target = {}
for l in num:
for k in factorial[int(l)].keys():
if k not in target: target[k] = 0
target[k] += factorial[int(l)][k]
res = ""
if 7 in target:
val = target[7]
res += "7" * val
for k in factorial[7].keys():
target[k] -= factorial[7][k] * val
if 5 in target and target[5] > 0:
val = target[5]
res += "5" * val
for k in factorial[5].keys():
target[k] -= factorial[5][k] * val
if 3 in target and target[3] > 0:
val = target[3]
res += "3" * val
for k in factorial[3].keys():
target[k] -= factorial[3][k] * val
if 2 in target: res += "2" * target[2]
print(res)
```
| 102,471 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number x satisfying following two conditions:
1. x doesn't contain neither digit 0 nor digit 1.
2. <image> = <image>.
Help friends find such number.
Input
The first line contains an integer n (1 β€ n β€ 15) β the number of digits in a.
The second line contains n digits of a. There is at least one digit in a that is larger than 1. Number a may possibly contain leading zeroes.
Output
Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation.
Examples
Input
4
1234
Output
33222
Input
3
555
Output
555
Note
In the first case, <image>
Submitted Solution:
```
# coding: utf-8
n = int(input())
cnt = {2:0,3:0,5:0,7:0}
for i in input():
if i == '2':
cnt[2] += 1
elif i == '3':
cnt[3] += 1
elif i == '4':
cnt[2] += 2
cnt[3] += 1
elif i == '5':
cnt[5] += 1
elif i == '6':
cnt[3] += 1
cnt[5] += 1
elif i == '7':
cnt[7] += 1
elif i == '8':
cnt[2] += 3
cnt[7] += 1
elif i == '9':
cnt[2] += 1
cnt[3] += 2
cnt[7] += 1
for i in sorted(cnt.keys(),reverse=True):
print(str(i)*cnt[i],end='')
print('')
```
Yes
| 102,472 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number x satisfying following two conditions:
1. x doesn't contain neither digit 0 nor digit 1.
2. <image> = <image>.
Help friends find such number.
Input
The first line contains an integer n (1 β€ n β€ 15) β the number of digits in a.
The second line contains n digits of a. There is at least one digit in a that is larger than 1. Number a may possibly contain leading zeroes.
Output
Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation.
Examples
Input
4
1234
Output
33222
Input
3
555
Output
555
Note
In the first case, <image>
Submitted Solution:
```
n=input()
x=input()
a,b=[0]*10,[0]*10
for i in range(2,10):
a[i]=x.count(str(i))
b[2]=a[2]+2*a[4]+3*a[8]+a[9]
b[3]=a[3]+a[4]+a[6]+2*a[9]
b[5]=a[5]+a[6]
b[7]=a[7]+a[8]+a[9]
print('7'*b[7]+'5'*b[5]+'3'*b[3]+'2'*b[2])
```
Yes
| 102,473 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number x satisfying following two conditions:
1. x doesn't contain neither digit 0 nor digit 1.
2. <image> = <image>.
Help friends find such number.
Input
The first line contains an integer n (1 β€ n β€ 15) β the number of digits in a.
The second line contains n digits of a. There is at least one digit in a that is larger than 1. Number a may possibly contain leading zeroes.
Output
Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation.
Examples
Input
4
1234
Output
33222
Input
3
555
Output
555
Note
In the first case, <image>
Submitted Solution:
```
def fact(num):
f=1
while (num>0):
f=f*num
num-=1
return f
n=int(input())
a=int(input())
d={"0":0,"1":0,"2":2,"3":3,"4":322,"5":5,"6":53,"7":7,"8":7222,"9":7332}
sa=str(a)
sans=""
for i in sa:
num=d[i]
if (num!=0):
sans+=str(num)
#print(sans)
arr=[]
for i in sans:
arr.append(i)
for i in range(len(arr)):
for j in range(len(arr)):
if (ord(arr[j])>ord(arr[i])):
arr[j],arr[i]=arr[i],arr[j]
arr.sort(reverse=True)
ans=0
for i in arr:
ans=ans*10+int(i)
print(ans)
```
Yes
| 102,474 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number x satisfying following two conditions:
1. x doesn't contain neither digit 0 nor digit 1.
2. <image> = <image>.
Help friends find such number.
Input
The first line contains an integer n (1 β€ n β€ 15) β the number of digits in a.
The second line contains n digits of a. There is at least one digit in a that is larger than 1. Number a may possibly contain leading zeroes.
Output
Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation.
Examples
Input
4
1234
Output
33222
Input
3
555
Output
555
Note
In the first case, <image>
Submitted Solution:
```
'''input
3
92
'''
# connected components
from sys import stdin
from collections import defaultdict
import sys
sys.setrecursionlimit(15000)
# main starts
n = int(stdin.readline().strip())
string = list(stdin.readline().strip())
mydict = []
for i in string:
if i == '0' or i == '1':
continue
else:
num = int(i)
if num in [2, 3, 5, 7]:
mydict.append(num)
else:
if num == 4:
mydict.append(3)
mydict.append(2)
mydict.append(2)
if num == 6:
mydict.append(5)
mydict.append(3)
if num == 8:
mydict.append(7)
mydict.append(2)
mydict.append(2)
mydict.append(2)
if num == 9:
mydict.append(7)
mydict.append(3)
mydict.append(3)
mydict.append(2)
mydict.sort(reverse = True)
for i in mydict:
print(i, end = '')
```
Yes
| 102,475 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number x satisfying following two conditions:
1. x doesn't contain neither digit 0 nor digit 1.
2. <image> = <image>.
Help friends find such number.
Input
The first line contains an integer n (1 β€ n β€ 15) β the number of digits in a.
The second line contains n digits of a. There is at least one digit in a that is larger than 1. Number a may possibly contain leading zeroes.
Output
Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation.
Examples
Input
4
1234
Output
33222
Input
3
555
Output
555
Note
In the first case, <image>
Submitted Solution:
```
n = int(input())
a = list(map(int, list(input())))
b = []
for e in a:
if e == 1 or e == 0:
continue
elif e == 2 or e == 3 or e == 5 or a == 7:
b.append(e)
elif e == 4:
b.append(3)
b.append(2)
b.append(2)
elif e == 6:
b.append(5)
b.append(3)
elif e == 8:
b.append(7)
b.append(2)
b.append(2)
b.append(2)
elif e == 9:
b.append(7)
b.append(3)
b.append(3)
b.append(2)
b = list(map(str, sorted(b)))
b.reverse()
print(''.join(b))
```
No
| 102,476 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number x satisfying following two conditions:
1. x doesn't contain neither digit 0 nor digit 1.
2. <image> = <image>.
Help friends find such number.
Input
The first line contains an integer n (1 β€ n β€ 15) β the number of digits in a.
The second line contains n digits of a. There is at least one digit in a that is larger than 1. Number a may possibly contain leading zeroes.
Output
Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation.
Examples
Input
4
1234
Output
33222
Input
3
555
Output
555
Note
In the first case, <image>
Submitted Solution:
```
def findPrime(n):
prime_numbers = []
# made a boolean list of all numbers from 1 - n
prime_number_list = [True for i in range(n+1)]
# taken 2 as a starting point as 2 is the lowers prime number
p = 2
while(p*p <= n):
# get unmarked number
if prime_number_list[p]:
# mark all the numbers divisible by unmarked number
for i in range(p*2, n+1, p):
prime_number_list[i] = False
p = p+1
for i in range(2, n+1):
if prime_number_list[i]:
prime_numbers.append(str(i))
return prime_numbers
a=int(input())
l=[]
li=[]
for i in input():
l=findPrime(int(i))
li=li+l
li=sorted(li,reverse=True)
print(''.join(li))
```
No
| 102,477 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number x satisfying following two conditions:
1. x doesn't contain neither digit 0 nor digit 1.
2. <image> = <image>.
Help friends find such number.
Input
The first line contains an integer n (1 β€ n β€ 15) β the number of digits in a.
The second line contains n digits of a. There is at least one digit in a that is larger than 1. Number a may possibly contain leading zeroes.
Output
Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation.
Examples
Input
4
1234
Output
33222
Input
3
555
Output
555
Note
In the first case, <image>
Submitted Solution:
```
n=int(input())
k=int(input())
a=["","2","3","322","5","35","7","7222","7233"]
s=""
for i in range(n):
s=s+a[int(k%10)-1]
k/=10
s=''.join(sorted(s))[::-1]
print(s)
```
No
| 102,478 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number x satisfying following two conditions:
1. x doesn't contain neither digit 0 nor digit 1.
2. <image> = <image>.
Help friends find such number.
Input
The first line contains an integer n (1 β€ n β€ 15) β the number of digits in a.
The second line contains n digits of a. There is at least one digit in a that is larger than 1. Number a may possibly contain leading zeroes.
Output
Output a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation.
Examples
Input
4
1234
Output
33222
Input
3
555
Output
555
Note
In the first case, <image>
Submitted Solution:
```
l = int(input())
number = list(input())
for i in range(len(number)):
if number[i] == '0' or number[i] == '1':
number[i:i+1] = []
if number[i] == '4':
number[i:i+1] = ['2', '2', '3']
i += 2
if number[i] == '6':
number[i:i+1] = ['5', '6']
i += 1
if number[i] == '8':
number[i:i+1] = ['7', '2', '2', '2']
i += 3
if number[i] == '9':
number[i:i+1] = ['7', '2', '2', '2', '3', '3']
i += 5
number.sort(reverse=True)
print(''.join(number))
```
No
| 102,479 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State.
Since roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of n rows and m columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable.
Your task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells.
It is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it.
Input
The first line of the input contains the dimensions of the map n and m (1 β€ n, m β€ 1000) β the number of rows and columns respectively.
Each of the next n lines contain m characters, describing the rows of the map. Digits from 1 to 3 represent the accessory to the corresponding state. The character '.' corresponds to the cell where it is allowed to build a road and the character '#' means no construction is allowed in this cell.
Output
Print a single integer β the minimum number of cells you need to build a road inside in order to connect all the cells of all states. If such a goal is unachievable, print -1.
Examples
Input
4 5
11..2
#..22
#.323
.#333
Output
2
Input
1 5
1#2#3
Output
-1
Tags: dfs and similar, graphs, shortest paths
Correct Solution:
```
# lista doble enlazada o(1) operaciones en los bordes es mejor que si se implementa en el propio lenguaje
from collections import deque
def idx(i, j):
return i*m + j
def solve():
global n, m
n, m = map(lambda x: int(x), input().split())
global maxValue
maxValue = (n*m)**2
global graph
graph = ['']*(n*m)
virtDist = [[maxValue] * (n*m), [maxValue] * (n*m), [maxValue] * (n*m)]
virtVertex = [deque(), deque(), deque()]
refAsci = ord("1")
for i in range(0, n):
s = input()
for j in range(0, m):
graph[idx(i, j)] = s[j]
indx = ord(s[j])-refAsci
if not (0 <= indx <= 2):
continue
virtVertex[indx].append((i, j))
virtDist[indx][idx(i, j)] = 0
bfs01(virtVertex[0], virtDist[0])
bfs01(virtVertex[1], virtDist[1])
bfs01(virtVertex[2], virtDist[2])
output = maxValue
for i in range(0, n*m):
output = min(virtDist[0][i] + virtDist[1][i] + virtDist[2][i]
- (2 if graph[i] == "."else 0), output)
print(output if output < maxValue else -1)
def bfs01(queue, distance):
while queue:
pi, pj = queue.popleft()
for i, j in [(pi, pj-1), (pi, pj+1), (pi-1, pj), (pi+1, pj)]:
indx = idx(i, j)
if 0 > i or i >= n or 0 > j or j >= m or graph[indx] == '#':
continue
isRoad = graph[indx] == "."
newDistance = distance[idx(pi, pj)] + (1 if isRoad else 0)
if distance[indx] > newDistance: # relax
distance[indx] = newDistance
if isRoad:
queue.append((i, j))
else:
queue.appendleft((i, j))
solve()
```
| 102,480 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State.
Since roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of n rows and m columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable.
Your task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells.
It is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it.
Input
The first line of the input contains the dimensions of the map n and m (1 β€ n, m β€ 1000) β the number of rows and columns respectively.
Each of the next n lines contain m characters, describing the rows of the map. Digits from 1 to 3 represent the accessory to the corresponding state. The character '.' corresponds to the cell where it is allowed to build a road and the character '#' means no construction is allowed in this cell.
Output
Print a single integer β the minimum number of cells you need to build a road inside in order to connect all the cells of all states. If such a goal is unachievable, print -1.
Examples
Input
4 5
11..2
#..22
#.323
.#333
Output
2
Input
1 5
1#2#3
Output
-1
Tags: dfs and similar, graphs, shortest paths
Correct Solution:
```
# lista doble enlazada o(1) operaciones en los bordes es mejor que si se implementa en el propio lenguaje
from collections import deque
def idx(i, j):
return i*m + j
def solve():
global n, m
n, m = map(lambda x: int(x), input().split())
global maxValue
maxValue = (n*m)**2
global graph
graph = ""
virtDist = [[maxValue] * (n*m), [maxValue] * (n*m), [maxValue] * (n*m)]
virtVertex = [deque(), deque(), deque()]
refAsci = ord("1")
for i in range(0, n):
s = input()
graph += s
for j in range(0, m):
indx = ord(s[j])-refAsci
if not (0 <= indx <= 2):
continue
virtVertex[indx].append((i, j))
virtDist[indx][idx(i, j)] = 0
bfs01(virtVertex[0], virtDist[0])
bfs01(virtVertex[1], virtDist[1])
bfs01(virtVertex[2], virtDist[2])
output = maxValue
for i in range(0, n*m):
output = min(virtDist[0][i] + virtDist[1][i] + virtDist[2][i]
- (2 if graph[i] == "."else 0), output)
print(output if output < maxValue else -1)
def bfs01(queue, distance):
while queue:
pi, pj = queue.popleft()
for i, j in [(pi, pj-1), (pi, pj+1), (pi-1, pj), (pi+1, pj)]:
indx = idx(i, j)
if 0 > i or i >= n or 0 > j or j >= m or graph[indx] == '#':
continue
isRoad = graph[indx] == "."
newDistance = distance[idx(pi, pj)] + (1 if isRoad else 0)
if distance[indx] > newDistance: # relax
distance[indx] = newDistance
if isRoad:
queue.append((i, j))
else:
queue.appendleft((i, j))
solve()
```
| 102,481 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State.
Since roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of n rows and m columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable.
Your task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells.
It is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it.
Input
The first line of the input contains the dimensions of the map n and m (1 β€ n, m β€ 1000) β the number of rows and columns respectively.
Each of the next n lines contain m characters, describing the rows of the map. Digits from 1 to 3 represent the accessory to the corresponding state. The character '.' corresponds to the cell where it is allowed to build a road and the character '#' means no construction is allowed in this cell.
Output
Print a single integer β the minimum number of cells you need to build a road inside in order to connect all the cells of all states. If such a goal is unachievable, print -1.
Examples
Input
4 5
11..2
#..22
#.323
.#333
Output
2
Input
1 5
1#2#3
Output
-1
Tags: dfs and similar, graphs, shortest paths
Correct Solution:
```
# lista doble enlazada o(1) operaciones en los bordes es mejor que si se implementa en el propio lenguaje
from collections import deque
def idx(i, j):
return i*m + j
def solve():
global n, m
n, m = map(lambda x: int(x), input().split())
global maxValue
maxValue = (n*m)**2
graph = ['']*(n*m)
virtDst = [[maxValue] * (n*m), [maxValue] * (n*m), [maxValue] * (n*m)]
virtVertex = [deque(), deque(), deque()]
refAsci = ord("1")
for i in range(0, n):
s = input()
for j in range(0, m):
graph[idx(i, j)] = s[j]
indx = ord(s[j])-refAsci
if not (0 <= indx <= 2):
continue
virtVertex[indx].append((i, j))
virtDst[indx][idx(i, j)] = 0
bfs01(graph, virtVertex[0], virtDst[0])
bfs01(graph, virtVertex[1], virtDst[1])
bfs01(graph, virtVertex[2], virtDst[2])
minimum = maxValue
for i in range(0, n*m):
minimum = min(virtDst[0][i] + virtDst[1][i] + virtDst[2][i]
- (2 if graph[i] == "."else 0), minimum)
print(minimum if minimum < maxValue else -1)
def bfs01(graph, queue, dist):
while queue:
pi, pj = queue.popleft()
for i, j in [(pi, pj-1), (pi, pj+1), (pi-1, pj), (pi+1, pj)]:
indx = idx(i, j)
if (not (0 <= i < n and 0 <= j < m)) or graph[indx] == '#':
continue
isRoad = graph[indx] == "."
newDist = dist[idx(pi, pj)] + (1 if isRoad else 0)
if dist[indx] > newDist: # relax
dist[indx] = newDist
if isRoad:
queue.append((i, j))
else:
queue.appendleft((i, j))
solve()
```
| 102,482 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State.
Since roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of n rows and m columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable.
Your task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells.
It is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it.
Input
The first line of the input contains the dimensions of the map n and m (1 β€ n, m β€ 1000) β the number of rows and columns respectively.
Each of the next n lines contain m characters, describing the rows of the map. Digits from 1 to 3 represent the accessory to the corresponding state. The character '.' corresponds to the cell where it is allowed to build a road and the character '#' means no construction is allowed in this cell.
Output
Print a single integer β the minimum number of cells you need to build a road inside in order to connect all the cells of all states. If such a goal is unachievable, print -1.
Examples
Input
4 5
11..2
#..22
#.323
.#333
Output
2
Input
1 5
1#2#3
Output
-1
Tags: dfs and similar, graphs, shortest paths
Correct Solution:
```
#!/usr/bin/env python3
#
# Three States
#
import sys, os
from collections import deque
from pprint import pprint
def read_ints(): return list(map(int, input().split()))
def read_str(): return input().strip()
n, m = read_ints()
s = [read_str() for _ in range(n)]
t = [set(), set(), set()]
for i in range(n):
for j in range(m):
if s[i][j] in '123':
for ii, jj in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
if 0 <= ii < n and 0 <= jj < m:
if s[ii][jj] in '123.' and s[i][j] != s[ii][jj]:
t[int(s[i][j]) - 1].add((i, j))
break
z = [[[1e18] * 3 for j in range(m)] for i in range(n)]
ans = 1e18
for root in range(3):
q = deque()
vi = [[False] * m for _ in range(n)]
for i, j in t[root]:
q.append((i, j, 0))
vi[i][j] = True
z[i][j][root] = 0
dist = [1e18] * 3
dist[root] = 0
while q:
i, j, d = q.popleft()
for ii, jj in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
if 0 <= ii < n and 0 <= jj < m and not vi[ii][jj]:
if s[ii][jj] == '.':
vi[ii][jj] = True
q.append((ii, jj, d + 1))
z[ii][jj][root] = min(z[ii][jj][root], d + 1)
elif s[ii][jj] != s[i][j] and s[ii][jj] in '123':
dist[int(s[ii][jj]) - 1] = min(dist[int(s[ii][jj]) - 1], d)
ans = min(ans, sum(dist))
if ans >= 1e18:
print(-1)
else:
for i in range(n):
for j in range(m):
if s[i][j] == '.':
ans = min(ans, sum(z[i][j]) - 2)
print(ans)
```
| 102,483 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State.
Since roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of n rows and m columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable.
Your task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells.
It is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it.
Input
The first line of the input contains the dimensions of the map n and m (1 β€ n, m β€ 1000) β the number of rows and columns respectively.
Each of the next n lines contain m characters, describing the rows of the map. Digits from 1 to 3 represent the accessory to the corresponding state. The character '.' corresponds to the cell where it is allowed to build a road and the character '#' means no construction is allowed in this cell.
Output
Print a single integer β the minimum number of cells you need to build a road inside in order to connect all the cells of all states. If such a goal is unachievable, print -1.
Examples
Input
4 5
11..2
#..22
#.323
.#333
Output
2
Input
1 5
1#2#3
Output
-1
Tags: dfs and similar, graphs, shortest paths
Correct Solution:
```
from collections import deque
def idx(i, j):
return i*m + j
def solve():
global n, m
n, m = map(lambda x: int(x), input().split())
global maxVal
maxVal = (n*m)**2
graph = ['']*(n*m)
vrtDst = [[maxVal] * (n*m), [maxVal] * (n*m), [maxVal] * (n*m)]
virtVertex = [deque(), deque(), deque()]
refAsci = ord("1")
for i in range(0, n):
s = input()
for j in range(0, m):
graph[idx(i, j)] = s[j]
indx = ord(s[j])-refAsci
if not (0 <= indx <= 2):
continue
virtVertex[indx].append((i, j))
vrtDst[indx][idx(i, j)] = 0
bfs01(graph, virtVertex[0], vrtDst[0])
bfs01(graph, virtVertex[1], vrtDst[1])
bfs01(graph, virtVertex[2], vrtDst[2])
smallst = maxVal
for i in range(0, n*m):
smallst = min(smallst, vrtDst[0][i]
+ vrtDst[1][i] + vrtDst[2][i]
- (2 if graph[i] == "."else 0))
print(smallst if smallst < maxVal else -1)
def bfs01(graph, queue, dist):
while queue:
pi, pj = queue.popleft()
for i, j in [(pi, pj-1), (pi, pj+1), (pi-1, pj), (pi+1, pj)]:
indx = idx(i, j)
if not (0 <= i < n and 0 <= j < m) or graph[indx] == '#':
continue
isRoad = graph[indx] == "."
newDist = dist[idx(pi, pj)] + (1 if isRoad else 0)
if dist[indx] > newDist: # relax
dist[indx] = newDist
if isRoad:
queue.append((i, j))
else:
queue.appendleft((i, j))
solve()
```
| 102,484 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State.
Since roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of n rows and m columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable.
Your task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells.
It is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it.
Input
The first line of the input contains the dimensions of the map n and m (1 β€ n, m β€ 1000) β the number of rows and columns respectively.
Each of the next n lines contain m characters, describing the rows of the map. Digits from 1 to 3 represent the accessory to the corresponding state. The character '.' corresponds to the cell where it is allowed to build a road and the character '#' means no construction is allowed in this cell.
Output
Print a single integer β the minimum number of cells you need to build a road inside in order to connect all the cells of all states. If such a goal is unachievable, print -1.
Examples
Input
4 5
11..2
#..22
#.323
.#333
Output
2
Input
1 5
1#2#3
Output
-1
Tags: dfs and similar, graphs, shortest paths
Correct Solution:
```
# lista doble enlazada o(1) operaciones en los bordes es mejor que si se implementa en el propio lenguaje
from collections import deque
n, m = input().split()
n = int(n)
m = int(m)
def idx(i, j):
return i*m + j
max = n*m*2
graph = ""
virtDist = [[], [], []]
virtVertex = [deque(), deque(), deque()]
virtNodesDst = [max, max, max]
code = ord("1")
for i in range(0, n):
s = input()
graph += s
for j in range(0, m):
virtDist[0].append(max)
virtDist[1].append(max)
virtDist[2].append(max)
indx = ord(s[j])-code
if 0 > indx or indx > 2:
continue
virtVertex[indx].append((i, j))
i2 = idx(i, j)
virtDist[indx][-1] = 0
def bfs01(queue, distance):
while queue:
pi, pj = queue.popleft()
for i, j in [(pi, pj-1), (pi, pj+1), (pi-1, pj), (pi+1, pj)]:
indx = idx(i, j)
if 0 > i or i >= n or 0 > j or j >= m or graph[indx] == '#':
continue
isRoad = graph[indx] == "."
newDistance = distance[idx(pi, pj)] + (1 if isRoad else 0)
if distance[indx] > newDistance: # relax
distance[indx] = newDistance
if isRoad:
queue.append((i, j))
else:
queue.appendleft((i, j))
bfs01(virtVertex[0], virtDist[0])
bfs01(virtVertex[1], virtDist[1])
bfs01(virtVertex[2], virtDist[2])
output = max
for i in range(0, n*m):
output = min(virtDist[0][i] + virtDist[1][i] + virtDist[2]
[i] - (2 if graph[i] == "."else 0), output)
print(output if output < max else -1)
```
| 102,485 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State.
Since roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of n rows and m columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable.
Your task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells.
It is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it.
Input
The first line of the input contains the dimensions of the map n and m (1 β€ n, m β€ 1000) β the number of rows and columns respectively.
Each of the next n lines contain m characters, describing the rows of the map. Digits from 1 to 3 represent the accessory to the corresponding state. The character '.' corresponds to the cell where it is allowed to build a road and the character '#' means no construction is allowed in this cell.
Output
Print a single integer β the minimum number of cells you need to build a road inside in order to connect all the cells of all states. If such a goal is unachievable, print -1.
Examples
Input
4 5
11..2
#..22
#.323
.#333
Output
2
Input
1 5
1#2#3
Output
-1
Submitted Solution:
```
from collections import deque
n, m = map(int, input().split())
cnt = set()
second = []
third = []
visit = [[0 for i in range(m)] for j in range(n)]
queue = deque()
maps = []
for i in range(n):
maps.append(input())
for j in range(m):
if maps[i][j] == '1':
queue.append((i, j))
visit[i][j] = 1
elif maps[i][j] == '#':
visit[i][j] = float('inf')
while queue:
x, y = queue.popleft()
if maps[x][y] in '.1':
if n - x - 1 and maps[x + 1][y] != '#' and not visit[x + 1][y]:
visit[x + 1][y] = visit[x][y] + 1
queue.append((x + 1, y))
if x and maps[x - 1][y] != '#' and not visit[x - 1][y]:
visit[x - 1][y] = visit[x][y] + 1
queue.append((x - 1, y))
if m - y - 1 and maps[x][y + 1] != '#' and not visit[x][y + 1]:
visit[x][y + 1] = visit[x][y] + 1
queue.append((x, y + 1))
if y and maps[x][y - 1] != '#' and not visit[x][y - 1]:
visit[x][y - 1] = visit[x][y] + 1
queue.append((x, y - 1))
elif maps[x][y] == '2':
if not second:
second = (x, y)
if n - x - 1 and maps[x + 1][y] in '.3' and not visit[x + 1][y]:
visit[x + 1][y] = visit[x][y] + 1
queue.append((x + 1, y))
elif n - x - 1 and maps[x + 1][y] == '2' and not visit[x + 1][y]:
visit[x + 1][y] = visit[x][y]
queue.appendleft((x + 1, y))
if x and maps[x - 1][y] in '.3' and not visit[x - 1][y]:
visit[x - 1][y] = visit[x][y] + 1
queue.append((x - 1, y))
elif x and maps[x - 1][y] == '2' and not visit[x - 1][y]:
visit[x - 1][y] = visit[x][y]
queue.appendleft((x - 1, y))
if m - y - 1 and maps[x][y + 1] in '.3' and not visit[x][y + 1]:
visit[x][y + 1] = visit[x][y] + 1
queue.append((x, y + 1))
elif m - y - 1 and maps[x][y + 1] == '2' and not visit[x + 1][y]:
visit[x][y + 1] = visit[x][y]
queue.appendleft((x, y + 1))
if y and maps[x][y - 1] in '.3' and not visit[x][y - 1]:
visit[x][y - 1] = visit[x][y] + 1
queue.append((x, y - 1))
elif y and maps[x][y - 1] == '2' and not visit[x][y - 1]:
visit[x][y - 1] = visit[x][y]
queue.appendleft((x, y - 1))
elif maps[x][y] == '3':
if not third:
third = (x, y)
if n - x - 1 and maps[x + 1][y] in '.2' and not visit[x + 1][y]:
visit[x + 1][y] = visit[x][y] + 1
queue.append((x + 1, y))
elif n - x - 1 and maps[x + 1][y] == '3' and not visit[x + 1][y]:
visit[x + 1][y] = visit[x][y]
queue.appendleft((x + 1, y))
if x and maps[x - 1][y] in '.2' and not visit[x - 1][y]:
visit[x - 1][y] = visit[x][y] + 1
queue.append((x - 1, y))
elif x and maps[x - 1][y] == '3' and not visit[x - 1][y]:
visit[x - 1][y] = visit[x][y]
queue.appendleft((x - 1, y))
if m - y - 1 and maps[x][y + 1] in '.2' and not visit[x][y + 1]:
visit[x][y + 1] = visit[x][y] + 1
queue.append((x, y + 1))
elif m - y - 1 and maps[x][y + 1] == '3' and not visit[x][y + 1]:
visit[x][y + 1] = visit[x][y]
queue.appendleft((x, y + 1))
if y and maps[x][y - 1] in '.2' and not visit[x][y - 1]:
visit[x][y - 1] = visit[x][y] + 1
queue.append((x, y - 1))
elif y and maps[x][y - 1] == '3' and not visit[x][y - 1]:
visit[x][y - 1] = visit[x][y]
queue.appendleft((x, y - 1))
if not third or not second:
print('-1')
else:
x, y = third
ans = 0
while maps[x][y] != '1':
if (x, y) not in cnt and (maps[x][y] == '.'):
ans += 1
cnt.add((x, y))
if x and visit[x - 1][y] < visit[x][y]:
x -= 1
elif n - x - 1 and visit[x + 1][y] < visit[x][y]:
x += 1
elif y and visit[x][y - 1] < visit[x][y]:
y -= 1
elif m - y - 1 and visit[x][y + 1] < visit[x][y]:
y += 1
if x and maps[x - 1][y] == '2':
second = 0
elif n - x - 1 and maps[x + 1][y] == '2':
second = 0
elif y and maps[x][y - 1] == '2':
second = 0
elif m - y - 1 and maps[x][y + 1] == '2':
second = 0
if maps[x][y] == '2':
x, y = second
second = 0
third = 0
if not second:
print(ans)
else:
x, y = second
while maps[x][y] != '1':
if (x, y) not in cnt and (maps[x][y] == '.'):
ans += 1
cnt.add((x, y))
if x and visit[x - 1][y] < visit[x][y]:
x -= 1
elif n - x - 1 and visit[x + 1][y] < visit[x][y]:
x += 1
elif y and visit[x][y - 1] < visit[x][y]:
y -= 1
elif m - y - 1 and visit[x][y + 1] < visit[x][y]:
y += 1
print(ans)
```
No
| 102,486 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State.
Since roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of n rows and m columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable.
Your task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells.
It is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it.
Input
The first line of the input contains the dimensions of the map n and m (1 β€ n, m β€ 1000) β the number of rows and columns respectively.
Each of the next n lines contain m characters, describing the rows of the map. Digits from 1 to 3 represent the accessory to the corresponding state. The character '.' corresponds to the cell where it is allowed to build a road and the character '#' means no construction is allowed in this cell.
Output
Print a single integer β the minimum number of cells you need to build a road inside in order to connect all the cells of all states. If such a goal is unachievable, print -1.
Examples
Input
4 5
11..2
#..22
#.323
.#333
Output
2
Input
1 5
1#2#3
Output
-1
Submitted Solution:
```
from collections import deque
infin = float('inf')
second = float('inf')
third = float('inf')
n, m = map(int, input().split())
visit = [[0 for i in range(m)] for j in range(n)]
maps = []
queue = deque()
for i in range(n):
maps.append(input())
for j in range(len(maps[i])):
if maps[i][j] in '1':
queue.append((i, j))
visit[i][j] = 1
def bfs(err):
global second, third
while queue:
x, y = queue.popleft()
if maps[x][y] == '2' and second > visit[x][y]:
second = visit[x][y]
if maps[x][y] == '3' and third > visit[x][y]:
third = visit[x][y]
if x + 1 < n and not visit[x + 1][y] and maps[x + 1][y] in '123.':
if maps[x + 1][y] == '.':
visit[x + 1][y] = visit[x][y] + 1
queue.append((x + 1, y))
else:
queue.appendleft((x + 1, y))
visit[x + 1][y] = visit[x][y]
if x and not visit[x - 1][y] and maps[x - 1][y] in '123.':
if maps[x - 1][y] == '.':
queue.append((x - 1, y))
visit[x - 1][y] = visit[x][y] + 1
else:
queue.appendleft((x - 1, y))
visit[x - 1][y] = visit[x][y]
if y + 1 < m and not visit[x][y + 1] and maps[x][y + 1] in '123.':
if maps[x][y + 1] == '.':
queue.append((x, y + 1))
visit[x][y + 1] = visit[x][y] + 1
else:
queue.appendleft((x, y + 1))
visit[x][y + 1] = visit[x][y]
if y and not visit[x][y - 1] and maps[x][y - 1] in '123.':
if maps[x][y - 1] == '.':
queue.append((x, y - 1))
visit[x][y - 1] = visit[x][y] + 1
else:
queue.appendleft((x, y - 1))
visit[x][y - 1] = visit[x][y]
bfs(0)
if second == infin or third == infin:
print('-1')
else:
print(max(second, third) - 1)
```
No
| 102,487 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State.
Since roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of n rows and m columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable.
Your task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells.
It is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it.
Input
The first line of the input contains the dimensions of the map n and m (1 β€ n, m β€ 1000) β the number of rows and columns respectively.
Each of the next n lines contain m characters, describing the rows of the map. Digits from 1 to 3 represent the accessory to the corresponding state. The character '.' corresponds to the cell where it is allowed to build a road and the character '#' means no construction is allowed in this cell.
Output
Print a single integer β the minimum number of cells you need to build a road inside in order to connect all the cells of all states. If such a goal is unachievable, print -1.
Examples
Input
4 5
11..2
#..22
#.323
.#333
Output
2
Input
1 5
1#2#3
Output
-1
Submitted Solution:
```
z=-1
print(z)
```
No
| 102,488 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State.
Since roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of n rows and m columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable.
Your task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells.
It is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it.
Input
The first line of the input contains the dimensions of the map n and m (1 β€ n, m β€ 1000) β the number of rows and columns respectively.
Each of the next n lines contain m characters, describing the rows of the map. Digits from 1 to 3 represent the accessory to the corresponding state. The character '.' corresponds to the cell where it is allowed to build a road and the character '#' means no construction is allowed in this cell.
Output
Print a single integer β the minimum number of cells you need to build a road inside in order to connect all the cells of all states. If such a goal is unachievable, print -1.
Examples
Input
4 5
11..2
#..22
#.323
.#333
Output
2
Input
1 5
1#2#3
Output
-1
Submitted Solution:
```
# lista doble enlazada o(1) operaciones en los bordes es mejor que si se implementa en el propio lenguaje
from collections import deque
n, m = input().split()
n = int(n)
m = int(m)
def idx(i, j):
return i*n +j
max = n*m*2
graph = ""
virtDistance = [[], [], []]
virtNodesStart = [deque(), deque(), deque()]
virtNodesDst = [max, max, max]
code = ord("1")
for i in range(0, n):
s = input()
graph += s
for j in range(0, m):
virtDistance[0].append(max)
virtDistance[1].append(max)
virtDistance[2].append(max)
indx = ord(s[j])-code
if 0 > indx or indx > 2:
continue
virtNodesStart[indx].append((i, j))
i2 = idx(i,j)
virtDistance[indx][-1]=0
def bfs(queue, distance):
while queue:
pi, pj = queue.popleft()
for i, j in [(pi, pj-1), (pi, pj+1), (pi-1, pj), (pi+1, pj)]:
indx =idx(i, j)
if 0 > i or i >= n or 0 > j or j >= m or graph[indx] == '#':
continue
isRoad = graph[indx] == "."
newDistance = distance[idx(pi, pj)] + (1 if isRoad else 0)
if distance[indx] > newDistance: # relax
distance[indx] = newDistance
if isRoad:
queue.append((i, j))
else:
dstidx = ord(graph[indx]) -code
virtNodesDst[dstidx] = min(virtNodesDst[dstidx], newDistance)
queue.appendleft((i, j))
bfs(virtNodesStart[0], virtDistance[0])
bfs(virtNodesStart[1], virtDistance[1])
bfs(virtNodesStart[2], virtDistance[2])
if virtNodesDst[0] == max or virtNodesDst[1] == max or virtNodesDst[2] == max:
print(-1)
else:
print(virtNodesDst[0] + virtNodesDst[1] + virtNodesDst[2])
```
No
| 102,489 |
Provide tags and a correct Python 3 solution for this coding contest problem.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
Tags: implementation, math
Correct Solution:
```
from collections import *
from itertools import *
from random import *
from bisect import *
from string import *
from queue import *
from heapq import *
from math import *
from re import *
from sys import *
def fast(): return stdin.readline().strip()
def zzz(): return [int(i) for i in fast().split()]
z, zz = input, lambda: list(map(int, z().split()))
szz, graph, mod, szzz = lambda: sorted(
zz()), {}, 10**9 + 7, lambda: sorted(zzz())
def lcd(xnum1, xnum2): return (xnum1 * xnum2 // gcd(xnum1, xnum2))
def output(answer): stdout.write(str(answer))
dx = [-1, 1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, 1, -1, 1, -1, -1, 1]
###########################---Test-Case---#################################
"""
If you Know me , Then you probably don't know me !
"""
###########################---START-CODING---##############################
# n, m = zzz()
# for _ in range(m):
# x, y, w = zzz()
# try:
# graph[x]
# except:
# graph[x] = []
# try:
# graph[y]
# except:
# graph[y] = []
# graph[x].append((y, w))
# graph[y].append((x, w))
# path = [0] * (n + 1)
# dis = [float('inf')] * (n + 1)
# hp = [(0, 1)]
# while hp:
# try:
# dcur, cur = heappop(hp)
# print(hp)
# for d, w in graph[cur]:
# if dcur + w < dis[d]:
# dis[d] = dcur + w
# path[d] = cur
# heappush(hp, (dis[d], d))
# print(hp)
# except:
# exit(print(-1))
# l = [n]
# x = n
# print(path)
# print(dis)
# if path[n] > 0:
# while x != 1:
# x = path[x]
# l.append(x)
# print(*l[::-1])
# else:
# print(-1)
# #
# root = {}
# def build(string, index):
# node = root
# for letter in string:
# if letter not in node:
# node[letter] = {}
# node = node[letter]
# node['index'] = index
# def contains(string):
# node = root
# for letter in string:
# if letter not in node:
# return False
# node = node[letter]
# return node['index']
# n, l = zzz()
# s = fast() * 2
# q = int(fast())
# for i in range(q):
# build(input(), i + 1)
# pos = False
# ans = [0] * n
# for i in range(l):
# pos = True
# found = [False] * (q + 1)
# for j in range(n):
# loc = contains(s[i + j * l: i + (j + 1) * l])
# if not loc or found[loc]:
# pos = False
# break
# found[loc] = True
# ans[j] = loc
# if pos:
# break
# if not pos:
# print("NO")
# else:
# print("YES")
# # print(' '.join([str(x) for x in ans]))
# for i in ans:
# print(i)
# num = int(z())
# for _ in range(num):
# a, b = zzz()
# arr = zzz()
# for i in arr:
# while 0 < i < b * 10 and i % b:
# i -= 10
# if i < b:
# print('NO')
# else:
# print('YES', i)
# num = int(z())
# def has(x, d):
# return str(x).count((str(d))) > 0
# for _ in range(num):
# arr = zzz()
# dp = [0] * (1005)
# dp[0] = 1
# for i in range(1, 1002):
# if has(i, d):
# for j in range(0, 1003 - i):
# if dp[j] > 0:
# dp[i + j] = 1
# for i in arr:
# if i > 1000 or dp[x]:
# print('YES')
# else:
# print('NO')
# n, m = zzz()
# arr = list(fast() + '***')
# k, res = 0, []
# for i in range(n):
# if arr[i] == arr[i + 1] == '.':
# k += 1
# for i in range(m):
# x, y = fast().split(' ')
# x = int(x) - 1
# if arr[x] == '.':
# if y != '.':
# if x > 0 and arr[x - 1] == '.':
# k -= 1
# if x < n - 1 and arr[x + 1] == '.':
# k -= 1
# else:
# if y == '.':
# if x > 0 and arr[x - 1] == '.':
# k += 1
# if x < n - 1 and arr[x + 1] == '.':
# k += 1
# print(k)
# arr[x] = y
n = int(fast())
arr = zzz()
lst = []
for i in range(n):
lst.append((arr[i], i))
lst = sorted(lst)
ans = 0
for i in range(n - 1):
ans += abs(lst[i][1] - lst[i + 1][1])
print(ans)
```
| 102,490 |
Provide tags and a correct Python 3 solution for this coding contest problem.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
Tags: implementation, math
Correct Solution:
```
n=int(input())
a=[];v=[];o=0
a=list(map(int,input().split()))
for i in range(0,n+1):
v.append(0)
for i in range(n):
v[a[i]]=i+1
for i in range(1,n):
o+=abs(v[i]-v[i+1])
print(o)
```
| 102,491 |
Provide tags and a correct Python 3 solution for this coding contest problem.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
Tags: implementation, math
Correct Solution:
```
n=int(input())
k=0
a=list(map(int,input().split()))
b=[0]*1000000
for i in range(n):
b[a[i]-1]=i
for i in range(n-1):
k+=abs(b[i]-b[i+1])
print(k)
```
| 102,492 |
Provide tags and a correct Python 3 solution for this coding contest problem.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
Tags: implementation, math
Correct Solution:
```
n= int(input())
arr= list(map(int,input().split()))
map={}
for i in range(n):
map[arr[i]]=i+1
ans=0
for i in range(1,n):
ans+=abs(map[i]-map[i+1])
print (ans)
```
| 102,493 |
Provide tags and a correct Python 3 solution for this coding contest problem.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
Tags: implementation, math
Correct Solution:
```
R = lambda : map(int, input().split())
n = int(input())
v = list(R())
d = {}
for i in range(n):
d[v[i]] = i
c = 0
for i in range(2,n+1):
c += abs(d[i]-d[i-1])
print(c)
```
| 102,494 |
Provide tags and a correct Python 3 solution for this coding contest problem.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
Tags: implementation, math
Correct Solution:
```
n = int(input())
L = list(map(int,input().split()))
A = []
for i in range(n):
A.append([L[i],i])
A.sort()
cnt = 0
for i in range(1,n):
cnt += abs(A[i][1] - A[i-1][1])
print(cnt)
```
| 102,495 |
Provide tags and a correct Python 3 solution for this coding contest problem.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
Tags: implementation, math
Correct Solution:
```
def hdd(n, lst):
res, answer = [0] * n, 0
for i in range(n):
res[lst[i] - 1] = i
for i in range(n - 1):
answer += abs(res[i] - res[i + 1])
return answer
m = int(input())
a = [int(j) for j in input().split()]
print(hdd(m, a))
```
| 102,496 |
Provide tags and a correct Python 3 solution for this coding contest problem.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
Tags: implementation, math
Correct Solution:
```
n=int(input())
ls=list(map(int,input().split()))
arr=[0]*n
for x in range(n):
arr[ls[x]-1]=x
su=0
for x in range(1,n):
su+=abs(arr[x]-arr[x-1])
print(su)
```
| 102,497 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
Submitted Solution:
```
n = int(input())
pos = [0] * (n+1)
for idx, num in enumerate(map(int, input().split())):
pos[num] = idx
count = 0
for a, b in zip(pos[1:], pos[2:]):
count += abs(a-b)
print(count)
```
Yes
| 102,498 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.
Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 β€ fi β€ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.
It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.
Input
The first line contains a positive integer n (1 β€ n β€ 2Β·105) β the number of fragments.
The second line contains n different integers fi (1 β€ fi β€ n) β the number of the fragment written in the i-th sector.
Output
Print the only integer β the number of time units needed to read the file.
Examples
Input
3
3 1 2
Output
3
Input
5
1 3 5 4 2
Output
10
Note
In the second example the head moves in the following way:
* 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units
* 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units
* 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units
* 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units
So the answer to the second example is 4 + 3 + 2 + 1 = 10.
Submitted Solution:
```
n=int(input());a=list(map(int,input().split()));p=0
i=0;x={}
while i<n:x[a[i]]=i;i+=1
while n>1:p=p+abs(x[n]-x[n-1]);n-=1
print(p)
```
Yes
| 102,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.