text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company.
Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!
Input
The first line of the input contains two space-separated integers, n and d (1 ≤ n ≤ 105, <image>) — the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively.
Next n lines contain the descriptions of Kefa's friends, the (i + 1)-th line contains the description of the i-th friend of type mi, si (0 ≤ mi, si ≤ 109) — the amount of money and the friendship factor, respectively.
Output
Print the maximum total friendship factir that can be reached.
Examples
Input
4 5
75 5
0 100
150 20
75 1
Output
100
Input
5 100
0 7
11 32
99 10
46 8
87 54
Output
111
Note
In the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse.
In the second sample test we can take all the friends.
Tags: binary search, sortings, two pointers
Correct Solution:
```
def find_company(friends, d):
def mergesort_tuples(tuples, index):
def merge(A, B):
i, j = 0, 0
result = []
while i < len(A) and j < len(B):
if A[i][index] < B[j][index]:
result.append(A[i])
i += 1
else:
result.append(B[j])
j += 1
result += A[i:]
result += B[j:]
return result
def divide(tuples):
if len(tuples) > 1:
middle = len(tuples) // 2
return merge(divide(tuples[:middle]), divide(tuples[middle:]))
return tuples
return divide(tuples)
def solve(friends, d):
friends = mergesort_tuples(friends, 0)
left_ptr = 0
right_ptr = 0
current_friendship = 0
max_friendship = 0
while right_ptr < len(friends):
if friends[right_ptr][0] - friends[left_ptr][0] < d:
current_friendship += friends[right_ptr][1]
right_ptr += 1
else:
max_friendship = max(current_friendship, max_friendship)
current_friendship -= friends[left_ptr][1]
left_ptr += 1
max_friendship = max(current_friendship, max_friendship)
return max_friendship
return solve(friends, d)
if __name__ == "__main__":
n, d = [int(x) for x in input().split()]
friends = []
for _ in range(n):
friends.append(tuple([int(x) for x in input().split()]))
print(find_company(friends, d))
```
| 7,100 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company.
Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!
Input
The first line of the input contains two space-separated integers, n and d (1 ≤ n ≤ 105, <image>) — the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively.
Next n lines contain the descriptions of Kefa's friends, the (i + 1)-th line contains the description of the i-th friend of type mi, si (0 ≤ mi, si ≤ 109) — the amount of money and the friendship factor, respectively.
Output
Print the maximum total friendship factir that can be reached.
Examples
Input
4 5
75 5
0 100
150 20
75 1
Output
100
Input
5 100
0 7
11 32
99 10
46 8
87 54
Output
111
Note
In the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse.
In the second sample test we can take all the friends.
Tags: binary search, sortings, two pointers
Correct Solution:
```
z,zz=input,lambda:list(map(int,z().split()))
zzz=lambda:[int(i) for i in stdin.readline().split()]
szz,graph,mod,szzz=lambda:sorted(zz()),{},10**9+7,lambda:sorted(zzz())
from string import *
from re import *
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f
from bisect import bisect as bs
from bisect import bisect_left as bsl
from itertools import accumulate as ac
def lcd(xnum1,xnum2):return (xnum1*xnum2//gcd(xnum1,xnum2))
def prime(x):
p=ceil(x**.5)+1
for i in range(2,p):
if (x%i==0 and x!=2) or x==0:return 0
return 1
def dfs(u,visit,graph):
visit[u]=True
for i in graph[u]:
if not visit[i]:
dfs(i,visit,graph)
###########################---Test-Case---#################################
"""
"""
###########################---START-CODING---##############################
n,m=zz()
lst=[]
for _ in range(n):
lst.append(zz())
lst=sorted(lst)
ans=0
l=0
s=0
for r in range(n):
while lst[r][0]-lst[l][0]>=m:
s-=lst[l][1]
l+=1
s+=lst[r][1]
ans=max(ans,s)
print(ans)
```
| 7,101 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company.
Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!
Input
The first line of the input contains two space-separated integers, n and d (1 ≤ n ≤ 105, <image>) — the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively.
Next n lines contain the descriptions of Kefa's friends, the (i + 1)-th line contains the description of the i-th friend of type mi, si (0 ≤ mi, si ≤ 109) — the amount of money and the friendship factor, respectively.
Output
Print the maximum total friendship factir that can be reached.
Examples
Input
4 5
75 5
0 100
150 20
75 1
Output
100
Input
5 100
0 7
11 32
99 10
46 8
87 54
Output
111
Note
In the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse.
In the second sample test we can take all the friends.
Tags: binary search, sortings, two pointers
Correct Solution:
```
from bisect import *
n,d = map(int,input().split())
tp = list()
for i in range(n):
m,s = map(int,input().split())
tp.append((m,s))
tp.sort(key = lambda x : x[0])
m = list()
s = list()
for i in range(n):
m.append(tp[i][0])
s.append(tp[i][1])
ps = list()
sn = 0
for i in range(n):
sn += s[i]
ps.append(sn)
mx = -1000
for i in range(n):
ind = bisect_left(m,m[i]+d)
if(i!=0):
mx = max(mx,ps[ind-1]-ps[i-1])
else:
mx = max(mx,ps[ind-1])
print(mx)
```
| 7,102 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company.
Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!
Input
The first line of the input contains two space-separated integers, n and d (1 ≤ n ≤ 105, <image>) — the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively.
Next n lines contain the descriptions of Kefa's friends, the (i + 1)-th line contains the description of the i-th friend of type mi, si (0 ≤ mi, si ≤ 109) — the amount of money and the friendship factor, respectively.
Output
Print the maximum total friendship factir that can be reached.
Examples
Input
4 5
75 5
0 100
150 20
75 1
Output
100
Input
5 100
0 7
11 32
99 10
46 8
87 54
Output
111
Note
In the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse.
In the second sample test we can take all the friends.
Submitted Solution:
```
n,d = map(int,input().split())
l = []
for i in range(n):
a,b = map(int,input().split())
l.append([a,b])
l.sort()
ans = l[0][1]
c = l[0][1]
i = 0
j = 1
while j<n:
if l[j][0]-l[i][0]<d:
c+=l[j][1]
j+=1
else:
c-=l[i][1]
i+=1
ans = max(ans,c)
print(ans)
```
Yes
| 7,103 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company.
Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!
Input
The first line of the input contains two space-separated integers, n and d (1 ≤ n ≤ 105, <image>) — the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively.
Next n lines contain the descriptions of Kefa's friends, the (i + 1)-th line contains the description of the i-th friend of type mi, si (0 ≤ mi, si ≤ 109) — the amount of money and the friendship factor, respectively.
Output
Print the maximum total friendship factir that can be reached.
Examples
Input
4 5
75 5
0 100
150 20
75 1
Output
100
Input
5 100
0 7
11 32
99 10
46 8
87 54
Output
111
Note
In the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse.
In the second sample test we can take all the friends.
Submitted Solution:
```
n,d=map(int,input().split())
l=[]
for i in range(n):
x,y=map(int,input().split())
l.append([x,y])
l.sort()
ans=0
a=[]
i=0
j=0
while i<n:
if l[i][0]-l[j][0]>=d:
a.append(ans)
ans-=l[j][1]
j+=1
else:
ans+=l[i][1]
a.append(ans)
i+=1
print(max(a))
```
Yes
| 7,104 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company.
Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!
Input
The first line of the input contains two space-separated integers, n and d (1 ≤ n ≤ 105, <image>) — the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively.
Next n lines contain the descriptions of Kefa's friends, the (i + 1)-th line contains the description of the i-th friend of type mi, si (0 ≤ mi, si ≤ 109) — the amount of money and the friendship factor, respectively.
Output
Print the maximum total friendship factir that can be reached.
Examples
Input
4 5
75 5
0 100
150 20
75 1
Output
100
Input
5 100
0 7
11 32
99 10
46 8
87 54
Output
111
Note
In the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse.
In the second sample test we can take all the friends.
Submitted Solution:
```
n, d = map(int, input().split())
a = []
for i in range(n):
a.append(list(map(int, input().split())))
a.sort(key=lambda x: x[0])
# print(a)
# очередной кандидат на удаление = 0
# в цикле по всем друзьям
# добавляем очередного ( = запоминаем уровень богатства + добавляем его степень дружбы)
# пока очередной кандидат на удаление слишком беден
# вычитаем его степень дружбы;
# переходим к следующему кандидату на удаление
j = 0
friendship = 0
max_friendship = 0
for i in range(n):
friendship += a[i][1]
while a[j][0] + d <= a[i][0]:
friendship -= a[j][1]
j += 1
max_friendship = max(friendship, max_friendship)
print(max_friendship)
```
Yes
| 7,105 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company.
Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!
Input
The first line of the input contains two space-separated integers, n and d (1 ≤ n ≤ 105, <image>) — the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively.
Next n lines contain the descriptions of Kefa's friends, the (i + 1)-th line contains the description of the i-th friend of type mi, si (0 ≤ mi, si ≤ 109) — the amount of money and the friendship factor, respectively.
Output
Print the maximum total friendship factir that can be reached.
Examples
Input
4 5
75 5
0 100
150 20
75 1
Output
100
Input
5 100
0 7
11 32
99 10
46 8
87 54
Output
111
Note
In the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse.
In the second sample test we can take all the friends.
Submitted Solution:
```
def max_friendship_factor(friends, min_money_diff):
sorted_friends = sorted(friends, key=lambda t: t[0])
n = len(friends)
_, ff_sum = sorted_friends[0] # set first elements ff to ff_sum
max_ff_sum = ff_sum # and max_ff_sum
head_index = 0
hm, hff = sorted_friends[0] # set head money and head ff
for i in range(1, n):
m, ff = sorted_friends[i]
ff_sum += ff
while abs(m - hm) >= min_money_diff:
# push head forwards
ff_sum -= hff
head_index += 1
hm, hff = sorted_friends[head_index]
if max_ff_sum < ff_sum:
max_ff_sum = ff_sum
return max_ff_sum
def run_alg():
first_line_data = input().split(' ')
num_friends = int(first_line_data[0])
min_money_diff = int(first_line_data[1])
friends = []
for _ in range(num_friends):
line_data = input().split(' ')
money = int(line_data[0])
friendship = int(line_data[1])
friends.append((money, friendship))
print(max_friendship_factor(friends, min_money_diff))
if __name__ == '__main__':
run_alg()
```
Yes
| 7,106 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company.
Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!
Input
The first line of the input contains two space-separated integers, n and d (1 ≤ n ≤ 105, <image>) — the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively.
Next n lines contain the descriptions of Kefa's friends, the (i + 1)-th line contains the description of the i-th friend of type mi, si (0 ≤ mi, si ≤ 109) — the amount of money and the friendship factor, respectively.
Output
Print the maximum total friendship factir that can be reached.
Examples
Input
4 5
75 5
0 100
150 20
75 1
Output
100
Input
5 100
0 7
11 32
99 10
46 8
87 54
Output
111
Note
In the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse.
In the second sample test we can take all the friends.
Submitted Solution:
```
# https://vjudge.net/contest/319995#problem/C
n, money = [ int(x) for x in input().split() ]
data = []
for i in range(n):
d = [ int(x) for x in input().split() ]
data.append(d)
data.sort(key=lambda x: x[1], reverse=True)
fact_c = 0
minc = 0
maxc = 0
for i in range(n):
if abs(data[i][0] - data[minc][0]) < money and abs(data[i][0] - data[maxc][0]) < money:
fact_c += data[i][1]
if data[i][0] < data[minc][0]:
minc = i
if data[i][0] > data[maxc][0]:
maxc = i
print(fact_c)
```
No
| 7,107 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company.
Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!
Input
The first line of the input contains two space-separated integers, n and d (1 ≤ n ≤ 105, <image>) — the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively.
Next n lines contain the descriptions of Kefa's friends, the (i + 1)-th line contains the description of the i-th friend of type mi, si (0 ≤ mi, si ≤ 109) — the amount of money and the friendship factor, respectively.
Output
Print the maximum total friendship factir that can be reached.
Examples
Input
4 5
75 5
0 100
150 20
75 1
Output
100
Input
5 100
0 7
11 32
99 10
46 8
87 54
Output
111
Note
In the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse.
In the second sample test we can take all the friends.
Submitted Solution:
```
n,d=map(int,input().split())
l=[]
for i in range(n):
j=tuple(map(int,input().split()))
l.append(j)
k=0
m=0
for i in range(n):
c=l[i][1]
for j in range(n):
if(l[j][0]<l[i][0]+d-1 and l[j][0]+d-1>l[i][0] and i!=j):
c+=l[j][1]
#print(l[j][0]+d,l[i][0])
#print("\n")
if(c>m):
m=c
k=i
print(m)
```
No
| 7,108 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company.
Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!
Input
The first line of the input contains two space-separated integers, n and d (1 ≤ n ≤ 105, <image>) — the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively.
Next n lines contain the descriptions of Kefa's friends, the (i + 1)-th line contains the description of the i-th friend of type mi, si (0 ≤ mi, si ≤ 109) — the amount of money and the friendship factor, respectively.
Output
Print the maximum total friendship factir that can be reached.
Examples
Input
4 5
75 5
0 100
150 20
75 1
Output
100
Input
5 100
0 7
11 32
99 10
46 8
87 54
Output
111
Note
In the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse.
In the second sample test we can take all the friends.
Submitted Solution:
```
n,k = map(int,input().split())
a = [list(map(int,input().split())) for _ in range(n)]
a.sort()
s = 0
ans = 0
r = 0
for l in range(n):
while r<n and a[r][0]-a[l][0]<=k:
s+=a[r][1]
r+=1
ans=max(ans,s)
s-=a[l][1]
print(ans)
```
No
| 7,109 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company.
Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!
Input
The first line of the input contains two space-separated integers, n and d (1 ≤ n ≤ 105, <image>) — the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively.
Next n lines contain the descriptions of Kefa's friends, the (i + 1)-th line contains the description of the i-th friend of type mi, si (0 ≤ mi, si ≤ 109) — the amount of money and the friendship factor, respectively.
Output
Print the maximum total friendship factir that can be reached.
Examples
Input
4 5
75 5
0 100
150 20
75 1
Output
100
Input
5 100
0 7
11 32
99 10
46 8
87 54
Output
111
Note
In the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse.
In the second sample test we can take all the friends.
Submitted Solution:
```
n, d = map(int, input().split())
T = [list(map(int, input().split())) for _ in range(n)]
T.sort(key=lambda x: x[0])
#print(T)
if n == 1:
print(T[0][1])
exit(0)
ans = []
for i in range(len(T) - 1):
temp = T[i][1]
for j in range(i + 1, len(T)):
if T[j][0] - T[i][0] <= d:
temp += T[j][1]
ans.append(temp)
#print(ans)
ans.append(T[-1][1])
print(max(ans))
```
No
| 7,110 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations.
You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers.
Input
The first line of the input contains two space-separated integers n and bx (1 ≤ n ≤ 10, 2 ≤ bx ≤ 40), where n is the number of digits in the bx-based representation of X.
The second line contains n space-separated integers x1, x2, ..., xn (0 ≤ xi < bx) — the digits of X. They are given in the order from the most significant digit to the least significant one.
The following two lines describe Y in the same way: the third line contains two space-separated integers m and by (1 ≤ m ≤ 10, 2 ≤ by ≤ 40, bx ≠ by), where m is the number of digits in the by-based representation of Y, and the fourth line contains m space-separated integers y1, y2, ..., ym (0 ≤ yi < by) — the digits of Y.
There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system.
Output
Output a single character (quotes for clarity):
* '<' if X < Y
* '>' if X > Y
* '=' if X = Y
Examples
Input
6 2
1 0 1 1 1 1
2 10
4 7
Output
=
Input
3 3
1 0 2
2 5
2 4
Output
<
Input
7 16
15 15 4 0 0 7 10
7 9
4 8 0 3 1 5 0
Output
>
Note
In the first sample, X = 1011112 = 4710 = Y.
In the second sample, X = 1023 = 215 and Y = 245 = 1123, thus X < Y.
In the third sample, <image> and Y = 48031509. We may notice that X starts with much larger digits and bx is much larger than by, so X is clearly larger than Y.
Tags: brute force, implementation
Correct Solution:
```
'''input
3 3
1 0 2
2 5
2 4
'''
n, b1 = map(int, input().split())
x = list(map(int, input().split()))[::-1]
m, b2 = map(int, input().split())
y = list(map(int, input().split()))[::-1]
sx, sy = 0, 0
for i in range(n):
sx += b1**(i) * x[i]
for j in range(m):
sy += b2**(j) * y[j]
if sx == sy:
print("=")
else:
print("<" if sx < sy else ">")
```
| 7,111 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations.
You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers.
Input
The first line of the input contains two space-separated integers n and bx (1 ≤ n ≤ 10, 2 ≤ bx ≤ 40), where n is the number of digits in the bx-based representation of X.
The second line contains n space-separated integers x1, x2, ..., xn (0 ≤ xi < bx) — the digits of X. They are given in the order from the most significant digit to the least significant one.
The following two lines describe Y in the same way: the third line contains two space-separated integers m and by (1 ≤ m ≤ 10, 2 ≤ by ≤ 40, bx ≠ by), where m is the number of digits in the by-based representation of Y, and the fourth line contains m space-separated integers y1, y2, ..., ym (0 ≤ yi < by) — the digits of Y.
There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system.
Output
Output a single character (quotes for clarity):
* '<' if X < Y
* '>' if X > Y
* '=' if X = Y
Examples
Input
6 2
1 0 1 1 1 1
2 10
4 7
Output
=
Input
3 3
1 0 2
2 5
2 4
Output
<
Input
7 16
15 15 4 0 0 7 10
7 9
4 8 0 3 1 5 0
Output
>
Note
In the first sample, X = 1011112 = 4710 = Y.
In the second sample, X = 1023 = 215 and Y = 245 = 1123, thus X < Y.
In the third sample, <image> and Y = 48031509. We may notice that X starts with much larger digits and bx is much larger than by, so X is clearly larger than Y.
Tags: brute force, implementation
Correct Solution:
```
n, b = list(map(int, input().split(' ')))
X = list(map(int, input().split(' ')))
Nico = 1
x = 0
for i in range(n):
x = x + X[n - 1 - i] * Nico
Nico = Nico * b
n, b = list(map(int, input().split(' ')))
Y = list(map(int, input().split(' ')))
Nico = 1
y = 0
for i in range(n):
y = y + Y[n - 1 - i] * Nico
Nico = Nico * b
if (x < y):
print("<")
if (x == y):
print("=")
if (x > y):
print(">")
```
| 7,112 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations.
You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers.
Input
The first line of the input contains two space-separated integers n and bx (1 ≤ n ≤ 10, 2 ≤ bx ≤ 40), where n is the number of digits in the bx-based representation of X.
The second line contains n space-separated integers x1, x2, ..., xn (0 ≤ xi < bx) — the digits of X. They are given in the order from the most significant digit to the least significant one.
The following two lines describe Y in the same way: the third line contains two space-separated integers m and by (1 ≤ m ≤ 10, 2 ≤ by ≤ 40, bx ≠ by), where m is the number of digits in the by-based representation of Y, and the fourth line contains m space-separated integers y1, y2, ..., ym (0 ≤ yi < by) — the digits of Y.
There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system.
Output
Output a single character (quotes for clarity):
* '<' if X < Y
* '>' if X > Y
* '=' if X = Y
Examples
Input
6 2
1 0 1 1 1 1
2 10
4 7
Output
=
Input
3 3
1 0 2
2 5
2 4
Output
<
Input
7 16
15 15 4 0 0 7 10
7 9
4 8 0 3 1 5 0
Output
>
Note
In the first sample, X = 1011112 = 4710 = Y.
In the second sample, X = 1023 = 215 and Y = 245 = 1123, thus X < Y.
In the third sample, <image> and Y = 48031509. We may notice that X starts with much larger digits and bx is much larger than by, so X is clearly larger than Y.
Tags: brute force, implementation
Correct Solution:
```
inp = input().split()
n = int(inp[0])
bx = int(inp[1])
X = input().split()
for i in range(n):
X[i] = int(X[i])
X = X[::-1]
inp = input().split()
m = int(inp[0])
by = int(inp[1])
Y = input().split()
for i in range(m):
Y[i] = int(Y[i])
Y = Y[::-1]
sum_X = 0
base = 1
for n in X:
sum_X += base*n
base *= bx
sum_Y = 0
base = 1
for n in Y:
sum_Y += base*n
base *= by
if sum_X == sum_Y:
print('=')
elif sum_X < sum_Y:
print('<')
else:
print('>')
```
| 7,113 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations.
You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers.
Input
The first line of the input contains two space-separated integers n and bx (1 ≤ n ≤ 10, 2 ≤ bx ≤ 40), where n is the number of digits in the bx-based representation of X.
The second line contains n space-separated integers x1, x2, ..., xn (0 ≤ xi < bx) — the digits of X. They are given in the order from the most significant digit to the least significant one.
The following two lines describe Y in the same way: the third line contains two space-separated integers m and by (1 ≤ m ≤ 10, 2 ≤ by ≤ 40, bx ≠ by), where m is the number of digits in the by-based representation of Y, and the fourth line contains m space-separated integers y1, y2, ..., ym (0 ≤ yi < by) — the digits of Y.
There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system.
Output
Output a single character (quotes for clarity):
* '<' if X < Y
* '>' if X > Y
* '=' if X = Y
Examples
Input
6 2
1 0 1 1 1 1
2 10
4 7
Output
=
Input
3 3
1 0 2
2 5
2 4
Output
<
Input
7 16
15 15 4 0 0 7 10
7 9
4 8 0 3 1 5 0
Output
>
Note
In the first sample, X = 1011112 = 4710 = Y.
In the second sample, X = 1023 = 215 and Y = 245 = 1123, thus X < Y.
In the third sample, <image> and Y = 48031509. We may notice that X starts with much larger digits and bx is much larger than by, so X is clearly larger than Y.
Tags: brute force, implementation
Correct Solution:
```
n, b = map(int, input().split())
num1 = 0
num2 = 0
n -= 1
for c in list(map(int, input().split())):
num1 += (b ** n) * c
n -= 1
n, a = map(int, input().split())
n -= 1
for c in list(map(int, input().split())):
num2 += (a ** n) * c
n -= 1
if num1 > num2:
print('>')
elif num1 == num2:
print('=')
else:
print('<')
```
| 7,114 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations.
You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers.
Input
The first line of the input contains two space-separated integers n and bx (1 ≤ n ≤ 10, 2 ≤ bx ≤ 40), where n is the number of digits in the bx-based representation of X.
The second line contains n space-separated integers x1, x2, ..., xn (0 ≤ xi < bx) — the digits of X. They are given in the order from the most significant digit to the least significant one.
The following two lines describe Y in the same way: the third line contains two space-separated integers m and by (1 ≤ m ≤ 10, 2 ≤ by ≤ 40, bx ≠ by), where m is the number of digits in the by-based representation of Y, and the fourth line contains m space-separated integers y1, y2, ..., ym (0 ≤ yi < by) — the digits of Y.
There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system.
Output
Output a single character (quotes for clarity):
* '<' if X < Y
* '>' if X > Y
* '=' if X = Y
Examples
Input
6 2
1 0 1 1 1 1
2 10
4 7
Output
=
Input
3 3
1 0 2
2 5
2 4
Output
<
Input
7 16
15 15 4 0 0 7 10
7 9
4 8 0 3 1 5 0
Output
>
Note
In the first sample, X = 1011112 = 4710 = Y.
In the second sample, X = 1023 = 215 and Y = 245 = 1123, thus X < Y.
In the third sample, <image> and Y = 48031509. We may notice that X starts with much larger digits and bx is much larger than by, so X is clearly larger than Y.
Tags: brute force, implementation
Correct Solution:
```
(n, b) = map(int, input().split())
x = list(map(int, input().split()))
(m, c) = map(int, input().split())
y = list(map(int, input().split()))
x = x[::-1]
y = y[::-1]
X = 0
Y = 0
for i in range(len(x)):
X += x[i] * b ** i
for i in range(len(y)):
Y += y[i] * c ** i
if (X == Y):
print("=")
elif (X < Y):
print("<")
else:
print(">")
```
| 7,115 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations.
You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers.
Input
The first line of the input contains two space-separated integers n and bx (1 ≤ n ≤ 10, 2 ≤ bx ≤ 40), where n is the number of digits in the bx-based representation of X.
The second line contains n space-separated integers x1, x2, ..., xn (0 ≤ xi < bx) — the digits of X. They are given in the order from the most significant digit to the least significant one.
The following two lines describe Y in the same way: the third line contains two space-separated integers m and by (1 ≤ m ≤ 10, 2 ≤ by ≤ 40, bx ≠ by), where m is the number of digits in the by-based representation of Y, and the fourth line contains m space-separated integers y1, y2, ..., ym (0 ≤ yi < by) — the digits of Y.
There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system.
Output
Output a single character (quotes for clarity):
* '<' if X < Y
* '>' if X > Y
* '=' if X = Y
Examples
Input
6 2
1 0 1 1 1 1
2 10
4 7
Output
=
Input
3 3
1 0 2
2 5
2 4
Output
<
Input
7 16
15 15 4 0 0 7 10
7 9
4 8 0 3 1 5 0
Output
>
Note
In the first sample, X = 1011112 = 4710 = Y.
In the second sample, X = 1023 = 215 and Y = 245 = 1123, thus X < Y.
In the third sample, <image> and Y = 48031509. We may notice that X starts with much larger digits and bx is much larger than by, so X is clearly larger than Y.
Tags: brute force, implementation
Correct Solution:
```
# Description of the problem can be found at http://codeforces.com/problemset/problem/602/A
def calc():
n, b = map(int, input().split())
x =list(map(int, input().split()))
a = 0
for i in x:
a = a * b + i
return a
l_n = list()
for _ in range(2):
l_n.append(calc())
if l_n[0] < l_n[1]:
print("<")
elif l_n[1] < l_n[0]:
print(">")
else:
print("=")
```
| 7,116 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations.
You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers.
Input
The first line of the input contains two space-separated integers n and bx (1 ≤ n ≤ 10, 2 ≤ bx ≤ 40), where n is the number of digits in the bx-based representation of X.
The second line contains n space-separated integers x1, x2, ..., xn (0 ≤ xi < bx) — the digits of X. They are given in the order from the most significant digit to the least significant one.
The following two lines describe Y in the same way: the third line contains two space-separated integers m and by (1 ≤ m ≤ 10, 2 ≤ by ≤ 40, bx ≠ by), where m is the number of digits in the by-based representation of Y, and the fourth line contains m space-separated integers y1, y2, ..., ym (0 ≤ yi < by) — the digits of Y.
There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system.
Output
Output a single character (quotes for clarity):
* '<' if X < Y
* '>' if X > Y
* '=' if X = Y
Examples
Input
6 2
1 0 1 1 1 1
2 10
4 7
Output
=
Input
3 3
1 0 2
2 5
2 4
Output
<
Input
7 16
15 15 4 0 0 7 10
7 9
4 8 0 3 1 5 0
Output
>
Note
In the first sample, X = 1011112 = 4710 = Y.
In the second sample, X = 1023 = 215 and Y = 245 = 1123, thus X < Y.
In the third sample, <image> and Y = 48031509. We may notice that X starts with much larger digits and bx is much larger than by, so X is clearly larger than Y.
Tags: brute force, implementation
Correct Solution:
```
from math import *
n,x = map(int,input().split())
a = list(map(int,input().split()))
m,y = map(int,input().split())
b = list(map(int,input().split()))
a.reverse()
b.reverse()
#print(a,b)
res1 = 0
for i in range(len(a)):
res1+=int(a[i])*(x)**i
res2 = 0
for i in range(len(b)):
res2+=int(b[i])*(y)**i
if res1==res2:
print('=')
quit()
if res1<res2:
print('<')
quit()
print('>')
```
| 7,117 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations.
You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers.
Input
The first line of the input contains two space-separated integers n and bx (1 ≤ n ≤ 10, 2 ≤ bx ≤ 40), where n is the number of digits in the bx-based representation of X.
The second line contains n space-separated integers x1, x2, ..., xn (0 ≤ xi < bx) — the digits of X. They are given in the order from the most significant digit to the least significant one.
The following two lines describe Y in the same way: the third line contains two space-separated integers m and by (1 ≤ m ≤ 10, 2 ≤ by ≤ 40, bx ≠ by), where m is the number of digits in the by-based representation of Y, and the fourth line contains m space-separated integers y1, y2, ..., ym (0 ≤ yi < by) — the digits of Y.
There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system.
Output
Output a single character (quotes for clarity):
* '<' if X < Y
* '>' if X > Y
* '=' if X = Y
Examples
Input
6 2
1 0 1 1 1 1
2 10
4 7
Output
=
Input
3 3
1 0 2
2 5
2 4
Output
<
Input
7 16
15 15 4 0 0 7 10
7 9
4 8 0 3 1 5 0
Output
>
Note
In the first sample, X = 1011112 = 4710 = Y.
In the second sample, X = 1023 = 215 and Y = 245 = 1123, thus X < Y.
In the third sample, <image> and Y = 48031509. We may notice that X starts with much larger digits and bx is much larger than by, so X is clearly larger than Y.
Tags: brute force, implementation
Correct Solution:
```
#!/usr/bin/env python3
# 602A_mem.py - Codeforces.com/problemset/problem/602/A by Sergey 2015
import unittest
import sys
###############################################################################
# Mem Class (Main Program)
###############################################################################
class Mem:
""" Mem representation """
def __init__(self, test_inputs=None):
""" Default constructor """
it = iter(test_inputs.split("\n")) if test_inputs else None
def uinput():
return next(it) if it else sys.stdin.readline().rstrip()
# Reading single elements
[self.n, self.bx] = map(int, uinput().split())
# Reading a single line of multiple elements
self.numsx = list(map(int, uinput().split()))
# Reading single elements
[self.m, self.by] = map(int, uinput().split())
# Reading a single line of multiple elements
self.numsy = list(map(int, uinput().split()))
self.x = 0
for n in self.numsx:
self.x = self.x * self.bx + n
self.y = 0
for n in self.numsy:
self.y = self.y * self.by + n
def calculate(self):
""" Main calcualtion function of the class """
if self.x == self.y:
return "="
if self.x > self.y:
return ">"
return "<"
###############################################################################
# Unit Tests
###############################################################################
class unitTests(unittest.TestCase):
def test_single_test(self):
""" Mem class testing """
# Constructor test
test = "6 2\n1 0 1 1 1 1\n2 10\n4 7"
d = Mem(test)
self.assertEqual(d.n, 6)
self.assertEqual(d.m, 2)
# Sample test
self.assertEqual(Mem(test).calculate(), "=")
# Sample test
test = "3 3\n1 0 2\n2 5\n2 4"
self.assertEqual(Mem(test).calculate(), "<")
# Sample test
test = "7 16\n15 15 4 0 0 7 10\n7 9\n4 8 0 3 1 5 0"
self.assertEqual(Mem(test).calculate(), ">")
# My tests
test = ""
# self.assertEqual(Mem(test).calculate(), "0")
# Time limit test
# self.time_limit_test(5000)
def time_limit_test(self, nmax):
""" Timelimit testing """
import random
import timeit
# Random inputs
test = str(nmax) + " " + str(nmax) + "\n"
numnums = [str(i) + " " + str(i+1) for i in range(nmax)]
test += "\n".join(numnums) + "\n"
nums = [random.randint(1, 10000) for i in range(nmax)]
test += " ".join(map(str, nums)) + "\n"
# Run the test
start = timeit.default_timer()
d = Mem(test)
calc = timeit.default_timer()
d.calculate()
stop = timeit.default_timer()
print("\nTimelimit Test: " +
"{0:.3f}s (init {1:.3f}s calc {2:.3f}s)".
format(stop-start, calc-start, stop-calc))
if __name__ == "__main__":
# Avoiding recursion limitaions
sys.setrecursionlimit(100000)
if sys.argv[-1] == "-ut":
unittest.main(argv=[" "])
# Print the result string
sys.stdout.write(Mem().calculate())
```
| 7,118 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations.
You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers.
Input
The first line of the input contains two space-separated integers n and bx (1 ≤ n ≤ 10, 2 ≤ bx ≤ 40), where n is the number of digits in the bx-based representation of X.
The second line contains n space-separated integers x1, x2, ..., xn (0 ≤ xi < bx) — the digits of X. They are given in the order from the most significant digit to the least significant one.
The following two lines describe Y in the same way: the third line contains two space-separated integers m and by (1 ≤ m ≤ 10, 2 ≤ by ≤ 40, bx ≠ by), where m is the number of digits in the by-based representation of Y, and the fourth line contains m space-separated integers y1, y2, ..., ym (0 ≤ yi < by) — the digits of Y.
There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system.
Output
Output a single character (quotes for clarity):
* '<' if X < Y
* '>' if X > Y
* '=' if X = Y
Examples
Input
6 2
1 0 1 1 1 1
2 10
4 7
Output
=
Input
3 3
1 0 2
2 5
2 4
Output
<
Input
7 16
15 15 4 0 0 7 10
7 9
4 8 0 3 1 5 0
Output
>
Note
In the first sample, X = 1011112 = 4710 = Y.
In the second sample, X = 1023 = 215 and Y = 245 = 1123, thus X < Y.
In the third sample, <image> and Y = 48031509. We may notice that X starts with much larger digits and bx is much larger than by, so X is clearly larger than Y.
Submitted Solution:
```
n, b1 = map(int, input().split())
num = [int(x) for x in input().split()]
p = b1 ** (n - 1)
x = 0
for i in range(n):
numx = int(num[i])
x += numx * p
p //= b1
m, b2 = map(int, input().split())
num = [int(x) for x in input().split()]
p = b2 ** (m - 1)
y = 0
for i in range(m):
numy = int(num[i])
y += numy * p
p //= b2
if x < y:
print('<')
elif x > y:
print('>')
else:
print('=')
```
Yes
| 7,119 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations.
You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers.
Input
The first line of the input contains two space-separated integers n and bx (1 ≤ n ≤ 10, 2 ≤ bx ≤ 40), where n is the number of digits in the bx-based representation of X.
The second line contains n space-separated integers x1, x2, ..., xn (0 ≤ xi < bx) — the digits of X. They are given in the order from the most significant digit to the least significant one.
The following two lines describe Y in the same way: the third line contains two space-separated integers m and by (1 ≤ m ≤ 10, 2 ≤ by ≤ 40, bx ≠ by), where m is the number of digits in the by-based representation of Y, and the fourth line contains m space-separated integers y1, y2, ..., ym (0 ≤ yi < by) — the digits of Y.
There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system.
Output
Output a single character (quotes for clarity):
* '<' if X < Y
* '>' if X > Y
* '=' if X = Y
Examples
Input
6 2
1 0 1 1 1 1
2 10
4 7
Output
=
Input
3 3
1 0 2
2 5
2 4
Output
<
Input
7 16
15 15 4 0 0 7 10
7 9
4 8 0 3 1 5 0
Output
>
Note
In the first sample, X = 1011112 = 4710 = Y.
In the second sample, X = 1023 = 215 and Y = 245 = 1123, thus X < Y.
In the third sample, <image> and Y = 48031509. We may notice that X starts with much larger digits and bx is much larger than by, so X is clearly larger than Y.
Submitted Solution:
```
n, bx = list(map(int, input().split(" ")))
X = list(map(int, input().split(" ")))
m, by = list(map(int, input().split(" ")))
Y = list(map(int, input().split(" ")))
vx = 0
vy = 0
for i in range(n-1, -1, -1):
vx+= X[n-i-1]*(bx**i)
for i in range(m-1, -1, -1):
vy+= Y[m-i-1]*(by**i)
if(vx == vy):
print("=")
elif(vx> vy):
print(">")
else:
print("<")
```
Yes
| 7,120 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations.
You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers.
Input
The first line of the input contains two space-separated integers n and bx (1 ≤ n ≤ 10, 2 ≤ bx ≤ 40), where n is the number of digits in the bx-based representation of X.
The second line contains n space-separated integers x1, x2, ..., xn (0 ≤ xi < bx) — the digits of X. They are given in the order from the most significant digit to the least significant one.
The following two lines describe Y in the same way: the third line contains two space-separated integers m and by (1 ≤ m ≤ 10, 2 ≤ by ≤ 40, bx ≠ by), where m is the number of digits in the by-based representation of Y, and the fourth line contains m space-separated integers y1, y2, ..., ym (0 ≤ yi < by) — the digits of Y.
There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system.
Output
Output a single character (quotes for clarity):
* '<' if X < Y
* '>' if X > Y
* '=' if X = Y
Examples
Input
6 2
1 0 1 1 1 1
2 10
4 7
Output
=
Input
3 3
1 0 2
2 5
2 4
Output
<
Input
7 16
15 15 4 0 0 7 10
7 9
4 8 0 3 1 5 0
Output
>
Note
In the first sample, X = 1011112 = 4710 = Y.
In the second sample, X = 1023 = 215 and Y = 245 = 1123, thus X < Y.
In the third sample, <image> and Y = 48031509. We may notice that X starts with much larger digits and bx is much larger than by, so X is clearly larger than Y.
Submitted Solution:
```
n, bx = map(int, input().split())
x = list(map(int, input().split()))[::-1]
m, by = map(int, input().split())
y = list(map(int, input().split()))[::-1]
d1 = 0
deg = 1
for d in x:
d1 += d * deg
deg *= bx
d2 = 0
deg = 1
for d in y:
d2 += d * deg
deg *= by
print('>' if d1 > d2 else '<' if d1 < d2 else '=')
```
Yes
| 7,121 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations.
You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers.
Input
The first line of the input contains two space-separated integers n and bx (1 ≤ n ≤ 10, 2 ≤ bx ≤ 40), where n is the number of digits in the bx-based representation of X.
The second line contains n space-separated integers x1, x2, ..., xn (0 ≤ xi < bx) — the digits of X. They are given in the order from the most significant digit to the least significant one.
The following two lines describe Y in the same way: the third line contains two space-separated integers m and by (1 ≤ m ≤ 10, 2 ≤ by ≤ 40, bx ≠ by), where m is the number of digits in the by-based representation of Y, and the fourth line contains m space-separated integers y1, y2, ..., ym (0 ≤ yi < by) — the digits of Y.
There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system.
Output
Output a single character (quotes for clarity):
* '<' if X < Y
* '>' if X > Y
* '=' if X = Y
Examples
Input
6 2
1 0 1 1 1 1
2 10
4 7
Output
=
Input
3 3
1 0 2
2 5
2 4
Output
<
Input
7 16
15 15 4 0 0 7 10
7 9
4 8 0 3 1 5 0
Output
>
Note
In the first sample, X = 1011112 = 4710 = Y.
In the second sample, X = 1023 = 215 and Y = 245 = 1123, thus X < Y.
In the third sample, <image> and Y = 48031509. We may notice that X starts with much larger digits and bx is much larger than by, so X is clearly larger than Y.
Submitted Solution:
```
a1,b1=map(int,input().split())
X=input().split()
a2,b2=map(int,input().split())
Y=input().split()
k=0
g=0
for i in range(a1):
k+=int(X[i])*(b1**(a1-i-1))
for i in range(a2):
g+=int(Y[i])*(b2**(a2-i-1))
if k>g:
print('>')
elif k<g:
print('<')
elif k==g:
print('=')
```
Yes
| 7,122 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations.
You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers.
Input
The first line of the input contains two space-separated integers n and bx (1 ≤ n ≤ 10, 2 ≤ bx ≤ 40), where n is the number of digits in the bx-based representation of X.
The second line contains n space-separated integers x1, x2, ..., xn (0 ≤ xi < bx) — the digits of X. They are given in the order from the most significant digit to the least significant one.
The following two lines describe Y in the same way: the third line contains two space-separated integers m and by (1 ≤ m ≤ 10, 2 ≤ by ≤ 40, bx ≠ by), where m is the number of digits in the by-based representation of Y, and the fourth line contains m space-separated integers y1, y2, ..., ym (0 ≤ yi < by) — the digits of Y.
There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system.
Output
Output a single character (quotes for clarity):
* '<' if X < Y
* '>' if X > Y
* '=' if X = Y
Examples
Input
6 2
1 0 1 1 1 1
2 10
4 7
Output
=
Input
3 3
1 0 2
2 5
2 4
Output
<
Input
7 16
15 15 4 0 0 7 10
7 9
4 8 0 3 1 5 0
Output
>
Note
In the first sample, X = 1011112 = 4710 = Y.
In the second sample, X = 1023 = 215 and Y = 245 = 1123, thus X < Y.
In the third sample, <image> and Y = 48031509. We may notice that X starts with much larger digits and bx is much larger than by, so X is clearly larger than Y.
Submitted Solution:
```
def convert_base(num, to_base=10, from_base=10):
if isinstance(num, str):
n = int(num, from_base)
else:
n = int(num)
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
if n < to_base:
return alphabet[n]
else:
return convert_base(n // to_base, to_base) + alphabet[n % to_base]
n, a = map(int, input().split())
x = convert_base(''.join(input().split()), from_base=a)
n, a = map(int, input().split())
y = convert_base(''.join(input().split()), from_base=a)
if x == y: print('=')
elif x > y: print('>')
elif x < y: print('<')
```
No
| 7,123 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations.
You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers.
Input
The first line of the input contains two space-separated integers n and bx (1 ≤ n ≤ 10, 2 ≤ bx ≤ 40), where n is the number of digits in the bx-based representation of X.
The second line contains n space-separated integers x1, x2, ..., xn (0 ≤ xi < bx) — the digits of X. They are given in the order from the most significant digit to the least significant one.
The following two lines describe Y in the same way: the third line contains two space-separated integers m and by (1 ≤ m ≤ 10, 2 ≤ by ≤ 40, bx ≠ by), where m is the number of digits in the by-based representation of Y, and the fourth line contains m space-separated integers y1, y2, ..., ym (0 ≤ yi < by) — the digits of Y.
There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system.
Output
Output a single character (quotes for clarity):
* '<' if X < Y
* '>' if X > Y
* '=' if X = Y
Examples
Input
6 2
1 0 1 1 1 1
2 10
4 7
Output
=
Input
3 3
1 0 2
2 5
2 4
Output
<
Input
7 16
15 15 4 0 0 7 10
7 9
4 8 0 3 1 5 0
Output
>
Note
In the first sample, X = 1011112 = 4710 = Y.
In the second sample, X = 1023 = 215 and Y = 245 = 1123, thus X < Y.
In the third sample, <image> and Y = 48031509. We may notice that X starts with much larger digits and bx is much larger than by, so X is clearly larger than Y.
Submitted Solution:
```
from math import *
n,x = map(int,input().split())
a = list(map(int,input().split()))
m,y = map(int,input().split())
b = list(map(int,input().split()))
a.reverse()
b.reverse()
#print(a,b)
res1 = 0
for i in range(len(a)):
res1+=int(a[i])**i
res2 = 0
for i in range(len(b)):
res2+=int(b[i])**i
if res1==res2:
print('=')
quit()
if res1<res2:
print('<')
quit()
print('>')
```
No
| 7,124 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations.
You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers.
Input
The first line of the input contains two space-separated integers n and bx (1 ≤ n ≤ 10, 2 ≤ bx ≤ 40), where n is the number of digits in the bx-based representation of X.
The second line contains n space-separated integers x1, x2, ..., xn (0 ≤ xi < bx) — the digits of X. They are given in the order from the most significant digit to the least significant one.
The following two lines describe Y in the same way: the third line contains two space-separated integers m and by (1 ≤ m ≤ 10, 2 ≤ by ≤ 40, bx ≠ by), where m is the number of digits in the by-based representation of Y, and the fourth line contains m space-separated integers y1, y2, ..., ym (0 ≤ yi < by) — the digits of Y.
There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system.
Output
Output a single character (quotes for clarity):
* '<' if X < Y
* '>' if X > Y
* '=' if X = Y
Examples
Input
6 2
1 0 1 1 1 1
2 10
4 7
Output
=
Input
3 3
1 0 2
2 5
2 4
Output
<
Input
7 16
15 15 4 0 0 7 10
7 9
4 8 0 3 1 5 0
Output
>
Note
In the first sample, X = 1011112 = 4710 = Y.
In the second sample, X = 1023 = 215 and Y = 245 = 1123, thus X < Y.
In the third sample, <image> and Y = 48031509. We may notice that X starts with much larger digits and bx is much larger than by, so X is clearly larger than Y.
Submitted Solution:
```
def trans( nums , n , b ):
res = 0
for i in reversed( range( n ) ):
res = res*b+nums[i]
return res
if __name__ == "__main__":
n , bx = [int(x) for x in input().split()]
numXArray = [int(x) for x in input().split()]
numX = trans( numXArray , n , bx )
m , by = [int(x) for x in input().split()]
numYArray = [int(x) for x in input().split()]
numY = trans( numYArray , m , by )
if numX < numY:
print("<")
elif numX > numY:
print(">")
else:
print("=")
```
No
| 7,125 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations.
You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers.
Input
The first line of the input contains two space-separated integers n and bx (1 ≤ n ≤ 10, 2 ≤ bx ≤ 40), where n is the number of digits in the bx-based representation of X.
The second line contains n space-separated integers x1, x2, ..., xn (0 ≤ xi < bx) — the digits of X. They are given in the order from the most significant digit to the least significant one.
The following two lines describe Y in the same way: the third line contains two space-separated integers m and by (1 ≤ m ≤ 10, 2 ≤ by ≤ 40, bx ≠ by), where m is the number of digits in the by-based representation of Y, and the fourth line contains m space-separated integers y1, y2, ..., ym (0 ≤ yi < by) — the digits of Y.
There will be no leading zeroes. Both X and Y will be positive. All digits of both numbers are given in the standard decimal numeral system.
Output
Output a single character (quotes for clarity):
* '<' if X < Y
* '>' if X > Y
* '=' if X = Y
Examples
Input
6 2
1 0 1 1 1 1
2 10
4 7
Output
=
Input
3 3
1 0 2
2 5
2 4
Output
<
Input
7 16
15 15 4 0 0 7 10
7 9
4 8 0 3 1 5 0
Output
>
Note
In the first sample, X = 1011112 = 4710 = Y.
In the second sample, X = 1023 = 215 and Y = 245 = 1123, thus X < Y.
In the third sample, <image> and Y = 48031509. We may notice that X starts with much larger digits and bx is much larger than by, so X is clearly larger than Y.
Submitted Solution:
```
n, bx = map(int, input().strip().split())
x = int("".join(input().strip().split()), bx)
m, by = map(int, input().strip().split())
y = int("".join(input().strip().split()), by)
if x == y:
print("=")
elif x < y:
print("<")
else:
print(">")
```
No
| 7,126 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Your task is to calculate for how many minutes Limak will watch the game.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 90) — the number of interesting minutes.
The second line contains n integers t1, t2, ..., tn (1 ≤ t1 < t2 < ... tn ≤ 90), given in the increasing order.
Output
Print the number of minutes Limak will watch the game.
Examples
Input
3
7 20 88
Output
35
Input
9
16 20 30 40 50 60 70 80 90
Output
15
Input
9
15 20 30 40 50 60 70 80 90
Output
90
Note
In the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.
In the second sample, the first 15 minutes are boring.
In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game.
Tags: implementation
Correct Solution:
```
n = int(input())
BoringTimes = [int(i) for i in input().split(' ')]
flag = 0
if BoringTimes[0] > 15:
flag = 1
print('15')
else:
for i in range(n-1):
if BoringTimes[i+1] - BoringTimes[i] > 15:
flag = 1
print(BoringTimes[i] + 15)
break
if flag == 0 and BoringTimes[n-1] < 75:
flag = 1
print(BoringTimes[n-1] + 15)
if flag == 0:
print('90')
```
| 7,127 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Your task is to calculate for how many minutes Limak will watch the game.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 90) — the number of interesting minutes.
The second line contains n integers t1, t2, ..., tn (1 ≤ t1 < t2 < ... tn ≤ 90), given in the increasing order.
Output
Print the number of minutes Limak will watch the game.
Examples
Input
3
7 20 88
Output
35
Input
9
16 20 30 40 50 60 70 80 90
Output
15
Input
9
15 20 30 40 50 60 70 80 90
Output
90
Note
In the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.
In the second sample, the first 15 minutes are boring.
In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game.
Tags: implementation
Correct Solution:
```
n=int(input())
a=[int(i) for i in input().split()]
ch=0
for f in a:
if f-ch>15:
break
else:
ch=f
if ch>=90-15:
ch=90
else:
ch+=15
print(ch)
```
| 7,128 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Your task is to calculate for how many minutes Limak will watch the game.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 90) — the number of interesting minutes.
The second line contains n integers t1, t2, ..., tn (1 ≤ t1 < t2 < ... tn ≤ 90), given in the increasing order.
Output
Print the number of minutes Limak will watch the game.
Examples
Input
3
7 20 88
Output
35
Input
9
16 20 30 40 50 60 70 80 90
Output
15
Input
9
15 20 30 40 50 60 70 80 90
Output
90
Note
In the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.
In the second sample, the first 15 minutes are boring.
In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game.
Tags: implementation
Correct Solution:
```
input()
ts = map(int, input().split())
time = 15
for t in ts:
if t <= time:
time = t + 15
else:
break
print(min(90, time))
```
| 7,129 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Your task is to calculate for how many minutes Limak will watch the game.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 90) — the number of interesting minutes.
The second line contains n integers t1, t2, ..., tn (1 ≤ t1 < t2 < ... tn ≤ 90), given in the increasing order.
Output
Print the number of minutes Limak will watch the game.
Examples
Input
3
7 20 88
Output
35
Input
9
16 20 30 40 50 60 70 80 90
Output
15
Input
9
15 20 30 40 50 60 70 80 90
Output
90
Note
In the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.
In the second sample, the first 15 minutes are boring.
In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game.
Tags: implementation
Correct Solution:
```
n = input()
minutes = list(map(int,input().split()))
total_time = 0
mark = 0
for i in minutes:
watching = min(i-mark,15)
total_time += watching
if i-mark>=16:
break
mark = i
if mark == minutes[-1]:
total_time += min(90-minutes[-1],15)
print(total_time)
```
| 7,130 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Your task is to calculate for how many minutes Limak will watch the game.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 90) — the number of interesting minutes.
The second line contains n integers t1, t2, ..., tn (1 ≤ t1 < t2 < ... tn ≤ 90), given in the increasing order.
Output
Print the number of minutes Limak will watch the game.
Examples
Input
3
7 20 88
Output
35
Input
9
16 20 30 40 50 60 70 80 90
Output
15
Input
9
15 20 30 40 50 60 70 80 90
Output
90
Note
In the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.
In the second sample, the first 15 minutes are boring.
In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game.
Tags: implementation
Correct Solution:
```
n = int(input())
arr = list(map(int, input().split(' ')))
last = 0
end = False
for i in arr:
if i - last > 15:
print(last + 15)
end = True
break
last = i
if not end:
if last > 74:
print(90)
else:
print(last + 15)
```
| 7,131 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Your task is to calculate for how many minutes Limak will watch the game.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 90) — the number of interesting minutes.
The second line contains n integers t1, t2, ..., tn (1 ≤ t1 < t2 < ... tn ≤ 90), given in the increasing order.
Output
Print the number of minutes Limak will watch the game.
Examples
Input
3
7 20 88
Output
35
Input
9
16 20 30 40 50 60 70 80 90
Output
15
Input
9
15 20 30 40 50 60 70 80 90
Output
90
Note
In the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.
In the second sample, the first 15 minutes are boring.
In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game.
Tags: implementation
Correct Solution:
```
n = int(input())
t = list(map(int, input().split()))
if(n==1 or t[0]>15):
if(t[0] > 15):
print(15)
else:
print(t[0]+15)
else:
watchtime = 0
for i in range(1,n):
if(t[i]-t[i-1] >15):
watchtime=t[i-1]+15
break
if watchtime == 0:
watchtime = t[-1]+15
if watchtime > 90:
print(90)
else:
print(watchtime)
```
| 7,132 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Your task is to calculate for how many minutes Limak will watch the game.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 90) — the number of interesting minutes.
The second line contains n integers t1, t2, ..., tn (1 ≤ t1 < t2 < ... tn ≤ 90), given in the increasing order.
Output
Print the number of minutes Limak will watch the game.
Examples
Input
3
7 20 88
Output
35
Input
9
16 20 30 40 50 60 70 80 90
Output
15
Input
9
15 20 30 40 50 60 70 80 90
Output
90
Note
In the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.
In the second sample, the first 15 minutes are boring.
In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game.
Tags: implementation
Correct Solution:
```
n=int(input())
l=list(map(int,input().split()))
m=0
s=0
for i in range(n):
if(l[i]-m<=15):
m=l[i]
else:
m+=15
s=1
break
if(s==0):
if(90-m<=15):
m=90
else:
m+=15
print(m)
```
| 7,133 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Your task is to calculate for how many minutes Limak will watch the game.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 90) — the number of interesting minutes.
The second line contains n integers t1, t2, ..., tn (1 ≤ t1 < t2 < ... tn ≤ 90), given in the increasing order.
Output
Print the number of minutes Limak will watch the game.
Examples
Input
3
7 20 88
Output
35
Input
9
16 20 30 40 50 60 70 80 90
Output
15
Input
9
15 20 30 40 50 60 70 80 90
Output
90
Note
In the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.
In the second sample, the first 15 minutes are boring.
In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game.
Tags: implementation
Correct Solution:
```
n=int(input())
l=list(map(int,input().split()))
if len(l)==1:
if l[0]>15:
time=15
else:
time=l[0]+15
for i in range(len(l)):
if l[i]<=15 and i==0:
continue
elif l[i]>15 and i==0:
time=15
break
if l[i]-l[i-1]>15:
time=l[i-1]+15
break
elif l[i]-l[i-1]<=15:
if i==len(l)-1:
if l[i]<90:
if 90-l[i]<=15:
time=90
elif 90-l[i]>15:
time=l[i]+15
else:
time=90
else:
continue
print(time)
```
| 7,134 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Your task is to calculate for how many minutes Limak will watch the game.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 90) — the number of interesting minutes.
The second line contains n integers t1, t2, ..., tn (1 ≤ t1 < t2 < ... tn ≤ 90), given in the increasing order.
Output
Print the number of minutes Limak will watch the game.
Examples
Input
3
7 20 88
Output
35
Input
9
16 20 30 40 50 60 70 80 90
Output
15
Input
9
15 20 30 40 50 60 70 80 90
Output
90
Note
In the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.
In the second sample, the first 15 minutes are boring.
In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game.
Submitted Solution:
```
n = int(input())
T = [0]+list(map(int, input().split()))+[90]
ok = 1
for i in range(1,n+2):
if T[i]-T[i-1]>15:
print(T[i-1]+15)
ok = 0
break
if ok:
print(90)
```
Yes
| 7,135 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Your task is to calculate for how many minutes Limak will watch the game.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 90) — the number of interesting minutes.
The second line contains n integers t1, t2, ..., tn (1 ≤ t1 < t2 < ... tn ≤ 90), given in the increasing order.
Output
Print the number of minutes Limak will watch the game.
Examples
Input
3
7 20 88
Output
35
Input
9
16 20 30 40 50 60 70 80 90
Output
15
Input
9
15 20 30 40 50 60 70 80 90
Output
90
Note
In the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.
In the second sample, the first 15 minutes are boring.
In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game.
Submitted Solution:
```
a = int(input());
c = input().split();
dem = int(c[0]);
if dem > 15:
dem = 15;
else:
for i in range(a):
d = int(c[i]) - dem;
if d > 15:
dem = int(c[i-1]) + 15;
break
else:
if (i + 1) != a:
dem = int(c[i]);
else:
if int(c[a-1]) > 75:
dem = 90;
else:
dem = int(c[a-1])+15
print(dem)
```
Yes
| 7,136 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Your task is to calculate for how many minutes Limak will watch the game.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 90) — the number of interesting minutes.
The second line contains n integers t1, t2, ..., tn (1 ≤ t1 < t2 < ... tn ≤ 90), given in the increasing order.
Output
Print the number of minutes Limak will watch the game.
Examples
Input
3
7 20 88
Output
35
Input
9
16 20 30 40 50 60 70 80 90
Output
15
Input
9
15 20 30 40 50 60 70 80 90
Output
90
Note
In the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.
In the second sample, the first 15 minutes are boring.
In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game.
Submitted Solution:
```
n = int(input())
minutes=[]
for i in range(91):
minutes.append(False)
for x in input().split():
x = int(x)
minutes[x] = True
l = 0
i = 1;
while i < 90:
if minutes[i] == False:
l += 1;
else:
l = 0
if (l == 15): break;
i += 1;
print(i)
```
Yes
| 7,137 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Your task is to calculate for how many minutes Limak will watch the game.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 90) — the number of interesting minutes.
The second line contains n integers t1, t2, ..., tn (1 ≤ t1 < t2 < ... tn ≤ 90), given in the increasing order.
Output
Print the number of minutes Limak will watch the game.
Examples
Input
3
7 20 88
Output
35
Input
9
16 20 30 40 50 60 70 80 90
Output
15
Input
9
15 20 30 40 50 60 70 80 90
Output
90
Note
In the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.
In the second sample, the first 15 minutes are boring.
In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game.
Submitted Solution:
```
first_line = input()
second_line = input()
n = int(first_line)
lst = list(map(lambda a: int(a), second_line.split()))
def solve1(n, lst):
if lst[0] > 15:
return 15
for i in range(len(lst) - 1):
if lst[i + 1] - lst[i] > 15:
return lst[i] + 15
return min(lst[n-1] + 15, 90)
print(solve1(n, lst))
```
Yes
| 7,138 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Your task is to calculate for how many minutes Limak will watch the game.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 90) — the number of interesting minutes.
The second line contains n integers t1, t2, ..., tn (1 ≤ t1 < t2 < ... tn ≤ 90), given in the increasing order.
Output
Print the number of minutes Limak will watch the game.
Examples
Input
3
7 20 88
Output
35
Input
9
16 20 30 40 50 60 70 80 90
Output
15
Input
9
15 20 30 40 50 60 70 80 90
Output
90
Note
In the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.
In the second sample, the first 15 minutes are boring.
In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game.
Submitted Solution:
```
n = int(input())
m = input()
minutes = [int(x) for x in m.split()]
ans = 0
for i in range(len(minutes)):
if ans + 15 >= minutes[i]:
ans = minutes[i]
else:
ans += 15
break
print(ans)
```
No
| 7,139 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Your task is to calculate for how many minutes Limak will watch the game.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 90) — the number of interesting minutes.
The second line contains n integers t1, t2, ..., tn (1 ≤ t1 < t2 < ... tn ≤ 90), given in the increasing order.
Output
Print the number of minutes Limak will watch the game.
Examples
Input
3
7 20 88
Output
35
Input
9
16 20 30 40 50 60 70 80 90
Output
15
Input
9
15 20 30 40 50 60 70 80 90
Output
90
Note
In the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.
In the second sample, the first 15 minutes are boring.
In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game.
Submitted Solution:
```
n=int(input())
l=list(map(int,input().split()))
m=0
for i in range(n):
if(l[i]-m<=15):
m=l[i]
else:
m+=15
break
if(i==n):
if(90-m<=15):
m=90
else:
m+=15
print(m)
```
No
| 7,140 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Your task is to calculate for how many minutes Limak will watch the game.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 90) — the number of interesting minutes.
The second line contains n integers t1, t2, ..., tn (1 ≤ t1 < t2 < ... tn ≤ 90), given in the increasing order.
Output
Print the number of minutes Limak will watch the game.
Examples
Input
3
7 20 88
Output
35
Input
9
16 20 30 40 50 60 70 80 90
Output
15
Input
9
15 20 30 40 50 60 70 80 90
Output
90
Note
In the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.
In the second sample, the first 15 minutes are boring.
In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game.
Submitted Solution:
```
x = int(input())
y = list(map(int, input().split(' ')))
watched = 0
base = 15
for t in y:
duration = t - watched
if duration <= base:
total = watched + duration + base
watched = total if total < 90 else 90
else:
watched = watched + base
break
watched = t
print(watched)
```
No
| 7,141 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Your task is to calculate for how many minutes Limak will watch the game.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 90) — the number of interesting minutes.
The second line contains n integers t1, t2, ..., tn (1 ≤ t1 < t2 < ... tn ≤ 90), given in the increasing order.
Output
Print the number of minutes Limak will watch the game.
Examples
Input
3
7 20 88
Output
35
Input
9
16 20 30 40 50 60 70 80 90
Output
15
Input
9
15 20 30 40 50 60 70 80 90
Output
90
Note
In the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.
In the second sample, the first 15 minutes are boring.
In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game.
Submitted Solution:
```
def main():
n = int(input())
c = 0
minutes = [int(i) for i in input().split()]
for m in minutes:
if m - c - 1 >= 15:
print(c + 15)
return
c = m
if m + 14 <= 90:
print(m + 14)
else:
print(90)
main()
```
No
| 7,142 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid.
Tags: constructive algorithms, dfs and similar, dsu, graphs, trees
Correct Solution:
```
from collections import deque
# ver si hay un camino que llega a el a partir
# de su padre entonces hay un ciclo
def Padre(x, padre):
while x != padre[x]:
x = padre[x]
return x
def DFS(x, color, padre, ciclos, adyacentes, raiz):
color[x] = 1 # nodo gris
for y in adyacentes[x]:
# el adyacente es blanco
if color[y] == 0:
DFS(y, color, padre, ciclos, adyacentes, raiz)
padre[y] = x
elif color[y] == 2:
padre[y] = x
# ese adyacente es gris entonces <u,v> rista de retroceso
else:
if y == x and not raiz:
raiz = x
else:
ciclos.append([x, y])
color[x] = 2 # nodo negro
def Solucion():
n = int(input())
A = list(map(lambda x: int(x)-1, input().split()))
padre = [x for x in range(0, n)]
ciclosC = 0
ciclos = deque([])
root = []
# ir haciendo Merge a cada arista
for i in range(0, n):
p = Padre(A[i], padre)
# Si dicha arista perticipa en un ciclo
if p == i:
# Si es un ciclo del tipo raiz y no hay raiz
if not root and (i == A[i]):
root = [i, A[i]]
else:
ciclos.append([i, A[i]])
ciclosC += 1
# Si no hay ciclo
else:
padre[i] = A[i]
print(str(ciclosC))
# si existe al menos un ciclo diferente d raiz
if ciclosC:
i = 0
# si no hay raiz el primer ciclo lo hago raiz
if not root:
root = ciclos.popleft()
i = 1
# los restantes ciclos hago que su padre sea la raiz
while ciclos:
ciclo = ciclos.popleft()
padre[ciclo[0]] = root[0]
PC = [x + 1 for x in padre]
print(*PC, sep=" ")
Solucion()
# Casos de prueba:
# 4
# 2 3 3 4
# respuesta
# 1
# 2 3 3 3
# 5
# 3 2 2 5 3
# respuesta
# 0
# 3 2 2 5 3
# 8
# 2 3 5 4 1 6 6 7
# respuesta
# 2
# 2 3 5 4 1 4 6 7
# 200000
# hacer con el generador
```
| 7,143 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid.
Tags: constructive algorithms, dfs and similar, dsu, graphs, trees
Correct Solution:
```
from collections import deque
# Para revisar la correctitud pueden probar el codigo en el codeforce que va a dar accepted
# ver si hay un camino que llega a el a partir
# de su padre entonces hay un ciclo
def Padre(x, padre):
while x != padre[x]:
x = padre[x]
return x
def FixATree():
n = int(input())
A = list(map(lambda x: int(x)-1, input().split()))
padre = [x for x in range(0, n)]
ciclosC = 0
ciclos = deque([])
root = []
# ir haciendo Merge a cada arista
for i in range(0, n):
p = Padre(A[i], padre)
# Si dicha arista perticipa en un ciclo
if p == i:
# Si es un ciclo del tipo raiz y no hay raiz
if not root and (i == A[i]):
root = [i, A[i]]
else:
ciclos.append([i, A[i]])
ciclosC += 1
# Si no hay ciclo
else:
padre[i] = A[i]
print(str(ciclosC))
# si existe al menos un ciclo diferente d raiz
if ciclosC:
i = 0
# si no hay raiz el primer ciclo lo hago raiz
if not root:
root = ciclos.popleft()
i = 1
# los restantes ciclos hago que su padre sea la raiz
while ciclos:
ciclo = ciclos.popleft()
padre[ciclo[0]] = root[0]
PC = [x + 1 for x in padre]
print(*PC, sep=" ")
FixATree()
# Casos de prueba:
# 4
# 2 3 3 4
# respuesta
# 1
# 2 3 3 3
# 5
# 3 2 2 5 3
# respuesta
# 0
# 3 2 2 5 3
# 8
# 2 3 5 4 1 6 6 7
# respuesta
# 2
# 2 3 5 4 1 4 6 7
# El codigo da accepted en el codeforce por lo que los casos de prueba que emplee son los que ahi estan
```
| 7,144 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid.
Tags: constructive algorithms, dfs and similar, dsu, graphs, trees
Correct Solution:
```
tree_size = int(input())
parents = [int(x)-1 for x in input().split(' ')]
num_changes = 0
root = tree_size
for node, parent in enumerate(parents):
if parent == node:
root = node
break
visited = set()
finished = set()
visited.add(root)
finished.add(root)
stack = []
fringe = []
for node in range(len(parents)):
if node not in visited:
fringe.append(node)
while fringe:
cur = fringe.pop()
visited.add(cur)
stack.append(cur)
if parents[cur] not in finished:
if parents[cur] in visited:
parents[cur] = root
num_changes += 1
else:
fringe.append(parents[cur])
while stack:
finished.add(stack.pop())
if root == tree_size:
new_root = None
for node, parent in enumerate(parents):
if parent == root:
if new_root is None:
new_root = node
parents[node] = new_root
for i in range(len(parents)):
parents[i] += 1
print(num_changes)
print(*parents)
```
| 7,145 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid.
Tags: constructive algorithms, dfs and similar, dsu, graphs, trees
Correct Solution:
```
n = int(input())
arr = list(map(int, input().split(' ')))
root=-1
for i,a in enumerate(arr) :
if i == a-1 :
root = i
break
v = [False]*len(arr)
if root>-1 :
v[root]=True
ans = 0
for i,a in enumerate(arr) :
if v[i] :
continue
v[i]= True
l=[i]
a-=1
while not v[a] :
l.append(a)
v[a]=True
a=arr[a]-1
if a in l: #new cycle
if root==-1:
arr[a]=a+1
root=a
ans+=1
else :
arr[a]=root+1
ans+=1
print(ans)
print(' '.join(map(str,arr)))
```
| 7,146 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid.
Tags: constructive algorithms, dfs and similar, dsu, graphs, trees
Correct Solution:
```
# Why do we fall ? So we can learn to pick ourselves up.
root = -1
def find(i,time):
parent[i] = time
while not parent[aa[i]]:
i = aa[i]
parent[i] = time
# print(parent,"in",i)
if parent[aa[i]] == time:
global root
if root == -1:
root = i
if aa[i] != root:
aa[i] = root
global ans
ans += 1
n = int(input())
aa = [0]+[int(i) for i in input().split()]
parent = [0]*(n+1)
ans = 0
time = 0
for i in range(1,n+1):
if aa[i] == i:
root = i
break
for i in range(1,n+1):
if not parent[i]:
# print(i,"pp")
time += 1
find(i,time)
# print(parent)
print(ans)
print(*aa[1:])
```
| 7,147 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid.
Tags: constructive algorithms, dfs and similar, dsu, graphs, trees
Correct Solution:
```
# from debug import debug
import sys; input = sys.stdin.readline
n = int(input())
lis = [0, *map(int , input().split())]
v = [0]*(n+1)
cycles = set()
roots = set()
for i in range(1, n+1):
if v[i] == 0:
node = i
while v[node] == 0:
v[node] = 1
node = lis[node]
if v[node] == 2: continue
start = node
ignore = 0
l = 1
while lis[node] != start:
if v[node] == 2: ignore = 1; break
v[node] = 2
node = lis[node]
l+=1
if ignore: continue
v[node] = 2
if l == 1: roots.add(node)
else: cycles.add(node)
ans = 0
if roots:
base = roots.pop()
for i in roots: lis[i] = base; ans+=1
for i in cycles: lis[i] = base; ans+=1
elif cycles:
base = cycles.pop()
cycles.add(base)
for i in roots: lis[i] = base; ans+=1
for i in cycles: lis[i] = base; ans+=1
print(ans)
print(*lis[1:])
```
| 7,148 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid.
Tags: constructive algorithms, dfs and similar, dsu, graphs, trees
Correct Solution:
```
# [https://codeforces.com/contest/698/submission/42129034]
input()
A = list(map(int, input().split(' ')))
root = -1
for i,a in enumerate(A) :
if i == a-1 :
root = i
break
v = [False]*len(A)
if root>-1 :
v[root]=True
changed = 0
for i,a in enumerate(A) :
if v[i] :
continue
v[i]= True
l=[i]
a-=1
while not v[a] :
l.append(a)
v[a]=True
a=A[a]-1
if a in l:
if root==-1:
A[a]=a+1
root=a
changed+=1
else :
A[a]=root+1
changed+=1
print(changed)
print(' '.join(map(str,A)))
```
| 7,149 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid.
Tags: constructive algorithms, dfs and similar, dsu, graphs, trees
Correct Solution:
```
input()
A = list(map(int, input().split(' ')))
root = -1
for i,a in enumerate(A) :
if i == a-1 :
root = i
break
v = [False]*len(A)
if root>-1 :
v[root]=True
changed = 0
for i,a in enumerate(A) :
if v[i] :
continue
v[i]= True
l=[i]
a-=1
while not v[a] :
l.append(a)
v[a]=True
a=A[a]-1
if a in l:
if root==-1:
A[a]=a+1
root=a
changed+=1
else :
A[a]=root+1
changed+=1
print(changed)
print(' '.join(map(str,A)))
# Made By Mostafa_Khaled
```
| 7,150 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
par=[]
for i in range(n):
if a[i]==i+1:
par.append(i)
v=[False for i in range(n)]
for i in par:
v[i]=True
ccl=[]
for i in range(n):
if v[i]:continue
s=[i]
v[i]=True
p=set(s)
t=True
while s and t:
x=s.pop()
j=a[x]-1
if j in p:
ccl.append(j)
t=False
else:
s.append(j)
p.add(j)
if v[j]:t=False
else:v[j]=True
if len(par)==0:
print(len(ccl))
c=ccl[0]
a[c]=c+1
for i in range(1,len(ccl)):
a[ccl[i]]=c+1
print(*a)
else:
print(len(ccl)+len(par)-1)
c=par[0]
for i in range(1,len(par)):
a[par[i]]=c+1
for i in range(len(ccl)):
a[ccl[i]]=c+1
print(*a)
```
Yes
| 7,151 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid.
Submitted Solution:
```
from collections import defaultdict
from sys import stdin,setrecursionlimit
setrecursionlimit(10**6)
import threading
def f(a):
n=len(a)
a=list(map(lambda s:s-1,a))
root=None
for i in range(len(a)):
if a[i]==i:
root=i
vis=[0]*(n)
traitors=[]
for i in range(0,n):
cycle=-1
cur=i
move=set()
while vis[cur]==0:
vis[cur]=1
move.add(cur)
if a[cur] in move:
cycle=cur
cur=a[cur]
if cycle!=-1:
traitors.append(cycle)
ans=len(traitors)-1
if root==None:
a[traitors[0]]=traitors[0]
root=traitors[0]
ans+=1
for i in traitors:
if i!=root:
a[i]=root
print(ans)
a=list(map(lambda s:s+1,a))
return a
n=input()
a=list(map(int,input().strip().split()))
print(*f(a))
```
Yes
| 7,152 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid.
Submitted Solution:
```
tree_size = int(input())
parents = [int(x)-1 for x in input().split(' ')]
num_changes = 0
root = None
for node, parent in enumerate(parents):
if parent == node:
root = node
if not root:
root = tree_size
num_changes += 1
finished = set()
visited = set()
visited.add(root)
finished.add(root)
def visit(node):
global num_changes
visited.add(node)
if parents[node] not in finished:
if parents[node] in visited:
parents[node] = root
num_changes += 1
else:
visit(parents[node])
finished.add(node)
for node in range(tree_size):
if node not in visited:
visit(node)
new_root = None
for node, parent in enumerate(parents):
if parent == tree_size:
if not new_root:
new_root = node
parents[node] = new_root
for i in range(tree_size):
parents[i] += 1
print(num_changes)
print(*parents)
```
No
| 7,153 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid.
Submitted Solution:
```
from collections import defaultdict
from sys import stdin,setrecursionlimit
setrecursionlimit(10**6)
import threading
def dfs(node,g,vis):
vis[node]=1
for i in g[node]:
if vis[i]==0:
dfs(i,g,vis)
def dfs2(node,g,vis,path):
path.append(node)
vis[node]=1
for i in g[node]:
if vis[i]==0:
dfs2(i,g,vis,path)
def main():
def f(a):
n=len(a)
g=defaultdict(list)
good=None
for i in range(0,len(a)):
if a[i]==i+1 and good==None:
# print(a[i],i,"lodu")
good=a[i]
g[i+1].append(a[i])
g[a[i]].append(i+1)
cnt=0
if good==None:
a[0]=1
good=1
cnt+=1
vis=[0]*(len(a)+1)
dfs(good,g,vis)
for i in range(1,n+1):
if i==good-1:
continue
if vis[i]==0:
pah=[]
dfs2(i,g,vis,pah)
if pah:
cnt+=1
a[i-1]=good
print(cnt)
print(*a)
a=input()
lst=list(map(int,input().strip().split()))
f(lst)
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()
```
No
| 7,154 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid.
Submitted Solution:
```
tree_size = int(input())
parents = [int(x)-1 for x in input().split(' ')]
num_changes = 0
root = None
for node, parent in enumerate(parents):
if parent == node:
root = node
break
if not root:
root = tree_size
finished = set()
visited = set()
visited.add(root)
finished.add(root)
def visit(node):
global num_changes
visited.add(node)
if parents[node] not in finished:
if parents[node] in visited:
parents[node] = root
num_changes += 1
else:
visit(parents[node])
finished.add(node)
for node in range(tree_size):
if node not in visited:
visit(node)
new_root = None
for node, parent in enumerate(parents):
if parent == tree_size:
if not new_root:
new_root = node
parents[node] = new_root
for i in range(tree_size):
parents[i] += 1
print(num_changes)
print(*parents)
```
No
| 7,155 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A tree is an undirected connected graph without cycles.
Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).
<image> For this rooted tree the array p is [2, 3, 3, 2].
Given a sequence p1, p2, ..., pn, one is able to restore a tree:
1. There must be exactly one index r that pr = r. A vertex r is a root of the tree.
2. For all other n - 1 vertices i, there is an edge between vertex i and vertex pi.
A sequence p1, p2, ..., pn is called valid if the described procedure generates some (any) rooted tree. For example, for n = 3 sequences (1,2,2), (2,3,1) and (2,1,3) are not valid.
You are given a sequence a1, a2, ..., an, not necessarily valid. Your task is to change the minimum number of elements, in order to get a valid sequence. Print the minimum number of changes and an example of a valid sequence after that number of changes. If there are many valid sequences achievable in the minimum number of changes, print any of them.
Input
The first line of the input contains an integer n (2 ≤ n ≤ 200 000) — the number of vertices in the tree.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n).
Output
In the first line print the minimum number of elements to change, in order to get a valid sequence.
In the second line, print any valid sequence possible to get from (a1, a2, ..., an) in the minimum number of changes. If there are many such sequences, any of them will be accepted.
Examples
Input
4
2 3 3 4
Output
1
2 3 4 4
Input
5
3 2 2 5 3
Output
0
3 2 2 5 3
Input
8
2 3 5 4 1 6 6 7
Output
2
2 3 7 8 1 6 6 7
Note
In the first sample, it's enough to change one element. In the provided output, a sequence represents a tree rooted in a vertex 4 (because p4 = 4), which you can see on the left drawing below. One of other correct solutions would be a sequence 2 3 3 2, representing a tree rooted in vertex 3 (right drawing below). On both drawings, roots are painted red.
<image>
In the second sample, the given sequence is already valid.
Submitted Solution:
```
from collections import defaultdict
from sys import stdin,setrecursionlimit
setrecursionlimit(10**6)
import threading
def dfs(node,g,vis):
vis[node]=1
for i in g[node]:
if vis[i]==0:
dfs(i,g,vis)
def dfs2(node,g,vis,path):
path.append(node)
vis[node]=1
for i in g[node]:
if vis[i]==0:
dfs2(i,g,vis,path)
def main():
def f(a):
n=len(a)
g=defaultdict(list)
good=None
for i in range(0,len(a)):
if a[i]==i+1 and good==None:
# print(a[i],i,"lodu")
good=a[i]
g[i+1].append(a[i])
g[a[i]].append(i+1)
cnt=0
# print(g)
if good==None:
t=max(g.keys(),key=lambda s:len(g[s]))
g[t].remove(a[t-1])
g[a[t-1]].remove(t)
g[t].append(t)
a[t-1]=t
good=t
cnt+=1
vis=[0]*(len(a)+1)
dfs(good,g,vis)
# print(vis)
for i in range(1,n+1):
if vis[i]==0:
pah=[]
dfs2(i,g,vis,pah)
if pah:
cnt+=1
a[i-1]=good
ind=[]
for i in range(0,len(a)):
if a[i]==i+1:
ind+=[a[i],i]
if len(ind)>2:
print(*ind,sep="+")
else:
print(cnt)
print(*a)
a=input()
lst=list(map(int,input().strip().split()))
f(lst)
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()
```
No
| 7,156 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.
Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches.
The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.
Output
Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.
Examples
Input
5
rbbrr
Output
1
Input
5
bbbbb
Output
2
Input
3
rbr
Output
0
Note
In the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.
In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.
In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.
Tags: greedy
Correct Solution:
```
n=int(input())
s=input()
e="rb"*(n//2)+"r"*(n%2)
w="br"*(n//2)+"b"*(n%2)
lenn=len(s)
f,r,b,rr,bb=0,0,0,0,0
for i in range(lenn):
if s[i]!=e[i]:
if s[i]=='r':
r+=1
else:
b+=1
if s[i]!=w[i]:
if s[i]=='r':
rr+=1
else:
bb+=1
f=min(max(r,b),max(rr,bb))
print(f)
```
| 7,157 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.
Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches.
The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.
Output
Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.
Examples
Input
5
rbbrr
Output
1
Input
5
bbbbb
Output
2
Input
3
rbr
Output
0
Note
In the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.
In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.
In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.
Tags: greedy
Correct Solution:
```
n, cr = int(input()), [i for i in input()]
case_1 = (["r", "b"]*n)[0:n]
case_2 = (["b", "r"]*n)[0:n]
btor, rtob = 0, 0
ans = []
for i in range(len(cr)):
if (cr[i] != case_1[i]) :
if cr[i] == "r" :
rtob += 1
else :
btor += 1
ans.append(min([rtob, btor]) + abs(rtob - btor))
btor, rtob = 0, 0
for i in range(len(cr)):
if (cr[i] != case_2[i]) :
if cr[i] == "r" :
rtob += 1
else :
btor += 1
ans.append(min([rtob, btor]) + abs(rtob - btor))
print(min(ans))
```
| 7,158 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.
Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches.
The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.
Output
Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.
Examples
Input
5
rbbrr
Output
1
Input
5
bbbbb
Output
2
Input
3
rbr
Output
0
Note
In the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.
In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.
In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.
Tags: greedy
Correct Solution:
```
def cal( s , c ):
w = [0 , 0]
for i in range(len(s)):
if s[i] != c: w[ i % 2 ] += 1
c = 'r' if c == 'b' else 'b'
return max(w[0], w[1])
n = int( input() )
s = input()
print( min( cal( s , 'r' ) , cal( s , 'b' ) ) )
```
| 7,159 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.
Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches.
The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.
Output
Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.
Examples
Input
5
rbbrr
Output
1
Input
5
bbbbb
Output
2
Input
3
rbr
Output
0
Note
In the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.
In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.
In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.
Tags: greedy
Correct Solution:
```
n = int(input())
cockroaches = input()
def get_color_range(start_color):
color = start_color
while True:
if color == 'b':
color = 'r'
else:
color ='b'
yield color
color_range1 = get_color_range('r')
color_range2 = get_color_range('b')
r1 = r2 = b1 = b2 = 0
for color in cockroaches:
if color != next(color_range1):
if color == 'r':
r1 += 1
else:
b1 += 1
if color != next(color_range2):
if color == 'r':
r2 += 1
else:
b2 += 1
variant1 = min(r1, b1) + abs(r1 - b1)
variant2 = min(r2, b2) + abs(r2 - b2)
print(min(variant1, variant2))
```
| 7,160 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.
Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches.
The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.
Output
Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.
Examples
Input
5
rbbrr
Output
1
Input
5
bbbbb
Output
2
Input
3
rbr
Output
0
Note
In the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.
In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.
In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.
Tags: greedy
Correct Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 17 19:15:41 2016
@author: bigu
"""
n = int(input())
line = input()
black0 = black1 = red0 = red1 = 0
for i,cock in enumerate(line):
if i%2==0 and cock == 'r':
red0+=1
elif i%2==1 and cock == 'r':
red1+=1
elif i%2==0 and cock == 'b':
black0+=1
elif i%2==1 and cock == 'b':
black1+=1
ans = min(max(red0,black1),max(red1,black0))
print(ans)
```
| 7,161 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.
Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches.
The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.
Output
Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.
Examples
Input
5
rbbrr
Output
1
Input
5
bbbbb
Output
2
Input
3
rbr
Output
0
Note
In the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.
In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.
In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.
Tags: greedy
Correct Solution:
```
def f(p):
cnt1 = sum(a[i] != p[i] == 1 for i in range(n))
cnt2 = sum(a[i] != p[i] == 0 for i in range(n))
res = max(cnt1, cnt2)
return res
n = int(input())
a = [int(i == 'r') for i in input()]
p1 = [i % 2 for i in range(n)]
p2 = [(i + 1) % 2 for i in range(n)]
ans = min(f(p1), f(p2))
print(ans)
```
| 7,162 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.
Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches.
The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.
Output
Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.
Examples
Input
5
rbbrr
Output
1
Input
5
bbbbb
Output
2
Input
3
rbr
Output
0
Note
In the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.
In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.
In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.
Tags: greedy
Correct Solution:
```
n=input()
word=input()
c=0
sum1,sum2,sum3,sum4=0,0,0,0
for i in word:
if c==0 :
if i=='r':
sum1+=1
else :
sum2+=1
c=1
else :
if i=='b':
sum3+=1
else :
sum4+=1
c=0
print(min(max(sum1,sum3),max(sum2,sum4)))
```
| 7,163 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.
Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches.
The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.
Output
Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.
Examples
Input
5
rbbrr
Output
1
Input
5
bbbbb
Output
2
Input
3
rbr
Output
0
Note
In the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.
In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.
In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.
Tags: greedy
Correct Solution:
```
def dist(s, choice):
r_diff = 0
b_diff = 0
for i in range(len(s)):
if choice[i] != s[i]:
if s[i] == 'r':
r_diff += 1
else:
b_diff += 1
min_diff = min(r_diff, b_diff)
return min_diff + (r_diff - min_diff) + (b_diff - min_diff)
if __name__ == '__main__':
n = int(input())
a = list(input())
choice_one = []
choice_two = []
for i in range(len(a)):
if i % 2 == 0:
choice_one.append('r')
choice_two.append('b')
else:
choice_one.append('b')
choice_two.append('r')
print(min(dist(a, choice_one), dist(a, choice_two)))
```
| 7,164 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.
Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches.
The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.
Output
Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.
Examples
Input
5
rbbrr
Output
1
Input
5
bbbbb
Output
2
Input
3
rbr
Output
0
Note
In the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.
In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.
In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.
Submitted Solution:
```
n=int(input())
m=input()
rb={'r':0,'b':0}
br={'r':0,'b':0}
for i in range(n):
if i%2:
if m[i]=='b':
br['b']+=1
else:
rb['r']+=1
else:
if m[i]=='r':
br['r']+=1
else:
rb['b']+=1
rbs=min(rb['b'],rb['r'])+abs(rb['b']-rb['r'])
brs=min(br['b'],br['r'])+abs(br['b']-br['r'])
print(min(rbs,brs))
```
Yes
| 7,165 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.
Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches.
The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.
Output
Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.
Examples
Input
5
rbbrr
Output
1
Input
5
bbbbb
Output
2
Input
3
rbr
Output
0
Note
In the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.
In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.
In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.
Submitted Solution:
```
n=int(input())
s=input()
a,b,c,d=0,0,0,0
for i in range(n):
if(s[i]=='r' and i%2==0):
a=a+1
elif(s[i]=='b' and i%2==1):
b=b+1
elif(s[i]=='r' and i%2==1):
c=c+1
elif(s[i]=='b' and i%2==0):
d=d+1
print(min(max(a,b),max(c,d)))
```
Yes
| 7,166 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.
Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches.
The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.
Output
Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.
Examples
Input
5
rbbrr
Output
1
Input
5
bbbbb
Output
2
Input
3
rbr
Output
0
Note
In the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.
In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.
In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.
Submitted Solution:
```
def miss(st, c):
r = 0
for i in range(0, n, 2):
if st[i] != c[0]:
r += 1
b = 0
for i in range(1, n, 2):
if st[i] != c[1]:
b += 1
return max(r, b)
n = int(input())
s = input()
print(min(miss(s, 'rb'), miss(s, 'br')))
```
Yes
| 7,167 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.
Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches.
The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.
Output
Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.
Examples
Input
5
rbbrr
Output
1
Input
5
bbbbb
Output
2
Input
3
rbr
Output
0
Note
In the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.
In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.
In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.
Submitted Solution:
```
n = int(input())
a = input()
p1 = 0
p2 = 0
for i in range(n):
if i % 2 and a[i] != 'r':
p1 += 1
if not i % 2 and a[i] != 'b':
p2 += 1
m1 = max(p1, p2)
p1 = 0
p2 = 0
for i in range(n):
if i % 2 and a[i] != 'b':
p1 += 1
if not i % 2 and a[i] != 'r':
p2 += 1
m2 = max(p1, p2)
print(min(m1, m2))
```
Yes
| 7,168 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.
Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches.
The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.
Output
Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.
Examples
Input
5
rbbrr
Output
1
Input
5
bbbbb
Output
2
Input
3
rbr
Output
0
Note
In the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.
In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.
In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.
Submitted Solution:
```
import math
x = int(input())
a = list(input())
def getMovesCount(a):
if len(a) == 2 and a[0] == a[1]:
return 1
r = a.count('r')
b = a.count('b')
k = {'r': 'b', 'b': 'r'}
if abs(r - b) <= 1: # rozdiel v pocte medzi cervenymi a ciernymi udava pocet prefarbeni
# zisti pocet nespravne umiestnenych/2
ma_ist = 'b'
result = 0
for i in range(len(a)):
if a[i] != ma_ist:
result += 1
# print(i)
ma_ist = k[ma_ist]
ma_ist = 'r'
result2 = 0
for i in range(len(a)):
if a[i] != ma_ist:
result2 += 1
# print(i)
ma_ist = k[ma_ist]
if result < result2:
return math.ceil(result/2)
return math.ceil(result2/2)
# todo
ma_ist = 'b'
resultp = 0
for i in range(len(a)):
if a[i] != ma_ist:
resultp += 1
ma_ist = k[ma_ist]
maxp = (max(r, b) - resultp)//2
ma_ist = 'r'
resultd = 0
for i in range(len(a)):
if a[i] != ma_ist:
resultd += 1
ma_ist = k[ma_ist]
maxd = (max(r, b) - resultd)//2
if maxp < maxd:
return resultp//2 + maxp
return resultd//2 + maxd
# print(getMovesCount(list('rrbrbrbrb')))
print(getMovesCount(a))
```
No
| 7,169 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.
Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches.
The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.
Output
Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.
Examples
Input
5
rbbrr
Output
1
Input
5
bbbbb
Output
2
Input
3
rbr
Output
0
Note
In the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.
In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.
In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.
Submitted Solution:
```
def dist(s, choice):
res = 0
for i in range(len(s)):
if s[i] == choice[i]:
continue
elif i + 1 < len(s) and choice[i] == s[i + 1] and choice[i + 1] == s[i]:
s[i + 1] = s[i]
res += 1
else:
res += 1
return res
if __name__ == '__main__':
n = int(input())
a = list(input())
choice_one = []
choice_two = []
for i in range(len(a)):
if i % 2 == 0:
choice_one.append('r')
choice_two.append('b')
else:
choice_one.append('b')
choice_two.append('r')
print(min(dist(a, choice_one), dist(a, choice_two)))
```
No
| 7,170 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.
Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches.
The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.
Output
Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.
Examples
Input
5
rbbrr
Output
1
Input
5
bbbbb
Output
2
Input
3
rbr
Output
0
Note
In the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.
In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.
In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.
Submitted Solution:
```
n=int(input())
ss=input()
s=list(ss)
c=0
o=0
for i in range(1,n):
if s[i]==s[i-1]:
if s[i]=='b':
s[i]='r'
else:
s[i]='b'
if c:
c=0
else:
c=1
o+=1
else:
c=0
o1=0
s=list(ss)
t=s[0]
s[0]=s[1]
s[1]=t
for i in range(1,n):
if s[i]==s[i-1]:
if s[i]=='b':
s[i]='r'
else:
s[i]='b'
if c:
c=0
else:
c=1
o1+=1
else:
c=0
o=min(o,o1)
print(o)
```
No
| 7,171 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.
Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.
Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches.
The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.
Output
Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.
Examples
Input
5
rbbrr
Output
1
Input
5
bbbbb
Output
2
Input
3
rbr
Output
0
Note
In the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.
In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.
In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.
Submitted Solution:
```
n=int(input())
S=input()
p=S[0]
k=0
for i in range(1,n-1) :
if S[i]==p :
if S[i+1]==p :
k=k+1
if p=='r' :
p='b'
else :
p='r'
else :
k=k+1
else :
p=S[i]
print(k)
```
No
| 7,172 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Timofey has a big tree — an undirected connected graph with n vertices and no simple cycles. He likes to walk along it. His tree is flat so when he walks along it he sees it entirely. Quite naturally, when he stands on a vertex, he sees the tree as a rooted tree with the root in this vertex.
Timofey assumes that the more non-isomorphic subtrees are there in the tree, the more beautiful the tree is. A subtree of a vertex is a subgraph containing this vertex and all its descendants. You should tell Timofey the vertex in which he should stand to see the most beautiful rooted tree.
Subtrees of vertices u and v are isomorphic if the number of children of u equals the number of children of v, and their children can be arranged in such a way that the subtree of the first son of u is isomorphic to the subtree of the first son of v, the subtree of the second son of u is isomorphic to the subtree of the second son of v, and so on. In particular, subtrees consisting of single vertex are isomorphic to each other.
Input
First line contains single integer n (1 ≤ n ≤ 105) — number of vertices in the tree.
Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ 105, ui ≠ vi), denoting the vertices the i-th edge connects.
It is guaranteed that the given graph is a tree.
Output
Print single integer — the index of the vertex in which Timofey should stand. If there are many answers, you can print any of them.
Examples
Input
3
1 2
2 3
Output
1
Input
7
1 2
4 2
2 3
5 6
6 7
3 7
Output
1
Input
10
1 7
1 8
9 4
5 1
9 2
3 5
10 6
10 9
5 10
Output
2
Note
In the first example we can stand in the vertex 1 or in the vertex 3 so that every subtree is non-isomorphic. If we stand in the vertex 2, then subtrees of vertices 1 and 3 are isomorphic.
In the second example, if we stand in the vertex 1, then only subtrees of vertices 4 and 5 are isomorphic.
In the third example, if we stand in the vertex 1, then subtrees of vertices 2, 3, 4, 6, 7 and 8 are isomorphic. If we stand in the vertex 2, than only subtrees of vertices 3, 4, 6, 7 and 8 are isomorphic. If we stand in the vertex 5, then subtrees of vertices 2, 3, 4, 6, 7 and 8 are isomorphic, and subtrees of vertices 1 and 9 are isomorphic as well:
1 9
/\ /\
7 8 4 2
Submitted Solution:
```
from random import randint
mod1 = 10**9 + 7
def hashing_dfs(v,deep, adj_list,rfd,_hash):
if len(adj_list[v]) == 0:
return 0
h = 1
set_hsh = []
for u in adj_list[v]:
if deep[u] == -1:
deep[u] = deep[v] + 1
h = max( h , hashing_dfs(u,deep,adj_list,rfd,_hash))
set_hsh.append(_hash[u])
if rfd[h] == -1:
rfd[h] = randint(1,mod1)
for value in set_hsh:
_hash[v] = (_hash[v] * (rfd[h] + value)) % mod1
return h
def min_isomorphic_tree(n,adj_list):
randix = 0
mic = n # min isomorphic counter
for v in range(1,n + 1):
_hash, deep, rfd = [1] * (n + 1), [-1] * (n + 1), [-1] * n
deep[v] = 0
hashing_dfs(v,deep,adj_list,rfd,_hash)
_hash.sort()
count = 0
for i in range( 1,n ):
count = count + (_hash[i] == _hash[i + 1])
if mic > count + (count != 0):
mic = count + (count != 0)
randix = v
print(randix)
```
No
| 7,173 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
<image>
The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.
Input
The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).
The second line contains two integers c and d (1 ≤ c, d ≤ 100).
Output
Print the first time Rick and Morty will scream at the same time, or - 1 if they will never scream at the same time.
Examples
Input
20 2
9 19
Output
82
Input
2 1
16 12
Output
-1
Note
In the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82.
In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.
Tags: brute force, math, number theory
Correct Solution:
```
# -*- coding: utf-8 -*-
a, b = map(int, input().split(' '))
c, d = map(int, input().split(' '))
if d < b:
x = b
b = d
d = x
x = a
a = c
c = x
k = 1
r = -1
while k < 100000:
n = (d-b+c*(k-1))/a+1
if n == int(n):
n = int(n)
r = b+a*(n-1)
break
k += 1
print(r)
```
| 7,174 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
<image>
The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.
Input
The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).
The second line contains two integers c and d (1 ≤ c, d ≤ 100).
Output
Print the first time Rick and Morty will scream at the same time, or - 1 if they will never scream at the same time.
Examples
Input
20 2
9 19
Output
82
Input
2 1
16 12
Output
-1
Note
In the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82.
In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.
Tags: brute force, math, number theory
Correct Solution:
```
a, b = map(int, input().split())
c, d = map(int, input().split())
for i in range(max(max(a, b), max(c, d)) + 1):
if a * i + b - d >= 0 and (a * i + b - d) % c == 0:
print(a * i + b)
exit()
print(-1)
```
| 7,175 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
<image>
The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.
Input
The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).
The second line contains two integers c and d (1 ≤ c, d ≤ 100).
Output
Print the first time Rick and Morty will scream at the same time, or - 1 if they will never scream at the same time.
Examples
Input
20 2
9 19
Output
82
Input
2 1
16 12
Output
-1
Note
In the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82.
In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.
Tags: brute force, math, number theory
Correct Solution:
```
from math import gcd
def main():
a, b = map(int, input().split())
c, d = map(int, input().split())
n = a * c // gcd(a, c) + b + d
l = [*[0] * n, 2]
for i in range(b, n, a):
l[i] = 1
for i in range(d, n, c):
l[i] += 1
i = l.index(2)
print(i if i < n else -1)
if __name__ == '__main__':
main()
```
| 7,176 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
<image>
The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.
Input
The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).
The second line contains two integers c and d (1 ≤ c, d ≤ 100).
Output
Print the first time Rick and Morty will scream at the same time, or - 1 if they will never scream at the same time.
Examples
Input
20 2
9 19
Output
82
Input
2 1
16 12
Output
-1
Note
In the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82.
In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.
Tags: brute force, math, number theory
Correct Solution:
```
g=lambda x,y:g(y,x%y)if y else x
a,b=map(int,input().split())
c,d=map(int,input().split())
e=g(a,c)
if (b-d)% e:print(-1)
else:
while b!=d:
if b<d:b+=a
else:d+=c
print(b)
```
| 7,177 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
<image>
The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.
Input
The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).
The second line contains two integers c and d (1 ≤ c, d ≤ 100).
Output
Print the first time Rick and Morty will scream at the same time, or - 1 if they will never scream at the same time.
Examples
Input
20 2
9 19
Output
82
Input
2 1
16 12
Output
-1
Note
In the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82.
In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.
Tags: brute force, math, number theory
Correct Solution:
```
a, b = map(int, input().split())
c, d = map(int, input().split())
ans = -1
for i in range(100000):
if b == d:
ans = b
break
elif b < d:
b += a
else:
d += c
print(ans)
```
| 7,178 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
<image>
The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.
Input
The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).
The second line contains two integers c and d (1 ≤ c, d ≤ 100).
Output
Print the first time Rick and Morty will scream at the same time, or - 1 if they will never scream at the same time.
Examples
Input
20 2
9 19
Output
82
Input
2 1
16 12
Output
-1
Note
In the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82.
In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.
Tags: brute force, math, number theory
Correct Solution:
```
ab = list(map(int, input().split()))
a = ab[0]
b = ab[1]
cd = list(map(int, input().split()))
c = cd[0]
d = cd[1]
num_list = []
if b == d:
print(b)
elif a > c:
for i in range(max(c, d // a + 1)):
num_list.append(a * i + b)
for i in num_list:
if (i - d) % c == 0 and i - d >= 0:
print(i)
break
if num_list.index(i) == len(num_list) - 1:
print(-1)
break
elif a < c:
for i in range(max(a, b // c + 1)):
num_list.append(c * i + d)
for i in num_list:
if (i - b) % a == 0 and i - b >= 0:
print(i)
break
if num_list.index(i) == len(num_list) - 1:
print(-1)
break
elif a == c:
if (max(b, d) - min(b, d)) % a == 0:
print(max(b, d))
else:
print(-1)
```
| 7,179 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
<image>
The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.
Input
The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).
The second line contains two integers c and d (1 ≤ c, d ≤ 100).
Output
Print the first time Rick and Morty will scream at the same time, or - 1 if they will never scream at the same time.
Examples
Input
20 2
9 19
Output
82
Input
2 1
16 12
Output
-1
Note
In the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82.
In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.
Tags: brute force, math, number theory
Correct Solution:
```
a, b = map(int, input().split())
c, d = map(int, input().split())
if b == d:
print(b)
else:
s = set()
for i in range(0, 101):
s.add(b + a * i)
for i in range(0, 101):
temp = d + c * i
if temp in s:
print(temp)
exit(0)
print(-1)
```
| 7,180 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
<image>
The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.
Input
The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).
The second line contains two integers c and d (1 ≤ c, d ≤ 100).
Output
Print the first time Rick and Morty will scream at the same time, or - 1 if they will never scream at the same time.
Examples
Input
20 2
9 19
Output
82
Input
2 1
16 12
Output
-1
Note
In the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82.
In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.
Tags: brute force, math, number theory
Correct Solution:
```
a, b = [int(i) for i in input().split()]
c, d = [int(i) for i in input().split()]
res = [0 for i in range(10000000)]
for i in range(10000):
res[int(b + a*i)] = 1
for i in range(10000):
if res[d + c*i] == 1:
print(d+c*i)
exit()
print(-1)
```
| 7,181 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
<image>
The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.
Input
The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).
The second line contains two integers c and d (1 ≤ c, d ≤ 100).
Output
Print the first time Rick and Morty will scream at the same time, or - 1 if they will never scream at the same time.
Examples
Input
20 2
9 19
Output
82
Input
2 1
16 12
Output
-1
Note
In the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82.
In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.
Submitted Solution:
```
a,b=map(int,input().split())
c,d=map(int,input().split())
if b==d:
print(b)
else:
if b<d:
b+=((d-b)//a)*a
for i in range(200):
if (b+i*a-d)%c==0:
print(b+i*a)
break
else:
print(-1)
```
Yes
| 7,182 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
<image>
The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.
Input
The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).
The second line contains two integers c and d (1 ≤ c, d ≤ 100).
Output
Print the first time Rick and Morty will scream at the same time, or - 1 if they will never scream at the same time.
Examples
Input
20 2
9 19
Output
82
Input
2 1
16 12
Output
-1
Note
In the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82.
In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.
Submitted Solution:
```
def gcd(a, b):
return a if b==0 else gcd(b, a%b)
a, b = map(int, input().split())
c, d = map(int, input().split())
g = gcd(a, c)
dif = abs(b-d)
if dif%g==0:
for t in range(max(b, d), 1000000):
if (t-b)%a==0 and (t-d)%c==0:
print(t)
break
else:
print(-1)
```
Yes
| 7,183 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
<image>
The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.
Input
The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).
The second line contains two integers c and d (1 ≤ c, d ≤ 100).
Output
Print the first time Rick and Morty will scream at the same time, or - 1 if they will never scream at the same time.
Examples
Input
20 2
9 19
Output
82
Input
2 1
16 12
Output
-1
Note
In the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82.
In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.
Submitted Solution:
```
a,b=map(int,input().split())
s=0
c,d=map(int,input().split())
flag=0
while(d!=b):
if(s==100000):
print(-1)
b=d
flag=1
if(d<b):
d+=max(c*((b-d)//c),c)
else:
b+=max(a*((d-b)//a),a)
s+=1
if(flag==0):
print(b)
```
Yes
| 7,184 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
<image>
The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.
Input
The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).
The second line contains two integers c and d (1 ≤ c, d ≤ 100).
Output
Print the first time Rick and Morty will scream at the same time, or - 1 if they will never scream at the same time.
Examples
Input
20 2
9 19
Output
82
Input
2 1
16 12
Output
-1
Note
In the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82.
In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.
Submitted Solution:
```
a, b = input().split()
c, d = input().split()
a, b, c, d = (int(x) for x in (a, b, c, d))
Rick = {(b + a * x) for x in range(1000005)}
Morty = {(d + c * x) for x in range(1000005)}
moments = Rick.intersection(Morty)
if len(moments)==0:
print(-1)
else:
print(min(moments))
```
Yes
| 7,185 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
<image>
The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.
Input
The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).
The second line contains two integers c and d (1 ≤ c, d ≤ 100).
Output
Print the first time Rick and Morty will scream at the same time, or - 1 if they will never scream at the same time.
Examples
Input
20 2
9 19
Output
82
Input
2 1
16 12
Output
-1
Note
In the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82.
In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.
Submitted Solution:
```
b,a=map(int,input().split(' '))
d,c=map(int,input().split(' '))
r=-1
if(b>=d):
while(b>=d):
if(b==d):
r=b
b+=a
d+=c
else:
while(d>=b):
if(b==d):
r=b
b+=a
d+=c
print(str(r))
```
No
| 7,186 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
<image>
The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.
Input
The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).
The second line contains two integers c and d (1 ≤ c, d ≤ 100).
Output
Print the first time Rick and Morty will scream at the same time, or - 1 if they will never scream at the same time.
Examples
Input
20 2
9 19
Output
82
Input
2 1
16 12
Output
-1
Note
In the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82.
In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.
Submitted Solution:
```
a,b = map(int,input().split())
c,d = map(int,input().split())
def rick(a,b,r):
return b+a*r
def morty(c,d,r):
return d+c*r
if (b%2 == 0 and d%2 != 0) or (b%2 != 0 and d%2 == 0):
print(-1)
else:
i = 0
j = 0
while True:
if rick(a,b,i) < morty(c,d,j):
i+=1
elif rick(a,b,i) > morty(c,d,j):
j+=1
else:
print(rick(a,b,i))
break
```
No
| 7,187 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
<image>
The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.
Input
The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).
The second line contains two integers c and d (1 ≤ c, d ≤ 100).
Output
Print the first time Rick and Morty will scream at the same time, or - 1 if they will never scream at the same time.
Examples
Input
20 2
9 19
Output
82
Input
2 1
16 12
Output
-1
Note
In the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82.
In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.
Submitted Solution:
```
R = lambda:map(int, input().split())
a, b = R()
c, d = R()
s = set(range(b, 100**2, a)) and set(range(d, 100*2, c))
print(min(s) if s else -1)
```
No
| 7,188 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
<image>
The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.
Input
The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).
The second line contains two integers c and d (1 ≤ c, d ≤ 100).
Output
Print the first time Rick and Morty will scream at the same time, or - 1 if they will never scream at the same time.
Examples
Input
20 2
9 19
Output
82
Input
2 1
16 12
Output
-1
Note
In the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82.
In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.
Submitted Solution:
```
import sys
from fractions import gcd
from math import floor
def egcd(b, n):
x0, x1, y0, y1 = 1, 0, 0, 1
while n != 0:
q, b, n = b // n, n, b % n
x0, x1 = x1, x0 - q * x1
y0, y1 = y1, y0 - q * y1
return b, x0, y0
def ans(rst):
print(rst)
sys.exit(0)
a, b = tuple(map(int, input().split()))
c, d = tuple(map(int, input().split()))
if a > c:
a, c = c, a
b, d = d, b
g, v, u = egcd(a, c)
print(g, u, v)
C = b - d + c - a
if C % g != 0:
ans(-1)
else:
t = max(floor(-C / c * u), floor(-C / a * v)) + 1
X = C / g * u + t * c / g
print(C, t, X)
ans(int(b + (X - 1) * a))
# if c == a:
# if b == d:
# ans(b)
# else:
# ans(-1)
# t = (d - b) / (a - c)
# if t.is_integer() and t > 0:
# ans(int(t))
# else:
# ans(-1)
```
No
| 7,189 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After several latest reforms many tourists are planning to visit Berland, and Berland people understood that it's an opportunity to earn money and changed their jobs to attract tourists. Petya, for example, left the IT corporation he had been working for and started to sell souvenirs at the market.
This morning, as usual, Petya will come to the market. Petya has n different souvenirs to sell; ith souvenir is characterised by its weight wi and cost ci. Petya knows that he might not be able to carry all the souvenirs to the market. So Petya wants to choose a subset of souvenirs such that its total weight is not greater than m, and total cost is maximum possible.
Help Petya to determine maximum possible total cost.
Input
The first line contains two integers n and m (1 ≤ n ≤ 100000, 1 ≤ m ≤ 300000) — the number of Petya's souvenirs and total weight that he can carry to the market.
Then n lines follow. ith line contains two integers wi and ci (1 ≤ wi ≤ 3, 1 ≤ ci ≤ 109) — the weight and the cost of ith souvenir.
Output
Print one number — maximum possible total cost of souvenirs that Petya can carry to the market.
Examples
Input
1 1
2 1
Output
0
Input
2 2
1 3
2 2
Output
3
Input
4 3
3 10
2 7
2 8
1 1
Output
10
Tags: binary search, dp, greedy, ternary search
Correct Solution:
```
def main():
n, m = map(int, input().split())
cost1 = []
cost2 = []
cost3 = []
for i in range(n):
w, c = map(int, input().split())
if w == 1:
cost1.append(c)
elif w == 2:
cost2.append(c)
else:
cost3.append(c)
cost1 = sorted(cost1)[::-1]
cost2 = sorted(cost2)[::-1]
cost3 = sorted(cost3)[::-1]
cost3_prefix = [0]
for c in cost3:
cost3_prefix.append(cost3_prefix[-1] + c)
dp = [(0, 0, 0)] * (m + 1)
dp[0] = (0, 0, 0)
for i in range(0, m):
cost, n1, n2 = dp[i]
if i + 1 <= m and n1 < len(cost1):
new_cost = cost + cost1[n1]
if dp[i + 1][0] < new_cost:
dp[i + 1] = (new_cost, n1 + 1, n2)
if i + 2 <= m and n2 < len(cost2):
new_cost = cost + cost2[n2]
if dp[i + 2][0] < new_cost:
dp[i + 2] = (new_cost, n1, n2 + 1)
if n1 == len(cost1) and n2 == len(cost2):
break
dp_prefix = [0]
for x in dp[1:]:
dp_prefix.append(max(dp_prefix[-1], x[0]))
ans = 0
for k in range(len(cost3) + 1):
l = m - 3 * k
if l < 0:
continue
new_ans = cost3_prefix[k] + dp_prefix[l]
ans = max(new_ans, ans)
print(ans)
if __name__ == '__main__':
main()
```
| 7,190 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After several latest reforms many tourists are planning to visit Berland, and Berland people understood that it's an opportunity to earn money and changed their jobs to attract tourists. Petya, for example, left the IT corporation he had been working for and started to sell souvenirs at the market.
This morning, as usual, Petya will come to the market. Petya has n different souvenirs to sell; ith souvenir is characterised by its weight wi and cost ci. Petya knows that he might not be able to carry all the souvenirs to the market. So Petya wants to choose a subset of souvenirs such that its total weight is not greater than m, and total cost is maximum possible.
Help Petya to determine maximum possible total cost.
Input
The first line contains two integers n and m (1 ≤ n ≤ 100000, 1 ≤ m ≤ 300000) — the number of Petya's souvenirs and total weight that he can carry to the market.
Then n lines follow. ith line contains two integers wi and ci (1 ≤ wi ≤ 3, 1 ≤ ci ≤ 109) — the weight and the cost of ith souvenir.
Output
Print one number — maximum possible total cost of souvenirs that Petya can carry to the market.
Examples
Input
1 1
2 1
Output
0
Input
2 2
1 3
2 2
Output
3
Input
4 3
3 10
2 7
2 8
1 1
Output
10
Tags: binary search, dp, greedy, ternary search
Correct Solution:
```
import sys
from itertools import accumulate
n, m = map(int, sys.stdin.buffer.readline().decode('utf-8').split())
items = [[], [], [], []]
for w, c in (map(int, line.decode('utf-8').split()) for line in sys.stdin.buffer):
items[w].append(c)
for i in range(1, 4):
items[i].sort(reverse=True)
n_w1, n_w2 = len(items[1]), len(items[2])
dp = [0]*(m+3)
dp_w1, dp_w2 = [0]*(m+3), [0]*(m+3)
for i in range(m+1):
if i > 0 and dp[i-1] > dp[i]:
dp[i] = dp[i-1]
dp_w1[i], dp_w2[i] = dp_w1[i-1], dp_w2[i-1]
if dp_w1[i] < n_w1 and dp[i+1] < dp[i] + items[1][dp_w1[i]]:
dp[i+1] = dp[i] + items[1][dp_w1[i]]
dp_w1[i+1] = dp_w1[i] + 1
dp_w2[i+1] = dp_w2[i]
if dp_w2[i] < n_w2 and dp[i+2] < dp[i] + items[2][dp_w2[i]]:
dp[i+2] = dp[i] + items[2][dp_w2[i]]
dp_w1[i+2] = dp_w1[i]
dp_w2[i+2] = dp_w2[i] + 1
items[3] = [0] + list(accumulate(items[3]))
ans = 0
for i in range(len(items[3])):
if i*3 > m:
break
ans = max(ans, items[3][i] + dp[m - i*3])
print(ans)
```
| 7,191 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After several latest reforms many tourists are planning to visit Berland, and Berland people understood that it's an opportunity to earn money and changed their jobs to attract tourists. Petya, for example, left the IT corporation he had been working for and started to sell souvenirs at the market.
This morning, as usual, Petya will come to the market. Petya has n different souvenirs to sell; ith souvenir is characterised by its weight wi and cost ci. Petya knows that he might not be able to carry all the souvenirs to the market. So Petya wants to choose a subset of souvenirs such that its total weight is not greater than m, and total cost is maximum possible.
Help Petya to determine maximum possible total cost.
Input
The first line contains two integers n and m (1 ≤ n ≤ 100000, 1 ≤ m ≤ 300000) — the number of Petya's souvenirs and total weight that he can carry to the market.
Then n lines follow. ith line contains two integers wi and ci (1 ≤ wi ≤ 3, 1 ≤ ci ≤ 109) — the weight and the cost of ith souvenir.
Output
Print one number — maximum possible total cost of souvenirs that Petya can carry to the market.
Examples
Input
1 1
2 1
Output
0
Input
2 2
1 3
2 2
Output
3
Input
4 3
3 10
2 7
2 8
1 1
Output
10
Tags: binary search, dp, greedy, ternary search
Correct Solution:
```
import sys
from itertools import accumulate
def solve():
n, m = map(int, input().split())
w = [[] for i in range(3)]
for i in range(n):
wi, ci = map(int, sys.stdin.readline().split())
wi -= 1
w[wi].append(ci)
for i in range(3):
w[i].sort(reverse=True)
dp = [0]*(m + 1)
used = [[0]*2 for i in range(m + 1)]
s0 = len(w[0])
s1 = len(w[1])
if s0 > 0:
dp[1] = w[0][0]
used[1] = [1, 0]
for i in range(2, m + 1):
if used[i - 1][0] < s0:
dp[i] = dp[i - 1] + w[0][used[i - 1][0]]
used[i] = used[i - 1][:]
used[i][0] += 1
else:
dp[i] = dp[i - 1]
used[i] = used[i - 1][:]
if used[i - 2][1] < s1 and dp[i] < dp[i - 2] + w[1][used[i - 2][1]]:
dp[i] = dp[i - 2] + w[1][used[i - 2][1]]
used[i] = used[i - 2][:]
used[i][1] += 1
pf = [0] + list(accumulate(w[2]))
ans = max(pf[k] + dp[m - 3*k] for k in range(min(len(pf),m // 3 + 1)))
print(ans)
if __name__ == '__main__':
solve()
```
| 7,192 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After several latest reforms many tourists are planning to visit Berland, and Berland people understood that it's an opportunity to earn money and changed their jobs to attract tourists. Petya, for example, left the IT corporation he had been working for and started to sell souvenirs at the market.
This morning, as usual, Petya will come to the market. Petya has n different souvenirs to sell; ith souvenir is characterised by its weight wi and cost ci. Petya knows that he might not be able to carry all the souvenirs to the market. So Petya wants to choose a subset of souvenirs such that its total weight is not greater than m, and total cost is maximum possible.
Help Petya to determine maximum possible total cost.
Input
The first line contains two integers n and m (1 ≤ n ≤ 100000, 1 ≤ m ≤ 300000) — the number of Petya's souvenirs and total weight that he can carry to the market.
Then n lines follow. ith line contains two integers wi and ci (1 ≤ wi ≤ 3, 1 ≤ ci ≤ 109) — the weight and the cost of ith souvenir.
Output
Print one number — maximum possible total cost of souvenirs that Petya can carry to the market.
Examples
Input
1 1
2 1
Output
0
Input
2 2
1 3
2 2
Output
3
Input
4 3
3 10
2 7
2 8
1 1
Output
10
Tags: binary search, dp, greedy, ternary search
Correct Solution:
```
n,m = map(int,input().split())
a = [[],[],[]]
for _ in range(n):
x,y = map(int,input().split())
a[x-1].append(y)
for i in range(3):
a[i].sort(reverse=True)
a_one_odd = []
a_one_even = []
a_length = [len(a[i]) for i in range(3)]
for i in range(0,a_length[0]-1,2):
a_one_even.append(a[0][i]+a[0][i+1])
for i in range(1,a_length[0]-1,2):
a_one_odd.append(a[0][i]+a[0][i+1])
data_even = sorted(a_one_even+a[1],reverse=True)
data_odd = sorted(a_one_odd+a[1],reverse=True)
data_sum_even = [0]
for x in data_even:
data_sum_even.append(data_sum_even[-1]+x)
data_sum_odd = [0]
for x in data_odd:
data_sum_odd.append(data_sum_odd[-1]+x)
data_sum_three = [0]
for x in a[2]:
data_sum_three.append(data_sum_three[-1]+x)
ans = 0
#print(data_sum_odd,data_sum_even,data_sum_three)
for k in range(a_length[2]+1):
if m-3*k < 0:break
now1,now2 = data_sum_three[k],data_sum_three[k]
if (m-3*k)%2== 0:
now1 += data_sum_even[min((m-3*k)//2,len(data_sum_even)-1)]
if a_length[0] > 0 and m-3*k > 0:
now2 += a[0][0]
if (m-3*k)//2 >= 1:
now2 += data_sum_odd[min((m-3*k)//2-1,len(data_sum_odd)-1)]
else:
now1 += data_sum_even[min((m-3*k)//2,len(data_sum_even)-1)]
if a_length[0] > 0 and m-3*k > 0:
now2 += a[0][0]
now2 += data_sum_odd[min((m-3*k-1)//2,len(data_sum_odd)-1)]
ans = max(ans,now1,now2)
print(ans)
```
| 7,193 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After several latest reforms many tourists are planning to visit Berland, and Berland people understood that it's an opportunity to earn money and changed their jobs to attract tourists. Petya, for example, left the IT corporation he had been working for and started to sell souvenirs at the market.
This morning, as usual, Petya will come to the market. Petya has n different souvenirs to sell; ith souvenir is characterised by its weight wi and cost ci. Petya knows that he might not be able to carry all the souvenirs to the market. So Petya wants to choose a subset of souvenirs such that its total weight is not greater than m, and total cost is maximum possible.
Help Petya to determine maximum possible total cost.
Input
The first line contains two integers n and m (1 ≤ n ≤ 100000, 1 ≤ m ≤ 300000) — the number of Petya's souvenirs and total weight that he can carry to the market.
Then n lines follow. ith line contains two integers wi and ci (1 ≤ wi ≤ 3, 1 ≤ ci ≤ 109) — the weight and the cost of ith souvenir.
Output
Print one number — maximum possible total cost of souvenirs that Petya can carry to the market.
Examples
Input
1 1
2 1
Output
0
Input
2 2
1 3
2 2
Output
3
Input
4 3
3 10
2 7
2 8
1 1
Output
10
Tags: binary search, dp, greedy, ternary search
Correct Solution:
```
def f():
n, m = map(int, input().split())
l = list(tuple(map(int, input().split())) for _ in range(n))
l.sort(key=lambda e: (0, 6, 3, 2)[e[0]] * e[1], reverse=True)
last, r = [0] * 4, 0
for i, (w, c) in enumerate(l):
if m < w:
break
m -= w
r += c
last[w] = c
else:
return r
if not m:
return r
res, tail = [r], (None, [], [], [])
for w, c in l[i:]:
tail[w].append(c)
for w in 1, 2, 3:
tail[w].append(0)
_, t1, t2, t3 = tail
if m == 1:
res.append(r + t1[0])
if last[1]:
res.append(r - last[1] + t2[0])
if last[2]:
res.append(r - last[2] + t3[0])
if last[3]:
r -= last[3]
res += (r + sum(t1[:4]), r + sum(t1[:2]) + t2[0], r + sum(t2[:2]))
else: # m == 2
res += (r + sum(t1[:2]), r + t2[0])
if last[1]:
res.append(r - last[1] + t3[0])
if last[2]:
res.append(r - last[2] + t3[0] + t1[0])
return max(res)
def main():
print(f())
if __name__ == '__main__':
main()
```
| 7,194 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After several latest reforms many tourists are planning to visit Berland, and Berland people understood that it's an opportunity to earn money and changed their jobs to attract tourists. Petya, for example, left the IT corporation he had been working for and started to sell souvenirs at the market.
This morning, as usual, Petya will come to the market. Petya has n different souvenirs to sell; ith souvenir is characterised by its weight wi and cost ci. Petya knows that he might not be able to carry all the souvenirs to the market. So Petya wants to choose a subset of souvenirs such that its total weight is not greater than m, and total cost is maximum possible.
Help Petya to determine maximum possible total cost.
Input
The first line contains two integers n and m (1 ≤ n ≤ 100000, 1 ≤ m ≤ 300000) — the number of Petya's souvenirs and total weight that he can carry to the market.
Then n lines follow. ith line contains two integers wi and ci (1 ≤ wi ≤ 3, 1 ≤ ci ≤ 109) — the weight and the cost of ith souvenir.
Output
Print one number — maximum possible total cost of souvenirs that Petya can carry to the market.
Examples
Input
1 1
2 1
Output
0
Input
2 2
1 3
2 2
Output
3
Input
4 3
3 10
2 7
2 8
1 1
Output
10
Tags: binary search, dp, greedy, ternary search
Correct Solution:
```
#Bhargey Mehta (Sophomore)
#DA-IICT, Gandhinagar
import sys, math, queue, bisect
#sys.stdin = open("input.txt", "r")
MOD = 10**9+7
sys.setrecursionlimit(1000000)
n, m = map(int, input().split())
c1, c2, c3 = [0], [0], [0]
for _ in range(n):
x, y = map(int, input().split())
if x == 3:
c3.append(y)
elif x == 2:
c2.append(y)
else:
c1.append(y)
c1.sort(reverse=True)
c2.sort(reverse=True)
c3.sort(reverse=True)
dp = [None for i in range(m+1)]
dp[0] = (0, 0, 0)
dp[1] = (c1[0], 1, 0)
for i in range(2, m+1):
if dp[i-1][1] == len(c1):
x1 = (dp[i-1][0], dp[i-1][1], dp[i-1][2])
else:
x1 = (dp[i-1][0]+c1[dp[i-1][1]], dp[i-1][1]+1, dp[i-1][2])
if dp[i-2][2] == len(c2):
x2 = (dp[i-2][0], dp[i-2][1], dp[i-2][2])
else:
x2 = (dp[i-2][0]+c2[dp[i-2][2]], dp[i-2][1], dp[i-2][2]+1)
if x1[0] > x2[0]:
dp[i] = x1
else:
dp[i] = x2
ans = 0
cost3 = 0
for i in range(len(c3)):
cost3 += c3[i-1]
cap = m - 3*i
if cap < 0: break
ans = max(ans, cost3+dp[cap][0])
print(ans)
```
| 7,195 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After several latest reforms many tourists are planning to visit Berland, and Berland people understood that it's an opportunity to earn money and changed their jobs to attract tourists. Petya, for example, left the IT corporation he had been working for and started to sell souvenirs at the market.
This morning, as usual, Petya will come to the market. Petya has n different souvenirs to sell; ith souvenir is characterised by its weight wi and cost ci. Petya knows that he might not be able to carry all the souvenirs to the market. So Petya wants to choose a subset of souvenirs such that its total weight is not greater than m, and total cost is maximum possible.
Help Petya to determine maximum possible total cost.
Input
The first line contains two integers n and m (1 ≤ n ≤ 100000, 1 ≤ m ≤ 300000) — the number of Petya's souvenirs and total weight that he can carry to the market.
Then n lines follow. ith line contains two integers wi and ci (1 ≤ wi ≤ 3, 1 ≤ ci ≤ 109) — the weight and the cost of ith souvenir.
Output
Print one number — maximum possible total cost of souvenirs that Petya can carry to the market.
Examples
Input
1 1
2 1
Output
0
Input
2 2
1 3
2 2
Output
3
Input
4 3
3 10
2 7
2 8
1 1
Output
10
Tags: binary search, dp, greedy, ternary search
Correct Solution:
```
#!/usr/bin/env python3
[n, m] = map(int, input().strip().split())
wc = [[] for _ in range(4)] # w[0] unused
for _ in range(n):
w, c = map(int, input().strip().split())
wc[w].append(c)
for i in range(1, 4):
wc[i].sort(reverse=True)
iwc = [[0 for _ in range(len(wc[i]) + 1)] for i in range(4)]
for i in range(4):
for j in range(len(wc[i])):
iwc[i][j + 1] = iwc[i][j] + wc[i][j]
n1 = len(wc[1])
n2 = len(wc[2])
n3 = len(wc[3])
c12 = [(0, 0, 0) for _ in range(m + 1)]
for w in range(len(c12) - 1):
c, q1, q2 = c12[w]
c12[w + 1] = max(c12[w + 1], c12[w])
if q1 < n1:
c12[w + 1] = max(c12[w + 1], (iwc[1][q1 + 1] + iwc[2][q2], q1 + 1, q2))
if q2 < n2 and w + 2 < len(c12):
c12[w + 2] = max(c12[w + 2], (iwc[1][q1] + iwc[2][q2 + 1], q1, q2 + 1))
cmax = 0
for i in range(n3 + 1):
if 3 * i > m:
break
cmax = max(cmax, iwc[3][i] + c12[m - 3 * i][0])
print(cmax)
```
| 7,196 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After several latest reforms many tourists are planning to visit Berland, and Berland people understood that it's an opportunity to earn money and changed their jobs to attract tourists. Petya, for example, left the IT corporation he had been working for and started to sell souvenirs at the market.
This morning, as usual, Petya will come to the market. Petya has n different souvenirs to sell; ith souvenir is characterised by its weight wi and cost ci. Petya knows that he might not be able to carry all the souvenirs to the market. So Petya wants to choose a subset of souvenirs such that its total weight is not greater than m, and total cost is maximum possible.
Help Petya to determine maximum possible total cost.
Input
The first line contains two integers n and m (1 ≤ n ≤ 100000, 1 ≤ m ≤ 300000) — the number of Petya's souvenirs and total weight that he can carry to the market.
Then n lines follow. ith line contains two integers wi and ci (1 ≤ wi ≤ 3, 1 ≤ ci ≤ 109) — the weight and the cost of ith souvenir.
Output
Print one number — maximum possible total cost of souvenirs that Petya can carry to the market.
Examples
Input
1 1
2 1
Output
0
Input
2 2
1 3
2 2
Output
3
Input
4 3
3 10
2 7
2 8
1 1
Output
10
Tags: binary search, dp, greedy, ternary search
Correct Solution:
```
import sys
n, m = map(int, input().split())
w1 = []
w2 = []
w3 = [10**10]
for w, c in (map(int, l.split()) for l in sys.stdin):
if w == 1:
w1.append(c)
elif w == 2:
w2.append(c)
else:
w3.append(c)
w1.sort(reverse=True)
w2.sort(reverse=True)
w3.sort(reverse=True)
w3[0] = 0
w1_size, w2_size = len(w1), len(w2)
dp = [(0, 0, 0) for _ in range(m+3)]
for i in range(m):
dp[i+1] = max(dp[i+1], dp[i])
if dp[i][1] < w1_size:
dp[i+1] = max(dp[i+1], (dp[i][0]+w1[dp[i][1]], dp[i][1]+1, dp[i][2]))
if dp[i][2] < w2_size:
dp[i+2] = max(dp[i+2], (dp[i][0]+w2[dp[i][2]], dp[i][1], dp[i][2]+1))
ans = 0
w3_c = 0
for i in range(len(w3)):
if i*3 > m:
continue
w3_c += w3[i]
ans = max(ans, w3_c + dp[m-i*3][0])
print(ans)
```
| 7,197 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After several latest reforms many tourists are planning to visit Berland, and Berland people understood that it's an opportunity to earn money and changed their jobs to attract tourists. Petya, for example, left the IT corporation he had been working for and started to sell souvenirs at the market.
This morning, as usual, Petya will come to the market. Petya has n different souvenirs to sell; ith souvenir is characterised by its weight wi and cost ci. Petya knows that he might not be able to carry all the souvenirs to the market. So Petya wants to choose a subset of souvenirs such that its total weight is not greater than m, and total cost is maximum possible.
Help Petya to determine maximum possible total cost.
Input
The first line contains two integers n and m (1 ≤ n ≤ 100000, 1 ≤ m ≤ 300000) — the number of Petya's souvenirs and total weight that he can carry to the market.
Then n lines follow. ith line contains two integers wi and ci (1 ≤ wi ≤ 3, 1 ≤ ci ≤ 109) — the weight and the cost of ith souvenir.
Output
Print one number — maximum possible total cost of souvenirs that Petya can carry to the market.
Examples
Input
1 1
2 1
Output
0
Input
2 2
1 3
2 2
Output
3
Input
4 3
3 10
2 7
2 8
1 1
Output
10
Submitted Solution:
```
import sys
import bisect
from bisect import bisect_left as lb
input_=lambda: sys.stdin.readline().strip("\r\n")
from math import log
from math import gcd
from math import atan2,acos
from random import randint
sa=lambda :input_()
sb=lambda:int(input_())
sc=lambda:input_().split()
sd=lambda:list(map(int,input_().split()))
sflo=lambda:list(map(float,input_().split()))
se=lambda:float(input_())
sf=lambda:list(input_())
flsh=lambda: sys.stdout.flush()
#sys.setrecursionlimit(10**6)
mod=10**9+7
mod1=998244353
gp=[]
cost=[]
dp=[]
mx=[]
ans1=[]
ans2=[]
special=[]
specnode=[]
a=0
kthpar=[]
def dfs(root,par):
if par!=-1:
dp[root]=dp[par]+1
for i in range(1,20):
if kthpar[root][i-1]!=-1:
kthpar[root][i]=kthpar[kthpar[root][i-1]][i-1]
for child in gp[root]:
if child==par:continue
kthpar[child][0]=root
dfs(child,root)
ans=0
b=[]
def hnbhai(tc):
n,m=sd()
dp=[(0,0,0) for i in range(m+3)]
gp=[[] for i in range(4)]
for i in range(n):
w,c=sd()
gp[w].append(c)
gp[1].sort(reverse=True)
gp[2].sort(reverse=True)
gp[3].sort(reverse=True)
for i in range(0,m+1):
one=dp[i][1]
two=dp[i][2]
if one<len(gp[1]):
if dp[i+1][0]<dp[i][0]+gp[1][one]:
dp[i+1]=(dp[i][0]+gp[1][one],one+1,two)
if two<len(gp[2]):
dp[i+2]=(dp[i][0]+gp[2][two],one,two+1)
for i in range(1,m+1):
dp[i]=max(dp[i-1],dp[i])
#print(dp)
ans=dp[m][0]
tot=0
for i in range(len(gp[3])+1):
if 3*i<=m:
ans=max(dp[m-3*(i)][0]+tot,ans)
if i<len(gp[3]):
tot+=gp[3][i]
print(ans)
for _ in range(1):
hnbhai(_+1)
```
Yes
| 7,198 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After several latest reforms many tourists are planning to visit Berland, and Berland people understood that it's an opportunity to earn money and changed their jobs to attract tourists. Petya, for example, left the IT corporation he had been working for and started to sell souvenirs at the market.
This morning, as usual, Petya will come to the market. Petya has n different souvenirs to sell; ith souvenir is characterised by its weight wi and cost ci. Petya knows that he might not be able to carry all the souvenirs to the market. So Petya wants to choose a subset of souvenirs such that its total weight is not greater than m, and total cost is maximum possible.
Help Petya to determine maximum possible total cost.
Input
The first line contains two integers n and m (1 ≤ n ≤ 100000, 1 ≤ m ≤ 300000) — the number of Petya's souvenirs and total weight that he can carry to the market.
Then n lines follow. ith line contains two integers wi and ci (1 ≤ wi ≤ 3, 1 ≤ ci ≤ 109) — the weight and the cost of ith souvenir.
Output
Print one number — maximum possible total cost of souvenirs that Petya can carry to the market.
Examples
Input
1 1
2 1
Output
0
Input
2 2
1 3
2 2
Output
3
Input
4 3
3 10
2 7
2 8
1 1
Output
10
Submitted Solution:
```
n, m = map(int, input().split())
d = [[] for i in range(3)]
res_odd = 0
res_even = 0
for i in range(n):
t1, t2 = map(int, input().split())
d[t1 - 1].append(t2)
d[0].sort()
d[2].sort(reverse=True)
c = d[1].copy()
if d[0]:
i = len(d[0]) - 2
while i >= 1:
c.append(d[0][i] + d[0][i - 1])
i -= 2
c.sort(reverse=True)
pref = [0 for i in range(len(c) + 1)]
pref[0] = 0
for i in range(1, len(c) + 1):
pref[i] = pref[i - 1] + c[i - 1]
p = 0
for i in range(min(len(d[2]), (m - 1) // 3) + 1):
if i != 0:
p += d[2][i - 1]
res_odd = max(res_odd, d[0][-1] + p + pref[min(max(m - i * 3 - 1, 0) // 2, len(pref) - 1)])
i = len(d[0]) - 1
while i >= 1:
d[1].append(d[0][i] + d[0][i - 1])
i -= 2
d[1].sort(reverse=True)
pref = [0 for i in range(len(d[1]) + 1)]
pref[0] = 0
for i in range(1, len(d[1]) + 1):
pref[i] = pref[i - 1] + d[1][i - 1]
p = 0
for i in range(min(len(d[2]), m // 3) + 1):
if i != 0:
p += d[2][i - 1]
res_even = max(res_even, p + pref[min(max(m - i * 3, 0) // 2, len(pref) - 1)])
print(max(res_odd, res_even))
```
Yes
| 7,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.