text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Karen is getting ready for a new school day!
<image>
It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.
What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome?
Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.
Input
The first and only line of input contains a single string in the format hh:mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59).
Output
Output a single integer on a line by itself, the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome.
Examples
Input
05:39
Output
11
Input
13:31
Output
0
Input
23:59
Output
1
Note
In the first test case, the minimum number of minutes Karen should sleep for is 11. She can wake up at 05:50, when the time is a palindrome.
In the second test case, Karen can wake up immediately, as the current time, 13:31, is already a palindrome.
In the third test case, the minimum number of minutes Karen should sleep for is 1 minute. She can wake up at 00:00, when the time is a palindrome.
Tags: brute force, implementation
Correct Solution:
```
h, m = input().split(':')
pos_hours = list(range(0, 6)) + list(range(10, 16)) + \
list(range(20, 25))
if int(h[1] + h[0]) == int(m):
print(0)
else:
if int(h[1] + h[0]) > int(m) and int(h) in pos_hours:
print(int(h[1] + h[0]) - int(m))
else:
i = 0
while pos_hours[i] <= int(h):
i += 1
if pos_hours[i] == 24:
i = 0
next_hour = "{:0>2}".format(pos_hours[i])
#print(next_hour)
minutes = 60-int(m) + int(next_hour[1] + next_hour[0]) + \
(int(next_hour) - int(h) - 1)*60
if (int(next_hour) - int(h) - 1 < 0):
minutes += 1440
print(minutes)
'''if int(m[1]+m[0]) == int(h):
print(0)
else:
if int(m) < int(h[1]+h[0]):
print(int(h[1]+h[0]) - int(m))
else:'''
```
| 4,700 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Karen is getting ready for a new school day!
<image>
It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.
What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome?
Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.
Input
The first and only line of input contains a single string in the format hh:mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59).
Output
Output a single integer on a line by itself, the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome.
Examples
Input
05:39
Output
11
Input
13:31
Output
0
Input
23:59
Output
1
Note
In the first test case, the minimum number of minutes Karen should sleep for is 11. She can wake up at 05:50, when the time is a palindrome.
In the second test case, Karen can wake up immediately, as the current time, 13:31, is already a palindrome.
In the third test case, the minimum number of minutes Karen should sleep for is 1 minute. She can wake up at 00:00, when the time is a palindrome.
Tags: brute force, implementation
Correct Solution:
```
h,m=map(int,input().split(':'))
i=0
a=h
b=m
while(1):
if(h%10==m//10 and h//10==m%10):
break
m+=1
i+=1
if(m>59):
h+=1
h=h%24
m=0
print(i)
```
| 4,701 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Karen is getting ready for a new school day!
<image>
It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.
What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome?
Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.
Input
The first and only line of input contains a single string in the format hh:mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59).
Output
Output a single integer on a line by itself, the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome.
Examples
Input
05:39
Output
11
Input
13:31
Output
0
Input
23:59
Output
1
Note
In the first test case, the minimum number of minutes Karen should sleep for is 11. She can wake up at 05:50, when the time is a palindrome.
In the second test case, Karen can wake up immediately, as the current time, 13:31, is already a palindrome.
In the third test case, the minimum number of minutes Karen should sleep for is 1 minute. She can wake up at 00:00, when the time is a palindrome.
Tags: brute force, implementation
Correct Solution:
```
time = input()
x = int(time[0])
y = (int(time[3])*10) + int(time[4])
z = int(time[1])
temp = (z*10) + x
if x == 0:
if z < 5:
if y > temp:
t1 = ((z+1)*10) + x
print((60 - y)+t1)
else:
print(temp - y)
elif z == 5:
if y <= temp:
print(temp - y)
else:
_min = 60 - y
_min1 = 60 * (10 - z - 1)
print(_min + _min1 + 1)
elif z > 5:
_min = 60 - y
_min1 = 60 * (10 - z - 1)
print(_min+_min1+1)
elif x == 1:
if z < 5:
if y > temp:
t1 = ((z+1)*10) + x
print((60 - y)+t1)
else:
print(temp - y)
elif z == 5:
if y <= temp:
print(temp-y)
else:
_min = 60 - y
hr = (x * 10) + z
_min1 = 60 * (20 - hr - 1)
print(_min + _min1 + 2)
elif z > 5:
_min = 60 - y
hr = (x*10) + z
_min1 = 60 * (20 - hr - 1)
print(_min+_min1+2)
elif x == 2:
if z <= 2:
if y > temp:
t1 = ((z+1)*10) + x
print((60 - y)+t1)
else:
print(temp - y)
if z == 3:
if y <= temp:
print(temp - y)
else:
print(60 - y)
```
| 4,702 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Karen is getting ready for a new school day!
<image>
It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.
What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome?
Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.
Input
The first and only line of input contains a single string in the format hh:mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59).
Output
Output a single integer on a line by itself, the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome.
Examples
Input
05:39
Output
11
Input
13:31
Output
0
Input
23:59
Output
1
Note
In the first test case, the minimum number of minutes Karen should sleep for is 11. She can wake up at 05:50, when the time is a palindrome.
In the second test case, Karen can wake up immediately, as the current time, 13:31, is already a palindrome.
In the third test case, the minimum number of minutes Karen should sleep for is 1 minute. She can wake up at 00:00, when the time is a palindrome.
Tags: brute force, implementation
Correct Solution:
```
rawtime = input()
hours = int(rawtime[0:2])
minutes = int(rawtime[3:5])
def isPal(s):
a = list(s)
a.reverse()
return list(s) == a
def formatTime(hours, minutes):
time = ''
if hours < 10:
time += '0'
time += str(hours)
time += ':'
if minutes < 10:
time += '0'
time += str(minutes)
return time
count = 0
while not isPal(formatTime(hours, minutes)):
count += 1
if minutes < 59:
minutes += 1
else:
if hours < 23:
hours += 1
minutes = 0
else:
hours = 0
minutes = 0
print(count)
```
| 4,703 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Karen is getting ready for a new school day!
<image>
It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.
What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome?
Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.
Input
The first and only line of input contains a single string in the format hh:mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59).
Output
Output a single integer on a line by itself, the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome.
Examples
Input
05:39
Output
11
Input
13:31
Output
0
Input
23:59
Output
1
Note
In the first test case, the minimum number of minutes Karen should sleep for is 11. She can wake up at 05:50, when the time is a palindrome.
In the second test case, Karen can wake up immediately, as the current time, 13:31, is already a palindrome.
In the third test case, the minimum number of minutes Karen should sleep for is 1 minute. She can wake up at 00:00, when the time is a palindrome.
Tags: brute force, implementation
Correct Solution:
```
h,m = map(int,input().split(':'))
count = 0
while h%10 != m//10 or h//10 != m%10:
m+=1
count+=1
if m == 60:
h+=1
h%=24
m = 0
print(count)
```
| 4,704 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Karen is getting ready for a new school day!
<image>
It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.
What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome?
Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.
Input
The first and only line of input contains a single string in the format hh:mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59).
Output
Output a single integer on a line by itself, the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome.
Examples
Input
05:39
Output
11
Input
13:31
Output
0
Input
23:59
Output
1
Note
In the first test case, the minimum number of minutes Karen should sleep for is 11. She can wake up at 05:50, when the time is a palindrome.
In the second test case, Karen can wake up immediately, as the current time, 13:31, is already a palindrome.
In the third test case, the minimum number of minutes Karen should sleep for is 1 minute. She can wake up at 00:00, when the time is a palindrome.
Tags: brute force, implementation
Correct Solution:
```
now = list(map(int, input().split(":")))
now = now[0] * 60 + now[1]
i = now
while True:
h = str(i // 60).rjust(2, '0')
m = str(i % 60).rjust(2, '0')
if h[::-1] == m:
print((i - now) % (24 * 60))
break
else:
i += 1
i %= (24 * 60)
```
| 4,705 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Karen is getting ready for a new school day!
<image>
It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.
What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome?
Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.
Input
The first and only line of input contains a single string in the format hh:mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59).
Output
Output a single integer on a line by itself, the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome.
Examples
Input
05:39
Output
11
Input
13:31
Output
0
Input
23:59
Output
1
Note
In the first test case, the minimum number of minutes Karen should sleep for is 11. She can wake up at 05:50, when the time is a palindrome.
In the second test case, Karen can wake up immediately, as the current time, 13:31, is already a palindrome.
In the third test case, the minimum number of minutes Karen should sleep for is 1 minute. She can wake up at 00:00, when the time is a palindrome.
Tags: brute force, implementation
Correct Solution:
```
import sys
import math
import itertools
import collections
def sieve(n):
prime = [True for i in range(n + 1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * 2, n + 1, p):
prime[i] = False
p += 1
prime[0] = prime[1] = False
r = [p for p in range(n + 1) if prime[p]]
return r
def divs(n, start=1):
r = []
for i in range(start, int(math.sqrt(n) + 1)):
if (n % i == 0):
if (n / i == i):
r.append(i)
else:
r.extend([i, n // i])
return r
def cdiv(n, k): return n // k + (n % k != 0)
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return list(map(int, input().split()))
def lcm(a, b): return abs(a * b) // math.gcd(a, b)
def wr(arr): return ''.join(map(str, arr))
def revn(n): return str(n)[::-1]
def prime(n):
if n == 2: return True
if n % 2 == 0 or n <= 1: return False
sqr = int(math.sqrt(n)) + 1
for d in range(3, sqr, 2):
if n % d == 0: return False
return True
def convn(number, base=3):
newnumber = ''
while number > 0:
newnumber = str(number % base) + newnumber
number //= base
return newnumber
def z(n):
if n < 10:
return '0' + str(n)
else:
return str(n)
hh, mm = map(int, input().split(':'))
ans = 0
while z(hh) != revn(z(mm)):
if mm + 1 == 60:
if hh == 23:
hh = 0
else:
hh += 1
mm = 0
else:
mm += 1
ans += 1
print(ans)
```
| 4,706 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Karen is getting ready for a new school day!
<image>
It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.
What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome?
Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.
Input
The first and only line of input contains a single string in the format hh:mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59).
Output
Output a single integer on a line by itself, the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome.
Examples
Input
05:39
Output
11
Input
13:31
Output
0
Input
23:59
Output
1
Note
In the first test case, the minimum number of minutes Karen should sleep for is 11. She can wake up at 05:50, when the time is a palindrome.
In the second test case, Karen can wake up immediately, as the current time, 13:31, is already a palindrome.
In the third test case, the minimum number of minutes Karen should sleep for is 1 minute. She can wake up at 00:00, when the time is a palindrome.
Submitted Solution:
```
def check(h,m):
s1 = chr(h%10+48)
h//=10
s1 += chr(h%10+48)
s1 = s1[::-1]
s2 = chr(m%10+48)
m//=10
s2 += chr(m%10+48)
s2 = s2[::-1]
if(s1[0]==s2[1] and s1[1]==s2[0]):
return True
else:
return False
h,m = map(int,input().split(':'))
ans = 0
while(True):
if(check(h,m)==True):
break
else:
ans+=1
m += 1
if(m==60):
h += 1
m = 0
if(h==24):
h = 0
print(ans)
```
Yes
| 4,707 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Karen is getting ready for a new school day!
<image>
It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.
What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome?
Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.
Input
The first and only line of input contains a single string in the format hh:mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59).
Output
Output a single integer on a line by itself, the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome.
Examples
Input
05:39
Output
11
Input
13:31
Output
0
Input
23:59
Output
1
Note
In the first test case, the minimum number of minutes Karen should sleep for is 11. She can wake up at 05:50, when the time is a palindrome.
In the second test case, Karen can wake up immediately, as the current time, 13:31, is already a palindrome.
In the third test case, the minimum number of minutes Karen should sleep for is 1 minute. She can wake up at 00:00, when the time is a palindrome.
Submitted Solution:
```
#
import sys
def minutos(hora):
a = int(hora[:2])
b = int(hora[3:])
return 60*a + b
palin = []
for i in range(0, 24):
hora = ""
if i < 10:
hora += "0"
hora += str(i)
if hora[::-1] < "60":
palin.append(hora + ":" + hora[::-1])
hora = sys.stdin.readline()
hora = hora[:-1]
greater = None
for index, x in enumerate(palin):
if hora <= x:
greater = index
break
if greater != None:
print(minutos(palin[greater]) - minutos(hora))
else:
print(minutos("24:00") - minutos(hora))
```
Yes
| 4,708 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Karen is getting ready for a new school day!
<image>
It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.
What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome?
Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.
Input
The first and only line of input contains a single string in the format hh:mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59).
Output
Output a single integer on a line by itself, the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome.
Examples
Input
05:39
Output
11
Input
13:31
Output
0
Input
23:59
Output
1
Note
In the first test case, the minimum number of minutes Karen should sleep for is 11. She can wake up at 05:50, when the time is a palindrome.
In the second test case, Karen can wake up immediately, as the current time, 13:31, is already a palindrome.
In the third test case, the minimum number of minutes Karen should sleep for is 1 minute. She can wake up at 00:00, when the time is a palindrome.
Submitted Solution:
```
s=list(map(int,input().split(':')))
i=0
while s[0]%10*10+s[0]//10!=s[1]:
i+=1
s[1]+=1
s[0]+=s[1]//60
s[1]%=60
s[0]%=24
print(i)
#print(' '.join([str(i) for i in s]))
```
Yes
| 4,709 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Karen is getting ready for a new school day!
<image>
It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.
What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome?
Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.
Input
The first and only line of input contains a single string in the format hh:mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59).
Output
Output a single integer on a line by itself, the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome.
Examples
Input
05:39
Output
11
Input
13:31
Output
0
Input
23:59
Output
1
Note
In the first test case, the minimum number of minutes Karen should sleep for is 11. She can wake up at 05:50, when the time is a palindrome.
In the second test case, Karen can wake up immediately, as the current time, 13:31, is already a palindrome.
In the third test case, the minimum number of minutes Karen should sleep for is 1 minute. She can wake up at 00:00, when the time is a palindrome.
Submitted Solution:
```
def isP(h,m):
return ''.join(reversed(h)) == m
def incH(h):
h = int(h) + 1
if h == 24:
h = 0
h = str(h)
if len(h) == 1:
h = "0" + h
return h
def incM(h,m):
m = int(m) + 1
if m == 60:
h = incH(h)
m = 0
m = str(m)
if len(m) == 1:
m = "0" + m
return h,m
h,m = input().split(":")
for i in range(3600):
if isP(h,m):
print(i)
import sys
sys.exit(0)
h, m = incM(h, m)
```
Yes
| 4,710 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Karen is getting ready for a new school day!
<image>
It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.
What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome?
Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.
Input
The first and only line of input contains a single string in the format hh:mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59).
Output
Output a single integer on a line by itself, the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome.
Examples
Input
05:39
Output
11
Input
13:31
Output
0
Input
23:59
Output
1
Note
In the first test case, the minimum number of minutes Karen should sleep for is 11. She can wake up at 05:50, when the time is a palindrome.
In the second test case, Karen can wake up immediately, as the current time, 13:31, is already a palindrome.
In the third test case, the minimum number of minutes Karen should sleep for is 1 minute. She can wake up at 00:00, when the time is a palindrome.
Submitted Solution:
```
a=input()
t1=a[0:2]
t2=a[3:5]
step=0
h=int(t1)
m=int(t2)
aim=int(t1[1]+t1[0])
if aim>=m and aim<=59:
print(aim-m)
else:
h+=1
if h==24:
h=0
if h>=10:
t1=str(h)
else:
t1='0'+str(h)
aim=int(t1[1]+t1[0])
print(aim+60-m)
```
No
| 4,711 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Karen is getting ready for a new school day!
<image>
It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.
What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome?
Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.
Input
The first and only line of input contains a single string in the format hh:mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59).
Output
Output a single integer on a line by itself, the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome.
Examples
Input
05:39
Output
11
Input
13:31
Output
0
Input
23:59
Output
1
Note
In the first test case, the minimum number of minutes Karen should sleep for is 11. She can wake up at 05:50, when the time is a palindrome.
In the second test case, Karen can wake up immediately, as the current time, 13:31, is already a palindrome.
In the third test case, the minimum number of minutes Karen should sleep for is 1 minute. She can wake up at 00:00, when the time is a palindrome.
Submitted Solution:
```
def parse(n):
if n[0] == '0':
return int(n[1])
else: return int(n)
def Func(time):
if time == time[::-1]:
return 0
a , b = time.split(':')
r = a[::-1]
if a == '23':
return 60 - int(b)
ls = [(1,10), (2,20), (3,30), (4,40), (5,50), (10,1), (11,11),(12,21),
(13,31), (14,42), (15,51), (20,2), (21, 12) , (22,22)]
c , d = parse(a), parse(b)
for i in range(len(ls)):
if ls[i][0] >= c:
return ls[i][0] * 60 + ls[i][1] - (c*60 + d)
print(Func(input()))
```
No
| 4,712 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Karen is getting ready for a new school day!
<image>
It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.
What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome?
Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.
Input
The first and only line of input contains a single string in the format hh:mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59).
Output
Output a single integer on a line by itself, the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome.
Examples
Input
05:39
Output
11
Input
13:31
Output
0
Input
23:59
Output
1
Note
In the first test case, the minimum number of minutes Karen should sleep for is 11. She can wake up at 05:50, when the time is a palindrome.
In the second test case, Karen can wake up immediately, as the current time, 13:31, is already a palindrome.
In the third test case, the minimum number of minutes Karen should sleep for is 1 minute. She can wake up at 00:00, when the time is a palindrome.
Submitted Solution:
```
def isPalindrome(st):
for idx in range(0,(len(st)//2)):
if st[idx] != st[len(st) - idx - 1]:
return False
return True
def incrementTime(st):
hh,mm = st.split(":")
mm = int(mm)
hh = int(hh)
mm += 1
if mm > 59:
mm = 0
hh += 1
mm = str(mm)
hh = str(hh)
if len(mm) < 2:
mm = "0" + mm
elif len(hh) < 2:
hh = "0" + hh
return ":".join([hh,mm])
def main(s):
count = 0
while(not isPalindrome(s)):
s = incrementTime(s)
count += 1
print(count)
main(input())
```
No
| 4,713 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Karen is getting ready for a new school day!
<image>
It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.
What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome?
Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.
Input
The first and only line of input contains a single string in the format hh:mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59).
Output
Output a single integer on a line by itself, the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome.
Examples
Input
05:39
Output
11
Input
13:31
Output
0
Input
23:59
Output
1
Note
In the first test case, the minimum number of minutes Karen should sleep for is 11. She can wake up at 05:50, when the time is a palindrome.
In the second test case, Karen can wake up immediately, as the current time, 13:31, is already a palindrome.
In the third test case, the minimum number of minutes Karen should sleep for is 1 minute. She can wake up at 00:00, when the time is a palindrome.
Submitted Solution:
```
def reverse(s):
if s < 10:
s = "0{}".format(s)
else:
s = str(s)
return int(s[::-1])
def main(s):
hh, mm = [int(item) for item in s.split(':')]
if hh == 23 and mm > 32:
return 60 - mm
elif 16 <= hh <= 19:
return (20 - hh) * 60 + 2 - mm
elif 6 <= hh <= 9:
return (10 - hh) * 60 + 1 - mm
elif reverse(hh) >= mm:
return reverse(hh) - mm
else:
return reverse(hh + 1) + 60 - mm
import sys
if sys.argv and sys.argv[-1] == 'test':
assert main('12:21') == 0
assert main('08:21') == 100
assert main('15:51') == 0
assert main('15:41') == 10
assert main('12:22') == 69
assert main('18:20') == 102
assert main('23:22') == 10
assert main('23:40') == 20
else:
print(main(input()))
```
No
| 4,714 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 100) — the number of baloons and friends.
Next line contains string s — colors of baloons.
Output
Answer to the task — «YES» or «NO» in a single line.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
4 2
aabb
Output
YES
Input
6 3
aacaab
Output
NO
Note
In the first sample Kefa can give 1-st and 3-rd baloon to the first friend, and 2-nd and 4-th to the second.
In the second sample Kefa needs to give to all his friends baloons of color a, but one baloon will stay, thats why answer is «NO».
Tags: brute force, implementation
Correct Solution:
```
d = {}
n, k = map(int, input().split())
s = input()
for i in s:
d[i] = d.get(i, 0)+1
# print(d)
m = max(d.values()) #2
for key in d: # a b
if d[key] == m:#
if d[key] > k:
print('NO')
else:
print('YES')
break
# How to count same colored balloons?
# we should count the same colored balloons and then if Samecoloredb <= friends then YES if > then NO
# d = {friends:colors}
```
| 4,715 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 100) — the number of baloons and friends.
Next line contains string s — colors of baloons.
Output
Answer to the task — «YES» or «NO» in a single line.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
4 2
aabb
Output
YES
Input
6 3
aacaab
Output
NO
Note
In the first sample Kefa can give 1-st and 3-rd baloon to the first friend, and 2-nd and 4-th to the second.
In the second sample Kefa needs to give to all his friends baloons of color a, but one baloon will stay, thats why answer is «NO».
Tags: brute force, implementation
Correct Solution:
```
#-------------Program--------------
#----Kuzlyaev-Nikita-Codeforces----
#-------------Training-------------
#----------------------------------
n,k=map(int,input().split())
s=list(str(input()))
p=list(set(s))
m=0
for i in range(len(p)):
if s.count(p[i])>k:
print("NO")
break
else:
print("YES")
```
| 4,716 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 100) — the number of baloons and friends.
Next line contains string s — colors of baloons.
Output
Answer to the task — «YES» or «NO» in a single line.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
4 2
aabb
Output
YES
Input
6 3
aacaab
Output
NO
Note
In the first sample Kefa can give 1-st and 3-rd baloon to the first friend, and 2-nd and 4-th to the second.
In the second sample Kefa needs to give to all his friends baloons of color a, but one baloon will stay, thats why answer is «NO».
Tags: brute force, implementation
Correct Solution:
```
'''input
4 2
aabb
'''
n, k = map(int, input().split())
s = input()
print("NO" if any(s.count(l) > k for l in set(s)) else "YES")
```
| 4,717 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 100) — the number of baloons and friends.
Next line contains string s — colors of baloons.
Output
Answer to the task — «YES» or «NO» in a single line.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
4 2
aabb
Output
YES
Input
6 3
aacaab
Output
NO
Note
In the first sample Kefa can give 1-st and 3-rd baloon to the first friend, and 2-nd and 4-th to the second.
In the second sample Kefa needs to give to all his friends baloons of color a, but one baloon will stay, thats why answer is «NO».
Tags: brute force, implementation
Correct Solution:
```
n,k = map(int, input().split())
s = input()
r = [0]*26
y=0
for i in s:
nomer = ord(i)-97
r[nomer] +=1
for i in range(len(r)):
if r[i] >k and r[i] !=0:
y+=1
if y>0:
print('NO')
elif y==0:
print('YES')
```
| 4,718 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 100) — the number of baloons and friends.
Next line contains string s — colors of baloons.
Output
Answer to the task — «YES» or «NO» in a single line.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
4 2
aabb
Output
YES
Input
6 3
aacaab
Output
NO
Note
In the first sample Kefa can give 1-st and 3-rd baloon to the first friend, and 2-nd and 4-th to the second.
In the second sample Kefa needs to give to all his friends baloons of color a, but one baloon will stay, thats why answer is «NO».
Tags: brute force, implementation
Correct Solution:
```
n, k = map(int, input().split())
b = list(input())
a = {}
s = 0
for i in b:
a[i] = a.get(i, 0) + 1
for i in a:
if a[i] > s:
s = a[i]
if s > k:
print('NO')
else:
print('YES')
```
| 4,719 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 100) — the number of baloons and friends.
Next line contains string s — colors of baloons.
Output
Answer to the task — «YES» or «NO» in a single line.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
4 2
aabb
Output
YES
Input
6 3
aacaab
Output
NO
Note
In the first sample Kefa can give 1-st and 3-rd baloon to the first friend, and 2-nd and 4-th to the second.
In the second sample Kefa needs to give to all his friends baloons of color a, but one baloon will stay, thats why answer is «NO».
Tags: brute force, implementation
Correct Solution:
```
n, k = map(int, input().split())
s = input()
l = set(list(s))
a = [s.count(i) for i in l]
if max(a) > k:
print('NO')
else:
print('YES')
```
| 4,720 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 100) — the number of baloons and friends.
Next line contains string s — colors of baloons.
Output
Answer to the task — «YES» or «NO» in a single line.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
4 2
aabb
Output
YES
Input
6 3
aacaab
Output
NO
Note
In the first sample Kefa can give 1-st and 3-rd baloon to the first friend, and 2-nd and 4-th to the second.
In the second sample Kefa needs to give to all his friends baloons of color a, but one baloon will stay, thats why answer is «NO».
Tags: brute force, implementation
Correct Solution:
```
n,k=map(int,input().split())
a=input()
d={}
for i in a:
d[i]=d.get(i,0)+1
for i in d:
if d[i]>k:
print('NO')
break
else:
print('YES')
# n,k=map(int,input().split())
# a=input()
# d={}
# kol=0
# kolkol=0
# for i in a:
# d[i]=d.get(i,0)+1
# print(d)
# for i in d:
# if d[i]%k==0:
# kol+=1
# for i in d:
# if d[i]==1:
# kolkol+=1
# if kol==k or kolkol==len(d):
# print('YES')
# else:
# print('NO')
```
| 4,721 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 100) — the number of baloons and friends.
Next line contains string s — colors of baloons.
Output
Answer to the task — «YES» or «NO» in a single line.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
4 2
aabb
Output
YES
Input
6 3
aacaab
Output
NO
Note
In the first sample Kefa can give 1-st and 3-rd baloon to the first friend, and 2-nd and 4-th to the second.
In the second sample Kefa needs to give to all his friends baloons of color a, but one baloon will stay, thats why answer is «NO».
Tags: brute force, implementation
Correct Solution:
```
n, k = list(map(int, input().split()))
s = list(input())
unique = set(s)
count = {}
for i in s:
count[i] = count.get(i, 0) + 1
values = [count[c] for c in unique]
values.sort(reverse=True)
assign = [[] for i in range(k)]
each = n//k
rem = n%k
for i in range(k):
for j in range(each):
for v in range(len(values)):
if(values[v] > 0 and v not in assign[i]):
assign[i].append(v)
values[v] -= 1
break
for v in range(len(values)):
while(values[v] > 0):
got = False
for i in range(k):
if(v not in assign[i]):
assign[i].append(v)
values[v] -= 1
got = True
break
if(got == False):
break
#print(assign, values)
ans = True
for v in range(len(values)):
if(values[v] > 0):
ans = False
break
if(ans == True):
print('YES')
else:
print('NO')
```
| 4,722 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 100) — the number of baloons and friends.
Next line contains string s — colors of baloons.
Output
Answer to the task — «YES» or «NO» in a single line.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
4 2
aabb
Output
YES
Input
6 3
aacaab
Output
NO
Note
In the first sample Kefa can give 1-st and 3-rd baloon to the first friend, and 2-nd and 4-th to the second.
In the second sample Kefa needs to give to all his friends baloons of color a, but one baloon will stay, thats why answer is «NO».
Submitted Solution:
```
n,k=map(int,input().split())
a=list(input())
b=list(set(a))
for i in range(len(b)):
if a.count(b[i])>k:
print('NO')
exit()
print('YES')
```
Yes
| 4,723 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 100) — the number of baloons and friends.
Next line contains string s — colors of baloons.
Output
Answer to the task — «YES» or «NO» in a single line.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
4 2
aabb
Output
YES
Input
6 3
aacaab
Output
NO
Note
In the first sample Kefa can give 1-st and 3-rd baloon to the first friend, and 2-nd and 4-th to the second.
In the second sample Kefa needs to give to all his friends baloons of color a, but one baloon will stay, thats why answer is «NO».
Submitted Solution:
```
msg = input().split()
n = int(msg[0])
k = int(msg[1])
msg = input()
msg = sorted(msg)
count = {}
for char in msg:
if char not in count:
count[char] = 1
else:
count[char] += 1
if max(count.values()) > k:
print ('NO')
else:
print ('YES')
```
Yes
| 4,724 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 100) — the number of baloons and friends.
Next line contains string s — colors of baloons.
Output
Answer to the task — «YES» or «NO» in a single line.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
4 2
aabb
Output
YES
Input
6 3
aacaab
Output
NO
Note
In the first sample Kefa can give 1-st and 3-rd baloon to the first friend, and 2-nd and 4-th to the second.
In the second sample Kefa needs to give to all his friends baloons of color a, but one baloon will stay, thats why answer is «NO».
Submitted Solution:
```
n, k = map(int, input().split())
s = list(input())
colors = set(s)
result = 'YES'
if result == 'YES':
for color in colors:
if s.count(color) > k:
result = 'NO'
break
print(result)
```
Yes
| 4,725 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 100) — the number of baloons and friends.
Next line contains string s — colors of baloons.
Output
Answer to the task — «YES» or «NO» in a single line.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
4 2
aabb
Output
YES
Input
6 3
aacaab
Output
NO
Note
In the first sample Kefa can give 1-st and 3-rd baloon to the first friend, and 2-nd and 4-th to the second.
In the second sample Kefa needs to give to all his friends baloons of color a, but one baloon will stay, thats why answer is «NO».
Submitted Solution:
```
##n = int(input())
##a = list(map(int, input().split()))
##print(' '.join(map(str, res)))
[n, k] = list(map(int, input().split()))
s = input()
h = [0 for i in range(26)]
for i in range(n):
h[ord(s[i])-ord('a')] += 1
hmax = 0
for i in range(26):
hmax = max(hmax, h[i])
if hmax > k:
print('NO')
exit(0)
print('YES')
```
Yes
| 4,726 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 100) — the number of baloons and friends.
Next line contains string s — colors of baloons.
Output
Answer to the task — «YES» or «NO» in a single line.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
4 2
aabb
Output
YES
Input
6 3
aacaab
Output
NO
Note
In the first sample Kefa can give 1-st and 3-rd baloon to the first friend, and 2-nd and 4-th to the second.
In the second sample Kefa needs to give to all his friends baloons of color a, but one baloon will stay, thats why answer is «NO».
Submitted Solution:
```
a, b = map(int, input().split())
c = list(input())
d = []
if a == b:
print("YES")
else:
if b * 2 != a:
b -= 1
for i in range(len(c)):
for j in range(len(c)):
if c[i] == c[j] and str(c[i]).isalpha() and str(c[j]).isalpha():
continue
elif c[i] != c[j] and str(c[i]).isalpha() and str(c[j]).isalpha():
d.append(c[i] + c[j])
c.pop(j)
c.insert(j, 1)
c.pop(i)
c.insert(i, 1)
if len(d) >= b:
print("YES")
else:
print("NO")
```
No
| 4,727 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 100) — the number of baloons and friends.
Next line contains string s — colors of baloons.
Output
Answer to the task — «YES» or «NO» in a single line.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
4 2
aabb
Output
YES
Input
6 3
aacaab
Output
NO
Note
In the first sample Kefa can give 1-st and 3-rd baloon to the first friend, and 2-nd and 4-th to the second.
In the second sample Kefa needs to give to all his friends baloons of color a, but one baloon will stay, thats why answer is «NO».
Submitted Solution:
```
n,k = map(int,input().split())
s = input()
s = [s.count(s[i]) for i in range(n) if s[i] not in s[:i]]
c = 0
for i in s:
if i%k!=0 and i>=k:
c+=1
if c==0:
print("YES")
else:
print("NO")
```
No
| 4,728 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 100) — the number of baloons and friends.
Next line contains string s — colors of baloons.
Output
Answer to the task — «YES» or «NO» in a single line.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
4 2
aabb
Output
YES
Input
6 3
aacaab
Output
NO
Note
In the first sample Kefa can give 1-st and 3-rd baloon to the first friend, and 2-nd and 4-th to the second.
In the second sample Kefa needs to give to all his friends baloons of color a, but one baloon will stay, thats why answer is «NO».
Submitted Solution:
```
# # --- Система регистрации (словарь)---
# keys = int(input())
# names = [input() for row in range(keys)]
# database = dict()
# for i in names:
# if i not in database:
# database[i] = 0
# print('OK')
# else:
# for k, val in database.items():
# if val >= 0 and k == i:
# val += 1
# database[i] = val
# print(k + str(val))
# # print(k + f'{val}')
# # --- Система регистрации (правильное решение)---
# keys = int(input())
# names = [input() for row in range(keys)]
# database = dict()
# for i in names:
# if i in database:
# database[i] += 1
# print(i + str(database[i]))
# else:
# database[i] = 0
# print('OK')
# # --- Single number ---
# nums = [2, 2, 1, 1, 1, 7]
# count = {}
# for i in nums:
# if i in count:
# count[i] += 1
# else:
# count[i] = 1
# for i in count:
# if count[i] == 1:
# print(i)
# # --- Persons ---
# contacts = {
# "John Kennedy": {
# 'birthday': '29 may 1917',
# 'city': 'Brookline',
# 'phone': None,
# 'children': 3
# },
# "Arnold Schwarzenegger": {
# 'birthday': '30 july 1947',
# 'city': 'Gradec',
# 'phone': '555-555-555',
# 'children': 5
# },
# "Donald John Trump": {
# 'birthday': '14 july 1946',
# 'city': 'New York',
# 'phone': '777-777-333',
# 'children': 4
# }
# }
# persons = list(contacts.keys())
# for person in persons:
# print(person)
# for data in contacts[person]:
# print(data, contacts[person][data], sep=': ')
# print()
balls, friends = map(int, input().split())
colours = input().lower()
lucky = 0
repeat = []
# a = 0
for i in range(balls - 1):
if i in repeat:
continue
for j in range(i + 1, balls):
if j in repeat or colours[i] == colours[j]:
continue
else:
repeat.append(j)
lucky += 1
break
if lucky == friends:
break
print('NO' if balls % 2 == 0 and lucky < friends else 'YES')
```
No
| 4,729 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, such that no one of his friens will be upset — print «YES», if he can, and «NO», otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.
Input
The first line contains two integers n and k (1 ≤ n, k ≤ 100) — the number of baloons and friends.
Next line contains string s — colors of baloons.
Output
Answer to the task — «YES» or «NO» in a single line.
You can choose the case (lower or upper) for each letter arbitrary.
Examples
Input
4 2
aabb
Output
YES
Input
6 3
aacaab
Output
NO
Note
In the first sample Kefa can give 1-st and 3-rd baloon to the first friend, and 2-nd and 4-th to the second.
In the second sample Kefa needs to give to all his friends baloons of color a, but one baloon will stay, thats why answer is «NO».
Submitted Solution:
```
# # --- Система регистрации (словарь)---
# keys = int(input())
# names = [input() for row in range(keys)]
# database = dict()
# for i in names:
# if i not in database:
# database[i] = 0
# print('OK')
# else:
# for k, val in database.items():
# if val >= 0 and k == i:
# val += 1
# database[i] = val
# print(k + str(val))
# # print(k + f'{val}')
# # --- Система регистрации (правильное решение)---
# keys = int(input())
# names = [input() for row in range(keys)]
# database = dict()
# for i in names:
# if i in database:
# database[i] += 1
# print(i + str(database[i]))
# else:
# database[i] = 0
# print('OK')
# # --- Single number ---
# nums = [2, 2, 1, 1, 1, 7]
# count = {}
# for i in nums:
# if i in count:
# count[i] += 1
# else:
# count[i] = 1
# for i in count:
# if count[i] == 1:
# print(i)
# # --- Persons ---
# contacts = {
# "John Kennedy": {
# 'birthday': '29 may 1917',
# 'city': 'Brookline',
# 'phone': None,
# 'children': 3
# },
# "Arnold Schwarzenegger": {
# 'birthday': '30 july 1947',
# 'city': 'Gradec',
# 'phone': '555-555-555',
# 'children': 5
# },
# "Donald John Trump": {
# 'birthday': '14 july 1946',
# 'city': 'New York',
# 'phone': '777-777-333',
# 'children': 4
# }
# }
# persons = list(contacts.keys())
# for person in persons:
# print(person)
# for data in contacts[person]:
# print(data, contacts[person][data], sep=': ')
# print()
balls, friends = map(int, input().split())
colours = input().lower()
lucky = 0
repeat = []
# a = 0
for i in range(balls - 1):
if i in repeat:
continue
for j in range(i + 1, balls):
if j in repeat or colours[i] == colours[j]:
continue
else:
repeat.append(j)
lucky += 1
break
if lucky == friends:
break
print('YES' if lucky >= friends or lucky * 2 == balls else 'NO')
```
No
| 4,730 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Tags: dfs and similar, graphs, trees
Correct Solution:
```
n = int(input())
edges = [[] for i in range(n)]
for i in range(n-1):
u, v = map(int, input().split())
edges[u-1].append(v-1)
edges[v-1].append(u-1)
colors = [-1 for i in range(n)]
dfs = [(0,0)]
while len(dfs) > 0:
node, color = dfs.pop()
colors[node] = color
for neighbor in edges[node]:
if colors[neighbor] == -1:
dfs.append((neighbor, 1-color))
blue = len([x for x in colors if x==0])
red = n - blue
total_graph_edges = blue*red
print(blue*red - (n-1))
```
| 4,731 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Tags: dfs and similar, graphs, trees
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 main():
for _ in range(1):
# for _ in range(int(input()) if True else 1):
n = int(input())
# n, u, r, d, l = map(int, input().split())
# a = list(map(int, input().split()))
# b = list(map(int, input().split()))
# c = list(map(int, input().split()))
# s = list(input())
# s = input()
d = {}
for i in range(n - 1):
a, b = map(int, input().split())
if a not in d:
d[a] = [b]
else:
d[a] += [b]
if b not in d:
d[b] = [a]
else:
d[b] += [a]
color = [-1] * n
# print(d)
def dfs(n, col):
color[n - 1] = col
# print('going to', d[n])
for child in d[n]:
if color[child - 1] == -1:
dfs(child, col ^ 1)
dfs(1, 1)
# print(color)
ans = color.count(0) * color.count(1) - n + 1 # n-1 edges are already present
print(ans)
t = threading.Thread(target=main)
t.start()
t.join()
```
| 4,732 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Tags: dfs and similar, graphs, trees
Correct Solution:
```
import sys
from sys import stdin,stdout
import bisect
import math
mod=10**9 +7
def st():
return list(stdin.readline().strip())
def inp():
return int(stdin.readline())
def li():
return list(map(int,stdin.readline().split()))
def mp():
return map(int,stdin.readline().split())
def pr(n):
stdout.write(str(n)+"\n")
def DFS(dictionary,vertex,visited):
visited[vertex]=True
stack=[vertex]
print(vertex)
while stack:
a=stack.pop()
for i in dictionary[a]:
if not visited[i]:
print(i)
visited[i]=True
stack.append(i)
def soe(limit):
l=[1]*(limit+1)
l[0]=0
l[1]=0
prime=[]
for i in range(2,limit+1):
if l[i]:
for j in range(i*i,limit+1,i):
l[j]=0
for i in range(2,limit+1):
if l[i]:
prime.append(i)
return prime
def segsoe(low,high):
limit=int(high**0.5)+1
prime=soe(limit)
n=high-low+1
l=[0]*(n+1)
for i in range(len(prime)):
lowlimit=(low//prime[i])*prime[i]
if lowlimit<low:
lowlimit+=prime[i]
if lowlimit==prime[i]:
lowlimit+=prime[i]
for j in range(lowlimit,high+1,prime[i]):
l[j-low]=1
for i in range(low,high+1):
if not l[i-low]:
if i!=1:
print(i)
def gcd(a,b):
while b:
a=a%b
b,a=a,b
return a
def power(a,n):
r=1
while n:
if n&1:
r=(r*a)
a*=a
n=n>>1
return r
def DFS(d,visited,ver,color,value):
value[ver]=color
visited[ver]=True
stack=[ver]
while stack:
a=stack.pop()
for i in d[a]:
if not visited[i]:
visited[i]=True
stack.append(i)
value[i]=value[a]^1
else:
if value[i]==value[a]:
return False
return True
def solve():
n=inp()
visited=[False for i in range(n+1)]
d={i:[] for i in range(1,n+1)}
for i in range(n-1):
a,b=mp()
d[a].append(b)
d[b].append(a)
ans=0
value=[-1]*(n+1)
for i in range(1,n+1):
if not visited[i]:
if not DFS(d,visited,i,0,value):
pr(0)
return
a=value.count(1)
pr(a*(n-a)-(n-1))
for _ in range(1):
solve()
```
| 4,733 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Tags: dfs and similar, graphs, trees
Correct Solution:
```
"""http://codeforces.com/problemset/problem/862/B"""
n = int(input())
edges = dict()
for i in range(n-1):
[v1,v2] = list(map(int,input().split()))
edges.setdefault(v1,[])
edges[v1].append(v2)
edges.setdefault(v2,[])
edges[v2].append(v1)
visited = [False] * (n+1)
queue = [(1,False)]
curr = 0
cntb, cntnotb = 0, 0
while curr < len(queue):
(el, b) = queue[curr]
visited[el] = True
if b:
cntb += 1
else:
cntnotb += 1
for neigh in edges[el]:
if not visited[neigh]:
queue.append((neigh, not b) )
curr += 1
print(cntb*cntnotb - (n-1))
```
| 4,734 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Tags: dfs and similar, graphs, trees
Correct Solution:
```
from collections import defaultdict
from queue import Queue as Q
n = int(input())
e = defaultdict(list)
for i in range(n-1):
x, y = tuple(map(int, input().split()))
e[x].append(y)
e[y].append(x)
def bfs(v):
mark = defaultdict(int)
q = Q()
q.put(v)
mark[v] = 1
while not q.empty():
v = q.get()
for i in e[v]:
if mark[i] == 0:
mark[i] = mark[v]*(-1)
q.put(i)
return sum(value==1 for value in mark.values())
a = bfs(1)
print(a*(n-a)-(n-1))
```
| 4,735 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Tags: dfs and similar, graphs, trees
Correct Solution:
```
n = int(input())
adj = [[] for i in range(n)]
for i in range(n - 1):
a, b = map(int, input().split())
adj[a - 1].append(b - 1)
adj[b - 1].append(a - 1)
visited = [0] * n
value = [-1] * n
q = [0]
value[0] = 0
while q:
x = q.pop(0)
for u in adj[x]:
if visited[u] == 0:
visited[u] = 1
q.append(u)
value[u] = 1 - value[x]
l = value.count(0)
r = value.count(1)
print(l * r - (n-1))
```
| 4,736 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Tags: dfs and similar, graphs, trees
Correct Solution:
```
n = int(input())
e = {}
for i in range(n-1):
a, b = map(int, input().split(' '))
x = e.get(a, [])
x.append(b)
e[a] = x
x = e.get(b, [])
x.append(a)
e[b] = x
c = set()
d = set()
c.add(1)
temp = [1]
seen = set()
while len(temp) > 0:
i = temp.pop(0)
seen.add(i)
if i in c:
for j in e[i]:
d.add(j)
if j not in seen: temp.append(j)
else:
for j in e[i]:
c.add(j)
if j not in seen: temp.append(j)
x = len(c)
y = len(d)
print(x*y-n+1)
```
| 4,737 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Tags: dfs and similar, graphs, trees
Correct Solution:
```
n=int(input())
a=[[]for i in range(n)]
for i in range(n-1):
f,s=map(int,input().split())
a[s-1].append(f)
a[f-1].append(s)
q=[1]
fl=[1]+[0]*n
while len(q)!=0:
x=q.pop()
for i in a[x-1]:
if fl[i-1]==0:
q.append(i)
fl[i-1]=-fl[x-1]
print(fl.count(1)*(n-fl.count(1))-n+1)
```
| 4,738 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Submitted Solution:
```
from collections import deque, defaultdict
typ = defaultdict(int)
p = defaultdict(list)
n = int(input())
for _ in range(n-1):
tmp = list(map(int,input().split()))
u, v = tmp[0], tmp[1]
p[u].append(v)
p[v].append(u)
deq = deque()
deq.append((1,1))
s1 = 0
s2 = 0
while len(deq):
cur = deq.popleft()
v, t = cur[0], cur[1]
typ[v] = t
if t == 1:
s1 += 1
else:
s2 += 1
for i in p[v]:
if not typ[i]:
deq.append((i,(t*2)%3))
print(s1*s2-n+1)
```
Yes
| 4,739 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Submitted Solution:
```
# Махмуд и Ехаб продолжают свои приключения! Каждый житель Злой Страны знает, что Доктор Зло любит двудольные графы, особенно деревья.
#
# Дерево — это связный граф без циклов. Двудольный граф — это граф, вершины которого можно разбить на 2 множества таким образом, что для любого ребра (u, v) графа вершины u и v лежат в разных множествах. Более формальное определение дерева и двудольного графа дано ниже.
#
# Доктор Зло дал Махмуду и Ехабу дерево, состоящее из n рёбер и сказал добавлять рёбра таким образом, чтобы граф оставался двудольным, а также в нём не было петель и кратных рёбер. Какое максимальное число рёбер они могут добавить?
# Входные данные
#
# В первой строке дано целое число n — число вершин в дереве (1 ≤ n ≤ 105).
#
# В следующих n - 1 строках содержатся пары целых чисел u и v (1 ≤ u, v ≤ n, u ≠ v) — описание рёбер дерева.
#
# Гарантируется, что заданный граф является деревом.
# Выходные данные
#
# Выведите одно число — максимальное число рёбер, которые Махмуд и Ехаб могут добавить в граф.
# python3
from collections import Counter
nodes_nr = int(input())
node_idx___neigh_idxes = []
for _ in range(nodes_nr):
node_idx___neigh_idxes.append([])
for _ in range(nodes_nr - 1):
node_idx1, node_idx2 = (int(x) - 1 for x in input().split())
node_idx___neigh_idxes[node_idx1].append(node_idx2)
node_idx___neigh_idxes[node_idx2].append(node_idx1)
node_idx___group = [-1] * nodes_nr
stack = []
stack.append(0)
node_idx___group[0] = 0
while stack:
curr_node_idx = stack.pop()
for neigh_idx in node_idx___neigh_idxes[curr_node_idx]:
if node_idx___group[neigh_idx] == -1:
if node_idx___group[curr_node_idx] == 0:
node_idx___group[neigh_idx] = 1
else:
node_idx___group[neigh_idx] = 0
stack.append(neigh_idx)
counter = Counter(node_idx___group)
ans = counter[0] * counter[1] - nodes_nr + 1
print(ans)
```
Yes
| 4,740 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Submitted Solution:
```
import sys
n = int(sys.stdin.readline().strip())
neighbours = {}
for i in range(n-1):
u, v = (int(x) for x in sys.stdin.readline().strip().split(' '))
if u in neighbours:
neighbours[u].append(v)
else:
neighbours[u] = [v]
if v in neighbours:
neighbours[v].append(u)
else:
neighbours[v] =[u]
start = list(neighbours.keys())[0]
stack = [(start, True)]
visited = set()
A = 0
B = 0
while stack:
curr, colour = stack.pop()
if curr in visited:
continue
visited.add(curr)
if colour:
A += 1
else:
B += 1
for neighbour in neighbours[curr]:
if neighbour not in visited:
stack.append((neighbour, not colour))
total_edges = A * B
print(total_edges - n + 1)
```
Yes
| 4,741 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Submitted Solution:
```
from collections import defaultdict
n = int(input())
graph = defaultdict(set)
for i in range(n - 1):
a, b = input().split()
graph[a].add(b)
graph[b].add(a)
start = next(iter(graph.keys()))
left, right = set([start]), set()
frontier = [(start, True)]
while frontier:
node, is_left = frontier.pop()
for neighbor in graph[node]:
if is_left and neighbor in right or not is_left and neighbor in left:
continue
frontier.append((neighbor, not is_left))
if is_left:
right.add(neighbor)
else:
left.add(neighbor)
print(sum(len(right) - len(graph[a]) for a in left))
```
Yes
| 4,742 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Submitted Solution:
```
n = int(input())
s1 = []
s2 = []
l = [int(x) for x in input().split()]
s1.append(l[0])
s2.append(l[1])
un = []
for i in range(1,n-1):
l = [int(x) for x in input().split()]
if l[0] in s1 and l[1] not in s2:
s2.append(l[1])
elif l[0] in s2 and l[1] not in s1:
s1.append(l[1])
elif l[1] in s1 and l[0] not in s2:
s2.append(l[0])
elif l[1] in s2 and l[0] not in s1:
s1.append(l[0])
else:
un.append(l)
b = 0
while b != len(un):
b = len(un)
for i in range(b-1,-1,-1):
l = un[i]
if l[0] in s1 and l[1] not in s2:
s2.append(l[1])
un.remove(l)
elif l[0] in s2 and l[1] not in s1:
s1.append(l[1])
un.remove(l)
elif l[1] in s1 and l[0] not in s2:
s2.append(l[0])
un.remove(l)
elif l[1] in s1 and l[0] not in s1:
s1.append(l[0])
un.remove(l)
print((len(s1)+len(un))*(len(s2)+len(un))-n+1)
```
No
| 4,743 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Submitted Solution:
```
def dfs(p, i):
color[i].append(p)
c = (i + 1) % 2
print(p)
for elem in sorted(a[p]):
if used[elem] == 0:
used[elem] = 1
dfs(elem, c)
n = int(input())
a = [[] for i in range(n)]
used = dict.fromkeys(range(n), 0)
for i in range(n - 1):
s1, s2 = sorted(map(int, input().split()))
a[s1 - 1].append(s2 - 1)
a[s2 - 1].append(s1 - 1)
color = [[], []]
used[0] = 1
dfs(0, 0)
print(color)
print(max(0, len(color[0]) * len(color[1]) - (n - 1)))
```
No
| 4,744 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Submitted Solution:
```
from collections import defaultdict
def dfs(adj,node,parent,colour,count_colour):
count_colour[colour]+=1
for i in range(len(adj[node])):
if adj[node][i]!=parent:
dfs(adj,adj[node][i],node,not colour,count_colour)
n=int(input())
adj=[[] for i in range(n+1)]
for i in range(n-1):
a,b=input().split()
adj[int(a)].append(int(b))
print(adj)
count_colour=[0,0]
dfs(adj,1,0,0,count_colour)
print(count_colour[0]*count_colour[1]-(n-1))
```
No
| 4,745 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and v belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of n nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
Input
The first line of input contains an integer n — the number of nodes in the tree (1 ≤ n ≤ 105).
The next n - 1 lines contain integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the description of the edges of the tree.
It's guaranteed that the given graph is a tree.
Output
Output one integer — the maximum number of edges that Mahmoud and Ehab can add to the tree while fulfilling the conditions.
Examples
Input
3
1 2
1 3
Output
0
Input
5
1 2
2 3
3 4
4 5
Output
2
Note
Tree definition: https://en.wikipedia.org/wiki/Tree_(graph_theory)
Bipartite graph definition: <https://en.wikipedia.org/wiki/Bipartite_graph>
In the first test case the only edge that can be added in such a way, that graph won't contain loops or multiple edges is (2, 3), but adding this edge will make the graph non-bipartite so the answer is 0.
In the second test case Mahmoud and Ehab can add edges (1, 4) and (2, 5).
Submitted Solution:
```
def dfs(graph, start, color):
global is_bipartite
for u in graph[start]:
if not color[u]:
color[u] = 3 - color[start]
dfs(graph, u, color)
elif color[u] == color[start]:
is_bipartite = False
n = int(input())
r = [[] for i in range(n + 1)]
f = []
s = []
for i in range(n - 1):
a, b = map(int, input().split())
r[a].append(b)
r[b].append(a)
if a in f:
s.append(b)
elif a in s:
f.append(b)
else:
if b in f:
s.append(a)
elif b in s:
f.append(a)
else:
f.append(b)
s.append(a)
k = 0
for i in f:
for j in s:
if i not in r[j]:
r[j].append(i)
r[i].append(j)
is_bipartite = True
df = [0] * (n + 1)
dfs(r, 1, df)
if is_bipartite :
k += 1
else:
r[j] = r[j][:-1]
r[i] = r[i][:-1]
print(k)
```
No
| 4,746 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the final part of fashion show all models come to the stage and stay in one row and fashion designer stays to right to model on the right. During the rehearsal, Izabella noticed, that row isn't nice, but she can't figure out how to fix it.
Like many other creative people, Izabella has a specific sense of beauty. Evaluating beauty of row of models Izabella looks at heights of models. She thinks that row is nice if for each model distance to nearest model with less height (model or fashion designer) to the right of her doesn't exceed k (distance between adjacent people equals 1, the distance between people with exactly one man between them equals 2, etc).
She wants to make row nice, but fashion designer has his own sense of beauty, so she can at most one time select two models from the row and swap their positions if the left model from this pair is higher than the right model from this pair.
Fashion designer (man to the right of rightmost model) has less height than all models and can't be selected for exchange.
You should tell if it's possible to make at most one exchange in such a way that row becomes nice for Izabella.
Input
In first line there are two integers n and k (1 ≤ n ≤ 5·105, 1 ≤ k ≤ n) — number of models and required distance.
Second line contains n space-separated integers ai (1 ≤ ai ≤ 109) — height of each model. Pay attention that height of fashion designer is not given and can be less than 1.
Output
Print «YES» (without quotes) if it's possible to make row nice using at most one exchange, and «NO» (without quotes) otherwise.
Examples
Input
5 4
2 3 5 2 5
Output
NO
Input
5 2
3 6 2 2 1
Output
YES
Input
5 2
5 3 6 5 2
Output
YES
Submitted Solution:
```
temp, k = [int(i) for i in input().split()]
models = [int(i) for i in input().split()]
min = models[0]
steps = 1
index = 0
index2 = 0
steps2 = 1
problems = 0
changed = False
for i in range(temp):
if models[i] < min:
min = models[i]
index = i
steps = 1
else:
steps += 1
if steps > k:
problems += 1
min2 = min
if not (temp - i - k > 0):
newk= temp - i
else:
newk = k
for j in range(newk):
if models[i+j] < min2:
if changed:
changed = False
break
else:
min2 = models[i+j]
changed = True
if not changed:
break
else:
problems -= 1
min = models[i]
steps = 1
if problems:
print('NO')
else:
print('YES')
```
No
| 4,747 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the final part of fashion show all models come to the stage and stay in one row and fashion designer stays to right to model on the right. During the rehearsal, Izabella noticed, that row isn't nice, but she can't figure out how to fix it.
Like many other creative people, Izabella has a specific sense of beauty. Evaluating beauty of row of models Izabella looks at heights of models. She thinks that row is nice if for each model distance to nearest model with less height (model or fashion designer) to the right of her doesn't exceed k (distance between adjacent people equals 1, the distance between people with exactly one man between them equals 2, etc).
She wants to make row nice, but fashion designer has his own sense of beauty, so she can at most one time select two models from the row and swap their positions if the left model from this pair is higher than the right model from this pair.
Fashion designer (man to the right of rightmost model) has less height than all models and can't be selected for exchange.
You should tell if it's possible to make at most one exchange in such a way that row becomes nice for Izabella.
Input
In first line there are two integers n and k (1 ≤ n ≤ 5·105, 1 ≤ k ≤ n) — number of models and required distance.
Second line contains n space-separated integers ai (1 ≤ ai ≤ 109) — height of each model. Pay attention that height of fashion designer is not given and can be less than 1.
Output
Print «YES» (without quotes) if it's possible to make row nice using at most one exchange, and «NO» (without quotes) otherwise.
Examples
Input
5 4
2 3 5 2 5
Output
NO
Input
5 2
3 6 2 2 1
Output
YES
Input
5 2
5 3 6 5 2
Output
YES
Submitted Solution:
```
n,k=list(map(int,input().split()))
number=list(map(int,input().split()))
count=0
flag=0
for i in range(n-1):
j=i
while(j<n and number[j]>=number[i]):
j=j+1
if j<n and count==0 and j-i>k:
temp=number[j]
number[j]=number[i]
number[i]=temp
count=1
elif j==n and j-i>k:
flag=1
print('NO')
break
elif j-i>k and count==1:
flag=1
print('NO')
break
if flag==0:
print('YES')
```
No
| 4,748 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the final part of fashion show all models come to the stage and stay in one row and fashion designer stays to right to model on the right. During the rehearsal, Izabella noticed, that row isn't nice, but she can't figure out how to fix it.
Like many other creative people, Izabella has a specific sense of beauty. Evaluating beauty of row of models Izabella looks at heights of models. She thinks that row is nice if for each model distance to nearest model with less height (model or fashion designer) to the right of her doesn't exceed k (distance between adjacent people equals 1, the distance between people with exactly one man between them equals 2, etc).
She wants to make row nice, but fashion designer has his own sense of beauty, so she can at most one time select two models from the row and swap their positions if the left model from this pair is higher than the right model from this pair.
Fashion designer (man to the right of rightmost model) has less height than all models and can't be selected for exchange.
You should tell if it's possible to make at most one exchange in such a way that row becomes nice for Izabella.
Input
In first line there are two integers n and k (1 ≤ n ≤ 5·105, 1 ≤ k ≤ n) — number of models and required distance.
Second line contains n space-separated integers ai (1 ≤ ai ≤ 109) — height of each model. Pay attention that height of fashion designer is not given and can be less than 1.
Output
Print «YES» (without quotes) if it's possible to make row nice using at most one exchange, and «NO» (without quotes) otherwise.
Examples
Input
5 4
2 3 5 2 5
Output
NO
Input
5 2
3 6 2 2 1
Output
YES
Input
5 2
5 3 6 5 2
Output
YES
Submitted Solution:
```
n,k=list(map(int,input().split()))
number=list(map(int,input().split()))
count=0
flag=0
for i in range(n):
j=i
while(j<n and number[j]>=number[i]):
j=j+1
if j<n-1 and count==0 and j-i>k:
temp=number[j]
number[j]=number[i]
number[i]=temp
count=1
elif j==n-1:
flag=1
print('NO')
break
elif j-i>k and count==1:
flag=1
print('NO')
break
if flag==0:
print('YES')
```
No
| 4,749 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the final part of fashion show all models come to the stage and stay in one row and fashion designer stays to right to model on the right. During the rehearsal, Izabella noticed, that row isn't nice, but she can't figure out how to fix it.
Like many other creative people, Izabella has a specific sense of beauty. Evaluating beauty of row of models Izabella looks at heights of models. She thinks that row is nice if for each model distance to nearest model with less height (model or fashion designer) to the right of her doesn't exceed k (distance between adjacent people equals 1, the distance between people with exactly one man between them equals 2, etc).
She wants to make row nice, but fashion designer has his own sense of beauty, so she can at most one time select two models from the row and swap their positions if the left model from this pair is higher than the right model from this pair.
Fashion designer (man to the right of rightmost model) has less height than all models and can't be selected for exchange.
You should tell if it's possible to make at most one exchange in such a way that row becomes nice for Izabella.
Input
In first line there are two integers n and k (1 ≤ n ≤ 5·105, 1 ≤ k ≤ n) — number of models and required distance.
Second line contains n space-separated integers ai (1 ≤ ai ≤ 109) — height of each model. Pay attention that height of fashion designer is not given and can be less than 1.
Output
Print «YES» (without quotes) if it's possible to make row nice using at most one exchange, and «NO» (without quotes) otherwise.
Examples
Input
5 4
2 3 5 2 5
Output
NO
Input
5 2
3 6 2 2 1
Output
YES
Input
5 2
5 3 6 5 2
Output
YES
Submitted Solution:
```
temp, k = [int(i) for i in input().split()]
models = [int(i) for i in input().split()]
min = models[0]
steps = 0
index = 0
index2 = 0
steps2 = 0
problems = 0
changed = False
for i in range(temp):
if models[i] < min:
min = models[i]
index = i
steps = 0
else:
steps += 1
if steps > k:
problems += 1
min2 = min
if temp - i - k > 0:
for j in range(k):
if models[i+j] < min2:
if changed:
changed = False
break
else:
min2 = models[i+j]
changed = True
if not changed:
break
else:
problems -= 1
min = models[i]
steps = 0
if problems:
print('NO')
else:
print('YES')
```
No
| 4,750 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d.
For each point from 1 to n is known if there is a lily flower in it. The frog can jump only in points with a lilies. Guaranteed that there are lilies in the points 1 and n.
Determine the minimal number of jumps that the frog needs to reach home which is in the point n from the point 1. Consider that initially the frog is in the point 1. If the frog can not reach home, print -1.
Input
The first line contains two integers n and d (2 ≤ n ≤ 100, 1 ≤ d ≤ n - 1) — the point, which the frog wants to reach, and the maximal length of the frog jump.
The second line contains a string s of length n, consisting of zeros and ones. If a character of the string s equals to zero, then in the corresponding point there is no lily flower. In the other case, in the corresponding point there is a lily flower. Guaranteed that the first and the last characters of the string s equal to one.
Output
If the frog can not reach the home, print -1.
In the other case, print the minimal number of jumps that the frog needs to reach the home which is in the point n from the point 1.
Examples
Input
8 4
10010101
Output
2
Input
4 2
1001
Output
-1
Input
8 4
11100101
Output
3
Input
12 3
101111100101
Output
4
Note
In the first example the from can reach home in two jumps: the first jump from the point 1 to the point 4 (the length of the jump is three), and the second jump from the point 4 to the point 8 (the length of the jump is four).
In the second example the frog can not reach home, because to make it she need to jump on a distance three, but the maximum length of her jump equals to two.
Tags: dfs and similar, dp, greedy, implementation
Correct Solution:
```
n,d = map(int,input().split())
s = input()
dp = [100000]*n
dp[0] = 0
for i in range(n):
if s[i] == '1':
for j in range(max(0,i-d),i):
dp[i] = min(dp[i],dp[j]+1)
print([-1,dp[n-1]][dp[n-1]!=100000])
```
| 4,751 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d.
For each point from 1 to n is known if there is a lily flower in it. The frog can jump only in points with a lilies. Guaranteed that there are lilies in the points 1 and n.
Determine the minimal number of jumps that the frog needs to reach home which is in the point n from the point 1. Consider that initially the frog is in the point 1. If the frog can not reach home, print -1.
Input
The first line contains two integers n and d (2 ≤ n ≤ 100, 1 ≤ d ≤ n - 1) — the point, which the frog wants to reach, and the maximal length of the frog jump.
The second line contains a string s of length n, consisting of zeros and ones. If a character of the string s equals to zero, then in the corresponding point there is no lily flower. In the other case, in the corresponding point there is a lily flower. Guaranteed that the first and the last characters of the string s equal to one.
Output
If the frog can not reach the home, print -1.
In the other case, print the minimal number of jumps that the frog needs to reach the home which is in the point n from the point 1.
Examples
Input
8 4
10010101
Output
2
Input
4 2
1001
Output
-1
Input
8 4
11100101
Output
3
Input
12 3
101111100101
Output
4
Note
In the first example the from can reach home in two jumps: the first jump from the point 1 to the point 4 (the length of the jump is three), and the second jump from the point 4 to the point 8 (the length of the jump is four).
In the second example the frog can not reach home, because to make it she need to jump on a distance three, but the maximum length of her jump equals to two.
Tags: dfs and similar, dp, greedy, implementation
Correct Solution:
```
n, d = map(int, input().split())
s = input()
nodes = [i for i in range(n) if s[i] == '1']
best = [None] * len(nodes)
def find_best(node_idx):
if best[node_idx]:
return best[node_idx]
if node_idx == len(nodes) - 1:
return 0
if n - nodes[node_idx] <= d:
return 1
cases = [find_best(idx) for idx in range(node_idx + 1, len(nodes)) if nodes[idx] - nodes[node_idx] <= d]
if cases:
best[node_idx] = min(cases) + 1
return best[node_idx]
else:
return float("inf")
res = find_best(0)
if res == float('inf'):
print(-1)
else:
print(res)
```
| 4,752 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d.
For each point from 1 to n is known if there is a lily flower in it. The frog can jump only in points with a lilies. Guaranteed that there are lilies in the points 1 and n.
Determine the minimal number of jumps that the frog needs to reach home which is in the point n from the point 1. Consider that initially the frog is in the point 1. If the frog can not reach home, print -1.
Input
The first line contains two integers n and d (2 ≤ n ≤ 100, 1 ≤ d ≤ n - 1) — the point, which the frog wants to reach, and the maximal length of the frog jump.
The second line contains a string s of length n, consisting of zeros and ones. If a character of the string s equals to zero, then in the corresponding point there is no lily flower. In the other case, in the corresponding point there is a lily flower. Guaranteed that the first and the last characters of the string s equal to one.
Output
If the frog can not reach the home, print -1.
In the other case, print the minimal number of jumps that the frog needs to reach the home which is in the point n from the point 1.
Examples
Input
8 4
10010101
Output
2
Input
4 2
1001
Output
-1
Input
8 4
11100101
Output
3
Input
12 3
101111100101
Output
4
Note
In the first example the from can reach home in two jumps: the first jump from the point 1 to the point 4 (the length of the jump is three), and the second jump from the point 4 to the point 8 (the length of the jump is four).
In the second example the frog can not reach home, because to make it she need to jump on a distance three, but the maximum length of her jump equals to two.
Tags: dfs and similar, dp, greedy, implementation
Correct Solution:
```
from queue import Queue
BigNum = 10 ** 10
n, d = map(int, input().split(' '))
gs = [False] + [c == '1' for c in input()]
ds = [BigNum] * len(gs)
q = Queue()
q.put((1, 0))
while not q.empty():
v, dist = q.get()
if not gs[v]:
continue
if ds[v] < BigNum:
continue
ds[v] = dist
for dx in range(-d, d + 1):
if 1 <= v + dx <= n:
q.put((v + dx, dist + 1))
print(-1 if ds[n] == BigNum else ds[n])
```
| 4,753 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d.
For each point from 1 to n is known if there is a lily flower in it. The frog can jump only in points with a lilies. Guaranteed that there are lilies in the points 1 and n.
Determine the minimal number of jumps that the frog needs to reach home which is in the point n from the point 1. Consider that initially the frog is in the point 1. If the frog can not reach home, print -1.
Input
The first line contains two integers n and d (2 ≤ n ≤ 100, 1 ≤ d ≤ n - 1) — the point, which the frog wants to reach, and the maximal length of the frog jump.
The second line contains a string s of length n, consisting of zeros and ones. If a character of the string s equals to zero, then in the corresponding point there is no lily flower. In the other case, in the corresponding point there is a lily flower. Guaranteed that the first and the last characters of the string s equal to one.
Output
If the frog can not reach the home, print -1.
In the other case, print the minimal number of jumps that the frog needs to reach the home which is in the point n from the point 1.
Examples
Input
8 4
10010101
Output
2
Input
4 2
1001
Output
-1
Input
8 4
11100101
Output
3
Input
12 3
101111100101
Output
4
Note
In the first example the from can reach home in two jumps: the first jump from the point 1 to the point 4 (the length of the jump is three), and the second jump from the point 4 to the point 8 (the length of the jump is four).
In the second example the frog can not reach home, because to make it she need to jump on a distance three, but the maximum length of her jump equals to two.
Tags: dfs and similar, dp, greedy, implementation
Correct Solution:
```
n,d = list(map(int,input().split()))
word = input()
if "0"*d in word:
print(-1)
else:
cnt=0
i=0
while i<n-1:
if word[i]=="1":
i+=d
cnt+=1
else:
i-=1
print(cnt)
```
| 4,754 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d.
For each point from 1 to n is known if there is a lily flower in it. The frog can jump only in points with a lilies. Guaranteed that there are lilies in the points 1 and n.
Determine the minimal number of jumps that the frog needs to reach home which is in the point n from the point 1. Consider that initially the frog is in the point 1. If the frog can not reach home, print -1.
Input
The first line contains two integers n and d (2 ≤ n ≤ 100, 1 ≤ d ≤ n - 1) — the point, which the frog wants to reach, and the maximal length of the frog jump.
The second line contains a string s of length n, consisting of zeros and ones. If a character of the string s equals to zero, then in the corresponding point there is no lily flower. In the other case, in the corresponding point there is a lily flower. Guaranteed that the first and the last characters of the string s equal to one.
Output
If the frog can not reach the home, print -1.
In the other case, print the minimal number of jumps that the frog needs to reach the home which is in the point n from the point 1.
Examples
Input
8 4
10010101
Output
2
Input
4 2
1001
Output
-1
Input
8 4
11100101
Output
3
Input
12 3
101111100101
Output
4
Note
In the first example the from can reach home in two jumps: the first jump from the point 1 to the point 4 (the length of the jump is three), and the second jump from the point 4 to the point 8 (the length of the jump is four).
In the second example the frog can not reach home, because to make it she need to jump on a distance three, but the maximum length of her jump equals to two.
Tags: dfs and similar, dp, greedy, implementation
Correct Solution:
```
n,d = [int(x) for x in input().split()]
s=input()
ptr=d
jump=0
flag=0
frog=0
while flag==0 and frog!=n-1:
c=0
while s[ptr]=='0':
ptr-=1
c+=1
if c==d:
flag=1
break
else:
jump+=1
frog=ptr
if ptr+d<n:
ptr+=d
else:
ptr=n-1
if flag==1:
print(-1)
else:
print(jump)
```
| 4,755 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d.
For each point from 1 to n is known if there is a lily flower in it. The frog can jump only in points with a lilies. Guaranteed that there are lilies in the points 1 and n.
Determine the minimal number of jumps that the frog needs to reach home which is in the point n from the point 1. Consider that initially the frog is in the point 1. If the frog can not reach home, print -1.
Input
The first line contains two integers n and d (2 ≤ n ≤ 100, 1 ≤ d ≤ n - 1) — the point, which the frog wants to reach, and the maximal length of the frog jump.
The second line contains a string s of length n, consisting of zeros and ones. If a character of the string s equals to zero, then in the corresponding point there is no lily flower. In the other case, in the corresponding point there is a lily flower. Guaranteed that the first and the last characters of the string s equal to one.
Output
If the frog can not reach the home, print -1.
In the other case, print the minimal number of jumps that the frog needs to reach the home which is in the point n from the point 1.
Examples
Input
8 4
10010101
Output
2
Input
4 2
1001
Output
-1
Input
8 4
11100101
Output
3
Input
12 3
101111100101
Output
4
Note
In the first example the from can reach home in two jumps: the first jump from the point 1 to the point 4 (the length of the jump is three), and the second jump from the point 4 to the point 8 (the length of the jump is four).
In the second example the frog can not reach home, because to make it she need to jump on a distance three, but the maximum length of her jump equals to two.
Tags: dfs and similar, dp, greedy, implementation
Correct Solution:
```
line = input()
pui = line.split()
n = int(pui[0])
d = int(pui[1])
st = input()
pos = 1
j = 0
while True :
temp = False
i = pos + d
if i >= n :
j = j+1
temp = True
break
while i != pos :
if st[i-1] == "1" :
pos = i
temp = True
j = j+1
break
i = i-1
if temp is False :
print("-1")
quit()
print(j)
```
| 4,756 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d.
For each point from 1 to n is known if there is a lily flower in it. The frog can jump only in points with a lilies. Guaranteed that there are lilies in the points 1 and n.
Determine the minimal number of jumps that the frog needs to reach home which is in the point n from the point 1. Consider that initially the frog is in the point 1. If the frog can not reach home, print -1.
Input
The first line contains two integers n and d (2 ≤ n ≤ 100, 1 ≤ d ≤ n - 1) — the point, which the frog wants to reach, and the maximal length of the frog jump.
The second line contains a string s of length n, consisting of zeros and ones. If a character of the string s equals to zero, then in the corresponding point there is no lily flower. In the other case, in the corresponding point there is a lily flower. Guaranteed that the first and the last characters of the string s equal to one.
Output
If the frog can not reach the home, print -1.
In the other case, print the minimal number of jumps that the frog needs to reach the home which is in the point n from the point 1.
Examples
Input
8 4
10010101
Output
2
Input
4 2
1001
Output
-1
Input
8 4
11100101
Output
3
Input
12 3
101111100101
Output
4
Note
In the first example the from can reach home in two jumps: the first jump from the point 1 to the point 4 (the length of the jump is three), and the second jump from the point 4 to the point 8 (the length of the jump is four).
In the second example the frog can not reach home, because to make it she need to jump on a distance three, but the maximum length of her jump equals to two.
Tags: dfs and similar, dp, greedy, implementation
Correct Solution:
```
a,b=map(int,input().split())
s=list(int(i) for i in input())
p=[0 for i in range(a)]
#print(s)
for i in range(a):
if (i==0) or (i!=0 and s[i]>1):
for j in range(i+1,i+b+1):
if j>=a:
break
if s[j]==1:
s[j]=s[i]+1
elif s[j]!=0:
s[j]=min(s[i]+1,s[j])
#print
if s[-1]==1:
print(-1)
else:
print(s[-1]-1)
```
| 4,757 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d.
For each point from 1 to n is known if there is a lily flower in it. The frog can jump only in points with a lilies. Guaranteed that there are lilies in the points 1 and n.
Determine the minimal number of jumps that the frog needs to reach home which is in the point n from the point 1. Consider that initially the frog is in the point 1. If the frog can not reach home, print -1.
Input
The first line contains two integers n and d (2 ≤ n ≤ 100, 1 ≤ d ≤ n - 1) — the point, which the frog wants to reach, and the maximal length of the frog jump.
The second line contains a string s of length n, consisting of zeros and ones. If a character of the string s equals to zero, then in the corresponding point there is no lily flower. In the other case, in the corresponding point there is a lily flower. Guaranteed that the first and the last characters of the string s equal to one.
Output
If the frog can not reach the home, print -1.
In the other case, print the minimal number of jumps that the frog needs to reach the home which is in the point n from the point 1.
Examples
Input
8 4
10010101
Output
2
Input
4 2
1001
Output
-1
Input
8 4
11100101
Output
3
Input
12 3
101111100101
Output
4
Note
In the first example the from can reach home in two jumps: the first jump from the point 1 to the point 4 (the length of the jump is three), and the second jump from the point 4 to the point 8 (the length of the jump is four).
In the second example the frog can not reach home, because to make it she need to jump on a distance three, but the maximum length of her jump equals to two.
Tags: dfs and similar, dp, greedy, implementation
Correct Solution:
```
def Frog(n,d,arr):
index = 0
count = 0
original = 1
while index < n-1 and index != original:
if arr[index] != "1":
index -= 1
elif arr[index] == "1":
original = index
index += d
count += 1
if index == original:
print(-1)
else:
print(count)
n,d = map(int,input().split())
arr = input()
Frog(n,d,arr)
```
| 4,758 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d.
For each point from 1 to n is known if there is a lily flower in it. The frog can jump only in points with a lilies. Guaranteed that there are lilies in the points 1 and n.
Determine the minimal number of jumps that the frog needs to reach home which is in the point n from the point 1. Consider that initially the frog is in the point 1. If the frog can not reach home, print -1.
Input
The first line contains two integers n and d (2 ≤ n ≤ 100, 1 ≤ d ≤ n - 1) — the point, which the frog wants to reach, and the maximal length of the frog jump.
The second line contains a string s of length n, consisting of zeros and ones. If a character of the string s equals to zero, then in the corresponding point there is no lily flower. In the other case, in the corresponding point there is a lily flower. Guaranteed that the first and the last characters of the string s equal to one.
Output
If the frog can not reach the home, print -1.
In the other case, print the minimal number of jumps that the frog needs to reach the home which is in the point n from the point 1.
Examples
Input
8 4
10010101
Output
2
Input
4 2
1001
Output
-1
Input
8 4
11100101
Output
3
Input
12 3
101111100101
Output
4
Note
In the first example the from can reach home in two jumps: the first jump from the point 1 to the point 4 (the length of the jump is three), and the second jump from the point 4 to the point 8 (the length of the jump is four).
In the second example the frog can not reach home, because to make it she need to jump on a distance three, but the maximum length of her jump equals to two.
Submitted Solution:
```
n,d=map(int,input().split())
s=input()
i=0
j=0
flag=0
while i<n:
if i==n-1:
print(j)
break
for k in range(d,0,-1):
if i+k<n:
if s[i+k]=='1':
j+=1
i+=k
break
if k==1:
if i+k<n:
if s[i+k]!='1':
flag=1
break
else:
i+=1
break
if flag==1:
print(-1)
break
```
Yes
| 4,759 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d.
For each point from 1 to n is known if there is a lily flower in it. The frog can jump only in points with a lilies. Guaranteed that there are lilies in the points 1 and n.
Determine the minimal number of jumps that the frog needs to reach home which is in the point n from the point 1. Consider that initially the frog is in the point 1. If the frog can not reach home, print -1.
Input
The first line contains two integers n and d (2 ≤ n ≤ 100, 1 ≤ d ≤ n - 1) — the point, which the frog wants to reach, and the maximal length of the frog jump.
The second line contains a string s of length n, consisting of zeros and ones. If a character of the string s equals to zero, then in the corresponding point there is no lily flower. In the other case, in the corresponding point there is a lily flower. Guaranteed that the first and the last characters of the string s equal to one.
Output
If the frog can not reach the home, print -1.
In the other case, print the minimal number of jumps that the frog needs to reach the home which is in the point n from the point 1.
Examples
Input
8 4
10010101
Output
2
Input
4 2
1001
Output
-1
Input
8 4
11100101
Output
3
Input
12 3
101111100101
Output
4
Note
In the first example the from can reach home in two jumps: the first jump from the point 1 to the point 4 (the length of the jump is three), and the second jump from the point 4 to the point 8 (the length of the jump is four).
In the second example the frog can not reach home, because to make it she need to jump on a distance three, but the maximum length of her jump equals to two.
Submitted Solution:
```
# https://codeforces.com/contest/910/problem/A
n,k = map(int, input().split())
s = input()
count = 0
i = 0
while i != (n-1):
j = min(i+k, n-1)
while j > i and s[j] != '1':
j -=1
if i == j:
count = -1
break
else:
count += 1
i = j
print(count)
```
Yes
| 4,760 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d.
For each point from 1 to n is known if there is a lily flower in it. The frog can jump only in points with a lilies. Guaranteed that there are lilies in the points 1 and n.
Determine the minimal number of jumps that the frog needs to reach home which is in the point n from the point 1. Consider that initially the frog is in the point 1. If the frog can not reach home, print -1.
Input
The first line contains two integers n and d (2 ≤ n ≤ 100, 1 ≤ d ≤ n - 1) — the point, which the frog wants to reach, and the maximal length of the frog jump.
The second line contains a string s of length n, consisting of zeros and ones. If a character of the string s equals to zero, then in the corresponding point there is no lily flower. In the other case, in the corresponding point there is a lily flower. Guaranteed that the first and the last characters of the string s equal to one.
Output
If the frog can not reach the home, print -1.
In the other case, print the minimal number of jumps that the frog needs to reach the home which is in the point n from the point 1.
Examples
Input
8 4
10010101
Output
2
Input
4 2
1001
Output
-1
Input
8 4
11100101
Output
3
Input
12 3
101111100101
Output
4
Note
In the first example the from can reach home in two jumps: the first jump from the point 1 to the point 4 (the length of the jump is three), and the second jump from the point 4 to the point 8 (the length of the jump is four).
In the second example the frog can not reach home, because to make it she need to jump on a distance three, but the maximum length of her jump equals to two.
Submitted Solution:
```
def solve():
n, d = map(int, input().split())
n -= 1
s = input()
i = 0
res = 0
while (i < len(s)):
r = min(len(s)-1,i+d)
for j in range(r,i,-1):
if (s[j] == '1'):
i = j
res += 1
break
else:
print(-1)
return
if (i == n):
print(res)
return
solve()
```
Yes
| 4,761 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d.
For each point from 1 to n is known if there is a lily flower in it. The frog can jump only in points with a lilies. Guaranteed that there are lilies in the points 1 and n.
Determine the minimal number of jumps that the frog needs to reach home which is in the point n from the point 1. Consider that initially the frog is in the point 1. If the frog can not reach home, print -1.
Input
The first line contains two integers n and d (2 ≤ n ≤ 100, 1 ≤ d ≤ n - 1) — the point, which the frog wants to reach, and the maximal length of the frog jump.
The second line contains a string s of length n, consisting of zeros and ones. If a character of the string s equals to zero, then in the corresponding point there is no lily flower. In the other case, in the corresponding point there is a lily flower. Guaranteed that the first and the last characters of the string s equal to one.
Output
If the frog can not reach the home, print -1.
In the other case, print the minimal number of jumps that the frog needs to reach the home which is in the point n from the point 1.
Examples
Input
8 4
10010101
Output
2
Input
4 2
1001
Output
-1
Input
8 4
11100101
Output
3
Input
12 3
101111100101
Output
4
Note
In the first example the from can reach home in two jumps: the first jump from the point 1 to the point 4 (the length of the jump is three), and the second jump from the point 4 to the point 8 (the length of the jump is four).
In the second example the frog can not reach home, because to make it she need to jump on a distance three, but the maximum length of her jump equals to two.
Submitted Solution:
```
n,d=[int(i) for i in input().split()]
a=[int(i) for i in input()]
dp=[0] ; l=d ; ans=0
for i in range(1,n):
if a[i]==1:
dp.append(i)
if i==l or i==n-1:
l=dp[-1]+d
if i==l:
print(-1)
exit(0)
ans+=1
print(ans)
```
Yes
| 4,762 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d.
For each point from 1 to n is known if there is a lily flower in it. The frog can jump only in points with a lilies. Guaranteed that there are lilies in the points 1 and n.
Determine the minimal number of jumps that the frog needs to reach home which is in the point n from the point 1. Consider that initially the frog is in the point 1. If the frog can not reach home, print -1.
Input
The first line contains two integers n and d (2 ≤ n ≤ 100, 1 ≤ d ≤ n - 1) — the point, which the frog wants to reach, and the maximal length of the frog jump.
The second line contains a string s of length n, consisting of zeros and ones. If a character of the string s equals to zero, then in the corresponding point there is no lily flower. In the other case, in the corresponding point there is a lily flower. Guaranteed that the first and the last characters of the string s equal to one.
Output
If the frog can not reach the home, print -1.
In the other case, print the minimal number of jumps that the frog needs to reach the home which is in the point n from the point 1.
Examples
Input
8 4
10010101
Output
2
Input
4 2
1001
Output
-1
Input
8 4
11100101
Output
3
Input
12 3
101111100101
Output
4
Note
In the first example the from can reach home in two jumps: the first jump from the point 1 to the point 4 (the length of the jump is three), and the second jump from the point 4 to the point 8 (the length of the jump is four).
In the second example the frog can not reach home, because to make it she need to jump on a distance three, but the maximum length of her jump equals to two.
Submitted Solution:
```
n,m =map(int,input().split())
a=list(input())
i=0
ans=0
while(i+m<=n-1):
for j in range(0,m):
if(a[m+i-j]=="1"):
i=m+i-j
ans+=1
break
else:
print(-1)
exit()
print(ans)
```
No
| 4,763 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d.
For each point from 1 to n is known if there is a lily flower in it. The frog can jump only in points with a lilies. Guaranteed that there are lilies in the points 1 and n.
Determine the minimal number of jumps that the frog needs to reach home which is in the point n from the point 1. Consider that initially the frog is in the point 1. If the frog can not reach home, print -1.
Input
The first line contains two integers n and d (2 ≤ n ≤ 100, 1 ≤ d ≤ n - 1) — the point, which the frog wants to reach, and the maximal length of the frog jump.
The second line contains a string s of length n, consisting of zeros and ones. If a character of the string s equals to zero, then in the corresponding point there is no lily flower. In the other case, in the corresponding point there is a lily flower. Guaranteed that the first and the last characters of the string s equal to one.
Output
If the frog can not reach the home, print -1.
In the other case, print the minimal number of jumps that the frog needs to reach the home which is in the point n from the point 1.
Examples
Input
8 4
10010101
Output
2
Input
4 2
1001
Output
-1
Input
8 4
11100101
Output
3
Input
12 3
101111100101
Output
4
Note
In the first example the from can reach home in two jumps: the first jump from the point 1 to the point 4 (the length of the jump is three), and the second jump from the point 4 to the point 8 (the length of the jump is four).
In the second example the frog can not reach home, because to make it she need to jump on a distance three, but the maximum length of her jump equals to two.
Submitted Solution:
```
n,m=map(int,input().split())
s=input()
c=0
t=m
i=0
while i <(len(s)):
if(t!=0 and i+t in range(len(s))and(s[i+t] =='1')):
c=c+1
i=i+t
t=m
continue
else:
if(t!=0):
t=t-1
continue
else:
break
if(i==len(s)-1):
break
if(c):
print(c)
else:
print(-1)
```
No
| 4,764 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d.
For each point from 1 to n is known if there is a lily flower in it. The frog can jump only in points with a lilies. Guaranteed that there are lilies in the points 1 and n.
Determine the minimal number of jumps that the frog needs to reach home which is in the point n from the point 1. Consider that initially the frog is in the point 1. If the frog can not reach home, print -1.
Input
The first line contains two integers n and d (2 ≤ n ≤ 100, 1 ≤ d ≤ n - 1) — the point, which the frog wants to reach, and the maximal length of the frog jump.
The second line contains a string s of length n, consisting of zeros and ones. If a character of the string s equals to zero, then in the corresponding point there is no lily flower. In the other case, in the corresponding point there is a lily flower. Guaranteed that the first and the last characters of the string s equal to one.
Output
If the frog can not reach the home, print -1.
In the other case, print the minimal number of jumps that the frog needs to reach the home which is in the point n from the point 1.
Examples
Input
8 4
10010101
Output
2
Input
4 2
1001
Output
-1
Input
8 4
11100101
Output
3
Input
12 3
101111100101
Output
4
Note
In the first example the from can reach home in two jumps: the first jump from the point 1 to the point 4 (the length of the jump is three), and the second jump from the point 4 to the point 8 (the length of the jump is four).
In the second example the frog can not reach home, because to make it she need to jump on a distance three, but the maximum length of her jump equals to two.
Submitted Solution:
```
# https://codeforces.com/problemset/problem/910/A
#
# Solution is to jump to farest lilie every time.
# If imagine we have 3 lilies in order on Ox axis: A, B, C in some distances between them.
# Notice if C is reachable from A then then it is reachable from B as distance from B to C is shorter than from A to C.
# Time complexity upper bounded with O(n) - every time jump by 1. Maybe there is better limit, but this one seems to be satisfactory.
def solution(n, d, L):
current_pos = 0
jumps = 0
while current_pos < n-1:
longest_jump = min(d, n-1-current_pos)
while L[current_pos + longest_jump] != '1' and longest_jump >= 0:
longest_jump -= 1
if longest_jump == 0:
return -1
current_pos += longest_jump
jumps += 1
return jumps
if __name__ == '__main__':
(n, k) = map(int, input().split())
L = input()
print(solution(n,k,L))
# print ('Start tests..')
# assert solution(8,4,'10010101') == 2
# assert solution(4,2,'1001') == -1
# assert solution(8,4,'11100101') == 3
# assert solution(12, 3, '101111100101') == 4
# assert solution(2, 1, '11') == 1
# assert solution(3, 1, '101') == -1
# assert solution(3, 2, '101') == 1
print ('passed!')
```
No
| 4,765 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d.
For each point from 1 to n is known if there is a lily flower in it. The frog can jump only in points with a lilies. Guaranteed that there are lilies in the points 1 and n.
Determine the minimal number of jumps that the frog needs to reach home which is in the point n from the point 1. Consider that initially the frog is in the point 1. If the frog can not reach home, print -1.
Input
The first line contains two integers n and d (2 ≤ n ≤ 100, 1 ≤ d ≤ n - 1) — the point, which the frog wants to reach, and the maximal length of the frog jump.
The second line contains a string s of length n, consisting of zeros and ones. If a character of the string s equals to zero, then in the corresponding point there is no lily flower. In the other case, in the corresponding point there is a lily flower. Guaranteed that the first and the last characters of the string s equal to one.
Output
If the frog can not reach the home, print -1.
In the other case, print the minimal number of jumps that the frog needs to reach the home which is in the point n from the point 1.
Examples
Input
8 4
10010101
Output
2
Input
4 2
1001
Output
-1
Input
8 4
11100101
Output
3
Input
12 3
101111100101
Output
4
Note
In the first example the from can reach home in two jumps: the first jump from the point 1 to the point 4 (the length of the jump is three), and the second jump from the point 4 to the point 8 (the length of the jump is four).
In the second example the frog can not reach home, because to make it she need to jump on a distance three, but the maximum length of her jump equals to two.
Submitted Solution:
```
n,d = map(int,input().split())
s = input()
w = [0]*n
w[0]=1
for i in range(1,n):
if s[i]=='1':
if i<=d:
for j in range(i):
w[i]+=w[j]
else:
for j in range(i-d,i):
w[i]+=w[j]
#print(w)
if w[n-1]==0:
print(-1)
else:
print(w[n-1])
```
No
| 4,766 |
Provide tags and a correct Python 3 solution for this coding contest problem.
For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:
<image>
Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.
For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.
Input
The only line contains three integers N, A, B (1 ≤ N ≤ 106, 1 ≤ A, B ≤ N).
Output
If no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to N.
Examples
Input
9 2 5
Output
6 5 8 3 4 1 9 2 7
Input
3 2 1
Output
1 2 3
Note
In the first example, g(1) = g(6) = g(7) = g(9) = 2 and g(2) = g(3) = g(4) = g(5) = g(8) = 5
In the second example, g(1) = g(2) = g(3) = 1
Tags: brute force, constructive algorithms
Correct Solution:
```
n, a, b = map(int, input().strip().split())
def pp(seq):
return ' '.join(map(str, seq))
def cycle(start, size):
return list(range(start+1, start+size)) + [start]
def fail_sequence(target, acc=[]):
''' recursion failure, bloody python '''
if target % a == 0:
return acc + [a] * (target//a)
if target % b == 0:
return acc + [b] * (target//b)
if a <= target:
acc.append(a)
res = sequence(target-a, acc)
if res:
return res
acc.pop()
if b <= target:
acc.append(b)
return sequence(target-b, acc)
return []
def sequence(target, a, b):
dp = {0:(0,0)} # num of (a, b) needed to reach sum
for i in range(1, target+1):
if i-a in dp:
na, nb = dp[i-a]
dp[i] = (na+1, nb)
elif i-b in dp:
na, nb = dp[i-b]
dp[i] = (na, nb+1)
na, nb = dp.get(target, (0,0))
return [a]*na + [b]*nb
def sol():
seq = sequence(n, a, b)
if seq:
res = []
i = 1
for size in seq:
res.extend(cycle(i, size))
i += size
return pp(res)
else:
return -1
print(sol())
```
| 4,767 |
Provide tags and a correct Python 3 solution for this coding contest problem.
For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:
<image>
Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.
For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.
Input
The only line contains three integers N, A, B (1 ≤ N ≤ 106, 1 ≤ A, B ≤ N).
Output
If no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to N.
Examples
Input
9 2 5
Output
6 5 8 3 4 1 9 2 7
Input
3 2 1
Output
1 2 3
Note
In the first example, g(1) = g(6) = g(7) = g(9) = 2 and g(2) = g(3) = g(4) = g(5) = g(8) = 5
In the second example, g(1) = g(2) = g(3) = 1
Tags: brute force, constructive algorithms
Correct Solution:
```
N, A, B = map(int, input().split())
for i in range(N//A+1):
if (N-i*A)%B==0:
ans = []
for j in range(i):
l = []
for k in range(1, A+1):
l.append(j*A+k)
ans += l[1:]+[l[0]]
for j in range((N-i*A)//B):
l = []
for k in range(1, B+1):
l.append(i*A+j*B+k)
ans += l[1:]+[l[0]]
print(*ans)
break
else:
print(-1)
```
| 4,768 |
Provide tags and a correct Python 3 solution for this coding contest problem.
For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:
<image>
Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.
For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.
Input
The only line contains three integers N, A, B (1 ≤ N ≤ 106, 1 ≤ A, B ≤ N).
Output
If no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to N.
Examples
Input
9 2 5
Output
6 5 8 3 4 1 9 2 7
Input
3 2 1
Output
1 2 3
Note
In the first example, g(1) = g(6) = g(7) = g(9) = 2 and g(2) = g(3) = g(4) = g(5) = g(8) = 5
In the second example, g(1) = g(2) = g(3) = 1
Tags: brute force, constructive algorithms
Correct Solution:
```
n, a, b = map(int, input().split())
x, y = 0, 0
ok = False
for i in range(n // a + 1):
if (n - a * i) % b == 0:
ok = True
x, y = i, (n - a * i) // b
break
if not ok:
print(-1)
exit()
pos = 1
for i in range(x):
print(pos + a - 1, end=' ')
for j in range(a - 1):
print(pos + j, end=' ')
pos += a
for i in range(y):
print(pos + b - 1, end=' ')
for j in range(b - 1):
print(pos + j, end=' ')
pos += b
```
| 4,769 |
Provide tags and a correct Python 3 solution for this coding contest problem.
For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:
<image>
Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.
For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.
Input
The only line contains three integers N, A, B (1 ≤ N ≤ 106, 1 ≤ A, B ≤ N).
Output
If no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to N.
Examples
Input
9 2 5
Output
6 5 8 3 4 1 9 2 7
Input
3 2 1
Output
1 2 3
Note
In the first example, g(1) = g(6) = g(7) = g(9) = 2 and g(2) = g(3) = g(4) = g(5) = g(8) = 5
In the second example, g(1) = g(2) = g(3) = 1
Tags: brute force, constructive algorithms
Correct Solution:
```
ans = []
def go(base, n):
ans.append(base + n - 1)
for i in range(base, base + n - 1):
ans.append(i)
def solve(n, a, b, x):
cur_start = 1
y = (n - a * x) // b
for i in range(x):
go(cur_start, a)
cur_start += a
for i in range(y):
go(cur_start, b)
cur_start += b
n, a, b = map(int, input().split())
for x in range(0, 10 ** 6 + 1):
if (n - x * a) % b == 0 and n - x * a >= 0:
solve(n, a, b, x)
print(' '.join(map(str, ans)))
break
else:
print(-1)
# Made By Mostafa_Khaled
```
| 4,770 |
Provide tags and a correct Python 3 solution for this coding contest problem.
For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:
<image>
Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.
For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.
Input
The only line contains three integers N, A, B (1 ≤ N ≤ 106, 1 ≤ A, B ≤ N).
Output
If no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to N.
Examples
Input
9 2 5
Output
6 5 8 3 4 1 9 2 7
Input
3 2 1
Output
1 2 3
Note
In the first example, g(1) = g(6) = g(7) = g(9) = 2 and g(2) = g(3) = g(4) = g(5) = g(8) = 5
In the second example, g(1) = g(2) = g(3) = 1
Tags: brute force, constructive algorithms
Correct Solution:
```
n,a,b=map(int,input().split())
x,y=-1,-1
for i in range(n+1):
if n-a*i>=0 and (n-a*i)%b==0:
x=i
y=(n-a*i)//b
break
if x==-1:
print(-1)
exit()
ans=[-1]*n
for i in range(0,a*x,a):
for j in range(i,i+a-1):
ans[j]=j+1
ans[i+a-1]=i
for i in range(a*x,n,b):
for j in range(i,i+b-1):
ans[j]=j+1
ans[i+b-1]=i
for i in range(n):
ans[i]+=1
print(*ans)
```
| 4,771 |
Provide tags and a correct Python 3 solution for this coding contest problem.
For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:
<image>
Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.
For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.
Input
The only line contains three integers N, A, B (1 ≤ N ≤ 106, 1 ≤ A, B ≤ N).
Output
If no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to N.
Examples
Input
9 2 5
Output
6 5 8 3 4 1 9 2 7
Input
3 2 1
Output
1 2 3
Note
In the first example, g(1) = g(6) = g(7) = g(9) = 2 and g(2) = g(3) = g(4) = g(5) = g(8) = 5
In the second example, g(1) = g(2) = g(3) = 1
Tags: brute force, constructive algorithms
Correct Solution:
```
n, a, b = map(int, input().split())
r = []
def f(a, l, r=r):
r += [a + l - 1] + list(range(a, a + l - 1))
i = 1
while n > 0:
if n % b is 0:
break
f(i, a)
i += a
n -= a
while n > 0:
f(i, b)
i += b
n -= b
print(-1) if n else print(*r)
```
| 4,772 |
Provide tags and a correct Python 3 solution for this coding contest problem.
For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:
<image>
Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.
For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.
Input
The only line contains three integers N, A, B (1 ≤ N ≤ 106, 1 ≤ A, B ≤ N).
Output
If no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to N.
Examples
Input
9 2 5
Output
6 5 8 3 4 1 9 2 7
Input
3 2 1
Output
1 2 3
Note
In the first example, g(1) = g(6) = g(7) = g(9) = 2 and g(2) = g(3) = g(4) = g(5) = g(8) = 5
In the second example, g(1) = g(2) = g(3) = 1
Tags: brute force, constructive algorithms
Correct Solution:
```
#!/usr/bin/env python3
import sys
n, a, b = map(int, sys.stdin.readline().strip().split())
# supposed a>=0, b>=0, a+b>0
# returns (d, p, q) where d = gcd(a, b) = a*p + b*q
def euc(a, b):
if b > a:
(d, p, q) = euc(b, a)
return (d, q, p)
if b == 0:
return (a, 1, 0)
s = a // b
(d, sp, sq) = euc(a - s * b, b)
return (d, sp, sq - s * sp)
def normalize(n, a, b, d, p, q):
if p < 0:
(sp, sq) = normalize(n, b, a, d, q, p)
return (sq, sp)
elif q >= 0:
return (p, q)
# p>=0, q < 0
r = - (q // (a // d))
sp = p - r * (b // d)
sq = q + r * (a // d)
if sp < 0:
raise ValueError
else:
return (sp, sq)
(d, p, q) = euc(a, b)
if n % d != 0:
print ('-1')
sys.exit(0)
m = n // d
p, q = m * p, m * q
try:
(p, q) = normalize(n, a, b, d, p, q)
except ValueError:
print ('-1')
sys.exit(0)
res = []
last = 1
for _ in range(p):
res.extend(range(last + 1, last + a))
res.append(last)
last += a
for _ in range(q):
res.extend(range(last + 1, last + b))
res.append(last)
last += b
print (' '.join(map(str, res)))
```
| 4,773 |
Provide tags and a correct Python 3 solution for this coding contest problem.
For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:
<image>
Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.
For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.
Input
The only line contains three integers N, A, B (1 ≤ N ≤ 106, 1 ≤ A, B ≤ N).
Output
If no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to N.
Examples
Input
9 2 5
Output
6 5 8 3 4 1 9 2 7
Input
3 2 1
Output
1 2 3
Note
In the first example, g(1) = g(6) = g(7) = g(9) = 2 and g(2) = g(3) = g(4) = g(5) = g(8) = 5
In the second example, g(1) = g(2) = g(3) = 1
Tags: brute force, constructive algorithms
Correct Solution:
```
# ========= /\ /| |====/|
# | / \ | | / |
# | /____\ | | / |
# | / \ | | / |
# ========= / \ ===== |/====|
# code
def main():
n , a , b = map(int , input().split())
if a < b:
a , b = b , a
s = []
k = 1
ok = False
x = 0
y = 0
for j in range(n):
kk = n - a * j
if kk >= 0:
if kk % b == 0:
ok = True
x = j
y = kk // b
break
if not ok:
print(-1)
return
for j in range(x):
for i in range(a - 1):
s.append(k + i + 1)
s.append(k)
k += a
n -= a
for j in range(y):
for i in range(b - 1):
s.append(k + i + 1)
s.append(k)
k += b
n -= b
print(*s)
return
if __name__ == "__main__":
main()
```
| 4,774 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:
<image>
Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.
For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.
Input
The only line contains three integers N, A, B (1 ≤ N ≤ 106, 1 ≤ A, B ≤ N).
Output
If no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to N.
Examples
Input
9 2 5
Output
6 5 8 3 4 1 9 2 7
Input
3 2 1
Output
1 2 3
Note
In the first example, g(1) = g(6) = g(7) = g(9) = 2 and g(2) = g(3) = g(4) = g(5) = g(8) = 5
In the second example, g(1) = g(2) = g(3) = 1
Submitted Solution:
```
from sys import stdin, stdout
from random import randrange
n, a, b = map(int, stdin.readline().split())
first, second = -1, -1
for i in range(n):
if a * i > n:
break
if not (n - a * i) % b:
first, second = i, (n - a * i) // b
break
if min(first, second) == -1:
stdout.write('-1')
else:
ans = [0 for i in range(n + 1)]
current = 1
for i in range(first):
ans[current] = current + a - 1
current += 1
for j in range(1, a):
ans[current] = current - 1
current += 1
for i in range(second):
ans[current] = current + b - 1
current += 1
for j in range(1, b):
ans[current] = current - 1
current += 1
stdout.write(' '.join(list(map(str, ans[1:]))))
```
Yes
| 4,775 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:
<image>
Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.
For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.
Input
The only line contains three integers N, A, B (1 ≤ N ≤ 106, 1 ≤ A, B ≤ N).
Output
If no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to N.
Examples
Input
9 2 5
Output
6 5 8 3 4 1 9 2 7
Input
3 2 1
Output
1 2 3
Note
In the first example, g(1) = g(6) = g(7) = g(9) = 2 and g(2) = g(3) = g(4) = g(5) = g(8) = 5
In the second example, g(1) = g(2) = g(3) = 1
Submitted Solution:
```
ans = []
def go(base, n):
ans.append(base + n - 1)
for i in range(base, base + n - 1):
ans.append(i)
def solve(n, a, b, x):
cur_start = 1
y = (n - a * x) // b
for i in range(x):
go(cur_start, a)
cur_start += a
for i in range(y):
go(cur_start, b)
cur_start += b
n, a, b = map(int, input().split())
for x in range(0, 10 ** 6 + 1):
if (n - x * a) % b == 0 and n - x * a >= 0:
solve(n, a, b, x)
print(' '.join(map(str, ans)))
break
else:
print(-1)
```
Yes
| 4,776 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:
<image>
Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.
For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.
Input
The only line contains three integers N, A, B (1 ≤ N ≤ 106, 1 ≤ A, B ≤ N).
Output
If no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to N.
Examples
Input
9 2 5
Output
6 5 8 3 4 1 9 2 7
Input
3 2 1
Output
1 2 3
Note
In the first example, g(1) = g(6) = g(7) = g(9) = 2 and g(2) = g(3) = g(4) = g(5) = g(8) = 5
In the second example, g(1) = g(2) = g(3) = 1
Submitted Solution:
```
n, a, b = map(int, input().split())
for i in range(n//a + 1):
if (n - i*a) % b == 0:
res = []
for j in range(i):
t = [j*a + k for k in range(1, a+1)]
res += t[1:] + [t[0]]
for j in range((n - i*a) // b):
t = [i*a + j*b + k for k in range(1, b+1)]
res += t[1:] + [t[0]]
print(*res)
break
else:
print(-1)
```
Yes
| 4,777 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:
<image>
Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.
For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.
Input
The only line contains three integers N, A, B (1 ≤ N ≤ 106, 1 ≤ A, B ≤ N).
Output
If no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to N.
Examples
Input
9 2 5
Output
6 5 8 3 4 1 9 2 7
Input
3 2 1
Output
1 2 3
Note
In the first example, g(1) = g(6) = g(7) = g(9) = 2 and g(2) = g(3) = g(4) = g(5) = g(8) = 5
In the second example, g(1) = g(2) = g(3) = 1
Submitted Solution:
```
def solution (a, b, n):
i = 0
while i * a <= n:
if (n - (i * a)) % b == 0:
return (i, int((n - (i * a)) / b))
i = i + 1
return -1
n,a,b = map(int,input().split())
a,b = max(a,b), min(a,b)
x = solution(a,b,n)
if(x == -1):
print(x)
else:
ans = []
r,s = x[0],x[1]
curr = 1
while(r):
last = a + curr - 1
ans.append(last)
for i in range(curr, curr + a - 1):
ans.append(i)
curr += a
r-=1
while(s):
last = b + curr - 1
ans.append(last)
for i in range(curr, curr + b - 1):
ans.append(i)
curr += b
s-=1
print(*ans)
```
Yes
| 4,778 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:
<image>
Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.
For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.
Input
The only line contains three integers N, A, B (1 ≤ N ≤ 106, 1 ≤ A, B ≤ N).
Output
If no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to N.
Examples
Input
9 2 5
Output
6 5 8 3 4 1 9 2 7
Input
3 2 1
Output
1 2 3
Note
In the first example, g(1) = g(6) = g(7) = g(9) = 2 and g(2) = g(3) = g(4) = g(5) = g(8) = 5
In the second example, g(1) = g(2) = g(3) = 1
Submitted Solution:
```
from sys import stdin, stdout
from random import randrange
n, a, b = map(int, stdin.readline().split())
first, second = -1, -1
for i in range(n):
if n >= a * i and not (n - a * i) % b:
first, second = i, (n - a * i) // b
break
if min(first, second) == -1:
stdout.write('-1')
else:
ans = [0 for i in range(n + 1)]
current = 1
for i in range(first):
ans[current] = current + a - 1
current += 1
for j in range(1, a):
ans[current] = current - 1
current += 1
current -= 1
for i in range(second):
ans[current] = current + b - 1
current += 1
for j in range(1, b):
ans[current] = current - 1
current += 1
stdout.write(' '.join(list(map(str, ans[1:]))))
```
No
| 4,779 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:
<image>
Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.
For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.
Input
The only line contains three integers N, A, B (1 ≤ N ≤ 106, 1 ≤ A, B ≤ N).
Output
If no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to N.
Examples
Input
9 2 5
Output
6 5 8 3 4 1 9 2 7
Input
3 2 1
Output
1 2 3
Note
In the first example, g(1) = g(6) = g(7) = g(9) = 2 and g(2) = g(3) = g(4) = g(5) = g(8) = 5
In the second example, g(1) = g(2) = g(3) = 1
Submitted Solution:
```
#This code sucks, you know it and I know it.
#Move on and call me an idiot later.
n, a, b = map(int, input().split())
if n%a!=0 and n%b!=0 and (n%a)%b!=0 and (n%b)%a!=0:
print(-1)
else:
if b > a:
a, b = b, a
aa = n//a
bb = (n-aa*a)//b
l = []
if n%a==0 or n%b==0:
c = a
if n%b==0:
c = b
for i in range(1, (n//c)+1):
x = c*(i-1) + 1
y = c*i
l.append(y)
l += [j for j in range(x, y)]
print(" ".join(map(str, l)))
exit(0)
for i in range(1,aa+1):
x = a*(i-1) + 1
y = a*i
l.append(y)
l += [j for j in range(x, y)]
for i in range(1,bb+1):
x = a*aa + b*(i-1) + 1
y = a*aa + b*i
l.append(y)
l += [j for j in range(x, y)]
print(" ".join(map(str, l)))
```
No
| 4,780 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:
<image>
Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.
For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.
Input
The only line contains three integers N, A, B (1 ≤ N ≤ 106, 1 ≤ A, B ≤ N).
Output
If no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to N.
Examples
Input
9 2 5
Output
6 5 8 3 4 1 9 2 7
Input
3 2 1
Output
1 2 3
Note
In the first example, g(1) = g(6) = g(7) = g(9) = 2 and g(2) = g(3) = g(4) = g(5) = g(8) = 5
In the second example, g(1) = g(2) = g(3) = 1
Submitted Solution:
```
from sys import stdin, stdout
from random import randrange
n, a, b = map(int, stdin.readline().split())
first, second = -1, -1
for i in range(n):
if n > a * i and not (n - a * i) % b:
first, second = i, (n - a * i) // b
break
if min(first, second) == -1:
stdout.write('-1')
else:
ans = [0 for i in range(n + 1)]
current = 1
for i in range(first):
ans[current] = current + a - 1
current += 1
for j in range(1, a):
ans[current] = current - 1
current += 1
current -= 1
for i in range(second):
ans[current] = current + b - 1
current += 1
for j in range(1, b):
ans[current] = current - 1
current += 1
stdout.write(' '.join(list(map(str, ans[1:]))))
```
No
| 4,781 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:
<image>
Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.
For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.
Input
The only line contains three integers N, A, B (1 ≤ N ≤ 106, 1 ≤ A, B ≤ N).
Output
If no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to N.
Examples
Input
9 2 5
Output
6 5 8 3 4 1 9 2 7
Input
3 2 1
Output
1 2 3
Note
In the first example, g(1) = g(6) = g(7) = g(9) = 2 and g(2) = g(3) = g(4) = g(5) = g(8) = 5
In the second example, g(1) = g(2) = g(3) = 1
Submitted Solution:
```
# ========= /\ /| |====/|
# | / \ | | / |
# | /____\ | | / |
# | / \ | | / |
# ========= / \ ===== |/====|
# code
def main():
n , a , b = map(int , input().split())
if a < b:
a , b = b , a
s = []
k = 1
ok = False
x = 0
y = 0
for j in range(n):
k = n - a * j
if k >= 0:
if k % b == 0:
ok = True
x = j
y = k // b
break
for j in range(x):
for i in range(a - 1):
s.append(k + i + 1)
s.append(k)
k += a
n -= a
for j in range(y):
for i in range(b - 1):
s.append(k + i + 1)
s.append(k)
k += b
n -= b
print(*s)
return
if __name__ == "__main__":
main()
```
No
| 4,782 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud has an array a consisting of n integers. He asked Ehab to find another array b of the same length such that:
* b is lexicographically greater than or equal to a.
* bi ≥ 2.
* b is pairwise coprime: for every 1 ≤ i < j ≤ n, bi and bj are coprime, i. e. GCD(bi, bj) = 1, where GCD(w, z) is the greatest common divisor of w and z.
Ehab wants to choose a special array so he wants the lexicographically minimal array between all the variants. Can you find it?
An array x is lexicographically greater than an array y if there exists an index i such than xi > yi and xj = yj for all 1 ≤ j < i. An array x is equal to an array y if xi = yi for all 1 ≤ i ≤ n.
Input
The first line contains an integer n (1 ≤ n ≤ 105), the number of elements in a and b.
The second line contains n integers a1, a2, ..., an (2 ≤ ai ≤ 105), the elements of a.
Output
Output n space-separated integers, the i-th of them representing bi.
Examples
Input
5
2 3 5 4 13
Output
2 3 5 7 11
Input
3
10 3 7
Output
10 3 7
Note
Note that in the second sample, the array is already pairwise coprime so we printed it.
Tags: constructive algorithms, greedy, math, number theory
Correct Solution:
```
import atexit
import io
import sys
# Buffering IO
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
ppp = ('2 3 5 7 11 13 17 19 23 29 '
+ '31 37 41 43 47 53 59 61 67 71 '
+ '73 79 83 89 97 101 103 107 109 113 '
+'127 131 137 139 149 151 157 163 167 173 '
+'179 181 191 193 197 199 211 223 227 229 '
+'233 239 241 251 257 263 269 271 277 281 '
+'283 293 307 311 313 317 ')
pp = [int(x) for x in ppp.split()]
xx = [False] * 1500000
def f(aa):
t = []
for p in pp:
if aa % p == 0:
while aa%p == 0:
aa = aa//p
t.append(p)
if aa == 1:
break
if aa != 1:
t.append(aa)
for tt in t:
for i in range(tt, 1500000, tt):
xx[i]=True
def main():
n = input()
a = [int(x) for x in input().split()]
b = []
for aa in a:
if xx[aa] == False:
b.append(aa)
f(aa)
else:
kk = aa + 1
while xx[kk] == True:
kk += 1
b.append(kk)
f(kk)
break
t = 2
while len(b) < len(a):
while xx[t] == True:
t+=1
b.append(t)
f(t)
print(' '.join(str(x) for x in b))
if __name__ == '__main__':
main()
```
| 4,783 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud has an array a consisting of n integers. He asked Ehab to find another array b of the same length such that:
* b is lexicographically greater than or equal to a.
* bi ≥ 2.
* b is pairwise coprime: for every 1 ≤ i < j ≤ n, bi and bj are coprime, i. e. GCD(bi, bj) = 1, where GCD(w, z) is the greatest common divisor of w and z.
Ehab wants to choose a special array so he wants the lexicographically minimal array between all the variants. Can you find it?
An array x is lexicographically greater than an array y if there exists an index i such than xi > yi and xj = yj for all 1 ≤ j < i. An array x is equal to an array y if xi = yi for all 1 ≤ i ≤ n.
Input
The first line contains an integer n (1 ≤ n ≤ 105), the number of elements in a and b.
The second line contains n integers a1, a2, ..., an (2 ≤ ai ≤ 105), the elements of a.
Output
Output n space-separated integers, the i-th of them representing bi.
Examples
Input
5
2 3 5 4 13
Output
2 3 5 7 11
Input
3
10 3 7
Output
10 3 7
Note
Note that in the second sample, the array is already pairwise coprime so we printed it.
Tags: constructive algorithms, greedy, math, number theory
Correct Solution:
```
m=2*10**6
prime=[0 for i in range(m)]
n=int(input())
arr=list(map(int,input().split()))
s=set(arr)
i=0
flag=0
for i in range(n):
jump =arr[i]
if prime[jump] ==1:
for k in range(jump,m):
if prime[k] ==0:
arr[i] = k
flag=1
break
s=set()
l=2
jump =arr[i]
while l*l <=arr[i]:
while jump %l ==0:
jump //=l
s.add(l)
l+=1
if jump >1:
s.add(jump)
for p in s:
for j in range(p,m,p):
prime[j] =1
if flag==1:
break
i+=1
for k in range(2,m):
if i ==n:
break
if prime[k] ==0:
arr[i] =k
for l in range(k,m,k):
prime[l] =1
i+=1
print(*arr)
```
| 4,784 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud has an array a consisting of n integers. He asked Ehab to find another array b of the same length such that:
* b is lexicographically greater than or equal to a.
* bi ≥ 2.
* b is pairwise coprime: for every 1 ≤ i < j ≤ n, bi and bj are coprime, i. e. GCD(bi, bj) = 1, where GCD(w, z) is the greatest common divisor of w and z.
Ehab wants to choose a special array so he wants the lexicographically minimal array between all the variants. Can you find it?
An array x is lexicographically greater than an array y if there exists an index i such than xi > yi and xj = yj for all 1 ≤ j < i. An array x is equal to an array y if xi = yi for all 1 ≤ i ≤ n.
Input
The first line contains an integer n (1 ≤ n ≤ 105), the number of elements in a and b.
The second line contains n integers a1, a2, ..., an (2 ≤ ai ≤ 105), the elements of a.
Output
Output n space-separated integers, the i-th of them representing bi.
Examples
Input
5
2 3 5 4 13
Output
2 3 5 7 11
Input
3
10 3 7
Output
10 3 7
Note
Note that in the second sample, the array is already pairwise coprime so we printed it.
Tags: constructive algorithms, greedy, math, number theory
Correct Solution:
```
# -*- coding: UTF-8 -*-
MAX_NUM = 2000000
prime_str = ('2 3 5 7 11 13 17 19 23 29 '
+ '31 37 41 43 47 53 59 61 67 71 '
+ '73 79 83 89 97 101 103 107 109 113 '
+ '127 131 137 139 149 151 157 163 167 173 '
+ '179 181 191 193 197 199 211 223 227 229 '
+ '233 239 241 251 257 263 269 271 277 281 '
+ '283 293 307 311 313 317 '
)
prime_list = [int(p) for p in prime_str.split()]
used = [False] * MAX_NUM
n = int(input())
a = list(map(int, input().split()))
def record(x):
t = []
for p in prime_list:
if x % p == 0:
while x % p == 0:
x = x // p
t.append(p)
if x == 1:
break
if x != 1:
t.append(x)
for ti in t:
for i in range(ti, MAX_NUM, ti):
used[i] = True
b = []
for ai in a:
if not used[ai]:
b.append(ai)
record(ai)
else:
tmp = ai + 1
while used[tmp]:
tmp += 1
b.append(tmp)
record(tmp)
break
tmp = 2
while len(b) < len(a):
while used[tmp]:
tmp += 1
b.append(tmp)
record(tmp)
print(' '.join(str(x) for x in b))
```
| 4,785 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud has an array a consisting of n integers. He asked Ehab to find another array b of the same length such that:
* b is lexicographically greater than or equal to a.
* bi ≥ 2.
* b is pairwise coprime: for every 1 ≤ i < j ≤ n, bi and bj are coprime, i. e. GCD(bi, bj) = 1, where GCD(w, z) is the greatest common divisor of w and z.
Ehab wants to choose a special array so he wants the lexicographically minimal array between all the variants. Can you find it?
An array x is lexicographically greater than an array y if there exists an index i such than xi > yi and xj = yj for all 1 ≤ j < i. An array x is equal to an array y if xi = yi for all 1 ≤ i ≤ n.
Input
The first line contains an integer n (1 ≤ n ≤ 105), the number of elements in a and b.
The second line contains n integers a1, a2, ..., an (2 ≤ ai ≤ 105), the elements of a.
Output
Output n space-separated integers, the i-th of them representing bi.
Examples
Input
5
2 3 5 4 13
Output
2 3 5 7 11
Input
3
10 3 7
Output
10 3 7
Note
Note that in the second sample, the array is already pairwise coprime so we printed it.
Tags: constructive algorithms, greedy, math, number theory
Correct Solution:
```
MAX_NUM = 2000000
prime_str = ('2 3 5 7 11 13 17 19 23 29 '
+ '31 37 41 43 47 53 59 61 67 71 '
+ '73 79 83 89 97 101 103 107 109 113 '
+ '127 131 137 139 149 151 157 163 167 173 '
+ '179 181 191 193 197 199 211 223 227 229 '
+ '233 239 241 251 257 263 269 271 277 281 '
+ '283 293 307 311 313 317 '
)
prime_list = [int(p) for p in prime_str.split()]
used = [False] * MAX_NUM
n = int(input())
a = list(map(int, input().split()))
def record(x):
t = []
for p in prime_list:
if x % p == 0:
while x % p == 0:
x = x // p
t.append(p)
if x == 1:
break
if x != 1:
t.append(x)
for ti in t:
for i in range(ti, MAX_NUM, ti):
used[i] = True
b = []
for ai in a:
if not used[ai]:
b.append(ai)
record(ai)
else:
temp = ai + 1
while used[temp]:
temp += 1
b.append(temp)
record(temp)
break
temp = 2
while len(b) < len(a):
while used[temp]:
temp += 1
b.append(temp)
record(temp)
print(' '.join(str(x) for x in b))
```
| 4,786 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mahmoud has an array a consisting of n integers. He asked Ehab to find another array b of the same length such that:
* b is lexicographically greater than or equal to a.
* bi ≥ 2.
* b is pairwise coprime: for every 1 ≤ i < j ≤ n, bi and bj are coprime, i. e. GCD(bi, bj) = 1, where GCD(w, z) is the greatest common divisor of w and z.
Ehab wants to choose a special array so he wants the lexicographically minimal array between all the variants. Can you find it?
An array x is lexicographically greater than an array y if there exists an index i such than xi > yi and xj = yj for all 1 ≤ j < i. An array x is equal to an array y if xi = yi for all 1 ≤ i ≤ n.
Input
The first line contains an integer n (1 ≤ n ≤ 105), the number of elements in a and b.
The second line contains n integers a1, a2, ..., an (2 ≤ ai ≤ 105), the elements of a.
Output
Output n space-separated integers, the i-th of them representing bi.
Examples
Input
5
2 3 5 4 13
Output
2 3 5 7 11
Input
3
10 3 7
Output
10 3 7
Note
Note that in the second sample, the array is already pairwise coprime so we printed it.
Tags: constructive algorithms, greedy, math, number theory
Correct Solution:
```
"""Codeforces P959D. Mahmoud and Ehab and another array construction task
(http://codeforces.com/problemset/problem/959/D)
Problem tags: constructive algorithms, greedy, number theory
Hint: Use sieve to keep the list of numbers which are coprime with every number
in the array. When a new elem is add to the array, the sieve is updated for
the prime factors of the new elem. The length of sieve should be larger than
n-th prime, which is 1,299,709 when n is 10^6. (This code uses 150000 for
the sieve size.)
Time Complexity: O(nlog^2(n))
"""
import atexit
import io
import sys
# Buffering IO
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
def prime_list(n):
""" Returns a list of primes < n """
sieve = [True] * n
for i in range(3, int(n ** 0.5) + 1, 2):
if sieve[i]:
sieve[i*i::2*i] = [False] * ((n - i * i - 1) // (2 * i) + 1)
return [2] + [i for i in range(3, n, 2) if sieve[i]]
def prime_factors(n):
if (not hasattr(prime_factors, "primes") or
prime_factors.primes[-1] ** 2 < n):
prime_factors.primes = prime_list(max(5000, int(n ** 0.5) + 1))
res = []
for p in prime_factors.primes:
if p * p > n:
break
count = 0
while n % p == 0:
n //= p
count += 1
if count:
res.append((p, count))
if n == 1:
break
if n != 1:
res.append((n, 1))
return res
def update_available(n, available):
pf = prime_factors(n)
for p, _ in pf:
if available[p]:
available[p::p] = [False] * ((len(available) - 1) // p)
def main():
n = int(input())
a = [int(x) for x in input().split()]
b = []
available = [True] * 1500000
for a_num in a:
if available[a_num] == True:
b.append(a_num)
update_available(a_num, available)
else:
b_num = available.index(True, a_num)
b.append(b_num)
update_available(b_num, available)
break
b_num = 2
while len(b) < n:
b_num = available.index(True, b_num)
b.append(b_num)
update_available(b_num, available)
print(' '.join(str(x) for x in b))
if __name__ == '__main__':
main()
```
| 4,787 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud has an array a consisting of n integers. He asked Ehab to find another array b of the same length such that:
* b is lexicographically greater than or equal to a.
* bi ≥ 2.
* b is pairwise coprime: for every 1 ≤ i < j ≤ n, bi and bj are coprime, i. e. GCD(bi, bj) = 1, where GCD(w, z) is the greatest common divisor of w and z.
Ehab wants to choose a special array so he wants the lexicographically minimal array between all the variants. Can you find it?
An array x is lexicographically greater than an array y if there exists an index i such than xi > yi and xj = yj for all 1 ≤ j < i. An array x is equal to an array y if xi = yi for all 1 ≤ i ≤ n.
Input
The first line contains an integer n (1 ≤ n ≤ 105), the number of elements in a and b.
The second line contains n integers a1, a2, ..., an (2 ≤ ai ≤ 105), the elements of a.
Output
Output n space-separated integers, the i-th of them representing bi.
Examples
Input
5
2 3 5 4 13
Output
2 3 5 7 11
Input
3
10 3 7
Output
10 3 7
Note
Note that in the second sample, the array is already pairwise coprime so we printed it.
Submitted Solution:
```
max_primes = 2*10**6
def get_primes(n):
""" Создание списка простых чисел меньших n
:param n: верхняя границаб до которой ищем простые числа
:return: отсортированный список простых чисе от 2 до n
"""
numbers = set(range(n, 1, -1))
primes = []
while numbers:
p = numbers.pop()
primes.append(p)
numbers.difference_update(set(range(p*2, n+1, p)))
primes_list = list(primes)
primes_list.sort()
return primes_list
def gcd (a,b):
if (b == 0):
return a
else:
return gcd (b, a % b)
def nextel(s):
for i in range(s,max_primes):
next_prime = primes[i]
for j in b:
if gcd(next_prime, j ) >1:
break
else:
return next_prime
primes = get_primes(max_primes)
n = int(input())
arr = list(map(int, input().split()))
b = [max(2, arr[0])]
bigger = b[0] > arr[0]
start = 0
for el in arr[1:]:
if bigger:
next_best = nextel(start)
b.append(next_best)
start += 1
else:
k = start
while True:
next_best = nextel(k)
if next_best >= el:
break
else:
k +=1
b.append(next_best)
bigger = next_best > el
# print(primes[:10])
print(*b)
```
No
| 4,788 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud has an array a consisting of n integers. He asked Ehab to find another array b of the same length such that:
* b is lexicographically greater than or equal to a.
* bi ≥ 2.
* b is pairwise coprime: for every 1 ≤ i < j ≤ n, bi and bj are coprime, i. e. GCD(bi, bj) = 1, where GCD(w, z) is the greatest common divisor of w and z.
Ehab wants to choose a special array so he wants the lexicographically minimal array between all the variants. Can you find it?
An array x is lexicographically greater than an array y if there exists an index i such than xi > yi and xj = yj for all 1 ≤ j < i. An array x is equal to an array y if xi = yi for all 1 ≤ i ≤ n.
Input
The first line contains an integer n (1 ≤ n ≤ 105), the number of elements in a and b.
The second line contains n integers a1, a2, ..., an (2 ≤ ai ≤ 105), the elements of a.
Output
Output n space-separated integers, the i-th of them representing bi.
Examples
Input
5
2 3 5 4 13
Output
2 3 5 7 11
Input
3
10 3 7
Output
10 3 7
Note
Note that in the second sample, the array is already pairwise coprime so we printed it.
Submitted Solution:
```
def IsPrime(n):
d = 2
while d * d <= n and n % d != 0:
d += 1
return d * d > n
prime = []
for i in range(100000):
if IsPrime(i):
prime.append(i)
prime.pop(0)
prime.pop(0)
def Factor(n):
Ans = []
d = 2
while d * d <= n:
if n % d == 0:
Ans.append(d)
n //= d
else:
d += 1
if n > 1:
Ans.append(n)
return Ans
ans = []
n = int(input())
s = input().split()
nums = []
for i in range(n):
nums.append(int(s[i]))
dels = []
delssprev = []
gi = 0
for i in nums:
dels += (Factor(i))
delss = set(dels)
if len(delss) < len(dels):
gi = i
break
delssprev = delss
ans.append(i)
for i in prime:
if i > gi and i not in delssprev:
ans.append(i)
delssprev.add(i)
break
ost = n - len(ans)
if delssprev:
for i in delssprev:
prime.pop(prime.index(i))
for i in range(ost):
ans.append(prime.pop(0))
sans = ''
for i in ans:
sans += str(i) + ' '
print(sans)
```
No
| 4,789 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud has an array a consisting of n integers. He asked Ehab to find another array b of the same length such that:
* b is lexicographically greater than or equal to a.
* bi ≥ 2.
* b is pairwise coprime: for every 1 ≤ i < j ≤ n, bi and bj are coprime, i. e. GCD(bi, bj) = 1, where GCD(w, z) is the greatest common divisor of w and z.
Ehab wants to choose a special array so he wants the lexicographically minimal array between all the variants. Can you find it?
An array x is lexicographically greater than an array y if there exists an index i such than xi > yi and xj = yj for all 1 ≤ j < i. An array x is equal to an array y if xi = yi for all 1 ≤ i ≤ n.
Input
The first line contains an integer n (1 ≤ n ≤ 105), the number of elements in a and b.
The second line contains n integers a1, a2, ..., an (2 ≤ ai ≤ 105), the elements of a.
Output
Output n space-separated integers, the i-th of them representing bi.
Examples
Input
5
2 3 5 4 13
Output
2 3 5 7 11
Input
3
10 3 7
Output
10 3 7
Note
Note that in the second sample, the array is already pairwise coprime so we printed it.
Submitted Solution:
```
def gcd(a,b):
if a>b:
a,b=b,a
if a==0:
return(b)
return(gcd(b%a,a))
n=int(input())
a=list(map(int,input().split()))
b=[str(a[0])]
g=a[0]
m=2
bol1=True
for i in range(1,n):
ai=a[i]
if bol1:
j=ai+1-ai%2
while gcd(g,j)!=1:
j+=2
else:
j=m
bol=True
while (j<ai and bol1) or gcd(g,j)!=1:
if j==2:
j=3
else:
j+=2
bol=bol and gcd(g,j)==1
if bol:
m=j
bol1=j==ai
b.append(str(j))
g*=j
print(' '.join(b))
```
No
| 4,790 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mahmoud has an array a consisting of n integers. He asked Ehab to find another array b of the same length such that:
* b is lexicographically greater than or equal to a.
* bi ≥ 2.
* b is pairwise coprime: for every 1 ≤ i < j ≤ n, bi and bj are coprime, i. e. GCD(bi, bj) = 1, where GCD(w, z) is the greatest common divisor of w and z.
Ehab wants to choose a special array so he wants the lexicographically minimal array between all the variants. Can you find it?
An array x is lexicographically greater than an array y if there exists an index i such than xi > yi and xj = yj for all 1 ≤ j < i. An array x is equal to an array y if xi = yi for all 1 ≤ i ≤ n.
Input
The first line contains an integer n (1 ≤ n ≤ 105), the number of elements in a and b.
The second line contains n integers a1, a2, ..., an (2 ≤ ai ≤ 105), the elements of a.
Output
Output n space-separated integers, the i-th of them representing bi.
Examples
Input
5
2 3 5 4 13
Output
2 3 5 7 11
Input
3
10 3 7
Output
10 3 7
Note
Note that in the second sample, the array is already pairwise coprime so we printed it.
Submitted Solution:
```
m = 300500
n = int(input())
b = map(int, input().split())
r = []
a = [0] * m
def gf(n):
d = 2
while d * d <= n:
f = 1
while n % d is 0:
if f:
yield d
f = 0
n //= d
d += 1
if n > 1:
yield n
def f(x):
r.append(x)
for y in gf(x):
for i in range(y, m, y):
a[i] = 1
for x in b:
if a[x]:
break
f(x)
if len(r) < n:
for i in range(x + 1, m):
if not a[i]:
f(i)
break
k = 2
for i in range(len(r), n):
for j in range(k, m):
if not a[j]:
f(j)
k = j + 1
break
print(*r)
```
No
| 4,791 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from 1 to n and then 3n times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements 7n+1 times instead of 3n times. Because it is more random, OK?!
You somehow get a test from one of these problems and now you want to know from which one.
Input
In the first line of input there is one integer n (10^{3} ≤ n ≤ 10^{6}).
In the second line there are n distinct integers between 1 and n — the permutation of size n from the test.
It is guaranteed that all tests except for sample are generated this way: First we choose n — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
Output
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
Example
Input
5
2 4 5 1 3
Output
Petr
Note
Please note that the sample is not a valid test (because of limitations for n) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.
Due to randomness of input hacks in this problem are forbidden.
Tags: combinatorics, math
Correct Solution:
```
n=int(input())
a=list(map(int,input().split()))
if sum(a[i]==i+1 for i in range(n))>=n//1000:print("Petr")
else:print("Um_nik")
```
| 4,792 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from 1 to n and then 3n times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements 7n+1 times instead of 3n times. Because it is more random, OK?!
You somehow get a test from one of these problems and now you want to know from which one.
Input
In the first line of input there is one integer n (10^{3} ≤ n ≤ 10^{6}).
In the second line there are n distinct integers between 1 and n — the permutation of size n from the test.
It is guaranteed that all tests except for sample are generated this way: First we choose n — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
Output
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
Example
Input
5
2 4 5 1 3
Output
Petr
Note
Please note that the sample is not a valid test (because of limitations for n) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.
Due to randomness of input hacks in this problem are forbidden.
Tags: combinatorics, math
Correct Solution:
```
input()
a=list(map(int,input().split()))
n=len(a)
u=n
for i in range(n):
j=i
k=0
while a[j]>0:
k+=1
t=j
j=a[j]-1
a[t]=0
if k>0:
u+=1-k%2
s='Petr'
if u%2>0:
s='Um_nik'
print(s)
```
| 4,793 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from 1 to n and then 3n times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements 7n+1 times instead of 3n times. Because it is more random, OK?!
You somehow get a test from one of these problems and now you want to know from which one.
Input
In the first line of input there is one integer n (10^{3} ≤ n ≤ 10^{6}).
In the second line there are n distinct integers between 1 and n — the permutation of size n from the test.
It is guaranteed that all tests except for sample are generated this way: First we choose n — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
Output
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
Example
Input
5
2 4 5 1 3
Output
Petr
Note
Please note that the sample is not a valid test (because of limitations for n) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.
Due to randomness of input hacks in this problem are forbidden.
Tags: combinatorics, math
Correct Solution:
```
#!/usr/bin/env python3
n = int(input().strip())
ais = list(map(int, input().strip().split()))
visited = [False for _ in range(n)]
parity = 0
for i in range(n):
if not visited[i]:
parity += 1
j = i
while not visited[j]:
visited[j] = True
j = ais[j] - 1
if parity % 2 == 0:
print ('Petr')
else:
print ('Um_nik')
```
| 4,794 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from 1 to n and then 3n times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements 7n+1 times instead of 3n times. Because it is more random, OK?!
You somehow get a test from one of these problems and now you want to know from which one.
Input
In the first line of input there is one integer n (10^{3} ≤ n ≤ 10^{6}).
In the second line there are n distinct integers between 1 and n — the permutation of size n from the test.
It is guaranteed that all tests except for sample are generated this way: First we choose n — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
Output
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
Example
Input
5
2 4 5 1 3
Output
Petr
Note
Please note that the sample is not a valid test (because of limitations for n) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.
Due to randomness of input hacks in this problem are forbidden.
Tags: combinatorics, math
Correct Solution:
```
n = int( input() )
a = list( map( lambda x: int( x )-1, input().split( ' ' ) ) )
ret = True
for i in range( n ):
if a[i]==-1: continue
x, ret = i, not ret
while a[x]!=i:
a[x], x = -1, a[x]
a[x] = -1
if ret: print( "Petr" )
else: print( "Um_nik" )
```
| 4,795 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from 1 to n and then 3n times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements 7n+1 times instead of 3n times. Because it is more random, OK?!
You somehow get a test from one of these problems and now you want to know from which one.
Input
In the first line of input there is one integer n (10^{3} ≤ n ≤ 10^{6}).
In the second line there are n distinct integers between 1 and n — the permutation of size n from the test.
It is guaranteed that all tests except for sample are generated this way: First we choose n — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
Output
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
Example
Input
5
2 4 5 1 3
Output
Petr
Note
Please note that the sample is not a valid test (because of limitations for n) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.
Due to randomness of input hacks in this problem are forbidden.
Tags: combinatorics, math
Correct Solution:
```
n = int(input())
u = list(map(int, input().split()))
for i in range(n):
u[i] -= 1
ans = 0
for i in range(n):
if u[i] == -1:
continue
ans = 1 - ans
x = i
while x >= 0:
y = u[x]
u[x] = -1
x = y
if ans:
print('Um_nik')
else:
print('Petr')
```
| 4,796 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from 1 to n and then 3n times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements 7n+1 times instead of 3n times. Because it is more random, OK?!
You somehow get a test from one of these problems and now you want to know from which one.
Input
In the first line of input there is one integer n (10^{3} ≤ n ≤ 10^{6}).
In the second line there are n distinct integers between 1 and n — the permutation of size n from the test.
It is guaranteed that all tests except for sample are generated this way: First we choose n — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
Output
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
Example
Input
5
2 4 5 1 3
Output
Petr
Note
Please note that the sample is not a valid test (because of limitations for n) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.
Due to randomness of input hacks in this problem are forbidden.
Tags: combinatorics, math
Correct Solution:
```
n=int(input())
a=[0] + list(map(int,input().split()))
d={}
for i in range(1,n+1):
d[a[i]]=i
ans=0
for i in range(1,n+1):
if a[i]!=i:
ind1=d[a[i]]
ind2=d[i]
va1=a[i]
val2=i
a[ind1],a[ind2]=a[ind2],a[ind1]
d[i]=i
d[va1]=ind2
ans+=1
# print(a,ans,d)
# print(ans)
if (3*n - ans)%2==0:
print("Petr")
else:
print("Um_nik")
```
| 4,797 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from 1 to n and then 3n times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements 7n+1 times instead of 3n times. Because it is more random, OK?!
You somehow get a test from one of these problems and now you want to know from which one.
Input
In the first line of input there is one integer n (10^{3} ≤ n ≤ 10^{6}).
In the second line there are n distinct integers between 1 and n — the permutation of size n from the test.
It is guaranteed that all tests except for sample are generated this way: First we choose n — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
Output
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
Example
Input
5
2 4 5 1 3
Output
Petr
Note
Please note that the sample is not a valid test (because of limitations for n) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.
Due to randomness of input hacks in this problem are forbidden.
Tags: combinatorics, math
Correct Solution:
```
import sys
n = int(sys.stdin.readline().rstrip())
nums = list(map(int, sys.stdin.readline().split()))
swaps = 0
visited = set()
for index in range(n):
if index in visited:
continue
else:
visited.add(index)
length = 0
value = nums[index]
while (value != index + 1):
visited.add(value - 1)
value = nums[value - 1]
length += 1
swaps += length
if ((3 * n - swaps) % 2):
print("Um_nik")
else:
print("Petr")
```
| 4,798 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from 1 to n and then 3n times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements 7n+1 times instead of 3n times. Because it is more random, OK?!
You somehow get a test from one of these problems and now you want to know from which one.
Input
In the first line of input there is one integer n (10^{3} ≤ n ≤ 10^{6}).
In the second line there are n distinct integers between 1 and n — the permutation of size n from the test.
It is guaranteed that all tests except for sample are generated this way: First we choose n — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method.
Output
If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).
Example
Input
5
2 4 5 1 3
Output
Petr
Note
Please note that the sample is not a valid test (because of limitations for n) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.
Due to randomness of input hacks in this problem are forbidden.
Tags: combinatorics, math
Correct Solution:
```
class BIT:
__all__ = ['add', 'sumrange', 'lower_left']
def __init__(self, maxsize=10**7):
assert (maxsize > 0)
self._n = maxsize+1
self._bitdata = [0]*(maxsize+1)
def add(self, i, x):
'''Add x to A[i] (A[i] += x) '''
assert(0 <= i < self._n)
pos = i+1
while pos < self._n:
self._bitdata[pos] += x
pos += pos&(-pos)
def running_total(self, i):
''' Return sum of (A[0] ... A[i]) '''
assert (-1<= i < self._n)
if i == -1:
return 0
returnval = 0
pos = i+1
while pos:
returnval += self._bitdata[pos]
pos -= pos & (-pos)
return returnval
def sumrange(self, lo=0, hi=None):
''' Return sum of (A[lo] ... A[hi]) '''
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = self._n
return self.running_total(hi) - self.running_total(lo-1)
def lower_left(self, total):
''' Return min-index satisfying {sum(A0 ~ Ai) >= total}
only if Ai >= 0 (for all i)
'''
if total < 0:
return -1
pos = 0
k = 1<<(self._n.bit_length()-1)
while k > 0:
if pos+k < self._n and self._bitdata[pos+k] < total:
total -= self._bitdata[pos+k]
pos += k
k //= 2
return pos
def tentousu(lis):
bit = BIT()
ans = 0
for i in range(len(lis)):
bit.add(lis[i], 1)
ans += i + 1 - bit.running_total(lis[i])
return ans
N=int(input())
L=list(map(int,input().split()))
a=tentousu(L)
a%=2
if N%2==0 and a%2==0:
print("Petr")
if N%2==0 and a%2==1:
print("Um_nik")
if N%2==1 and a%2==0:
print("Um_nik")
if N%2==1 and a%2==1:
print("Petr")
```
| 4,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.