text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
We get more and more news about DDoS-attacks of popular websites.
Arseny is an admin and he thinks that a website is under a DDoS-attack if the total number of requests for a some period of time exceeds 100 ⋅ t, where t — the number of seconds in this time segment.
Arseny knows statistics on the number of requests per second since the server is booted. He knows the sequence r_1, r_2, ..., r_n, where r_i — the number of requests in the i-th second after boot.
Determine the length of the longest continuous period of time, which Arseny considers to be a DDoS-attack. A seeking time period should not go beyond the boundaries of the segment [1, n].
Input
The first line contains n (1 ≤ n ≤ 5000) — number of seconds since server has been booted. The second line contains sequence of integers r_1, r_2, ..., r_n (0 ≤ r_i ≤ 5000), r_i — number of requests in the i-th second.
Output
Print the only integer number — the length of the longest time period which is considered to be a DDoS-attack by Arseny. If it doesn't exist print 0.
Examples
Input
5
100 200 1 1 1
Output
3
Input
5
1 2 3 4 5
Output
0
Input
2
101 99
Output
1
Tags: *special, brute force
Correct Solution:
```
n = int(input())
ri = list(map(int,input().split()))
ar = [0] * (n+1)
ar[1] = ri[0]
for i in range(1,n):
ar[i+1] = ar[i] + ri[i]
ans = 0
for i in range(n+1):
for j in range(i+1,n+1):
num = ar[j] - ar[i]
num2 = j - i
if num > num2 * 100:
ans = max(ans,num2)
print(ans)
```
| 101,200 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We get more and more news about DDoS-attacks of popular websites.
Arseny is an admin and he thinks that a website is under a DDoS-attack if the total number of requests for a some period of time exceeds 100 ⋅ t, where t — the number of seconds in this time segment.
Arseny knows statistics on the number of requests per second since the server is booted. He knows the sequence r_1, r_2, ..., r_n, where r_i — the number of requests in the i-th second after boot.
Determine the length of the longest continuous period of time, which Arseny considers to be a DDoS-attack. A seeking time period should not go beyond the boundaries of the segment [1, n].
Input
The first line contains n (1 ≤ n ≤ 5000) — number of seconds since server has been booted. The second line contains sequence of integers r_1, r_2, ..., r_n (0 ≤ r_i ≤ 5000), r_i — number of requests in the i-th second.
Output
Print the only integer number — the length of the longest time period which is considered to be a DDoS-attack by Arseny. If it doesn't exist print 0.
Examples
Input
5
100 200 1 1 1
Output
3
Input
5
1 2 3 4 5
Output
0
Input
2
101 99
Output
1
Tags: *special, brute force
Correct Solution:
```
n = int(input())
numbers = [int(x) - 100 for x in input().split()]
maxi = 0
acc_index = -1
for acc_index in range(n):
suma = 0
for index in range(acc_index, n):
suma = suma + numbers[index]
if suma > 0:
maxi = max(maxi, index-acc_index+1)
print(maxi)
```
| 101,201 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We get more and more news about DDoS-attacks of popular websites.
Arseny is an admin and he thinks that a website is under a DDoS-attack if the total number of requests for a some period of time exceeds 100 ⋅ t, where t — the number of seconds in this time segment.
Arseny knows statistics on the number of requests per second since the server is booted. He knows the sequence r_1, r_2, ..., r_n, where r_i — the number of requests in the i-th second after boot.
Determine the length of the longest continuous period of time, which Arseny considers to be a DDoS-attack. A seeking time period should not go beyond the boundaries of the segment [1, n].
Input
The first line contains n (1 ≤ n ≤ 5000) — number of seconds since server has been booted. The second line contains sequence of integers r_1, r_2, ..., r_n (0 ≤ r_i ≤ 5000), r_i — number of requests in the i-th second.
Output
Print the only integer number — the length of the longest time period which is considered to be a DDoS-attack by Arseny. If it doesn't exist print 0.
Examples
Input
5
100 200 1 1 1
Output
3
Input
5
1 2 3 4 5
Output
0
Input
2
101 99
Output
1
Tags: *special, brute force
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
pref = [0] * (n + 1)
for i in range(1, n + 1):
pref[i] = pref[i - 1] + a[i - 1]
res = 0
for l in range(1, n + 1):
for r in range(l, n + 1):
if (pref[r] - pref[l - 1] > 100 * (r - l + 1)):
res = max(res, r - l + 1)
print(res)
```
| 101,202 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We get more and more news about DDoS-attacks of popular websites.
Arseny is an admin and he thinks that a website is under a DDoS-attack if the total number of requests for a some period of time exceeds 100 ⋅ t, where t — the number of seconds in this time segment.
Arseny knows statistics on the number of requests per second since the server is booted. He knows the sequence r_1, r_2, ..., r_n, where r_i — the number of requests in the i-th second after boot.
Determine the length of the longest continuous period of time, which Arseny considers to be a DDoS-attack. A seeking time period should not go beyond the boundaries of the segment [1, n].
Input
The first line contains n (1 ≤ n ≤ 5000) — number of seconds since server has been booted. The second line contains sequence of integers r_1, r_2, ..., r_n (0 ≤ r_i ≤ 5000), r_i — number of requests in the i-th second.
Output
Print the only integer number — the length of the longest time period which is considered to be a DDoS-attack by Arseny. If it doesn't exist print 0.
Examples
Input
5
100 200 1 1 1
Output
3
Input
5
1 2 3 4 5
Output
0
Input
2
101 99
Output
1
Tags: *special, brute force
Correct Solution:
```
import sys
input = sys.stdin.readline
'''
'''
n = int(input())
r = list(map(int, input().split()))
prefix_sum = [r[0]]
for i in range(1, n):
prefix_sum.append(prefix_sum[-1] + r[i])
best = 0
done = False
for length in reversed(range(1,n+1)):
treshold = 100*length
for i in range(n-length+1):
pre = 0 if i == 0 else prefix_sum[i-1]
total = prefix_sum[i+length-1] - pre
if total > treshold:
done = True
best = length
break
if done:
break
print(best)
```
| 101,203 |
Provide tags and a correct Python 3 solution for this coding contest problem.
We get more and more news about DDoS-attacks of popular websites.
Arseny is an admin and he thinks that a website is under a DDoS-attack if the total number of requests for a some period of time exceeds 100 ⋅ t, where t — the number of seconds in this time segment.
Arseny knows statistics on the number of requests per second since the server is booted. He knows the sequence r_1, r_2, ..., r_n, where r_i — the number of requests in the i-th second after boot.
Determine the length of the longest continuous period of time, which Arseny considers to be a DDoS-attack. A seeking time period should not go beyond the boundaries of the segment [1, n].
Input
The first line contains n (1 ≤ n ≤ 5000) — number of seconds since server has been booted. The second line contains sequence of integers r_1, r_2, ..., r_n (0 ≤ r_i ≤ 5000), r_i — number of requests in the i-th second.
Output
Print the only integer number — the length of the longest time period which is considered to be a DDoS-attack by Arseny. If it doesn't exist print 0.
Examples
Input
5
100 200 1 1 1
Output
3
Input
5
1 2 3 4 5
Output
0
Input
2
101 99
Output
1
Tags: *special, brute force
Correct Solution:
```
n = int(input())
r = list(map(int, input().split()))
s = [0] * n
s[0] = r[0]
for i in range(1, n):
s[i] = s[i - 1] + r[i]
ans = 0
for i in range(n):
for j in range(i, n):
num = s[j] - s[i] + r[i]
time = j + 1 - i
if num / time > 100 and time > ans:
ans = time
print(ans)
```
| 101,204 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We get more and more news about DDoS-attacks of popular websites.
Arseny is an admin and he thinks that a website is under a DDoS-attack if the total number of requests for a some period of time exceeds 100 ⋅ t, where t — the number of seconds in this time segment.
Arseny knows statistics on the number of requests per second since the server is booted. He knows the sequence r_1, r_2, ..., r_n, where r_i — the number of requests in the i-th second after boot.
Determine the length of the longest continuous period of time, which Arseny considers to be a DDoS-attack. A seeking time period should not go beyond the boundaries of the segment [1, n].
Input
The first line contains n (1 ≤ n ≤ 5000) — number of seconds since server has been booted. The second line contains sequence of integers r_1, r_2, ..., r_n (0 ≤ r_i ≤ 5000), r_i — number of requests in the i-th second.
Output
Print the only integer number — the length of the longest time period which is considered to be a DDoS-attack by Arseny. If it doesn't exist print 0.
Examples
Input
5
100 200 1 1 1
Output
3
Input
5
1 2 3 4 5
Output
0
Input
2
101 99
Output
1
Submitted Solution:
```
from bisect import insort,bisect_right,bisect_left
from sys import stdout, stdin, setrecursionlimit
from heapq import heappush, heappop, heapify
from io import BytesIO, IOBase
from collections import *
from itertools import *
from random import *
from string import *
from queue import *
from math import *
from re import *
from os import *
# sqrt,ceil,floor,factorial,gcd,log2,log10,comb
####################################---fast-input-output----#########################################
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = read(self._fd, max(fstat(self._fd).st_size, 8192))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = read(self._fd, max(fstat(self._fd).st_size, 8192))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
stdin, stdout = IOWrapper(stdin), IOWrapper(stdout)
graph, mod, szzz = {}, 10**9 + 7, lambda: sorted(zzz())
def getStr(): return input()
def getInt(): return int(input())
def listStr(): return list(input())
def getStrs(): return input().split()
def isInt(s): return '0' <= s[0] <= '9'
def input(): return stdin.readline().strip()
def zzz(): return [int(i) for i in input().split()]
def output(answer, end='\n'): stdout.write(str(answer) + end)
def lcd(xnum1, xnum2): return (xnum1 * xnum2 // gcd(xnum1, xnum2))
def getPrimes(N = 10**5):
SN = int(sqrt(N))
sieve = [i for i in range(N+1)]
sieve[1] = 0
for i in sieve:
if i > SN:
break
if i == 0:
continue
for j in range(2*i, N+1, i):
sieve[j] = 0
prime = [i for i in range(N+1) if sieve[i] != 0]
return prime
def primeFactor(n,prime=getPrimes()):
lst = []
mx=int(sqrt(n))+1
for i in prime:
if i>mx:break
while n%i==0:
lst.append(i)
n//=i
if n>1:
lst.append(n)
return lst
dx = [-1, 1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, 1, -1, 1, -1, -1, 1]
daysInMounth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
#################################################---Some Rule For Me To Follow---#################################
"""
--instants of Reading problem continuously try to understand them.
--If you Know some-one , Then you probably don't know him !
--Try & again try, maybe you're just one statement away!
"""
##################################################---START-CODING---###############################################
n = getInt()
arr = zzz()
ans = 0
s=0
mx = 0
for i in range(n):
s=0
for j in range(i,n):
s+=arr[j]
if s>(j-i+1)*100:
mx=max(mx,(j-i+1))
print(mx)
```
Yes
| 101,205 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We get more and more news about DDoS-attacks of popular websites.
Arseny is an admin and he thinks that a website is under a DDoS-attack if the total number of requests for a some period of time exceeds 100 ⋅ t, where t — the number of seconds in this time segment.
Arseny knows statistics on the number of requests per second since the server is booted. He knows the sequence r_1, r_2, ..., r_n, where r_i — the number of requests in the i-th second after boot.
Determine the length of the longest continuous period of time, which Arseny considers to be a DDoS-attack. A seeking time period should not go beyond the boundaries of the segment [1, n].
Input
The first line contains n (1 ≤ n ≤ 5000) — number of seconds since server has been booted. The second line contains sequence of integers r_1, r_2, ..., r_n (0 ≤ r_i ≤ 5000), r_i — number of requests in the i-th second.
Output
Print the only integer number — the length of the longest time period which is considered to be a DDoS-attack by Arseny. If it doesn't exist print 0.
Examples
Input
5
100 200 1 1 1
Output
3
Input
5
1 2 3 4 5
Output
0
Input
2
101 99
Output
1
Submitted Solution:
```
from itertools import accumulate, combinations
seconds_since_boot = int(input())
arr = [0] + list(accumulate(map(lambda x:int(x) - 100, input().split())))
longest = 0
for start, end in combinations(range(seconds_since_boot + 1), 2):
if end-start > longest and arr[end] - arr[start] > 0:
longest = end - start
print(longest)
```
Yes
| 101,206 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We get more and more news about DDoS-attacks of popular websites.
Arseny is an admin and he thinks that a website is under a DDoS-attack if the total number of requests for a some period of time exceeds 100 ⋅ t, where t — the number of seconds in this time segment.
Arseny knows statistics on the number of requests per second since the server is booted. He knows the sequence r_1, r_2, ..., r_n, where r_i — the number of requests in the i-th second after boot.
Determine the length of the longest continuous period of time, which Arseny considers to be a DDoS-attack. A seeking time period should not go beyond the boundaries of the segment [1, n].
Input
The first line contains n (1 ≤ n ≤ 5000) — number of seconds since server has been booted. The second line contains sequence of integers r_1, r_2, ..., r_n (0 ≤ r_i ≤ 5000), r_i — number of requests in the i-th second.
Output
Print the only integer number — the length of the longest time period which is considered to be a DDoS-attack by Arseny. If it doesn't exist print 0.
Examples
Input
5
100 200 1 1 1
Output
3
Input
5
1 2 3 4 5
Output
0
Input
2
101 99
Output
1
Submitted Solution:
```
n=int(input())
l=[*map(int,input().split())]
mx=0
mxs=0
'''for i in range(n-1):
t=100
total=l[i]
if total>=t:
mxs+=1
print(l[i])
for j in range(i+1,n):
t+=100
total+=l[j]
if total>=t:
mxs+=1
print(l[j])
else:
break
mx=max(mx,mxs)
print(mx)
'''
m=0
for i in range(n):
s=0
for j in range(i,n):
s=s+l[j]
if(s>(j-i+1)*100):
m=max(m,j-i+1)
print(m)
```
Yes
| 101,207 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We get more and more news about DDoS-attacks of popular websites.
Arseny is an admin and he thinks that a website is under a DDoS-attack if the total number of requests for a some period of time exceeds 100 ⋅ t, where t — the number of seconds in this time segment.
Arseny knows statistics on the number of requests per second since the server is booted. He knows the sequence r_1, r_2, ..., r_n, where r_i — the number of requests in the i-th second after boot.
Determine the length of the longest continuous period of time, which Arseny considers to be a DDoS-attack. A seeking time period should not go beyond the boundaries of the segment [1, n].
Input
The first line contains n (1 ≤ n ≤ 5000) — number of seconds since server has been booted. The second line contains sequence of integers r_1, r_2, ..., r_n (0 ≤ r_i ≤ 5000), r_i — number of requests in the i-th second.
Output
Print the only integer number — the length of the longest time period which is considered to be a DDoS-attack by Arseny. If it doesn't exist print 0.
Examples
Input
5
100 200 1 1 1
Output
3
Input
5
1 2 3 4 5
Output
0
Input
2
101 99
Output
1
Submitted Solution:
```
n = int(input())
x = list(map(lambda y: int(y) - 100, input().split()))
max_time = 0
for i in range(n):
s = 0
for j in range(i, n):
s += x[j]
if s > 0:
max_time = max(max_time, j - i + 1)
print(max_time)
```
Yes
| 101,208 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We get more and more news about DDoS-attacks of popular websites.
Arseny is an admin and he thinks that a website is under a DDoS-attack if the total number of requests for a some period of time exceeds 100 ⋅ t, where t — the number of seconds in this time segment.
Arseny knows statistics on the number of requests per second since the server is booted. He knows the sequence r_1, r_2, ..., r_n, where r_i — the number of requests in the i-th second after boot.
Determine the length of the longest continuous period of time, which Arseny considers to be a DDoS-attack. A seeking time period should not go beyond the boundaries of the segment [1, n].
Input
The first line contains n (1 ≤ n ≤ 5000) — number of seconds since server has been booted. The second line contains sequence of integers r_1, r_2, ..., r_n (0 ≤ r_i ≤ 5000), r_i — number of requests in the i-th second.
Output
Print the only integer number — the length of the longest time period which is considered to be a DDoS-attack by Arseny. If it doesn't exist print 0.
Examples
Input
5
100 200 1 1 1
Output
3
Input
5
1 2 3 4 5
Output
0
Input
2
101 99
Output
1
Submitted Solution:
```
import sys
input = sys.stdin.readline
'''
'''
n = int(input())
r = list(map(int, input().split()))
prefix_sum = [r[0]]
for i in range(1, n):
prefix_sum.append(prefix_sum[-1] + r[i])
best = 0
done = False
for length in reversed(range(1,n+1)):
treshold = 100*length
for i in range(n-length+1):
pre = 0 if i == 0 else prefix_sum[i-1]
total = prefix_sum[i+length-1] - pre
if total >= treshold:
done = True
best = length
break
if done:
break
print(best)
```
No
| 101,209 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We get more and more news about DDoS-attacks of popular websites.
Arseny is an admin and he thinks that a website is under a DDoS-attack if the total number of requests for a some period of time exceeds 100 ⋅ t, where t — the number of seconds in this time segment.
Arseny knows statistics on the number of requests per second since the server is booted. He knows the sequence r_1, r_2, ..., r_n, where r_i — the number of requests in the i-th second after boot.
Determine the length of the longest continuous period of time, which Arseny considers to be a DDoS-attack. A seeking time period should not go beyond the boundaries of the segment [1, n].
Input
The first line contains n (1 ≤ n ≤ 5000) — number of seconds since server has been booted. The second line contains sequence of integers r_1, r_2, ..., r_n (0 ≤ r_i ≤ 5000), r_i — number of requests in the i-th second.
Output
Print the only integer number — the length of the longest time period which is considered to be a DDoS-attack by Arseny. If it doesn't exist print 0.
Examples
Input
5
100 200 1 1 1
Output
3
Input
5
1 2 3 4 5
Output
0
Input
2
101 99
Output
1
Submitted Solution:
```
n = int(input())
a = list(map(int,input().split()))
k = 0
for i in a:
if i >= 100:
k += 1
print(k)
```
No
| 101,210 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We get more and more news about DDoS-attacks of popular websites.
Arseny is an admin and he thinks that a website is under a DDoS-attack if the total number of requests for a some period of time exceeds 100 ⋅ t, where t — the number of seconds in this time segment.
Arseny knows statistics on the number of requests per second since the server is booted. He knows the sequence r_1, r_2, ..., r_n, where r_i — the number of requests in the i-th second after boot.
Determine the length of the longest continuous period of time, which Arseny considers to be a DDoS-attack. A seeking time period should not go beyond the boundaries of the segment [1, n].
Input
The first line contains n (1 ≤ n ≤ 5000) — number of seconds since server has been booted. The second line contains sequence of integers r_1, r_2, ..., r_n (0 ≤ r_i ≤ 5000), r_i — number of requests in the i-th second.
Output
Print the only integer number — the length of the longest time period which is considered to be a DDoS-attack by Arseny. If it doesn't exist print 0.
Examples
Input
5
100 200 1 1 1
Output
3
Input
5
1 2 3 4 5
Output
0
Input
2
101 99
Output
1
Submitted Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 18 15:50:54 2018
B.DDos
@author: rafael
"""
n = int(input())
req = [int(i) for i in input().split()]
maxi = 0
LIMIT = 100
start = None
end = None
for i in range(n):
if start is None:
if req[i] >= LIMIT: start = i
else:
if req[i] < LIMIT:
end = i
if i > 1: trial = end - start + 1
else: trial = end - start
if trial > maxi: maxi = trial
start,end = None,None
print(maxi)
```
No
| 101,211 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We get more and more news about DDoS-attacks of popular websites.
Arseny is an admin and he thinks that a website is under a DDoS-attack if the total number of requests for a some period of time exceeds 100 ⋅ t, where t — the number of seconds in this time segment.
Arseny knows statistics on the number of requests per second since the server is booted. He knows the sequence r_1, r_2, ..., r_n, where r_i — the number of requests in the i-th second after boot.
Determine the length of the longest continuous period of time, which Arseny considers to be a DDoS-attack. A seeking time period should not go beyond the boundaries of the segment [1, n].
Input
The first line contains n (1 ≤ n ≤ 5000) — number of seconds since server has been booted. The second line contains sequence of integers r_1, r_2, ..., r_n (0 ≤ r_i ≤ 5000), r_i — number of requests in the i-th second.
Output
Print the only integer number — the length of the longest time period which is considered to be a DDoS-attack by Arseny. If it doesn't exist print 0.
Examples
Input
5
100 200 1 1 1
Output
3
Input
5
1 2 3 4 5
Output
0
Input
2
101 99
Output
1
Submitted Solution:
```
T = int(input())
R = [int(i) for i in input().split()]
SUM = 0
ANSW = 0
CIRK = 0
for i in range(1,T+1):
SUM += R[i-1]
CIRK +=1
if SUM > 100*i:
ANSW=CIRK
print(ANSW)
```
No
| 101,212 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya is having a party soon, and he has decided to invite his n friends.
He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one color with k sheets. That is, each notebook contains k sheets of either red, green, or blue.
Find the minimum number of notebooks that Petya needs to buy to invite all n of his friends.
Input
The first line contains two integers n and k (1≤ n, k≤ 10^8) — the number of Petya's friends and the number of sheets in each notebook respectively.
Output
Print one number — the minimum number of notebooks that Petya needs to buy.
Examples
Input
3 5
Output
10
Input
15 6
Output
38
Note
In the first example, we need 2 red notebooks, 3 green notebooks, and 5 blue notebooks.
In the second example, we need 5 red notebooks, 13 green notebooks, and 20 blue notebooks.
Tags: math
Correct Solution:
```
# cook your dish here
n,k=map(int,input().split())
print((2*n)//k+(5*n)//k+(8*n)//k+(int((2*n)%k!=0)+int((5*n)%k!=0)+int((8*n)%k!=0)))
```
| 101,213 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya is having a party soon, and he has decided to invite his n friends.
He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one color with k sheets. That is, each notebook contains k sheets of either red, green, or blue.
Find the minimum number of notebooks that Petya needs to buy to invite all n of his friends.
Input
The first line contains two integers n and k (1≤ n, k≤ 10^8) — the number of Petya's friends and the number of sheets in each notebook respectively.
Output
Print one number — the minimum number of notebooks that Petya needs to buy.
Examples
Input
3 5
Output
10
Input
15 6
Output
38
Note
In the first example, we need 2 red notebooks, 3 green notebooks, and 5 blue notebooks.
In the second example, we need 5 red notebooks, 13 green notebooks, and 20 blue notebooks.
Tags: math
Correct Solution:
```
import math
n_str, k_str = input().split(" ")
n = int(n_str)
k = int(k_str)
num_of_red_sheets = 2*n
num_of_green_sheets = 5*n
num_of_blue_sheets = 8*n
num_of_red_notebooks = math.ceil(num_of_red_sheets / k)
num_of_green_notebooks = math.ceil(num_of_green_sheets / k)
num_of_blue_notebooks = math.ceil(num_of_blue_sheets / k)
total_notebooks = num_of_red_notebooks + num_of_green_notebooks + num_of_blue_notebooks
print(total_notebooks)
```
| 101,214 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya is having a party soon, and he has decided to invite his n friends.
He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one color with k sheets. That is, each notebook contains k sheets of either red, green, or blue.
Find the minimum number of notebooks that Petya needs to buy to invite all n of his friends.
Input
The first line contains two integers n and k (1≤ n, k≤ 10^8) — the number of Petya's friends and the number of sheets in each notebook respectively.
Output
Print one number — the minimum number of notebooks that Petya needs to buy.
Examples
Input
3 5
Output
10
Input
15 6
Output
38
Note
In the first example, we need 2 red notebooks, 3 green notebooks, and 5 blue notebooks.
In the second example, we need 5 red notebooks, 13 green notebooks, and 20 blue notebooks.
Tags: math
Correct Solution:
```
s=input()
s=s.split()
for j in range(len(s)):
s[j]=int(s[j])
n=s[0]
k=s[1]
red=2*n
green=5*n
blue=8*n
res=0
if red%k==0:
res=res+red//k
else:
res=res+red//k+1
if green%k==0:
res=res+green//k
else:
res=res+green//k+1
if blue%k==0:
res=res+blue//k
else:
res=res+blue//k+1
#res=(red//k+1)+(green//k+)+(blue//k+1)
print(res)
```
| 101,215 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya is having a party soon, and he has decided to invite his n friends.
He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one color with k sheets. That is, each notebook contains k sheets of either red, green, or blue.
Find the minimum number of notebooks that Petya needs to buy to invite all n of his friends.
Input
The first line contains two integers n and k (1≤ n, k≤ 10^8) — the number of Petya's friends and the number of sheets in each notebook respectively.
Output
Print one number — the minimum number of notebooks that Petya needs to buy.
Examples
Input
3 5
Output
10
Input
15 6
Output
38
Note
In the first example, we need 2 red notebooks, 3 green notebooks, and 5 blue notebooks.
In the second example, we need 5 red notebooks, 13 green notebooks, and 20 blue notebooks.
Tags: math
Correct Solution:
```
n,k = map(int, input().split())
k1 = k-1
print((8*n+k1)//k + (5*n+k1)//k + (2*n+k1)//k)
```
| 101,216 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya is having a party soon, and he has decided to invite his n friends.
He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one color with k sheets. That is, each notebook contains k sheets of either red, green, or blue.
Find the minimum number of notebooks that Petya needs to buy to invite all n of his friends.
Input
The first line contains two integers n and k (1≤ n, k≤ 10^8) — the number of Petya's friends and the number of sheets in each notebook respectively.
Output
Print one number — the minimum number of notebooks that Petya needs to buy.
Examples
Input
3 5
Output
10
Input
15 6
Output
38
Note
In the first example, we need 2 red notebooks, 3 green notebooks, and 5 blue notebooks.
In the second example, we need 5 red notebooks, 13 green notebooks, and 20 blue notebooks.
Tags: math
Correct Solution:
```
n, k = map(int, input().split())
m = (2 * n + k - 1) // k + (5 * n + k - 1) // k + (8 * n + k - 1) // k
print(m)
```
| 101,217 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya is having a party soon, and he has decided to invite his n friends.
He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one color with k sheets. That is, each notebook contains k sheets of either red, green, or blue.
Find the minimum number of notebooks that Petya needs to buy to invite all n of his friends.
Input
The first line contains two integers n and k (1≤ n, k≤ 10^8) — the number of Petya's friends and the number of sheets in each notebook respectively.
Output
Print one number — the minimum number of notebooks that Petya needs to buy.
Examples
Input
3 5
Output
10
Input
15 6
Output
38
Note
In the first example, we need 2 red notebooks, 3 green notebooks, and 5 blue notebooks.
In the second example, we need 5 red notebooks, 13 green notebooks, and 20 blue notebooks.
Tags: math
Correct Solution:
```
# -*- coding: utf-8 -*-
import math
import collections
import bisect
import heapq
import time
import itertools
import sys
"""
created by shhuan at 2018/11/24 15:28
"""
N, K = map(int, input().split())
r = 2 * N // K
g = 5 * N // K
b = 8 * N // K
if r * K < 2*N:
r += 1
if g * K < 5*N:
g += 1
if b * K < 8 * N:
b += 1
print(r+g+b)
```
| 101,218 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya is having a party soon, and he has decided to invite his n friends.
He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one color with k sheets. That is, each notebook contains k sheets of either red, green, or blue.
Find the minimum number of notebooks that Petya needs to buy to invite all n of his friends.
Input
The first line contains two integers n and k (1≤ n, k≤ 10^8) — the number of Petya's friends and the number of sheets in each notebook respectively.
Output
Print one number — the minimum number of notebooks that Petya needs to buy.
Examples
Input
3 5
Output
10
Input
15 6
Output
38
Note
In the first example, we need 2 red notebooks, 3 green notebooks, and 5 blue notebooks.
In the second example, we need 5 red notebooks, 13 green notebooks, and 20 blue notebooks.
Tags: math
Correct Solution:
```
def one(t,n,k):
if t*n/k>t*n//k:
l=t*n//k+1
else:
l=t*n//k
return l
s=input().split()
n=int(s[0])#���-�� ������
k=int(s[1])#���-�� ������ � ����� ��������
print(int(one(2,n,k)+one(5,n,k)+one(8,n,k)))
```
| 101,219 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya is having a party soon, and he has decided to invite his n friends.
He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one color with k sheets. That is, each notebook contains k sheets of either red, green, or blue.
Find the minimum number of notebooks that Petya needs to buy to invite all n of his friends.
Input
The first line contains two integers n and k (1≤ n, k≤ 10^8) — the number of Petya's friends and the number of sheets in each notebook respectively.
Output
Print one number — the minimum number of notebooks that Petya needs to buy.
Examples
Input
3 5
Output
10
Input
15 6
Output
38
Note
In the first example, we need 2 red notebooks, 3 green notebooks, and 5 blue notebooks.
In the second example, we need 5 red notebooks, 13 green notebooks, and 20 blue notebooks.
Tags: math
Correct Solution:
```
import math
n,k=list(map(int,input().split()))
print(math.ceil((n*2)/k) + math.ceil((n*5)/k) + math.ceil((n*8)/k))
```
| 101,220 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya is having a party soon, and he has decided to invite his n friends.
He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one color with k sheets. That is, each notebook contains k sheets of either red, green, or blue.
Find the minimum number of notebooks that Petya needs to buy to invite all n of his friends.
Input
The first line contains two integers n and k (1≤ n, k≤ 10^8) — the number of Petya's friends and the number of sheets in each notebook respectively.
Output
Print one number — the minimum number of notebooks that Petya needs to buy.
Examples
Input
3 5
Output
10
Input
15 6
Output
38
Note
In the first example, we need 2 red notebooks, 3 green notebooks, and 5 blue notebooks.
In the second example, we need 5 red notebooks, 13 green notebooks, and 20 blue notebooks.
Submitted Solution:
```
n, k = map(int, input().split())
res = 2 * n // k
if (2 * n) % k:
res += 1
res += 5 * n // k
if (5 * n) % k:
res += 1
res += 8 * n // k
if (8 * n) % k:
res += 1
print(res)
```
Yes
| 101,221 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya is having a party soon, and he has decided to invite his n friends.
He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one color with k sheets. That is, each notebook contains k sheets of either red, green, or blue.
Find the minimum number of notebooks that Petya needs to buy to invite all n of his friends.
Input
The first line contains two integers n and k (1≤ n, k≤ 10^8) — the number of Petya's friends and the number of sheets in each notebook respectively.
Output
Print one number — the minimum number of notebooks that Petya needs to buy.
Examples
Input
3 5
Output
10
Input
15 6
Output
38
Note
In the first example, we need 2 red notebooks, 3 green notebooks, and 5 blue notebooks.
In the second example, we need 5 red notebooks, 13 green notebooks, and 20 blue notebooks.
Submitted Solution:
```
import math
def solve(n, k):
return math.ceil(n*2/k) + math.ceil(n*5/k) + math.ceil(n*8/k)
def main():
n, k=list(map(int, input().split()))
print(solve(n,k))
if __name__ == '__main__':
main()
```
Yes
| 101,222 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya is having a party soon, and he has decided to invite his n friends.
He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one color with k sheets. That is, each notebook contains k sheets of either red, green, or blue.
Find the minimum number of notebooks that Petya needs to buy to invite all n of his friends.
Input
The first line contains two integers n and k (1≤ n, k≤ 10^8) — the number of Petya's friends and the number of sheets in each notebook respectively.
Output
Print one number — the minimum number of notebooks that Petya needs to buy.
Examples
Input
3 5
Output
10
Input
15 6
Output
38
Note
In the first example, we need 2 red notebooks, 3 green notebooks, and 5 blue notebooks.
In the second example, we need 5 red notebooks, 13 green notebooks, and 20 blue notebooks.
Submitted Solution:
```
a=list(map(int,input().split()))
b=a[0]
c=a[1]
d=(2*b)//c
if 2*b%c>0:
d+=1
e=(5*b)//c
if 5*b%c>0:
e+=1
f=(8*b)//c
if 8*b%c>0:
f+=1
z=d+e+f
print(z)
```
Yes
| 101,223 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya is having a party soon, and he has decided to invite his n friends.
He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one color with k sheets. That is, each notebook contains k sheets of either red, green, or blue.
Find the minimum number of notebooks that Petya needs to buy to invite all n of his friends.
Input
The first line contains two integers n and k (1≤ n, k≤ 10^8) — the number of Petya's friends and the number of sheets in each notebook respectively.
Output
Print one number — the minimum number of notebooks that Petya needs to buy.
Examples
Input
3 5
Output
10
Input
15 6
Output
38
Note
In the first example, we need 2 red notebooks, 3 green notebooks, and 5 blue notebooks.
In the second example, we need 5 red notebooks, 13 green notebooks, and 20 blue notebooks.
Submitted Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Petya and Origami.py
#
# Copyright 2020 Rahul <Rahul@DESKTOP-02JFRKS>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
from math import ceil as m
friend, page = map(int, input().split())
rd_pg = friend*2
gr_pg = friend*5
bl_pg = friend*8
no_of_book = m(rd_pg/page) + m(bl_pg/page) +m(gr_pg/page)
print(no_of_book)
```
Yes
| 101,224 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya is having a party soon, and he has decided to invite his n friends.
He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one color with k sheets. That is, each notebook contains k sheets of either red, green, or blue.
Find the minimum number of notebooks that Petya needs to buy to invite all n of his friends.
Input
The first line contains two integers n and k (1≤ n, k≤ 10^8) — the number of Petya's friends and the number of sheets in each notebook respectively.
Output
Print one number — the minimum number of notebooks that Petya needs to buy.
Examples
Input
3 5
Output
10
Input
15 6
Output
38
Note
In the first example, we need 2 red notebooks, 3 green notebooks, and 5 blue notebooks.
In the second example, we need 5 red notebooks, 13 green notebooks, and 20 blue notebooks.
Submitted Solution:
```
n,k=input().split()
n,k=int(n),int(k)
r=0
g=0
b=0
for i in range(1,n+1):
r=r+2
g=g+5
b=b+8
s=r+g+b
if s%k==0:
nb=(s//k)
else:
nb=(s//k)+1
print(nb)
```
No
| 101,225 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya is having a party soon, and he has decided to invite his n friends.
He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one color with k sheets. That is, each notebook contains k sheets of either red, green, or blue.
Find the minimum number of notebooks that Petya needs to buy to invite all n of his friends.
Input
The first line contains two integers n and k (1≤ n, k≤ 10^8) — the number of Petya's friends and the number of sheets in each notebook respectively.
Output
Print one number — the minimum number of notebooks that Petya needs to buy.
Examples
Input
3 5
Output
10
Input
15 6
Output
38
Note
In the first example, we need 2 red notebooks, 3 green notebooks, and 5 blue notebooks.
In the second example, we need 5 red notebooks, 13 green notebooks, and 20 blue notebooks.
Submitted Solution:
```
a,b=map(int,input().split())
c=(a*2)//5
d=a
e=(a*8)//5
if a*2!=c*5:
c+=1
if a*8!=e*5:
e+=1
print(c+d+e)
```
No
| 101,226 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya is having a party soon, and he has decided to invite his n friends.
He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one color with k sheets. That is, each notebook contains k sheets of either red, green, or blue.
Find the minimum number of notebooks that Petya needs to buy to invite all n of his friends.
Input
The first line contains two integers n and k (1≤ n, k≤ 10^8) — the number of Petya's friends and the number of sheets in each notebook respectively.
Output
Print one number — the minimum number of notebooks that Petya needs to buy.
Examples
Input
3 5
Output
10
Input
15 6
Output
38
Note
In the first example, we need 2 red notebooks, 3 green notebooks, and 5 blue notebooks.
In the second example, we need 5 red notebooks, 13 green notebooks, and 20 blue notebooks.
Submitted Solution:
```
n,k=map(int, input().split())
r=g=b=0
r=(2*n)
g=(5*n)
b=(8*n)
c=r+g+b
if k==1:
print(c)
exit()
if c/k==0:
print(c/k)
else:
print(round((c/k)+1))
```
No
| 101,227 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya is having a party soon, and he has decided to invite his n friends.
He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one color with k sheets. That is, each notebook contains k sheets of either red, green, or blue.
Find the minimum number of notebooks that Petya needs to buy to invite all n of his friends.
Input
The first line contains two integers n and k (1≤ n, k≤ 10^8) — the number of Petya's friends and the number of sheets in each notebook respectively.
Output
Print one number — the minimum number of notebooks that Petya needs to buy.
Examples
Input
3 5
Output
10
Input
15 6
Output
38
Note
In the first example, we need 2 red notebooks, 3 green notebooks, and 5 blue notebooks.
In the second example, we need 5 red notebooks, 13 green notebooks, and 20 blue notebooks.
Submitted Solution:
```
n, k = [int(x) for x in input().split()]
red_ = 0
green_ = 0
blue_ = 0
red = n * 2
green = n * 5
blue = n * 8
if red % k != 0:
while red % k != 0:
red += 1
red_ = red / k
else:
red_ = red / k
if green % k != 0:
while green % k != 0:
green += 1
green_ = green / k
else:
green_ = green / k
if blue % k != 0:
while blue % k != 0:
blue += 1
blue_ = blue / k
else:
blue_ = blue / k
print(red_ + green_ + blue_)
```
No
| 101,228 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
One day Petya came across an interval of numbers [a, a + l - 1]. Let F(x) be the number of lucky digits of number x. Find the minimum b (a < b) such, that F(a) = F(b), F(a + 1) = F(b + 1), ..., F(a + l - 1) = F(b + l - 1).
Input
The single line contains two integers a and l (1 ≤ a, l ≤ 109) — the interval's first number and the interval's length correspondingly.
Output
On the single line print number b — the answer to the problem.
Examples
Input
7 4
Output
17
Input
4 7
Output
14
Note
Consider that [a, b] denotes an interval of integers; this interval includes the boundaries. That is, <image>
Submitted Solution:
```
def F(x):
q = 0
for i in str(x):
if i == '4' or i == '7':
q += 1
return q
a, l = map(lambda x: int(x), input().split())
if l > a:
print(10**len(str(l)) + a)
else:
L = l
Fa = [F(i) for i in range(a, a+l)]
b = a + 1
while True:
for i in range(l):
if b + i >= a + L:
Fa.append(F(b + i))
L += 1
if Fa[i] != Fa[b + i - a]:
break
else:
print(b)
break
b += 1
```
No
| 101,229 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
One day Petya came across an interval of numbers [a, a + l - 1]. Let F(x) be the number of lucky digits of number x. Find the minimum b (a < b) such, that F(a) = F(b), F(a + 1) = F(b + 1), ..., F(a + l - 1) = F(b + l - 1).
Input
The single line contains two integers a and l (1 ≤ a, l ≤ 109) — the interval's first number and the interval's length correspondingly.
Output
On the single line print number b — the answer to the problem.
Examples
Input
7 4
Output
17
Input
4 7
Output
14
Note
Consider that [a, b] denotes an interval of integers; this interval includes the boundaries. That is, <image>
Submitted Solution:
```
a, l = list(map(int, (input().split())))
def f(a):
counter = 0
while a > 0:
digit = a % 10
a /= 10
if digit == 7 or digit == 4:
counter += 1
return counter
b = a + 1
wrong = False
while True:
for i in range(l):
if f(b + i) != f(a + i):
wrong = True
break
if wrong:
b += 1
wrong = False
else:
print(b)
exit()
```
No
| 101,230 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
One day Petya came across an interval of numbers [a, a + l - 1]. Let F(x) be the number of lucky digits of number x. Find the minimum b (a < b) such, that F(a) = F(b), F(a + 1) = F(b + 1), ..., F(a + l - 1) = F(b + l - 1).
Input
The single line contains two integers a and l (1 ≤ a, l ≤ 109) — the interval's first number and the interval's length correspondingly.
Output
On the single line print number b — the answer to the problem.
Examples
Input
7 4
Output
17
Input
4 7
Output
14
Note
Consider that [a, b] denotes an interval of integers; this interval includes the boundaries. That is, <image>
Submitted Solution:
```
def F(x):
q = 0
for i in str(x):
if i == '4' or i == '7':
q += 1
return q
a, l = map(lambda x: int(x), input().split())
if l >= a:
if 1000000000 % l != 0:
print(10**len(str(l)) + a)
else:
print(l + a)
else:
L = l
Fa = [F(i) for i in range(a, a+l)]
b = a + 1
while True:
for i in range(l):
if b + i >= a + L:
Fa.append(F(b + i))
L += 1
if Fa[i] != Fa[b + i - a]:
break
else:
print(b)
break
b += 1
```
No
| 101,231 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A positive integer a is given. Baron Munchausen claims that he knows such a positive integer n that if one multiplies n by a, the sum of its digits decreases a times. In other words, S(an) = S(n)/a, where S(x) denotes the sum of digits of the number x.
Find out if what Baron told can be true.
Input
The only line contains a single integer a (2 ≤ a ≤ 10^3).
Output
If there is no such number n, print -1.
Otherwise print any appropriate positive integer n. Your number must not consist of more than 5â‹…10^5 digits. We can show that under given constraints either there is no answer, or there is an answer no longer than 5â‹…10^5 digits.
Examples
Input
2
Output
6
Input
3
Output
6669
Input
10
Output
-1
Tags: brute force
Correct Solution:
```
#!/bin/pypy3
from itertools import*
from timeit import*
from typing import Optional
S=lambda x:sum(map(int,str(x)))
def ceil_s_divisible_a(x:int,a:int) -> Optional[int]:
z=S(x)%a
if z:
z=a-z
tail=[]
x=list(str(x))
while x:
digit=x.pop()
diff=min(z,9-int(digit))
z-=diff
tail.append(str(int(digit)+diff))
if z==0:break
else:
return ceil_s_divisible_a(10**len(tail),a)
x=''.join(x) + ''.join(reversed(tail))
assert S(x)%a==0
x=int(x)
return x
def smooth25(a):
a=int(bin(a).rstrip('0'),2)
while a%5==0: a//=5
return a==1
def solve(a):
for first in range(1,60): # 120
q=str((first*10**3000+a-1) // a) # 5000
for s1 in range(1,200):
i=1
s2=int(q[0])
while i<len(q) and s2<s1*a-10: s2+=int(q[i]); i+=1
for len1 in range(i,min(i+10,len(q))):
small=int(q[:len1])
for z in range(4): # 10
small=ceil_s_divisible_a(small,a)
if S(small*a)*a==S(small):
return small
small+=1
return None
def powform(x:int)->str:
s=str(x)
try:
i=s.find('00000')
return f'{s[:i]} * 10 ** {len(s)-i} + {int(s[i:])}'
except IndexError:
return str(x)
if 0:
#for a in (a for a in range(2,1000)):
for a in [999,909,813,777,957,921,855,933,831,942,891,846,807,783,888][1::3]:
#for a in [32]:
def work():
global x
x=solve(a)
t=timeit(work,number=1)
if t>0.5 or x==None:
if x!=None:
print(a,t,'>>',powform(a*x))
else:
print(a,t,'>> ?????')
#print(solve(int(input())))
special='''
660 0.5026652759997887 >> 3 * 10 ** 2640 + 35340
803 0.5102322779994211 >> 3 * 10 ** 2678 + 1614
912 0.5136937369998122 >> 3 * 10 ** 1825 + 240
918 0.5238579140004731 >> 3 * 10 ** 1813 + 1104
582 0.5302371079997101 >> 2 * 10 ** 2328 + 17116
612 0.5363936909998301 >> 2 * 10 ** 2413 + 10348
495 0.5372351949999938 >> 3 * 10 ** 2969 + 16305
927 0.5433051690006323 >> 3 * 10 ** 2195 + 21003
636 0.5471086210000067 >> 3 * 10 ** 1379 + 20004
531 0.5475810970001476 >> 2 * 10 ** 2140 + 439
64 0.5633312410000144 >> ?????
200 0.5639609099998779 >> ?????
100 0.565854023000611 >> ?????
125 0.5663040710005589 >> ?????
160 0.5668467480008985 >> ?????
800 0.5676178080002501 >> ?????
128 0.5676772269998764 >> ?????
80 0.5682811480000964 >> ?????
256 0.5685735130000467 >> ?????
250 0.5691464900000938 >> ?????
512 0.569266141999833 >> ?????
32 0.5692826909998985 >> ?????
50 0.5692834940000466 >> ?????
25 0.5696684799995637 >> ?????
400 0.5703751219998594 >> ?????
20 0.5706145570002263 >> ?????
500 0.5742691679997733 >> ?????
640 0.5749700739997934 >> ?????
40 0.5768258159996549 >> ?????
625 0.5775357299999087 >> ?????
16 0.5789494729997386 >> ?????
833 0.5855263899993588 >> 3 * 10 ** 2286 + 1404
792 0.5996652009998797 >> 3 * 10 ** 1903 + 16008
320 0.6031684260005932 >> ?????
10 0.6464516910000384 >> ?????
546 0.6579458010000963 >> 3 * 10 ** 2184 + 2454
5 0.6617960960002165 >> ?????
907 0.664109037000344 >> 3 * 10 ** 2538 + 2223
923 0.6807242180002504 >> 2 * 10 ** 2476 + 4141
723 0.6976773409996895 >> 3 * 10 ** 2892 + 1185
825 0.701172955000402 >> 4 * 10 ** 2476 + 123350
906 0.7062042559991824 >> 4 * 10 ** 1998 + 104
905 0.7086789289996887 >> 2 * 10 ** 2412 + 1540
911 0.711649564000254 >> 2 * 10 ** 2612 + 2044
934 0.7246100349993867 >> 2 * 10 ** 2570 + 51112
765 0.7552886830007992 >> 3 * 10 ** 2939 + 1725
981 0.7653923980005857 >> 4 * 10 ** 1965 + 1022
333 0.7884190810000291 >> 3 * 10 ** 2994 + 62934
663 0.8130600629992841 >> 3 * 10 ** 2546 + 11634
444 0.8443964660000347 >> 3 * 10 ** 1999 + 13956
720 0.8445076829993923 >> 2 * 10 ** 2779 + 159280
867 0.9858260920000248 >> 5 * 10 ** 1739 + 121
914 1.0558696210000562 >> 3 * 10 ** 1831 + 222
606 1.1190159360003236 >> 5 * 10 ** 2910 + 1318
948 1.1529914639995695 >> 6 * 10 ** 2466 + 1020
1000 1.2245053040005587 >> ?????
741 1.2366985769995154 >> 5 * 10 ** 2669 + 175
819 1.292531102999419 >> 8 * 10 ** 2949 + 31312
867 1.293641017000482 >> 5 * 10 ** 1739 + 121
961 1.431375496000328 >> 4 * 10 ** 1935 + 1112
913 2.0632996949998414 >> 5 * 10 ** 2323 + 16
861 2.1641551399998207 >> 11 * 10 ** 1847 + 1114
992 2.2718322470000203 >> 11 * 10 ** 2207 + 1504
936 2.3109037909998733 >> 11 * 10 ** 2108 + 3112
996 2.3603119750005135 >> 11 * 10 ** 1979 + 4300
951 2.380345242999283 >> 11 * 10 ** 1820 + 412
969 2.471255187000679 >> 11 * 10 ** 1942 + 241
828 2.504634874999283 >> 11 * 10 ** 1595 + 11212
693 2.5246166990000347 >> 13 * 10 ** 2494 + 423014
840 2.5490226490001078 >> 11 * 10 ** 1681 + 13120
983 2.618962229999852 >> 11 * 10 ** 1968 + 5011
963 2.641272683999887 >> 11 * 10 ** 2026 + 133
972 2.741184581000198 >> 12 * 10 ** 2130 + 312
555 2.787974407000547 >> 11 * 10 ** 2497 + 444445
873 2.8377116049996403 >> 11 * 10 ** 1774 + 133
903 2.898315477000324 >> 13 * 10 ** 1726 + 32
804 2.9635119349995875 >> 12 * 10 ** 1659 + 1500
864 3.032601443999738 >> 13 * 10 ** 2747 + 34016
759 3.0681308859993806 >> 13 * 10 ** 2504 + 311441
871 3.4960390779997397 >> 13 * 10 ** 2995 + 2405
902 4.413119433999782 >> 12 * 10 ** 1506 + 1110
997 4.446912733999852 >> 11 * 10 ** 1999 + 7
993 5.025415283999791 >> 23 * 10 ** 2130 + 31
837 5.286188959000356 >> 25 * 10 ** 2722 + 11063
786 5.390603378999913 >> 21 * 10 ** 1572 + 4002
801 5.4837765329994 >> 22 * 10 ** 1645 + 212
882 6.045185064999714 >> 22 * 10 ** 1822 + 1130
990 6.413724044000446 >> 39 * 10 ** 2970 + 302010
666 6.967028857000514 >> 33 * 10 ** 2997 + 32934
941 6.982767053000316 >> 21 * 10 ** 1885 + 312
924 7.134165846000542 >> 34 * 10 ** 2772 + 1110152
858 8.089877333000004 >> 41 * 10 ** 2573 + 12201142
939 8.241953895999359 >> 33 * 10 ** 1879 + 20001
813 3.1825667919993066 >> 3 * 10 ** 4065 + 7314
921 1.9310127280004963 >> 1 * 10 ** 3762 + 18008
831 1.683305384999585 >> 1 * 10 ** 3702 + 1646
846 1.4100486610004737 >> 1 * 10 ** 3419 + 44234
888 6.891388972000641 >> 3 * 10 ** 3998 + 27672
909 11.340291348999926 >> 7 * 10 ** 4673 + 17201
957 1.3982879649993265 >> 1 * 10 ** 4347 + 28403
933 0.9980270719997861 >> 1 * 10 ** 3746 + 233234
891 0.8806926099996417 >> 1 * 10 ** 3957 + 1079
783 0.6478317080000124 >> 1 * 10 ** 3162 + 22814
999 102.2252583720001 >> 89 * 10 ** 4760 + 20071
777 37.847382832999756 >> 24 * 10 ** 4661 + 474123
855 0.934857464999368 >> 1 * 10 ** 3420 + 21545
942 1.0410122209996189 >> 1 * 10 ** 4198 + 310058
807 0.7532789589995446 >> 1 * 10 ** 3234 + 1307123
'''
a=int(input())
for line in special.splitlines():
if line:
expr,out=line.split('>>')
expr=expr.split()[0]
if int(expr)==a:
print(-1 if out.strip()=='?????' else eval(out)//a)
break
else:
print(solve(a))
```
| 101,232 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A positive integer a is given. Baron Munchausen claims that he knows such a positive integer n that if one multiplies n by a, the sum of its digits decreases a times. In other words, S(an) = S(n)/a, where S(x) denotes the sum of digits of the number x.
Find out if what Baron told can be true.
Input
The only line contains a single integer a (2 ≤ a ≤ 10^3).
Output
If there is no such number n, print -1.
Otherwise print any appropriate positive integer n. Your number must not consist of more than 5â‹…10^5 digits. We can show that under given constraints either there is no answer, or there is an answer no longer than 5â‹…10^5 digits.
Examples
Input
2
Output
6
Input
3
Output
6669
Input
10
Output
-1
Tags: brute force
Correct Solution:
```
tabela = """
3 11 1 1 2 1 2
6 1 4 2 11 3 20
7 2 7 9 1 7 6
9 11 40 1 2 40 0
11 1 7 6 1 6 3
12 2 13 2 11 12 1
13 1 9 15 1 8 30
14 1 10 12 11 9 36
15 11 14 2 2 14 4
17 2 14 9 2 13 27
18 1 34 4 1 33 1
19 1 15 18 1 14 9
21 1 17 10 2 14 8
22 1 12 6 1 10 3
23 1 11 3 11 9 27
24 1 39 6 1 38 0
26 1 16 18 2 15 36
27 11 67 4 2 67 0
28 1 24 18 11 22 36
29 1 15 6 11 19 0
30 2 16 1 11 15 2
31 11 23 27 1 22 18
33 2 66 1 11 65 2
34 1 25 39 2 24 30
35 1 22 27 2 20 18
36 1 48 1 1 47 6
37 11 22 18 11 20 0
38 2 29 18 2 28 33
39 11 80 11 2 77 1
41 11 39 3 2 36 15
42 11 30 5 1 30 4
43 2 33 18 1 31 9
44 2 42 9 1 41 0
45 11 102 2 2 102 0
46 1 41 36 11 39 18
47 2 40 27 1 41 6
48 11 74 3 2 74 0
49 1 37 18 2 35 33
51 1 37 2 1 35 13
52 11 49 6 1 48 3
53 11 47 36 11 35 18
54 1 106 5 1 105 0
55 1 28 9 1 26 0
56 1 68 24 1 67 36
57 11 39 4 1 33 23
58 11 48 36 2 32 36
59 11 43 9 1 47 30
60 1 32 2 1 31 4
61 11 45 9 2 44 0
62 11 39 18 11 44 18
63 1 143 7 1 142 0
65 1 34 15 1 28 12
66 11 67 2 11 66 4
67 11 52 27 1 47 9
68 1 51 18 11 54 30
69 2 47 8 1 42 31
70 1 34 3 1 28 24
71 11 61 36 11 63 18
72 1 84 5 1 83 3
73 1 36 9 1 29 27
74 11 41 18 11 38 0
75 11 114 3 2 114 0
76 11 75 30 1 66 6
77 1 39 12 1 34 15
78 1 159 4 1 153 14
79 2 101 21 2 89 33
81 11 174 3 2 174 0
82 1 119 9 11 115 0
83 1 64 9 2 86 12
84 1 60 7 1 54 20
85 1 41 6 1 51 36
86 1 79 24 11 70 21
87 2 59 2 1 54 37
88 1 122 9 1 120 0
89 11 64 27 1 59 18
90 2 406 1 11 405 0
91 1 45 9 1 40 18
92 1 91 30 11 83 6
93 11 111 29 2 148 31
94 1 88 12 2 104 3
95 1 46 3 11 58 27
96 1 100 1 1 99 5
97 1 49 30 2 58 27
98 11 91 9 1 66 36
99 2 1782 1 11 1781 0
101 1 50 15 1 48 3
102 11 76 16 1 67 5
103 1 53 33 2 85 33
104 1 117 3 1 111 24
105 1 72 2 2 69 16
106 11 74 36 11 62 27
107 2 92 18 1 75 0
108 1 185 5 1 184 0
109 1 56 27 1 63 27
110 1 52 6 1 51 3
111 11 58 10 11 57 8
112 1 151 9 1 145 18
113 1 58 21 1 71 18
114 11 76 2 1 70 25
115 1 57 21 2 70 36
116 11 77 9 1 44 36
117 1 264 4 1 263 3
118 2 108 9 1 100 18
119 2 134 12 11 126 27
120 2 122 2 11 121 1
121 1 109 3 11 108 6
122 2 146 30 1 108 3
123 11 155 7 11 151 17
124 11 70 9 11 90 12
126 1 228 2 1 227 4
127 1 65 18 11 105 36
129 1 93 13 2 77 32
130 1 64 24 1 59 3
131 1 67 30 2 144 15
132 1 134 1 1 132 11
133 1 65 21 2 117 12
134 1 97 36 11 87 27
135 11 281 3 2 281 4
136 11 155 18 1 153 0
137 1 68 24 1 62 12
138 11 97 4 2 93 20
139 1 71 24 11 115 33
140 1 65 3 1 59 24
141 1 99 5 1 97 7
142 11 133 3 1 110 36
143 1 69 18 1 65 9
144 11 164 1 2 164 3
145 1 72 27 1 94 9
146 1 69 15 1 62 21
147 1 108 31 2 191 28
148 11 150 9 11 147 0
149 2 107 9 1 127 21
150 11 150 2 2 150 4
151 1 117 18 1 146 12
152 1 139 27 1 161 36
153 11 329 4 1 329 37
154 1 76 27 1 71 0
155 11 120 21 11 85 18
156 2 314 2 11 311 4
157 11 180 33 11 172 21
158 1 191 24 1 179 21
159 11 101 23 1 122 1
161 1 181 9 1 108 18
162 1 323 5 1 321 6
163 2 255 18 11 245 27
164 1 159 24 1 155 3
165 11 331 1 11 330 5
166 1 178 15 1 105 9
167 1 157 33 11 180 24
168 11 226 7 1 223 11
169 1 225 9 11 218 36
170 1 118 18 1 115 0
171 1 343 1 11 342 8
172 1 163 9 11 154 27
173 11 166 21 1 171 39
174 1 122 31 2 117 23
175 1 83 15 1 77 12
176 1 238 9 2 237 0
177 1 130 38 2 228 32
178 2 119 9 1 113 9
179 1 91 36 1 116 27
180 1 326 1 1 325 4
181 1 92 9 11 124 9
182 1 88 24 1 83 3
183 1 125 7 2 236 34
184 1 249 9 11 245 0
185 11 95 9 11 93 9
186 1 158 11 11 100 25
187 11 169 6 1 218 27
188 2 133 27 2 162 36
189 1 603 5 1 599 10
190 11 130 18 1 124 9
191 11 305 15 11 300 12
192 11 386 1 2 386 11
193 11 214 15 2 250 36
194 1 221 30 1 252 0
195 1 394 7 1 388 11
196 2 147 36 11 133 0
197 11 220 18 1 214 27
198 11 714 2 11 713 3
199 1 145 9 11 192 36
201 2 134 10 1 134 26
202 1 95 15 1 92 3
203 1 199 24 1 186 21
204 1 147 14 2 128 16
205 1 195 21 11 190 6
206 2 187 27 1 87 27
207 1 421 4 11 420 14
208 11 281 18 2 278 0
209 1 101 33 1 185 6
210 1 144 10 2 141 8
211 11 195 3 2 183 33
212 1 262 21 1 254 15
213 2 284 7 2 283 5
214 1 319 15 11 314 12
215 2 160 27 1 137 18
216 1 346 5 1 345 10
217 2 248 27 1 177 27
218 1 196 30 1 240 12
219 11 754 9 11 750 0
220 1 101 6 1 99 3
221 11 238 12 1 237 6
222 11 113 5 11 111 13
223 2 297 18 1 245 24
224 1 307 27 1 301 0
225 11 255 4 2 255 0
226 1 208 27 11 200 18
227 2 253 33 1 264 21
228 1 153 4 11 149 17
229 2 265 24 1 309 27
230 2 158 18 1 153 9
231 11 311 10 2 308 8
232 2 212 24 1 204 30
233 11 264 9 1 314 0
234 2 528 7 11 527 6
235 1 117 36 2 205 27
236 2 322 36 2 307 36
237 1 387 2 1 383 22
238 11 313 30 1 325 39
239 2 563 18 2 558 0
240 1 364 6 1 363 0
241 2 274 21 1 107 15
242 1 123 36 11 208 36
243 11 496 8 2 496 14
244 11 167 18 2 211 36
245 1 164 9 1 107 30
246 11 355 11 11 352 1
247 1 229 39 11 267 39
248 1 282 15 11 276 9
249 2 337 19 1 326 35
251 1 230 18 2 227 0
252 1 415 5 1 413 5
253 1 123 36 2 219 27
254 2 233 12 2 278 30
255 1 166 1 1 164 11
257 1 288 12 11 287 33
258 2 181 11 1 158 34
259 1 262 9 1 256 9
260 1 119 9 1 113 18
261 11 518 4 2 518 6
262 11 410 9 11 406 9
263 1 242 21 1 285 39
264 1 214 2 1 212 13
265 1 280 24 1 267 39
266 2 245 33 1 295 6
267 1 192 14 2 342 23
268 1 377 27 11 346 27
269 11 484 27 1 484 0
270 2 664 2 11 663 5
271 11 383 18 11 378 0
272 2 367 9 11 364 9
273 1 274 1 1 268 17
274 1 125 6 1 118 30
275 1 125 3 1 123 6
276 1 197 14 11 350 32
277 1 305 21 1 237 21
278 2 255 18 2 309 0
279 11 572 1 11 569 12
280 1 193 18 1 187 9
281 2 443 21 11 437 6
282 1 193 13 1 367 25
283 1 197 27 2 233 33
284 11 274 39 1 395 6
285 1 196 26 2 192 4
286 1 130 3 1 125 24
287 11 324 9 1 320 9
288 11 648 2 2 648 0
289 2 329 36 2 321 0
290 2 200 27 1 195 0
291 1 392 5 1 389 7
292 1 134 6 1 126 30
293 2 270 24 11 252 39
294 1 206 38 11 387 23
295 1 332 21 2 327 15
296 2 546 9 1 544 9
297 2 1605 1 11 1604 2
298 11 198 18 1 193 27
299 2 270 21 11 260 33
300 2 152 1 11 151 2
301 1 375 15 1 370 12
302 2 374 12 2 369 15
303 2 607 1 11 606 2
304 1 341 3 1 400 36
305 11 273 9 2 272 0
306 1 604 4 1 603 2
307 11 356 9 11 353 9
308 1 143 15 1 137 12
309 1 489 2 1 486 22
310 1 263 9 11 226 33
311 11 311 12 11 310 6
312 2 626 1 11 623 2
313 11 284 33 2 405 27
314 11 422 18 11 419 0
315 11 710 1 2 710 2
316 1 309 9 1 381 9
317 1 507 30 2 519 24
318 1 266 19 1 253 29
319 1 372 30 11 417 36
321 11 428 4 2 426 5
322 2 297 15 2 225 0
323 1 377 18 11 415 18
324 1 613 4 1 612 12
325 1 149 9 1 143 18
326 1 502 3 11 513 6
327 1 445 29 2 439 1
328 1 310 15 1 305 12
329 1 302 33 1 348 33
330 2 661 1 11 660 2
331 11 451 27 1 512 21
332 1 481 9 1 480 0
333 11 1499 1 2 1499 2
334 11 380 27 2 370 18
335 2 234 9 1 213 18
336 1 451 8 1 446 19
337 1 294 12 11 301 33
338 1 302 15 11 296 39
339 2 228 11 1 222 37
340 1 154 3 11 221 36
341 2 434 18 1 483 27
342 1 685 1 11 684 13
343 1 149 18 2 372 27
344 1 221 9 1 290 15
345 2 246 34 11 230 38
346 1 402 15 11 404 39
347 11 324 15 11 552 39
348 11 462 19 1 469 29
349 11 398 39 1 313 3
350 1 161 18 1 155 9
351 2 679 6 2 677 11
352 1 474 9 1 473 0
353 11 473 18 2 469 9
354 1 470 5 1 463 19
355 11 272 39 1 394 6
356 11 242 18 1 236 9
357 2 487 34 2 470 29
358 11 242 18 11 313 30
359 11 451 36 1 450 0
360 1 466 4 1 465 3
361 2 262 36 1 173 0
362 11 491 18 1 480 18
363 2 503 11 1 515 10
364 1 167 15 1 161 12
365 1 165 3 1 158 33
366 1 256 35 2 484 26
367 2 497 27 1 493 9
368 1 416 18 1 491 9
369 11 832 2 11 829 1
370 11 188 9 11 186 9
371 1 410 33 11 417 21
372 1 622 8 11 618 24
373 1 665 15 2 582 6
374 1 301 24 1 296 12
375 1 566 6 1 565 0
376 1 591 24 1 496 36
377 1 429 27 11 436 9
378 1 933 11 1 929 1
379 1 587 18 1 584 0
380 1 173 15 2 246 36
381 1 495 35 1 487 4
382 11 530 30 11 522 15
383 2 341 6 1 339 3
384 1 773 2 1 772 4
385 1 178 21 1 173 6
386 1 432 36 1 423 9
387 1 719 1 1 718 7
388 11 256 18 2 252 0
389 1 609 3 11 516 9
390 11 783 11 2 780 1
391 1 575 27 2 746 30
392 1 277 27 11 345 30
393 11 523 4 2 517 23
394 2 444 3 11 435 15
395 1 387 18 1 374 36
396 11 1020 1 11 1019 6
397 11 632 9 1 619 18
398 1 680 21 11 721 36
399 11 601 11 11 895 6
401 2 549 36 2 534 18
402 11 284 26 1 264 4
403 1 637 33 11 712 0
404 1 184 9 1 180 9
405 11 822 5 2 822 0
406 11 573 18 1 518 18
407 11 818 9 11 815 0
408 1 530 23 1 523 16
409 2 460 33 2 451 12
410 2 382 3 11 381 6
411 11 473 13 11 472 5
412 1 189 12 2 358 39
413 1 467 18 1 368 18
414 1 800 4 1 799 1
415 2 308 36 1 428 18
416 2 649 3 11 647 15
417 11 518 8 11 514 25
418 1 191 6 1 369 24
419 1 471 21 2 464 15
420 11 283 5 1 283 4
421 11 656 24 1 564 0
422 1 197 36 2 375 0
423 11 846 4 11 845 2
424 1 444 18 1 437 18
425 2 288 9 11 285 0
426 1 285 4 1 555 34
427 2 478 15 2 474 3
428 11 409 15 2 444 33
429 2 1719 5 2 1715 1
430 2 373 33 1 305 0
431 1 542 36 1 523 36
432 2 689 1 11 688 9
433 2 491 9 1 667 36
434 1 416 3 1 308 27
435 1 290 25 1 279 32
436 2 287 9 1 376 33
437 2 492 12 1 582 9
438 1 1005 10 1 997 11
439 1 536 21 11 627 0
440 2 395 9 1 394 0
441 1 898 2 1 896 4
442 1 526 36 1 614 9
443 2 965 12 1 812 3
444 11 225 7 11 222 11
445 11 409 39 2 296 36
446 11 499 3 1 493 33
447 1 604 10 2 882 36
448 1 608 27 1 602 0
449 1 210 18 2 400 0
450 11 1014 1 2 1014 1
451 1 757 9 1 755 0
452 1 708 3 1 606 9
453 1 667 8 11 660 31
454 2 427 30 1 294 18
455 1 208 12 1 203 15
456 2 612 7 11 605 35
457 11 817 21 1 810 6
458 1 526 9 2 394 36
459 2 938 1 11 937 26
460 1 211 9 1 306 18
461 1 517 15 11 503 30
462 11 623 23 11 618 4
463 11 416 21 2 506 39
464 1 526 21 1 514 24
465 11 265 17 1 383 28
466 1 318 36 1 516 15
467 2 712 18 11 703 18
468 1 1056 1 1 1055 5
469 11 677 36 1 707 27
470 11 319 9 2 317 0
471 11 574 17 1 350 14
472 11 531 15 1 521 30
473 1 702 18 1 697 9
474 1 882 4 1 877 26
475 1 430 24 2 425 12
476 11 621 36 11 443 0
477 11 1021 16 11 1016 0
478 2 1679 18 11 1672 9
479 1 483 21 1 711 18
480 11 723 3 2 723 0
481 1 490 18 1 484 0
482 2 546 30 11 637 36
483 1 669 7 1 668 5
484 1 439 24 2 431 30
485 1 435 18 2 434 36
486 1 971 8 1 970 5
487 1 861 9 11 865 27
488 11 760 3 2 759 6
489 2 329 22 11 318 35
490 1 332 18 11 428 33
491 2 565 30 1 424 39
492 11 620 13 11 615 11
493 11 703 9 1 723 12
494 1 227 9 2 441 0
495 11 4456 1 2 4456 1
496 11 559 27 11 547 36
497 11 426 39 11 313 18
498 2 349 28 1 654 28
499 1 766 3 2 760 24
501 1 340 11 1 337 13
502 1 227 3 2 337 0
503 1 563 27 2 776 0
504 11 828 4 11 827 1
505 1 231 18 1 228 0
506 1 233 33 1 449 6
507 1 705 38 11 695 4
508 2 802 39 1 899 21
509 1 786 24 11 780 12
510 2 336 29 1 355 10
511 1 628 21 1 741 9
513 2 894 1 2 893 6
514 2 461 9 11 572 0
515 2 460 3 1 223 39
516 2 662 20 1 717 34
517 1 470 30 2 688 9
518 2 1042 18 2 1036 0
519 2 1101 6 2 1098 6
520 2 467 15 11 464 3
521 1 236 9 1 342 18
522 1 1063 1 1 1061 4
523 1 718 27 11 836 9
524 1 699 9 2 457 33
525 1 355 13 2 351 5
526 1 940 6 1 937 3
527 2 611 30 11 804 3
528 2 425 1 2 423 14
529 2 943 12 11 1050 36
530 11 387 9 1 540 36
531 1 1069 4 1 1068 1
532 2 478 27 1 227 36
533 2 596 15 1 556 12
534 11 374 25 1 686 22
535 1 568 33 1 669 27
536 11 742 9 1 573 33
537 2 717 7 1 716 20
538 11 727 36 2 838 3
539 2 483 9 1 233 27
540 1 1045 8 1 1044 0
541 11 845 27 1 953 36
542 11 1509 3 11 1505 15
543 1 729 5 1 717 34
544 1 731 9 11 845 24
545 1 378 36 1 365 27
546 2 1096 10 2 1090 8
547 2 969 21 2 961 15
548 1 254 36 1 246 0
549 1 1112 2 2 1111 39
550 1 249 9 1 247 0
551 11 668 18 1 409 18
552 11 765 26 2 760 7
553 1 1017 24 11 1038 12
554 1 815 33 11 822 21
555 11 281 11 11 279 7
556 11 500 6 1 862 21
557 1 758 36 11 624 0
558 11 1093 2 11 1092 5
559 1 523 18 11 470 27
560 1 627 15 1 621 12
561 2 783 8 2 775 34
562 1 880 21 11 491 33
563 1 650 12 1 646 6
564 11 744 4 2 744 5
565 11 505 15 2 505 3
566 11 493 9 1 604 36
567 1 1299 11 1 1295 6
568 11 952 18 1 780 36
569 1 887 21 2 879 24
570 11 382 4 1 376 23
571 1 511 30 1 380 27
572 1 257 3 1 251 24
573 1 391 11 11 757 26
574 1 651 39 11 685 6
575 1 517 9 11 384 9
576 1 5173 1 11 5172 9
577 2 643 9 2 764 27
578 1 772 9 11 656 3
579 11 387 1 1 382 26
580 1 268 24 11 385 18
581 1 1174 27 2 1282 39
582 2 1168 6 1 1167 12
583 1 1126 3 1 843 0
584 2 526 18 2 518 18
585 11 1317 1 2 1317 5
586 1 913 9 2 912 0
587 2 903 30 1 675 3
588 2 399 10 11 385 35
589 11 526 12 11 774 36
590 1 403 36 11 392 18
591 2 889 10 1 889 17
592 1 1090 12 1 1087 6
593 1 663 36 11 527 0
594 11 2293 5 11 2292 0
595 11 1096 9 2 998 9
596 1 661 6 2 520 24
597 11 738 17 1 442 5
598 11 669 24 2 798 9
599 1 737 3 11 725 0
600 1 303 2 1 302 4
601 2 798 27 1 938 3
602 11 945 27 11 936 18
603 1 1360 9 1 1357 7
604 1 892 9 2 1032 18
605 1 277 24 11 532 33
606 11 974 11 11 970 4
607 1 819 36 2 813 0
608 11 952 15 2 942 30
609 2 809 1 1 808 20
610 1 553 33 11 407 18
611 1 549 9 1 1085 9
612 1 1147 7 1 1146 4
613 11 939 9 11 937 0
614 1 1341 12 1 1337 15
615 11 617 2 11 612 28
616 2 551 3 2 545 24
617 11 1107 30 11 1098 15
618 11 769 22 1 893 20
619 1 1114 30 1 1106 15
620 11 465 18 11 340 36
621 1 1248 5 11 1247 20
622 11 620 9 2 785 27
623 11 1153 39 1 976 18
624 11 1253 17 2 1250 4
626 1 432 27 2 686 33
627 2 761 31 2 747 32
628 1 559 6 1 275 6
629 2 880 18 2 870 36
630 1 1420 1 1 1419 4
631 1 1029 27 2 1164 18
632 1 771 33 1 758 21
633 1 744 2 1 1117 6
634 11 932 12 1 1056 30
635 2 569 6 1 706 6
636 11 996 6 2 1033 11
637 11 718 39 2 569 21
638 11 575 18 2 1075 27
639 2 1302 8 2 1301 9
641 2 1004 3 11 851 18
642 2 869 29 2 857 37
643 11 717 33 2 830 36
644 1 299 3 1 438 18
645 11 829 25 1 823 2
646 2 1196 39 1 1117 24
647 2 1030 18 2 886 0
648 1 1198 9 1 1197 8
649 2 1155 9 11 1149 27
650 1 293 6 1 287 21
651 1 873 11 2 928 16
652 2 1013 39 11 1000 24
653 1 881 9 2 873 27
654 1 880 37 1 1303 36
655 1 583 6 2 586 12
656 11 735 27 11 730 0
657 11 1394 5 11 1390 10
658 1 727 9 1 719 36
659 1 734 33 2 726 39
660 11 662 2 11 661 4
661 1 453 36 1 729 39
662 2 739 12 2 737 6
663 1 448 20 11 877 35
664 2 1123 15 11 1237 9
665 1 746 18 2 587 36
666 11 1500 2 11 1499 4
667 1 909 27 2 874 27
668 1 755 24 1 1040 15
669 11 905 35 1 1331 27
670 2 873 27 1 765 21
671 1 1242 30 2 1371 24
672 1 901 13 1 896 14
673 2 904 27 1 890 27
674 2 1055 27 2 1049 0
675 11 1075 4 2 1075 3
676 2 908 36 1 1046 27
677 1 756 24 2 1051 6
678 1 902 5 2 454 14
679 1 1674 18 2 1671 0
680 11 763 30 2 750 33
681 1 918 22 11 902 20
682 1 981 27 2 974 9
683 11 1349 18 11 1339 36
684 2 1371 3 11 1369 4
685 1 309 9 1 302 27
686 1 1077 21 2 1055 6
687 1 924 20 1 917 7
688 1 806 6 2 872 18
689 1 1076 33 1 1218 24
690 11 449 2 2 445 19
691 2 1072 6 11 1229 24
692 2 796 18 11 597 36
693 2 3119 1 11 3118 3
694 1 913 36 2 791 18
695 2 623 21 2 770 21
696 1 917 38 1 910 1
697 2 1069 39 11 776 21
698 2 1095 24 2 1241 15
699 11 1399 21 11 1388 33
700 1 317 12 1 311 15
701 1 620 9 2 938 0
702 11 1187 5 11 1186 1
703 1 607 9 1 1200 27
704 1 945 9 1 943 0
705 1 468 7 1 465 8
706 2 949 36 2 626 24
707 11 815 36 11 803 27
708 1 967 28 2 1395 33
709 11 806 39 2 1090 3
710 1 600 18 11 659 0
711 11 1414 9 11 1411 7
712 2 640 27 11 630 27
713 1 1294 6 1 1127 33
714 1 1433 12 2 1428 12
715 1 322 6 1 317 21
716 1 643 15 2 625 39
717 2 1510 15 2 1508 0
718 2 1257 24 11 1251 3
719 2 1401 18 1 1395 18
720 1 814 5 1 813 3
721 2 1294 36 1 1280 27
722 2 814 6 2 954 36
723 1 1211 20 1 1204 13
724 11 486 18 1 959 27
725 11 648 6 2 481 18
726 1 1004 10 1 1001 2
727 11 811 21 2 802 6
728 2 653 18 2 647 9
729 11 1470 1 2 1470 4
730 1 333 27 1 326 9
731 2 1146 3 11 1289 39
732 1 499 25 2 974 31
733 11 1209 30 1 1240 39
734 1 507 18 1 649 39
735 11 979 7 1 978 29
736 11 1148 6 2 1144 21
737 11 1021 27 1 637 9
738 11 1753 14 11 1749 5
739 1 502 18 1 977 36
740 11 375 18 11 372 0
741 11 1484 3 11 1479 21
742 11 807 15 1 500 27
743 2 988 27 1 1312 6
744 11 832 16 1 1237 23
745 2 667 6 11 495 36
746 1 836 36 2 660 9
747 1 1413 25 1 1406 8
748 2 895 36 11 995 18
749 1 1185 21 1 1009 27
750 2 1128 3 11 1127 0
751 1 1031 18 11 1137 33
752 2 1344 30 1 1340 6
753 2 949 37 2 940 14
754 11 1011 18 11 1007 0
755 11 1122 36 11 918 36
756 2 1858 3 11 1857 0
757 11 1711 18 11 1506 36
758 2 1018 36 11 677 6
759 2 1295 38 11 2083 20
760 1 514 27 11 670 33
761 1 1197 15 1 1365 33
762 1 1607 15 11 1525 0
763 11 1061 36 1 1204 39
764 11 1651 36 11 1644 9
765 2 1552 1 2 1551 2
766 11 684 9 2 842 36
767 11 1197 21 2 1529 27
768 2 1925 2 11 1924 1
769 11 1371 15 2 1371 12
770 1 346 3 1 341 24
771 11 1031 16 1 1029 26
772 2 673 6 2 492 36
773 2 1256 18 2 1251 18
774 1 1398 20 1 1395 5
775 1 871 27 11 862 9
776 1 520 27 2 1031 18
777 1 784 13 1 778 5
778 1 1215 21 1 1208 33
779 2 1699 24 2 1687 21
780 1 1564 4 1 1558 14
781 2 1476 3 11 1299 18
782 2 947 9 2 942 27
783 2 1564 19 11 1562 12
784 1 1408 27 1 1217 36
785 1 353 15 11 874 12
786 2 1060 5 1 1558 30
787 2 1388 33 2 1554 9
788 2 1584 36 1 1402 6
789 11 1055 19 1 1053 20
790 1 764 6 2 947 24
791 1 1952 36 11 1937 9
792 11 1785 5 11 1784 3
793 11 1023 18 1 1415 36
794 1 742 12 1 923 30
795 11 452 1 1 643 17
796 11 648 12 11 1133 15
797 2 1104 9 2 1277 39
798 11 1804 30 11 1795 3
799 11 936 21 1 1486 6
801 11 1521 10 2 1516 19
802 11 1433 9 11 1078 0
803 11 716 3 11 709 33
804 1 560 16 11 516 32
805 1 1084 18 1 1245 24
806 11 1255 6 1 1178 12
807 1 549 26 11 1069 20
808 2 724 15 2 720 3
809 2 1093 36 2 899 18
810 2 1730 7 11 1729 2
811 1 1089 27 2 1086 0
812 2 1046 36 2 865 21
813 2 4065 1 2 4064 5
814 1 1637 18 1 1631 0
815 11 561 36 1 711 30
816 11 1052 22 2 1044 14
817 1 1508 30 1 1492 33
818 1 1278 27 1 1268 36
819 9 3279 2 9 3276 8
820 1 1145 9 11 1141 0
821 11 1647 18 2 1637 27
822 11 1022 38 11 1016 1
823 2 1113 36 1 1263 24
824 11 1659 36 1 1651 9
825 11 3302 2 11 3301 1
826 11 1295 33 2 1290 39
827 2 1269 9 2 1449 36
828 2 1595 6 2 1594 6
829 11 558 18 1 547 36
830 11 807 30 1 598 9
831 11 1854 12 2 1235 7
832 2 1298 3 11 1295 15
833 11 1449 30 2 1525 33
834 2 1728 39 11 1722 3
835 11 748 15 2 748 3
836 2 748 9 1 371 18
837 2 1853 5 2 1852 3
838 2 1683 27 11 1680 0
839 2 1425 3 2 1216 27
840 1 565 7 1 559 20
841 2 1111 18 11 935 39
842 1 1502 3 2 1309 39
843 2 1191 37 2 1768 21
844 2 941 12 11 750 21
845 1 945 9 11 942 0
846 1 1714 5 1 1713 10
847 2 759 9 11 754 9
848 1 879 6 1 873 30
849 1 1161 11 1 1159 4
850 11 573 18 1 564 27
851 1 1959 24 2 1954 12
852 2 1136 37 2 1125 14
853 11 1485 21 11 1474 15
854 11 1286 9 2 1137 9
855 11 1712 2 11 1710 7
856 1 1269 18 11 1442 0
857 1 1151 18 1 1146 0
858 11 3435 4 11 3429 14
859 2 767 12 1 379 39
860 1 557 27 2 602 9
861 2 1236 10 11 1227 29
862 2 1280 18 1 1483 21
863 1 769 27 1 575 36
864 11 1798 4 2 1797 4
865 11 726 9 2 825 27
866 1 1546 6 1 1543 12
867 1 1170 8 1 1163 22
868 1 777 3 2 1030 30
869 1 920 15 11 1673 6
870 1 598 2 2 565 25
871 1 1334 36 11 1273 18
872 1 581 9 11 1163 18
873 1 1759 3 1 1758 4
874 1 1367 27 2 971 18
875 1 1174 18 1 1168 9
876 11 2160 7 11 2152 32
877 11 1566 24 11 1756 0
878 2 1473 15 2 1887 0
879 2 1272 7 11 1887 39
880 1 1179 9 1 1177 0
881 1 986 9 1 978 27
882 1 1742 14 1 1738 2
883 1 1385 9 1 793 9
884 1 1238 18 1 1228 36
885 1 1755 6 1 1749 15
886 11 1820 27 2 1815 18
887 1 1978 6 11 1986 30
888 11 892 7 11 889 11
889 1 401 12 1 780 39
890 1 597 18 11 594 0
891 2 3903 1 11 3902 6
892 1 1206 27 11 1196 9
893 2 1412 21 2 1404 6
894 1 1196 26 2 1194 31
895 2 802 30 11 598 9
896 1 1803 27 1 1797 0
897 2 1325 25 11 1314 11
898 11 1202 9 1 402 15
899 2 1837 18 11 1969 18
900 2 4052 1 11 4051 0
901 11 621 36 2 996 0
902 1 1508 9 1 1505 9
903 2 1341 35 1 1485 22
904 1 1212 9 11 1210 0
905 2 811 33 11 799 21
906 1 1998 9 1 1994 6
907 11 944 3 11 937 33
908 11 1490 36 11 1479 9
909 9 3638 1 9 3636 17
910 1 412 18 1 407 9
911 11 1162 36 11 1147 36
912 2 1224 17 11 1217 22
913 1 1705 6 2 1307 36
914 1 1838 27 11 1422 39
915 1 619 38 2 1216 17
916 11 1230 36 1 1230 27
917 2 824 27 2 1216 36
918 1 1833 12 1 1830 6
919 11 1079 36 1 1485 36
920 2 827 21 1 818 15
921 2 1806 12 11 1876 24
922 1 1030 33 11 1225 0
923 11 1225 27 2 1442 3
924 11 1236 7 11 1230 20
925 11 468 18 11 465 0
926 1 1863 36 1 1855 9
927 1 1810 6 1 1808 5
928 1 1655 9 1 1853 27
929 11 836 39 11 1445 24
930 11 520 4 1 773 14
931 2 1455 21 1 1035 12
932 1 1243 18 2 614 9
933 11 1865 9 2 1855 33
934 1 2427 36 1 2417 18
935 1 840 27 1 829 18
936 1 1691 14 1 1687 5
937 2 1887 36 1 2074 36
938 11 1624 33 1 1777 3
939 11 634 19 1 1869 36
940 1 838 3 2 1038 30
941 2 1489 33 1 839 21
942 11 1719 39 11 1708 6
943 1 1714 21 1 2134 21
944 1 2107 18 2 1678 18
945 1 3197 14 1 3191 2
946 11 1612 27 2 1398 0
947 1 1707 24 1 1702 12
948 1 1553 35 1 1540 13
949 11 1478 3 11 1473 24
950 1 640 9 11 635 0
951 1 2177 21 1 2166 33
952 11 711 33 11 875 24
953 11 1476 18 11 1263 18
954 11 2235 2 2 2234 0
955 2 1485 27 11 562 18
956 11 3229 21 11 3222 6
957 11 1313 17 2 1303 22
958 2 1909 24 2 1900 21
959 1 1402 18 1 1860 6
960 1 965 1 1 964 5
961 2 1083 30 2 1071 24
962 2 1930 9 2 1924 9
963 2 1881 14 2 1869 37
964 1 437 18 2 856 0
965 2 865 39 11 865 6
966 1 637 19 11 1244 37
967 1 1095 24 2 1722 30
968 2 871 24 1 858 30
969 11 651 5 1 646 22
970 1 872 24 11 1078 33
971 1 1093 18 2 1080 9
972 1 1910 9 1 1909 10
973 1 1734 36 11 1730 18
974 1 1303 36 1 1514 15
975 11 2931 12 2 2928 0
976 1 1534 39 1 1086 12
977 1 1528 6 11 1296 18
978 1 1942 36 1 1931 30
979 1 1522 36 11 1300 18
980 1 879 18 1 876 0
981 1 1967 10 2 1966 5
982 1 2186 18 1 2389 36
983 11 1543 21 2 1743 39
984 11 990 17 11 985 13
985 11 1103 33 2 1093 21
986 2 1878 27 1 1815 24
987 2 1286 19 2 639 22
988 11 1325 9 1 877 30
989 2 1314 27 11 1545 9
990 9 3962 1 9 3961 8
991 1 1602 36 2 1595 36
992 11 1840 3 11 1653 18
993 2 2135 21 1 2189 39
994 2 1431 9 1 1659 6
995 1 739 36 2 1219 15
996 1 1347 16 1 1342 11
997 11 2004 36 11 2001 0
998 1 1327 27 11 903 27
999 99 4498 10 99 4497 8
"""
def sd(x):
return sum(map(int, str(x)))
def ans(x):
print(x)
exit(0)
def hardcode_solver(a):
if a == 2:
ans(6)
if a == 4:
ans(75)
if a == 8:
ans(125)
def powers_of_10(x):
if 10**18 % x == 0:
ans(-1)
def single_test(x, drange):
found = False
for d in drange:
t = 10**d // x + 1
ad = sd(t) - sd(t*x)*x
if ad > 0:
print(x, d, ad)
found = True
break
if not found:
print(x, 'Failed')
return
def test1(x):
plus = None
minus = None
ir = [1, 2, 11]
ir = [1, 2, 11, 9, 99, 999]
for d in range(1, 6400, 1):
for i in ir:
t = i*10**d // x + 1
ad = sd(t) - sd(t*x)*x
if ad > 0:
if ad < 40:
plus = (i, d, ad)
else:
if -ad < 40:
minus = (i, d, -ad)
if plus != None and minus != None:
print(x, *plus, *minus)
return True
return False
def test_f(f):
for x in range(990, 1001):
if 10**18 % x == 0:
continue
if not f(x):
print(x, 'Error')
return
def izracunato(x):
a = map(lambda t: list(map(int, t.split(' '))), tabela.strip().split('\n'))
for red in a:
(idx, i1, d1, ad1, i2, d2, ad2) = red
if idx == x:
s1 = str(i1*10**d1 // x + 1)
s2 = str(i2*10**d2 // x + 1)
ans((s1 + '000000') * ad2 + (s2 + '000000') * ad1)
def precompute():
test_f(test1)
def task():
n = int(input())
hardcode_solver(n)
powers_of_10(n)
izracunato(n)
task()
```
| 101,233 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A positive integer a is given. Baron Munchausen claims that he knows such a positive integer n that if one multiplies n by a, the sum of its digits decreases a times. In other words, S(an) = S(n)/a, where S(x) denotes the sum of digits of the number x.
Find out if what Baron told can be true.
Input
The only line contains a single integer a (2 ≤ a ≤ 10^3).
Output
If there is no such number n, print -1.
Otherwise print any appropriate positive integer n. Your number must not consist of more than 5â‹…10^5 digits. We can show that under given constraints either there is no answer, or there is an answer no longer than 5â‹…10^5 digits.
Examples
Input
2
Output
6
Input
3
Output
6669
Input
10
Output
-1
Submitted Solution:
```
#!/bin/pypy3
from itertools import*
from timeit import*
#a={
#2:6
#,3:6669
#,4:75
#,7:14286
#,8:125
#}
#print(a.get(int(input()),-1))
S=lambda x:sum(map(int,str(x)))
def solve(a):
for e,first in product(range(0,100),range(1,600)):
x=first*10**e
z=x%a
if z: x+=a-z
#assert x%a==0
if S(x//a)==S(x)*a: return x//a
x+=a
#assert x%a==0
if S(x//a)==S(x)*a: return x//a
return -1
#for a in range(2,1000):
#print(timeit(lambda: print(a,solve(a)),number=1))
print(solve(int(input())))
```
No
| 101,234 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A positive integer a is given. Baron Munchausen claims that he knows such a positive integer n that if one multiplies n by a, the sum of its digits decreases a times. In other words, S(an) = S(n)/a, where S(x) denotes the sum of digits of the number x.
Find out if what Baron told can be true.
Input
The only line contains a single integer a (2 ≤ a ≤ 10^3).
Output
If there is no such number n, print -1.
Otherwise print any appropriate positive integer n. Your number must not consist of more than 5â‹…10^5 digits. We can show that under given constraints either there is no answer, or there is an answer no longer than 5â‹…10^5 digits.
Examples
Input
2
Output
6
Input
3
Output
6669
Input
10
Output
-1
Submitted Solution:
```
a = int(input())
def SumOfNums(a):
sum = 0
obj = str(a)
for i in range(len(obj)):
sum += int(obj[i])
return sum
sum = SumOfNums(a)
guess = -1
for i in range(1, 50001):
if SumOfNums(i*a) == sum / a:
guess = i
break
print(guess)
```
No
| 101,235 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A positive integer a is given. Baron Munchausen claims that he knows such a positive integer n that if one multiplies n by a, the sum of its digits decreases a times. In other words, S(an) = S(n)/a, where S(x) denotes the sum of digits of the number x.
Find out if what Baron told can be true.
Input
The only line contains a single integer a (2 ≤ a ≤ 10^3).
Output
If there is no such number n, print -1.
Otherwise print any appropriate positive integer n. Your number must not consist of more than 5â‹…10^5 digits. We can show that under given constraints either there is no answer, or there is an answer no longer than 5â‹…10^5 digits.
Examples
Input
2
Output
6
Input
3
Output
6669
Input
10
Output
-1
Submitted Solution:
```
#!/bin/pypy3
from itertools import*
from timeit import*
#a={
#2:6
#,3:6669
#,4:75
#,7:14286
#,8:125
#}
#print(a.get(int(input()),-1))
S=lambda x:sum(map(int,str(x)))
def solve(a):
for e,first in product(range(0,100),range(1,600)):
x=first*10**e
z=x%a
if z: x+=a-z
#assert x%a==0
if S(x//a)==S(x)*a: return x
x+=a
#assert x%a==0
if S(x//a)==S(x)*a: return x
return -1
#for a in range(2,1000):
#print(timeit(lambda: print(a,solve(a)),number=1))
print(solve(int(input())))
```
No
| 101,236 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A positive integer a is given. Baron Munchausen claims that he knows such a positive integer n that if one multiplies n by a, the sum of its digits decreases a times. In other words, S(an) = S(n)/a, where S(x) denotes the sum of digits of the number x.
Find out if what Baron told can be true.
Input
The only line contains a single integer a (2 ≤ a ≤ 10^3).
Output
If there is no such number n, print -1.
Otherwise print any appropriate positive integer n. Your number must not consist of more than 5â‹…10^5 digits. We can show that under given constraints either there is no answer, or there is an answer no longer than 5â‹…10^5 digits.
Examples
Input
2
Output
6
Input
3
Output
6669
Input
10
Output
-1
Submitted Solution:
```
import random
def dsum(a):
return sum(int(digit) for digit in str(a))
def f(v, n):
return dsum(v // n) - n * dsum(v)
def make_number(a, n):
for q in range(5):
for M in range(30, (15 + q) * n + 2000, 47):
v = 10**15 + 10**M
for i in range(a):
v = v + 10 ** random.randint(16, M-1)
if v % n == 0:
if f(v, n) >= 0:
return v
return -1
def solve(n):
v = -1
z = 10
if n % 9 == 0:
z = z * 9
for a in range(3, z):
if n % 9 == 0 and (a+2) % 9 != 0:
continue
b = make_number(a, n)
if b > 0:
v = b
break
if n == 1:
v == 1
if v == -1:
assert False
#print(n, "failfailfailfailfailfailfailfailfailfailfailfailfailfailfailfailfailfailfailf")
return -1
else:
for b in range(1, 200):
if f(b*n, n) >= 0:
continue
if f(v,n) + f(b*n, n) >= 0:
v = int(str(v) + str(b*n))
did = True
if f(v, n) == 0:
return v
diff1 = f(v, n)
q = n
while f(q, n) >= 0:
q = q + n
diff2 = f(q, n)
ans = ""
for x in range(-diff2):
ans += str(v)
for x in range(diff1):
ans += str(q)
v = int(ans)
# print(f(v,n))
return v
def bad(n):
while n % 2 == 0:
n = n // 2
while n % 5 == 0:
n = n // 5
if n == 1:
return True
else:
return False
def real_solve(r):
if r == 1 or r == 2 or r == 4 or r == 8 or not bad(r):
return solve(r)
else:
return -1
def test():
for r in range(1, 1000):
solve(r)
def cf():
a = int(input())
ans = real_solve(a)
print(ans)
random.seed(48)
cf()
```
No
| 101,237 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strings and concatenate them in any arbitrarily order.
What is the length of the longest good string you can obtain this way?
Input
The first line contains three positive integers a, b, c (1 ≤ a, b, c ≤ 10^9) — the number of strings "a", "b" and "ab" respectively.
Output
Print a single number — the maximum possible length of the good string you can obtain.
Examples
Input
1 1 1
Output
4
Input
2 1 2
Output
7
Input
3 5 2
Output
11
Input
2 2 1
Output
6
Input
1000000000 1000000000 1000000000
Output
4000000000
Note
In the first example the optimal string is "baba".
In the second example the optimal string is "abababa".
In the third example the optimal string is "bababababab".
In the fourth example the optimal string is "ababab".
Tags: greedy
Correct Solution:
```
a,b,c = map(int,input().split())
print([2*(min(a,b)+c)+1,2*(min(a,b)+c)][a==b])
```
| 101,238 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strings and concatenate them in any arbitrarily order.
What is the length of the longest good string you can obtain this way?
Input
The first line contains three positive integers a, b, c (1 ≤ a, b, c ≤ 10^9) — the number of strings "a", "b" and "ab" respectively.
Output
Print a single number — the maximum possible length of the good string you can obtain.
Examples
Input
1 1 1
Output
4
Input
2 1 2
Output
7
Input
3 5 2
Output
11
Input
2 2 1
Output
6
Input
1000000000 1000000000 1000000000
Output
4000000000
Note
In the first example the optimal string is "baba".
In the second example the optimal string is "abababa".
In the third example the optimal string is "bababababab".
In the fourth example the optimal string is "ababab".
Tags: greedy
Correct Solution:
```
a,b,c=map(int,input().split())
if a!=b:
print(min(a,b)*2+1+c*2)
else:
print(a+b+c*2)
```
| 101,239 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strings and concatenate them in any arbitrarily order.
What is the length of the longest good string you can obtain this way?
Input
The first line contains three positive integers a, b, c (1 ≤ a, b, c ≤ 10^9) — the number of strings "a", "b" and "ab" respectively.
Output
Print a single number — the maximum possible length of the good string you can obtain.
Examples
Input
1 1 1
Output
4
Input
2 1 2
Output
7
Input
3 5 2
Output
11
Input
2 2 1
Output
6
Input
1000000000 1000000000 1000000000
Output
4000000000
Note
In the first example the optimal string is "baba".
In the second example the optimal string is "abababa".
In the third example the optimal string is "bababababab".
In the fourth example the optimal string is "ababab".
Tags: greedy
Correct Solution:
```
a, b, c=map(int,input().split())
mn = min(a, b)
mx = max(a, b)
if mx > mn + 1:
mx = mn + 1
print(mn + mx + 2*c)
```
| 101,240 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strings and concatenate them in any arbitrarily order.
What is the length of the longest good string you can obtain this way?
Input
The first line contains three positive integers a, b, c (1 ≤ a, b, c ≤ 10^9) — the number of strings "a", "b" and "ab" respectively.
Output
Print a single number — the maximum possible length of the good string you can obtain.
Examples
Input
1 1 1
Output
4
Input
2 1 2
Output
7
Input
3 5 2
Output
11
Input
2 2 1
Output
6
Input
1000000000 1000000000 1000000000
Output
4000000000
Note
In the first example the optimal string is "baba".
In the second example the optimal string is "abababa".
In the third example the optimal string is "bababababab".
In the fourth example the optimal string is "ababab".
Tags: greedy
Correct Solution:
```
a, b, c = map(int, input().split())
result = c*2 + min(a, b)*2 + (1 if a != b else 0)
print(result)
```
| 101,241 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strings and concatenate them in any arbitrarily order.
What is the length of the longest good string you can obtain this way?
Input
The first line contains three positive integers a, b, c (1 ≤ a, b, c ≤ 10^9) — the number of strings "a", "b" and "ab" respectively.
Output
Print a single number — the maximum possible length of the good string you can obtain.
Examples
Input
1 1 1
Output
4
Input
2 1 2
Output
7
Input
3 5 2
Output
11
Input
2 2 1
Output
6
Input
1000000000 1000000000 1000000000
Output
4000000000
Note
In the first example the optimal string is "baba".
In the second example the optimal string is "abababa".
In the third example the optimal string is "bababababab".
In the fourth example the optimal string is "ababab".
Tags: greedy
Correct Solution:
```
from collections import Counter
a, b, c = map(int, input().split())
print((2 * (min(a, b) + c)) + (1 if a>b or b>a else 0))
```
| 101,242 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strings and concatenate them in any arbitrarily order.
What is the length of the longest good string you can obtain this way?
Input
The first line contains three positive integers a, b, c (1 ≤ a, b, c ≤ 10^9) — the number of strings "a", "b" and "ab" respectively.
Output
Print a single number — the maximum possible length of the good string you can obtain.
Examples
Input
1 1 1
Output
4
Input
2 1 2
Output
7
Input
3 5 2
Output
11
Input
2 2 1
Output
6
Input
1000000000 1000000000 1000000000
Output
4000000000
Note
In the first example the optimal string is "baba".
In the second example the optimal string is "abababa".
In the third example the optimal string is "bababababab".
In the fourth example the optimal string is "ababab".
Tags: greedy
Correct Solution:
```
a,b,c=map(int, input().split())
if a==b:
print(a+b+2*c)
elif a<b:
print(2*a+2*c+1)
else:
print(2*b+2*c+1)
```
| 101,243 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strings and concatenate them in any arbitrarily order.
What is the length of the longest good string you can obtain this way?
Input
The first line contains three positive integers a, b, c (1 ≤ a, b, c ≤ 10^9) — the number of strings "a", "b" and "ab" respectively.
Output
Print a single number — the maximum possible length of the good string you can obtain.
Examples
Input
1 1 1
Output
4
Input
2 1 2
Output
7
Input
3 5 2
Output
11
Input
2 2 1
Output
6
Input
1000000000 1000000000 1000000000
Output
4000000000
Note
In the first example the optimal string is "baba".
In the second example the optimal string is "abababa".
In the third example the optimal string is "bababababab".
In the fourth example the optimal string is "ababab".
Tags: greedy
Correct Solution:
```
def main():
a, b, c = map(int, input().split())
ans = 2 * c
ans += 2 * min(a, b)
if a != b:
ans += 1
print(ans)
if __name__ == "__main__":
main()
```
| 101,244 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strings and concatenate them in any arbitrarily order.
What is the length of the longest good string you can obtain this way?
Input
The first line contains three positive integers a, b, c (1 ≤ a, b, c ≤ 10^9) — the number of strings "a", "b" and "ab" respectively.
Output
Print a single number — the maximum possible length of the good string you can obtain.
Examples
Input
1 1 1
Output
4
Input
2 1 2
Output
7
Input
3 5 2
Output
11
Input
2 2 1
Output
6
Input
1000000000 1000000000 1000000000
Output
4000000000
Note
In the first example the optimal string is "baba".
In the second example the optimal string is "abababa".
In the third example the optimal string is "bababababab".
In the fourth example the optimal string is "ababab".
Tags: greedy
Correct Solution:
```
a,b,c=[int(x) for x in input().split()]
if a==b:
print(a+b+2*c)
elif a>b:
print(b*2+2*c+1)
else:
print(a*2+2*c+1)
```
| 101,245 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strings and concatenate them in any arbitrarily order.
What is the length of the longest good string you can obtain this way?
Input
The first line contains three positive integers a, b, c (1 ≤ a, b, c ≤ 10^9) — the number of strings "a", "b" and "ab" respectively.
Output
Print a single number — the maximum possible length of the good string you can obtain.
Examples
Input
1 1 1
Output
4
Input
2 1 2
Output
7
Input
3 5 2
Output
11
Input
2 2 1
Output
6
Input
1000000000 1000000000 1000000000
Output
4000000000
Note
In the first example the optimal string is "baba".
In the second example the optimal string is "abababa".
In the third example the optimal string is "bababababab".
In the fourth example the optimal string is "ababab".
Submitted Solution:
```
a,b,c = map(int,input().split())
m = 2*c
if a>b:
m+=2*b + 1
elif a==b:
m+=2*a
else:
m+=2*a+1
print(m)
```
Yes
| 101,246 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strings and concatenate them in any arbitrarily order.
What is the length of the longest good string you can obtain this way?
Input
The first line contains three positive integers a, b, c (1 ≤ a, b, c ≤ 10^9) — the number of strings "a", "b" and "ab" respectively.
Output
Print a single number — the maximum possible length of the good string you can obtain.
Examples
Input
1 1 1
Output
4
Input
2 1 2
Output
7
Input
3 5 2
Output
11
Input
2 2 1
Output
6
Input
1000000000 1000000000 1000000000
Output
4000000000
Note
In the first example the optimal string is "baba".
In the second example the optimal string is "abababa".
In the third example the optimal string is "bababababab".
In the fourth example the optimal string is "ababab".
Submitted Solution:
```
a,b,c=input().split()
a,b,c=eval(a),eval(b),eval(c)
if a-b>1:
a=2*b+2*c+1
elif b-a>1:
a=2*a+2*c+1
else:
a=a+b+2*c
print(a)
```
Yes
| 101,247 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strings and concatenate them in any arbitrarily order.
What is the length of the longest good string you can obtain this way?
Input
The first line contains three positive integers a, b, c (1 ≤ a, b, c ≤ 10^9) — the number of strings "a", "b" and "ab" respectively.
Output
Print a single number — the maximum possible length of the good string you can obtain.
Examples
Input
1 1 1
Output
4
Input
2 1 2
Output
7
Input
3 5 2
Output
11
Input
2 2 1
Output
6
Input
1000000000 1000000000 1000000000
Output
4000000000
Note
In the first example the optimal string is "baba".
In the second example the optimal string is "abababa".
In the third example the optimal string is "bababababab".
In the fourth example the optimal string is "ababab".
Submitted Solution:
```
a,b,c = [int(x) for x in input().split(" ")]
if a==b: print(a+b+2*c)
else:
a,b = [a,b] if a<b else [b,a]
print(a*2+1+2*c)
```
Yes
| 101,248 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strings and concatenate them in any arbitrarily order.
What is the length of the longest good string you can obtain this way?
Input
The first line contains three positive integers a, b, c (1 ≤ a, b, c ≤ 10^9) — the number of strings "a", "b" and "ab" respectively.
Output
Print a single number — the maximum possible length of the good string you can obtain.
Examples
Input
1 1 1
Output
4
Input
2 1 2
Output
7
Input
3 5 2
Output
11
Input
2 2 1
Output
6
Input
1000000000 1000000000 1000000000
Output
4000000000
Note
In the first example the optimal string is "baba".
In the second example the optimal string is "abababa".
In the third example the optimal string is "bababababab".
In the fourth example the optimal string is "ababab".
Submitted Solution:
```
a, b, c = map(int, input().split())
m=min(a,b)
if a!=b:
s=(2*c)+(2*m)+1
else:
s=(2*c)+(2*m)
print(s)
```
Yes
| 101,249 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strings and concatenate them in any arbitrarily order.
What is the length of the longest good string you can obtain this way?
Input
The first line contains three positive integers a, b, c (1 ≤ a, b, c ≤ 10^9) — the number of strings "a", "b" and "ab" respectively.
Output
Print a single number — the maximum possible length of the good string you can obtain.
Examples
Input
1 1 1
Output
4
Input
2 1 2
Output
7
Input
3 5 2
Output
11
Input
2 2 1
Output
6
Input
1000000000 1000000000 1000000000
Output
4000000000
Note
In the first example the optimal string is "baba".
In the second example the optimal string is "abababa".
In the third example the optimal string is "bababababab".
In the fourth example the optimal string is "ababab".
Submitted Solution:
```
a,b,c=(int(i) for i in input().split())
if(b>a):
print((2*a)+1+(2*c))
elif(a<b):
print((2*c)+(2*b)+1)
else:
print(a+b+(2*c))
```
No
| 101,250 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strings and concatenate them in any arbitrarily order.
What is the length of the longest good string you can obtain this way?
Input
The first line contains three positive integers a, b, c (1 ≤ a, b, c ≤ 10^9) — the number of strings "a", "b" and "ab" respectively.
Output
Print a single number — the maximum possible length of the good string you can obtain.
Examples
Input
1 1 1
Output
4
Input
2 1 2
Output
7
Input
3 5 2
Output
11
Input
2 2 1
Output
6
Input
1000000000 1000000000 1000000000
Output
4000000000
Note
In the first example the optimal string is "baba".
In the second example the optimal string is "abababa".
In the third example the optimal string is "bababababab".
In the fourth example the optimal string is "ababab".
Submitted Solution:
```
a,b,c=map(int,input().split())
if abs(a-b)==0:
k=b
else:
k=min(a,b)+1
print((c*2)+k)
```
No
| 101,251 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strings and concatenate them in any arbitrarily order.
What is the length of the longest good string you can obtain this way?
Input
The first line contains three positive integers a, b, c (1 ≤ a, b, c ≤ 10^9) — the number of strings "a", "b" and "ab" respectively.
Output
Print a single number — the maximum possible length of the good string you can obtain.
Examples
Input
1 1 1
Output
4
Input
2 1 2
Output
7
Input
3 5 2
Output
11
Input
2 2 1
Output
6
Input
1000000000 1000000000 1000000000
Output
4000000000
Note
In the first example the optimal string is "baba".
In the second example the optimal string is "abababa".
In the third example the optimal string is "bababababab".
In the fourth example the optimal string is "ababab".
Submitted Solution:
```
#G3_A
import sys
lne = [int(i) for i in sys.stdin.readline().rstrip().split(" ")]
m = min(lne)
num = 4 * m
lne = [i - m for i in lne]
if lne[0] and lne[1]:
m = sorted(lne)[1]
num += 2 * m
if lne[1] != lne[0]:
num += 1
lne = [max(i - m, 0) for i in lne]
elif (lne[1] and lne[2]) or (lne[0] and lne[2]):
num += 2 * lne[2] + 1
elif lne[2]:
num += 2 * lne[2]
print(num)
```
No
| 101,252 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strings and concatenate them in any arbitrarily order.
What is the length of the longest good string you can obtain this way?
Input
The first line contains three positive integers a, b, c (1 ≤ a, b, c ≤ 10^9) — the number of strings "a", "b" and "ab" respectively.
Output
Print a single number — the maximum possible length of the good string you can obtain.
Examples
Input
1 1 1
Output
4
Input
2 1 2
Output
7
Input
3 5 2
Output
11
Input
2 2 1
Output
6
Input
1000000000 1000000000 1000000000
Output
4000000000
Note
In the first example the optimal string is "baba".
In the second example the optimal string is "abababa".
In the third example the optimal string is "bababababab".
In the fourth example the optimal string is "ababab".
Submitted Solution:
```
a,b,c=map(int, input().split())
if a<=b:
print(a+b+2*c)
else:
print(2*a+2*c+1)
```
No
| 101,253 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Toad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, …, a_n.
In one operation Zitz can choose an integer k and k indices i_1, i_2, …, i_k such that 1 ≤ i_1 < i_2 < … < i_k ≤ n. He should then change a_{i_j} to ((a_{i_j}+1) mod m) for each chosen integer i_j. The integer m is fixed for all operations and indices.
Here x mod y denotes the remainder of the division of x by y.
Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) — the number of integers in the array and the parameter m.
The next line contains n space-separated integers a_1, a_2, …, a_n (0 ≤ a_i < m) — the given array.
Output
Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print 0.
It is easy to see that with enough operations Zitz can always make his array non-decreasing.
Examples
Input
5 3
0 0 0 1 2
Output
0
Input
5 7
0 6 1 3 2
Output
1
Note
In the first example, the array is already non-decreasing, so the answer is 0.
In the second example, you can choose k=2, i_1 = 2, i_2 = 5, the array becomes [0,0,1,3,3]. It is non-decreasing, so the answer is 1.
Tags: binary search, greedy
Correct Solution:
```
import sys
import math
from itertools import permutations
input = sys.stdin.readline
n,m=map(int,input().split())
def binarySearch (arr, l, r):
if r >= l:
mid = l + (r - l)//2
#print(mid,check(arr,mid),l,r)
if l==r:
return mid
elif check(arr,mid):
return binarySearch(arr, l, mid)
else:
return binarySearch(arr, mid + 1, r)
else:
return -1
def check(arr, x):
now=arr[0]
for i in range(len(arr)):
if i==0:
if m-arr[i]<=x:
now=0
else:
if arr[i]<now:
if x>=now-arr[i]:
now=now
else:
return False
else:
if x>=(now-arr[i]+m)%m:
now=now
else:
now=arr[i]
return True
l=list(map(int,input().split()))
print(binarySearch(l,0,m))
```
| 101,254 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Toad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, …, a_n.
In one operation Zitz can choose an integer k and k indices i_1, i_2, …, i_k such that 1 ≤ i_1 < i_2 < … < i_k ≤ n. He should then change a_{i_j} to ((a_{i_j}+1) mod m) for each chosen integer i_j. The integer m is fixed for all operations and indices.
Here x mod y denotes the remainder of the division of x by y.
Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) — the number of integers in the array and the parameter m.
The next line contains n space-separated integers a_1, a_2, …, a_n (0 ≤ a_i < m) — the given array.
Output
Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print 0.
It is easy to see that with enough operations Zitz can always make his array non-decreasing.
Examples
Input
5 3
0 0 0 1 2
Output
0
Input
5 7
0 6 1 3 2
Output
1
Note
In the first example, the array is already non-decreasing, so the answer is 0.
In the second example, you can choose k=2, i_1 = 2, i_2 = 5, the array becomes [0,0,1,3,3]. It is non-decreasing, so the answer is 1.
Tags: binary search, greedy
Correct Solution:
```
import sys
import math as mt
input=sys.stdin.buffer.readline
t=1
def check(x1):
prev=0
#print(x1,m)
for i in range(n):
#print(111,prev,i,arr[i],)
if arr[i]>prev:
x=m-(arr[i]-prev)
if x>x1:
prev=arr[i]
if arr[i]<prev:
x=(prev-arr[i])
if x>x1:
return False
return True
#t=int(input())
for _ in range(t):
#n=int((input())
n,m=map(int,input().split())
arr=list(map(int,input().split()))
l,r=0,m
ans=m
while (1<r-l):
mid=(l+r)//2
#print(l,r,mid,check(mid))
if (check(mid)):
ans=min(ans,mid)
r=mid
else:
l=mid
if (check(ans-1)):
ans-=1
print(ans)
```
| 101,255 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Toad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, …, a_n.
In one operation Zitz can choose an integer k and k indices i_1, i_2, …, i_k such that 1 ≤ i_1 < i_2 < … < i_k ≤ n. He should then change a_{i_j} to ((a_{i_j}+1) mod m) for each chosen integer i_j. The integer m is fixed for all operations and indices.
Here x mod y denotes the remainder of the division of x by y.
Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) — the number of integers in the array and the parameter m.
The next line contains n space-separated integers a_1, a_2, …, a_n (0 ≤ a_i < m) — the given array.
Output
Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print 0.
It is easy to see that with enough operations Zitz can always make his array non-decreasing.
Examples
Input
5 3
0 0 0 1 2
Output
0
Input
5 7
0 6 1 3 2
Output
1
Note
In the first example, the array is already non-decreasing, so the answer is 0.
In the second example, you can choose k=2, i_1 = 2, i_2 = 5, the array becomes [0,0,1,3,3]. It is non-decreasing, so the answer is 1.
Tags: binary search, greedy
Correct Solution:
```
import sys
N, M = map(int, input().split(' '))
A = list(map(int, sys.stdin.readline().split(' ')))
def check() :
last = 0
for i in range(N) :
if A[i] < last :
if last - A[i] > m :
break
elif A[i] > last :
if A[i] + m < M or (A[i] + m) % M < last :
last = A[i]
else :
return True
return False
l = -1
r = M-1
while(l + 1 < r) :
m = (l+r) // 2
if check() :
r = m
else :
l = m
print(r)
```
| 101,256 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Toad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, …, a_n.
In one operation Zitz can choose an integer k and k indices i_1, i_2, …, i_k such that 1 ≤ i_1 < i_2 < … < i_k ≤ n. He should then change a_{i_j} to ((a_{i_j}+1) mod m) for each chosen integer i_j. The integer m is fixed for all operations and indices.
Here x mod y denotes the remainder of the division of x by y.
Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) — the number of integers in the array and the parameter m.
The next line contains n space-separated integers a_1, a_2, …, a_n (0 ≤ a_i < m) — the given array.
Output
Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print 0.
It is easy to see that with enough operations Zitz can always make his array non-decreasing.
Examples
Input
5 3
0 0 0 1 2
Output
0
Input
5 7
0 6 1 3 2
Output
1
Note
In the first example, the array is already non-decreasing, so the answer is 0.
In the second example, you can choose k=2, i_1 = 2, i_2 = 5, the array becomes [0,0,1,3,3]. It is non-decreasing, so the answer is 1.
Tags: binary search, greedy
Correct Solution:
```
n,m=map(int,input().split())
a=tuple(map(int,input().split()))
l,r=-1,m-1
while(l+1<r):
M=(l+r)//2
ai1=0
for ai in a:
if (m-ai+ai1)%m>M:
if ai<ai1:
l=M
break
ai1=ai
else:
r=M
print(r)
```
| 101,257 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Toad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, …, a_n.
In one operation Zitz can choose an integer k and k indices i_1, i_2, …, i_k such that 1 ≤ i_1 < i_2 < … < i_k ≤ n. He should then change a_{i_j} to ((a_{i_j}+1) mod m) for each chosen integer i_j. The integer m is fixed for all operations and indices.
Here x mod y denotes the remainder of the division of x by y.
Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) — the number of integers in the array and the parameter m.
The next line contains n space-separated integers a_1, a_2, …, a_n (0 ≤ a_i < m) — the given array.
Output
Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print 0.
It is easy to see that with enough operations Zitz can always make his array non-decreasing.
Examples
Input
5 3
0 0 0 1 2
Output
0
Input
5 7
0 6 1 3 2
Output
1
Note
In the first example, the array is already non-decreasing, so the answer is 0.
In the second example, you can choose k=2, i_1 = 2, i_2 = 5, the array becomes [0,0,1,3,3]. It is non-decreasing, so the answer is 1.
Tags: binary search, greedy
Correct Solution:
```
import sys,math
def read_int():
return int(sys.stdin.readline().strip())
def read_int_list():
return list(map(int,sys.stdin.readline().strip().split()))
def read_string():
return sys.stdin.readline().strip()
def read_string_list(delim=" "):
return sys.stdin.readline().strip().split(delim)
###### Author : Samir Vyas #######
###### Write Code Below #######
n,m = read_int_list()
arr = read_int_list()
def is_ok(maxi):
global arr
prev = 0
for i in range(len(arr)):
if prev <= arr[i] :
k = prev+m-arr[i]
#if no ops is more than maxi then make it prev
if k > maxi:
prev = arr[i]
else:
k = prev-arr[i]
if k > maxi:
return 0
return 1
l,r = 0,m
while l<=r:
mid = l+((r-l)//2)
if is_ok(mid):
r = mid-1
else:
l = mid+1
if is_ok(l):
print(l)
else:
print(r)
```
| 101,258 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Toad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, …, a_n.
In one operation Zitz can choose an integer k and k indices i_1, i_2, …, i_k such that 1 ≤ i_1 < i_2 < … < i_k ≤ n. He should then change a_{i_j} to ((a_{i_j}+1) mod m) for each chosen integer i_j. The integer m is fixed for all operations and indices.
Here x mod y denotes the remainder of the division of x by y.
Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) — the number of integers in the array and the parameter m.
The next line contains n space-separated integers a_1, a_2, …, a_n (0 ≤ a_i < m) — the given array.
Output
Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print 0.
It is easy to see that with enough operations Zitz can always make his array non-decreasing.
Examples
Input
5 3
0 0 0 1 2
Output
0
Input
5 7
0 6 1 3 2
Output
1
Note
In the first example, the array is already non-decreasing, so the answer is 0.
In the second example, you can choose k=2, i_1 = 2, i_2 = 5, the array becomes [0,0,1,3,3]. It is non-decreasing, so the answer is 1.
Tags: binary search, greedy
Correct Solution:
```
from sys import stdin, stdout
from math import *
n,m,a=0,0,[]
def test(k):
global n,m,a
# print([n,m,a])
b=[]
for i in range(n):
b.append(a[i])
if (i==0):
if ((b[i]+k) >= m):
b[i]=0
else:
if (b[i]==b[i-1]):
continue
if (b[i-1]>b[i]):
if (b[i-1]<=(b[i]+k)):
b[i]=b[i-1]
else:
if (b[i]+k>=m) and (b[i-1]<= ((b[i]+k)%m)):
b[i]=b[i-1]
if (b[i-1]>b[i]):
return False
# print(k)
# print(b)
return True
def main():
global n,m,a
n,m=[int(x) for x in stdin.readline().split()]
a=[int(x) for x in stdin.readline().split()]
res=m
l=0
r=m
while(l<=r):
mid=floor((l+r)/2)
if test(mid)==True:
res=min(res,mid)
r=mid-1
else:
l=mid+1
stdout.write(str(res))
return 0
if __name__ == "__main__":
main()
```
| 101,259 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Toad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, …, a_n.
In one operation Zitz can choose an integer k and k indices i_1, i_2, …, i_k such that 1 ≤ i_1 < i_2 < … < i_k ≤ n. He should then change a_{i_j} to ((a_{i_j}+1) mod m) for each chosen integer i_j. The integer m is fixed for all operations and indices.
Here x mod y denotes the remainder of the division of x by y.
Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) — the number of integers in the array and the parameter m.
The next line contains n space-separated integers a_1, a_2, …, a_n (0 ≤ a_i < m) — the given array.
Output
Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print 0.
It is easy to see that with enough operations Zitz can always make his array non-decreasing.
Examples
Input
5 3
0 0 0 1 2
Output
0
Input
5 7
0 6 1 3 2
Output
1
Note
In the first example, the array is already non-decreasing, so the answer is 0.
In the second example, you can choose k=2, i_1 = 2, i_2 = 5, the array becomes [0,0,1,3,3]. It is non-decreasing, so the answer is 1.
Tags: binary search, greedy
Correct Solution:
```
from collections import Counter
from collections import defaultdict
from collections import deque
import math
import sys
input = sys.stdin.readline
import bisect
rs = lambda: input().strip()
ri = lambda: int(input())
rl = lambda: list(map(int, input().strip().split()))
rls= lambda: list(map(str, input().split()))
def check(k):
p=[]
c=a[0]
prev=0
for i in range(0,n):
x1=a[i]
x2=(a[i]+k)%m
if(x2<x1):
if(x1<=prev<=m-1 or 0<=prev<=x2):
p.append(prev)
continue
else:
prev=a[i]
elif(x2>x1):
if(x1<=prev<=x2):
p.append(prev)
continue
elif(x2<prev):
# print(p,"llll")
return -1
else:
prev=x1
else:
return -1
p.append(prev)
# print(p,mid)
return 1
n,m=rl()
a=list(map(int,input().strip().split()))
if(a==sorted(a)):
print(0)
exit()
l=0
r=m-1
ans=m
while(l<=r):
mid=l+(r-l)//2
if(check(mid)==1):
# print(mid)
ans=min(mid,ans)
r=mid-1
else:
l=mid+1
print(ans)
```
| 101,260 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Toad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, …, a_n.
In one operation Zitz can choose an integer k and k indices i_1, i_2, …, i_k such that 1 ≤ i_1 < i_2 < … < i_k ≤ n. He should then change a_{i_j} to ((a_{i_j}+1) mod m) for each chosen integer i_j. The integer m is fixed for all operations and indices.
Here x mod y denotes the remainder of the division of x by y.
Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) — the number of integers in the array and the parameter m.
The next line contains n space-separated integers a_1, a_2, …, a_n (0 ≤ a_i < m) — the given array.
Output
Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print 0.
It is easy to see that with enough operations Zitz can always make his array non-decreasing.
Examples
Input
5 3
0 0 0 1 2
Output
0
Input
5 7
0 6 1 3 2
Output
1
Note
In the first example, the array is already non-decreasing, so the answer is 0.
In the second example, you can choose k=2, i_1 = 2, i_2 = 5, the array becomes [0,0,1,3,3]. It is non-decreasing, so the answer is 1.
Tags: binary search, greedy
Correct Solution:
```
from sys import stdin
ii = lambda: int(input())
mi = lambda: map(int, input().split())
li = lambda: list(mi())
si = lambda: input()
msi = lambda: map(int, stdin.readline().split())
lsi = lambda: list(msi())
n,m=li()
a=li()
l,r=0,m
while(l<r):
M=(l+r)//2
ai1=0
for ai in a:
if (m-ai+ai1)%m>M:
if ai<ai1:
l=M+1
break
ai1=ai
else:
r=M
print(l)
```
| 101,261 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Toad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, …, a_n.
In one operation Zitz can choose an integer k and k indices i_1, i_2, …, i_k such that 1 ≤ i_1 < i_2 < … < i_k ≤ n. He should then change a_{i_j} to ((a_{i_j}+1) mod m) for each chosen integer i_j. The integer m is fixed for all operations and indices.
Here x mod y denotes the remainder of the division of x by y.
Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) — the number of integers in the array and the parameter m.
The next line contains n space-separated integers a_1, a_2, …, a_n (0 ≤ a_i < m) — the given array.
Output
Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print 0.
It is easy to see that with enough operations Zitz can always make his array non-decreasing.
Examples
Input
5 3
0 0 0 1 2
Output
0
Input
5 7
0 6 1 3 2
Output
1
Note
In the first example, the array is already non-decreasing, so the answer is 0.
In the second example, you can choose k=2, i_1 = 2, i_2 = 5, the array becomes [0,0,1,3,3]. It is non-decreasing, so the answer is 1.
Submitted Solution:
```
n , k = map(int , input().split())
A = list(map(int , input().split()))
l = 0
r = k + 1
ans = k + 1
for _ in range(20):
B = [0] * n
m = (l + r)//2
min1 = 0
fl = 0
#print(m)
for i in range(n):
if A[i] > min1 :
if k - A[i] + min1 <= m:
B[i] = min1
else:
min1 = A[i]
B[i] = A[i]
else:
if min1 - A[i] > m:
fl = 1
break
else:
B[i] = min1
if fl == 0:
#print(B)
for i in range( n -1 ):
if B[i] > B[i + 1]:
break
fl = 1
if fl == 0:
r = m
ans = min(ans , m)
else:
l = m
else:
l = m
print(ans)
```
Yes
| 101,262 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Toad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, …, a_n.
In one operation Zitz can choose an integer k and k indices i_1, i_2, …, i_k such that 1 ≤ i_1 < i_2 < … < i_k ≤ n. He should then change a_{i_j} to ((a_{i_j}+1) mod m) for each chosen integer i_j. The integer m is fixed for all operations and indices.
Here x mod y denotes the remainder of the division of x by y.
Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) — the number of integers in the array and the parameter m.
The next line contains n space-separated integers a_1, a_2, …, a_n (0 ≤ a_i < m) — the given array.
Output
Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print 0.
It is easy to see that with enough operations Zitz can always make his array non-decreasing.
Examples
Input
5 3
0 0 0 1 2
Output
0
Input
5 7
0 6 1 3 2
Output
1
Note
In the first example, the array is already non-decreasing, so the answer is 0.
In the second example, you can choose k=2, i_1 = 2, i_2 = 5, the array becomes [0,0,1,3,3]. It is non-decreasing, so the answer is 1.
Submitted Solution:
```
#!/usr/bin/env python
def check(mid):
# print(f'called check({mid})')
local_a = [0]
for ai in a:
local_a.append(ai)
for i in range(1, n + 1):
if local_a[i] < local_a[i - 1]:
if local_a[i] + mid >= local_a[i - 1]:
local_a[i] = local_a[i - 1]
elif local_a[i] + mid >= m + local_a[i - 1]:
local_a[i] = local_a[i - 1]
if local_a[i] < local_a[i - 1]:
return False
# print(local_a)
return True
n, m = map(int, input().split())
a = list(map(int, input().split()))
low, high = 0, m
while low != high:
mid = (low + high) >> 1
if check(mid):
high = mid
else:
low = mid + 1
print(low)
```
Yes
| 101,263 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Toad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, …, a_n.
In one operation Zitz can choose an integer k and k indices i_1, i_2, …, i_k such that 1 ≤ i_1 < i_2 < … < i_k ≤ n. He should then change a_{i_j} to ((a_{i_j}+1) mod m) for each chosen integer i_j. The integer m is fixed for all operations and indices.
Here x mod y denotes the remainder of the division of x by y.
Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) — the number of integers in the array and the parameter m.
The next line contains n space-separated integers a_1, a_2, …, a_n (0 ≤ a_i < m) — the given array.
Output
Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print 0.
It is easy to see that with enough operations Zitz can always make his array non-decreasing.
Examples
Input
5 3
0 0 0 1 2
Output
0
Input
5 7
0 6 1 3 2
Output
1
Note
In the first example, the array is already non-decreasing, so the answer is 0.
In the second example, you can choose k=2, i_1 = 2, i_2 = 5, the array becomes [0,0,1,3,3]. It is non-decreasing, so the answer is 1.
Submitted Solution:
```
def check(M):
now = 0
for i in range(n):
#print(i, now, mas[i], M, (now - mas[i]) % m)
if (now - mas[i]) % m > M:
if mas[i] > now:
now = mas[i]
else:
return False
return True
n, m = list(map(int, input().split()))
l = -1
r = m
mas = list(map(int, input().split()))
check(3)
while l < r - 1:
M = (l + r) // 2
if check(M):
r = M
else:
l = M
print(r)
```
Yes
| 101,264 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Toad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, …, a_n.
In one operation Zitz can choose an integer k and k indices i_1, i_2, …, i_k such that 1 ≤ i_1 < i_2 < … < i_k ≤ n. He should then change a_{i_j} to ((a_{i_j}+1) mod m) for each chosen integer i_j. The integer m is fixed for all operations and indices.
Here x mod y denotes the remainder of the division of x by y.
Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) — the number of integers in the array and the parameter m.
The next line contains n space-separated integers a_1, a_2, …, a_n (0 ≤ a_i < m) — the given array.
Output
Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print 0.
It is easy to see that with enough operations Zitz can always make his array non-decreasing.
Examples
Input
5 3
0 0 0 1 2
Output
0
Input
5 7
0 6 1 3 2
Output
1
Note
In the first example, the array is already non-decreasing, so the answer is 0.
In the second example, you can choose k=2, i_1 = 2, i_2 = 5, the array becomes [0,0,1,3,3]. It is non-decreasing, so the answer is 1.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
_str = str
BUFSIZE = 8192
def str(x=b''):
return x if type(x) is bytes else _str(x).encode()
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')
def inp():
return sys.stdin.readline().rstrip()
def mpint():
return map(int, inp().split(' '))
def itg():
return int(inp())
# ############################## import
def discrete_binary_search(func, lo, hi):
"""
Locate the first value x s.t. func(x) = True within [lo, hi]
return hi if not founded
func(hi) will never been execution
"""
while lo < hi:
mi = lo + (hi - lo) // 2
if func(mi):
hi = mi
else:
lo = mi + 1
return lo
# ############################## main
def solve():
n, m = mpint()
arr = tuple(mpint())
def check(x):
""" ans is <= x """
prev = 0
for i in range(n):
if arr[i] > prev:
if m - (arr[i] - prev) > x:
prev = arr[i]
elif prev - arr[i] > x:
return False
return True
return discrete_binary_search(check, 0, m)
def main():
# print("YES" if solve() else "NO")
# print("yes" if solve() else "no")
# solve()
print(solve())
# for _ in range(itg()):
# print(solve())
DEBUG = 0
URL = 'https://codeforces.com/contest/1169/problem/C'
if __name__ == '__main__':
if DEBUG:
if DEBUG == 2:
main()
exit()
import requests # ImportError: cannot import name 'md5' from 'sys' (unknown location)
from ACgenerator.Y_Test_Case_Runner import TestCaseRunner
runner = TestCaseRunner(main, URL)
inp = runner.input_stream
print = runner.output_stream
runner.checking()
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
main()
# Please check!
```
Yes
| 101,265 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Toad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, …, a_n.
In one operation Zitz can choose an integer k and k indices i_1, i_2, …, i_k such that 1 ≤ i_1 < i_2 < … < i_k ≤ n. He should then change a_{i_j} to ((a_{i_j}+1) mod m) for each chosen integer i_j. The integer m is fixed for all operations and indices.
Here x mod y denotes the remainder of the division of x by y.
Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) — the number of integers in the array and the parameter m.
The next line contains n space-separated integers a_1, a_2, …, a_n (0 ≤ a_i < m) — the given array.
Output
Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print 0.
It is easy to see that with enough operations Zitz can always make his array non-decreasing.
Examples
Input
5 3
0 0 0 1 2
Output
0
Input
5 7
0 6 1 3 2
Output
1
Note
In the first example, the array is already non-decreasing, so the answer is 0.
In the second example, you can choose k=2, i_1 = 2, i_2 = 5, the array becomes [0,0,1,3,3]. It is non-decreasing, so the answer is 1.
Submitted Solution:
```
n , k = map(int , input().split())
A = list(map(int , input().split()))
l = 0
r = k
ans = k
for _ in range(5):
B = [0] * n
m = (l + r)//2
min1 = 0
fl = 0
#print(m)
for i in range(n):
if A[i] > min1 :
if k - A[i] + min1 <= m:
B[i] = min1
else:
min1 = A[i]
B[i] = A[i]
else:
if min1 - A[i] > m:
fl = 1
break
else:
B[i] = min1
if fl == 0:
#print(B)
for i in range( n -1 ):
if B[i] > B[i + 1]:
break
fl = 1
if fl == 0:
r = m
ans = min(ans , m)
else:
l = r
print(ans)
```
No
| 101,266 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Toad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, …, a_n.
In one operation Zitz can choose an integer k and k indices i_1, i_2, …, i_k such that 1 ≤ i_1 < i_2 < … < i_k ≤ n. He should then change a_{i_j} to ((a_{i_j}+1) mod m) for each chosen integer i_j. The integer m is fixed for all operations and indices.
Here x mod y denotes the remainder of the division of x by y.
Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) — the number of integers in the array and the parameter m.
The next line contains n space-separated integers a_1, a_2, …, a_n (0 ≤ a_i < m) — the given array.
Output
Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print 0.
It is easy to see that with enough operations Zitz can always make his array non-decreasing.
Examples
Input
5 3
0 0 0 1 2
Output
0
Input
5 7
0 6 1 3 2
Output
1
Note
In the first example, the array is already non-decreasing, so the answer is 0.
In the second example, you can choose k=2, i_1 = 2, i_2 = 5, the array becomes [0,0,1,3,3]. It is non-decreasing, so the answer is 1.
Submitted Solution:
```
from sys import stdin
# stdin=open('input.txt')
def input():
return stdin.readline().strip()
# from sys import stdout
# stdout=open('input.txt',mode='w+')
# def print1(x, end='\n'):
# stdout.write(str(x) +end)
# a, b = map(int, input().split())
# l = list(map(int, input().split()))
# # CODE BEGINS HERE.................
def solve(beg, end, a, MOD):
if beg + 1 == end:
return end
k = (beg + end)//2
conditions = []
# print(beg, end, k)
for i in range(n):
if k + a[i] < MOD:
conditions.append([(a[i],a[i] + k)])
elif k + a[i] >= MOD:
conditions.append([(a[i], MOD - 1), (0, (a[i] + k) % MOD)])
prev = 0
flag = True
for cond in conditions:
if len(cond) == 2:
if prev <= min(cond[0][0], cond[1][0]):
prev = min(cond[0][0], cond[1][0])
elif prev <= max(cond[0][0], cond[1][0]):
prev = max(cond[0][0], cond[1][0])
elif prev >= cond[0][0] and prev <= cond[0][1]:
prev = prev
elif prev >= cond[1][0] and prev <= cond[1][1]:
prev = prev
else:
flag = False
break
else:
if prev <= cond[0][0]:
prev = cond[0][0]
elif prev >= cond[0][0] and prev <= cond[0][1]:
prev = prev
else:
flag = False
break
if not flag:
return solve(k, end, a, MOD)
else:
if beg == k:
return k
return solve(beg, k, a, MOD)
n, MOD = map(int, input().split())
a = list(map(int, input().split()))
print(solve(-1, MOD, a, MOD))
# # CODE ENDS HERE....................
# stdout.close()
```
No
| 101,267 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Toad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, …, a_n.
In one operation Zitz can choose an integer k and k indices i_1, i_2, …, i_k such that 1 ≤ i_1 < i_2 < … < i_k ≤ n. He should then change a_{i_j} to ((a_{i_j}+1) mod m) for each chosen integer i_j. The integer m is fixed for all operations and indices.
Here x mod y denotes the remainder of the division of x by y.
Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) — the number of integers in the array and the parameter m.
The next line contains n space-separated integers a_1, a_2, …, a_n (0 ≤ a_i < m) — the given array.
Output
Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print 0.
It is easy to see that with enough operations Zitz can always make his array non-decreasing.
Examples
Input
5 3
0 0 0 1 2
Output
0
Input
5 7
0 6 1 3 2
Output
1
Note
In the first example, the array is already non-decreasing, so the answer is 0.
In the second example, you can choose k=2, i_1 = 2, i_2 = 5, the array becomes [0,0,1,3,3]. It is non-decreasing, so the answer is 1.
Submitted Solution:
```
import copy
n, m = map(int, input().split())
a = list(map(int, input().split()))
l = -1
r = 300001
def check(x):
global a
global m
success = True
if (a[0] + x >= m):
a[0] = 0
last = a[0]
for i in range(1, len(a)):
now = a[i]
if (now < last):
now = min(last, now + x)
if (a[i] + x >= m + last):
now = last
if (now < last):
return False
last = now
return True
while (r - l > 1):
mid = (l + r) // 2
if (check(mid)):
r = mid
else:
l = mid
print(r)
```
No
| 101,268 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Toad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, …, a_n.
In one operation Zitz can choose an integer k and k indices i_1, i_2, …, i_k such that 1 ≤ i_1 < i_2 < … < i_k ≤ n. He should then change a_{i_j} to ((a_{i_j}+1) mod m) for each chosen integer i_j. The integer m is fixed for all operations and indices.
Here x mod y denotes the remainder of the division of x by y.
Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) — the number of integers in the array and the parameter m.
The next line contains n space-separated integers a_1, a_2, …, a_n (0 ≤ a_i < m) — the given array.
Output
Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print 0.
It is easy to see that with enough operations Zitz can always make his array non-decreasing.
Examples
Input
5 3
0 0 0 1 2
Output
0
Input
5 7
0 6 1 3 2
Output
1
Note
In the first example, the array is already non-decreasing, so the answer is 0.
In the second example, you can choose k=2, i_1 = 2, i_2 = 5, the array becomes [0,0,1,3,3]. It is non-decreasing, so the answer is 1.
Submitted Solution:
```
import copy
n, m = map(int, input().split())
a = list(map(int, input().split()))
l = -1
r = 1000000
def check(x):
global a
global m
b = a.copy()
b[0] = max(0, b[0] - x)
success = True
for i in range(1, len(b)):
if (b[i] < b[i - 1]):
b[i] = min(b[i - 1], b[i] + x)
if (a[i] - x < 0 and a[i] - x + m <= b[i-1]):
b[i] = b[i - 1]
if (a[i] - x < 0 and a[i] - x + m > b[i-1]):
b[i] = min(b[i], a[i] - x + m)
if (b[i] > b[i - 1]):
b[i] = max(b[i - 1], b[i] - x)
if (a[i] + x >= m + b[i - 1]):
b[i] = b[i - 1]
if (b[i] < b[i - 1]):
success = False
return success
while (r - l > 1):
mid = (l + r) // 2
if (check(mid)):
r = mid
else:
l = mid
print(r)
```
No
| 101,269 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Tags: dfs and similar, dp, trees
Correct Solution:
```
from sys import stdin
si = iter(stdin)
num = int(next(si))
nodeedge = [[] for _ in range(num + 1)]
nodescore = [0] * (num + 1)
nodecount = [0] * (num + 1)
for _ in range(num-1):
u,v = map(int, next(si).split())
nodeedge[u].append(v)
nodeedge[v].append(u)
p = 0
q = 1
n = 1
inlist = [False] * (num + 1)
nodelist = [n]
inlist[n] = True
for p in range(num):
for m in nodeedge[nodelist[p]]:
if not inlist[m]:
nodelist.append(m)
inlist[m] = True
for p in range(num-1, -1, -1):
nodes = 1
score = 0
n = nodelist[p]
for m in nodeedge[n]:
nodes += nodecount[m]
score += nodescore[m]
score += nodes
nodecount[n] = nodes
nodescore[n] = score
updated = [False] * (num + 1)
updated[nodelist[0]] = True
best = 0
for p in range(num):
n = nodelist[p]
for m in nodeedge[n]:
if not updated[m]:
nodescore[m] = nodescore[n] - 2 * nodecount[m] + num
updated[m] = True
if nodescore[m] > best:
best = nodescore[m]
print(best)
```
| 101,270 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Tags: dfs and similar, dp, trees
Correct Solution:
```
import sys
from collections import deque
input = sys.stdin.readline
n=int(input())
E=[[] for i in range(n+1)]
for i in range(n-1):
x,y=map(int,input().split())
E[x].append(y)
E[y].append(x)
H=[-1]*(n+1)
H[1]=0
QUE=deque([1])
fromnode=[-1]*(n+1)
while QUE:
x=QUE.pop()
for to in E[x]:
if H[to]==-1:
H[to]=H[x]+1
fromnode[to]=x
QUE.append(to)
S=list(range(1,n+1))
S.sort(key=lambda x:H[x],reverse=True)
DP1=[0]*(n+1) # from the other nodes to 1
Size=[0]*(n+1)
for s in S:
for to in E[s]:
if Size[to]!=0:
Size[s]+=Size[to]
DP1[s]+=DP1[to]
Size[s]+=1
DP1[s]+=Size[s]
ANS=[0]*(n+1)
ANS[1]=DP1[1]
for s in S[::-1][1:]:
ANS[s]=ANS[fromnode[s]]+n-2*Size[s]
print(max(ANS))
```
| 101,271 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Tags: dfs and similar, dp, trees
Correct Solution:
```
import sys
input = sys.stdin.readline
n = int(input())
ab = [list(map(int,input().split())) for i in range(n-1)]
graph = [[] for i in range(n+1)]
deg = [0]*(n+1)
for a,b in ab:
graph[a].append(b)
graph[b].append(a)
deg[a] += 1
deg[b] += 1
if n == 2:
print(3)
exit()
root = 0
stack = []
for i in range(1,n+1):
if deg[i] == 1:
stack.append(i)
elif not root:
root = i
deg[root] += 1
dpp = [[] for i in range(n+1)]
dpv = [[] for i in range(n+1)]
pnt = [0]*(n+1)
vtxs = [0]*(n+1)
while stack:
x = stack.pop()
vtxs[x] = sum(dpv[x])+1
pnt[x] = sum(dpp[x])+vtxs[x]
for y in graph[x]:
if deg[y] > 1:
dpp[y].append(pnt[x])
dpv[y].append(vtxs[x])
deg[y] -= 1
if deg[y] == 1:
stack.append(y)
pntsum = [0]*(n+1)
pntsum[root] = pnt[root]
stack = [root]
while stack:
x = stack.pop()
if x == root:
deg[x] -= 1
pntsum[x] = sum(dpp[x])+n
for y in graph[x]:
if deg[y] == 1:
dpp[y].append(pntsum[x]-vtxs[y]-pnt[y])
dpv[y].append(n-vtxs[y])
deg[y] -= 1
stack.append(y)
print(max(pntsum))
```
| 101,272 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Tags: dfs and similar, dp, trees
Correct Solution:
```
###pyrival template for fast IO
import os
import sys
from io import BytesIO, IOBase
# region fastio
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")
##make the tree
n=int(input())
tree={1:[]}
for i in range(n-1):
a,b=[int(x) for x in input().split()]
if a not in tree:
tree[a]=[b]
else:
tree[a].append(b)
if b not in tree:
tree[b]=[a]
else:
tree[b].append(a)
###### undirected dfs thats not n2 in worst case
def dfs(graph,n,currnode):
visited=[False for x in range(n+1)]
stack=[currnode]
parent=[0 for x in range(n+1)]
index=[0 for x in range(n+1)]
ans=[1 for x in range(n+1)]
arr=[]
while stack:
currnode=stack[-1]
if visited[currnode]==False:
visited[currnode]=True
arr.append(currnode)
for i in range(index[currnode],len(graph[currnode])):
neighbour=graph[currnode][i]
if visited[neighbour]==False:
visited[neighbour]=True
stack.append(neighbour)
parent[neighbour]=currnode
arr.append(neighbour)
index[currnode]+=1
break
else:
ans[parent[currnode]]+=ans[currnode]
####prefix sum arr
stack.pop()
return ans,parent,arr
a,parent,arr=dfs(tree,n,1)
ans=[0 for x in range(n+1)]
ans[1]=sum(a[1:]) #total sum of prefix sum
s=ans[1]
'''
rooting forula
node=2
a[parent[node]]-=a[node]
a[node]+=a[parent[node]]
print(sum(a[1:]))
'''
def dfs1(graph,n,currnode):
global s
visited=[False for x in range(n+1)]
stack=[currnode]
index=[0 for x in range(n+1)]
while stack:
currnode=stack[-1]
if visited[currnode]==False:
visited[currnode]=True
for i in range(index[currnode],len(graph[currnode])):
neighbour=graph[currnode][i]
if visited[neighbour]==False:
visited[neighbour]=True
stack.append(neighbour)
index[currnode]+=1
###re rooting our ans arr
a[parent[neighbour]]-=a[neighbour]
s-=a[neighbour]
a[neighbour]+=a[parent[neighbour]]
s+=a[parent[neighbour]]
ans[neighbour]=s##optimise this
break
else:
##changing state back to its parent after backtacking
a[currnode]-=a[parent[currnode]]
s-=a[parent[currnode]]
a[parent[currnode]]+=a[currnode]
s+=a[currnode]
stack.pop()
return
dfs1(tree,n,1)
print(max(ans[1:]))
```
| 101,273 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Tags: dfs and similar, dp, trees
Correct Solution:
```
import sys
from collections import deque
from random import randrange
input = sys.stdin.readline
print = sys.stdout.write
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
n = int(input())
tree = [[] for i in range(n + 1)]
for i in range(n - 1):
a,b = map(int,input().strip().split())
tree[a].append(b)
tree[b].append(a)
dp = [0 for i in range(n + 1)]
s = [0 for i in range(n + 1)]
ans = [0 for i in range(n + 1)]
@bootstrap
def dfs(node,pd,dist):
for child in tree[node]:
if child == pd:
continue
yield dfs(child,node,dist + 1)
dp[node] += dp[child]
s[node] += s[child]
s[node] += 1
dp[node] += dist
yield dp[node]
root = randrange(1,n + 1)
dfs(root,-1,1)
q = deque(); ans[root] = dp[root]
for start in tree[root]:
q.append((start,root))
while len(q) > 0:
node,pd = q.popleft()
ans[node] = ans[pd] - s[node] + (s[root] - s[node])
for child in tree[node]:
if child == pd:
continue
q.append((child,node))
print(str(max(ans)))
```
| 101,274 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Tags: dfs and similar, dp, trees
Correct Solution:
```
class Graph:
def __init__(self, n_vertices, edges, directed=True):
self.n_vertices = n_vertices
self.edges = edges
self.directed = directed
@property
def adj(self):
try:
return self._adj
except AttributeError:
adj = [[] for _ in range(self.n_vertices)]
if self.directed:
for u,v in self.edges:
adj[u].append(v)
else:
for u,v in self.edges:
adj[u].append(v)
adj[v].append(u)
self._adj = adj
return adj
class RootedTree(Graph):
def __init__(self, n_vertices, edges, root_vertex=0):
self.root = root_vertex
super().__init__(n_vertices, edges, False)
@property
def parent(self):
try:
return self._parent
except AttributeError:
adj = self.adj
parent = [None]*self.n_vertices
parent[self.root] = -1
stack = [self.root]
for _ in range(self.n_vertices):
v = stack.pop()
for u in adj[v]:
if parent[u] is None:
parent[u] = v
stack.append(u)
self._parent = parent
return parent
@property
def children(self):
try:
return self._children
except AttributeError:
children = [None]*self.n_vertices
for v,(l,p) in enumerate(zip(self.adj,self.parent)):
children[v] = [u for u in l if u != p]
self._children = children
return children
@property
def dfs_order(self):
try:
return self._dfs_order
except AttributeError:
order = [None]*self.n_vertices
children = self.children
stack = [self.root]
for i in range(self.n_vertices):
v = stack.pop()
order[i] = v
for u in children[v]:
stack.append(u)
self._dfs_order = order
return order
from functools import reduce
from itertools import accumulate,chain
def rerooting(rooted_tree, merge, identity, finalize):
N = rooted_tree.n_vertices
parent = rooted_tree.parent
children = rooted_tree.children
order = rooted_tree.dfs_order
# from leaf to parent
dp_down = [None]*N
for v in reversed(order[1:]):
dp_down[v] = finalize(reduce(merge,
(dp_down[c] for c in children[v]),
identity), v)
# from parent to leaf
dp_up = [None]*N
dp_up[0] = identity
for v in order:
if len(children[v]) == 0:
continue
temp = (dp_up[v],)+tuple(dp_down[u] for u in children[v])+(identity,)
left = accumulate(temp[:-2],merge)
right = tuple(accumulate(reversed(temp[2:]),merge))
for u,l,r in zip(children[v],left,reversed(right)):
dp_up[u] = finalize(merge(l,r), v)
res = [None]*N
for v,l in enumerate(children):
res[v] = reduce(merge,
(dp_down[u] for u in children[v]),
identity)
res[v] = finalize(merge(res[v], dp_up[v]), v)
return res
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
if __name__ == '__main__':
n = int(readline())
temp = map(lambda x:int(x)-1, read().split())
edges = zip(temp,temp)
def merge(x,y):
p1, s1 = x
p2, s2 = y
return p1+p2,s1+s2
def finalize(x,v):
p, s = x
return p+s+1, s+1
t = RootedTree(n, edges, 0)
res = rerooting(t, merge, (0,0), finalize)
print(max(res)[0])
```
| 101,275 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Tags: dfs and similar, dp, trees
Correct Solution:
```
import sys
def getpar(Edge, p):
N = len(Edge)
par = [0]*N
par[0] = -1
par[p] -1
stack = [p]
visited = set([p])
while stack:
vn = stack.pop()
for vf in Edge[vn]:
if vf in visited:
continue
visited.add(vf)
par[vf] = vn
stack.append(vf)
return par
def topological_sort_tree(E, r):
Q = [r]
L = []
visited = set([r])
while Q:
vn = Q.pop()
L.append(vn)
for vf in E[vn]:
if vf not in visited:
visited.add(vf)
Q.append(vf)
return L
def getcld(p):
res = [[] for _ in range(len(p))]
for i, v in enumerate(p[1:], 1):
res[v].append(i)
return res
N = int(input())
Edge = [[] for _ in range(N)]
for _ in range(N-1):
a, b = map(int, sys.stdin.readline().split())
a -= 1
b -= 1
Edge[a].append(b)
Edge[b].append(a)
P = getpar(Edge, 0)
L = topological_sort_tree(Edge, 0)
C = getcld(P)
dp1 = [1]*N
size = [1]*N
for l in L[N-1:0:-1]:
p = P[l]
dp1[p] = dp1[p] + dp1[l] + size[l]
size[p] = size[p] + size[l]
dp2 = [1]*N
dp2[0] = dp1[0]
for l in L[1:]:
p = P[l]
dp2[l] = dp2[p] + N - 2*size[l]
print(max(dp2))
```
| 101,276 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Tags: dfs and similar, dp, trees
Correct Solution:
```
import sys
import threading
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
N = int(input())
graph = [[] for _ in range(N)]
for _ in range(N-1):
a, b = map(int, input().split())
graph[a-1].append(b-1)
graph[b-1].append(a-1)
dp = [1]*N
checked1 = [False]*N
checked = [False]*N
ans = 0
def dfs(p):
checked1[p] = True
for np in graph[p]:
if not checked1[np]:
dfs(np)
dp[p] += dp[np]
def reroot(p, score):
global ans
ans = max(ans, score)
checked[p] = True
for np in graph[p]:
if not checked[np]:
root = dp[p]
goto = dp[np]
dp[np] = root
dp[p] = root - goto
reroot(np, score + root - 2*goto)
dp[np] = goto
dp[p] = root
def main():
dfs(0)
reroot(0, sum(dp))
print(ans)
if __name__ == "__main__":
threading.stack_size(1024 * 100000)
thread = threading.Thread(target=main)
thread.start()
thread.join()
```
| 101,277 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Submitted Solution:
```
# ///////////////////////////////////////////////////////////////////////////
# //////////////////// PYTHON IS THE BEST ////////////////////////
# ///////////////////////////////////////////////////////////////////////////
import sys,os,io
import math
from collections import defaultdict
from io import BytesIO, IOBase
from types import GeneratorType
BUFSIZE = 8192
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
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")
def ii():
return int(input())
def li():
return list(map(int,input().split()))
# ///////////////////////////////////////////////////////////////////////////
# //////////////////// DO NOT TOUCH BEFORE THIS LINE ////////////////////////
# ///////////////////////////////////////////////////////////////////////////
if(os.path.exists('input.txt')):
sys.stdin = open("input.txt","r") ; sys.stdout = open("output.txt","w")
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
n = ii()
adj = [[] for i in range(n)]
for i in range(n-1):
u,v = li()
u-=1
v-=1
adj[u].append(v)
adj[v].append(u)
ans = 0
size = [0]*n
@bootstrap
def dfs(node,parent):
sz = 0
for kid in adj[node]:
if kid!=parent:
sz+=yield dfs(kid,node)
size[node] = sz+1
yield size[node]
dfs(0,-1)
# print(size)
parentscore = 0
@bootstrap
def dfs(node,parent):
global parentscore
parentscore += size[node]
cnt = 0
for kid in adj[node]:
if kid!=parent:
yield dfs(kid,node)
yield
dfs(0,-1)
# print(parentscore)
@bootstrap
def dfs(node,parent,parentscore):
global ans
ans = max(ans,parentscore)
# print(parent,node,parentscore)
for kid in adj[node]:
if kid!=parent:
yield dfs(kid,node,parentscore+n-2*size[kid])
yield
dfs(0,-1,parentscore)
print(ans)
```
Yes
| 101,278 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Submitted Solution:
```
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n = int(input())
g = [[] for _ in range(n)]
for i in range(n-1):
u, v = map(int, input().split())
u, v = u-1, v-1
g[u].append(v)
g[v].append(u)
s = []
s.append(0)
order = []
parent = [-1]*n
while s:
v = s.pop()
order.append(v)
for u in g[v]:
if parent[v] != u:
s.append(u)
parent[u] = v
order.reverse()
dp = [0]*n
subtree = [1]*n
for v in order:
dp[v] += subtree[v]
if parent[v] != -1:
subtree[parent[v]] += subtree[v]
dp[parent[v]] += dp[v]
#print(dp)
#print(subtree)
order.reverse()
ans = [0]*n
for v in order:
ans[v] = dp[v]
for u in g[v]:
temp = ans[v]
temp -= dp[u]+subtree[u]
#print(u, temp)
dp[u] -= subtree[u]
subtree[u] = n
dp[u] += subtree[u]
dp[u] += temp
print(max(ans))
```
Yes
| 101,279 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Submitted Solution:
```
from sys import stdin
def create_nodelist():
p = 0
q = 1
n = 1
inlist = [False] * (num+1)
nodelist = [n]
inlist[n] = True
while p < q:
for m in nodeedge[nodelist[p]]:
if not inlist[m]:
nodelist.append(m)
q+=1
inlist[m] = True
p+=1
assert len(nodelist) == num
return nodelist
def base_nodescores(nodelist):
for p in range(num-1, -1, -1):
nodes = 1
score = 0
n = nodelist[p]
for m in nodeedge[n]:
nodes += nodecount[m]
score += nodescore[m]
score += nodes
nodecount[n] = nodes
nodescore[n] = score
def update_nodescores(nodelist):
updated = [False] * (num+1)
updated[nodelist[0]] = True
for p in range(num):
n = nodelist[p]
for m in nodeedge[n]:
if not updated[m]:
nodescore[m] = nodescore[n] - 2*nodecount[m] + num
updated[m] = True
si = iter(stdin)
num = int(next(si))
nodeedge = [[] for _ in range(num + 1)]
nodescore = [0] * (num + 1)
nodecount = [0] * (num + 1)
for _ in range(num-1):
u,v = map(int, next(si).split())
nodeedge[u].append(v)
nodeedge[v].append(u)
nodelist = create_nodelist()
base_nodescores(nodelist)
update_nodescores(nodelist)
print(max(nodescore))
```
Yes
| 101,280 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Submitted Solution:
```
from sys import *
from queue import deque
n = int(stdin.readline())
adj = [[] for i in range(n)]
for i in range(n-1):
u,v = map(int, stdin.readline().split())
adj[u-1].append(v-1)
adj[v-1].append(u-1)
root = 0
# root the tree
def rooted(root):
new_adj = [[] for i in range(n)]
pi = [-1]*n
visited = [False]*n
visited[root] = True
todo = [root]
while todo:
top = todo.pop()
for nbr in adj[top]:
if not visited[nbr]:
visited[nbr] = True
todo.append(nbr)
pi[nbr] = top
new_adj[top].append(nbr)
return new_adj, pi
adj, pi = rooted(root)
size = [0]*n
subtree = [0]*n
dists = [0]*n
# post-order: process children, then parent
def fill_size(v):
s = 1
subt = 0
for nbr in adj[v]:
rs, rsubt = fill_size(nbr)
s += rs
subt += rsubt + rs
size[v] = s
subtree[v] = subt
return s, subt
#fill_size(root)
#iterative version
final = []
todo = [root]
while todo:
v = todo.pop()
for w in adj[v]:
todo.append(w)
final.append(v)
for v in reversed(final):
s = 1
subt = 0
for child in adj[v]:
s += size[child]
subt += size[child] + subtree[child]
size[v] = s
subtree[v] = subt
# preorder: process parent, then children
dists[root] = subtree[root]
def fill_dists(v):
if v != root:
dists[v] = dists[pi[v]] - size[v] + (n - size[v])
for nbr in adj[v]:
fill_dists(nbr)
#fill_dists(root)
#iterative version
todo = deque([root])
while todo:
top = todo.popleft()
if top != root:
dists[top] = dists[pi[top]] - size[top] + (n - size[top])
for nbr in adj[top]:
todo.append(nbr)
print(max(dists) + n)
```
Yes
| 101,281 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Submitted Solution:
```
n = int(input())
uvs = [[0, 0] for i in range(n)]
for i in range(n - 1):
uvs[i][0], uvs[i][1] = map(int, input().split(' '))
if n == 9:
print(36)
elif n == 5:
print(14)
```
No
| 101,282 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Submitted Solution:
```
g = {}
p = {}
n = int(input())
dp_1 = [0] * (n+1)
size = [0] * (n+1)
dp_2 = [None for _ in range(n+1)]
for _ in range(n-1):
u, v = map(int, input().split())
if u not in g:
g[u] = []
g[u].append(v)
if v not in g:
g[v] = []
g[v].append(u)
def dfs(p, dp_1, dp_2, size):
p[1] = 0
i = 0
S = [1]
while i < len(S):
cur = S[i]
for x in g[cur]:
if x == p[cur]:continue
p[x] = cur
S.append(x)
i += 1
for cur in S[::-1]:
if len(g[cur]) == 1 and cur!=1:
dp_1[cur] = 1
size[cur] = 1
dp_2[cur] = [1, 1]
else:
size[cur] = 1
max_val = 0
length = 0
for x in g[cur]:
if x == p[cur]:continue
size[cur] += size[x]
dp_1[cur] = size[cur]
for x in g[cur]:
if x == p[cur]:continue
dp_1[cur] += dp_1[x]
for x in g[cur]:
if x == p[cur]:continue
new_val = dp_2[x][0] + dp_2[x][1] * (size[cur]-size[x]) + (dp_1[cur]-dp_1[x]-size[x])
if new_val > max_val:
max_val, length = new_val, dp_2[x][1] + 1
elif new_val == max_val and dp_2[x][1] + 1 > length:
length = dp_2[x][1] + 1
dp_2[cur] = [max_val, length]
dfs(p, dp_1, dp_2, size)
print(dp_2[1][0])
#7
#7 6
#7 5
#7 2
#7 1
#5 4
#5 3
```
No
| 101,283 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Submitted Solution:
```
from collections import defaultdict as dd
v=int(input())
graph=dd(list)
deg=dd(int)
for edges in range(v-1):
a,b=map(int,input().split())
graph[a].append(b)
graph[b].append(a)
deg[a]+=1
deg[b]+=1
for i in deg:
if deg[i]==1:
leaf=i
break
visited=[0 for i in range(v+1)]
def dfs(graph,node=leaf,pts=0,vert=0):
visited[node]=1
if node!=leaf and deg[node]==1:
return 1
else:
for i in graph[node]:
if not visited[i]:
return(pts+vert+dfs(graph,i,pts,vert-1))
print(dfs(graph,leaf,0,v))
```
No
| 101,284 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.
Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.
Let's see the following example:
<image>
Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.
Your task is to maximize the number of points you gain.
Input
The first line contains an integer n — the number of vertices in the tree (2 ≤ n ≤ 2 ⋅ 10^5).
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum number of points you gain if you will play optimally.
Examples
Input
9
1 2
2 3
2 5
2 6
1 4
4 9
9 7
9 8
Output
36
Input
5
1 2
1 3
2 4
2 5
Output
14
Note
The first example tree is shown in the problem statement.
Submitted Solution:
```
g = {}
p = {}
n = int(input())
dp_1 = [0] * (n+1)
size = [0] * (n+1)
dp_2 = [None for _ in range(n+1)]
for _ in range(n-1):
u, v = map(int, input().split())
if u not in g:
g[u] = []
g[u].append(v)
if v not in g:
g[v] = []
g[v].append(u)
def dfs(p, dp_1, dp_2, size):
root = 1
s_ = 1
for x in g:
if len(g[x]) > s_:
root = x
s_ = len(g[x])
p[root] = 0
i = 0
S = [root]
while i < len(S):
cur = S[i]
for x in g[cur]:
if x == p[cur]:continue
p[x] = cur
S.append(x)
i += 1
for cur in S[::-1]:
if len(g[cur]) == 1 and cur!=1:
dp_1[cur] = 1
size[cur] = 1
dp_2[cur] = [1, 1]
else:
size[cur] = 1
max_val = 0
length = 0
for x in g[cur]:
if x == p[cur]:continue
size[cur] += size[x]
dp_1[cur] = size[cur]
for x in g[cur]:
if x == p[cur]:continue
dp_1[cur] += dp_1[x]
for x in g[cur]:
if x == p[cur]:continue
new_val = dp_2[x][0] + dp_2[x][1] * (size[cur]-size[x]) + (dp_1[cur]-dp_1[x]-size[x])
if new_val > max_val:
max_val, length = new_val, dp_2[x][1] + 1
dp_2[cur] = [max_val, length]
return root
root = dfs(p, dp_1, dp_2, size)
print(dp_2[root][0])
#7
#7 6
#7 5
#7 2
#7 1
#5 4
#5 3
```
No
| 101,285 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠j) are connected if and only if, a_i AND a_j≠0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).
Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all.
Input
The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}).
Output
If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle.
Examples
Input
4
3 6 28 9
Output
4
Input
5
5 12 9 16 48
Output
3
Input
4
1 2 4 8
Output
-1
Note
In the first example, the shortest cycle is (9, 3, 6, 28).
In the second example, the shortest cycle is (5, 12, 9).
The graph has no cycles in the third example.
Tags: bitmasks, brute force, graphs, shortest paths
Correct Solution:
```
#!/usr/bin/python3
import math
import sys
DEBUG = False
def inp():
return sys.stdin.readline().rstrip()
def dprint(*value, sep=' ', end='\n'):
if DEBUG:
print(*value, sep=sep, end=end)
INF = 70
def solve(N, A):
B = [set() for _ in range(63)]
for i, a in enumerate(A):
if a == 0:
continue
m = 1
for j in range(63):
if a & m:
B[j].add((a, i))
if len(B[j]) == 3:
return 3
m <<= 1
G = {}
for b in B:
if len(b) <= 1:
continue
(p, _), (q, _) = list(b)
if p == q:
continue
if p not in G:
G[p] = set()
if q not in G:
G[q] = set()
G[p].add(q)
G[q].add(p)
dprint(G)
best = INF
for start in G:
nodes = set([start])
level = 1
visited = set()
while nodes and level * 2 <= best:
nnodes = set()
for i in nodes:
for j in G[i]:
if j in nodes:
best = level * 2 - 1
break
if j in nnodes:
best = min(best, level * 2)
elif j not in visited:
nnodes.add(j)
if best == level * 2 - 1:
break
visited |= nodes
nodes = nnodes
level += 1
if best == INF:
return -1
return best
def main():
N = int(inp())
A = [int(e) for e in inp().split()]
print(solve(N, A))
if __name__ == '__main__':
main()
```
| 101,286 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠j) are connected if and only if, a_i AND a_j≠0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).
Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all.
Input
The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}).
Output
If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle.
Examples
Input
4
3 6 28 9
Output
4
Input
5
5 12 9 16 48
Output
3
Input
4
1 2 4 8
Output
-1
Note
In the first example, the shortest cycle is (9, 3, 6, 28).
In the second example, the shortest cycle is (5, 12, 9).
The graph has no cycles in the third example.
Tags: bitmasks, brute force, graphs, shortest paths
Correct Solution:
```
import math
edges = []
result = -1
def dfs(ns, path, visited, last, now):
visited[now] = True
global edges
for i in edges[now]:
if i == last:
continue
if i in path:
new_result = len(path) - path.index(i)
global result
if result < 0 or result > new_result:
result = new_result
continue
dfs(ns, path + [i], visited, now, i)
def solve():
n = int(input())
ns = [int(x) for x in input().split()]
global edges
edges = []
for i in range(n):
edges.append(list())
p = 1
for i in range(70):
s = []
for t in range(n):
if ns[t] & p != 0:
s.append(t)
if len(s) >= 3:
return 3
if len(s) == 2:
edges[s[0]].append(s[1])
edges[s[1]].append(s[0])
p <<= 1
# print(edges)
global result
result = -1
visited = [False] * n
for start in range(n):
if not visited[start]:
dfs(ns, [start], visited, -1, start)
return result
def main():
print(solve())
if __name__ == '__main__':
main()
```
| 101,287 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠j) are connected if and only if, a_i AND a_j≠0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).
Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all.
Input
The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}).
Output
If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle.
Examples
Input
4
3 6 28 9
Output
4
Input
5
5 12 9 16 48
Output
3
Input
4
1 2 4 8
Output
-1
Note
In the first example, the shortest cycle is (9, 3, 6, 28).
In the second example, the shortest cycle is (5, 12, 9).
The graph has no cycles in the third example.
Tags: bitmasks, brute force, graphs, shortest paths
Correct Solution:
```
# Using BFS
from collections import defaultdict
import queue
class Graph:
def __init__(self, length):
self.length = length
self.graph = defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
def bfs(self, s, max_len):
D = [self.length + 1] * self.length
visited = [False] * self.length
P = [None] * self.length
stack = queue.Queue()
stack.put(s)
visited[s] = True
D[s] = 0
while not stack.empty():
v = stack.get()
# print(v, end = " ")
if D[v] >= max_len:
break
for w in self.graph[v]:
if visited[w] == False:
visited[w] = True
stack.put(w)
D[w] = D[v] + 1
P[w] = v
elif P[v] != w:
# P[w] = v
# print(w)
# print(P)
# return True, find_cycle_length(w, P)
return True, D[v] + D[w] + 1
# print("")
return False, self.length + 1
n = int(input())
nums = list(map(int, input().split(' ')))
a = []
for i in range(n):
if nums[i] != 0:
a.append(nums[i])
n = len(a)
if n < 3:
print(-1)
elif n > 120:
print(3)
else:
G = Graph(n)
for i in range(n-1):
for j in range(i+1, n):
if a[i] & a[j] != 0:
G.addEdge(i, j)
G.addEdge(j, i)
# print(G.graph)
min_len = n + 1
for i in range(n):
has_cycle, length = G.bfs(i, min_len)
if has_cycle and length < min_len:
min_len = length
if min_len == (n + 1):
print(-1)
else:
print(min_len)
```
| 101,288 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠j) are connected if and only if, a_i AND a_j≠0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).
Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all.
Input
The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}).
Output
If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle.
Examples
Input
4
3 6 28 9
Output
4
Input
5
5 12 9 16 48
Output
3
Input
4
1 2 4 8
Output
-1
Note
In the first example, the shortest cycle is (9, 3, 6, 28).
In the second example, the shortest cycle is (5, 12, 9).
The graph has no cycles in the third example.
Tags: bitmasks, brute force, graphs, shortest paths
Correct Solution:
```
import sys
input = sys.stdin.readline
N = int(input())
A = list(map(int, input().split()))
L = max(A).bit_length()
ans = -1
graph = [[] for _ in range(N)]
V = []
for l in range(L):
P = []
for i in range(N):
if (1 << l) & A[i]:
P.append(i)
if len(P) > 2:
ans = 3
break
elif len(P) == 2:
p0, p1 = P
graph[p0].append(p1)
graph[p1].append(p0)
V.append(P)
def bfs(s, g):
a = -1
q = [s]
checked = [False]*N
checked[s] = True
d = 0
while q:
qq = []
d += 1
for p in q:
for np in graph[p]:
if np == g:
if d == 1: continue
else: return d
if not checked[np]:
qq.append(np)
checked[np] = True
q = qq
return -1
if ans == 3:
print(3)
else:
ans = 10**9
for s, g in V:
cycle = bfs(s, g)
if cycle == -1:
continue
ans = min(cycle+1, ans)
if ans == 10**9:
print(-1)
else:
print(ans)
```
| 101,289 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠j) are connected if and only if, a_i AND a_j≠0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).
Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all.
Input
The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}).
Output
If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle.
Examples
Input
4
3 6 28 9
Output
4
Input
5
5 12 9 16 48
Output
3
Input
4
1 2 4 8
Output
-1
Note
In the first example, the shortest cycle is (9, 3, 6, 28).
In the second example, the shortest cycle is (5, 12, 9).
The graph has no cycles in the third example.
Tags: bitmasks, brute force, graphs, shortest paths
Correct Solution:
```
from collections import *
import sys
# "". join(strings)
def ri():
return int(input())
def rl():
return list(map(int, input().split()))
n = ri()
aa = rl()
zero_cnt = 0
aa = [value for value in aa if value != 0]
n = len(aa)
edges = set()
graph = defaultdict(list)
bit_shared = defaultdict(list)
#2^60 > 10^18 >= aa[i]. So we have 60 bits to check, between 0 and 59.
#Also note that for a given bit, if 3 numbers share it, then the answer is 3
for k in range(60):
for i in range(n):
if (1 << k) & aa[i]:
bit_shared[k].append(i)
if len(bit_shared[k]) >= 3:
print(3)
sys.exit()
# print("bit: ", bit_shared)
#we build the graph
for i in range(n):
for j in range(i + 1, n):
if aa[i] & aa[j]:
if (i,j) not in edges:
graph[i].append(j)
graph[j].append(i)
edges.add((i,j)) # we need a set, because sometimes many edges between same 2 vertices, but they dont count as cycle according to:
#ANNOUCEMENT : Note that the graph does not contain parallel edges. Therefore, one edge can not be a cycle. A cycle should contain at least three distinct vertices.
# print("graph: ",graph)
# print("edges: ",edges)
#if we havent exited yet, it means for all bit 2^k, it is shared at most between two elements of aa.
#We have to find the shortest length cycle of this graph.
#I think we can chose to iterate over edges (there are less than 60 of them)
#Or we can iterate over vertices (there are less of 60*3 + 1 = 183 of them because of pigeonhole principle)
#let's iterate of vertices v and use BFS to find the shortest cycle containing v
ans = 10**5
# For all vertices
for i in range(n):
# Make distance maximum
dist = [int(1e5)] * n
# Take a imaginary parent
par = [-1] * n
# Distance of source to source is 0
dist[i] = 0
q = deque()
# Push the source element
q.append(i)
# Continue until queue is not empty
while q:
# Take the first element
x = q[0]
q.popleft()
# Traverse for all it's childs
for child in graph[x]:
# If it is not visited yet
if dist[child] == int(1e5):
# Increase distance by 1
dist[child] = 1 + dist[x]
# Change parent
par[child] = x
# Push into the queue
q.append(child)
# If it is already visited
elif par[x] != child and par[child] != x:
ans = min(ans, dist[x] +
dist[child] + 1)
if ans == 10**5:
print(-1)
else:
print(ans)
```
| 101,290 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠j) are connected if and only if, a_i AND a_j≠0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).
Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all.
Input
The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}).
Output
If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle.
Examples
Input
4
3 6 28 9
Output
4
Input
5
5 12 9 16 48
Output
3
Input
4
1 2 4 8
Output
-1
Note
In the first example, the shortest cycle is (9, 3, 6, 28).
In the second example, the shortest cycle is (5, 12, 9).
The graph has no cycles in the third example.
Tags: bitmasks, brute force, graphs, shortest paths
Correct Solution:
```
def bfs(g, src, dest):
visited = {}
dist = {}
for i in g:
visited[i] = False
dist[i] = 1e18
dist[src] = 0
visited[src] = True
q = []
q.append(src)
while q:
src = q.pop(0)
for i in g[src]:
if visited[i] == False:
visited[i] = True
dist[i] = min(dist[i], dist[src] + 1)
q.append(i)
return dist[dest]
#print(timeit.timeit("c += 1", "c = 0", number = 100000000)
#from random import *
#[randint(1, int(1e18)) for i in range(100000)]
n = int(input())
a = list(map(int, input().split()))
c = 0 #this overlooks parallel edges
a = sorted(a)
while n != 0 and a[0] == 0:
a.pop(0)
n -= 1
for i in range(64):
c = 0
for j in range(n):
if ((a[j] >> i) & 1):
c += 1
if c == 3:
break
if c == 3:
break
if c == 3:#[565299879350784, 4508014854799360, 0, 0, 0, 4503635094929409, 18014810826352646, 306526525186934784, 0, 0]:
print(3)
else:
g = {}
#create adjacency list
for i in range(64):
buff = [-1, -1]
for j in range(n):
if (a[j] >> i) & 1:
if buff[0] == -1:
buff[0] = j
elif buff[1] == -1:
buff[1] = j
if buff[0] not in g:
g[buff[0]] = []
g[buff[0]].append(buff[1])
if buff[1] not in g:
g[buff[1]] = []
g[buff[1]].append(buff[0]) #this completes our graph
tg = {}
dist = []
for i in g:
for j in g[i]:
tg = g
tg[i].remove(j)
tg[j].remove(i)
dist.append( bfs(tg, i, j) )
while len(dist) != 0 and min(dist) < 2:
dist.remove(min(dist))
if len(dist) != 0 and min(dist) < 1e18:
print(min(dist) + 1)
else:
print(-1)
```
| 101,291 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠j) are connected if and only if, a_i AND a_j≠0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).
Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all.
Input
The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}).
Output
If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle.
Examples
Input
4
3 6 28 9
Output
4
Input
5
5 12 9 16 48
Output
3
Input
4
1 2 4 8
Output
-1
Note
In the first example, the shortest cycle is (9, 3, 6, 28).
In the second example, the shortest cycle is (5, 12, 9).
The graph has no cycles in the third example.
Tags: bitmasks, brute force, graphs, shortest paths
Correct Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from sys import maxsize as INT_MAX
from collections import defaultdict,deque
def shortest_cycle(n: int) -> int:
ans = INT_MAX
for i in range(n):
dist=defaultdict(lambda: -1);par=defaultdict(lambda: -1);dist[i]=0
q = deque([]) ;q.append(i)
while q:
x=q[0];q.popleft()
for child in graph[x]:
if dist[child] == -1:
dist[child]=1+dist[x];par[child]=x;q.append(child)
elif par[x]!= child and par[child]!= x:
ans=min(ans,dist[x]+dist[child] + 1)
if ans==INT_MAX:
return -1
else:
return ans
n=int(input());vals=list(map(int,input().split()));zer=0
for s in range(n):
if vals[s]==0:
zer+=1
if n-zer>=121:
print(3)
else:
bit=[[] for s in range(60)];info=defaultdict(list)
for s in range(n):
num=vals[s]
for i in range(59,-1,-1):
if num-2**i>=0:
bit[i].append(s);num-=2**i;info[vals[s]].append(i)
graph=[[] for s in range(n)];tracker=[set([]) for s in range(n)]
for s in range(n):
for i in info[vals[s]]:
for b in range(len(bit[i])):
if bit[i][b]!=s and not(bit[i][b] in tracker[s]):
graph[s].append(bit[i][b]);tracker[s].add(bit[i][b])
print(shortest_cycle(n))
```
| 101,292 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠j) are connected if and only if, a_i AND a_j≠0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).
Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all.
Input
The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}).
Output
If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle.
Examples
Input
4
3 6 28 9
Output
4
Input
5
5 12 9 16 48
Output
3
Input
4
1 2 4 8
Output
-1
Note
In the first example, the shortest cycle is (9, 3, 6, 28).
In the second example, the shortest cycle is (5, 12, 9).
The graph has no cycles in the third example.
Tags: bitmasks, brute force, graphs, shortest paths
Correct Solution:
```
from collections import *
import sys
def ri():
return int(input())
def rl():
return list(map(int, input().split()))
n = ri()
aa = rl()
zero_cnt = 0
aa = [value for value in aa if value != 0]
n = len(aa)
edges = set()
graph = defaultdict(list)
bit_shared = defaultdict(list)
#2^60 > 10^18 >= aa[i]. So we have 60 bits to check, between 0 and 59.
#Also note that for a given bit, if 3 numbers share it, then the answer is 3
for k in range(60):
for i in range(n):
if (1 << k) & aa[i]:
bit_shared[k].append(i)
if len(bit_shared[k]) >= 3:
print(3)
sys.exit()
# print("bit: ", bit_shared)
#we build the graph
for i in range(n):
for j in range(i + 1, n):
if aa[i] & aa[j]:
if (i,j) not in edges:
graph[i].append(j)
graph[j].append(i)
edges.add((i,j)) # we use a set, because sometimes many edges between same 2 vertices, but they dont count as cycle according to:
#ANNOUCEMENT : Note that the graph does not contain parallel edges. Therefore, one edge can not be a cycle. A cycle should contain at least three distinct vertices.
# print("graph: ",graph)
# print("edges: ",edges)
#if we havent exited yet, it means for all bit 2^k, it is shared at most between two elements of aa.
#We have to find the shortest length cycle of this graph.
#I think we can chose to iterate over edges (there are less than 60 of them)
#Or we can iterate over vertices (there are less of 60*3 + 1 = 183 of them because of pigeonhole principle)
#let's iterate of vertices v and use Dijikstra to find the shortest cycle containing v
###########################################################################################################
####Approach: For every vertex, we check if it is possible to get the shortest cycle involving this vertex.
#### For every vertex first, push current vertex into the queue and then it’s neighbours
#### and if vertex which is already visited comes again then the cycle is present.
###########################################################################################################
ans = 10**5
# For all vertices
for i in range(n):
# dist stores the distance to i. Make distance maximum
dist = [int(1e5)] * n
# except distance from i to i is 0
dist[i] = 0
# Take a imaginary parent
par = [-1] * n
#make a queue with just the source element
q = deque([i])
# Continue until queue is not empty
while q:
# Take the first element
x = q.popleft()
# Traverse for all it's children
for child in graph[x]:
# If it is not visited yet
if dist[child] == int(1e5):
# Increase distance by 1
dist[child] = 1 + dist[x]
# Change parent
par[child] = x
# Push into the queue
q.append(child)
# If it is already visited
elif par[x] != child and par[child] != x:
ans = min(ans, dist[x] +
dist[child] + 1)
if ans == 10**5:
print(-1)
else:
print(ans)
```
| 101,293 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠j) are connected if and only if, a_i AND a_j≠0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).
Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all.
Input
The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}).
Output
If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle.
Examples
Input
4
3 6 28 9
Output
4
Input
5
5 12 9 16 48
Output
3
Input
4
1 2 4 8
Output
-1
Note
In the first example, the shortest cycle is (9, 3, 6, 28).
In the second example, the shortest cycle is (5, 12, 9).
The graph has no cycles in the third example.
Submitted Solution:
```
import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
from heapq import heappop,heappush,heapify
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
n = inp()
a = inpl()
b = []
for x in a:
if x != 0: b.append(x)
n = len(b)
if n > 120: print(3); quit()
if n == 0: print(-1); quit()
g = [[] for _ in range(n)]
for i in range(n):
for j in range(i+1,n):
for k in range(65):
if (b[i]>>k)%2 and (b[j]>>k)%2:
g[i].append(j)
g[j].append(i)
break
res = INF
for i in range(n):
dist = [INF]*n; dist[i] = 0
fro = [-1]*n
q = deque(); q.append(i)
while q:
nv = q.popleft()
for v in g[nv]:
if fro[nv] == v: continue
if dist[v] != INF:
if fro[v] == fro[nv]: res = 3
else: res = min(res, dist[nv]+dist[v]+1)
else:
fro[v] = nv
dist[v] = dist[nv] + 1
q.append(v)
print(res if res != INF else -1)
```
Yes
| 101,294 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠j) are connected if and only if, a_i AND a_j≠0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).
Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all.
Input
The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}).
Output
If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle.
Examples
Input
4
3 6 28 9
Output
4
Input
5
5 12 9 16 48
Output
3
Input
4
1 2 4 8
Output
-1
Note
In the first example, the shortest cycle is (9, 3, 6, 28).
In the second example, the shortest cycle is (5, 12, 9).
The graph has no cycles in the third example.
Submitted Solution:
```
from collections import defaultdict
def extract_min(D, X):
arg_min = -1
min_val = float('inf')
for i in X:
if D[i] < min_val:
arg_min = i
min_val = D[i]
return arg_min
class Graph:
def __init__(self, length):
self.length = length
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
def Dijkstra(self, s):
X = set(range(self.length))
D = [self.length + 1] * self.length
P = [None] * self.length
D[s] = 0
while X:
u = extract_min(D, X)
X.remove(u)
for v in self.graph[u]:
if v in X:
new_dist = D[u] + 1
if D[v] > new_dist:
D[v] = new_dist
P[v] = u
elif P[u] != v:
return True, D[u] + D[v] + 1
return False, self.length
n = int(input())
nums = list(map(int, input().split(' ')))
a = []
for i in range(n):
if nums[i] != 0:
a.append(nums[i])
n = len(a)
if n < 3:
print(-1)
elif n > 120:
print(3)
else:
G = Graph(n)
for i in range(n-1):
for j in range(i+1, n):
if a[i] & a[j] != 0:
G.addEdge(i, j)
G.addEdge(j, i)
# print(G.graph)
min_len = n + 1
for i in range(n):
has_cycle, length = G.Dijkstra(i)
if has_cycle and length < min_len:
min_len = length
if min_len == (n + 1):
print(-1)
else:
print(min_len)
```
Yes
| 101,295 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠j) are connected if and only if, a_i AND a_j≠0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).
Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all.
Input
The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}).
Output
If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle.
Examples
Input
4
3 6 28 9
Output
4
Input
5
5 12 9 16 48
Output
3
Input
4
1 2 4 8
Output
-1
Note
In the first example, the shortest cycle is (9, 3, 6, 28).
In the second example, the shortest cycle is (5, 12, 9).
The graph has no cycles in the third example.
Submitted Solution:
```
"""This code was written by
Russell Emerine - linguist,
mathematician, coder,
musician, and metalhead."""
n = int(input())
a = []
for x in input().split():
x = int(x)
if x: a.append(x)
n = len(a)
edges = set()
for d in range(64):
p = 1 << d
c = []
for i in range(n):
x = a[i]
if x & p:
c.append(i)
if len(c) > 2:
import sys
print(3)
sys.exit()
if len(c) == 2:
edges.add((c[0], c[1]))
m = n + 1
adj = [[][:] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
from collections import deque
for r in range(n):
v = [False] * n
p = [-1] * n
d = [n + 1] * n
d[r] = 0
s = deque([r])
while len(s):
h = s.popleft()
v[h] = True
for c in adj[h]:
if p[h] == c:
continue
elif v[c]:
m = min(d[h] + 1 + d[c], m)
else:
d[c] = d[h] + 1
v[c] = True
p[c] = h
s.append(c);
if m == n + 1: m = -1
print(m)
```
Yes
| 101,296 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠j) are connected if and only if, a_i AND a_j≠0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).
Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all.
Input
The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}).
Output
If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle.
Examples
Input
4
3 6 28 9
Output
4
Input
5
5 12 9 16 48
Output
3
Input
4
1 2 4 8
Output
-1
Note
In the first example, the shortest cycle is (9, 3, 6, 28).
In the second example, the shortest cycle is (5, 12, 9).
The graph has no cycles in the third example.
Submitted Solution:
```
import sys, os, re, datetime, copy
from collections import *
from bisect import *
def mat(v, *dims):
def dim(i): return [copy.copy(v) for _ in range(dims[-1])] if i == len(dims)-1 else [dim(i+1) for _ in range(dims[i])]
return dim(0)
__cin__ = None
def cin():
global __cin__
if __cin__ is None: __cin__ = iter(input().split(" "))
try: return next(__cin__)
except StopIteration:
__cin__ = iter(input().split(" "))
return next(__cin__)
def iarr(n): return [int(cin()) for _ in range(n)]
def farr(n): return [float(cin()) for _ in range(n)]
def sarr(n): return [cin() for _ in range(n)]
def carr(n): return input()
def imat(n, m): return [iarr(m) for _ in range(n)]
def fmat(n, m): return [farr(m) for _ in range(n)]
def smat(n, m): return [sarr(m) for _ in range(n)]
def cmat(n, m): return [input() for _ in range(n)]
def bfs(i):
dist = mat(INF, n)
q = deque()
q.append(i)
dist[i] = 0
while len(q) > 0:
u = q.popleft()
for v in adj[u]:
if dist[v] == INF:
q.append(v)
dist[v] = dist[u]+1
elif dist[v]+1 != dist[u]:
return dist[v]+dist[u]+1
return INF
N = 64
n = int(cin())
tmp = iarr(n)
t = mat(0, N)
g = mat([], N)
adj = mat(set(), n)
INF = 100000
ans = INF
a = list(filter(lambda x: x > 0, tmp))
n = len(a)
for j in range(N):
for i in range(n):
v = a[i]
t[j] += (v>>j)&1
if t[j] >= 3:
print("3")
exit(0)
if ((v>>j)&1) == 1:
g[j].append(i)
for i in range(N):
if len(g[i]) == 2:
adj[g[i][0]].add(g[i][1])
adj[g[i][1]].add(g[i][0])
for i in range(n):
ans = min(ans, bfs(i))
print(-1 if ans == INF else ans)
mmap = {0: "Hola", 1: "Mundo"}
```
Yes
| 101,297 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠j) are connected if and only if, a_i AND a_j≠0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).
Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all.
Input
The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}).
Output
If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle.
Examples
Input
4
3 6 28 9
Output
4
Input
5
5 12 9 16 48
Output
3
Input
4
1 2 4 8
Output
-1
Note
In the first example, the shortest cycle is (9, 3, 6, 28).
In the second example, the shortest cycle is (5, 12, 9).
The graph has no cycles in the third example.
Submitted Solution:
```
import sys
n = int(input())
data = [int(i) for i in input().split()]
inf = 1 << 10
if n > 100:
print(3)
sys.exit()
def bfs(a):
layer = {a}
parent = {a: -1}
cnt = 0
while len(layer) > 0:
# print(a, layer)
cnt += 1
new = set()
for l in layer:
for v in data:
if l & v and v != l and parent[l] != v:
if v in layer:
return 2 * cnt - 1
elif v in new:
return 2 * cnt
parent[v] = l
new.add(v)
# if v == a:
# print(l, v)
# print(parent)
# return cnt
# 5
# 5 12 9 16 48
layer = new
return inf
ans = inf
for d in data:
a2 = bfs(d)
if a2 == inf:
continue
elif a2 == 3:
print(3)
sys.exit()
elif a2 < ans:
ans = a2
if ans == inf:
print(-1)
else:
print(ans)
```
No
| 101,298 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠j) are connected if and only if, a_i AND a_j≠0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).
Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all.
Input
The first line contains one integer n (1 ≤ n ≤ 10^5) — number of numbers.
The second line contains n integer numbers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^{18}).
Output
If the graph doesn't have any cycles, output -1. Else output the length of the shortest cycle.
Examples
Input
4
3 6 28 9
Output
4
Input
5
5 12 9 16 48
Output
3
Input
4
1 2 4 8
Output
-1
Note
In the first example, the shortest cycle is (9, 3, 6, 28).
In the second example, the shortest cycle is (5, 12, 9).
The graph has no cycles in the third example.
Submitted Solution:
```
def bfs(g, src, dest):
visited = {}
dist = {}
for i in g:
visited[i] = False
dist[i] = 1e18
dist[src] = 0
visited[src] = True
q = []
q.append(src)
while q:
src = q.pop(0)
for i in g[src]:
if visited[i] == False:
visited[i] = True
dist[i] = min(dist[i], dist[src] + 1)
q.append(i)
return dist[dest]
#print(timeit.timeit("c += 1", "c = 0", number = 100000000)
n = int(input())
a = list(map(int, input().split()))
c = 0
for i in range(64):
c = 0
for j in range(n):
if ((a[j] >> i) & 1):
c += 1
if c == 3:
break
if c == 3:
break
if c == 3 or a == [565299879350784, 4508014854799360, 0, 0, 0, 4503635094929409, 18014810826352646, 306526525186934784, 0, 0]:
print(3)
else:
g = {}
#create adjacency list
for i in range(64):
buff = [-1, -1]
for j in range(n):
if (a[j] >> i) & 1:
if buff[0] == -1:
buff[0] = j
elif buff[1] == -1:
buff[1] = j
if buff[0] not in g:
g[buff[0]] = []
g[buff[0]].append(buff[1])
if buff[1] not in g:
g[buff[1]] = []
g[buff[1]].append(buff[0]) #this completes our graph
tg = {}
dist = []
for i in g:
for j in g[i]:
tg = g
tg[i].remove(j)
tg[j].remove(i)
dist.append( bfs(tg, i, j) )
if len(dist) != 0 and min(dist) < 1e18:
print(min(dist) + 1)
else:
print(-1)
```
No
| 101,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.