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.
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a seconds to swipe from photo to adjacent.
For each photo it is known which orientation is intended for it β horizontal or vertical. Phone is in the vertical orientation and can't be rotated. It takes b second to change orientation of the photo.
Vasya has T seconds to watch photos. He want to watch as many photos as possible. If Vasya opens the photo for the first time, he spends 1 second to notice all details in it. If photo is in the wrong orientation, he spends b seconds on rotating it before watching it. If Vasya has already opened the photo, he just skips it (so he doesn't spend any time for watching it or for changing its orientation). It is not allowed to skip unseen photos.
Help Vasya find the maximum number of photos he is able to watch during T seconds.
Input
The first line of the input contains 4 integers n, a, b, T (1 β€ n β€ 5Β·105, 1 β€ a, b β€ 1000, 1 β€ T β€ 109) β the number of photos, time to move from a photo to adjacent, time to change orientation of a photo and time Vasya can spend for watching photo.
Second line of the input contains a string of length n containing symbols 'w' and 'h'.
If the i-th position of a string contains 'w', then the photo i should be seen in the horizontal orientation.
If the i-th position of a string contains 'h', then the photo i should be seen in vertical orientation.
Output
Output the only integer, the maximum number of photos Vasya is able to watch during those T seconds.
Examples
Input
4 2 3 10
wwhw
Output
2
Input
5 2 4 13
hhwhh
Output
4
Input
5 2 4 1000
hhwhh
Output
5
Input
3 1 100 10
whw
Output
0
Note
In the first sample test you can rotate the first photo (3 seconds), watch the first photo (1 seconds), move left (2 second), rotate fourth photo (3 seconds), watch fourth photo (1 second). The whole process takes exactly 10 seconds.
Note that in the last sample test the time is not enough even to watch the first photo, also you can't skip it.
Submitted Solution:
```
#! /usr/bin/env python3
def main():
# n, a, b, t = map(int, input().split())
# oris = input()
s1 = "5 2 4 1000"
s2 = "hhwhh"
n, a, b, t = map(int, s1.split())
oris = s2
def get_time(front, rear, count_rot):
span = front - rear
offset = min(front, -rear)
return span, span * a + (span + 1) + offset * a + count_rot * b
front = rear = span = count_rot = new_count_rot = time = 0
has_one = False
for i in range(0, -n, -1):
if oris[i] == 'w':
new_count_rot += 1
new_span, new_time = get_time(front, i, new_count_rot)
if new_time > t:
break
has_one = True
span, time, rear, count_rot = new_span, new_time, i, new_count_rot
if not has_one:
return 0
maxi = max_span = n - 1
while front < maxi and rear <= 0 and span != max_span:
front += 1
if oris[front] == 'w':
count_rot += 1
while True:
new_span, time = get_time(front, rear, count_rot)
if time <= t:
break
if oris[rear] == 'w':
count_rot -= 1
rear += 1
if rear > 0:
return span + 1
span = max(new_span, span)
return span + 1
print(main())
```
No
| 1,300 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.
Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:
1. If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.
2. Processor smashes k centimeters of potato (or just everything that is inside).
Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.
Input
The first line of the input contains integers n, h and k (1 β€ n β€ 100 000, 1 β€ k β€ h β€ 109) β the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively.
The second line contains n integers ai (1 β€ ai β€ h) β the heights of the pieces.
Output
Print a single integer β the number of seconds required to smash all the potatoes following the process described in the problem statement.
Examples
Input
5 6 3
5 4 3 2 1
Output
5
Input
5 6 3
5 5 5 5 5
Output
10
Input
5 6 3
1 2 1 1 1
Output
2
Note
Consider the first sample.
1. First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.
2. Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.
3. Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.
4. Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.
5. During this second processor finally smashes all the remaining potato and the process finishes.
In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2Β·5 = 10 seconds.
In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.
Tags: implementation, math
Correct Solution:
```
n,h,k = map(int,input().split())
arr = [int(x) for x in input().split()]
ph = 0
second = 0
for i in range(n):
ph += arr[i]
if(i==n-1):
break
d = h-ph
x = arr[i+1]-d
if(x<=0):
continue
plus = 0
if(x%k==0):
plus = int(x/k)
else:
plus = int(x/k)+1
minus = k*plus
ph -= minus
if(ph<0):
ph = 0
second += plus
plus = 0
if(ph%k==0):
plus = int(ph/k)
else:
plus = int(ph/k)+1
second += plus
print(second)
```
| 1,301 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.
Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:
1. If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.
2. Processor smashes k centimeters of potato (or just everything that is inside).
Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.
Input
The first line of the input contains integers n, h and k (1 β€ n β€ 100 000, 1 β€ k β€ h β€ 109) β the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively.
The second line contains n integers ai (1 β€ ai β€ h) β the heights of the pieces.
Output
Print a single integer β the number of seconds required to smash all the potatoes following the process described in the problem statement.
Examples
Input
5 6 3
5 4 3 2 1
Output
5
Input
5 6 3
5 5 5 5 5
Output
10
Input
5 6 3
1 2 1 1 1
Output
2
Note
Consider the first sample.
1. First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.
2. Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.
3. Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.
4. Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.
5. During this second processor finally smashes all the remaining potato and the process finishes.
In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2Β·5 = 10 seconds.
In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.
Tags: implementation, math
Correct Solution:
```
d=input().split()
d=[int(x) for x in d]
n,h,k=d[0],d[1],d[2]
d=input().split()
d=[int(x) for x in d]
S=0
R=0
for i in d:
if R+i<=h:
S+=i//k
R+=i%k
else:
while R+i>h:
if R%k==0:
S+=R//k
R=0
elif R<k:
S+=1
R=0
else:
S+=R//k
R=R%k
S+=i//k
R+=i%k
if R%k==0:
S+=R//k
else:
S+=R//k
S+=1
print(S)
```
| 1,302 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.
Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:
1. If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.
2. Processor smashes k centimeters of potato (or just everything that is inside).
Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.
Input
The first line of the input contains integers n, h and k (1 β€ n β€ 100 000, 1 β€ k β€ h β€ 109) β the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively.
The second line contains n integers ai (1 β€ ai β€ h) β the heights of the pieces.
Output
Print a single integer β the number of seconds required to smash all the potatoes following the process described in the problem statement.
Examples
Input
5 6 3
5 4 3 2 1
Output
5
Input
5 6 3
5 5 5 5 5
Output
10
Input
5 6 3
1 2 1 1 1
Output
2
Note
Consider the first sample.
1. First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.
2. Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.
3. Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.
4. Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.
5. During this second processor finally smashes all the remaining potato and the process finishes.
In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2Β·5 = 10 seconds.
In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.
Tags: implementation, math
Correct Solution:
```
n,h,k=map(int,input().split())
ip=list(map(int,input().split()))
time=0
count=0
height=0
while count<n:
if height + ip[count]<= h:
height+=ip[count]
count+=1
else:
if height%k==0:
time+=height//k
height=0
elif height>=k:
time+=height//k
height=height%k
else:
height-=min(k,height)
time+=1
#print(height,time,count)
if height==0:
s=0
elif height%k==0:
s=height//k
else:
s=(height//k)+1
print(time+s)
```
| 1,303 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.
Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:
1. If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.
2. Processor smashes k centimeters of potato (or just everything that is inside).
Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.
Input
The first line of the input contains integers n, h and k (1 β€ n β€ 100 000, 1 β€ k β€ h β€ 109) β the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively.
The second line contains n integers ai (1 β€ ai β€ h) β the heights of the pieces.
Output
Print a single integer β the number of seconds required to smash all the potatoes following the process described in the problem statement.
Examples
Input
5 6 3
5 4 3 2 1
Output
5
Input
5 6 3
5 5 5 5 5
Output
10
Input
5 6 3
1 2 1 1 1
Output
2
Note
Consider the first sample.
1. First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.
2. Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.
3. Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.
4. Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.
5. During this second processor finally smashes all the remaining potato and the process finishes.
In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2Β·5 = 10 seconds.
In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.
Tags: implementation, math
Correct Solution:
```
from math import ceil
n, h, k = map(int, input().strip().split())
potatoes = map(int, input().strip().split())
sec = 0
in_progress = 0
for p in potatoes:
while p + in_progress > h:
if in_progress < k:
sec += 1
in_progress = 0
else:
elapsed, in_progress = divmod(in_progress, k)
sec += elapsed
in_progress += p
sec += ceil(in_progress/k)
print(sec)
```
| 1,304 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.
Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:
1. If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.
2. Processor smashes k centimeters of potato (or just everything that is inside).
Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.
Input
The first line of the input contains integers n, h and k (1 β€ n β€ 100 000, 1 β€ k β€ h β€ 109) β the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively.
The second line contains n integers ai (1 β€ ai β€ h) β the heights of the pieces.
Output
Print a single integer β the number of seconds required to smash all the potatoes following the process described in the problem statement.
Examples
Input
5 6 3
5 4 3 2 1
Output
5
Input
5 6 3
5 5 5 5 5
Output
10
Input
5 6 3
1 2 1 1 1
Output
2
Note
Consider the first sample.
1. First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.
2. Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.
3. Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.
4. Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.
5. During this second processor finally smashes all the remaining potato and the process finishes.
In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2Β·5 = 10 seconds.
In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.
Tags: implementation, math
Correct Solution:
```
n, mxH, k = map(int, input().split())
arr = list(map(int, input().split()))
currT, currH, res = 0, 0, 0
i = 0
while i < len(arr):
while (i < len(arr)) and (currH + arr[i] <= mxH):
currH += arr[i]
i += 1
if i < len(arr):
currT = (currH + arr[i] - mxH + k - 1) // k
else:
currT = (currH + k - 1) // k
currH = max(currH - currT * k, 0)
res += currT
print(res)
```
| 1,305 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.
Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:
1. If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.
2. Processor smashes k centimeters of potato (or just everything that is inside).
Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.
Input
The first line of the input contains integers n, h and k (1 β€ n β€ 100 000, 1 β€ k β€ h β€ 109) β the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively.
The second line contains n integers ai (1 β€ ai β€ h) β the heights of the pieces.
Output
Print a single integer β the number of seconds required to smash all the potatoes following the process described in the problem statement.
Examples
Input
5 6 3
5 4 3 2 1
Output
5
Input
5 6 3
5 5 5 5 5
Output
10
Input
5 6 3
1 2 1 1 1
Output
2
Note
Consider the first sample.
1. First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.
2. Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.
3. Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.
4. Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.
5. During this second processor finally smashes all the remaining potato and the process finishes.
In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2Β·5 = 10 seconds.
In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.
Tags: implementation, math
Correct Solution:
```
n, h, k = map(int,input().split())
t, x = 0, 0
w=list(map(int,input().split()))
for z in w:
t += x // k; x %= k
if x + z > h: t, x = t + 1, 0
x += z
t+=(x+k-1)//k
print(t)
```
| 1,306 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.
Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:
1. If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.
2. Processor smashes k centimeters of potato (or just everything that is inside).
Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.
Input
The first line of the input contains integers n, h and k (1 β€ n β€ 100 000, 1 β€ k β€ h β€ 109) β the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively.
The second line contains n integers ai (1 β€ ai β€ h) β the heights of the pieces.
Output
Print a single integer β the number of seconds required to smash all the potatoes following the process described in the problem statement.
Examples
Input
5 6 3
5 4 3 2 1
Output
5
Input
5 6 3
5 5 5 5 5
Output
10
Input
5 6 3
1 2 1 1 1
Output
2
Note
Consider the first sample.
1. First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.
2. Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.
3. Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.
4. Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.
5. During this second processor finally smashes all the remaining potato and the process finishes.
In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2Β·5 = 10 seconds.
In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.
Tags: implementation, math
Correct Solution:
```
import math
if __name__ == '__main__':
n, h, k = map(int, input().split())
heights = list(map(int, input().split()))
time = 0
r = 0
i = 0
while i < n:
while i < n and h - r >= heights[i]:
r += heights[i]
i += 1
if i < n:
a = math.ceil((heights[i] - (h - r)) / k)
r -= a * k
time += a
if r < 0:
r = 0
time += math.ceil(r / k)
print(time)
```
| 1,307 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.
Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:
1. If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.
2. Processor smashes k centimeters of potato (or just everything that is inside).
Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.
Input
The first line of the input contains integers n, h and k (1 β€ n β€ 100 000, 1 β€ k β€ h β€ 109) β the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively.
The second line contains n integers ai (1 β€ ai β€ h) β the heights of the pieces.
Output
Print a single integer β the number of seconds required to smash all the potatoes following the process described in the problem statement.
Examples
Input
5 6 3
5 4 3 2 1
Output
5
Input
5 6 3
5 5 5 5 5
Output
10
Input
5 6 3
1 2 1 1 1
Output
2
Note
Consider the first sample.
1. First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.
2. Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.
3. Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.
4. Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.
5. During this second processor finally smashes all the remaining potato and the process finishes.
In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2Β·5 = 10 seconds.
In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.
Tags: implementation, math
Correct Solution:
```
######### ## ## ## #### ##### ## # ## # ##
# # # # # # # # # # # # # # # # # # #
# # # # ### # # # # # # # # # # # #
# ##### # # # # ### # # # # # # # # #####
# # # # # # # # # # # # # # # # # #
######### # # # # ##### # ##### # ## # ## # #
"""
PPPPPPP RRRRRRR OOOO VV VV EEEEEEEEEE
PPPPPPPP RRRRRRRR OOOOOO VV VV EE
PPPPPPPPP RRRRRRRRR OOOOOOOO VV VV EE
PPPPPPPP RRRRRRRR OOOOOOOO VV VV EEEEEE
PPPPPPP RRRRRRR OOOOOOOO VV VV EEEEEEE
PP RRRR OOOOOOOO VV VV EEEEEE
PP RR RR OOOOOOOO VV VV EE
PP RR RR OOOOOO VV VV EE
PP RR RR OOOO VVVV EEEEEEEEEE
"""
"""
Perfection is achieved not when there is nothing more to add, but rather when there is nothing more to take away.
"""
import sys
input = sys.stdin.readline
# from bisect import bisect_left as lower_bound;
# from bisect import bisect_right as upper_bound;
# from math import ceil, factorial;
def ceil(x):
if x != int(x):
x = int(x) + 1
return x
def factorial(x, m):
val = 1
while x>0:
val = (val * x) % m
x -= 1
return val
def fact(x):
val = 1
while x > 0:
val *= x
x -= 1
return val
# 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 b == 0:
return a;
return gcd(b, a % b);
## nCr function efficient using Binomial Cofficient
def nCr(n, k):
if k > n:
return 0
if(k > n - k):
k = n - k
res = 1
for i in range(k):
res = res * (n - i)
res = res / (i + 1)
return int(res)
## upper bound function code -- such that e in a[:i] e < x;
def upper_bound(a, x, lo=0, hi = None):
if hi == None:
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 and n > 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 and n > 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 with path compression included (recursive)
# def find(x, link):
# if link[x] == x:
# return x
# link[x] = find(link[x], link);
# return link[x];
# find function with path compression (ITERATIVE)
def find(x, link):
p = x;
while( p != link[p]):
p = link[p];
while( x != p):
nex = link[x];
link[x] = p;
x = nex;
return p;
# 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)]
prime[0], prime[1] = False, False
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(1e5 + 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):
res = []
for i in range(2, int(x ** 0.5) + 1):
while x % i == 0:
res.append(i)
x //= i
if x != 1:
res.append(x)
return res
## 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()));
def float_array():
return list(map(float, 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 ---------------- ###################
from itertools import permutations
import math
from bisect import bisect_left
def solve():
n, h, k = map(int, input().split())
a = list(map(int, input().split()))
c = 0
summ = 0
waste = 0
for x in a:
summ += c // k
c %= k
if c + x > h:
summ, c = summ + 1, 0
c += x
print(summ + math.ceil(c / k))
if __name__ == '__main__':
for _ in range(1):
solve()
# fin_time = datetime.now()
# print("Execution time (for loop): ", (fin_time-init_time))
```
| 1,308 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.
Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:
1. If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.
2. Processor smashes k centimeters of potato (or just everything that is inside).
Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.
Input
The first line of the input contains integers n, h and k (1 β€ n β€ 100 000, 1 β€ k β€ h β€ 109) β the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively.
The second line contains n integers ai (1 β€ ai β€ h) β the heights of the pieces.
Output
Print a single integer β the number of seconds required to smash all the potatoes following the process described in the problem statement.
Examples
Input
5 6 3
5 4 3 2 1
Output
5
Input
5 6 3
5 5 5 5 5
Output
10
Input
5 6 3
1 2 1 1 1
Output
2
Note
Consider the first sample.
1. First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.
2. Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.
3. Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.
4. Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.
5. During this second processor finally smashes all the remaining potato and the process finishes.
In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2Β·5 = 10 seconds.
In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.
Submitted Solution:
```
n, h, j = map(int, input().split())
pots = [int(x) for x in input().split()]
count = 0
height = 0
pot = 0
while pot < n:
if height + pots[pot] <= h:
height += pots[pot]
count += height // j
height = height % j
pot += 1
elif height <= j:
height = 0
count += 1
else:
count += height // j
height = height % j
if height > 0:
print(count +1)
else:
print(count)
```
Yes
| 1,309 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.
Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:
1. If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.
2. Processor smashes k centimeters of potato (or just everything that is inside).
Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.
Input
The first line of the input contains integers n, h and k (1 β€ n β€ 100 000, 1 β€ k β€ h β€ 109) β the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively.
The second line contains n integers ai (1 β€ ai β€ h) β the heights of the pieces.
Output
Print a single integer β the number of seconds required to smash all the potatoes following the process described in the problem statement.
Examples
Input
5 6 3
5 4 3 2 1
Output
5
Input
5 6 3
5 5 5 5 5
Output
10
Input
5 6 3
1 2 1 1 1
Output
2
Note
Consider the first sample.
1. First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.
2. Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.
3. Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.
4. Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.
5. During this second processor finally smashes all the remaining potato and the process finishes.
In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2Β·5 = 10 seconds.
In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.
Submitted Solution:
```
import sys
n, h, k = map(int, sys.stdin.readline().split())
an = list(map(int, sys.stdin.readline().split()))
ans = 0
cur = 0
height = 0
while cur < n:
if height + an[cur] <= h:
height += an[cur]
else:
ans += 1
height = an[cur]
ans += height // k
height %= k
cur += 1
if cur == n and height != 0:
ans += 1
print(ans)
```
Yes
| 1,310 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.
Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:
1. If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.
2. Processor smashes k centimeters of potato (or just everything that is inside).
Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.
Input
The first line of the input contains integers n, h and k (1 β€ n β€ 100 000, 1 β€ k β€ h β€ 109) β the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively.
The second line contains n integers ai (1 β€ ai β€ h) β the heights of the pieces.
Output
Print a single integer β the number of seconds required to smash all the potatoes following the process described in the problem statement.
Examples
Input
5 6 3
5 4 3 2 1
Output
5
Input
5 6 3
5 5 5 5 5
Output
10
Input
5 6 3
1 2 1 1 1
Output
2
Note
Consider the first sample.
1. First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.
2. Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.
3. Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.
4. Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.
5. During this second processor finally smashes all the remaining potato and the process finishes.
In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2Β·5 = 10 seconds.
In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.
Submitted Solution:
```
n,h,k=map(int,input().split())
xs=list(map(int,input().split()))+[h+1]
t=0
x=0
i=0
while i+1<len(xs) or x>0:
while x+xs[i]<=h:
x+=xs[i]
i+=1
d=max(1,min(x,x-h+xs[i]+k-1)//k)
x=max(0,x-d*k)
t+=d
print(t)
```
Yes
| 1,311 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.
Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:
1. If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.
2. Processor smashes k centimeters of potato (or just everything that is inside).
Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.
Input
The first line of the input contains integers n, h and k (1 β€ n β€ 100 000, 1 β€ k β€ h β€ 109) β the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively.
The second line contains n integers ai (1 β€ ai β€ h) β the heights of the pieces.
Output
Print a single integer β the number of seconds required to smash all the potatoes following the process described in the problem statement.
Examples
Input
5 6 3
5 4 3 2 1
Output
5
Input
5 6 3
5 5 5 5 5
Output
10
Input
5 6 3
1 2 1 1 1
Output
2
Note
Consider the first sample.
1. First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.
2. Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.
3. Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.
4. Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.
5. During this second processor finally smashes all the remaining potato and the process finishes.
In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2Β·5 = 10 seconds.
In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.
Submitted Solution:
```
# 677B
# ΞΈ(n) time
# ΞΈ(n) space
__author__ = 'artyom'
# SOLUTION
def main():
n, h, k = read(3)
a = read(3)
c = i = d = 0
while i < n:
while i < n and d + a[i] <= h:
d += a[i]
i += 1
x = a[i] - h + d if i < n else d
t = (x - 1) // k + 1
d = max(0, d - t * k)
c += t
return c
# HELPERS
def read(mode=1, size=None):
# 0: String
# 1: Integer
# 2: List of strings
# 3: List of integers
# 4: Matrix of integers
if mode == 0: return input().strip()
if mode == 1: return int(input().strip())
if mode == 2: return input().strip().split()
if mode == 3: return list(map(int, input().strip().split()))
a = []
for _ in range(size):
a.append(read(3))
return a
def write(s="\n"):
if s is None: s = ''
if isinstance(s, tuple) or isinstance(s, list): s = ' '.join(map(str, s))
s = str(s)
print(s, end="\n")
write(main())
```
Yes
| 1,312 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.
Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:
1. If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.
2. Processor smashes k centimeters of potato (or just everything that is inside).
Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.
Input
The first line of the input contains integers n, h and k (1 β€ n β€ 100 000, 1 β€ k β€ h β€ 109) β the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively.
The second line contains n integers ai (1 β€ ai β€ h) β the heights of the pieces.
Output
Print a single integer β the number of seconds required to smash all the potatoes following the process described in the problem statement.
Examples
Input
5 6 3
5 4 3 2 1
Output
5
Input
5 6 3
5 5 5 5 5
Output
10
Input
5 6 3
1 2 1 1 1
Output
2
Note
Consider the first sample.
1. First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.
2. Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.
3. Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.
4. Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.
5. During this second processor finally smashes all the remaining potato and the process finishes.
In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2Β·5 = 10 seconds.
In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.
Submitted Solution:
```
import sys
n, h, k = map(int,sys.stdin.readline().split())
papa = input()
#n, h, k = map(int,"5 6 3".split())
#papa = "5 4 3 2 1"
#papa = "5 5 5 5 5"
#papa = "1 2 1 1 1"
papa = papa.split(' ')
papa = [int(i) for i in papa]
papa.append(2 * k)
print (n, h, k, papa)
sec = 0
food = 0
while len(papa) > 1:# and food > 0:
#print (n, h, k, food, sec, papa)
while food + papa[0] <= h:
food += papa[0]
del papa[0]
food -= k
if food < 0:
food = 0
sec += 1
#print (food, sec)
while food > 0:
food -= k
if food < 0:
food = 0
sec += 1
print (sec)
```
No
| 1,313 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.
Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:
1. If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.
2. Processor smashes k centimeters of potato (or just everything that is inside).
Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.
Input
The first line of the input contains integers n, h and k (1 β€ n β€ 100 000, 1 β€ k β€ h β€ 109) β the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively.
The second line contains n integers ai (1 β€ ai β€ h) β the heights of the pieces.
Output
Print a single integer β the number of seconds required to smash all the potatoes following the process described in the problem statement.
Examples
Input
5 6 3
5 4 3 2 1
Output
5
Input
5 6 3
5 5 5 5 5
Output
10
Input
5 6 3
1 2 1 1 1
Output
2
Note
Consider the first sample.
1. First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.
2. Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.
3. Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.
4. Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.
5. During this second processor finally smashes all the remaining potato and the process finishes.
In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2Β·5 = 10 seconds.
In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.
Submitted Solution:
```
n, h, k = list(map(int, input().split()))
a = list(reversed(sorted(list(map(int, input().split())))))
out = 0
cur = 0
while len(a) > 0:
tmp = cur
i = 0
while i < len(a):
if tmp + a[i] <= h:
tmp+=a[i]
del(a[i])
i-=1
i+=1
cur = tmp
if cur < k:
cur = 0
else:
cur-=k
out+=1
print(out+1)
```
No
| 1,314 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.
Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:
1. If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.
2. Processor smashes k centimeters of potato (or just everything that is inside).
Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.
Input
The first line of the input contains integers n, h and k (1 β€ n β€ 100 000, 1 β€ k β€ h β€ 109) β the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively.
The second line contains n integers ai (1 β€ ai β€ h) β the heights of the pieces.
Output
Print a single integer β the number of seconds required to smash all the potatoes following the process described in the problem statement.
Examples
Input
5 6 3
5 4 3 2 1
Output
5
Input
5 6 3
5 5 5 5 5
Output
10
Input
5 6 3
1 2 1 1 1
Output
2
Note
Consider the first sample.
1. First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.
2. Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.
3. Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.
4. Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.
5. During this second processor finally smashes all the remaining potato and the process finishes.
In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2Β·5 = 10 seconds.
In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.
Submitted Solution:
```
n,h,k = [int(x) for x in input().split(' ')]
ai = [int(x) for x in input().split(' ')]
time = 0
i = 0
r = 0
while i < n:
if r + ai[i] > h:
p = ai[i]-h+r
rr = p // k
if p % k != 0: rr += 1
r -= rr * k
if r < 0: r = 0
time += rr
while True:
if i >= n: break
if r + ai[i] > h: break
r += ai[i]
i += 1
r -= k
time += 1
#print(time)
if r > 0:
p = r // k
if r % k != 0: p += 1
time += p
print(r)
print(time)
```
No
| 1,315 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.
Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:
1. If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.
2. Processor smashes k centimeters of potato (or just everything that is inside).
Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.
Input
The first line of the input contains integers n, h and k (1 β€ n β€ 100 000, 1 β€ k β€ h β€ 109) β the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively.
The second line contains n integers ai (1 β€ ai β€ h) β the heights of the pieces.
Output
Print a single integer β the number of seconds required to smash all the potatoes following the process described in the problem statement.
Examples
Input
5 6 3
5 4 3 2 1
Output
5
Input
5 6 3
5 5 5 5 5
Output
10
Input
5 6 3
1 2 1 1 1
Output
2
Note
Consider the first sample.
1. First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.
2. Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.
3. Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.
4. Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.
5. During this second processor finally smashes all the remaining potato and the process finishes.
In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2Β·5 = 10 seconds.
In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.
Submitted Solution:
```
[x,y,z]=list(map(int,input().split()))
l=list(map(int,input().split()))
s=0
p=sum(l)
if p%z==0:
s=p//z
else:
for a in l:
if a>z:
s+=2
else:
s+=1
print(s)
```
No
| 1,316 |
Provide tags and a correct Python 3 solution for this coding contest problem.
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.
The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The Β«periodΒ» character (Β«.Β») stands for an empty cell.
Input
The first line contains two separated by a space integer numbers n, m (1 β€ n, m β€ 100) β the length and the width of the office-room, and c character β the President's desk colour. The following n lines contain m characters each β the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.
Output
Print the only number β the amount of President's deputies.
Examples
Input
3 4 R
G.B.
.RR.
TTT.
Output
2
Input
3 3 Z
...
.H.
..Z
Output
0
Tags: implementation
Correct Solution:
```
n , m , p = input().strip().split(' ')
n , m = int(n), int(m)
M = [[None for _ in range(m)] for _ in range(n)]
for i in range(n):
s = input().strip()
for j in range(m):
M[i][j] = s[j]
T = [[False for _ in range(m)] for _ in range(n)]
for i in range(n):
for j in range(m):
if M[i][j] == p:
a , b , c , d , e , f , g , h = i , j - 1 , i , j + 1 , i - 1 , j , i + 1 , j
if 0 <= a < n and 0 <= b < m:
T[a][b] = True
if 0 <= c < n and 0 <= d < m:
T[c][d] = True
if 0 <= e < n and 0 <= f < m:
T[e][f] = True
if 0 <= g < n and 0 <= h < m:
T[g][h] = True
ans = 0
x = [False for _ in range(26)]
for i in range(n):
for j in range(m):
c = M[i][j]
if c != '.' and c != p:
if T[i][j] == True and x[ord(c)- ord('A')] == False:
x[ord(c)-ord('A')] = True
ans += 1
print(ans)
```
| 1,317 |
Provide tags and a correct Python 3 solution for this coding contest problem.
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.
The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The Β«periodΒ» character (Β«.Β») stands for an empty cell.
Input
The first line contains two separated by a space integer numbers n, m (1 β€ n, m β€ 100) β the length and the width of the office-room, and c character β the President's desk colour. The following n lines contain m characters each β the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.
Output
Print the only number β the amount of President's deputies.
Examples
Input
3 4 R
G.B.
.RR.
TTT.
Output
2
Input
3 3 Z
...
.H.
..Z
Output
0
Tags: implementation
Correct Solution:
```
t=list(map(str,input().split()))
a=[]
for _ in range(int(t[0])):
a.append(input())
r=[]
#print(a)
n=int(t[0])
m=int(t[1])
for i in range(n-1):
for j in range(m-1):
if a[i][j]!='.' and a[i][j+1]==t[2] and a[i][j]!=t[2]:
r.append(a[i][j])
if a[i][j]==t[2] and a[i+1][j]!='.' and a[i+1][j]!=t[2]:
r.append(a[i+1][j])
if a[i][j]==t[2] and a[i][j+1]!=t[2] and a[i][j+1]!='.':
r.append(a[i][j+1])
if a[i][j]!='.' and a[i+1][j]==t[2] and a[i][j]!=t[2]:
r.append(a[i][j])
for i in range(n-1):
if a[i][m-1]==t[2] and a[i+1][m-1]!='.' and a[i+1][m-1]!=t[2]:
r.append(a[i+1][m-1])
if a[i][m-1]!='.' and a[i+1][m-1]==t[2] and a[i][m-1]!=t[2]:
r.append(a[i][m-1])
for i in range(m-1):
if a[n-1][i]==t[2] and a[n-1][i+1]!='.' and a[n-1][i+1]!=t[2]:
r.append(a[n-1][i+1])
if a[n-1][i]!='.' and a[n-1][i+1]==t[2] and a[n-1][i]!=t[2]:
r.append(a[n-1][i])
#print(r)
r=set(r)
print(len(r))
```
| 1,318 |
Provide tags and a correct Python 3 solution for this coding contest problem.
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.
The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The Β«periodΒ» character (Β«.Β») stands for an empty cell.
Input
The first line contains two separated by a space integer numbers n, m (1 β€ n, m β€ 100) β the length and the width of the office-room, and c character β the President's desk colour. The following n lines contain m characters each β the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.
Output
Print the only number β the amount of President's deputies.
Examples
Input
3 4 R
G.B.
.RR.
TTT.
Output
2
Input
3 3 Z
...
.H.
..Z
Output
0
Tags: implementation
Correct Solution:
```
a = input().split()
n = int(a[0])
m = int(a[1])
c = a[2]
k = []
d = []
b = []
for i in range(n):
st = input()
k.append(st)
for i in range(n):
for j in range(m):
if k[i][j] == c:
d.append([i, j])
b.append(c)
for i in range(len(d)):
if d[i][0] != 0:
if k[d[i][0] - 1][d[i][1]] != "." and k[d[i][0] - 1][d[i][1]] not in b:
b.append(k[d[i][0] - 1][d[i][1]])
if d[i][1] != 0:
if k[d[i][0]][d[i][1] - 1] != "." and k[d[i][0]][d[i][1] - 1] not in b:
b.append(k[d[i][0]][d[i][1] - 1])
if d[i][0] != n - 1:
if k[d[i][0] + 1][d[i][1]] != "." and k[d[i][0] + 1][d[i][1]] not in b:
b.append(k[d[i][0] + 1][d[i][1]])
if d[i][1] != m - 1:
if k[d[i][0]][d[i][1] + 1] != "." and k[d[i][0]][d[i][1] + 1] not in b:
b.append(k[d[i][0]][d[i][1] + 1])
print(len(b) - 1)
```
| 1,319 |
Provide tags and a correct Python 3 solution for this coding contest problem.
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.
The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The Β«periodΒ» character (Β«.Β») stands for an empty cell.
Input
The first line contains two separated by a space integer numbers n, m (1 β€ n, m β€ 100) β the length and the width of the office-room, and c character β the President's desk colour. The following n lines contain m characters each β the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.
Output
Print the only number β the amount of President's deputies.
Examples
Input
3 4 R
G.B.
.RR.
TTT.
Output
2
Input
3 3 Z
...
.H.
..Z
Output
0
Tags: implementation
Correct Solution:
```
n, m, c = input().split()
n, m = map(int, (n, m))
a = [input() for i in range(n)]
s = set()
d = (0, 1), (1, 0), (0, -1), (-1, 0)
cor = lambda x, y: 0 <= x < n and 0 <= y < m
for i in range(n):
for j in range(m):
if a[i][j] == c:
for dx, dy in d:
ni, nj = i + dx, j + dy
if cor(ni, nj):
s.add(a[ni][nj])
s.discard('.')
s.discard(c)
ans = len(s)
print(ans)
```
| 1,320 |
Provide tags and a correct Python 3 solution for this coding contest problem.
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.
The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The Β«periodΒ» character (Β«.Β») stands for an empty cell.
Input
The first line contains two separated by a space integer numbers n, m (1 β€ n, m β€ 100) β the length and the width of the office-room, and c character β the President's desk colour. The following n lines contain m characters each β the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.
Output
Print the only number β the amount of President's deputies.
Examples
Input
3 4 R
G.B.
.RR.
TTT.
Output
2
Input
3 3 Z
...
.H.
..Z
Output
0
Tags: implementation
Correct Solution:
```
# Fast IO
import sys
input = sys.stdin.readline
def print(x, end='\n'):
sys.stdout.write(str(x) + end)
# IO helpers
def get_int():
return int(input())
def get_list_ints():
return list(map(int, input().split()))
def get_char_list():
s = input()
return list(s[:len(s) - 1])
def get_tuple_ints():
return tuple(map(int, input().split()))
def print_iterable(p):
print(" ".join(map(str, p)))
#Code
def main():
n, m, c = input().split()
n=int(n)
m=int(m)
a=[]
a=[get_char_list() for _ in range(n)]
d=[]
for i in range(n):
for j in range(m):
if a[i][j]==c:
if i!=0:
if a[i-1][j]!=c and a[i-1][j]!='.' and a[i-1][j] not in d:
d+=[a[i-1][j]]
if j!=0:
if a[i][j-1]!=c and a[i][j-1]!='.' and a[i][j-1] not in d:
d+=[a[i][j-1]]
if i!=n-1:
if a[i+1][j]!=c and a[i+1][j]!='.' and a[i+1][j] not in d:
d+=[a[i+1][j]]
if j!=m-1:
if a[i][j+1]!=c and a[i][j+1]!='.' and a[i][j+1] not in d:
d+=[a[i][j+1]]
print(len(d))
if __name__=='__main__':
main()
```
| 1,321 |
Provide tags and a correct Python 3 solution for this coding contest problem.
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.
The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The Β«periodΒ» character (Β«.Β») stands for an empty cell.
Input
The first line contains two separated by a space integer numbers n, m (1 β€ n, m β€ 100) β the length and the width of the office-room, and c character β the President's desk colour. The following n lines contain m characters each β the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.
Output
Print the only number β the amount of President's deputies.
Examples
Input
3 4 R
G.B.
.RR.
TTT.
Output
2
Input
3 3 Z
...
.H.
..Z
Output
0
Tags: implementation
Correct Solution:
```
m, n, c = input().split()
m = int(m)
n = int(n)
a = [[j for j in input()]for i in range(m)]
inxs = list()
con = list()
fin = list()
for i in range(m):
for j in range(n):
if a[i][j] == c:
inxs.append(i)
inxs.append(j)
# if i == 0:
# if j == 0:
# if (a[0][1] != '.') & (a[0][1] != c):
# con += 1
# if (a[1][0] != '.') & (a[1][0] != c):
# con += 1
# if j == n-1:
# if (a[0][n-2] != '.') & (a[0][n-2] != c):
# con += 1
# if (a[1][n-1] != '.') & (a[1][n-1] != c):
# con += 1
# if i == m-1:
# if j == 0:
# if (a[m-1][1] != '.') & (a[m-1][1] != c):
# con += 1
# if (a[m-2][0] != '.') & (a[m-2][0] != c):
# con += 1
# if j == n-1:
# if (a[m-1][n-2] != '.') & (a[m-1][n-2] != c):
# con += 1
# if (a[m-2][n-1] != '.') & (a[m-2][n-1] != c):
# con += 1
for i in range(0, len(inxs), 2):
if inxs[i+1] > 0:
if (a[inxs[i]][inxs[i+1]-1] != c) & (a[inxs[i]][inxs[i+1]-1] != '.'):
con.append(a[inxs[i]][inxs[i+1]-1])
if inxs[i+1] < n-1:
if (a[inxs[i]][inxs[i+1]+1] != c) & (a[inxs[i]][inxs[i+1]+1] != '.'):
con.append(a[inxs[i]][inxs[i+1]+1])
if inxs[i] > 0:
if (a[inxs[i]-1][inxs[i+1]] != c) & (a[inxs[i]-1][inxs[i+1]] != '.'):
con.append(a[inxs[i]-1][inxs[i+1]])
if inxs[i] < m-1:
if (a[inxs[i]+1][inxs[i+1]] != c) & (a[inxs[i]+1][inxs[i+1]] != '.'):
con.append(a[inxs[i]+1][inxs[i+1]])
for i in con:
if i not in fin:
fin.append(i)
print(len(fin))
# def index_2d(a, c):
# for i, e in enumerate(a):
# try:
# return i, e.index(c)
# except ValueError:
# pass
# raise ValueError("{} is not in list".format(repr(c)))
# print(index_2d(a, c))
```
| 1,322 |
Provide tags and a correct Python 3 solution for this coding contest problem.
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.
The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The Β«periodΒ» character (Β«.Β») stands for an empty cell.
Input
The first line contains two separated by a space integer numbers n, m (1 β€ n, m β€ 100) β the length and the width of the office-room, and c character β the President's desk colour. The following n lines contain m characters each β the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.
Output
Print the only number β the amount of President's deputies.
Examples
Input
3 4 R
G.B.
.RR.
TTT.
Output
2
Input
3 3 Z
...
.H.
..Z
Output
0
Tags: implementation
Correct Solution:
```
n,m,c = input().split(" ")
n = int(n)
m = int(m)
M = []
temp = []
for i in range(m+2):
temp.append('.')
M.append(temp)
for i in range(0,n):
k = list(input())
k.insert(0,'.')
k.insert(len(k),'.')
M.append(k)
M.append(temp)
#print(M)
d={}
for i in range(1,n+1):
for j in range(1,m+1):
#print(M[i][j])
if M[i][j]==c :
if M[i][j+1]!=c and M[i][j+1]!='.':
d[M[i][j+1]] =1
if M[i+1][j]!=c and M[i+1][j]!='.':
d[M[i+1][j]] =1
if M[i][j-1]!=c and M[i][j-1]!='.':
d[M[i][j-1]] =1
if M[i-1][j]!=c and M[i-1][j]!='.':
d[M[i-1][j]] =1
print(len(d))
```
| 1,323 |
Provide tags and a correct Python 3 solution for this coding contest problem.
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.
The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The Β«periodΒ» character (Β«.Β») stands for an empty cell.
Input
The first line contains two separated by a space integer numbers n, m (1 β€ n, m β€ 100) β the length and the width of the office-room, and c character β the President's desk colour. The following n lines contain m characters each β the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.
Output
Print the only number β the amount of President's deputies.
Examples
Input
3 4 R
G.B.
.RR.
TTT.
Output
2
Input
3 3 Z
...
.H.
..Z
Output
0
Tags: implementation
Correct Solution:
```
rows, columns, color = input().split()
rows = int(rows)
columns = int(columns)
mat = []
desk = {color}
for i in range(rows):
mat.append(list(input()))
for i in range(len(mat)):
for j in range(columns):
if mat[i][j] != '.':
if j+1 < columns:
if mat[i][j+1] == color:
desk.add(mat[i][j])
if j-1 >=0:
if mat[i][j-1] == color:
desk.add(mat[i][j])
if i+1 < rows:
if mat[i+1][j] == color:
desk.add(mat[i][j])
if i-1 >=0:
if mat[i-1][j] == color:
desk.add(mat[i][j])
print(len(desk)-1)
```
| 1,324 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.
The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The Β«periodΒ» character (Β«.Β») stands for an empty cell.
Input
The first line contains two separated by a space integer numbers n, m (1 β€ n, m β€ 100) β the length and the width of the office-room, and c character β the President's desk colour. The following n lines contain m characters each β the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.
Output
Print the only number β the amount of President's deputies.
Examples
Input
3 4 R
G.B.
.RR.
TTT.
Output
2
Input
3 3 Z
...
.H.
..Z
Output
0
Submitted Solution:
```
n,m,pres=input().split()
n,m=int(n),int(m)
l=[]
for i in range(n):
l1=list(input())
l.append(l1)
ans=[]
for i in range(n):
for j in range(m):
if l[i][j]==pres:
if i-1>=0:
ans.append(l[i-1][j])
if i+1<n:
ans.append(l[i+1][j])
if j-1>=0:
ans.append(l[i][j-1])
if j+1<m:
ans.append(l[i][j+1])
ans=set(ans)
ans.discard('.')
ans.discard(pres)
print(len(set(ans)))
```
Yes
| 1,325 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.
The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The Β«periodΒ» character (Β«.Β») stands for an empty cell.
Input
The first line contains two separated by a space integer numbers n, m (1 β€ n, m β€ 100) β the length and the width of the office-room, and c character β the President's desk colour. The following n lines contain m characters each β the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.
Output
Print the only number β the amount of President's deputies.
Examples
Input
3 4 R
G.B.
.RR.
TTT.
Output
2
Input
3 3 Z
...
.H.
..Z
Output
0
Submitted Solution:
```
n,m,c = input().split()
n = int(n)
m = int(m)
office = ''
for i in range(n):
office += input()
x,y=office.index(c),office.rindex(c)
colours={}
for i in range(len(office)):
if office[i]!='.' and office[i]!=c and ((x%m-1==i%m or i%m==y%m+1) and x//m<=i//m<=y//m or (int(x/m)-1==int(i/m) or int(i/m)==int(y/m)+1) and x%m<=i%m<=y%m):
colours[office[i]]=1
print(len(colours))
```
Yes
| 1,326 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.
The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The Β«periodΒ» character (Β«.Β») stands for an empty cell.
Input
The first line contains two separated by a space integer numbers n, m (1 β€ n, m β€ 100) β the length and the width of the office-room, and c character β the President's desk colour. The following n lines contain m characters each β the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.
Output
Print the only number β the amount of President's deputies.
Examples
Input
3 4 R
G.B.
.RR.
TTT.
Output
2
Input
3 3 Z
...
.H.
..Z
Output
0
Submitted Solution:
```
n , m , c = input().split()
n = int(n)
m = int(m)
matrix = []
for i in range(n):
matrix.append(input())
count = 0
d = {}
for i in range(n):
val = matrix[i]
for j in range(m):
if(val[j]==c):
if(i-1>=0 and matrix[i-1][j]!=c and matrix[i-1][j]!='.' and matrix[i-1][j] not in d):
count+=1
v = matrix[i-1][j]
d[v] = 1
if(j-1>=0 and matrix[i][j-1]!=c and matrix[i][j-1]!='.' and matrix[i][j-1] not in d):
count+=1
v = matrix[i][j-1]
d[v]=1
if(j+1<m and matrix[i][j+1]!=c and matrix[i][j+1]!='.' and matrix[i][j+1] not in d):
count+=1
v = matrix[i][j+1]
d[v] = 1
if(i+1<n and matrix[i+1][j]!=c and matrix[i+1][j]!='.' and matrix[i+1][j] not in d):
count+=1
v = matrix[i+1][j]
d[v] = 1
print(count)
```
Yes
| 1,327 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.
The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The Β«periodΒ» character (Β«.Β») stands for an empty cell.
Input
The first line contains two separated by a space integer numbers n, m (1 β€ n, m β€ 100) β the length and the width of the office-room, and c character β the President's desk colour. The following n lines contain m characters each β the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.
Output
Print the only number β the amount of President's deputies.
Examples
Input
3 4 R
G.B.
.RR.
TTT.
Output
2
Input
3 3 Z
...
.H.
..Z
Output
0
Submitted Solution:
```
def solution(n,m,c,lists):
deputies = {}
x = []
ans = 0
for _x,l in enumerate(lists):
for _y,d in enumerate(l):
if d == c:
x.append((_x,_y))
else:
if d!='.' and d not in deputies:
deputies[d] = False
for _x,l in enumerate(lists):
for _y,d in enumerate(l):
if d in deputies:
if not deputies[d] and ((_x+1,_y) in x or (_x-1,_y) in x or (_x,_y+1) in x or (_x,_y-1) in x):
ans+=1
deputies[d] = True
return ans
n,m,c = input().split(' ')
n = int(n)
m = int(m)
lists = []
for x in range(n):
lists.append(list(input()))
print(solution(n,m,c,lists))
```
Yes
| 1,328 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.
The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The Β«periodΒ» character (Β«.Β») stands for an empty cell.
Input
The first line contains two separated by a space integer numbers n, m (1 β€ n, m β€ 100) β the length and the width of the office-room, and c character β the President's desk colour. The following n lines contain m characters each β the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.
Output
Print the only number β the amount of President's deputies.
Examples
Input
3 4 R
G.B.
.RR.
TTT.
Output
2
Input
3 3 Z
...
.H.
..Z
Output
0
Submitted Solution:
```
def find_color(room, color):
for i, line in enumerate(room):
j = line.find(color)
if j != -1:
return (i, j)
inp = input().split()
height, width = [int(i) for i in inp[:2]]
color = inp[2]
room = []
for i in range(height):
room.append(input())
y, x = find_color(room, color)
adyacents = set()
i = x
j = y
# print(i, j)
if y > 0:
while i < width and room[y][i] == color:
# print(f"checking {(y - 1, i)}: {room[y - 1][i]}")
adyacents.add(room[y - 1][i])
i += 1
if x > 0:
while j < height and room[j][x]:
# print(f"checking {(j, x - 1)}: {room[j][x - 1]}")
adyacents.add(room[j][x - 1])
j += 1
# print(i, j)
if i < width - 1:
i -= 1
while y < height and room[y][i] == color:
# print(f"checking {(y, i + 1)}: {room[y - 1][i]}")
adyacents.add(room[y][i + 1])
y += 1
if j < height - 1:
j -= 1
while x < width and room[j][x] == color:
# print(f"checking {(j + 1, x)}: {room[j + 1][x]}")
adyacents.add(room[j + 1][x])
x += 1
# print(adyacents)
result = len(adyacents)
if '.' in adyacents:
result -= 1
if color in adyacents:
result -= 1
print(result)
```
No
| 1,329 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.
The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The Β«periodΒ» character (Β«.Β») stands for an empty cell.
Input
The first line contains two separated by a space integer numbers n, m (1 β€ n, m β€ 100) β the length and the width of the office-room, and c character β the President's desk colour. The following n lines contain m characters each β the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.
Output
Print the only number β the amount of President's deputies.
Examples
Input
3 4 R
G.B.
.RR.
TTT.
Output
2
Input
3 3 Z
...
.H.
..Z
Output
0
Submitted Solution:
```
if __name__ == '__main__':
n, m, color = input().split()
n = int(n)
m = int(m)
mat = []
indi = []
indj = []
dep = []
for i in range(n):
ar = input()
for j in range(m):
if ar[j] == color:
indi.append(i)
indj.append(j)
mat.append(ar)
l = len(indi)
for k in range(l):
i = indi[k]
j = indj[k]
if i+1 < n and j < m:
if mat[i+1][j] != 'R' and mat[i+1][j] != '.':
dep.append(mat[i+1][j])
if i < n and j+1 < m:
if mat[i][j+1] != 'R' and mat[i][j+1] != '.':
dep.append(mat[i][j+1])
if i-1 >=0 and j < m:
if mat[i-1][j] != 'R' and mat[i-1][j] != '.':
dep.append(mat[i-1][j])
if i < n and j-1>= 0:
if mat[i][j-1] != 'R' and mat[i][j-1] != '.':
dep.append(mat[i][j-1])
d = set(dep)
ans = len(d)
print(ans)
```
No
| 1,330 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.
The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The Β«periodΒ» character (Β«.Β») stands for an empty cell.
Input
The first line contains two separated by a space integer numbers n, m (1 β€ n, m β€ 100) β the length and the width of the office-room, and c character β the President's desk colour. The following n lines contain m characters each β the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.
Output
Print the only number β the amount of President's deputies.
Examples
Input
3 4 R
G.B.
.RR.
TTT.
Output
2
Input
3 3 Z
...
.H.
..Z
Output
0
Submitted Solution:
```
n,m,z=map(str,input().split())
r=[]
for _ in range(int(n)):
d=input()
r.append(d)
ans=[]
for i in range(int(n)):
for j in range(int(m)):
if r[i][j]==z:
#print(i,j,r[i][j])
try:
if r[i-1][j]!=z and r[i-1][j]!='.' and i>=0:
ans.append(r[i-1][j])
#print(ans,i,j)
if r[i][j-1]!=z and r[i][j-1]!='.'and j>=0:
ans.append(r[i][j-1])
#print(ans,i,j)
if r[i+1][j]!=z and r[i+1][j]!='.':
ans.append(r[i+1][j])
#print(ans,i,j)
if r[i][j+1]!=z and r[i][j+1]!='.':
ans.append(r[i][j+1])
#print(ans,i,j)
except:
pass
print(len(set(ans)))
#print(ans)
```
No
| 1,331 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.
The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The Β«periodΒ» character (Β«.Β») stands for an empty cell.
Input
The first line contains two separated by a space integer numbers n, m (1 β€ n, m β€ 100) β the length and the width of the office-room, and c character β the President's desk colour. The following n lines contain m characters each β the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.
Output
Print the only number β the amount of President's deputies.
Examples
Input
3 4 R
G.B.
.RR.
TTT.
Output
2
Input
3 3 Z
...
.H.
..Z
Output
0
Submitted Solution:
```
list = []
list2 = []
deputies = 0
x,y,c = input().split()
for i in range(int(x)):
lst = input()
list.append(lst)
for i in range(int(x)):
for j in range(int(y)):
if list[i][j] == c:
list2.append(i)
list2.append(j)
for i in range(len(list2)//2):
list3 = []
rows = list2[2*i]
columns = list2[2*i+1]
if int(rows) > 0:
if list[rows-1][columns] != '.' and list[rows-1][columns] != c:
list3.append(list[rows-1][columns])
if int(columns) > 0:
if list[rows][columns-1] != '.' and list[rows][columns-1] != c:
list3.append(list[rows][columns-1])
if int(rows) < int(x)-1:
if list[rows+1][columns] != '.' and list[rows+1][columns] != c:
list3.append(list[rows+1][columns])
if int(columns) < int(y)-1:
if list[rows][columns+1] != '.' and list[rows][columns+1] != c:
list3.append(list[rows][columns+1])
if len(set(list3)) > deputies:
deputies = len(set(list3))
print(deputies)
```
No
| 1,332 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 β€ i β€ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position.
Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that.
Input
The first line of the input contains three integers n, k and x (1 β€ n, k β€ 200 000, 1 β€ x β€ 109) β the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively.
The second line contains n integers a1, a2, ..., an (<image>) β the elements of the array found by Maxim.
Output
Print n integers b1, b2, ..., bn in the only line β the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 β€ i β€ n, but the product of all array elements should be minimum possible.
If there are multiple answers, print any of them.
Examples
Input
5 3 1
5 4 3 5 2
Output
5 4 3 5 -1
Input
5 3 1
5 4 3 5 5
Output
5 4 0 5 5
Input
5 3 1
5 4 4 5 5
Output
5 1 4 5 5
Input
3 2 7
5 4 2
Output
5 11 -5
Tags: constructive algorithms, data structures, greedy, math
Correct Solution:
```
def main():
from heapq import heapify, heappop, heappushpop,heappush
n, k, x = map(int, input().split())
l, sign, h = list(map(int, input().split())), [False] * n, []
helper = lambda: print(' '.join(str(-a if s else a) for a, s in zip(l, sign)))
for i, a in enumerate(l):
if a < 0:
sign[i] = True
h.append((-a, i))
else:
h.append((a, i))
heapify(h)
a, i = heappop(h)
if 1 - sum(sign) % 2:
j = min(a // x + (1 if a % x else 0), k)
a -= j * x
if a > 0:
l[i] = a
return helper()
k -= j
a = -a
sign[i] ^= True
for _ in range(k):
a, i = heappushpop(h, (a, i))
a += x
l[i] = a
for a, i in h:
l[i] = a
helper()
if __name__ == '__main__':
main()
```
| 1,333 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 β€ i β€ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position.
Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that.
Input
The first line of the input contains three integers n, k and x (1 β€ n, k β€ 200 000, 1 β€ x β€ 109) β the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively.
The second line contains n integers a1, a2, ..., an (<image>) β the elements of the array found by Maxim.
Output
Print n integers b1, b2, ..., bn in the only line β the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 β€ i β€ n, but the product of all array elements should be minimum possible.
If there are multiple answers, print any of them.
Examples
Input
5 3 1
5 4 3 5 2
Output
5 4 3 5 -1
Input
5 3 1
5 4 3 5 5
Output
5 4 0 5 5
Input
5 3 1
5 4 4 5 5
Output
5 1 4 5 5
Input
3 2 7
5 4 2
Output
5 11 -5
Tags: constructive algorithms, data structures, greedy, math
Correct Solution:
```
import heapq
inp = list(map(int, input().split()))
n = inp[0]
k = inp[1]
x = inp[2]
a = [int(i) for i in input().strip().split(' ')]
isPositive = True
nodes = [[abs(val), val, index] for index, val in enumerate(a)]
for el in a:
if el < 0:
isPositive = not isPositive
heapq.heapify(nodes)
for i in range(k):
minNode = nodes[0]
val = minNode[1]
isCurPositive = val >= 0
newVal = val
if isPositive == isCurPositive:
newVal -= x
else:
newVal += x
minNode[1] = newVal
if val >= 0 > newVal or val < 0 <= newVal:
isPositive = not isPositive
heapq.heapreplace(nodes, [abs(newVal), newVal, minNode[2]])
result = [None] * n
for node in nodes:
result[node[2]] = str(node[1])
print(" ".join(result))
```
| 1,334 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 β€ i β€ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position.
Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that.
Input
The first line of the input contains three integers n, k and x (1 β€ n, k β€ 200 000, 1 β€ x β€ 109) β the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively.
The second line contains n integers a1, a2, ..., an (<image>) β the elements of the array found by Maxim.
Output
Print n integers b1, b2, ..., bn in the only line β the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 β€ i β€ n, but the product of all array elements should be minimum possible.
If there are multiple answers, print any of them.
Examples
Input
5 3 1
5 4 3 5 2
Output
5 4 3 5 -1
Input
5 3 1
5 4 3 5 5
Output
5 4 0 5 5
Input
5 3 1
5 4 4 5 5
Output
5 1 4 5 5
Input
3 2 7
5 4 2
Output
5 11 -5
Tags: constructive algorithms, data structures, greedy, math
Correct Solution:
```
f = lambda: map(int, input().split())
from heapq import *
n, k, x = f()
t, h, p = 0, [], list(f())
for i in range(n):
t ^= p[i] < 0
heappush(h, (abs(p[i]), i))
for j in range(k):
i = heappop(h)[1]
d = p[i] < 0
if not t: d, t = 1 - d, -x <= p[i] < x
if d: p[i] -= x
else: p[i] += x
heappush(h, (abs(p[i]), i))
for q in p: print(q)
```
| 1,335 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 β€ i β€ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position.
Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that.
Input
The first line of the input contains three integers n, k and x (1 β€ n, k β€ 200 000, 1 β€ x β€ 109) β the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively.
The second line contains n integers a1, a2, ..., an (<image>) β the elements of the array found by Maxim.
Output
Print n integers b1, b2, ..., bn in the only line β the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 β€ i β€ n, but the product of all array elements should be minimum possible.
If there are multiple answers, print any of them.
Examples
Input
5 3 1
5 4 3 5 2
Output
5 4 3 5 -1
Input
5 3 1
5 4 3 5 5
Output
5 4 0 5 5
Input
5 3 1
5 4 4 5 5
Output
5 1 4 5 5
Input
3 2 7
5 4 2
Output
5 11 -5
Tags: constructive algorithms, data structures, greedy, math
Correct Solution:
```
import heapq
n,k,v = map(int, input().split())
num = list(map(int, input().split()))
sign = len([x for x in num if x<0])
minx,mini = min([[abs(x),i] for i,x in enumerate(num)])
if sign%2==0:
if num[mini]<0:
c = min(minx//v+1, k)
k -= c
num[mini] += v*c
elif num[mini]>=0:
c = min(minx//v+1, k)
k -= c
num[mini] -= v*c
heap = []
heapq.heapify(heap)
for i,x in enumerate(num):
heapq.heappush(heap, [abs(x), i])
while k:
absx,curi = heapq.heappop(heap)
#print(curi, num[curi])
if num[curi]>=0:
num[curi] += v
else:
num[curi] -= v
heapq.heappush(heap, [abs(num[curi]),curi])
k -= 1
print(' '.join([str(x) for x in num]))
```
| 1,336 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 β€ i β€ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position.
Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that.
Input
The first line of the input contains three integers n, k and x (1 β€ n, k β€ 200 000, 1 β€ x β€ 109) β the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively.
The second line contains n integers a1, a2, ..., an (<image>) β the elements of the array found by Maxim.
Output
Print n integers b1, b2, ..., bn in the only line β the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 β€ i β€ n, but the product of all array elements should be minimum possible.
If there are multiple answers, print any of them.
Examples
Input
5 3 1
5 4 3 5 2
Output
5 4 3 5 -1
Input
5 3 1
5 4 3 5 5
Output
5 4 0 5 5
Input
5 3 1
5 4 4 5 5
Output
5 1 4 5 5
Input
3 2 7
5 4 2
Output
5 11 -5
Tags: constructive algorithms, data structures, greedy, math
Correct Solution:
```
import heapq as hq
from math import ceil
n, k, x = [int(i) for i in input().strip().split(' ')]
arr = [int(i) for i in input().strip().split(' ')]
is_neg = False
for i in arr:
if i < 0:
is_neg = True if is_neg == False else False
narr = [[abs(i), pos, i < 0] for pos, i in enumerate(arr)]
hq.heapify(narr)
if is_neg:
while k > 0:
hq.heapreplace(narr, [narr[0][0]+x, narr[0][1], narr[0][2]])
k -= 1
else:
minode = hq.heappop(narr)
mi = minode[0]
kswitch = ceil(mi/x) #make the off number of negatives
if kswitch > k:
kswitch = k
else:
minode[2] = False if minode[2] == True else True
k -= kswitch
hq.heappush(narr, [abs(mi-kswitch*x), minode[1], minode[2]])
while k > 0:
hq.heapreplace(narr, [narr[0][0]+x, narr[0][1], narr[0][2]])
k -= 1
narr = sorted(narr, key=lambda x:x[1])
arr = [str(i[0]*(-1 if i[2] else 1)) for i in narr]
print(" ".join(arr))
```
| 1,337 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 β€ i β€ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position.
Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that.
Input
The first line of the input contains three integers n, k and x (1 β€ n, k β€ 200 000, 1 β€ x β€ 109) β the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively.
The second line contains n integers a1, a2, ..., an (<image>) β the elements of the array found by Maxim.
Output
Print n integers b1, b2, ..., bn in the only line β the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 β€ i β€ n, but the product of all array elements should be minimum possible.
If there are multiple answers, print any of them.
Examples
Input
5 3 1
5 4 3 5 2
Output
5 4 3 5 -1
Input
5 3 1
5 4 3 5 5
Output
5 4 0 5 5
Input
5 3 1
5 4 4 5 5
Output
5 1 4 5 5
Input
3 2 7
5 4 2
Output
5 11 -5
Tags: constructive algorithms, data structures, greedy, math
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
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")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**51, func=lambda a, b: a & b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
def calc(n):
if n>=0:
return 1
return -1
n,k,x=map(int,input().split())
l=list(map(int,input().split()))
eq=0
for i in l:
if i<0:
eq+=1
e=[[abs(l[i]),i,calc(l[i])] for i in range(n)]
e.sort()
if eq%2==0:
k1=int(math.ceil(e[0][0]/x))
k1=min(k,k1)
e[0][0]-=k1*x
if e[0][0]<=0:
e[0][2]*=-1
e[0][0] = abs(e[0][0])
k-=k1
heapq.heapify(e)
while(k>0):
w=heapq.heappop(e)
w[0]+=x
heapq.heappush(e,w)
k-=1
ans=[0]*n
for i in e:
a,b,c=i
ans[b]=a*c
print(*ans)
```
| 1,338 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 β€ i β€ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position.
Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that.
Input
The first line of the input contains three integers n, k and x (1 β€ n, k β€ 200 000, 1 β€ x β€ 109) β the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively.
The second line contains n integers a1, a2, ..., an (<image>) β the elements of the array found by Maxim.
Output
Print n integers b1, b2, ..., bn in the only line β the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 β€ i β€ n, but the product of all array elements should be minimum possible.
If there are multiple answers, print any of them.
Examples
Input
5 3 1
5 4 3 5 2
Output
5 4 3 5 -1
Input
5 3 1
5 4 3 5 5
Output
5 4 0 5 5
Input
5 3 1
5 4 4 5 5
Output
5 1 4 5 5
Input
3 2 7
5 4 2
Output
5 11 -5
Tags: constructive algorithms, data structures, greedy, math
Correct Solution:
```
import heapq
n, k, X = map(int, input().split())
a = list(map(int, input().split()))
Q = []
sit = 0
for i, x in enumerate(a):
if x < 0:
sit += 1
heapq.heappush(Q, (abs(x), x, i))
sit = sit % 2
while k > 0:
(val, x, i) = heapq.heappop(Q)
change = None
if x < 0:
if sit == 1:
change = x - X
else:
change = x + X
else:
if sit == 1:
change = x + X
else:
change = x - X
if (x * change < 0) or (x < 0 and change == 0) or (x == 0 and change < 0):
sit = (sit+1) % 2
heapq.heappush(Q, (abs(change), change, i))
k-=1
ans = [0] * n
for (val, x, i) in Q:
ans[i] = str(x)
print(' '.join(ans))
#5 3 1
#5 4 3 5 2
#5 3 1
#5 4 3 5 5
#5 3 1
#5 4 4 5 5
#3 2 7
#5 4 2
```
| 1,339 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 β€ i β€ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position.
Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that.
Input
The first line of the input contains three integers n, k and x (1 β€ n, k β€ 200 000, 1 β€ x β€ 109) β the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively.
The second line contains n integers a1, a2, ..., an (<image>) β the elements of the array found by Maxim.
Output
Print n integers b1, b2, ..., bn in the only line β the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 β€ i β€ n, but the product of all array elements should be minimum possible.
If there are multiple answers, print any of them.
Examples
Input
5 3 1
5 4 3 5 2
Output
5 4 3 5 -1
Input
5 3 1
5 4 3 5 5
Output
5 4 0 5 5
Input
5 3 1
5 4 4 5 5
Output
5 1 4 5 5
Input
3 2 7
5 4 2
Output
5 11 -5
Tags: constructive algorithms, data structures, greedy, math
Correct Solution:
```
__author__ = 'Think'
def respond():
if len(arr)>0:
if not arr[0][2]:
print(-arr[0][0], end="")
else:
print(arr[0][0], end="")
for i in arr[1:]:
if i[2]:
print(" "+str(i[0]), end="")
else:
print(" "+str(-i[0]), end="")
n, k, x=[int(i) for i in input().split()]
data=[int(i) for i in input().split()]
arr=[]
parity=0
for i in range(n):
if data[i]<0:
parity+=1
arr.append([abs(data[i]), i, data[i]>=0])
ordered=sorted(arr, key=lambda n:abs(n[0]))
if ordered[0][0]>=k*x and (parity%2)==0:
arr[ordered[0][1]][0]-=k*x
respond()
else:
start=0
if (parity%2)==0:
start=1
c=ordered[0][0]
ordered[0][0]=(x*((c//x)+1))-c
k-=(c//x+1)
arr[ordered[0][1]][2]=(not arr[ordered[0][1]][2])
if k>0:
total=0
prev=0
broken=False
for m in range(len(ordered)):
a=ordered[m][0]//x
if a==prev:
total+=a
continue
prev=a
if m*a-total<k:
total+=a
continue
else:
broken=True
break
if not broken:
m+=1
base=(k+total)//m
k-=(m*base-total)
increm=sorted(ordered[:m], key=lambda n:(n[0]%x))
for i in increm:
pos=i[1]
if k>0:
arr[pos][0]=(base+1)*x+(arr[pos][0]%x)
k-=1
else:
arr[pos][0]=base*x+(arr[pos][0]%x)
respond()
else:
respond()
```
| 1,340 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 β€ i β€ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position.
Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that.
Input
The first line of the input contains three integers n, k and x (1 β€ n, k β€ 200 000, 1 β€ x β€ 109) β the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively.
The second line contains n integers a1, a2, ..., an (<image>) β the elements of the array found by Maxim.
Output
Print n integers b1, b2, ..., bn in the only line β the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 β€ i β€ n, but the product of all array elements should be minimum possible.
If there are multiple answers, print any of them.
Examples
Input
5 3 1
5 4 3 5 2
Output
5 4 3 5 -1
Input
5 3 1
5 4 3 5 5
Output
5 4 0 5 5
Input
5 3 1
5 4 4 5 5
Output
5 1 4 5 5
Input
3 2 7
5 4 2
Output
5 11 -5
Submitted Solution:
```
import heapq
n, k, x = [int(val) for val in input().split()]
a = [int(val) for val in input().split()]
data = [(val, 1, i) if val >= 0 else (-1 * val, -1, i) for i, val in enumerate(a)]
heapq.heapify(data)
sign = sum([1 if s == -1 else 0 for _, s, _ in data])
if sign % 2 == 1:
for i in range(k):
e = heapq.heappop(data)
heapq.heappush(data, (e[0] + x, e[1], e[2]))
else:
e = heapq.heappop(data)
if e[0] < k * x:
s = (e[0] // x) + 1
k -= s
heapq.heappush(data, (s * x - e[0], -1 * e[1], e[2]))
for i in range(k):
e = heapq.heappop(data)
heapq.heappush(data, (e[0] + x, e[1], e[2]))
else:
heapq.heappush(data, (e[0] - k * x, e[1], e[2]))
output = [0] * n
for val, s, i in data:
output[i] = s * val
print(' '.join([str(val) for val in output]))
```
Yes
| 1,341 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 β€ i β€ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position.
Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that.
Input
The first line of the input contains three integers n, k and x (1 β€ n, k β€ 200 000, 1 β€ x β€ 109) β the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively.
The second line contains n integers a1, a2, ..., an (<image>) β the elements of the array found by Maxim.
Output
Print n integers b1, b2, ..., bn in the only line β the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 β€ i β€ n, but the product of all array elements should be minimum possible.
If there are multiple answers, print any of them.
Examples
Input
5 3 1
5 4 3 5 2
Output
5 4 3 5 -1
Input
5 3 1
5 4 3 5 5
Output
5 4 0 5 5
Input
5 3 1
5 4 4 5 5
Output
5 1 4 5 5
Input
3 2 7
5 4 2
Output
5 11 -5
Submitted Solution:
```
import heapq
s = input().split()
n = int(s[0])
k = int(s[1])
x = int(s[2])
neg=0
zeroes=0
numbers = list(map(int,input().split()))
num = []
for i in numbers:
if(i<0):
neg+=1
elif(i==0):
zeroes+=1
for i,x1 in enumerate(numbers):
num.append([abs(x1),i])
heapq.heapify(num)
temp=[]
steps=0
if(neg%2==0):
temp = heapq.heappop(num)
# print(temp[1],temp[0])
# print(numbers[temp[1]],x)
if(numbers[temp[1]]<0):
steps = min(abs(numbers[temp[1]])//x+1,k)
k-=steps
numbers[temp[1]]+=steps*x
heapq.heappush(num,[abs(numbers[temp[1]]),temp[1]])
else:
steps = min((abs(numbers[temp[1]])//x)+1,k)
# print(steps)
k-=steps
numbers[temp[1]]-=steps*x
heapq.heappush(num,[abs(numbers[temp[1]]),temp[1]])
while(k>0):
temp = heapq.heappop(num)
# print(temp[1],temp[0])
if(numbers[temp[1]]<0):
# steps = (numbers[temp[1]]//x+1)
# k-=steps
numbers[temp[1]]-=x
heapq.heappush(num,[abs(numbers[temp[1]]),temp[1]])
else:
# steps = (numbers[temp[1]]//x+1)
# k-=steps
numbers[temp[1]]+=x
heapq.heappush(num,[abs(numbers[temp[1]]),temp[1]])
k-=1
for i in numbers:
print(i,end=" ")
```
Yes
| 1,342 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 β€ i β€ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position.
Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that.
Input
The first line of the input contains three integers n, k and x (1 β€ n, k β€ 200 000, 1 β€ x β€ 109) β the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively.
The second line contains n integers a1, a2, ..., an (<image>) β the elements of the array found by Maxim.
Output
Print n integers b1, b2, ..., bn in the only line β the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 β€ i β€ n, but the product of all array elements should be minimum possible.
If there are multiple answers, print any of them.
Examples
Input
5 3 1
5 4 3 5 2
Output
5 4 3 5 -1
Input
5 3 1
5 4 3 5 5
Output
5 4 0 5 5
Input
5 3 1
5 4 4 5 5
Output
5 1 4 5 5
Input
3 2 7
5 4 2
Output
5 11 -5
Submitted Solution:
```
def pull(i):
global sign
if L[i] < 0:
L[i]+= x
if L[i]>=0:
sign*= -1
elif L[i] > 0:
L[i]-= x
if L[i]<0:
sign*= -1
elif sign < 0:
L[i]+= x
else:
L[i]-= x
sign = -1
def push(i):
global sign
if L[i] > 0:
L[i]+= x
elif L[i] < 0:
L[i]-= x
elif sign < 0:
L[i]+= x
else:
L[i]-= x
sign = -1
n,k,x = map(int,input().split())
L = list(map(int,input().split()))
sign = 1
for q in L:
if q<0:
sign*= -1
for i in range(n):
if L[i] == 0:
if k == 0:
break
k-= 1
push(i)
ini = min(range(n), key=lambda i: abs(L[i]))
while (sign > 0 or not L[ini]) and k > 0:
k-= 1
pull(ini)
#print(L, sign)
#print(L)
S = sorted(range(n), key=lambda i: abs(L[i]))
i = 0
while k > 0:
push(S[i])
k-= 1
j = (i+1)%n
if abs(L[S[i]]) > abs(L[S[j]]):
i = j
#print(L)
for i in L:
print(i, end=' ')
```
No
| 1,343 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 β€ i β€ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position.
Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that.
Input
The first line of the input contains three integers n, k and x (1 β€ n, k β€ 200 000, 1 β€ x β€ 109) β the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively.
The second line contains n integers a1, a2, ..., an (<image>) β the elements of the array found by Maxim.
Output
Print n integers b1, b2, ..., bn in the only line β the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 β€ i β€ n, but the product of all array elements should be minimum possible.
If there are multiple answers, print any of them.
Examples
Input
5 3 1
5 4 3 5 2
Output
5 4 3 5 -1
Input
5 3 1
5 4 3 5 5
Output
5 4 0 5 5
Input
5 3 1
5 4 4 5 5
Output
5 1 4 5 5
Input
3 2 7
5 4 2
Output
5 11 -5
Submitted Solution:
```
import heapq
class Node(object):
def __init__(self, index, val):
self.index = index
self.val = val
def __lt__(self, other):
return abs(self.val).__lt__(abs(other.val))
inp = list(map(int, input().split()))
n = inp[0]
k = inp[1]
x = inp[2]
a = list(map(int, input().split()))
isPositive = True
nodes = []
for i in range(len(a)):
el = a[i]
node = Node(i, el)
nodes.append(node)
if el < 0:
isPositive = not isPositive
heapq.heapify(nodes)
for i in range(k):
minNode = nodes[0]
val = minNode.val
isCurPositive = val >= 0
if isPositive == isCurPositive:
minNode.val -= x
else:
minNode.val += x
if val * minNode.val < 0:
isPositive = not isPositive
heapq.heapify(nodes)
result = ['0'] * n
for node in nodes:
result[node.index] = str(node.val)
print(" ".join(result))
```
No
| 1,344 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 β€ i β€ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position.
Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that.
Input
The first line of the input contains three integers n, k and x (1 β€ n, k β€ 200 000, 1 β€ x β€ 109) β the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively.
The second line contains n integers a1, a2, ..., an (<image>) β the elements of the array found by Maxim.
Output
Print n integers b1, b2, ..., bn in the only line β the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 β€ i β€ n, but the product of all array elements should be minimum possible.
If there are multiple answers, print any of them.
Examples
Input
5 3 1
5 4 3 5 2
Output
5 4 3 5 -1
Input
5 3 1
5 4 3 5 5
Output
5 4 0 5 5
Input
5 3 1
5 4 4 5 5
Output
5 1 4 5 5
Input
3 2 7
5 4 2
Output
5 11 -5
Submitted Solution:
```
import heapq
n, k, X = map(int, input().split())
a = list(map(int, input().split()))
Q = []
sit = 0
for i, x in enumerate(a):
if x < 0:
sit += 1
heapq.heappush(Q, (abs(x), x, i))
sit = sit % 2
while k > 0:
(val, x, i) = heapq.heappop(Q)
change = None
if x < 0:
if sit == 1:
change = x - X
else:
change = x + X
else:
if sit == 1:
change = x + X
else:
change = x - X
if (x * change < 0) or (x < 0 and change == 0):
sit = (sit+1) % 2
heapq.heappush(Q, (abs(change), change, i))
k-=1
ans = [0] * n
for (val, x, i) in Q:
ans[i] = x
print(ans)
#5 3 1
#5 4 3 5 2
#5 3 1
#5 4 3 5 5
#5 3 1
#5 4 4 5 5
#3 2 7
#5 4 2
```
No
| 1,345 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 β€ i β€ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position.
Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. <image>) can reach, if Maxim would apply no more than k operations to it. Please help him in that.
Input
The first line of the input contains three integers n, k and x (1 β€ n, k β€ 200 000, 1 β€ x β€ 109) β the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively.
The second line contains n integers a1, a2, ..., an (<image>) β the elements of the array found by Maxim.
Output
Print n integers b1, b2, ..., bn in the only line β the array elements after applying no more than k operations to the array. In particular, <image> should stay true for every 1 β€ i β€ n, but the product of all array elements should be minimum possible.
If there are multiple answers, print any of them.
Examples
Input
5 3 1
5 4 3 5 2
Output
5 4 3 5 -1
Input
5 3 1
5 4 3 5 5
Output
5 4 0 5 5
Input
5 3 1
5 4 4 5 5
Output
5 1 4 5 5
Input
3 2 7
5 4 2
Output
5 11 -5
Submitted Solution:
```
def s():
[n,k,x] = list(map(int,input().split()))
a = list(map(int,input().split()))
a = [[a[i],i] for i in range(len(a))]
a.sort(key = lambda x:abs(x[0]))
z = 0
neg = 0
for i in a:
i = i[0]
if i == z:
z += 1
if i < 0:
neg += 1
if neg %2 == 0:
if a[0][0] == 0:
a[0][0] = -x
k -= 1
elif a[0][0] < 0:
while k > 0 and a[0][0] <= 0:
a[0][0] += x
k -= 1
else:
while k > 0 and a[0][0] >= 0:
a[0][0] -= x
k -= 1
a.sort(key = lambda x:abs(x[0]))
i = 0
while k > 0:
if i >= n:
i = 0
while k > 0 and abs(a[i][0]) <= abs(a[0][0]):
if a[i][0] < 0:
a[i][0] -= x
else:
a[i][0] += x
k -= 1
i += 1
b = n*[0]
for i in a:
b[i[1]] = i[0]
print(*b)
s()
```
No
| 1,346 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step.
The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps.
Please help Chloe to solve the problem!
Input
The only line contains two integers n and k (1 β€ n β€ 50, 1 β€ k β€ 2n - 1).
Output
Print single integer β the integer at the k-th position in the obtained sequence.
Examples
Input
3 2
Output
2
Input
4 8
Output
4
Note
In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.
In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
Tags: binary search, bitmasks, constructive algorithms, implementation
Correct Solution:
```
#Precomputation
arr=[1]
while len(arr)!=50:
arr.append(arr[-1]*2+1)
#input
n,k=map(int,input().split())
l=arr[n-1]
while k>1 and k!=l//2+1:
l=l//2
if k>l:
k-=l+1
n-=1
if k>1:
print(n)
else:
print(1)
```
| 1,347 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step.
The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps.
Please help Chloe to solve the problem!
Input
The only line contains two integers n and k (1 β€ n β€ 50, 1 β€ k β€ 2n - 1).
Output
Print single integer β the integer at the k-th position in the obtained sequence.
Examples
Input
3 2
Output
2
Input
4 8
Output
4
Note
In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.
In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
Tags: binary search, bitmasks, constructive algorithms, implementation
Correct Solution:
```
import sys
from math import hypot
N = 0
cos = 0.5
sin = -(3 ** 0.5) / 2
type = 0
sqrt2 = 2 ** 0.5
sin45 = 1 / (2 ** 0.5)
size_po = 1 / (2 ** 0.5)
sin_45 = -sin45
num = [6 / 19, 6 / 19, 11 / 9, 16 / 21, 20 / 32, 22 / 18, 8 / 10]
def make_koch(n, x1, y1, x2, y2, painter):
if n > 8:
Window.SpinBox.setValue(8)
return 0
if n == 0:
painter.drawLine(x1, y1, x2, y2)
else:
x3, y3 = (x2 - x1) / 3 + x1, (y2 - y1) / 3 + y1
make_koch(n - 1, x1, y1, x3, y3, painter)
x4, y4 = x2 - (x2 - x1) / 3, y2 - (y2 - y1) / 3
make_koch(n - 1, x4, y4, x2, y2, painter)
# Now we are going to turn x3, y3, x4, y4
x5, y5 = (x4 - x3) * cos - (y4 - y3) * sin + x3, ((y4 - y3) * cos + (x4 - x3) * sin) + y3
make_koch(n - 1, x3, y3, x5, y5, painter)
make_koch(n - 1, x5, y5, x4, y4, painter)
def make_dima_tree(n, x1, y1, x2, y2, painter):
painter.drawLine(x1, y1, x2, y2)
if n > 0:
# Now we are turning line x1, y1, x2, y2
length = hypot(x2 - x1, y2 - y1)
sinb = (y2 - y1) / length
cosb = (x2 - x1) / length
x3, y3 = sin45 * cosb - sin45 * sinb, sin45 * cosb + sin45 * sinb
x3 *= size_po * length
y3 *= size_po * length
x3 += x2
y3 += y2
make_dima_tree(n - 1, x2, y2, x3, y3, painter)
x3, y3 = sin45 * cosb - sin_45 * sinb, sin45 * cosb + sin_45 * sinb
x3 *= size_po * length
y3 *= size_po * length
x3 += x2
y3 += y2
make_dima_tree(n - 1, x2, y2, x3, y3, painter)
def f(n, k):
m = our[n]
if m // 2 + 1 == k:
return n
return f(n - 1, k % (m // 2 + 1))
def make_dr(n, x1, y1, x2, y2, painter):
if n == 0:
painter.drawLine(x1, y1, x2, y2)
else:
# turning x1, y1, x2, y2
length = hypot(x2 - x1, y2 - y1)
sinb = (y2 - y1) / length
cosb = (x2 - x1) / length
x2 -= x1
y2 -= y1
x3 = sin45 * cosb - sin45 * sinb
y3 = sin45 * cosb + sin45 * sinb
x3 *= size_po * length
y3 *= size_po * length
x3 += x1
y3 += y1
x2 += x1
y2 += y1
make_dr(n - 1, x1, y1, x3, y3, painter)
make_dr(n - 1, x3, y3, x2, y2, painter)
def make_dr2(n, x1, y1, x2, y2, painter):
if n == 0:
painter.drawLine(x1, y1, x2, y2)
else:
# turning x1, y1, x2, y2
length = hypot(x2 - x1, y2 - y1)
sinb = (y2 - y1) / length
cosb = (x2 - x1) / length
x2 -= x1
y2 -= y1
x3 = sin45 * cosb - sin45 * sinb
y3 = sin45 * cosb + sin45 * sinb
x3 *= size_po * length
y3 *= size_po * length
x3 += x1
y3 += y1
x2 += x1
y2 += y1
make_dr2(n - 1, x1, y3, x3, y1, painter)
make_dr2(n - 1, x3, y2, x2, y3, painter)
def make_dr3(n, x1, y1, x2, y2, painter):
if n == 0:
painter.drawLine(x1, y1, x2, y2)
else:
# turning x1, y1, x2, y2
length = hypot(x2 - x1, y2 - y1)
sinb = (y2 - y1) / length
cosb = (x2 - x1) / length
x2 -= x1
y2 -= y1
x3 = sin45 * cosb - sin45 * sinb
y3 = sin45 * cosb + sin45 * sinb
x3 *= size_po * length
y3 *= size_po * length
x3 += x1
y3 += y1
x2 += x1
y2 += y1
make_dr3(n - 1, x1, y1, x3, y3, painter)
make_dr3(n - 1, x2, y2, x3, y3, painter)
our = [0, 1]
n, k = map(int, input().split())
class MyWidget():
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.depth = N
def paintEvent(self, event):
painter = QtGui.QPainter()
painter.begin(self)
if type == 0:
make_koch(self.depth, 10, self.height() - 10, self.width(), self.height() - 10, painter)
elif type == 1:
make_dima_tree(self.depth, self.width() / 2, self.height(), self.width() / 2, self.height() / 2, painter)
elif type == 2:
make_birch(self.depth, self.width() / 4, self.height() - 170, self.width() / 4, self.height() / 2.5, painter)
elif type == 3:
make_tree(self.depth, self.width() / 2, self.height() - 10, self.width() / 2, self.height() * 2 / 3, painter)
elif type == 4:
make_dr(self.depth, self.width() / 3.7, self.height() / 4.1, self.width() / 3.7 * 2.7, self.height() / 4.1, painter)
elif type == 6:
make_dr3(self.depth, self.width() / 4.8, self.height() / 2.5, self.width() / 6 * 5, self.height() / 2.5, painter)
elif type == 5:
make_dr2(self.depth, self.width() / 55, self.height() / 4.7, self.width() / 55 * 54, self.height() / 4.7, painter)
painter.end()
def setValue(self, depth):
if depth > 19:
Window.SpinBox.setValue(19)
if self.depth != depth:
self.depth = depth
self.repaint()
while len(our) <= n + 1:
our.append(our[-1] * 2 + 1)
print(f(n, k))
class MyWindow():
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.resize(1910, 610)
self.setWindowTitle("Painter demo")
self.Widget = MyWidget(self)
self.Widget.setGeometry(0, 0, 1900, 600)
self.setMinimumSize(300, 300)
self.SpinBox = QtGui.QSpinBox(self)
self.SpinBox.setGeometry(10, 10, 100, 30)
QtCore.QObject.connect(self.SpinBox, QtCore.SIGNAL("valueChanged(int)"), self.Widget.setValue)
self.SpinBox.setValue(5)
self.b = QtGui.QComboBox(self)
self.b.addItem("ΠΡΡΠΌΠ°Ρ ΠΠΎΡ
Π°")
self.b.addItem("ΠΠΎΠ΄ΠΈΡΠΈΡΠΈΡΠΎΠ²Π°Π½Π½ΠΎΠ΅ Π΄Π΅ΡΠ΅Π²ΠΎ")
self.b.addItem("ΠΠ΅Π²Π΅Π΄ΠΎΠΌΠ°Ρ Π±Π΅ΡΡΠ·Π°")
self.b.addItem("ΠΠ΅ΡΠ΅Π²ΠΎ")
self.b.addItem("ΠΡΠΈΠ²Π°Ρ ΠΠ΅Π²ΠΈ")
self.b.addItem("ΠΠ°Π·Π°")
self.b.addItem("ΠΡΠΈΠ²Π°Ρ ΠΡΠ°ΠΊΠΎΠ½Π°")
self.b.setGeometry(130, 10, 250, 30)
QtCore.QObject.connect(self.b, QtCore.SIGNAL("currentIndexChanged(int)"), self.temp)
self.b.setCurrentIndex(5)
# self.b.emit(QtCore.SIGNAL("currentIndexChanged()"))
def temp(self, a):
global type
type = self.b.currentIndex()
self.resizeEvent(0)
self.Widget.repaint()
def resizeEvent(self, event):
Y = self.height()
X = self.width()
dx = 0
dy = 0
cons = num[type]
if Y / X > cons:
dy = (Y - X * cons) / 2
Y = X * cons
elif Y / X < cons:
dx = (X - Y / cons) / 2
X = Y / cons
self.Widget.setGeometry(dx, dy, X, Y)
```
| 1,348 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step.
The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps.
Please help Chloe to solve the problem!
Input
The only line contains two integers n and k (1 β€ n β€ 50, 1 β€ k β€ 2n - 1).
Output
Print single integer β the integer at the k-th position in the obtained sequence.
Examples
Input
3 2
Output
2
Input
4 8
Output
4
Note
In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.
In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
Tags: binary search, bitmasks, constructive algorithms, implementation
Correct Solution:
```
n, k = map(int, input().split())
if k % 2 == 1:
print(1)
else:
power = 51
while k % 2 ** power != 0:
power -= 1
print(power + 1)
```
| 1,349 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step.
The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps.
Please help Chloe to solve the problem!
Input
The only line contains two integers n and k (1 β€ n β€ 50, 1 β€ k β€ 2n - 1).
Output
Print single integer β the integer at the k-th position in the obtained sequence.
Examples
Input
3 2
Output
2
Input
4 8
Output
4
Note
In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.
In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
Tags: binary search, bitmasks, constructive algorithms, implementation
Correct Solution:
```
lengthes = dict()
lengthes[0] = 1
for k in range(1, 51):
lengthes[k] = lengthes[k - 1] * 2 + 1
n, k = list(map(int, input().split()))
def rec(n, k):
if n == 0:
return 1
if k <= lengthes[n - 1]:
return rec(n - 1, k)
if k == lengthes[n - 1] + 1:
return n + 1
return rec(n - 1, k - 1 - lengthes[n - 1])
print(rec(n - 1, k))
```
| 1,350 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step.
The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps.
Please help Chloe to solve the problem!
Input
The only line contains two integers n and k (1 β€ n β€ 50, 1 β€ k β€ 2n - 1).
Output
Print single integer β the integer at the k-th position in the obtained sequence.
Examples
Input
3 2
Output
2
Input
4 8
Output
4
Note
In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.
In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
Tags: binary search, bitmasks, constructive algorithms, implementation
Correct Solution:
```
a, b = map(int, input().split())
c = 1
while (b % 2 == 0):
b //= 2
c += 1
print(c)
```
| 1,351 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step.
The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps.
Please help Chloe to solve the problem!
Input
The only line contains two integers n and k (1 β€ n β€ 50, 1 β€ k β€ 2n - 1).
Output
Print single integer β the integer at the k-th position in the obtained sequence.
Examples
Input
3 2
Output
2
Input
4 8
Output
4
Note
In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.
In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
Tags: binary search, bitmasks, constructive algorithms, implementation
Correct Solution:
```
y, x = map(int, input().split())
for i in range(50):
if (x >> i) & 1:
print(i + 1)
break
```
| 1,352 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step.
The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps.
Please help Chloe to solve the problem!
Input
The only line contains two integers n and k (1 β€ n β€ 50, 1 β€ k β€ 2n - 1).
Output
Print single integer β the integer at the k-th position in the obtained sequence.
Examples
Input
3 2
Output
2
Input
4 8
Output
4
Note
In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.
In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
Tags: binary search, bitmasks, constructive algorithms, implementation
Correct Solution:
```
def dfs(n, k):
if n == 1:
return 1
m = 1 << (n-1)
if m == k:
return n
if m > k:
return dfs(n-1, k)
return dfs(n-1, k-m)
N, K = map(int, input().split())
print(dfs(N, K))
```
| 1,353 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step.
The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps.
Please help Chloe to solve the problem!
Input
The only line contains two integers n and k (1 β€ n β€ 50, 1 β€ k β€ 2n - 1).
Output
Print single integer β the integer at the k-th position in the obtained sequence.
Examples
Input
3 2
Output
2
Input
4 8
Output
4
Note
In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.
In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
Tags: binary search, bitmasks, constructive algorithms, implementation
Correct Solution:
```
# n, a, b = list(map(lambda k: int(k), input().split(' ')))
# s = input()
def solveQ1(n, a, b, s):
if s[a-1] == s[b-1]:
return 0
c = s[b-1]
n = len(s)
min_dist = n
for i in range(n):
if s[i] == c:
min_dist = min(abs(a-1-i), min_dist)
return min_dist
n, k = list(map(lambda i: int(i), input().split(' ')))
def solveQ2(n, k):
if n == 1:
return 1
if k == pow(2, n-1):
return n
if k > pow(2, n-1):
return solveQ2(n - 1, k - pow(2, n-1))
else:
return solveQ2(n - 1, k)
print(solveQ2(n, k))
# lst = [1,2,1,3,1,2,1,4,1,2,1,3,1,2,1,5,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1,6,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1,5,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1]
# for i in range(1, 63):
# print(solveQ2(6, i))
# if solveQ2(6, i) != lst[i-1]:
# print(solveQ2(6, i))
# print(6, i, lst[i-1])
```
| 1,354 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step.
The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps.
Please help Chloe to solve the problem!
Input
The only line contains two integers n and k (1 β€ n β€ 50, 1 β€ k β€ 2n - 1).
Output
Print single integer β the integer at the k-th position in the obtained sequence.
Examples
Input
3 2
Output
2
Input
4 8
Output
4
Note
In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.
In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
Submitted Solution:
```
# Fast IO Region
import os
import sys
"""
from io import BytesIO, IOBase
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")
"""
# Get out of main function
def main():
pass
# decimal to binary
def binary(n):
return (bin(n).replace("0b", ""))
# binary to decimal
def decimal(s):
return (int(s, 2))
# power of a number base 2
def pow2(n):
p = 0
while n > 1:
n //= 2
p += 1
return (p)
# if number is prime in βn time
def isPrime(n):
if (n == 1):
return (False)
else:
root = int(n ** 0.5)
root += 1
for i in range(2, root):
if (n % i == 0):
return (False)
return (True)
# list to string ,no spaces
def lts(l):
s = ''.join(map(str, l))
return s
# String to list
def stl(s):
# for each character in string to list with no spaces -->
l = list(s)
# for space in string -->
# l=list(s.split(" "))
return l
# Returns list of numbers with a particular sum
def sq(a, target, arr=[]):
s = sum(arr)
if (s == target):
return arr
if (s >= target):
return
for i in range(len(a)):
n = a[i]
remaining = a[i + 1:]
ans = sq(remaining, target, arr + [n])
if (ans):
return ans
# Sieve for prime numbers in a range
def SieveOfEratosthenes(n):
cnt = 0
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
for p in range(2, n + 1):
if prime[p]:
cnt += 1
# print(p)
return (cnt)
# for positive integerse only
def nCr(n, r):
f = math.factorial
return f(n) // f(r) // f(n - r)
# 1000000007
mod = int(1e9) + 7
def ssinp(): return input()
# s=input()
def iinp(): return int(input())
# n=int(input())
def nninp(): return map(int, input().split())
# a,b,c=map(int,input().split())
def llinp(): return list(map(int, input().split()))
# a=list(map(int,input().split()))
def p(xyz): print(xyz)
def p2(a, b): print(a, b)
import math
# import random
# sys.setrecursionlimit(300000)
# from fractions import Fraction
from collections import OrderedDict
# from collections import deque
######################## mat=[[0 for i in range(n)] for j in range(m)] ########################
######################## list.sort(key=lambda x:x[1]) for sorting a list according to second element in sublist ########################
######################## Speed: STRING < LIST < SET,DICTIONARY ########################
######################## from collections import deque ########################
######################## ASCII of A-Z= 65-90 ########################
######################## ASCII of a-z= 97-122 ########################
######################## d1.setdefault(key, []).append(value) ########################
#for __ in range(iinp()):
n,k=nninp()
l1=[0]
ind=1
length=1
for i in range(n):
l1.append([ind,length+1])
ind=length+1
length=(2*length)+1
for i in range(1,n+1):
if(((k-l1[i][0])/l1[i][1])%1==0):
print(i)
exit()
```
Yes
| 1,355 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step.
The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps.
Please help Chloe to solve the problem!
Input
The only line contains two integers n and k (1 β€ n β€ 50, 1 β€ k β€ 2n - 1).
Output
Print single integer β the integer at the k-th position in the obtained sequence.
Examples
Input
3 2
Output
2
Input
4 8
Output
4
Note
In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.
In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
Submitted Solution:
```
import math
n, k = list(map(int, input().split()))
arr = reversed([int(math.pow(2, i)) for i in range(50)])
for index, num in enumerate(arr):
if k % num == 0:
print(50 - index)
break
```
Yes
| 1,356 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step.
The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps.
Please help Chloe to solve the problem!
Input
The only line contains two integers n and k (1 β€ n β€ 50, 1 β€ k β€ 2n - 1).
Output
Print single integer β the integer at the k-th position in the obtained sequence.
Examples
Input
3 2
Output
2
Input
4 8
Output
4
Note
In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.
In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
Submitted Solution:
```
n, k = [int(i) for i in input().split()]
p = 2**n
# for k in range(p-1):
num = k
counter = n
while num != 0:
num = abs(num-p//2)
# print(num)
p = p//2
counter-=1
print(counter+1)
# p = 2**n
```
Yes
| 1,357 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step.
The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps.
Please help Chloe to solve the problem!
Input
The only line contains two integers n and k (1 β€ n β€ 50, 1 β€ k β€ 2n - 1).
Output
Print single integer β the integer at the k-th position in the obtained sequence.
Examples
Input
3 2
Output
2
Input
4 8
Output
4
Note
In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.
In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
Submitted Solution:
```
# https://codeforces.com/problemset/problem/743/B
# Problem
# Big O:
# Time complexity: O(n) n-> step
# Space complexity: O(1)
def sequenceLengthAtStep(steps):
if steps == 1:
return 1
return sequenceLengthAtStep(steps - 1) * 2 + 1
def elementAtPos(pos, steps):
sequenceLength = sequenceLengthAtStep(steps)
integer = 1
firstIntegerPos = 1
while firstIntegerPos < sequenceLength:
integerModulus = firstIntegerPos * 2
if (pos - firstIntegerPos) % integerModulus == 0:
return integer
integer += 1
firstIntegerPos *= 2
return integer
# Read input
steps, pos = (int(x) for x in input().split())
print(elementAtPos(pos, steps))
```
Yes
| 1,358 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step.
The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps.
Please help Chloe to solve the problem!
Input
The only line contains two integers n and k (1 β€ n β€ 50, 1 β€ k β€ 2n - 1).
Output
Print single integer β the integer at the k-th position in the obtained sequence.
Examples
Input
3 2
Output
2
Input
4 8
Output
4
Note
In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.
In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
Submitted Solution:
```
n,k=map(int,input().split())
from math import log
ans=n
while (k):
k%=2**ans
ans-=1
print(ans+1)
```
No
| 1,359 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step.
The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps.
Please help Chloe to solve the problem!
Input
The only line contains two integers n and k (1 β€ n β€ 50, 1 β€ k β€ 2n - 1).
Output
Print single integer β the integer at the k-th position in the obtained sequence.
Examples
Input
3 2
Output
2
Input
4 8
Output
4
Note
In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.
In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
Submitted Solution:
```
from sys import stdin, stdout
def b_e(n):
if n == 0:
return 1
elif n%2 == 0:
return b_e(n//2)*b_e(n//2)
else:
return 2*b_e(n//2)*b_e(n//2)
def give(n):
yield b_e(n-1)
yield b_e(n)
def main():
n, m = map(int, stdin.readline().strip().split())
l, r = 1, n+1
number = -1
while l <= r:
mid = (l+r) // 2
a, d = give(mid)
if m-a < 0:
r = mid - 1
elif m-a>0 and (m-a)%d != 0:
l = mid + 1
else:
number = mid
break
stdout.write(f'{number}')
if __name__ == '__main__':
main()
```
No
| 1,360 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step.
The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps.
Please help Chloe to solve the problem!
Input
The only line contains two integers n and k (1 β€ n β€ 50, 1 β€ k β€ 2n - 1).
Output
Print single integer β the integer at the k-th position in the obtained sequence.
Examples
Input
3 2
Output
2
Input
4 8
Output
4
Note
In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.
In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
Submitted Solution:
```
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
def pow_mod(base, exp):
if exp == 0:
return 1
elif exp == 1:
return base
elif (exp & 1) != 0:
return base * pow_mod(base * base, exp // 2)
else:
return pow_mod(base * base, exp // 2)
#n, m = map(int, input().split())
#c = ([int(z) for z in input().split()])
n, k = map(int, input().split())
t1 = pow_mod(2, n-1)
print(t1)
if k==t1:
print(n)
elif k%2!=0:
print('1')
else:
flag = 1
while(flag==1):
if (k!=t1):
n = n - 1
k = max(min(k, t1-k), min(k, k-t1))
t1 = t1//2
else:
flag = 0
print(n)
```
No
| 1,361 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step.
The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps.
Please help Chloe to solve the problem!
Input
The only line contains two integers n and k (1 β€ n β€ 50, 1 β€ k β€ 2n - 1).
Output
Print single integer β the integer at the k-th position in the obtained sequence.
Examples
Input
3 2
Output
2
Input
4 8
Output
4
Note
In the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.
In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4.
Submitted Solution:
```
from copy import deepcopy
n, k = [int(x) for x in input().split()]
if k & 1:
print(1)
else:
x = 1
c = 0
while x < k:
x = x << 1
c += 1
d = min(abs(k - x), abs(k - x // 2))
if d & (d - 1) == 0 and d > 2:
print(d - 1)
else:
if d == 0:
d = k
a = [1]
pp = 2
while True:
cc = deepcopy(a)
a.append(pp)
a = a + cc
pp += 1
if 2 ** (pp - 1) > d:
break
if k > len(a):
if k % (2 ** (c - 1)) - 1 < len(a):
print(a[k % (2 ** (c - 1)) - 1])
else:
print(a[k % len(a)])
else:
print(a[k - 1])
```
No
| 1,362 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud wants to write a new dictionary that contains n words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words.
He know that if two words have a relation between them, then each of them has relations with the words that has relations with the other. For example, if like means love and love is the opposite of hate, then like is also the opposite of hate. One more example: if love is the opposite of hate and hate is the opposite of like, then love means like, and so on.
Sometimes Mahmoud discovers a wrong relation. A wrong relation is a relation that makes two words equal and opposite at the same time. For example if he knows that love means like and like is the opposite of hate, and then he figures out that hate means like, the last relation is absolutely wrong because it makes hate and like opposite and have the same meaning at the same time.
After Mahmoud figured out many relations, he was worried that some of them were wrong so that they will make other relations also wrong, so he decided to tell every relation he figured out to his coder friend Ehab and for every relation he wanted to know is it correct or wrong, basing on the previously discovered relations. If it is wrong he ignores it, and doesn't check with following relations.
After adding all relations, Mahmoud asked Ehab about relations between some words based on the information he had given to him. Ehab is busy making a Codeforces round so he asked you for help.
Input
The first line of input contains three integers n, m and q (2 β€ n β€ 105, 1 β€ m, q β€ 105) where n is the number of words in the dictionary, m is the number of relations Mahmoud figured out and q is the number of questions Mahmoud asked after telling all relations.
The second line contains n distinct words a1, a2, ..., an consisting of small English letters with length not exceeding 20, which are the words in the dictionary.
Then m lines follow, each of them contains an integer t (1 β€ t β€ 2) followed by two different words xi and yi which has appeared in the dictionary words. If t = 1, that means xi has a synonymy relation with yi, otherwise xi has an antonymy relation with yi.
Then q lines follow, each of them contains two different words which has appeared in the dictionary. That are the pairs of words Mahmoud wants to know the relation between basing on the relations he had discovered.
All words in input contain only lowercase English letters and their lengths don't exceed 20 characters. In all relations and in all questions the two words are different.
Output
First, print m lines, one per each relation. If some relation is wrong (makes two words opposite and have the same meaning at the same time) you should print "NO" (without quotes) and ignore it, otherwise print "YES" (without quotes).
After that print q lines, one per each question. If the two words have the same meaning, output 1. If they are opposites, output 2. If there is no relation between them, output 3.
See the samples for better understanding.
Examples
Input
3 3 4
hate love like
1 love like
2 love hate
1 hate like
love like
love hate
like hate
hate like
Output
YES
YES
NO
1
2
2
2
Input
8 6 5
hi welcome hello ihateyou goaway dog cat rat
1 hi welcome
1 ihateyou goaway
2 hello ihateyou
2 hi goaway
2 hi hello
1 hi hello
dog cat
dog hi
hi hello
ihateyou goaway
welcome ihateyou
Output
YES
YES
YES
YES
NO
YES
3
3
1
1
2
Tags: data structures, dfs and similar, dp, dsu, graphs
Correct Solution:
```
f = lambda: input().split()
n, m, k = map(int, f())
u = list(range(n + 1))
v = [n] * n
s = {q: i for i, q in zip(u, f())}
p = ['YES'] * m
def g(i):
k = u[i]
while k != u[k]: k = u[k]
while u[i] != k: i, u[i] = u[i], k
return k
for l in range(m):
r, x, y = f()
i, j = s[x], s[y]
a, b = g(i), g(j)
i, j = v[a], v[b]
c, d = g(i), g(j)
if r == '2': b, d = d, b
if a == d: p[l] = 'NO'
elif c == b == n: v[a], v[d] = d, a
elif c == b: p[l] = 'NO'
elif c == n: u[a] = b
elif b == n: u[d] = c
elif d == n: u[b] = a
else: u[a], u[c] = b, d
u = [g(q) for q in u]
v = [u[q] for q in v]
for l in range(k):
x, y = f()
i, j = s[x], s[y]
a, c = u[i], u[j]
p.append(str(3 - 2 * (a == c) - (a == v[c])))
print('\n'.join(p))
```
| 1,363 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud wants to write a new dictionary that contains n words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words.
He know that if two words have a relation between them, then each of them has relations with the words that has relations with the other. For example, if like means love and love is the opposite of hate, then like is also the opposite of hate. One more example: if love is the opposite of hate and hate is the opposite of like, then love means like, and so on.
Sometimes Mahmoud discovers a wrong relation. A wrong relation is a relation that makes two words equal and opposite at the same time. For example if he knows that love means like and like is the opposite of hate, and then he figures out that hate means like, the last relation is absolutely wrong because it makes hate and like opposite and have the same meaning at the same time.
After Mahmoud figured out many relations, he was worried that some of them were wrong so that they will make other relations also wrong, so he decided to tell every relation he figured out to his coder friend Ehab and for every relation he wanted to know is it correct or wrong, basing on the previously discovered relations. If it is wrong he ignores it, and doesn't check with following relations.
After adding all relations, Mahmoud asked Ehab about relations between some words based on the information he had given to him. Ehab is busy making a Codeforces round so he asked you for help.
Input
The first line of input contains three integers n, m and q (2 β€ n β€ 105, 1 β€ m, q β€ 105) where n is the number of words in the dictionary, m is the number of relations Mahmoud figured out and q is the number of questions Mahmoud asked after telling all relations.
The second line contains n distinct words a1, a2, ..., an consisting of small English letters with length not exceeding 20, which are the words in the dictionary.
Then m lines follow, each of them contains an integer t (1 β€ t β€ 2) followed by two different words xi and yi which has appeared in the dictionary words. If t = 1, that means xi has a synonymy relation with yi, otherwise xi has an antonymy relation with yi.
Then q lines follow, each of them contains two different words which has appeared in the dictionary. That are the pairs of words Mahmoud wants to know the relation between basing on the relations he had discovered.
All words in input contain only lowercase English letters and their lengths don't exceed 20 characters. In all relations and in all questions the two words are different.
Output
First, print m lines, one per each relation. If some relation is wrong (makes two words opposite and have the same meaning at the same time) you should print "NO" (without quotes) and ignore it, otherwise print "YES" (without quotes).
After that print q lines, one per each question. If the two words have the same meaning, output 1. If they are opposites, output 2. If there is no relation between them, output 3.
See the samples for better understanding.
Examples
Input
3 3 4
hate love like
1 love like
2 love hate
1 hate like
love like
love hate
like hate
hate like
Output
YES
YES
NO
1
2
2
2
Input
8 6 5
hi welcome hello ihateyou goaway dog cat rat
1 hi welcome
1 ihateyou goaway
2 hello ihateyou
2 hi goaway
2 hi hello
1 hi hello
dog cat
dog hi
hi hello
ihateyou goaway
welcome ihateyou
Output
YES
YES
YES
YES
NO
YES
3
3
1
1
2
Tags: data structures, dfs and similar, dp, dsu, graphs
Correct Solution:
```
def get_relation(synonyms, antonyms, word1, word2):
if word1 not in synonyms or word2 not in synonyms:
return '3'
group1 = synonyms[word1]
group2 = synonyms[word2]
if group1 == group2:
return '1'
if group1 in antonyms and antonyms[group1] == group2:
return '2'
return '3'
def unify_synonyms(synonyms, groups, group1, group2):
min_group = min(group1, group2)
max_group = max(group1, group2)
max_synonyms = groups[max_group]
for synonym in max_synonyms:
synonyms[synonym] = min_group
update_groups(groups, min_group, max_synonyms)
return min_group, max_group
def make_synonyms(synonyms, antonyms, groups, group1, group2):
min_group1, max_group1 = unify_synonyms(synonyms, groups, group1, group2)
if group1 in antonyms and group2 in antonyms:
min_group2, max_group2 = unify_synonyms(synonyms, groups, antonyms[group1], antonyms[group2])
del antonyms[min_group1]
del antonyms[max_group1]
del antonyms[min_group2]
del antonyms[max_group2]
antonyms[min_group1] = min_group2
antonyms[min_group2] = min_group1
return min_group1
if max_group1 in antonyms:
antonym_group = antonyms[max_group1]
del antonyms[max_group1]
antonyms[min_group1] = antonym_group
antonyms[antonym_group] = min_group1
return min_group1
def update_groups(groups, group, words):
if group in groups:
groups[group].update(words)
else:
groups.update({group: set(words)})
def make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group):
if relation == '1':
if word1 not in synonyms and word2 not in synonyms:
current_group += 1
synonyms[word1] = current_group
synonyms[word2] = current_group
update_groups(groups, current_group, [word1, word2])
return current_group
if word1 not in synonyms:
synonyms[word1] = synonyms[word2]
update_groups(groups, synonyms[word2], [word1])
return current_group
if word2 not in synonyms:
synonyms[word2] = synonyms[word1]
update_groups(groups, synonyms[word1], [word2])
return current_group
group1 = synonyms[word1]
group2 = synonyms[word2]
if group1 != group2:
make_synonyms(synonyms, antonyms, groups, group1, group2)
return current_group
if relation == '2':
if word1 not in synonyms:
current_group += 1
group1 = current_group
synonyms[word1] = group1
update_groups(groups, group1, [word1])
else:
group1 = synonyms[word1]
if word2 not in synonyms:
current_group += 1
group2 = current_group
synonyms[word2] = group2
update_groups(groups, group2, [word2])
else:
group2 = synonyms[word2]
if group1 not in antonyms and group2 not in antonyms:
antonyms[group1] = group2
antonyms[group2] = group1
return current_group
if group1 in antonyms and antonyms[group1] != group2:
antonym_group = antonyms[group1]
group2 = make_synonyms(synonyms, antonyms, groups, group2, antonym_group)
if group2 in antonyms and antonyms[group2] != group1:
antonym_group = antonyms[group2]
make_synonyms(synonyms, antonyms, groups, group1, antonym_group)
return current_group
def make_relations(relation_no):
synonyms = dict()
antonyms = dict()
groups = dict()
current_group = 0
for relation in range(relation_no):
relation, word1, word2 = input().split()
current_relation = get_relation(synonyms, antonyms, word1, word2)
if current_relation == '2' and relation == '1':
print ('NO')
continue
if current_relation == '1' and relation == '2':
print ('NO')
continue
print ('YES')
current_group = make_relation(synonyms, antonyms, groups, word1, word2, relation, current_group)
return synonyms, antonyms
def answer_questions(question_no, synonyms, antonyms):
for question in range(question_no):
word1, word2 = input().split()
print(get_relation(synonyms, antonyms, word1, word2))
def main():
word_no, relation_no, question_no = [int(number) for number in input().split()]
input()
synonyms, antonyms = make_relations(relation_no)
answer_questions(question_no, synonyms, antonyms)
main()
```
| 1,364 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud wants to write a new dictionary that contains n words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words.
He know that if two words have a relation between them, then each of them has relations with the words that has relations with the other. For example, if like means love and love is the opposite of hate, then like is also the opposite of hate. One more example: if love is the opposite of hate and hate is the opposite of like, then love means like, and so on.
Sometimes Mahmoud discovers a wrong relation. A wrong relation is a relation that makes two words equal and opposite at the same time. For example if he knows that love means like and like is the opposite of hate, and then he figures out that hate means like, the last relation is absolutely wrong because it makes hate and like opposite and have the same meaning at the same time.
After Mahmoud figured out many relations, he was worried that some of them were wrong so that they will make other relations also wrong, so he decided to tell every relation he figured out to his coder friend Ehab and for every relation he wanted to know is it correct or wrong, basing on the previously discovered relations. If it is wrong he ignores it, and doesn't check with following relations.
After adding all relations, Mahmoud asked Ehab about relations between some words based on the information he had given to him. Ehab is busy making a Codeforces round so he asked you for help.
Input
The first line of input contains three integers n, m and q (2 β€ n β€ 105, 1 β€ m, q β€ 105) where n is the number of words in the dictionary, m is the number of relations Mahmoud figured out and q is the number of questions Mahmoud asked after telling all relations.
The second line contains n distinct words a1, a2, ..., an consisting of small English letters with length not exceeding 20, which are the words in the dictionary.
Then m lines follow, each of them contains an integer t (1 β€ t β€ 2) followed by two different words xi and yi which has appeared in the dictionary words. If t = 1, that means xi has a synonymy relation with yi, otherwise xi has an antonymy relation with yi.
Then q lines follow, each of them contains two different words which has appeared in the dictionary. That are the pairs of words Mahmoud wants to know the relation between basing on the relations he had discovered.
All words in input contain only lowercase English letters and their lengths don't exceed 20 characters. In all relations and in all questions the two words are different.
Output
First, print m lines, one per each relation. If some relation is wrong (makes two words opposite and have the same meaning at the same time) you should print "NO" (without quotes) and ignore it, otherwise print "YES" (without quotes).
After that print q lines, one per each question. If the two words have the same meaning, output 1. If they are opposites, output 2. If there is no relation between them, output 3.
See the samples for better understanding.
Examples
Input
3 3 4
hate love like
1 love like
2 love hate
1 hate like
love like
love hate
like hate
hate like
Output
YES
YES
NO
1
2
2
2
Input
8 6 5
hi welcome hello ihateyou goaway dog cat rat
1 hi welcome
1 ihateyou goaway
2 hello ihateyou
2 hi goaway
2 hi hello
1 hi hello
dog cat
dog hi
hi hello
ihateyou goaway
welcome ihateyou
Output
YES
YES
YES
YES
NO
YES
3
3
1
1
2
Tags: data structures, dfs and similar, dp, dsu, graphs
Correct Solution:
```
def union(u,v,parent):
x = find(u,parent)
y = find(v,parent)
if x==y:
return
parent[x]=y
def find(u,parent):
k = parent[u]
while k != parent[k]:
k = parent[k]
while parent[u] != k:
u, parent[u] = parent[u], k
return k
n,m,q = map(int,input().split())
p = [i for i in range(2*n)]
d = {}
s = input().split()
for i in range(n):
d[s[i]]=i
for i in range(m):
re,node1,node2 = input().split()
a1 = find(d[node1],p)
a2 = find(d[node1]+n,p)
b1 = find(d[node2],p)
b2 = find(d[node2]+n,p)
if re=='1':
if a1==b2 or a2==b1:
print('NO')
else:
print('YES')
union(d[node1],d[node2],p)
union(d[node1]+n,d[node2]+n,p)
elif re=='2':
if a1==b1 or a2==b2:
print('NO')
else:
print('YES')
union(d[node1],d[node2]+n,p)
union(d[node1]+n,d[node2],p)
for i in range(q):
node1,node2= input().split()
a1 = find(d[node1],p)
a2 = find(d[node1]+n,p)
b1 = find(d[node2],p)
b2 = find(d[node2]+n,p)
if a1==b1 or a2==b2:
print(1)
elif a1==b2 or b1==a2:
print(2)
else:
print(3)
```
| 1,365 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud wants to write a new dictionary that contains n words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words.
He know that if two words have a relation between them, then each of them has relations with the words that has relations with the other. For example, if like means love and love is the opposite of hate, then like is also the opposite of hate. One more example: if love is the opposite of hate and hate is the opposite of like, then love means like, and so on.
Sometimes Mahmoud discovers a wrong relation. A wrong relation is a relation that makes two words equal and opposite at the same time. For example if he knows that love means like and like is the opposite of hate, and then he figures out that hate means like, the last relation is absolutely wrong because it makes hate and like opposite and have the same meaning at the same time.
After Mahmoud figured out many relations, he was worried that some of them were wrong so that they will make other relations also wrong, so he decided to tell every relation he figured out to his coder friend Ehab and for every relation he wanted to know is it correct or wrong, basing on the previously discovered relations. If it is wrong he ignores it, and doesn't check with following relations.
After adding all relations, Mahmoud asked Ehab about relations between some words based on the information he had given to him. Ehab is busy making a Codeforces round so he asked you for help.
Input
The first line of input contains three integers n, m and q (2 β€ n β€ 105, 1 β€ m, q β€ 105) where n is the number of words in the dictionary, m is the number of relations Mahmoud figured out and q is the number of questions Mahmoud asked after telling all relations.
The second line contains n distinct words a1, a2, ..., an consisting of small English letters with length not exceeding 20, which are the words in the dictionary.
Then m lines follow, each of them contains an integer t (1 β€ t β€ 2) followed by two different words xi and yi which has appeared in the dictionary words. If t = 1, that means xi has a synonymy relation with yi, otherwise xi has an antonymy relation with yi.
Then q lines follow, each of them contains two different words which has appeared in the dictionary. That are the pairs of words Mahmoud wants to know the relation between basing on the relations he had discovered.
All words in input contain only lowercase English letters and their lengths don't exceed 20 characters. In all relations and in all questions the two words are different.
Output
First, print m lines, one per each relation. If some relation is wrong (makes two words opposite and have the same meaning at the same time) you should print "NO" (without quotes) and ignore it, otherwise print "YES" (without quotes).
After that print q lines, one per each question. If the two words have the same meaning, output 1. If they are opposites, output 2. If there is no relation between them, output 3.
See the samples for better understanding.
Examples
Input
3 3 4
hate love like
1 love like
2 love hate
1 hate like
love like
love hate
like hate
hate like
Output
YES
YES
NO
1
2
2
2
Input
8 6 5
hi welcome hello ihateyou goaway dog cat rat
1 hi welcome
1 ihateyou goaway
2 hello ihateyou
2 hi goaway
2 hi hello
1 hi hello
dog cat
dog hi
hi hello
ihateyou goaway
welcome ihateyou
Output
YES
YES
YES
YES
NO
YES
3
3
1
1
2
Tags: data structures, dfs and similar, dp, dsu, graphs
Correct Solution:
```
n,m,q=map(int,input().split())
a=input().split()
c={x:([x],[]) for x in a}
for i in range(m):
t,x,y=input().split()
if t=='2':
sign=1
else: sign=0
if c[x][0] is c[y][1-sign]:
print("NO")
continue
print("YES")
if c[x][0] is c[y][sign]:
continue
c1,c2=c[x],c[y]
if len(c1[0])+len(c1[1])<len(c2[0])+len(c2[1]):
c1,c2=c2,c1
s1,a1=c1
if sign==0:
s2,a2=c2
else:
a2,s2=c2
s1+=s2
a1+=a2
cs=s1,a1
for x in s2:
c[x]=cs
ca=a1,s1
for x in a2:
c[x]=ca
for i in range(q):
x,y=input().split()
if c[x][0] is c[y][0]:
print(1)
elif c[x][0] is c[y][1]:
print(2)
else:
print(3)
```
| 1,366 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud wants to write a new dictionary that contains n words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words.
He know that if two words have a relation between them, then each of them has relations with the words that has relations with the other. For example, if like means love and love is the opposite of hate, then like is also the opposite of hate. One more example: if love is the opposite of hate and hate is the opposite of like, then love means like, and so on.
Sometimes Mahmoud discovers a wrong relation. A wrong relation is a relation that makes two words equal and opposite at the same time. For example if he knows that love means like and like is the opposite of hate, and then he figures out that hate means like, the last relation is absolutely wrong because it makes hate and like opposite and have the same meaning at the same time.
After Mahmoud figured out many relations, he was worried that some of them were wrong so that they will make other relations also wrong, so he decided to tell every relation he figured out to his coder friend Ehab and for every relation he wanted to know is it correct or wrong, basing on the previously discovered relations. If it is wrong he ignores it, and doesn't check with following relations.
After adding all relations, Mahmoud asked Ehab about relations between some words based on the information he had given to him. Ehab is busy making a Codeforces round so he asked you for help.
Input
The first line of input contains three integers n, m and q (2 β€ n β€ 105, 1 β€ m, q β€ 105) where n is the number of words in the dictionary, m is the number of relations Mahmoud figured out and q is the number of questions Mahmoud asked after telling all relations.
The second line contains n distinct words a1, a2, ..., an consisting of small English letters with length not exceeding 20, which are the words in the dictionary.
Then m lines follow, each of them contains an integer t (1 β€ t β€ 2) followed by two different words xi and yi which has appeared in the dictionary words. If t = 1, that means xi has a synonymy relation with yi, otherwise xi has an antonymy relation with yi.
Then q lines follow, each of them contains two different words which has appeared in the dictionary. That are the pairs of words Mahmoud wants to know the relation between basing on the relations he had discovered.
All words in input contain only lowercase English letters and their lengths don't exceed 20 characters. In all relations and in all questions the two words are different.
Output
First, print m lines, one per each relation. If some relation is wrong (makes two words opposite and have the same meaning at the same time) you should print "NO" (without quotes) and ignore it, otherwise print "YES" (without quotes).
After that print q lines, one per each question. If the two words have the same meaning, output 1. If they are opposites, output 2. If there is no relation between them, output 3.
See the samples for better understanding.
Examples
Input
3 3 4
hate love like
1 love like
2 love hate
1 hate like
love like
love hate
like hate
hate like
Output
YES
YES
NO
1
2
2
2
Input
8 6 5
hi welcome hello ihateyou goaway dog cat rat
1 hi welcome
1 ihateyou goaway
2 hello ihateyou
2 hi goaway
2 hi hello
1 hi hello
dog cat
dog hi
hi hello
ihateyou goaway
welcome ihateyou
Output
YES
YES
YES
YES
NO
YES
3
3
1
1
2
Tags: data structures, dfs and similar, dp, dsu, graphs
Correct Solution:
```
class Union:
def __init__(self, n):
self.p = {i:i for i in range(n)}
self.rank = {i:1 for i in range(n)}
def find(self, x):
if x < 0: return x
if self.p[x] != x:
self.p[x] = self.find(self.p[x])
return self.p[x]
def union(self, x, y):
if x < 0 or y < 0:return
x = self.find(x)
y = self.find(y)
if x != y:
if self.rank[x] < self.rank[y]:
self.p[x] = y
self.rank[y] += self.rank[x]
else:
self.p[y] = x
self.rank[x] += self.rank[y]
n,m,q = map(int, input().split())
listW = input().split()
dic = {w:i for i, w in enumerate(listW)}
u = Union(n)
opposite = {i: -(i+1) for i in range(n)}
for i in range(m):
t, s1, s2 = input().split()
x = u.find(dic[s1])
y = u.find(dic[s2])
if t == '1':
if opposite[x] == y:
print('NO')
else:
print('YES')
if x != y:
ox = opposite[x]
oy = opposite[y]
op = max(ox, oy)
u.union(x, y)
u.union(ox,oy)
op = u.find(op)
p = u.find(x)
if op > 0:
opposite[p] = op
opposite[op] = p
else:
if x == y:
print('NO')
else:
print('YES')
if opposite[x] != y:
u.union(y, opposite[x])
u.union(x, opposite[y])
x = u.find(x)
y = u.find(y)
opposite[x] = y
opposite[y] = x
for _ in range(q):
s1, s2 = input().split()
id1, id2 = u.find(dic[s1]), u.find(dic[s2])
if id1 == id2:
print(1)
elif opposite[id1] == id2:
print(2)
else:
print(3)
```
| 1,367 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud wants to write a new dictionary that contains n words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words.
He know that if two words have a relation between them, then each of them has relations with the words that has relations with the other. For example, if like means love and love is the opposite of hate, then like is also the opposite of hate. One more example: if love is the opposite of hate and hate is the opposite of like, then love means like, and so on.
Sometimes Mahmoud discovers a wrong relation. A wrong relation is a relation that makes two words equal and opposite at the same time. For example if he knows that love means like and like is the opposite of hate, and then he figures out that hate means like, the last relation is absolutely wrong because it makes hate and like opposite and have the same meaning at the same time.
After Mahmoud figured out many relations, he was worried that some of them were wrong so that they will make other relations also wrong, so he decided to tell every relation he figured out to his coder friend Ehab and for every relation he wanted to know is it correct or wrong, basing on the previously discovered relations. If it is wrong he ignores it, and doesn't check with following relations.
After adding all relations, Mahmoud asked Ehab about relations between some words based on the information he had given to him. Ehab is busy making a Codeforces round so he asked you for help.
Input
The first line of input contains three integers n, m and q (2 β€ n β€ 105, 1 β€ m, q β€ 105) where n is the number of words in the dictionary, m is the number of relations Mahmoud figured out and q is the number of questions Mahmoud asked after telling all relations.
The second line contains n distinct words a1, a2, ..., an consisting of small English letters with length not exceeding 20, which are the words in the dictionary.
Then m lines follow, each of them contains an integer t (1 β€ t β€ 2) followed by two different words xi and yi which has appeared in the dictionary words. If t = 1, that means xi has a synonymy relation with yi, otherwise xi has an antonymy relation with yi.
Then q lines follow, each of them contains two different words which has appeared in the dictionary. That are the pairs of words Mahmoud wants to know the relation between basing on the relations he had discovered.
All words in input contain only lowercase English letters and their lengths don't exceed 20 characters. In all relations and in all questions the two words are different.
Output
First, print m lines, one per each relation. If some relation is wrong (makes two words opposite and have the same meaning at the same time) you should print "NO" (without quotes) and ignore it, otherwise print "YES" (without quotes).
After that print q lines, one per each question. If the two words have the same meaning, output 1. If they are opposites, output 2. If there is no relation between them, output 3.
See the samples for better understanding.
Examples
Input
3 3 4
hate love like
1 love like
2 love hate
1 hate like
love like
love hate
like hate
hate like
Output
YES
YES
NO
1
2
2
2
Input
8 6 5
hi welcome hello ihateyou goaway dog cat rat
1 hi welcome
1 ihateyou goaway
2 hello ihateyou
2 hi goaway
2 hi hello
1 hi hello
dog cat
dog hi
hi hello
ihateyou goaway
welcome ihateyou
Output
YES
YES
YES
YES
NO
YES
3
3
1
1
2
Tags: data structures, dfs and similar, dp, dsu, graphs
Correct Solution:
```
f = lambda: input().split()
n, m, k = map(int, f())
c = {x: ([x], []) for x in f()}
for i in range(m):
t, x, y = f()
s = 2 - int(t)
cx, cy = c[x], c[y]
if cx[0] is cy[s]:
print('NO')
continue
print('YES')
if cx[0] is cy[1 - s]: continue
if len(cx[0]) + len(cx[1]) < len(cy[0]) + len(cy[1]): cx, cy = cy, cx
ux, vx = cx
if s: uy, vy = cy
else: vy, uy = cy
ux += uy
vx += vy
for x in uy: c[x] = (ux, vx)
for x in vy: c[x] = (vx, ux)
for i in range(k):
x, y = f()
print(1 if c[x][0] is c[y][0] else 2 if c[x][0] is c[y][1] else 3)
```
| 1,368 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud wants to write a new dictionary that contains n words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words.
He know that if two words have a relation between them, then each of them has relations with the words that has relations with the other. For example, if like means love and love is the opposite of hate, then like is also the opposite of hate. One more example: if love is the opposite of hate and hate is the opposite of like, then love means like, and so on.
Sometimes Mahmoud discovers a wrong relation. A wrong relation is a relation that makes two words equal and opposite at the same time. For example if he knows that love means like and like is the opposite of hate, and then he figures out that hate means like, the last relation is absolutely wrong because it makes hate and like opposite and have the same meaning at the same time.
After Mahmoud figured out many relations, he was worried that some of them were wrong so that they will make other relations also wrong, so he decided to tell every relation he figured out to his coder friend Ehab and for every relation he wanted to know is it correct or wrong, basing on the previously discovered relations. If it is wrong he ignores it, and doesn't check with following relations.
After adding all relations, Mahmoud asked Ehab about relations between some words based on the information he had given to him. Ehab is busy making a Codeforces round so he asked you for help.
Input
The first line of input contains three integers n, m and q (2 β€ n β€ 105, 1 β€ m, q β€ 105) where n is the number of words in the dictionary, m is the number of relations Mahmoud figured out and q is the number of questions Mahmoud asked after telling all relations.
The second line contains n distinct words a1, a2, ..., an consisting of small English letters with length not exceeding 20, which are the words in the dictionary.
Then m lines follow, each of them contains an integer t (1 β€ t β€ 2) followed by two different words xi and yi which has appeared in the dictionary words. If t = 1, that means xi has a synonymy relation with yi, otherwise xi has an antonymy relation with yi.
Then q lines follow, each of them contains two different words which has appeared in the dictionary. That are the pairs of words Mahmoud wants to know the relation between basing on the relations he had discovered.
All words in input contain only lowercase English letters and their lengths don't exceed 20 characters. In all relations and in all questions the two words are different.
Output
First, print m lines, one per each relation. If some relation is wrong (makes two words opposite and have the same meaning at the same time) you should print "NO" (without quotes) and ignore it, otherwise print "YES" (without quotes).
After that print q lines, one per each question. If the two words have the same meaning, output 1. If they are opposites, output 2. If there is no relation between them, output 3.
See the samples for better understanding.
Examples
Input
3 3 4
hate love like
1 love like
2 love hate
1 hate like
love like
love hate
like hate
hate like
Output
YES
YES
NO
1
2
2
2
Input
8 6 5
hi welcome hello ihateyou goaway dog cat rat
1 hi welcome
1 ihateyou goaway
2 hello ihateyou
2 hi goaway
2 hi hello
1 hi hello
dog cat
dog hi
hi hello
ihateyou goaway
welcome ihateyou
Output
YES
YES
YES
YES
NO
YES
3
3
1
1
2
Submitted Solution:
```
def get_groups(synonyms, antonyms, word1, word2):
group1 = 0
group2 = 0
antonym1 = 0
antonym2 = 0
if word1 in synonyms:
group1 = synonyms[word1]
if word2 in synonyms:
group2 = synonyms[word2]
if group1 in antonyms:
antonym1 = antonyms[group1]
if group2 in antonyms:
antonym2 = antonyms[group2]
return group1, group2, antonym1, antonym2
def get_relation(group1, group2, antonym1, antonym2):
if group1 == group2 and group1 != 0:
return '1'
if (antonym1 == group2 and group2 != 0) or (antonym2 == group1 and group1 != 0):
return '2'
return '3'
def unify_synonyms(synonyms, antonyms, group1, group2):
min_group = min(group1, group2)
max_group = max(group1, group2)
for synonym in synonyms:
if synonyms[synonym] == max_group:
synonyms[synonym] = min_group
if max_group in antonyms:
group = antonyms[max_group]
del antonyms[max_group]
antonyms[min_group] = group
antonyms[group] = min_group
return min_group
def make_relation(synonyms, antonyms, group1, group2, antonym1, antonym2, word1, word2, relation, current_group):
if relation == '1':
if group1 == 0 and group2 == 0:
current_group += 1
synonyms[word1] = current_group
synonyms[word2] = current_group
return current_group
if group1 == 0 and group2 != 0:
synonyms[word1] = group2
return current_group
if group1 != 0 and group2 == 0:
synonyms[word2] = group1
return current_group
if group1 != group2:
unify_synonyms(synonyms, antonyms, group1, group2)
return current_group
if relation == '2':
if group1 == 0 or group2 == 0:
if group1 == 0:
current_group += 1
group1 = current_group
synonyms[word1] = group1
if group2 == 0:
current_group += 1
group2 = current_group
synonyms[word2] = group2
if group1 not in antonyms and group2 not in antonyms:
antonyms[group1] = group2
antonyms[group2] = group1
return current_group
if group1 in antonyms and group2 not in antonyms and antonyms[group1] != group2:
antonym_group = antonyms[group1]
new_group = unify_synonyms(synonyms, antonyms, group2, antonym_group)
elif group2 in antonyms and group1 not in antonyms and antonyms[group2] != group1:
antonym_group = antonyms[group2]
unify_synonyms(synonyms, antonyms, group1, antonym_group)
return current_group
if group1 in antnoyms and group2 in antonyms:
antonym_group1 = antonyms[group1]
antonym_group2 = antonyms[group2]
unify_synonyms(synonyms, antonyms, antonym_group1, antonym_group2)
return current_group
def make_relations(relation_no):
synonyms = dict()
antonyms = dict()
current_group = 0
for relation in range(relation_no):
relation, word1, word2 = input().split()
group1, group2, antonym1, antonym2 = get_groups(synonyms, antonyms, word1, word2)
current_relation = get_relation(group1, group2, antonym1, antonym2)
if current_relation == '2' and relation == '1':
print ('NO')
continue
if current_relation == '1' and relation == '2':
print ('NO')
continue
print ('YES')
current_group = make_relation(synonyms, antonyms, group1, group2, antonym1, antonym2, word1, word2, relation, current_group)
return synonyms, antonyms
def answer_questions(question_no, synonyms, antonyms):
for question in range(question_no):
word1, word2 = input().split()
group1, group2, antonym1, antonym2 = get_groups(synonyms, antonyms, word1, word2)
print(get_relation(group1, group2, antonym1, antonym2))
def main():
word_no, relation_no, question_no = [int(number) for number in input().split()]
input()
synonyms, antonyms = make_relations(relation_no)
answer_questions(question_no, synonyms, antonyms)
main()
```
No
| 1,369 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud wants to write a new dictionary that contains n words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words.
He know that if two words have a relation between them, then each of them has relations with the words that has relations with the other. For example, if like means love and love is the opposite of hate, then like is also the opposite of hate. One more example: if love is the opposite of hate and hate is the opposite of like, then love means like, and so on.
Sometimes Mahmoud discovers a wrong relation. A wrong relation is a relation that makes two words equal and opposite at the same time. For example if he knows that love means like and like is the opposite of hate, and then he figures out that hate means like, the last relation is absolutely wrong because it makes hate and like opposite and have the same meaning at the same time.
After Mahmoud figured out many relations, he was worried that some of them were wrong so that they will make other relations also wrong, so he decided to tell every relation he figured out to his coder friend Ehab and for every relation he wanted to know is it correct or wrong, basing on the previously discovered relations. If it is wrong he ignores it, and doesn't check with following relations.
After adding all relations, Mahmoud asked Ehab about relations between some words based on the information he had given to him. Ehab is busy making a Codeforces round so he asked you for help.
Input
The first line of input contains three integers n, m and q (2 β€ n β€ 105, 1 β€ m, q β€ 105) where n is the number of words in the dictionary, m is the number of relations Mahmoud figured out and q is the number of questions Mahmoud asked after telling all relations.
The second line contains n distinct words a1, a2, ..., an consisting of small English letters with length not exceeding 20, which are the words in the dictionary.
Then m lines follow, each of them contains an integer t (1 β€ t β€ 2) followed by two different words xi and yi which has appeared in the dictionary words. If t = 1, that means xi has a synonymy relation with yi, otherwise xi has an antonymy relation with yi.
Then q lines follow, each of them contains two different words which has appeared in the dictionary. That are the pairs of words Mahmoud wants to know the relation between basing on the relations he had discovered.
All words in input contain only lowercase English letters and their lengths don't exceed 20 characters. In all relations and in all questions the two words are different.
Output
First, print m lines, one per each relation. If some relation is wrong (makes two words opposite and have the same meaning at the same time) you should print "NO" (without quotes) and ignore it, otherwise print "YES" (without quotes).
After that print q lines, one per each question. If the two words have the same meaning, output 1. If they are opposites, output 2. If there is no relation between them, output 3.
See the samples for better understanding.
Examples
Input
3 3 4
hate love like
1 love like
2 love hate
1 hate like
love like
love hate
like hate
hate like
Output
YES
YES
NO
1
2
2
2
Input
8 6 5
hi welcome hello ihateyou goaway dog cat rat
1 hi welcome
1 ihateyou goaway
2 hello ihateyou
2 hi goaway
2 hi hello
1 hi hello
dog cat
dog hi
hi hello
ihateyou goaway
welcome ihateyou
Output
YES
YES
YES
YES
NO
YES
3
3
1
1
2
Submitted Solution:
```
inp = (input().strip().split(' '))
n = int(inp[0])
m = int(inp[1])
q = int(inp[2])
A = [[0 for i in range(n)] for j in range(n)]
B = list(input().strip().split(' '))
C = {}
for i in range(n):
C[B[i]] = i
for i in range(m):
status = False
relation = list(input().strip().split(' '))
x= C[relation[1]]
y= C[relation[2]]
if(A[x][y] ==0):
for j in range(n):
if A[j][x]*A[j][y] % 3 !=int(relation[0]) and A[j][y] !=0 and A[j][x]!=0:
print("NO")
status = True
A[x][y] = A[j][x]*A[j][y] % 3
A[y][x] = A[j][x]*A[j][y] % 3
break
if not status:
A[x][y] = int(relation[0])
A[y][x] = int(relation[0])
print('YES')
for i in range(q):
question = list(input().strip().split(' '))
x = C[question[0]]
y= C[question[1]]
print(A[x][y])
```
No
| 1,370 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud wants to write a new dictionary that contains n words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words.
He know that if two words have a relation between them, then each of them has relations with the words that has relations with the other. For example, if like means love and love is the opposite of hate, then like is also the opposite of hate. One more example: if love is the opposite of hate and hate is the opposite of like, then love means like, and so on.
Sometimes Mahmoud discovers a wrong relation. A wrong relation is a relation that makes two words equal and opposite at the same time. For example if he knows that love means like and like is the opposite of hate, and then he figures out that hate means like, the last relation is absolutely wrong because it makes hate and like opposite and have the same meaning at the same time.
After Mahmoud figured out many relations, he was worried that some of them were wrong so that they will make other relations also wrong, so he decided to tell every relation he figured out to his coder friend Ehab and for every relation he wanted to know is it correct or wrong, basing on the previously discovered relations. If it is wrong he ignores it, and doesn't check with following relations.
After adding all relations, Mahmoud asked Ehab about relations between some words based on the information he had given to him. Ehab is busy making a Codeforces round so he asked you for help.
Input
The first line of input contains three integers n, m and q (2 β€ n β€ 105, 1 β€ m, q β€ 105) where n is the number of words in the dictionary, m is the number of relations Mahmoud figured out and q is the number of questions Mahmoud asked after telling all relations.
The second line contains n distinct words a1, a2, ..., an consisting of small English letters with length not exceeding 20, which are the words in the dictionary.
Then m lines follow, each of them contains an integer t (1 β€ t β€ 2) followed by two different words xi and yi which has appeared in the dictionary words. If t = 1, that means xi has a synonymy relation with yi, otherwise xi has an antonymy relation with yi.
Then q lines follow, each of them contains two different words which has appeared in the dictionary. That are the pairs of words Mahmoud wants to know the relation between basing on the relations he had discovered.
All words in input contain only lowercase English letters and their lengths don't exceed 20 characters. In all relations and in all questions the two words are different.
Output
First, print m lines, one per each relation. If some relation is wrong (makes two words opposite and have the same meaning at the same time) you should print "NO" (without quotes) and ignore it, otherwise print "YES" (without quotes).
After that print q lines, one per each question. If the two words have the same meaning, output 1. If they are opposites, output 2. If there is no relation between them, output 3.
See the samples for better understanding.
Examples
Input
3 3 4
hate love like
1 love like
2 love hate
1 hate like
love like
love hate
like hate
hate like
Output
YES
YES
NO
1
2
2
2
Input
8 6 5
hi welcome hello ihateyou goaway dog cat rat
1 hi welcome
1 ihateyou goaway
2 hello ihateyou
2 hi goaway
2 hi hello
1 hi hello
dog cat
dog hi
hi hello
ihateyou goaway
welcome ihateyou
Output
YES
YES
YES
YES
NO
YES
3
3
1
1
2
Submitted Solution:
```
def find(a):
if a is None:
return a
if a != dsu[a]:
dsu[a] = find(dsu[a])
return dsu[a]
def union(a, b):
a = find(a)
b = find(b)
if a == b:
return True
aa = antonyms[a] = find(antonyms[a])
ab = antonyms[b] = find(antonyms[b])
if aa == b or ab == a:
return False
if aa is None or ab is None:
antonyms[a] = antonyms[b] = aa if ab is None else ab
else: # if aa == ab then already a == b
dsu[ab] = aa
# antonyms[ab] = a
# antonyms[b] = aa
dsu[b] = a
return True
def disunion(a, b):
a = find(a)
b = find(b)
if a == b:
return False
aa = antonyms[a] = find(antonyms[a])
ab = antonyms[b] = find(antonyms[b])
if aa == b and ab == a:
return True
if aa is not None:
# union(b, aa)
dsu[aa] = b
if ab is not None:
# union(a, ab)
dsu[ab] = a
antonyms[a] = b
antonyms[b] = a
return True
n, m, q = [int(i) for i in input().split()]
dsu = {s: s for s in input().split()}
antonyms = {s: None for s in dsu.keys()}
for _ in range(m):
t, x, y = [i for i in input().split()]
t = int(t)
if t == 1:
if union(x, y):
print('YES')
else:
print('NO')
elif t == 2:
if disunion(x, y):
print('YES')
else:
print('NO')
print(dsu)
print(antonyms)
for _ in range(q):
x, y = [find(i) for i in input().split()]
ax, ay = antonyms[x], antonyms[y] = find(antonyms[x]), find(antonyms[y])
if x == y:
print(1)
elif x == ay and y == ax:
print(2)
elif x == ay or y == ax:
print('!!!ERROR!!!')
else:
print(3)
```
No
| 1,371 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud wants to write a new dictionary that contains n words and relations between them. There are two types of relations: synonymy (i. e. the two words mean the same) and antonymy (i. e. the two words mean the opposite). From time to time he discovers a new relation between two words.
He know that if two words have a relation between them, then each of them has relations with the words that has relations with the other. For example, if like means love and love is the opposite of hate, then like is also the opposite of hate. One more example: if love is the opposite of hate and hate is the opposite of like, then love means like, and so on.
Sometimes Mahmoud discovers a wrong relation. A wrong relation is a relation that makes two words equal and opposite at the same time. For example if he knows that love means like and like is the opposite of hate, and then he figures out that hate means like, the last relation is absolutely wrong because it makes hate and like opposite and have the same meaning at the same time.
After Mahmoud figured out many relations, he was worried that some of them were wrong so that they will make other relations also wrong, so he decided to tell every relation he figured out to his coder friend Ehab and for every relation he wanted to know is it correct or wrong, basing on the previously discovered relations. If it is wrong he ignores it, and doesn't check with following relations.
After adding all relations, Mahmoud asked Ehab about relations between some words based on the information he had given to him. Ehab is busy making a Codeforces round so he asked you for help.
Input
The first line of input contains three integers n, m and q (2 β€ n β€ 105, 1 β€ m, q β€ 105) where n is the number of words in the dictionary, m is the number of relations Mahmoud figured out and q is the number of questions Mahmoud asked after telling all relations.
The second line contains n distinct words a1, a2, ..., an consisting of small English letters with length not exceeding 20, which are the words in the dictionary.
Then m lines follow, each of them contains an integer t (1 β€ t β€ 2) followed by two different words xi and yi which has appeared in the dictionary words. If t = 1, that means xi has a synonymy relation with yi, otherwise xi has an antonymy relation with yi.
Then q lines follow, each of them contains two different words which has appeared in the dictionary. That are the pairs of words Mahmoud wants to know the relation between basing on the relations he had discovered.
All words in input contain only lowercase English letters and their lengths don't exceed 20 characters. In all relations and in all questions the two words are different.
Output
First, print m lines, one per each relation. If some relation is wrong (makes two words opposite and have the same meaning at the same time) you should print "NO" (without quotes) and ignore it, otherwise print "YES" (without quotes).
After that print q lines, one per each question. If the two words have the same meaning, output 1. If they are opposites, output 2. If there is no relation between them, output 3.
See the samples for better understanding.
Examples
Input
3 3 4
hate love like
1 love like
2 love hate
1 hate like
love like
love hate
like hate
hate like
Output
YES
YES
NO
1
2
2
2
Input
8 6 5
hi welcome hello ihateyou goaway dog cat rat
1 hi welcome
1 ihateyou goaway
2 hello ihateyou
2 hi goaway
2 hi hello
1 hi hello
dog cat
dog hi
hi hello
ihateyou goaway
welcome ihateyou
Output
YES
YES
YES
YES
NO
YES
3
3
1
1
2
Submitted Solution:
```
import sys
n, m, q = sys.stdin.readline().split()
words = sys.stdin.readline().split()
clusters = []
ii = {}
clusters_map = {}
for idx, w in enumerate(words):
ii[w] = idx
clusters.append(2*idx)
clusters.append(2*idx+1)
clusters_map[2*idx] = [2*idx]
clusters_map[2*idx+1] = [2*idx+1]
def conflict(rtype, w1, w2):
rtype=int(rtype)
if rtype == 1:
return ((clusters[2*ii[w1]] >> 1) == (clusters[2*ii[w2]] >> 1)
and clusters[2*ii[w1]] != clusters[2*ii[w2]])\
or ((clusters[2*ii[w1]+1] >> 1) == (clusters[2*ii[w2]+1] >> 1)
and clusters[2*ii[w1]+1] != clusters[2*ii[w2]]+1)
else:
return ((clusters[2*ii[w1]] >> 1) == (clusters[2*ii[w2]+1] >> 1)
and clusters[2*ii[w1]] != clusters[2*ii[w2]+1])\
or ((clusters[2*ii[w1]+1] >> 1) == (clusters[2*ii[w2]] >> 1)
and clusters[2*ii[w1]+1] != clusters[2*ii[w2]])
def existing_rel(rtype, w1, w2):
rtype = int(rtype)
if (clusters[2*ii[w1]] >> 1) == (clusters[2*ii[w2]] >> 1):
if clusters[2*ii[w1]] == clusters[2*ii[w2]]:
return rtype == 1
else:
return rtype == 2
else:
False
for rel in range(int(m)):
rtype, w1, w2 = sys.stdin.readline().split()
rtype = int(rtype)
if conflict(rtype, w1, w2):
print("NO")
continue
print("YES")
if existing_rel(rtype, w1, w2):
continue
if rtype == 1:
old_idx = clusters[2*ii[w2]]
for cl in clusters_map[clusters[2*ii[w2]]]:
clusters[cl] = clusters[2*ii[w1]]
clusters_map[clusters[2*ii[w1]]].append(cl)
del clusters_map[old_idx]
old_idx = clusters[2*ii[w2]+1]
for cl in clusters_map[clusters[2*ii[w2]+1]]:
clusters[cl] = clusters[2*ii[w1]+1]
clusters_map[clusters[2*ii[w1]+1]].append(cl)
del clusters_map[old_idx]
else:
old_idx = clusters[2*ii[w2]]
for cl in clusters_map[clusters[2*ii[w2]]]:
clusters[cl] = clusters[2*ii[w1]+1]
clusters_map[clusters[2*ii[w1]+1]].append(cl)
del clusters_map[old_idx]
old_idx = clusters[2*ii[w2]+1]
for cl in clusters_map[clusters[2*ii[w2]+1]]:
clusters[cl] = clusters[2*ii[w1]]
clusters_map[clusters[2*ii[w1]]].append(cl)
del clusters_map[old_idx]
for query in range(int(q)):
w1, w2 = sys.stdin.readline().split()
if (clusters[2*ii[w1]] >> 1) == (clusters[2*ii[w2]] >> 1):
if clusters[2*ii[w1]] == clusters[2*ii[w2]]:
print("1")
else:
print("2")
else:
print("3")
```
No
| 1,372 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Two beavers, Timur and Marsel, play the following game.
There are n logs, each of exactly m meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of equal parts, the length of each one is expressed by an integer and is no less than k meters. Each resulting part is also a log which can be gnawed in future by any beaver. The beaver that can't make a move loses. Thus, the other beaver wins.
Timur makes the first move. The players play in the optimal way. Determine the winner.
Input
The first line contains three integers n, m, k (1 β€ n, m, k β€ 109).
Output
Print "Timur", if Timur wins, or "Marsel", if Marsel wins. You should print everything without the quotes.
Examples
Input
1 15 4
Output
Timur
Input
4 9 5
Output
Marsel
Note
In the first sample the beavers only have one log, of 15 meters in length. Timur moves first. The only move he can do is to split the log into 3 parts each 5 meters in length. Then Marsel moves but he can't split any of the resulting logs, as k = 4. Thus, the winner is Timur.
In the second example the beavers have 4 logs 9 meters in length. Timur can't split any of them, so that the resulting parts possessed the length of not less than 5 meters, that's why he loses instantly.
Tags: dp, games, number theory
Correct Solution:
```
#!/usr/bin/env python3
def main():
n, m, k = (int(t) for t in input().split())
if n % 2 == 0:
print("Marsel")
return
if k == 1 and m > k:
print("Timur")
return
t = 2
while t * t <= m:
if m % t == 0:
if m // t >= k:
print("Timur")
return
print("Marsel")
return
t += 1
print("Marsel")
return
main()
```
| 1,373 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Two beavers, Timur and Marsel, play the following game.
There are n logs, each of exactly m meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of equal parts, the length of each one is expressed by an integer and is no less than k meters. Each resulting part is also a log which can be gnawed in future by any beaver. The beaver that can't make a move loses. Thus, the other beaver wins.
Timur makes the first move. The players play in the optimal way. Determine the winner.
Input
The first line contains three integers n, m, k (1 β€ n, m, k β€ 109).
Output
Print "Timur", if Timur wins, or "Marsel", if Marsel wins. You should print everything without the quotes.
Examples
Input
1 15 4
Output
Timur
Input
4 9 5
Output
Marsel
Note
In the first sample the beavers only have one log, of 15 meters in length. Timur moves first. The only move he can do is to split the log into 3 parts each 5 meters in length. Then Marsel moves but he can't split any of the resulting logs, as k = 4. Thus, the winner is Timur.
In the second example the beavers have 4 logs 9 meters in length. Timur can't split any of them, so that the resulting parts possessed the length of not less than 5 meters, that's why he loses instantly.
Tags: dp, games, number theory
Correct Solution:
```
x=input()
l=x.split()
n=int(l[0])
m=int(l[1])
k=int(l[2])
def func_2(m,k):
if k==1 and m!=1:
return True
s=int(m**.5)
for i in range(2,s+1):
if not m%i:
if i>=k or m/i>=k:
return True
return False
if func_2(m,k):
p=n
else :
p=0
if p%2==0:
print('Marsel')
else :
print('Timur')
```
| 1,374 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Two beavers, Timur and Marsel, play the following game.
There are n logs, each of exactly m meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of equal parts, the length of each one is expressed by an integer and is no less than k meters. Each resulting part is also a log which can be gnawed in future by any beaver. The beaver that can't make a move loses. Thus, the other beaver wins.
Timur makes the first move. The players play in the optimal way. Determine the winner.
Input
The first line contains three integers n, m, k (1 β€ n, m, k β€ 109).
Output
Print "Timur", if Timur wins, or "Marsel", if Marsel wins. You should print everything without the quotes.
Examples
Input
1 15 4
Output
Timur
Input
4 9 5
Output
Marsel
Note
In the first sample the beavers only have one log, of 15 meters in length. Timur moves first. The only move he can do is to split the log into 3 parts each 5 meters in length. Then Marsel moves but he can't split any of the resulting logs, as k = 4. Thus, the winner is Timur.
In the second example the beavers have 4 logs 9 meters in length. Timur can't split any of them, so that the resulting parts possessed the length of not less than 5 meters, that's why he loses instantly.
Tags: dp, games, number theory
Correct Solution:
```
n, m, k = map(int, input().split())
if n % 2 == 0:
print('Marsel')
else:
divisors = set()
i = 1
while i * i <= m:
if m % i == 0:
divisors.add(i)
divisors.add(m // i)
i += 1
ans = 10 ** 18
for x in divisors:
if x >= k and x != m:
ans = min(ans, x)
if ans < 10 ** 18:
print('Timur')
else:
print('Marsel')
```
| 1,375 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Two beavers, Timur and Marsel, play the following game.
There are n logs, each of exactly m meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of equal parts, the length of each one is expressed by an integer and is no less than k meters. Each resulting part is also a log which can be gnawed in future by any beaver. The beaver that can't make a move loses. Thus, the other beaver wins.
Timur makes the first move. The players play in the optimal way. Determine the winner.
Input
The first line contains three integers n, m, k (1 β€ n, m, k β€ 109).
Output
Print "Timur", if Timur wins, or "Marsel", if Marsel wins. You should print everything without the quotes.
Examples
Input
1 15 4
Output
Timur
Input
4 9 5
Output
Marsel
Note
In the first sample the beavers only have one log, of 15 meters in length. Timur moves first. The only move he can do is to split the log into 3 parts each 5 meters in length. Then Marsel moves but he can't split any of the resulting logs, as k = 4. Thus, the winner is Timur.
In the second example the beavers have 4 logs 9 meters in length. Timur can't split any of them, so that the resulting parts possessed the length of not less than 5 meters, that's why he loses instantly.
Tags: dp, games, number theory
Correct Solution:
```
from sys import stdin, stdout
def check(m, k):
for i in range(2, int(m ** 0.5) + 1):
if not m % i and (i >= k or m // i >= k):
return 1
else:
return 0
n, m, k = map(int, stdin.readline().split())
if m < 2 * k or (k != 1 and not check(m, k)):
stdout.write('Marsel')
elif n % 2:
stdout.write('Timur')
else:
stdout.write('Marsel')
```
| 1,376 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Two beavers, Timur and Marsel, play the following game.
There are n logs, each of exactly m meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of equal parts, the length of each one is expressed by an integer and is no less than k meters. Each resulting part is also a log which can be gnawed in future by any beaver. The beaver that can't make a move loses. Thus, the other beaver wins.
Timur makes the first move. The players play in the optimal way. Determine the winner.
Input
The first line contains three integers n, m, k (1 β€ n, m, k β€ 109).
Output
Print "Timur", if Timur wins, or "Marsel", if Marsel wins. You should print everything without the quotes.
Examples
Input
1 15 4
Output
Timur
Input
4 9 5
Output
Marsel
Note
In the first sample the beavers only have one log, of 15 meters in length. Timur moves first. The only move he can do is to split the log into 3 parts each 5 meters in length. Then Marsel moves but he can't split any of the resulting logs, as k = 4. Thus, the winner is Timur.
In the second example the beavers have 4 logs 9 meters in length. Timur can't split any of them, so that the resulting parts possessed the length of not less than 5 meters, that's why he loses instantly.
Tags: dp, games, number theory
Correct Solution:
```
from collections import Counter
nn,mm,kk=[int(i) for i in input().split()]
if nn%2==0:
print('Marsel')
exit(0)
def get_ls(n):
result = []
i = 2
while i < n:
if n % i == 0:
n /= i
result.append(i)
else:
i += 1
result.append(int(n))
return result
#print(mm)
if mm%499999993==0:
mm=mm//499999993
ls = get_ls(mm)
ls.append(499999993)
mm*=499999993
elif mm%166666649==0:
#print('***')
mm=mm//166666649
ls = get_ls(mm)
ls.append(166666649)
mm*=166666649
elif mm%999999937==0:
#print('***')
mm=mm//999999937
ls = get_ls(mm)
ls.append(999999937)
mm*=999999937
elif mm%14925373==0:
#print('***')
mm=mm//14925373
ls = get_ls(mm)
ls.append(14925373)
mm*=14925373
elif mm%10204081==0:
#print('***')
mm=mm//10204081
ls = get_ls(mm)
ls.append(10204081)
mm*=10204081
else:
ls = get_ls(mm)
#print(ls)
kkk = dict(Counter(ls)).items()
d = [k for k, _ in kkk]
m = [v for _, v in kkk]
k = [0 for _ in range(len(set(ls)))]
ln = range(len(m))
dels=[]
try:
while True:
r = 1
for i1, i2 in zip(d, k):
r *= i1 ** i2
dels.append(r)
k[0] += 1
for i in ln:
if k[i] > m[i]:
k[i] = 0
k[i+1] += 1
except IndexError:
pass
for i in dels:
#print(i,kk,mm)
if kk<=i<mm:
print('Timur')
exit(0)
print('Marsel')
```
| 1,377 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Two beavers, Timur and Marsel, play the following game.
There are n logs, each of exactly m meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of equal parts, the length of each one is expressed by an integer and is no less than k meters. Each resulting part is also a log which can be gnawed in future by any beaver. The beaver that can't make a move loses. Thus, the other beaver wins.
Timur makes the first move. The players play in the optimal way. Determine the winner.
Input
The first line contains three integers n, m, k (1 β€ n, m, k β€ 109).
Output
Print "Timur", if Timur wins, or "Marsel", if Marsel wins. You should print everything without the quotes.
Examples
Input
1 15 4
Output
Timur
Input
4 9 5
Output
Marsel
Note
In the first sample the beavers only have one log, of 15 meters in length. Timur moves first. The only move he can do is to split the log into 3 parts each 5 meters in length. Then Marsel moves but he can't split any of the resulting logs, as k = 4. Thus, the winner is Timur.
In the second example the beavers have 4 logs 9 meters in length. Timur can't split any of them, so that the resulting parts possessed the length of not less than 5 meters, that's why he loses instantly.
Tags: dp, games, number theory
Correct Solution:
```
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
def get_primes(n: int):
from itertools import chain
from array import array
primes = [2, 3]
is_prime = (array('b', (0, 0, 1, 1, 0, 1, 0)) +
array('b', (1, 0, 0, 0, 1, 0)) * ((n - 1) // 6))
for i in chain.from_iterable((range(5, n + 1, 6), range(7, n + 1, 6))):
if is_prime[i]:
primes.append(i)
for j in range(i * 3, n + 1, i * 2):
is_prime[j] = 0
return is_prime, primes
n, m, k = map(int, input().split())
if m == 1:
print('Marsel')
exit()
_, primes = get_primes(32000)
primes.append(m)
for p in primes:
if m % p == 0 and m // p >= k:
print('Timur' if n & 1 else 'Marsel')
exit()
print('Marsel')
```
| 1,378 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Two beavers, Timur and Marsel, play the following game.
There are n logs, each of exactly m meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of equal parts, the length of each one is expressed by an integer and is no less than k meters. Each resulting part is also a log which can be gnawed in future by any beaver. The beaver that can't make a move loses. Thus, the other beaver wins.
Timur makes the first move. The players play in the optimal way. Determine the winner.
Input
The first line contains three integers n, m, k (1 β€ n, m, k β€ 109).
Output
Print "Timur", if Timur wins, or "Marsel", if Marsel wins. You should print everything without the quotes.
Examples
Input
1 15 4
Output
Timur
Input
4 9 5
Output
Marsel
Note
In the first sample the beavers only have one log, of 15 meters in length. Timur moves first. The only move he can do is to split the log into 3 parts each 5 meters in length. Then Marsel moves but he can't split any of the resulting logs, as k = 4. Thus, the winner is Timur.
In the second example the beavers have 4 logs 9 meters in length. Timur can't split any of them, so that the resulting parts possessed the length of not less than 5 meters, that's why he loses instantly.
Tags: dp, games, number theory
Correct Solution:
```
def check(a, b, c):
return (b <= a and a < c)
def can(n, m, k):
if n % 2 == 0:
return False
d = 1
while d*d <= m:
if m % d == 0 and (check(d, k, m) or check(m/d, k, m)):
return True
d += 1
return False
n, m, k = map(int, input().split(' '))
print ('Timur' if can(n, m, k) else 'Marsel')
```
| 1,379 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Two beavers, Timur and Marsel, play the following game.
There are n logs, each of exactly m meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of equal parts, the length of each one is expressed by an integer and is no less than k meters. Each resulting part is also a log which can be gnawed in future by any beaver. The beaver that can't make a move loses. Thus, the other beaver wins.
Timur makes the first move. The players play in the optimal way. Determine the winner.
Input
The first line contains three integers n, m, k (1 β€ n, m, k β€ 109).
Output
Print "Timur", if Timur wins, or "Marsel", if Marsel wins. You should print everything without the quotes.
Examples
Input
1 15 4
Output
Timur
Input
4 9 5
Output
Marsel
Note
In the first sample the beavers only have one log, of 15 meters in length. Timur moves first. The only move he can do is to split the log into 3 parts each 5 meters in length. Then Marsel moves but he can't split any of the resulting logs, as k = 4. Thus, the winner is Timur.
In the second example the beavers have 4 logs 9 meters in length. Timur can't split any of them, so that the resulting parts possessed the length of not less than 5 meters, that's why he loses instantly.
Tags: dp, games, number theory
Correct Solution:
```
def IsPrime(n):
d = 2
if n != 1:
while n % d != 0:
d += 1
return d == n
p = False
n, m, k = [int(i) for i in input().split()]
if m==2 and k==1 :
if n%2!=0:
print('Timur')
else:print('Marsel')
quit()
elif m<=k:
print('Marsel')
quit()
if n%2!=0 and m%k==0:
print('Timur')
quit()
if m==999999937 :
print('Marsel')
quit()
if k!=1 and k!=100:
for i in range(2,round(m**0.5)+1):
if m % i == 0 and m//i>k:
p = True
if p==False and k!=1 and k!=100:
print('Marsel')
quit()
if IsPrime(m):
print('Marsel')
elif m % 2 == 0 or m % 2 != 0:
if n % 2 != 0:
print('Timur')
else:
print('Marsel')
```
| 1,380 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Two beavers, Timur and Marsel, play the following game.
There are n logs, each of exactly m meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of equal parts, the length of each one is expressed by an integer and is no less than k meters. Each resulting part is also a log which can be gnawed in future by any beaver. The beaver that can't make a move loses. Thus, the other beaver wins.
Timur makes the first move. The players play in the optimal way. Determine the winner.
Input
The first line contains three integers n, m, k (1 β€ n, m, k β€ 109).
Output
Print "Timur", if Timur wins, or "Marsel", if Marsel wins. You should print everything without the quotes.
Examples
Input
1 15 4
Output
Timur
Input
4 9 5
Output
Marsel
Note
In the first sample the beavers only have one log, of 15 meters in length. Timur moves first. The only move he can do is to split the log into 3 parts each 5 meters in length. Then Marsel moves but he can't split any of the resulting logs, as k = 4. Thus, the winner is Timur.
In the second example the beavers have 4 logs 9 meters in length. Timur can't split any of them, so that the resulting parts possessed the length of not less than 5 meters, that's why he loses instantly.
Submitted Solution:
```
from sys import stdin, stdout
def check(m, k):
for i in range(2, int(m ** 0.5) + 1):
if not m % i and (i >= k or m // i >= k):
return 1
else:
return 0
n, m, k = map(int, stdin.readline().split())
if m < 2 * k or (k != 1 and not check(m, k)):
stdout.write('Marsel')
elif n % 2:
stdout.write('Timur')
else:
stdout.write('Marsel')
# Made By Mostafa_Khaled
```
Yes
| 1,381 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Two beavers, Timur and Marsel, play the following game.
There are n logs, each of exactly m meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of equal parts, the length of each one is expressed by an integer and is no less than k meters. Each resulting part is also a log which can be gnawed in future by any beaver. The beaver that can't make a move loses. Thus, the other beaver wins.
Timur makes the first move. The players play in the optimal way. Determine the winner.
Input
The first line contains three integers n, m, k (1 β€ n, m, k β€ 109).
Output
Print "Timur", if Timur wins, or "Marsel", if Marsel wins. You should print everything without the quotes.
Examples
Input
1 15 4
Output
Timur
Input
4 9 5
Output
Marsel
Note
In the first sample the beavers only have one log, of 15 meters in length. Timur moves first. The only move he can do is to split the log into 3 parts each 5 meters in length. Then Marsel moves but he can't split any of the resulting logs, as k = 4. Thus, the winner is Timur.
In the second example the beavers have 4 logs 9 meters in length. Timur can't split any of them, so that the resulting parts possessed the length of not less than 5 meters, that's why he loses instantly.
Submitted Solution:
```
n, m, k = map(int, input().split())
if n % 2 == 0:
print("Marsel")
exit(0)
if m % 2 == 0 and m // 2 >= k:
print("Timur")
exit(0)
if k == 1:
if m > 1:
print("Timur")
else:
print("Marsel")
exit(0)
root = int(m ** 0.5)
for d in range(2, root + 1):
if m % d == 0 and m / d >= k:
print("Timur")
exit(0)
print("Marsel")
```
Yes
| 1,382 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Two beavers, Timur and Marsel, play the following game.
There are n logs, each of exactly m meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of equal parts, the length of each one is expressed by an integer and is no less than k meters. Each resulting part is also a log which can be gnawed in future by any beaver. The beaver that can't make a move loses. Thus, the other beaver wins.
Timur makes the first move. The players play in the optimal way. Determine the winner.
Input
The first line contains three integers n, m, k (1 β€ n, m, k β€ 109).
Output
Print "Timur", if Timur wins, or "Marsel", if Marsel wins. You should print everything without the quotes.
Examples
Input
1 15 4
Output
Timur
Input
4 9 5
Output
Marsel
Note
In the first sample the beavers only have one log, of 15 meters in length. Timur moves first. The only move he can do is to split the log into 3 parts each 5 meters in length. Then Marsel moves but he can't split any of the resulting logs, as k = 4. Thus, the winner is Timur.
In the second example the beavers have 4 logs 9 meters in length. Timur can't split any of them, so that the resulting parts possessed the length of not less than 5 meters, that's why he loses instantly.
Submitted Solution:
```
n,m,k=map(int,input().split())
if n%2==0:
print("Marsel")
else:
for z in range(2,int(m**0.5)+2):
if m%z==0 and m//z>=k:
print("Timur")
break
else:
if k==1 and m>1:
print("Timur")
else:
print("Marsel")
```
Yes
| 1,383 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Two beavers, Timur and Marsel, play the following game.
There are n logs, each of exactly m meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of equal parts, the length of each one is expressed by an integer and is no less than k meters. Each resulting part is also a log which can be gnawed in future by any beaver. The beaver that can't make a move loses. Thus, the other beaver wins.
Timur makes the first move. The players play in the optimal way. Determine the winner.
Input
The first line contains three integers n, m, k (1 β€ n, m, k β€ 109).
Output
Print "Timur", if Timur wins, or "Marsel", if Marsel wins. You should print everything without the quotes.
Examples
Input
1 15 4
Output
Timur
Input
4 9 5
Output
Marsel
Note
In the first sample the beavers only have one log, of 15 meters in length. Timur moves first. The only move he can do is to split the log into 3 parts each 5 meters in length. Then Marsel moves but he can't split any of the resulting logs, as k = 4. Thus, the winner is Timur.
In the second example the beavers have 4 logs 9 meters in length. Timur can't split any of them, so that the resulting parts possessed the length of not less than 5 meters, that's why he loses instantly.
Submitted Solution:
```
import math
def check(m, k):
if k == 1 and m != 1: return True
for i in range(2, math.floor(math.pow(m, 0.5)) + 1):
if (m % i == 0) and (m / i) >= k:
return True
return False
n, m, k = map(int, input().split(" "))
if (n % 2 != 0) and check(m, k):
print("Timur")
if (n % 2 == 0) or not check(m, k):
print("Marsel")
```
Yes
| 1,384 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Two beavers, Timur and Marsel, play the following game.
There are n logs, each of exactly m meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of equal parts, the length of each one is expressed by an integer and is no less than k meters. Each resulting part is also a log which can be gnawed in future by any beaver. The beaver that can't make a move loses. Thus, the other beaver wins.
Timur makes the first move. The players play in the optimal way. Determine the winner.
Input
The first line contains three integers n, m, k (1 β€ n, m, k β€ 109).
Output
Print "Timur", if Timur wins, or "Marsel", if Marsel wins. You should print everything without the quotes.
Examples
Input
1 15 4
Output
Timur
Input
4 9 5
Output
Marsel
Note
In the first sample the beavers only have one log, of 15 meters in length. Timur moves first. The only move he can do is to split the log into 3 parts each 5 meters in length. Then Marsel moves but he can't split any of the resulting logs, as k = 4. Thus, the winner is Timur.
In the second example the beavers have 4 logs 9 meters in length. Timur can't split any of them, so that the resulting parts possessed the length of not less than 5 meters, that's why he loses instantly.
Submitted Solution:
```
n,m,k=map(int,input().split())
if n%2==0:
print("Marsel")
else:
for z in range(k,m+1):
if m%z==0:
print("Timur")
break
else:
print("Marsel")
```
No
| 1,385 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Two beavers, Timur and Marsel, play the following game.
There are n logs, each of exactly m meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of equal parts, the length of each one is expressed by an integer and is no less than k meters. Each resulting part is also a log which can be gnawed in future by any beaver. The beaver that can't make a move loses. Thus, the other beaver wins.
Timur makes the first move. The players play in the optimal way. Determine the winner.
Input
The first line contains three integers n, m, k (1 β€ n, m, k β€ 109).
Output
Print "Timur", if Timur wins, or "Marsel", if Marsel wins. You should print everything without the quotes.
Examples
Input
1 15 4
Output
Timur
Input
4 9 5
Output
Marsel
Note
In the first sample the beavers only have one log, of 15 meters in length. Timur moves first. The only move he can do is to split the log into 3 parts each 5 meters in length. Then Marsel moves but he can't split any of the resulting logs, as k = 4. Thus, the winner is Timur.
In the second example the beavers have 4 logs 9 meters in length. Timur can't split any of them, so that the resulting parts possessed the length of not less than 5 meters, that's why he loses instantly.
Submitted Solution:
```
n,m,k=[int(i) for i in input().split()]
b='Timur'
for i in range(m//k,k-1,-1):
if m%i==0:
m//=i
b='Marsel'
if n%2!=0 :
print(b)
elif b=='Timur':
print('Marsel')
else: print('Timur')
```
No
| 1,386 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Two beavers, Timur and Marsel, play the following game.
There are n logs, each of exactly m meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of equal parts, the length of each one is expressed by an integer and is no less than k meters. Each resulting part is also a log which can be gnawed in future by any beaver. The beaver that can't make a move loses. Thus, the other beaver wins.
Timur makes the first move. The players play in the optimal way. Determine the winner.
Input
The first line contains three integers n, m, k (1 β€ n, m, k β€ 109).
Output
Print "Timur", if Timur wins, or "Marsel", if Marsel wins. You should print everything without the quotes.
Examples
Input
1 15 4
Output
Timur
Input
4 9 5
Output
Marsel
Note
In the first sample the beavers only have one log, of 15 meters in length. Timur moves first. The only move he can do is to split the log into 3 parts each 5 meters in length. Then Marsel moves but he can't split any of the resulting logs, as k = 4. Thus, the winner is Timur.
In the second example the beavers have 4 logs 9 meters in length. Timur can't split any of them, so that the resulting parts possessed the length of not less than 5 meters, that's why he loses instantly.
Submitted Solution:
```
def IsPrime(n):
d = 2
if n != 1:
while n % d != 0:
d += 1
return d == n
p = False
n, m, k = [int(i) for i in input().split()]
if m==2 and k==1:
print('Timur')
quit()
for i in range(m // 2, k - 1, -1):
if m % i == 0:
p = True
if p==False:
print('Marsel')
quit()
if IsPrime(m):
print('Marsel')
elif k >= m:
print('Marsel')
elif m % 2 == 0 or m % 2 != 0:
if n % 2 != 0:
print('Timur')
else:
print('Marsel')
```
No
| 1,387 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Two beavers, Timur and Marsel, play the following game.
There are n logs, each of exactly m meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of equal parts, the length of each one is expressed by an integer and is no less than k meters. Each resulting part is also a log which can be gnawed in future by any beaver. The beaver that can't make a move loses. Thus, the other beaver wins.
Timur makes the first move. The players play in the optimal way. Determine the winner.
Input
The first line contains three integers n, m, k (1 β€ n, m, k β€ 109).
Output
Print "Timur", if Timur wins, or "Marsel", if Marsel wins. You should print everything without the quotes.
Examples
Input
1 15 4
Output
Timur
Input
4 9 5
Output
Marsel
Note
In the first sample the beavers only have one log, of 15 meters in length. Timur moves first. The only move he can do is to split the log into 3 parts each 5 meters in length. Then Marsel moves but he can't split any of the resulting logs, as k = 4. Thus, the winner is Timur.
In the second example the beavers have 4 logs 9 meters in length. Timur can't split any of them, so that the resulting parts possessed the length of not less than 5 meters, that's why he loses instantly.
Submitted Solution:
```
def can(n, m, k):
if n % 2 == 0:
return False
d = 2
while d <= m:
if m % d == 0 and (d >= k or m/d >= k):
return True
if d * d > m:
break
d += 1
return False
n, m, k = map(int, input().split(' '))
print ('Timur' if can(n, m, k) else 'Marsel')
```
No
| 1,388 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The flag of Berland is such rectangular field n Γ m that satisfies following conditions:
* Flag consists of three colors which correspond to letters 'R', 'G' and 'B'.
* Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has exactly one color.
* Each color should be used in exactly one stripe.
You are given a field n Γ m, consisting of characters 'R', 'G' and 'B'. Output "YES" (without quotes) if this field corresponds to correct flag of Berland. Otherwise, print "NO" (without quotes).
Input
The first line contains two integer numbers n and m (1 β€ n, m β€ 100) β the sizes of the field.
Each of the following n lines consisting of m characters 'R', 'G' and 'B' β the description of the field.
Output
Print "YES" (without quotes) if the given field corresponds to correct flag of Berland . Otherwise, print "NO" (without quotes).
Examples
Input
6 5
RRRRR
RRRRR
BBBBB
BBBBB
GGGGG
GGGGG
Output
YES
Input
4 3
BRG
BRG
BRG
BRG
Output
YES
Input
6 7
RRRGGGG
RRRGGGG
RRRGGGG
RRRBBBB
RRRBBBB
RRRBBBB
Output
NO
Input
4 4
RRRR
RRRR
BBBB
GGGG
Output
NO
Note
The field in the third example doesn't have three parralel stripes.
Rows of the field in the fourth example are parralel to each other and to borders. But they have different heights β 2, 1 and 1.
Tags: brute force, implementation
Correct Solution:
```
N, M = map(int, input().split())
flag = [input() for n in range(N)]
def get_rect_of_color(color):
rect_points = []
for i, row in enumerate(flag):
first = True
seq_is_broken = False
tmp = [None] * 4
for j, char in enumerate(row):
if char == color:
if first:
first = False
tmp[0], tmp[1] = i, j
if seq_is_broken:
raise Exception()
tmp[2], tmp[3] = i, j
elif not first:
seq_is_broken = True
if tmp[0] is not None:
rect_points += [tmp]
return rect_points
def get_bounding_rect(rect):
last_pos = rect[0]
first = True
for row in rect:
if first:
first = False
continue
ly1, lx1, ly2, lx2 = last_pos
y1, x1, y2, x2 = row
# print(y1, x1, y2, x2)
# print(ly1, lx1, ly2, lx2)
if y1 - ly1 != 1 or y2 - ly2 != 1 or\
x1 - lx1 != 0 or x2 - lx2 != 0:
raise Exception()
last_pos = row
return (
(rect[0][0], rect[0][1]),
(rect[-1][2], rect[-1][3]),
)
try:
R = get_bounding_rect(get_rect_of_color('R'))
G = get_bounding_rect(get_rect_of_color('G'))
B = get_bounding_rect(get_rect_of_color('B'))
Rh = abs(R[1][0] - R[0][0])
Bh = abs(B[1][0] - B[0][0])
Gh = abs(G[1][0] - G[0][0])
Rw = abs(R[1][1] - R[0][1])
Bw = abs(B[1][1] - B[0][1])
Gw = abs(G[1][1] - G[0][1])
# print(Rh, Bh, Gh)
# print(Rw, Bw, Gw)
if len(set([Rw, Bw, Gw])) != 1 or len(set([Rh, Bh, Gh])) != 1:
print('NO')
else:
print('YES')
except Exception:
print('NO')
```
| 1,389 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The flag of Berland is such rectangular field n Γ m that satisfies following conditions:
* Flag consists of three colors which correspond to letters 'R', 'G' and 'B'.
* Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has exactly one color.
* Each color should be used in exactly one stripe.
You are given a field n Γ m, consisting of characters 'R', 'G' and 'B'. Output "YES" (without quotes) if this field corresponds to correct flag of Berland. Otherwise, print "NO" (without quotes).
Input
The first line contains two integer numbers n and m (1 β€ n, m β€ 100) β the sizes of the field.
Each of the following n lines consisting of m characters 'R', 'G' and 'B' β the description of the field.
Output
Print "YES" (without quotes) if the given field corresponds to correct flag of Berland . Otherwise, print "NO" (without quotes).
Examples
Input
6 5
RRRRR
RRRRR
BBBBB
BBBBB
GGGGG
GGGGG
Output
YES
Input
4 3
BRG
BRG
BRG
BRG
Output
YES
Input
6 7
RRRGGGG
RRRGGGG
RRRGGGG
RRRBBBB
RRRBBBB
RRRBBBB
Output
NO
Input
4 4
RRRR
RRRR
BBBB
GGGG
Output
NO
Note
The field in the third example doesn't have three parralel stripes.
Rows of the field in the fourth example are parralel to each other and to borders. But they have different heights β 2, 1 and 1.
Tags: brute force, implementation
Correct Solution:
```
n, m = list(map(int, input().split()))
res = max(n, m) >= 3
is_horo = True
is_vert = True
if res:
flag = []
for i in range(n):
r = input()
if len(r) != m:
res = False
break
flag.append(list(r))
px = flag[0][0]
for i in range(1, m):
if flag[0][i] != px:
is_horo = False
break
for i in range(1, n):
if flag[i][0] != px:
is_vert = False
break
res = is_horo ^ is_vert
compressed = []
if res:
if is_horo:
for r in flag:
px = r[0]
for c in r[1:]:
if c != px:
res = False
break
compressed.append(px)
elif is_vert:
for i in range(m):
px = flag[0][i]
for j in range(1, n):
if flag[j][i] != px:
res = False
break
compressed.append(px)
if res and compressed:
stripe_width = None
c_stripe = None
c_width = 0
widths = []
seen = set()
for stripe in compressed:
if c_stripe is None:
c_stripe = stripe
c_width = 1
elif c_stripe != stripe:
seen.add(c_stripe)
widths.append(c_width)
c_width = 1
c_stripe = stripe
else:
c_width += 1
widths.append(c_width)
seen.add(c_stripe)
if len(widths) != 3 or len(seen) != 3:
res = False
else:
first = widths[0]
for i in range(1, len(widths)):
if widths[i] != first:
res = False
break
print('YES' if res else 'NO')
```
| 1,390 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The flag of Berland is such rectangular field n Γ m that satisfies following conditions:
* Flag consists of three colors which correspond to letters 'R', 'G' and 'B'.
* Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has exactly one color.
* Each color should be used in exactly one stripe.
You are given a field n Γ m, consisting of characters 'R', 'G' and 'B'. Output "YES" (without quotes) if this field corresponds to correct flag of Berland. Otherwise, print "NO" (without quotes).
Input
The first line contains two integer numbers n and m (1 β€ n, m β€ 100) β the sizes of the field.
Each of the following n lines consisting of m characters 'R', 'G' and 'B' β the description of the field.
Output
Print "YES" (without quotes) if the given field corresponds to correct flag of Berland . Otherwise, print "NO" (without quotes).
Examples
Input
6 5
RRRRR
RRRRR
BBBBB
BBBBB
GGGGG
GGGGG
Output
YES
Input
4 3
BRG
BRG
BRG
BRG
Output
YES
Input
6 7
RRRGGGG
RRRGGGG
RRRGGGG
RRRBBBB
RRRBBBB
RRRBBBB
Output
NO
Input
4 4
RRRR
RRRR
BBBB
GGGG
Output
NO
Note
The field in the third example doesn't have three parralel stripes.
Rows of the field in the fourth example are parralel to each other and to borders. But they have different heights β 2, 1 and 1.
Tags: brute force, implementation
Correct Solution:
```
#python 3.5.2
b, k = map(int, input().split())
arr = []
for i in range(b):
s = input()
arr.append(s)
x = arr[0][0]
nb = 1
nk = 1
pola = str(x)
while (nk < k and arr[0][nk] == x):
nk += 1
pola += x
if (nk == k or nk == k/3):
if (nk == k/3):
# print("xx")
arr = list(map(lambda x: ''.join(x), (map(list, zip(*arr)))))
# print(arr)
b, k = k, b
nb = 1
nk = 1
pola = str(x)
while (nk < k and arr[0][nk] == x):
nk += 1
pola += x
while (nb < b and arr[nb][:nk] == pola):
nb += 1
if (nb == b/3):
y = arr[nb][0]
polay = ""
for i in range(nk):
polay += y
nby = 0
brs = nb
while (nby+nb < b and arr[nby+nb] == polay): nby+=1
if (nby == nb):
z = arr[nby+nb][0]
if (z != x):
polaz = ""
for i in range(nk):
polaz += z
nbz = 0
brs = nby+nb
while (nbz+nby+nb < b and arr[nbz+nby+nb] == polaz): nbz+=1
if (nbz == nb):
print("YES")
else:
print("NO")
else:
print("NO")
else:
print("NO")
else:
print("NO")
else:
print("NO")
```
| 1,391 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The flag of Berland is such rectangular field n Γ m that satisfies following conditions:
* Flag consists of three colors which correspond to letters 'R', 'G' and 'B'.
* Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has exactly one color.
* Each color should be used in exactly one stripe.
You are given a field n Γ m, consisting of characters 'R', 'G' and 'B'. Output "YES" (without quotes) if this field corresponds to correct flag of Berland. Otherwise, print "NO" (without quotes).
Input
The first line contains two integer numbers n and m (1 β€ n, m β€ 100) β the sizes of the field.
Each of the following n lines consisting of m characters 'R', 'G' and 'B' β the description of the field.
Output
Print "YES" (without quotes) if the given field corresponds to correct flag of Berland . Otherwise, print "NO" (without quotes).
Examples
Input
6 5
RRRRR
RRRRR
BBBBB
BBBBB
GGGGG
GGGGG
Output
YES
Input
4 3
BRG
BRG
BRG
BRG
Output
YES
Input
6 7
RRRGGGG
RRRGGGG
RRRGGGG
RRRBBBB
RRRBBBB
RRRBBBB
Output
NO
Input
4 4
RRRR
RRRR
BBBB
GGGG
Output
NO
Note
The field in the third example doesn't have three parralel stripes.
Rows of the field in the fourth example are parralel to each other and to borders. But they have different heights β 2, 1 and 1.
Tags: brute force, implementation
Correct Solution:
```
n, m = map(int, input().split())
s = [input() for _ in range(n)]
if n % 3 != 0 and m % 3 != 0:
print('NO')
exit()
flag = 0
if n % 3 == 0:
if not(s[0][0]!=s[n//3][0] and s[2*n//3][0]!=s[n//3][0] and s[2*n//3][0]!=s[0][0]):
flag=1
r, g, b = 0, 0, 0
if s[0][0] == 'R':
r = 1
elif s[0][0] == 'G':
g = 1
else:
b = 1
for i in range(n//3):
for j in range(m):
if s[i][j] == 'G' and g != 1:
flag = 1
elif s[i][j] == 'R' and r != 1:
flag = 1
elif s[i][j] == 'B' and b != 1:
flag = 1
if s[n//3][0] == 'R':
if r == 1:
flag = 1
r = 1
g, b = 0, 0
elif s[n//3][0] == 'G':
if g == 1:
flag = 1
g = 1
r, b = 0, 0
else:
if b == 1:
flag = 1
b = 1
r, g = 0, 0
for i in range(n//3, 2*n//3):
for j in range(m):
if s[i][j] == 'G' and g != 1:
flag = 1
elif s[i][j] == 'R' and r != 1:
flag = 1
elif s[i][j] == 'B' and b != 1:
flag = 1
if s[2*n//3][0] == 'R':
if r == 1:
flag = 1
r = 1
g, b = 0, 0
elif s[2*n//3][0] == 'G':
if g == 1:
flag = 1
g=1
r, b = 0, 0
else:
if b == 1:
flag = 1
b = 1
r, g = 0, 0
for i in range(2*n//3, n):
for j in range(m):
if s[i][j] == 'G' and g != 1:
flag = 1
elif s[i][j] == 'R' and r != 1:
flag = 1
elif s[i][j] == 'B' and b != 1:
flag = 1
if flag == 0:
print('YES')
exit()
flag = 0
if (m % 3 == 0):
if not (s[0][0]!=s[0][m//3] and s[0][2*m//3]!=s[0][m//3] and s[0][0]!=s[0][2*m//3]):
flag=1
r, g, b = 0, 0, 0
if s[0][0] == 'R':
r += 1
elif s[0][0] == 'G':
g += 1
else:
b += 1
for j in range(m//3):
for i in range(n):
if s[i][j] == 'G' and g != 1:
flag = 1
elif s[i][j] == 'R' and r != 1:
flag = 1
elif s[i][j] == 'B' and b != 1:
flag = 1
if s[0][m//3] == 'R':
if r == 1:
flag = 1
r = 1
g, b = 0, 0
elif s[0][m//3] == 'G':
if g == 1:
flag = 1
g = 1
r, b = 0, 0
else:
if b == 1:
flag = 1
b = 1
r, g = 0, 0
for j in range(m//3, 2*m//3):
for i in range(n):
if s[i][j] == 'G' and g != 1:
flag = 1
elif s[i][j] == 'R' and r != 1:
flag = 1
elif s[i][j] == 'B' and b != 1:
flag = 1
if s[0][2*m//3] == 'R':
if r == 1:
flag = 1
r = 1
g, b = 0, 0
elif s[0][2*m//3] == 'G':
if g == 1:
flag = 1
g=1
r, b = 0, 0
else:
if b == 1:
flag = 1
b = 1
r, g = 0, 0
for j in range(2*m//3, m):
for i in range(n):
if s[i][j] == 'G' and g != 1:
flag = 1
elif s[i][j] == 'R' and r != 1:
flag = 1
elif s[i][j] == 'B' and b != 1:
flag = 1
if flag == 0:
print('YES')
exit()
print('NO')
```
| 1,392 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The flag of Berland is such rectangular field n Γ m that satisfies following conditions:
* Flag consists of three colors which correspond to letters 'R', 'G' and 'B'.
* Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has exactly one color.
* Each color should be used in exactly one stripe.
You are given a field n Γ m, consisting of characters 'R', 'G' and 'B'. Output "YES" (without quotes) if this field corresponds to correct flag of Berland. Otherwise, print "NO" (without quotes).
Input
The first line contains two integer numbers n and m (1 β€ n, m β€ 100) β the sizes of the field.
Each of the following n lines consisting of m characters 'R', 'G' and 'B' β the description of the field.
Output
Print "YES" (without quotes) if the given field corresponds to correct flag of Berland . Otherwise, print "NO" (without quotes).
Examples
Input
6 5
RRRRR
RRRRR
BBBBB
BBBBB
GGGGG
GGGGG
Output
YES
Input
4 3
BRG
BRG
BRG
BRG
Output
YES
Input
6 7
RRRGGGG
RRRGGGG
RRRGGGG
RRRBBBB
RRRBBBB
RRRBBBB
Output
NO
Input
4 4
RRRR
RRRR
BBBB
GGGG
Output
NO
Note
The field in the third example doesn't have three parralel stripes.
Rows of the field in the fourth example are parralel to each other and to borders. But they have different heights β 2, 1 and 1.
Tags: brute force, implementation
Correct Solution:
```
import sys
#import random
from bisect import bisect_left as lb
from collections import deque
#sys.setrecursionlimit(10**8)
from queue import PriorityQueue as pq
from math import *
input_ = lambda: sys.stdin.readline().strip("\r\n")
ii = lambda : int(input_())
il = lambda : list(map(int, input_().split()))
ilf = lambda : list(map(float, input_().split()))
ip = lambda : input_()
fi = lambda : float(input_())
ap = lambda ab,bc,cd : ab[bc].append(cd)
li = lambda : list(input_())
pr = lambda x : print(x)
prinT = lambda x : print(x)
f = lambda : sys.stdout.flush()
inv =lambda x:pow(x,mod-2,mod)
mod = 10**9 + 7
n,m = il()
a = []
for i in range (n) :
a.append(list(ip()))
if (n%3 != 0 and m%3 != 0) :
print("NO")
exit(0)
fl = 1
if (n%3 == 0) :
x = n//3
d = {}
for k in range (3) :
i = 0 + x*k
ch = a[i][0]
if (d.get(ch)) :
fl = 0
break
for i1 in range (x) :
for j in range (m) :
if (ch != a[i1+i][j]) :
fl = 0
break
if (fl == 0) :
break
d[ch] = 1
if fl :
print("YES")
exit(0)
if (m%3 == 0) :
x = m//3
d = {}
fl = 1
for k in range (3) :
i = 0 + x*k
ch = a[0][i]
if (d.get(ch)) :
fl = 0
break
for i1 in range (x) :
for j in range (n) :
if (ch != a[j][i1+i]) :
fl = 0
break
if (fl == 0) :
break
d[ch] = 1
if (fl) :
print("YES")
exit(0)
print("NO")
```
| 1,393 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The flag of Berland is such rectangular field n Γ m that satisfies following conditions:
* Flag consists of three colors which correspond to letters 'R', 'G' and 'B'.
* Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has exactly one color.
* Each color should be used in exactly one stripe.
You are given a field n Γ m, consisting of characters 'R', 'G' and 'B'. Output "YES" (without quotes) if this field corresponds to correct flag of Berland. Otherwise, print "NO" (without quotes).
Input
The first line contains two integer numbers n and m (1 β€ n, m β€ 100) β the sizes of the field.
Each of the following n lines consisting of m characters 'R', 'G' and 'B' β the description of the field.
Output
Print "YES" (without quotes) if the given field corresponds to correct flag of Berland . Otherwise, print "NO" (without quotes).
Examples
Input
6 5
RRRRR
RRRRR
BBBBB
BBBBB
GGGGG
GGGGG
Output
YES
Input
4 3
BRG
BRG
BRG
BRG
Output
YES
Input
6 7
RRRGGGG
RRRGGGG
RRRGGGG
RRRBBBB
RRRBBBB
RRRBBBB
Output
NO
Input
4 4
RRRR
RRRR
BBBB
GGGG
Output
NO
Note
The field in the third example doesn't have three parralel stripes.
Rows of the field in the fourth example are parralel to each other and to borders. But they have different heights β 2, 1 and 1.
Tags: brute force, implementation
Correct Solution:
```
def c(f, n, m):
if n % 3 != 0:return 0
s=n//3;s=f[0],f[s],f[2*s]
if set(s)!=set(map(lambda x:x*m,'RGB')):return 0
for i in range(n):
if f[i] != s[i*3 // n]:return 0
return 1
n,m=map(int, input().split())
f=[input() for _ in range(n)]
print('Yes'if c(f,n,m) or c([''.join(f[j][i] for j in range(n)) for i in range(m)],m,n)else'No')
```
| 1,394 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The flag of Berland is such rectangular field n Γ m that satisfies following conditions:
* Flag consists of three colors which correspond to letters 'R', 'G' and 'B'.
* Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has exactly one color.
* Each color should be used in exactly one stripe.
You are given a field n Γ m, consisting of characters 'R', 'G' and 'B'. Output "YES" (without quotes) if this field corresponds to correct flag of Berland. Otherwise, print "NO" (without quotes).
Input
The first line contains two integer numbers n and m (1 β€ n, m β€ 100) β the sizes of the field.
Each of the following n lines consisting of m characters 'R', 'G' and 'B' β the description of the field.
Output
Print "YES" (without quotes) if the given field corresponds to correct flag of Berland . Otherwise, print "NO" (without quotes).
Examples
Input
6 5
RRRRR
RRRRR
BBBBB
BBBBB
GGGGG
GGGGG
Output
YES
Input
4 3
BRG
BRG
BRG
BRG
Output
YES
Input
6 7
RRRGGGG
RRRGGGG
RRRGGGG
RRRBBBB
RRRBBBB
RRRBBBB
Output
NO
Input
4 4
RRRR
RRRR
BBBB
GGGG
Output
NO
Note
The field in the third example doesn't have three parralel stripes.
Rows of the field in the fourth example are parralel to each other and to borders. But they have different heights β 2, 1 and 1.
Tags: brute force, implementation
Correct Solution:
```
import sys
#sys.stdin = open("input2","r")
n,m = map(int,input().split())
s = []
for i in range(n):
string = input()
s.append(string)
no = 0
# row mix check
r_mix = 0
for i in range(n):
cnt_r = s[i].count('R')
cnt_b = s[i].count('B')
cnt_g = s[i].count('G')
if ((cnt_r and cnt_b) or (cnt_b and cnt_g) or (cnt_g and cnt_r) ):
r_mix = 1
# col mix check
c_mix = 0
for j in range(m):
cnt_r = cnt_b = cnt_g = 0
for i in range(n):
if (s[i][j] == 'R'):
cnt_r += 1
elif (s[i][j] == 'B'):
cnt_b += 1
elif(s[i][j] == 'G'):
cnt_g += 1
if ((cnt_r and cnt_b) or (cnt_b and cnt_g) or (cnt_g and cnt_r) ):
c_mix = 1
if (r_mix == 1 and c_mix == 1) or ( r_mix == 0 and c_mix == 0):
no = 1
if(r_mix == 1):
cnt_b = cnt_g = cnt_r = 0
if s[0][0] == 'R':
cnt_r += 1
elif s[0][0] == 'G':
cnt_g += 1
elif s[0][0] == 'B':
cnt_b += 1
f,c = -1,1
for j in range(0,m-1):
if s[0][j] == s[0][j+1]:
c += 1
else:
if s[0][j+1] == 'R':
cnt_r += 1
elif s[0][j + 1] == 'G':
cnt_g += 1
elif s[0][j + 1] == 'B':
cnt_b += 1
if f == -1:
f = c
if f != c:
no = 1
break
c = 1
if ((f != c) or (cnt_r != 1 or cnt_b != 1 or cnt_g != 1)):
no = 1
if (c_mix):
f = -1
c = 1
cnt_b = 0
cnt_g = 0
cnt_r = 0
if s[0][0] == 'R':
cnt_r += 1
elif s[0][0] == 'G':
cnt_g += 1
elif s[0][0] == 'B':
cnt_b += 1
for i in range(0, n-1):
if s[i][0] == s[i+1][0]:
c += 1
#print('c',c)
else:
if s[i + 1][0] == 'R':
cnt_r += 1
elif s[i + 1][0] == 'G':
cnt_g += 1
elif s[i + 1][0] == 'B':
cnt_b += 1
if f == -1:
f = c
#print('f',f)
if f != c:
#print(f,c)
no = 1
break
c = 1
#print(cnt_r,cnt_b,cnt_g)
if ((f != c) or (cnt_r != 1 or cnt_b != 1 or cnt_g != 1)):
no = 1
if no == 1:
print('NO')
else:
print('YES')
```
| 1,395 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The flag of Berland is such rectangular field n Γ m that satisfies following conditions:
* Flag consists of three colors which correspond to letters 'R', 'G' and 'B'.
* Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has exactly one color.
* Each color should be used in exactly one stripe.
You are given a field n Γ m, consisting of characters 'R', 'G' and 'B'. Output "YES" (without quotes) if this field corresponds to correct flag of Berland. Otherwise, print "NO" (without quotes).
Input
The first line contains two integer numbers n and m (1 β€ n, m β€ 100) β the sizes of the field.
Each of the following n lines consisting of m characters 'R', 'G' and 'B' β the description of the field.
Output
Print "YES" (without quotes) if the given field corresponds to correct flag of Berland . Otherwise, print "NO" (without quotes).
Examples
Input
6 5
RRRRR
RRRRR
BBBBB
BBBBB
GGGGG
GGGGG
Output
YES
Input
4 3
BRG
BRG
BRG
BRG
Output
YES
Input
6 7
RRRGGGG
RRRGGGG
RRRGGGG
RRRBBBB
RRRBBBB
RRRBBBB
Output
NO
Input
4 4
RRRR
RRRR
BBBB
GGGG
Output
NO
Note
The field in the third example doesn't have three parralel stripes.
Rows of the field in the fourth example are parralel to each other and to borders. But they have different heights β 2, 1 and 1.
Tags: brute force, implementation
Correct Solution:
```
[n,m] = [int(i) for i in input().split()]
flag = []
flip_flag = []
for i in range(m):
flip_flag.append([])
tmp = n
while tmp:
tmp -= 1
flag.append(list(input()))
for i in range(m):
flip_flag[i].append(flag[-1][i])
if len(set(flag[0])) != 1:
flag = flip_flag
strip_count = {}
valid = True
strip_count[flag[0][0]]=1
if len(set(flag[0])) != 1:
valid = False
for i in range(1, len(flag)):
if len(set(flag[i])) != 1 or valid == False:
valid = False
break
if flag[i][0] not in strip_count.keys():
strip_count[flag[i][0]] = 1
elif flag[i][0] != flag[i-1][0]:
valid = False
break
else:
strip_count[flag[i][0]] += 1
if len(set(strip_count.values())) != 1:
valid = False
if not(all(i in strip_count.keys() for i in ['R','G','B']) and len(set(strip_count.keys())) == 3):
valid = False
print('YES' if valid else 'NO')
```
| 1,396 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The flag of Berland is such rectangular field n Γ m that satisfies following conditions:
* Flag consists of three colors which correspond to letters 'R', 'G' and 'B'.
* Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has exactly one color.
* Each color should be used in exactly one stripe.
You are given a field n Γ m, consisting of characters 'R', 'G' and 'B'. Output "YES" (without quotes) if this field corresponds to correct flag of Berland. Otherwise, print "NO" (without quotes).
Input
The first line contains two integer numbers n and m (1 β€ n, m β€ 100) β the sizes of the field.
Each of the following n lines consisting of m characters 'R', 'G' and 'B' β the description of the field.
Output
Print "YES" (without quotes) if the given field corresponds to correct flag of Berland . Otherwise, print "NO" (without quotes).
Examples
Input
6 5
RRRRR
RRRRR
BBBBB
BBBBB
GGGGG
GGGGG
Output
YES
Input
4 3
BRG
BRG
BRG
BRG
Output
YES
Input
6 7
RRRGGGG
RRRGGGG
RRRGGGG
RRRBBBB
RRRBBBB
RRRBBBB
Output
NO
Input
4 4
RRRR
RRRR
BBBB
GGGG
Output
NO
Note
The field in the third example doesn't have three parralel stripes.
Rows of the field in the fourth example are parralel to each other and to borders. But they have different heights β 2, 1 and 1.
Submitted Solution:
```
n,m=map(int,input().split())
ls=[]
for i in range(n):
s=input()
ls.append(s)
#check for horizontal strips
horizontal=[]
f1=True
for i in range(n):
if(ls[i]==ls[i][0]*len(ls[i])):
if(i==0):
horizontal.append([ls[i],1])
elif(ls[i]==horizontal[-1][0]):
horizontal[-1][1]+=1
else:
horizontal.append([ls[i],1])
else:
f1=False
break
if(len(horizontal)==3 and horizontal[0][1]==horizontal[1][1]==horizontal[2][1]):
if(horizontal[0][0]!=horizontal[1][0] and horizontal[0][0]!=horizontal[2][0] and horizontal[1][0]!=horizontal[2][0]):
s=""
else:
f1=False
else:
f1=False
new_ls=["" for i in range(m)]
for i in range(n):
for j in range(m):
new_ls[j]+=ls[i][j]
ls=new_ls
#check for horizontal strips
horizontal=[]
f2=True
for i in range(m):
if(ls[i]==ls[i][0]*len(ls[i])):
if(i==0):
horizontal.append([ls[i],1])
elif(ls[i]==horizontal[-1][0]):
horizontal[-1][1]+=1
else:
horizontal.append([ls[i],1])
else:
f2=False
break
if(len(horizontal)==3 and horizontal[0][1]==horizontal[1][1]==horizontal[2][1]):
if(horizontal[0][0]!=horizontal[1][0] and horizontal[0][0]!=horizontal[2][0] and horizontal[1][0]!=horizontal[2][0]):
s=""
else:
f2=False
else:
f2=False
if(f1 or f2):print("YES")
else:print("NO")
```
Yes
| 1,397 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The flag of Berland is such rectangular field n Γ m that satisfies following conditions:
* Flag consists of three colors which correspond to letters 'R', 'G' and 'B'.
* Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has exactly one color.
* Each color should be used in exactly one stripe.
You are given a field n Γ m, consisting of characters 'R', 'G' and 'B'. Output "YES" (without quotes) if this field corresponds to correct flag of Berland. Otherwise, print "NO" (without quotes).
Input
The first line contains two integer numbers n and m (1 β€ n, m β€ 100) β the sizes of the field.
Each of the following n lines consisting of m characters 'R', 'G' and 'B' β the description of the field.
Output
Print "YES" (without quotes) if the given field corresponds to correct flag of Berland . Otherwise, print "NO" (without quotes).
Examples
Input
6 5
RRRRR
RRRRR
BBBBB
BBBBB
GGGGG
GGGGG
Output
YES
Input
4 3
BRG
BRG
BRG
BRG
Output
YES
Input
6 7
RRRGGGG
RRRGGGG
RRRGGGG
RRRBBBB
RRRBBBB
RRRBBBB
Output
NO
Input
4 4
RRRR
RRRR
BBBB
GGGG
Output
NO
Note
The field in the third example doesn't have three parralel stripes.
Rows of the field in the fourth example are parralel to each other and to borders. But they have different heights β 2, 1 and 1.
Submitted Solution:
```
height, width = map(int, input().split())
a = [input() for i in range(height)]
c = {'r': 0, 'g': 0, 'b': 0}
p = {'r': 0, 'g': 0, 'b': 0}
color = {'r': False, 'g': False, 'b': False}
horizontal, vertical = True, False
for i in range(height):
for j in range(width):
color[a[i][j].lower()] = True
for i in range(height):
for j in range(1, width):
if a[i][j] != a[i][j - 1]:
horizontal = False
break
c[a[i][j].lower()] += 1
if not horizontal:
vertical = True
for key in c.keys():
c[key] = 0
for i in range(width):
for j in range(1, height):
if a[j][i] != a[j - 1][i]:
vertical = False
break
c[a[j][i].lower()] += 1
prev = None
if horizontal:
for i in range(height):
if prev is None:
prev = a[i][0].lower()
c[a[i][0].lower()] += 1
p[a[i][0].lower()] += 1
else:
if prev != a[i][0].lower():
p[a[i][0].lower()] += 1
if p[a[i][0].lower()] >= 2:
print('NO')
exit()
prev = a[i][0].lower()
c[a[i][0].lower()] += 1
elif vertical:
for i in range(width):
if prev is None:
prev = a[0][i].lower()
c[a[0][i].lower()] += 1
else:
if prev != a[0][i].lower():
p[a[0][i].lower()] += 1
if p[a[0][i].lower()] >= 2:
print('NO')
exit()
prev = a[0][i].lower()
c[a[0][i].lower()] += 1
else:
print('NO')
exit()
if c['r'] == c['g'] == c['b'] and color['r'] and color['g'] and color['b']:
print('YES')
else:
print('NO')
```
Yes
| 1,398 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The flag of Berland is such rectangular field n Γ m that satisfies following conditions:
* Flag consists of three colors which correspond to letters 'R', 'G' and 'B'.
* Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has exactly one color.
* Each color should be used in exactly one stripe.
You are given a field n Γ m, consisting of characters 'R', 'G' and 'B'. Output "YES" (without quotes) if this field corresponds to correct flag of Berland. Otherwise, print "NO" (without quotes).
Input
The first line contains two integer numbers n and m (1 β€ n, m β€ 100) β the sizes of the field.
Each of the following n lines consisting of m characters 'R', 'G' and 'B' β the description of the field.
Output
Print "YES" (without quotes) if the given field corresponds to correct flag of Berland . Otherwise, print "NO" (without quotes).
Examples
Input
6 5
RRRRR
RRRRR
BBBBB
BBBBB
GGGGG
GGGGG
Output
YES
Input
4 3
BRG
BRG
BRG
BRG
Output
YES
Input
6 7
RRRGGGG
RRRGGGG
RRRGGGG
RRRBBBB
RRRBBBB
RRRBBBB
Output
NO
Input
4 4
RRRR
RRRR
BBBB
GGGG
Output
NO
Note
The field in the third example doesn't have three parralel stripes.
Rows of the field in the fourth example are parralel to each other and to borders. But they have different heights β 2, 1 and 1.
Submitted Solution:
```
#python 3.5.2
#ΠΠ²ΠΎΠ΄ n m ΠΈ ΡΠ°ΠΌΠΈΡ
ΡΠ²Π΅ΡΠΎΠ²
vv = input()
n = int(vv[0:vv.find(' ')])
m = int(vv[vv.find(' '):])
x = ''
for mm in range(n):
x += input()
col = 0
row = 0
res = True
types = 0
if x[0] == x[n*m - m]:
if m % 3 == 0:
col = m//3
row = n
types = 1
else:
res = False
else:
if x[0] == x[m - 1]:
if n%3 == 0:
col = m
row = n//3
types = 2
else:
res = False
else:
res = False
c1 = ''
c2 = ''
c3 = ''
if res:
if types == 1:
for i in range(row):
for j in range(col):
c1 += x[j + m*i]
for i in range(row):
for j in range(col, col*2):
c2 += x[j + m*i]
for i in range(row):
for j in range(col*2, col*3):
c3 += x[j + m*i]
if types == 2:
for i in range(m*n//3):
c1 += x[i]
for i in range(m*n//3, m*n//3*2):
c2 += x[i]
for i in range(m*n//3*2, m*n):
c3 += x[i]
if res:
let1 = c1[0]
for i in c1:
if i != let1:
res = False
break
if res:
let2 = c2[0]
if let1 == let2:
res =False
else:
for i in c2:
if i != let2:
res = False
break
if res:
let3 = c3[0]
if let1 == let3 or let2 == let3:
res = False
else:
for i in c3:
if i != let3:
res = False
break
if res:
print('YES')
else:
print('NO')
```
Yes
| 1,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.