text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.
Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.
There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.
Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of banks.
The second line contains n integers ai ( - 109 β€ ai β€ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.
Output
Print the minimum number of operations required to change balance in each bank to zero.
Examples
Input
3
5 0 -5
Output
1
Input
4
-1 0 1 0
Output
2
Input
4
1 2 3 -6
Output
3
Note
In the first sample, Vasya may transfer 5 from the first bank to the third.
In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.
In the third sample, the following sequence provides the optimal answer:
1. transfer 1 from the first bank to the second bank;
2. transfer 3 from the second bank to the third;
3. transfer 6 from the third bank to the fourth.
Tags: constructive algorithms, data structures, greedy, sortings
Correct Solution:
```
n = int(input(""))
l = input("").split(" ")
for i in range(len(l)):
l[i] = int(l[i])
s = 0
m = 0
ps = {}
for i in range(len(l)):
s += l[i]
if (s in ps):
ps[s] += 1
else:
ps[s] = 1
if (ps[s] > m):
m = ps[s]
print((n-m))
```
| 3,800 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.
Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.
There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.
Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of banks.
The second line contains n integers ai ( - 109 β€ ai β€ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.
Output
Print the minimum number of operations required to change balance in each bank to zero.
Examples
Input
3
5 0 -5
Output
1
Input
4
-1 0 1 0
Output
2
Input
4
1 2 3 -6
Output
3
Note
In the first sample, Vasya may transfer 5 from the first bank to the third.
In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.
In the third sample, the following sequence provides the optimal answer:
1. transfer 1 from the first bank to the second bank;
2. transfer 3 from the second bank to the third;
3. transfer 6 from the third bank to the fourth.
Tags: constructive algorithms, data structures, greedy, sortings
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
d = dict()
total = 0
for i in range(n):
total += a[i]
d[total] = 0
total = 0
ans = 0
for i in range(n):
total += a[i]
d[total] += 1
ans = max(ans, d[total])
print(n - ans)
```
| 3,801 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.
Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.
There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.
Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of banks.
The second line contains n integers ai ( - 109 β€ ai β€ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.
Output
Print the minimum number of operations required to change balance in each bank to zero.
Examples
Input
3
5 0 -5
Output
1
Input
4
-1 0 1 0
Output
2
Input
4
1 2 3 -6
Output
3
Note
In the first sample, Vasya may transfer 5 from the first bank to the third.
In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.
In the third sample, the following sequence provides the optimal answer:
1. transfer 1 from the first bank to the second bank;
2. transfer 3 from the second bank to the third;
3. transfer 6 from the third bank to the fourth.
Tags: constructive algorithms, data structures, greedy, sortings
Correct Solution:
```
"""
def sol(arr):
n = len(arr)
# avg = int(np.mean(arr))
# print(avg)
# for i in range(n):
# arr[i]-=avg
for i in range(n-1):
arr[i+1]+=arr[i]
res = arr.count(max(set(arr),key=arr.count))
return n-res
"""
def sol1(arr):
mp = {}
cnt = 0
n = len(arr)
ans = 0
for a in arr:
ans += a
if ans in mp:
mp[ans] += 1
else:
mp[ans] = 1
# cnt = min(cnt, n - mp[ans])
cnt = max(cnt, int(mp[ans]))
return n-cnt
n = int(input())
arr = list(map(int,input().split()))
print(sol1(arr))
```
| 3,802 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.
Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.
There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.
Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of banks.
The second line contains n integers ai ( - 109 β€ ai β€ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.
Output
Print the minimum number of operations required to change balance in each bank to zero.
Examples
Input
3
5 0 -5
Output
1
Input
4
-1 0 1 0
Output
2
Input
4
1 2 3 -6
Output
3
Note
In the first sample, Vasya may transfer 5 from the first bank to the third.
In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.
In the third sample, the following sequence provides the optimal answer:
1. transfer 1 from the first bank to the second bank;
2. transfer 3 from the second bank to the third;
3. transfer 6 from the third bank to the fourth.
Tags: constructive algorithms, data structures, greedy, sortings
Correct Solution:
```
import sys
input=sys.stdin.readline
from collections import defaultdict as dd
n=int(input())
a=list(map(int,input().split()))
d=dd(int)
sa=0
ans=10**9
for i in range(n):
sa+=a[i]
d[sa]+=1
ans=min(ans,n-d[sa])
print(ans)
```
| 3,803 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.
Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.
There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.
Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of banks.
The second line contains n integers ai ( - 109 β€ ai β€ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.
Output
Print the minimum number of operations required to change balance in each bank to zero.
Examples
Input
3
5 0 -5
Output
1
Input
4
-1 0 1 0
Output
2
Input
4
1 2 3 -6
Output
3
Note
In the first sample, Vasya may transfer 5 from the first bank to the third.
In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.
In the third sample, the following sequence provides the optimal answer:
1. transfer 1 from the first bank to the second bank;
2. transfer 3 from the second bank to the third;
3. transfer 6 from the third bank to the fourth.
Submitted Solution:
```
n = int(input())
arr = list(map(int,input().split()))
ans = n-1
sm = 0
freq = {}
for i in arr:
sm += i
freq[sm] = freq.get(sm,0)+1
ans = min(ans,n-freq[sm])
print(ans)
```
Yes
| 3,804 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.
Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.
There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.
Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of banks.
The second line contains n integers ai ( - 109 β€ ai β€ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.
Output
Print the minimum number of operations required to change balance in each bank to zero.
Examples
Input
3
5 0 -5
Output
1
Input
4
-1 0 1 0
Output
2
Input
4
1 2 3 -6
Output
3
Note
In the first sample, Vasya may transfer 5 from the first bank to the third.
In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.
In the third sample, the following sequence provides the optimal answer:
1. transfer 1 from the first bank to the second bank;
2. transfer 3 from the second bank to the third;
3. transfer 6 from the third bank to the fourth.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
d,s={},0
for i in range(n):
s+=a[i]
if s not in d:d[s]=0
d[s]+=1
print(n-max(d.values()))
```
Yes
| 3,805 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.
Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.
There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.
Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of banks.
The second line contains n integers ai ( - 109 β€ ai β€ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.
Output
Print the minimum number of operations required to change balance in each bank to zero.
Examples
Input
3
5 0 -5
Output
1
Input
4
-1 0 1 0
Output
2
Input
4
1 2 3 -6
Output
3
Note
In the first sample, Vasya may transfer 5 from the first bank to the third.
In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.
In the third sample, the following sequence provides the optimal answer:
1. transfer 1 from the first bank to the second bank;
2. transfer 3 from the second bank to the third;
3. transfer 6 from the third bank to the fourth.
Submitted Solution:
```
n = int(input())
b = list(map(int, input().split()))
from collections import Counter
from itertools import accumulate
cum = list(accumulate(b))
cnt = Counter(cum)
print (n - cnt.most_common(1)[0][1])
```
Yes
| 3,806 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.
Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.
There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.
Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of banks.
The second line contains n integers ai ( - 109 β€ ai β€ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.
Output
Print the minimum number of operations required to change balance in each bank to zero.
Examples
Input
3
5 0 -5
Output
1
Input
4
-1 0 1 0
Output
2
Input
4
1 2 3 -6
Output
3
Note
In the first sample, Vasya may transfer 5 from the first bank to the third.
In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.
In the third sample, the following sequence provides the optimal answer:
1. transfer 1 from the first bank to the second bank;
2. transfer 3 from the second bank to the third;
3. transfer 6 from the third bank to the fourth.
Submitted Solution:
```
from collections import Counter
from itertools import accumulate
n = int(input())
A = (int(x) for x in input().split())
print(n-max(Counter(accumulate(A)).values()))
```
Yes
| 3,807 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.
Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.
There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.
Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of banks.
The second line contains n integers ai ( - 109 β€ ai β€ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.
Output
Print the minimum number of operations required to change balance in each bank to zero.
Examples
Input
3
5 0 -5
Output
1
Input
4
-1 0 1 0
Output
2
Input
4
1 2 3 -6
Output
3
Note
In the first sample, Vasya may transfer 5 from the first bank to the third.
In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.
In the third sample, the following sequence provides the optimal answer:
1. transfer 1 from the first bank to the second bank;
2. transfer 3 from the second bank to the third;
3. transfer 6 from the third bank to the fourth.
Submitted Solution:
```
n = int(input())
A = list(map(int, input().split()))
max_czc = 0
czc = 0
for a in A :
if a == 0 :
czc += 1
max_czc = max(max_czc, czc)
else :
czc = 0
ans = n - max_czc - 1
ans = max(ans, 0)
print(ans)
```
No
| 3,808 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.
Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.
There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.
Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of banks.
The second line contains n integers ai ( - 109 β€ ai β€ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.
Output
Print the minimum number of operations required to change balance in each bank to zero.
Examples
Input
3
5 0 -5
Output
1
Input
4
-1 0 1 0
Output
2
Input
4
1 2 3 -6
Output
3
Note
In the first sample, Vasya may transfer 5 from the first bank to the third.
In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.
In the third sample, the following sequence provides the optimal answer:
1. transfer 1 from the first bank to the second bank;
2. transfer 3 from the second bank to the third;
3. transfer 6 from the third bank to the fourth.
Submitted Solution:
```
input()
l = list(map(int, input().split()))
c = 0
t = 0
s = -1
s2 = 0
for i in range(len(l)):
if l[i] != 0:
s = i
break
if s == -1:
print(0)
exit()
s2 = s
st = 0
while True:
s += 1
if s >= len(l):
s -= len(l)
if l[s] == 0:
c += 1
else:
c = 0
if c > t:
st = s
t = c
if s == s2:
break
st2 = st
st = st-t+5*len(l)
st %= len(l)
l2 = []
for i in range(len(l)):
if st<=i<=st2:
continue
l2.append(l[i])
cr = 0
ans = 0
for i in l2:
cr += i
if cr == 0:
continue
else:
ans += 1
print(ans)
```
No
| 3,809 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.
Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.
There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.
Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of banks.
The second line contains n integers ai ( - 109 β€ ai β€ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.
Output
Print the minimum number of operations required to change balance in each bank to zero.
Examples
Input
3
5 0 -5
Output
1
Input
4
-1 0 1 0
Output
2
Input
4
1 2 3 -6
Output
3
Note
In the first sample, Vasya may transfer 5 from the first bank to the third.
In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.
In the third sample, the following sequence provides the optimal answer:
1. transfer 1 from the first bank to the second bank;
2. transfer 3 from the second bank to the third;
3. transfer 6 from the third bank to the fourth.
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
head = 0
tail = 0
mid = 0
i = 0
while i < n:
if a[i] == 0:
head += 1
else:
break
i += 1
j = n - 1
while j > head:
if a[j] == 0:
tail += 1
else:
break
j -= 1
i = head
while i in range(head, n - tail):
if a[i] == 0:
cur = 1
i += 1
while i < n - tail:
if a[i] == 0:
cur += 1
else:
break
mid = max(mid, cur)
else:
i += 1
print(n - max(head + tail, mid) - 1)
```
No
| 3,810 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.
Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.
There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.
Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.
Input
The first line of the input contains a single integer n (1 β€ n β€ 100 000) β the number of banks.
The second line contains n integers ai ( - 109 β€ ai β€ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.
Output
Print the minimum number of operations required to change balance in each bank to zero.
Examples
Input
3
5 0 -5
Output
1
Input
4
-1 0 1 0
Output
2
Input
4
1 2 3 -6
Output
3
Note
In the first sample, Vasya may transfer 5 from the first bank to the third.
In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.
In the third sample, the following sequence provides the optimal answer:
1. transfer 1 from the first bank to the second bank;
2. transfer 3 from the second bank to the third;
3. transfer 6 from the third bank to the fourth.
Submitted Solution:
```
n = int(input())
lst = list(input().split())
lst.extend(lst)
mi, c = 0, 0
for i in range(-2*n+1, 2*n):
if lst[i] == '0':
c += 1
if c > mi:
mi = c
if lst[i] != '0':
c = 0
print(n-1-mi)
```
No
| 3,811 |
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
```
| 3,812 |
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:
```
import math,sys,bisect,heapq
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
#sys.setrecursionlimit(200000000)
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda: map(int,input().split())
alele = lambda: list(map(int, input().split()))
from functools import lru_cache
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
#MOD = 1000000000 + 7
def Y(c): print(["NO","YES"][c])
def y(c): print(["no","yes"][c])
def Yy(c): print(["No","Yes"][c])
N= int(input())
A = alele()
root = -1
vis = [False]*N
for i in range(N):
if i == A[i] - 1:
root = i
vis[i] = True
break
count = 0
for i in range(N):
if not vis[i]:
vis[i] = True;x= A[i]-1
temp =[i]
while not vis[x]:
temp.append(x)
vis[x] = True
x = A[x] - 1
if x in temp:
if root == -1: root = x
A[x] = root + 1
count += 1
print(count)
print(*A)
```
| 3,813 |
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())
par = [int(x)-1 for x in input().split()]
assert len(par) == n
changes = 0
root = -1
for i, p in enumerate(par):
if i == p:
root = i
break
# possibly cycles, 0-n roots, possibly still root == -1
seen = [-1 for _ in range(n)]
for x in range(n):
if seen[x] >= 0:
continue
seen[x] = x
cur = x
while par[cur] != cur:
if seen[par[cur]] >= 0 and seen[par[cur]] < x:
break
if seen[par[cur]] == x:
changes += 1
if root == -1:
par[cur] = cur
root = cur
else:
par[cur] = root
break
cur = par[cur]
seen[cur] = x
# no cycles, root >= 0, 1-n roots
for i, p in enumerate(par):
if i == p and i != root:
par[i] = root
changes += 1
# no cycles, root >= 0, 1 root
print(changes)
print(' '.join([str(p+1) for p in par]))
```
| 3,814 |
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)))
```
| 3,815 |
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, P):
while x != P[x]:
x = P[x]
return x
def Solucion():
P = [None]*n
for i in range(0, n):
P[i] = i
ciclosC = 0
ciclos = deque([])
root = []
i = 0
# ir haciendo Merge a cada arista
while i < n:
# Merge
padre = Padre(A[i], P)
# Si dicha arista perticipa en un ciclo
if padre == 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:
P[i] = A[i]
i += 1
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()
P[ciclo[0]] = root[0]
PC = [x + 1 for x in P]
print(*PC, sep=" ")
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
n = int(input())
A = list(map(lambda x: int(x)-1, input().split()))
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
```
| 3,816 |
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
```
| 3,817 |
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:
```
class DSU(object):
def __init__(self, n):
self.p = list(range(n))
self.rk = [0] * n
def find(self, u):
while u != self.p[u]:
u = self.p[u]
return u
def unite(self, u, v):
u = self.find(u)
v = self.find(v)
if u == v:
return
if self.rk[u] < self.rk[v]:
u, v = v, u
self.p[v] = u
self.rk[u] += self.rk[u] == self.rk[v]
n = int(input())
p = list(map(int, input().split()))
dsu = DSU(n)
s = None
for u in range(n):
p[u] -= 1
if p[u] == u:
s = u
for u in range(n):
dsu.unite(u, p[u])
ans = 0
rt = [None] * n
vis = [False] * n
for u in range(n):
if dsu.find(u) != u:
continue
v = u
while not vis[v]:
vis[v] = True
v = p[v]
rt[u] = v
if p[v] != v:
p[v] = v
if s is None:
ans += 1
s = v
for u in range(n):
if u != dsu.find(s) and u == dsu.find(u):
p[rt[u]] = s
ans += 1
print(ans)
for u in range(n):
p[u] += 1
print(*p)
```
| 3,818 |
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:])
```
| 3,819 |
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 deque
def Padre(x, P):
while x != P[x]:
x = P[x]
return x
def Solucion():
P = [None]*n
for i in range(0, n):
P[i] = i
ciclosC = 0
ciclos = deque([])
root = []
i = 0
while i < n:
padre = Padre(A[i], P)
if padre == i:
if not root and (i == A[i]):
root = [i, A[i]]
else:
ciclos.append([i, A[i]])
ciclosC += 1
else:
P[i] = A[i]
i += 1
print(str(ciclosC))
if ciclosC:
i = 0
if not root:
root = ciclos.popleft()
i = 1
while ciclos:
ciclo = ciclos.popleft()
P[ciclo[0]] = root[0]
PC = [x + 1 for x in P]
print(*PC, sep=" ")
def DFS(x, color, padre, ciclos, adyacentes, raiz):
color[x] = 1
for y in adyacentes[x]:
if color[y] == 0:
DFS(y, color, padre, ciclos, adyacentes, raiz)
padre[y] = x
elif color[y] == 2:
padre[y] = x
else:
if y == x and not raiz:
raiz = x
else:
ciclos.append([x, y])
color[x] = 2
n = int(input())
A = list(map(lambda x: int(x)-1, input().split()))
Solucion()
```
Yes
| 3,820 |
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())
parents = [None] + list(map(int, input().split()))
visited = [None] * len(parents)
candidates = set()
hot = None
for node in range(1, n+1):
if visited[node]:
continue
run = node
visited[node] = run
while parents[node] != node and not visited[parents[node]]:
node = parents[node]
visited[node] = run
if visited[parents[node]] == run:
candidates.add(node)
if parents[node] == node:
hot = node
if hot:
root = hot
candidates.remove(hot)
else:
root = candidates.pop()
candidates.add(root)
print(len(candidates))
print(" ".join(map(str, (p if node not in candidates else root for node, p in list(enumerate(parents))[1:]))))
```
Yes
| 3,821 |
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())
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)))
```
Yes
| 3,822 |
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:
```
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
ans= 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: #new cycle
if root==-1:
A[a]=a+1
root=a
ans+=1
else :
A[a]=root+1
ans+=1
print(ans)
print(' '.join(map(str,A)))
```
Yes
| 3,823 |
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:
```
def get(x):
if p[x] != x:
p[x] = get(p[x])
return p[x]
def union(x, y):
x = get(x)
y = get(y)
p[x] = y
n = int(input())
a = list(x - 1 for x in map(int, input().split()))
p = list(range(n))
bad = []
root = None
for i in range(n):
if i == a[i]:
if root is None:
root = i
else:
bad.append(i)
else:
if get(i) != get(a[i]):
union(i, a[i])
else:
bad.append(i)
result = len(bad)
if root is None:
root = bad[-1]
bad = bad[:-1]
a[root] = root
components = set(p)
for i in bad:
cur = get(i)
for j in components:
if j != cur:
a[i] = j
union(i, j)
break
print(result)
print(' '.join(map(str, map(lambda x: x + 1, a))))
```
No
| 3,824 |
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
| 3,825 |
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:
```
class DSU(object):
def __init__(self, n):
self.p = list(range(n))
self.rk = [0] * n
def find(self, u):
while u != self.p[u]:
u = self.p[u]
return u
def unite(self, u, v):
u = self.find(u)
v = self.find(v)
if u == v:
return
if self.rk[u] < self.rk[v]:
u, v = v, u
self.p[v] = u
self.rk[u] += self.rk[u] == self.rk[v]
n = int(input())
p = list(map(int, input().split()))
dsu = DSU(n)
s = None
for u in range(n):
p[u] -= 1
if p[u] == u:
s = u
for u in range(n):
dsu.unite(u, p[u])
ans = 0
rt = [None] * n
vis = [False] * n
for u in range(n):
if dsu.find(u) != u:
continue
v = u
while not vis[v]:
vis[v] = True
v = p[v]
rt[u] = v
if p[v] != v:
p[v] = v
if s is None:
ans += 1
s = v
for u in range(n):
if u != dsu.find(s) and u == dsu.find(u):
p[u] = s
ans += 1
print(ans)
for u in range(n):
p[u] += 1
print(*p)
```
No
| 3,826 |
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()))
class DisjSet:
def __init__(self, n):
# Constructor to create and
# initialize sets of n items
self.rank = [1] * n
self.parent = [i for i in range(n)]
self.extra = []
# Finds set of given item x
def find(self, x):
# Finds the representative of the set
# that x is an element of
if (self.parent[x] != x):
# if x is not the parent of itself
# Then x is not the representative of
# its set,
self.parent[x] = self.find(self.parent[x])
# so we recursively call Find on its parent
# and move i's node directly under the
# representative of this set
return self.parent[x]
# Do union of two sets represented
# by x and y.
def Union(self, x, y):
# Find current sets of x and y
xset = self.find(x)
yset = self.find(y)
# If they are already in same set
if xset == yset:
self.extra.append((x, y))
return
# Put smaller ranked item under
# bigger ranked item if ranks are
# different
if self.rank[xset] < self.rank[yset]:
self.parent[xset] = yset
elif self.rank[xset] > self.rank[yset]:
self.parent[yset] = xset
# If ranks are same, then move y under
# x (doesn't matter which one goes where)
# and increment rank of x's tree
else:
self.parent[yset] = xset
self.rank[xset] = self.rank[xset] + 1
obj = DisjSet(n)
self_parent=0
for i in range(n):
obj.Union(i,a[i]-1)
if i==a[i]-1:
self_parent+=1
hashmap={}
for i in range(n):
temp=obj.find(i)
if temp not in hashmap:
hashmap[temp]=[]
hashmap[temp].append(i)
if len(hashmap)==1 and self_parent==1:
print(0)
print(*a)
elif len(hashmap)==1 and self_parent==0:
print(1)
a[0]=1
print(*a)
else:
self_parents=[]
total=0
for i in range(0,len(a)):
if i==a[i]-1:
self_parents.append(i)
if len(self_parents)==0:
total+=1
self_parents=[0]
for i in hashmap:
self_parent=-1
for k in hashmap[i]:
if a[k]-1==k:
self_parent=k
if self_parent==-1:
a[hashmap[i][0]]=self_parents[0]+1
total+=1
else:
if a[self_parent]==self_parents[0]+1:
continue
a[self_parent]=self_parents[0]+1
total+=1
print(total)
print(*a)
```
No
| 3,827 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The closing ceremony of Squanch Code Cup is held in the big hall with n Γ m seats, arranged in n rows, m seats in a row. Each seat has two coordinates (x, y) (1 β€ x β€ n, 1 β€ y β€ m).
There are two queues of people waiting to enter the hall: k people are standing at (0, 0) and nΒ·m - k people are standing at (0, m + 1). Each person should have a ticket for a specific seat. If person p at (x, y) has ticket for seat (xp, yp) then he should walk |x - xp| + |y - yp| to get to his seat.
Each person has a stamina β the maximum distance, that the person agrees to walk. You should find out if this is possible to distribute all nΒ·m tickets in such a way that each person has enough stamina to get to their seat.
Input
The first line of input contains two integers n and m (1 β€ nΒ·m β€ 104) β the size of the hall.
The second line contains several integers. The first integer k (0 β€ k β€ nΒ·m) β the number of people at (0, 0). The following k integers indicate stamina of each person there.
The third line also contains several integers. The first integer l (l = nΒ·m - k) β the number of people at (0, m + 1). The following l integers indicate stamina of each person there.
The stamina of the person is a positive integer less that or equal to n + m.
Output
If it is possible to distribute tickets between people in the described manner print "YES", otherwise print "NO".
Examples
Input
2 2
3 3 3 2
1 3
Output
YES
Input
2 2
3 2 3 3
1 2
Output
NO
Submitted Solution:
```
print("YES")
```
No
| 3,828 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Note that girls in Arpaβs land are really attractive.
Arpa loves overnight parties. In the middle of one of these parties Mehrdad suddenly appeared. He saw n pairs of friends sitting around a table. i-th pair consisted of a boy, sitting on the ai-th chair, and his girlfriend, sitting on the bi-th chair. The chairs were numbered 1 through 2n in clockwise direction. There was exactly one person sitting on each chair.
<image>
There were two types of food: Kooft and Zahre-mar. Now Mehrdad wonders, was there any way to serve food for the guests such that:
* Each person had exactly one type of food,
* No boy had the same type of food as his girlfriend,
* Among any three guests sitting on consecutive chairs, there was two of them who had different type of food. Note that chairs 2n and 1 are considered consecutive.
Find the answer for the Mehrdad question. If it was possible, find some arrangement of food types that satisfies the conditions.
Input
The first line contains an integer n (1 β€ n β€ 105) β the number of pairs of guests.
The i-th of the next n lines contains a pair of integers ai and bi (1 β€ ai, bi β€ 2n) β the number of chair on which the boy in the i-th pair was sitting and the number of chair on which his girlfriend was sitting. It's guaranteed that there was exactly one person sitting on each chair.
Output
If there is no solution, print -1.
Otherwise print n lines, the i-th of them should contain two integers which represent the type of food for the i-th pair. The first integer in the line is the type of food the boy had, and the second integer is the type of food the girl had. If someone had Kooft, print 1, otherwise print 2.
If there are multiple solutions, print any of them.
Example
Input
3
1 4
2 5
3 6
Output
1 2
2 1
1 2
Tags: constructive algorithms, dfs and similar, graphs
Correct Solution:
```
import sys
n = int(input())
A = [0]*(2*n)
B = []
for line in sys.stdin:
x, y = [int(x)-1 for x in line.split()]
A[x] = y
A[y] = x
B.append(x)
C = [0]*(2*n)
for i in range(2*n):
while not C[i]:
C[i] = 1
C[i^1] = 2
i = A[i^1]
for x in B:
print(C[x], C[A[x]])
```
| 3,829 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Note that girls in Arpaβs land are really attractive.
Arpa loves overnight parties. In the middle of one of these parties Mehrdad suddenly appeared. He saw n pairs of friends sitting around a table. i-th pair consisted of a boy, sitting on the ai-th chair, and his girlfriend, sitting on the bi-th chair. The chairs were numbered 1 through 2n in clockwise direction. There was exactly one person sitting on each chair.
<image>
There were two types of food: Kooft and Zahre-mar. Now Mehrdad wonders, was there any way to serve food for the guests such that:
* Each person had exactly one type of food,
* No boy had the same type of food as his girlfriend,
* Among any three guests sitting on consecutive chairs, there was two of them who had different type of food. Note that chairs 2n and 1 are considered consecutive.
Find the answer for the Mehrdad question. If it was possible, find some arrangement of food types that satisfies the conditions.
Input
The first line contains an integer n (1 β€ n β€ 105) β the number of pairs of guests.
The i-th of the next n lines contains a pair of integers ai and bi (1 β€ ai, bi β€ 2n) β the number of chair on which the boy in the i-th pair was sitting and the number of chair on which his girlfriend was sitting. It's guaranteed that there was exactly one person sitting on each chair.
Output
If there is no solution, print -1.
Otherwise print n lines, the i-th of them should contain two integers which represent the type of food for the i-th pair. The first integer in the line is the type of food the boy had, and the second integer is the type of food the girl had. If someone had Kooft, print 1, otherwise print 2.
If there are multiple solutions, print any of them.
Example
Input
3
1 4
2 5
3 6
Output
1 2
2 1
1 2
Tags: constructive algorithms, dfs and similar, graphs
Correct Solution:
```
import sys
def solve():
n = int(input())
partner = [0]*(2*n)
pacani = []
for line in sys.stdin:
pacan, telka = [int(x) - 1 for x in line.split()]
partner[pacan] = telka
partner[telka] = pacan
pacani.append(pacan)
khavka = [None]*(2*n)
for i in range(2*n):
while khavka[i] is None:
khavka[i] = 1
khavka[i^1] = 2
i = partner[i^1]
for pacan in pacani:
print(khavka[pacan], khavka[partner[pacan]])
solve()
```
| 3,830 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.
To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol a, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with b, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.
You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.
Input
In the only line of input there is a string S of lowercase English letters (1 β€ |S| β€ 500) β the identifiers of a program with removed whitespace characters.
Output
If this program can be a result of Kostya's obfuscation, print "YES" (without quotes), otherwise print "NO".
Examples
Input
abacaba
Output
YES
Input
jinotega
Output
NO
Note
In the first sample case, one possible list of identifiers would be "number string number character number string number". Here how Kostya would obfuscate the program:
* replace all occurences of number with a, the result would be "a string a character a string a",
* replace all occurences of string with b, the result would be "a b a character a b a",
* replace all occurences of character with c, the result would be "a b a c a b a",
* all identifiers have been replaced, thus the obfuscation is finished.
Tags: greedy, implementation, strings
Correct Solution:
```
alphabet = [chr(i) for i in range(97, 123)]
line = input()
obfuscated_array = []
for el in line:
obfuscated_array.append(el)
point = 0
while len(obfuscated_array) != 0:
if obfuscated_array[0] == alphabet[0]:
for _ in range(obfuscated_array.count(alphabet[0])):
obfuscated_array.remove(alphabet[0])
alphabet.pop(0)
else:
print("NO")
break
if len(obfuscated_array) == 0:
print("YES")
```
| 3,831 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.
To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol a, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with b, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.
You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.
Input
In the only line of input there is a string S of lowercase English letters (1 β€ |S| β€ 500) β the identifiers of a program with removed whitespace characters.
Output
If this program can be a result of Kostya's obfuscation, print "YES" (without quotes), otherwise print "NO".
Examples
Input
abacaba
Output
YES
Input
jinotega
Output
NO
Note
In the first sample case, one possible list of identifiers would be "number string number character number string number". Here how Kostya would obfuscate the program:
* replace all occurences of number with a, the result would be "a string a character a string a",
* replace all occurences of string with b, the result would be "a b a character a b a",
* replace all occurences of character with c, the result would be "a b a c a b a",
* all identifiers have been replaced, thus the obfuscation is finished.
Tags: greedy, implementation, strings
Correct Solution:
```
s = input()
length = len(s)
a = ord('a')
i = 0
for c in s:
if (a + i < ord(c)):
print("NO")
break
if (a + i == ord(c)):
i += 1
else:
print("YES")
```
| 3,832 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.
To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol a, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with b, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.
You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.
Input
In the only line of input there is a string S of lowercase English letters (1 β€ |S| β€ 500) β the identifiers of a program with removed whitespace characters.
Output
If this program can be a result of Kostya's obfuscation, print "YES" (without quotes), otherwise print "NO".
Examples
Input
abacaba
Output
YES
Input
jinotega
Output
NO
Note
In the first sample case, one possible list of identifiers would be "number string number character number string number". Here how Kostya would obfuscate the program:
* replace all occurences of number with a, the result would be "a string a character a string a",
* replace all occurences of string with b, the result would be "a b a character a b a",
* replace all occurences of character with c, the result would be "a b a c a b a",
* all identifiers have been replaced, thus the obfuscation is finished.
Tags: greedy, implementation, strings
Correct Solution:
```
##n = int(input())
##a = list(map(int, input().split()))
##print(' '.join(map(str, res)))
s = list(input())
n = len(s)
flag = True
last = ord(s[0])
if last != ord('a'):
flag = False
else:
for i in range(1, n):
cur = ord(s[i])
if cur-last > 1:
flag = False
break
last = max(last, cur)
if flag == True:
print('YES')
else:
print('NO')
```
| 3,833 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.
To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol a, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with b, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.
You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.
Input
In the only line of input there is a string S of lowercase English letters (1 β€ |S| β€ 500) β the identifiers of a program with removed whitespace characters.
Output
If this program can be a result of Kostya's obfuscation, print "YES" (without quotes), otherwise print "NO".
Examples
Input
abacaba
Output
YES
Input
jinotega
Output
NO
Note
In the first sample case, one possible list of identifiers would be "number string number character number string number". Here how Kostya would obfuscate the program:
* replace all occurences of number with a, the result would be "a string a character a string a",
* replace all occurences of string with b, the result would be "a b a character a b a",
* replace all occurences of character with c, the result would be "a b a c a b a",
* all identifiers have been replaced, thus the obfuscation is finished.
Tags: greedy, implementation, strings
Correct Solution:
```
n=input()
k=96
for i in n:
if(ord(i)-k>1):
k=0
break
elif(ord(i)-k==1):
k+=1
if(k):
print("YES")
else:
print("NO")
```
| 3,834 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.
To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol a, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with b, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.
You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.
Input
In the only line of input there is a string S of lowercase English letters (1 β€ |S| β€ 500) β the identifiers of a program with removed whitespace characters.
Output
If this program can be a result of Kostya's obfuscation, print "YES" (without quotes), otherwise print "NO".
Examples
Input
abacaba
Output
YES
Input
jinotega
Output
NO
Note
In the first sample case, one possible list of identifiers would be "number string number character number string number". Here how Kostya would obfuscate the program:
* replace all occurences of number with a, the result would be "a string a character a string a",
* replace all occurences of string with b, the result would be "a b a character a b a",
* replace all occurences of character with c, the result would be "a b a c a b a",
* all identifiers have been replaced, thus the obfuscation is finished.
Tags: greedy, implementation, strings
Correct Solution:
```
a=list(input())
b=[]
for i in a:
if i not in b:
b.append(i)
for i in range(len(b)):
if (ord(b[i])-ord('a'))!=i:
exit(print('NO'))
print('YES')
```
| 3,835 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.
To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol a, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with b, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.
You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.
Input
In the only line of input there is a string S of lowercase English letters (1 β€ |S| β€ 500) β the identifiers of a program with removed whitespace characters.
Output
If this program can be a result of Kostya's obfuscation, print "YES" (without quotes), otherwise print "NO".
Examples
Input
abacaba
Output
YES
Input
jinotega
Output
NO
Note
In the first sample case, one possible list of identifiers would be "number string number character number string number". Here how Kostya would obfuscate the program:
* replace all occurences of number with a, the result would be "a string a character a string a",
* replace all occurences of string with b, the result would be "a b a character a b a",
* replace all occurences of character with c, the result would be "a b a c a b a",
* all identifiers have been replaced, thus the obfuscation is finished.
Tags: greedy, implementation, strings
Correct Solution:
```
a=input()
x=96
b=''
c=[]
for i in set(a):
if x<ord(i):
x=ord(i)
for i in range(97,x+1):
if chr(i) in a:
b+=(chr(i))
else:
print("NO")
exit(0)
for i in b:
c.append(a.index(i))
d=sorted(c)
if d==c:
print("YES")
else:
print("NO")
```
| 3,836 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.
To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol a, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with b, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.
You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.
Input
In the only line of input there is a string S of lowercase English letters (1 β€ |S| β€ 500) β the identifiers of a program with removed whitespace characters.
Output
If this program can be a result of Kostya's obfuscation, print "YES" (without quotes), otherwise print "NO".
Examples
Input
abacaba
Output
YES
Input
jinotega
Output
NO
Note
In the first sample case, one possible list of identifiers would be "number string number character number string number". Here how Kostya would obfuscate the program:
* replace all occurences of number with a, the result would be "a string a character a string a",
* replace all occurences of string with b, the result would be "a b a character a b a",
* replace all occurences of character with c, the result would be "a b a c a b a",
* all identifiers have been replaced, thus the obfuscation is finished.
Tags: greedy, implementation, strings
Correct Solution:
```
def Main():
inp = list(input())
found = 0
error = False
for c in inp:
p = ord(c) - ord('a') + 1
if p == found + 1:
found += 1
elif p > found:
error = True
break
if error == False:
print("YES")
else:
print("NO")
if __name__ == "__main__":
Main()
```
| 3,837 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.
To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol a, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with b, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.
You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.
Input
In the only line of input there is a string S of lowercase English letters (1 β€ |S| β€ 500) β the identifiers of a program with removed whitespace characters.
Output
If this program can be a result of Kostya's obfuscation, print "YES" (without quotes), otherwise print "NO".
Examples
Input
abacaba
Output
YES
Input
jinotega
Output
NO
Note
In the first sample case, one possible list of identifiers would be "number string number character number string number". Here how Kostya would obfuscate the program:
* replace all occurences of number with a, the result would be "a string a character a string a",
* replace all occurences of string with b, the result would be "a b a character a b a",
* replace all occurences of character with c, the result would be "a b a c a b a",
* all identifiers have been replaced, thus the obfuscation is finished.
Tags: greedy, implementation, strings
Correct Solution:
```
import sys
s = input()
expected = ord('a')
for i in s :
if ord(i) > expected:
print('NO')
sys.exit()
elif ord(i) == expected:
expected +=1
print('YES')
```
| 3,838 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.
To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol a, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with b, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.
You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.
Input
In the only line of input there is a string S of lowercase English letters (1 β€ |S| β€ 500) β the identifiers of a program with removed whitespace characters.
Output
If this program can be a result of Kostya's obfuscation, print "YES" (without quotes), otherwise print "NO".
Examples
Input
abacaba
Output
YES
Input
jinotega
Output
NO
Note
In the first sample case, one possible list of identifiers would be "number string number character number string number". Here how Kostya would obfuscate the program:
* replace all occurences of number with a, the result would be "a string a character a string a",
* replace all occurences of string with b, the result would be "a b a character a b a",
* replace all occurences of character with c, the result would be "a b a c a b a",
* all identifiers have been replaced, thus the obfuscation is finished.
Submitted Solution:
```
# 1 Yotta Byte!
# Codeforces 397
s=input()
a=sorted(set(s))
b=[]
counter=0
for i in range(len(s)):
if s[i] not in b:
b.append(s[i])
if ord(b[counter])-97!=counter:
print('NO')
exit()
counter+=1
if a==b and a[0]=='a':
print('YES')
else:
print('NO')
```
Yes
| 3,839 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.
To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol a, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with b, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.
You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.
Input
In the only line of input there is a string S of lowercase English letters (1 β€ |S| β€ 500) β the identifiers of a program with removed whitespace characters.
Output
If this program can be a result of Kostya's obfuscation, print "YES" (without quotes), otherwise print "NO".
Examples
Input
abacaba
Output
YES
Input
jinotega
Output
NO
Note
In the first sample case, one possible list of identifiers would be "number string number character number string number". Here how Kostya would obfuscate the program:
* replace all occurences of number with a, the result would be "a string a character a string a",
* replace all occurences of string with b, the result would be "a b a character a b a",
* replace all occurences of character with c, the result would be "a b a c a b a",
* all identifiers have been replaced, thus the obfuscation is finished.
Submitted Solution:
```
import string
s = input()
arr = ""
for char in s:
if char not in arr:
arr += char
if arr == string.ascii_lowercase[:len(arr)]:
print("YES")
else:
print("NO")
```
Yes
| 3,840 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.
To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol a, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with b, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.
You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.
Input
In the only line of input there is a string S of lowercase English letters (1 β€ |S| β€ 500) β the identifiers of a program with removed whitespace characters.
Output
If this program can be a result of Kostya's obfuscation, print "YES" (without quotes), otherwise print "NO".
Examples
Input
abacaba
Output
YES
Input
jinotega
Output
NO
Note
In the first sample case, one possible list of identifiers would be "number string number character number string number". Here how Kostya would obfuscate the program:
* replace all occurences of number with a, the result would be "a string a character a string a",
* replace all occurences of string with b, the result would be "a b a character a b a",
* replace all occurences of character with c, the result would be "a b a c a b a",
* all identifiers have been replaced, thus the obfuscation is finished.
Submitted Solution:
```
s = input()
idents = list('abcdefghijklmnopqrstuvwxyz')
possible = True
for x in s:
if not idents:
break
elif x == idents[0]:
idents.pop(0)
elif x not in idents:
continue
else:
possible = False
print('YES' if possible else 'NO')
```
Yes
| 3,841 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.
To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol a, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with b, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.
You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.
Input
In the only line of input there is a string S of lowercase English letters (1 β€ |S| β€ 500) β the identifiers of a program with removed whitespace characters.
Output
If this program can be a result of Kostya's obfuscation, print "YES" (without quotes), otherwise print "NO".
Examples
Input
abacaba
Output
YES
Input
jinotega
Output
NO
Note
In the first sample case, one possible list of identifiers would be "number string number character number string number". Here how Kostya would obfuscate the program:
* replace all occurences of number with a, the result would be "a string a character a string a",
* replace all occurences of string with b, the result would be "a b a character a b a",
* replace all occurences of character with c, the result would be "a b a c a b a",
* all identifiers have been replaced, thus the obfuscation is finished.
Submitted Solution:
```
import math
input_string = input()
map = []
first_index = []
for i in range(0,26):
map.append(0)
first_index.append(math.inf)
for i in range(0, len(input_string)):
if map[ord(input_string[i]) - 97] == 0:
first_index[ord(input_string[i]) - 97] = i
map[ord(input_string[i]) - 97]+=1
fault = False
for i in range(1, len(map)):
if map[i - 1] == 0 and map[i] > 0:
fault = True
break
for i in range(0, len(first_index) - 1):
if first_index[i] > first_index[i + 1]:
fault = True
break
if fault == True:
print("NO")
else:
print("YES")
```
Yes
| 3,842 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.
To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol a, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with b, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.
You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.
Input
In the only line of input there is a string S of lowercase English letters (1 β€ |S| β€ 500) β the identifiers of a program with removed whitespace characters.
Output
If this program can be a result of Kostya's obfuscation, print "YES" (without quotes), otherwise print "NO".
Examples
Input
abacaba
Output
YES
Input
jinotega
Output
NO
Note
In the first sample case, one possible list of identifiers would be "number string number character number string number". Here how Kostya would obfuscate the program:
* replace all occurences of number with a, the result would be "a string a character a string a",
* replace all occurences of string with b, the result would be "a b a character a b a",
* replace all occurences of character with c, the result would be "a b a c a b a",
* all identifiers have been replaced, thus the obfuscation is finished.
Submitted Solution:
```
""" Created by Henrikh Kantuni on 2/14/17 """
if __name__ == '__main__':
obfuscation = list(input())
obfuscation = [ord(c) for c in obfuscation]
obfuscation = list(set(obfuscation))
obfuscation.sort()
print(obfuscation)
if len(obfuscation) == 1:
if obfuscation[0] == 97:
print('YES')
else:
print('NO')
else:
i = 0
while i < len(obfuscation) - 1:
if obfuscation[i + 1] != obfuscation[i] + 1:
print('NO')
exit()
i += 1
print('YES')
```
No
| 3,843 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.
To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol a, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with b, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.
You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.
Input
In the only line of input there is a string S of lowercase English letters (1 β€ |S| β€ 500) β the identifiers of a program with removed whitespace characters.
Output
If this program can be a result of Kostya's obfuscation, print "YES" (without quotes), otherwise print "NO".
Examples
Input
abacaba
Output
YES
Input
jinotega
Output
NO
Note
In the first sample case, one possible list of identifiers would be "number string number character number string number". Here how Kostya would obfuscate the program:
* replace all occurences of number with a, the result would be "a string a character a string a",
* replace all occurences of string with b, the result would be "a b a character a b a",
* replace all occurences of character with c, the result would be "a b a c a b a",
* all identifiers have been replaced, thus the obfuscation is finished.
Submitted Solution:
```
s = sorted(input())
for i in range(1, len(s)):
if ord(s[i]) > ord(s[i-1])+1:
print("NO")
break
else:
print("YES")
```
No
| 3,844 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.
To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol a, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with b, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.
You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.
Input
In the only line of input there is a string S of lowercase English letters (1 β€ |S| β€ 500) β the identifiers of a program with removed whitespace characters.
Output
If this program can be a result of Kostya's obfuscation, print "YES" (without quotes), otherwise print "NO".
Examples
Input
abacaba
Output
YES
Input
jinotega
Output
NO
Note
In the first sample case, one possible list of identifiers would be "number string number character number string number". Here how Kostya would obfuscate the program:
* replace all occurences of number with a, the result would be "a string a character a string a",
* replace all occurences of string with b, the result would be "a b a character a b a",
* replace all occurences of character with c, the result would be "a b a c a b a",
* all identifiers have been replaced, thus the obfuscation is finished.
Submitted Solution:
```
import sys
n = input()
good = 'a'
for i in range (len(n)):
if n[i] == good or n[i] < good:
good = chr(ord(good) + 1)
else:
print('NO')
sys.exit()
print('YES')
```
No
| 3,845 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate (intentionally make less readable) his code before upcoming contest.
To obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol a, then he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with b, and so on. Kostya is well-mannered, so he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.
You are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.
Input
In the only line of input there is a string S of lowercase English letters (1 β€ |S| β€ 500) β the identifiers of a program with removed whitespace characters.
Output
If this program can be a result of Kostya's obfuscation, print "YES" (without quotes), otherwise print "NO".
Examples
Input
abacaba
Output
YES
Input
jinotega
Output
NO
Note
In the first sample case, one possible list of identifiers would be "number string number character number string number". Here how Kostya would obfuscate the program:
* replace all occurences of number with a, the result would be "a string a character a string a",
* replace all occurences of string with b, the result would be "a b a character a b a",
* replace all occurences of character with c, the result would be "a b a c a b a",
* all identifiers have been replaced, thus the obfuscation is finished.
Submitted Solution:
```
s = str(input())
from collections import defaultdict
m = defaultdict(int)
valid = True
for i in range(len(s) - 1):
if ord(s[i]) > ord(s[i-1]):
m[s[i]] += 1
else:
if m[s[i]] == 0:
valid = False
print("YES" if valid else "NO")
```
No
| 3,846 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers, where y is the next prime number after x, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat n Roman soldiers and it turned out that the number n was prime! Today their victims were a troop of m Romans (m > n). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
Input
The first and only input line contains two positive integers β n and m (2 β€ n < m β€ 50). It is guaranteed that n is prime.
Pretests contain all the cases with restrictions 2 β€ n < m β€ 4.
Output
Print YES, if m is the next prime number after n, or NO otherwise.
Examples
Input
3 5
Output
YES
Input
7 11
Output
YES
Input
7 9
Output
NO
Tags: brute force
Correct Solution:
```
import math
def isPrime(n1):
if n1 == 0 or n1 == 1:
return False
s = int(math.sqrt(n1))
for i in range(2, s+1):
if n1 % i == 0:
return False
return True
m, n = map(int, input().split())
ans, i, x = m, m+1, []
while i <= n:
if isPrime(i):
x.append(i)
i += 1
if x:
if x[0] == n:
print("YES")
else:
print("NO")
else:
print("NO")
```
| 3,847 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers, where y is the next prime number after x, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat n Roman soldiers and it turned out that the number n was prime! Today their victims were a troop of m Romans (m > n). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
Input
The first and only input line contains two positive integers β n and m (2 β€ n < m β€ 50). It is guaranteed that n is prime.
Pretests contain all the cases with restrictions 2 β€ n < m β€ 4.
Output
Print YES, if m is the next prime number after n, or NO otherwise.
Examples
Input
3 5
Output
YES
Input
7 11
Output
YES
Input
7 9
Output
NO
Tags: brute force
Correct Solution:
```
data = list(map(int, input().split()))
def eratosthenes(n): # n - ΡΠΈΡΠ»ΠΎ, Π΄ΠΎ ΠΊΠΎΡΠΎΡΠΎΠ³ΠΎ Ρ
ΠΎΡΠΈΠΌ Π½Π°ΠΉΡΠΈ ΠΏΡΠΎΡΡΡΠ΅ ΡΠΈΡΠ»Π°
sieve = list(range(n + 1))
sieve[1] = 0 # Π±Π΅Π· ΡΡΠΎΠΉ ΡΡΡΠΎΠΊΠΈ ΠΈΡΠΎΠ³ΠΎΠ²ΡΠΉ ΡΠΏΠΈΡΠΎΠΊ Π±ΡΠ΄Π΅Ρ ΡΠΎΠ΄Π΅ΡΠΆΠ°ΡΡ Π΅Π΄ΠΈΠ½ΠΈΡΡ
for i in sieve:
if i > 1:
for j in range(i + i, len(sieve), i):
sieve[j] = 0
return sieve
primary_numbers = eratosthenes(data[1])
filtered = list(filter(lambda x: x != 0, primary_numbers))
if filtered.__len__() < 2:
print("NO")
else:
last = filtered[filtered.__len__() - 1]
prev = filtered[filtered.__len__() - 2]
if prev == data[0] and last == data[1]:
print("YES")
else:
print("NO")
```
| 3,848 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers, where y is the next prime number after x, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat n Roman soldiers and it turned out that the number n was prime! Today their victims were a troop of m Romans (m > n). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
Input
The first and only input line contains two positive integers β n and m (2 β€ n < m β€ 50). It is guaranteed that n is prime.
Pretests contain all the cases with restrictions 2 β€ n < m β€ 4.
Output
Print YES, if m is the next prime number after n, or NO otherwise.
Examples
Input
3 5
Output
YES
Input
7 11
Output
YES
Input
7 9
Output
NO
Tags: brute force
Correct Solution:
```
from math import sqrt
n, m = map(int, input().split())
def isprime(nn):
if nn % 2 == 0:
return False
for i in range(3, int(sqrt(nn))+1):
if nn % i == 0:
return False
return True
for i in range(n+1, m+1):
if isprime(i):
if i == m:
print("YES")
else:
print("NO")
break
else:
print("NO")
```
| 3,849 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers, where y is the next prime number after x, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat n Roman soldiers and it turned out that the number n was prime! Today their victims were a troop of m Romans (m > n). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
Input
The first and only input line contains two positive integers β n and m (2 β€ n < m β€ 50). It is guaranteed that n is prime.
Pretests contain all the cases with restrictions 2 β€ n < m β€ 4.
Output
Print YES, if m is the next prime number after n, or NO otherwise.
Examples
Input
3 5
Output
YES
Input
7 11
Output
YES
Input
7 9
Output
NO
Tags: brute force
Correct Solution:
```
import math
num = input().split()
def pcheck(num):
num = int(num)
for i in range(2, int(math.sqrt(num))+1):
if num%i == 0:
return False #RETURN FALSE FOR NON PRIME NUMBER
return True
for i in range(int(num[0])+1, int(num[1])+1):
if pcheck(i):
break
if i == int(num[1]) and pcheck(num[1]):
print("YES")
else:
print("NO")
```
| 3,850 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers, where y is the next prime number after x, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat n Roman soldiers and it turned out that the number n was prime! Today their victims were a troop of m Romans (m > n). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
Input
The first and only input line contains two positive integers β n and m (2 β€ n < m β€ 50). It is guaranteed that n is prime.
Pretests contain all the cases with restrictions 2 β€ n < m β€ 4.
Output
Print YES, if m is the next prime number after n, or NO otherwise.
Examples
Input
3 5
Output
YES
Input
7 11
Output
YES
Input
7 9
Output
NO
Tags: brute force
Correct Solution:
```
def isPrime(num):
if num > 1:
for i in range(2, num):
if num % i == 0:
return False
return True
def nextPrime(num):
num += 1
while not isPrime(num):
num += 1
return num
if __name__ == '__main__':
d1, d2 = input().strip().split()
if isPrime(int(d1)) and isPrime(int(d2)):
if nextPrime(int(d1)) == int(d2):
print("YES")
else:
print("NO")
else:
print("NO")
```
| 3,851 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers, where y is the next prime number after x, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat n Roman soldiers and it turned out that the number n was prime! Today their victims were a troop of m Romans (m > n). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
Input
The first and only input line contains two positive integers β n and m (2 β€ n < m β€ 50). It is guaranteed that n is prime.
Pretests contain all the cases with restrictions 2 β€ n < m β€ 4.
Output
Print YES, if m is the next prime number after n, or NO otherwise.
Examples
Input
3 5
Output
YES
Input
7 11
Output
YES
Input
7 9
Output
NO
Tags: brute force
Correct Solution:
```
def answer():
a = [int(x) for x in input().split()]
m = a[0]
n = a[1]
if m==2:
if n==3:
return "YES"
else:
return "NO"
elif m==3:
if n==5:
return "YES"
else:
return "NO"
if m%6==1:
skip = 4
else:
skip = 2
i=2
while i<=n**(1/2):
if not n%i:
return "NO"
i+=1
j=m+skip
while j<n:
i=2
composite=0
while i<=j**(1/2):
if not j%i:
composite=1
break
i+=1
if not composite and j!=n:
return "NO"
if skip==2:skip=4
else:skip=2
j+=skip
return "YES"
print(answer())
```
| 3,852 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers, where y is the next prime number after x, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat n Roman soldiers and it turned out that the number n was prime! Today their victims were a troop of m Romans (m > n). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
Input
The first and only input line contains two positive integers β n and m (2 β€ n < m β€ 50). It is guaranteed that n is prime.
Pretests contain all the cases with restrictions 2 β€ n < m β€ 4.
Output
Print YES, if m is the next prime number after n, or NO otherwise.
Examples
Input
3 5
Output
YES
Input
7 11
Output
YES
Input
7 9
Output
NO
Tags: brute force
Correct Solution:
```
def main():
n, m = map(int,input().split(" "))
if m <= n:
print("NO")
return;
for num in range(n+1,100):
d = 2
f = 1
while d*d <= num:
if num % d == 0:
f = 0
break
d += 1
if f == 1:
if num == m:
print("YES")
else:
print("NO")
return
if __name__ == "__main__":
main()
```
| 3,853 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers, where y is the next prime number after x, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat n Roman soldiers and it turned out that the number n was prime! Today their victims were a troop of m Romans (m > n). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
Input
The first and only input line contains two positive integers β n and m (2 β€ n < m β€ 50). It is guaranteed that n is prime.
Pretests contain all the cases with restrictions 2 β€ n < m β€ 4.
Output
Print YES, if m is the next prime number after n, or NO otherwise.
Examples
Input
3 5
Output
YES
Input
7 11
Output
YES
Input
7 9
Output
NO
Tags: brute force
Correct Solution:
```
def calc(n, m):
for i in range(n+1, m+1):
is_prime = True
if i < 2:
is_prime = False
for j in range(2, i):
if i % j == 0:
is_prime = False
break
if is_prime:
#print(i)
if i == m:
return 'YES'
break
return 'NO'
# get inputs
n, m = map(int, input().split())
print(calc(n, m))
```
| 3,854 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers, where y is the next prime number after x, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat n Roman soldiers and it turned out that the number n was prime! Today their victims were a troop of m Romans (m > n). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
Input
The first and only input line contains two positive integers β n and m (2 β€ n < m β€ 50). It is guaranteed that n is prime.
Pretests contain all the cases with restrictions 2 β€ n < m β€ 4.
Output
Print YES, if m is the next prime number after n, or NO otherwise.
Examples
Input
3 5
Output
YES
Input
7 11
Output
YES
Input
7 9
Output
NO
Submitted Solution:
```
def f(n):
for i in range(2, n):
if n % i == 0:
return False
return True
n, m = input().split()
n,m = int(n), int(m)
x = 0
for i in range(n+1, m+1):
if f(i) == True:
x = i
break
if x == m:
print('YES')
else:
print('NO')
```
Yes
| 3,855 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers, where y is the next prime number after x, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat n Roman soldiers and it turned out that the number n was prime! Today their victims were a troop of m Romans (m > n). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
Input
The first and only input line contains two positive integers β n and m (2 β€ n < m β€ 50). It is guaranteed that n is prime.
Pretests contain all the cases with restrictions 2 β€ n < m β€ 4.
Output
Print YES, if m is the next prime number after n, or NO otherwise.
Examples
Input
3 5
Output
YES
Input
7 11
Output
YES
Input
7 9
Output
NO
Submitted Solution:
```
from sys import stdin
n,m = map(int, stdin.readline().rstrip().split(' '))
nxt = True
for i in range(n+1, 100, 1):
is_prime = True
for j in range(2, i, 1):
if i % j == 0:
is_prime = False
break
if is_prime:
if i == m:
print('YES')
exit()
else:
print('NO')
exit()
print('NO')
exit()
```
Yes
| 3,856 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers, where y is the next prime number after x, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat n Roman soldiers and it turned out that the number n was prime! Today their victims were a troop of m Romans (m > n). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
Input
The first and only input line contains two positive integers β n and m (2 β€ n < m β€ 50). It is guaranteed that n is prime.
Pretests contain all the cases with restrictions 2 β€ n < m β€ 4.
Output
Print YES, if m is the next prime number after n, or NO otherwise.
Examples
Input
3 5
Output
YES
Input
7 11
Output
YES
Input
7 9
Output
NO
Submitted Solution:
```
from math import sqrt
def is_prime(n):
for i in range(2, int(sqrt(n))+1):
if n%i==0:
return False
return True
n, m = map(int, input().split())
for i in range(n+1, 1000000):
if is_prime(i):
print("YES" if i == m else "NO")
break
```
Yes
| 3,857 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers, where y is the next prime number after x, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat n Roman soldiers and it turned out that the number n was prime! Today their victims were a troop of m Romans (m > n). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
Input
The first and only input line contains two positive integers β n and m (2 β€ n < m β€ 50). It is guaranteed that n is prime.
Pretests contain all the cases with restrictions 2 β€ n < m β€ 4.
Output
Print YES, if m is the next prime number after n, or NO otherwise.
Examples
Input
3 5
Output
YES
Input
7 11
Output
YES
Input
7 9
Output
NO
Submitted Solution:
```
def isPrime(x):
for i in range(2, x):
if x % i == 0:
return -1
return 1
n = list(map(int, input().split()))
count = 0
for i in range(n[0]+1, n[1] + 1):
if isPrime(i) == 1 and count == 0:
count += 1
if i == n[1]:
print('YES')
exit()
print('NO')
```
Yes
| 3,858 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers, where y is the next prime number after x, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat n Roman soldiers and it turned out that the number n was prime! Today their victims were a troop of m Romans (m > n). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
Input
The first and only input line contains two positive integers β n and m (2 β€ n < m β€ 50). It is guaranteed that n is prime.
Pretests contain all the cases with restrictions 2 β€ n < m β€ 4.
Output
Print YES, if m is the next prime number after n, or NO otherwise.
Examples
Input
3 5
Output
YES
Input
7 11
Output
YES
Input
7 9
Output
NO
Submitted Solution:
```
l=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47]
n,m=map(int,input().split())
a=l.index(n)
if n!=47:
if m==l[a+1] :
print("YES")
else:
print("NO")
```
No
| 3,859 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers, where y is the next prime number after x, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat n Roman soldiers and it turned out that the number n was prime! Today their victims were a troop of m Romans (m > n). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
Input
The first and only input line contains two positive integers β n and m (2 β€ n < m β€ 50). It is guaranteed that n is prime.
Pretests contain all the cases with restrictions 2 β€ n < m β€ 4.
Output
Print YES, if m is the next prime number after n, or NO otherwise.
Examples
Input
3 5
Output
YES
Input
7 11
Output
YES
Input
7 9
Output
NO
Submitted Solution:
```
nm=input().split(" ")
n=int(nm[0])
m=int(nm[1])
primes=[2,3,5,7,11,13,17,19,21,23,29,31,37,41,43,47]
ni=primes.index(n)
if m in primes and primes.index(m)==ni+1:
print('YES')
else:
print('NO')
```
No
| 3,860 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers, where y is the next prime number after x, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat n Roman soldiers and it turned out that the number n was prime! Today their victims were a troop of m Romans (m > n). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
Input
The first and only input line contains two positive integers β n and m (2 β€ n < m β€ 50). It is guaranteed that n is prime.
Pretests contain all the cases with restrictions 2 β€ n < m β€ 4.
Output
Print YES, if m is the next prime number after n, or NO otherwise.
Examples
Input
3 5
Output
YES
Input
7 11
Output
YES
Input
7 9
Output
NO
Submitted Solution:
```
"""
Author : Aman Thakur
mantra: chor kya hi kar sakte hai!!
"""
import math
class Solution:
def __init__(self):
self.arr = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
def solution(self):
n, m = map(int, input().strip().split())
if m in self.arr and n in self.arr and m > n:
print('YES')
else:
print('NO')
if __name__ == '__main__':
ob = Solution()
ob.solution()
```
No
| 3,861 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers, where y is the next prime number after x, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat n Roman soldiers and it turned out that the number n was prime! Today their victims were a troop of m Romans (m > n). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
Input
The first and only input line contains two positive integers β n and m (2 β€ n < m β€ 50). It is guaranteed that n is prime.
Pretests contain all the cases with restrictions 2 β€ n < m β€ 4.
Output
Print YES, if m is the next prime number after n, or NO otherwise.
Examples
Input
3 5
Output
YES
Input
7 11
Output
YES
Input
7 9
Output
NO
Submitted Solution:
```
t=input()
x,y=t.split()
c=0
for i in range( (int(x) + 1) , (int(y) + 1) ):
if i %2!=0 and i%3!=0:
c=i
break
elif int(y)==3:
c=3
if c == int(y):
print('YES')
else:
print('NO')
```
No
| 3,862 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
<image>
Some time ago Slastyona the Sweetmaid decided to open her own bakery! She bought required ingredients and a wonder-oven which can bake several types of cakes, and opened the bakery.
Soon the expenses started to overcome the income, so Slastyona decided to study the sweets market. She learned it's profitable to pack cakes in boxes, and that the more distinct cake types a box contains (let's denote this number as the value of the box), the higher price it has.
She needs to change the production technology! The problem is that the oven chooses the cake types on its own and Slastyona can't affect it. However, she knows the types and order of n cakes the oven is going to bake today. Slastyona has to pack exactly k boxes with cakes today, and she has to put in each box several (at least one) cakes the oven produced one right after another (in other words, she has to put in a box a continuous segment of cakes).
Slastyona wants to maximize the total value of all boxes with cakes. Help her determine this maximum possible total value.
Input
The first line contains two integers n and k (1 β€ n β€ 35000, 1 β€ k β€ min(n, 50)) β the number of cakes and the number of boxes, respectively.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β the types of cakes in the order the oven bakes them.
Output
Print the only integer β the maximum total value of all boxes with cakes.
Examples
Input
4 1
1 2 2 1
Output
2
Input
7 2
1 3 3 1 4 4 4
Output
5
Input
8 3
7 7 8 7 7 8 1 7
Output
6
Note
In the first example Slastyona has only one box. She has to put all cakes in it, so that there are two types of cakes in the box, so the value is equal to 2.
In the second example it is profitable to put the first two cakes in the first box, and all the rest in the second. There are two distinct types in the first box, and three in the second box then, so the total value is 5.
Submitted Solution:
```
s=input()
n=int(s[0])
k=int(s[2])
f=input()
l=f.split()
v=[int(l[i]) for i in range (len(l))]
t=[v[0]]
p=0
m=0
o=0
pos=0
for i in range(1,n-1):
if (o==k-1):
pos=i
break
if((v[i]==t[p]) and (v[i]==v[i+1])):
t.append(v[i])
p+=1
elif(v[i]not in t) :
t.append(v[i])
p+=1
else :
m+=len(set(t))
o+=1
p=0
t=[v[i]]
g=v[pos:n]
m=m+len(set(g))
print(m)
```
No
| 3,863 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
<image>
Some time ago Slastyona the Sweetmaid decided to open her own bakery! She bought required ingredients and a wonder-oven which can bake several types of cakes, and opened the bakery.
Soon the expenses started to overcome the income, so Slastyona decided to study the sweets market. She learned it's profitable to pack cakes in boxes, and that the more distinct cake types a box contains (let's denote this number as the value of the box), the higher price it has.
She needs to change the production technology! The problem is that the oven chooses the cake types on its own and Slastyona can't affect it. However, she knows the types and order of n cakes the oven is going to bake today. Slastyona has to pack exactly k boxes with cakes today, and she has to put in each box several (at least one) cakes the oven produced one right after another (in other words, she has to put in a box a continuous segment of cakes).
Slastyona wants to maximize the total value of all boxes with cakes. Help her determine this maximum possible total value.
Input
The first line contains two integers n and k (1 β€ n β€ 35000, 1 β€ k β€ min(n, 50)) β the number of cakes and the number of boxes, respectively.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β the types of cakes in the order the oven bakes them.
Output
Print the only integer β the maximum total value of all boxes with cakes.
Examples
Input
4 1
1 2 2 1
Output
2
Input
7 2
1 3 3 1 4 4 4
Output
5
Input
8 3
7 7 8 7 7 8 1 7
Output
6
Note
In the first example Slastyona has only one box. She has to put all cakes in it, so that there are two types of cakes in the box, so the value is equal to 2.
In the second example it is profitable to put the first two cakes in the first box, and all the rest in the second. There are two distinct types in the first box, and three in the second box then, so the total value is 5.
Submitted Solution:
```
s=input()
n=int(s[0])
k=int(s[2])
f=input()
l=f.split()
v=[int(l[i]) for i in range (len(l))]
t=[v[0]]
p=0
m=0
o=0
pos=0
for i in range(1,n-1):
if (o==k-1):
g=v[pos:n]+[v[i-1]]
pos=i
break
if((v[i]==t[p]) and (v[i]==v[i+1])):
t.append(v[i])
p+=1
elif(v[i]not in t) :
t.append(v[i])
p+=1
else :
print(t)
m+=len(set(t))
o+=1
p=0
t=[v[i]]
print(t)
m=m+len(set(g))
print(m)
```
No
| 3,864 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
<image>
Some time ago Slastyona the Sweetmaid decided to open her own bakery! She bought required ingredients and a wonder-oven which can bake several types of cakes, and opened the bakery.
Soon the expenses started to overcome the income, so Slastyona decided to study the sweets market. She learned it's profitable to pack cakes in boxes, and that the more distinct cake types a box contains (let's denote this number as the value of the box), the higher price it has.
She needs to change the production technology! The problem is that the oven chooses the cake types on its own and Slastyona can't affect it. However, she knows the types and order of n cakes the oven is going to bake today. Slastyona has to pack exactly k boxes with cakes today, and she has to put in each box several (at least one) cakes the oven produced one right after another (in other words, she has to put in a box a continuous segment of cakes).
Slastyona wants to maximize the total value of all boxes with cakes. Help her determine this maximum possible total value.
Input
The first line contains two integers n and k (1 β€ n β€ 35000, 1 β€ k β€ min(n, 50)) β the number of cakes and the number of boxes, respectively.
The second line contains n integers a1, a2, ..., an (1 β€ ai β€ n) β the types of cakes in the order the oven bakes them.
Output
Print the only integer β the maximum total value of all boxes with cakes.
Examples
Input
4 1
1 2 2 1
Output
2
Input
7 2
1 3 3 1 4 4 4
Output
5
Input
8 3
7 7 8 7 7 8 1 7
Output
6
Note
In the first example Slastyona has only one box. She has to put all cakes in it, so that there are two types of cakes in the box, so the value is equal to 2.
In the second example it is profitable to put the first two cakes in the first box, and all the rest in the second. There are two distinct types in the first box, and three in the second box then, so the total value is 5.
Submitted Solution:
```
if 1>1:
print("NO")
else:
print("YES")
# dsajlf skfs lfjs fj safjsa fjals
```
No
| 3,865 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made.
Value of x is calculated as maximum of pΒ·ai + qΒ·aj + rΒ·ak for given p, q, r and array a1, a2, ... an such that 1 β€ i β€ j β€ k β€ n. Help Snape find the value of x. Do note that the value of x may be negative.
Input
First line of input contains 4 integers n, p, q, r ( - 109 β€ p, q, r β€ 109, 1 β€ n β€ 105).
Next line of input contains n space separated integers a1, a2, ... an ( - 109 β€ ai β€ 109).
Output
Output a single integer the maximum value of pΒ·ai + qΒ·aj + rΒ·ak that can be obtained provided 1 β€ i β€ j β€ k β€ n.
Examples
Input
5 1 2 3
1 2 3 4 5
Output
30
Input
5 1 2 -3
-1 -2 -3 -4 -5
Output
12
Note
In the first sample case, we can take i = j = k = 5, thus making the answer as 1Β·5 + 2Β·5 + 3Β·5 = 30.
In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.
Tags: brute force, data structures, dp
Correct Solution:
```
import bisect
from itertools import accumulate, count
import os
import sys
import math
from decimal import *
from io import BytesIO, IOBase
from sys import maxsize
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input():
return sys.stdin.readline().rstrip("\r\n")
def isPrime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i = i + 6
return True
def SieveOfEratosthenes(n):
prime = []
primes = [True for i in range(n + 1)]
p = 2
while p * p <= n:
if primes[p] == True:
prime.append(p)
for i in range(p * p, n + 1, p):
primes[i] = False
p += 1
return prime
def primefactors(n):
fac = []
while n % 2 == 0:
fac.append(2)
n = n // 2
for i in range(3, int(math.sqrt(n)) + 2):
while n % i == 0:
fac.append(i)
n = n // i
if n > 1:
fac.append(n)
return sorted(fac)
def factors(n):
fac = set()
fac.add(1)
fac.add(n)
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
fac.add(i)
fac.add(n // i)
return list(fac)
def modInverse(a, m):
m0 = m
y = 0
x = 1
if m == 1:
return 0
while a > 1:
q = a // m
t = m
m = a % m
a = t
t = y
y = x - q * y
x = t
if x < 0:
x = x + m0
return x
# ------------------------------------------------------code
n,p,q,r=map(int,input().split())
dp=[[0]*(n+1)]*4
a=list(map(int,input().split()))
ans1=-1e22
ans2=-1e22
ans3=-1e22
for i in a:
ans1=max(ans1,p*i)
ans2=max(ans2,ans1+q*i)
ans3=max(ans3,ans2+r*i)
print(ans3)
```
| 3,866 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made.
Value of x is calculated as maximum of pΒ·ai + qΒ·aj + rΒ·ak for given p, q, r and array a1, a2, ... an such that 1 β€ i β€ j β€ k β€ n. Help Snape find the value of x. Do note that the value of x may be negative.
Input
First line of input contains 4 integers n, p, q, r ( - 109 β€ p, q, r β€ 109, 1 β€ n β€ 105).
Next line of input contains n space separated integers a1, a2, ... an ( - 109 β€ ai β€ 109).
Output
Output a single integer the maximum value of pΒ·ai + qΒ·aj + rΒ·ak that can be obtained provided 1 β€ i β€ j β€ k β€ n.
Examples
Input
5 1 2 3
1 2 3 4 5
Output
30
Input
5 1 2 -3
-1 -2 -3 -4 -5
Output
12
Note
In the first sample case, we can take i = j = k = 5, thus making the answer as 1Β·5 + 2Β·5 + 3Β·5 = 30.
In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.
Tags: brute force, data structures, dp
Correct Solution:
```
n,p,q,r=map(int,input().split())
arr=list(map(int,input().split()))
arr1=[p*arr[0]]
for i in range(1,n):
arr1.append(max(p*arr[i],arr1[-1]))
arr2=[arr1[0]+(q*arr[0])]
for i in range(1,n):
arr2.append(max(arr2[-1],arr1[i]+(q*arr[i])))
arr3=[arr2[0]+(r*arr[0])]
for i in range(1,n):
arr3.append(max(arr3[-1],arr2[i]+(r*arr[i])))
print(arr3[-1])
```
| 3,867 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made.
Value of x is calculated as maximum of pΒ·ai + qΒ·aj + rΒ·ak for given p, q, r and array a1, a2, ... an such that 1 β€ i β€ j β€ k β€ n. Help Snape find the value of x. Do note that the value of x may be negative.
Input
First line of input contains 4 integers n, p, q, r ( - 109 β€ p, q, r β€ 109, 1 β€ n β€ 105).
Next line of input contains n space separated integers a1, a2, ... an ( - 109 β€ ai β€ 109).
Output
Output a single integer the maximum value of pΒ·ai + qΒ·aj + rΒ·ak that can be obtained provided 1 β€ i β€ j β€ k β€ n.
Examples
Input
5 1 2 3
1 2 3 4 5
Output
30
Input
5 1 2 -3
-1 -2 -3 -4 -5
Output
12
Note
In the first sample case, we can take i = j = k = 5, thus making the answer as 1Β·5 + 2Β·5 + 3Β·5 = 30.
In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.
Tags: brute force, data structures, dp
Correct Solution:
```
n,p,q,r=map(int,input().split())
arr = list(map(int,input().split()))
n=len(arr)
if n==1:
print(arr[0]*(p+q+r))
else:
pref=[arr[0]]
if(p>0):
for i in range(1,n):
pref.append(max(pref[-1],arr[i]))
else:
for i in range(1,n):
pref.append(min(pref[-1],arr[i]))
suff=[arr[-1]]
if(r>0):
for i in range(n-2,-1,-1):
suff.append(max(suff[-1],arr[i]))
else:
for i in range(n-2,-1,-1):
suff.append(min(suff[-1],arr[i]))
suff=suff[::-1]
ans= float('-inf')
for i in range(n):
ans=max(ans, p*pref[i]+q*arr[i]+r*suff[i])
print(ans)
```
| 3,868 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made.
Value of x is calculated as maximum of pΒ·ai + qΒ·aj + rΒ·ak for given p, q, r and array a1, a2, ... an such that 1 β€ i β€ j β€ k β€ n. Help Snape find the value of x. Do note that the value of x may be negative.
Input
First line of input contains 4 integers n, p, q, r ( - 109 β€ p, q, r β€ 109, 1 β€ n β€ 105).
Next line of input contains n space separated integers a1, a2, ... an ( - 109 β€ ai β€ 109).
Output
Output a single integer the maximum value of pΒ·ai + qΒ·aj + rΒ·ak that can be obtained provided 1 β€ i β€ j β€ k β€ n.
Examples
Input
5 1 2 3
1 2 3 4 5
Output
30
Input
5 1 2 -3
-1 -2 -3 -4 -5
Output
12
Note
In the first sample case, we can take i = j = k = 5, thus making the answer as 1Β·5 + 2Β·5 + 3Β·5 = 30.
In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.
Tags: brute force, data structures, dp
Correct Solution:
```
x = list(map(int, input().split()))
n = x[0]
x[0] = 0
data = list(map(int, input().split()))
ans = [-(10 ** 19)] * 4
ans[0] = 0
for i in data:
for j in range(1, 4):
ans[j] = max(ans[j], ans[j-1] + x[j] * i)
print(ans[3])
```
| 3,869 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made.
Value of x is calculated as maximum of pΒ·ai + qΒ·aj + rΒ·ak for given p, q, r and array a1, a2, ... an such that 1 β€ i β€ j β€ k β€ n. Help Snape find the value of x. Do note that the value of x may be negative.
Input
First line of input contains 4 integers n, p, q, r ( - 109 β€ p, q, r β€ 109, 1 β€ n β€ 105).
Next line of input contains n space separated integers a1, a2, ... an ( - 109 β€ ai β€ 109).
Output
Output a single integer the maximum value of pΒ·ai + qΒ·aj + rΒ·ak that can be obtained provided 1 β€ i β€ j β€ k β€ n.
Examples
Input
5 1 2 3
1 2 3 4 5
Output
30
Input
5 1 2 -3
-1 -2 -3 -4 -5
Output
12
Note
In the first sample case, we can take i = j = k = 5, thus making the answer as 1Β·5 + 2Β·5 + 3Β·5 = 30.
In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.
Tags: brute force, data structures, dp
Correct Solution:
```
nn, p, q, r = map(int, input().split())
ar = list(map(int, input().split()))
max_l = [ar[0]]
for i in range(1, nn):
max_l.append(max(max_l[-1], ar[i]))
min_l = [ar[0]]
for i in range(1, nn):
min_l.append(min(min_l[-1], ar[i]))
max_r = [0] * nn
max_r[-1] = ar[-1]
for i in range(nn - 2, -1, -1):
max_r[i] = max(max_r[i + 1], ar[i])
min_r = [0] * nn
min_r[-1] = ar[-1]
for i in range(nn - 2, -1, -1):
min_r[i] = min(min_r[i + 1], ar[i])
ans = -3 * 10 ** 19
for i in range(0, nn):
t = q * ar[i]
t += p * (min_l[i] if p < 0 else max_l[i])
t += r * (min_r[i] if r < 0 else max_r[i])
ans = max(ans, t)
print(ans)
```
| 3,870 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made.
Value of x is calculated as maximum of pΒ·ai + qΒ·aj + rΒ·ak for given p, q, r and array a1, a2, ... an such that 1 β€ i β€ j β€ k β€ n. Help Snape find the value of x. Do note that the value of x may be negative.
Input
First line of input contains 4 integers n, p, q, r ( - 109 β€ p, q, r β€ 109, 1 β€ n β€ 105).
Next line of input contains n space separated integers a1, a2, ... an ( - 109 β€ ai β€ 109).
Output
Output a single integer the maximum value of pΒ·ai + qΒ·aj + rΒ·ak that can be obtained provided 1 β€ i β€ j β€ k β€ n.
Examples
Input
5 1 2 3
1 2 3 4 5
Output
30
Input
5 1 2 -3
-1 -2 -3 -4 -5
Output
12
Note
In the first sample case, we can take i = j = k = 5, thus making the answer as 1Β·5 + 2Β·5 + 3Β·5 = 30.
In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.
Tags: brute force, data structures, dp
Correct Solution:
```
n, p, q, r = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
crmx, crmn = [a[n - 1]] * n, [a[n - 1]] * n
for i in range(n - 2, -1, -1):
crmx[i] = max(crmx[i + 1], a[i])
crmn[i] = min(crmn[i + 1], a[i])
ans = 0 - 10 ** 21
mn, mx = a[0], a[0]
for i in range(n):
cans = q * a[i]
mx = max(mx, a[i])
mn = min(mn, a[i])
cans += max(mx * p, mn * p)
cans += max(crmx[i] * r, crmn[i] * r)
ans = max(ans, cans)
print(ans)
```
| 3,871 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made.
Value of x is calculated as maximum of pΒ·ai + qΒ·aj + rΒ·ak for given p, q, r and array a1, a2, ... an such that 1 β€ i β€ j β€ k β€ n. Help Snape find the value of x. Do note that the value of x may be negative.
Input
First line of input contains 4 integers n, p, q, r ( - 109 β€ p, q, r β€ 109, 1 β€ n β€ 105).
Next line of input contains n space separated integers a1, a2, ... an ( - 109 β€ ai β€ 109).
Output
Output a single integer the maximum value of pΒ·ai + qΒ·aj + rΒ·ak that can be obtained provided 1 β€ i β€ j β€ k β€ n.
Examples
Input
5 1 2 3
1 2 3 4 5
Output
30
Input
5 1 2 -3
-1 -2 -3 -4 -5
Output
12
Note
In the first sample case, we can take i = j = k = 5, thus making the answer as 1Β·5 + 2Β·5 + 3Β·5 = 30.
In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.
Tags: brute force, data structures, dp
Correct Solution:
```
import sys
n,p,q,r=map(int,input().split())
arr=list(map(int,input().split()))
suffix_max=[0]*n
suffix_max[n-1]=r*arr[n-1]
for i in range(n-2,-1,-1):
suffix_max[i]=max(suffix_max[i+1],r*arr[i])
max_left=-1*sys.maxsize*(10**15)
ans=-1*sys.maxsize*(10**15)
for j in range(0,n):
max_left=max(max_left,p*arr[j])
max_right=suffix_max[j]
max_value_1=q*arr[j]
ans=max(ans,max_left+max_right+max_value_1)
print(ans)
```
| 3,872 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made.
Value of x is calculated as maximum of pΒ·ai + qΒ·aj + rΒ·ak for given p, q, r and array a1, a2, ... an such that 1 β€ i β€ j β€ k β€ n. Help Snape find the value of x. Do note that the value of x may be negative.
Input
First line of input contains 4 integers n, p, q, r ( - 109 β€ p, q, r β€ 109, 1 β€ n β€ 105).
Next line of input contains n space separated integers a1, a2, ... an ( - 109 β€ ai β€ 109).
Output
Output a single integer the maximum value of pΒ·ai + qΒ·aj + rΒ·ak that can be obtained provided 1 β€ i β€ j β€ k β€ n.
Examples
Input
5 1 2 3
1 2 3 4 5
Output
30
Input
5 1 2 -3
-1 -2 -3 -4 -5
Output
12
Note
In the first sample case, we can take i = j = k = 5, thus making the answer as 1Β·5 + 2Β·5 + 3Β·5 = 30.
In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.
Tags: brute force, data structures, dp
Correct Solution:
```
n,p,q,r = map(int,input().split())
alist = list(map(int,input().split()))
a,b,c = -8e18,-8e18,-8e18
for i in range(n):
a = max(a, alist[i]*p)
b = max(b, a+alist[i]*q)
c = max(c, b+alist[i]*r)
print(c)
```
| 3,873 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made.
Value of x is calculated as maximum of pΒ·ai + qΒ·aj + rΒ·ak for given p, q, r and array a1, a2, ... an such that 1 β€ i β€ j β€ k β€ n. Help Snape find the value of x. Do note that the value of x may be negative.
Input
First line of input contains 4 integers n, p, q, r ( - 109 β€ p, q, r β€ 109, 1 β€ n β€ 105).
Next line of input contains n space separated integers a1, a2, ... an ( - 109 β€ ai β€ 109).
Output
Output a single integer the maximum value of pΒ·ai + qΒ·aj + rΒ·ak that can be obtained provided 1 β€ i β€ j β€ k β€ n.
Examples
Input
5 1 2 3
1 2 3 4 5
Output
30
Input
5 1 2 -3
-1 -2 -3 -4 -5
Output
12
Note
In the first sample case, we can take i = j = k = 5, thus making the answer as 1Β·5 + 2Β·5 + 3Β·5 = 30.
In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.
Submitted Solution:
```
a = [int(x) for x in input().split()]
b = [int(y) for y in input().split()]
n = a[0]
p,q,r = a[1], a[2], a[3]
left = []
right = []
for i in range(n):
left.append(b[i]*p)
right.append(b[i]*r)
prefixMax = [0]*n
temp = -10000000000000000000
i = 0
while i < n:
temp = max(temp,left[i])
prefixMax[i] = temp
i += 1
temp = -10000000000000000000
suffixMax = [0]*n
i = n - 1
while i >= 0:
temp = max(temp, right[i])
suffixMax[i] = temp
i -= 1
ans = -10000000000000000000
for j in range(n):
aJ = q*b[j]
lMax = prefixMax[j]
rMax = suffixMax[j]
s = aJ + lMax + rMax
ans = max(ans, s)
print(ans)
```
Yes
| 3,874 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made.
Value of x is calculated as maximum of pΒ·ai + qΒ·aj + rΒ·ak for given p, q, r and array a1, a2, ... an such that 1 β€ i β€ j β€ k β€ n. Help Snape find the value of x. Do note that the value of x may be negative.
Input
First line of input contains 4 integers n, p, q, r ( - 109 β€ p, q, r β€ 109, 1 β€ n β€ 105).
Next line of input contains n space separated integers a1, a2, ... an ( - 109 β€ ai β€ 109).
Output
Output a single integer the maximum value of pΒ·ai + qΒ·aj + rΒ·ak that can be obtained provided 1 β€ i β€ j β€ k β€ n.
Examples
Input
5 1 2 3
1 2 3 4 5
Output
30
Input
5 1 2 -3
-1 -2 -3 -4 -5
Output
12
Note
In the first sample case, we can take i = j = k = 5, thus making the answer as 1Β·5 + 2Β·5 + 3Β·5 = 30.
In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.
Submitted Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 24 20:12:17 2017
@author: savit
"""
def sign(n):
return n//abs(n)
n,p,q,r=map(int,input().split())
A=list(map(int,input().split()))
Q=q
P=p
R=r
if(p<=0 and q<=0 and r<=0):
print((p+q+r)*min(A))
elif(p>=0 and q>=0 and r>=0):
print((p+q+r)*max(A))
elif(p*r>=0 and p<0):
b=[]
max1=-9999999999999999999999999999999
for i in range(n):
b.append((A[i],i))
b.sort()
mini=b[0][1]
temp=mini
temp2=A[mini]
tempb=0
while(temp>=0):
temp2=max(A[temp],temp2)
while(b[tempb][1]>temp):
tempb+=1
max1=max(p*b[tempb][0]+q*temp2 + r*A[mini],max1)
temp-=1
temp2=A[mini]
tempb=0
temp=mini
while(temp<=n-1):
temp2=max(A[temp],temp2)
while(b[tempb][1]<temp):
tempb+=1
max1=max(r*b[tempb][0]+q*temp2 + p*A[mini],max1)
temp+=1
print(max1)
elif(p*r>=0 and p>=0):
b=[]
max1=-9999999999999999999999999999999
for i in range(n):
b.append((A[i],i))
b.sort()
mini=b[n-1][1]
temp=mini
temp2=A[mini]
tempb=n-1
while(temp>=0):
temp2=min(A[temp],temp2)
while(b[tempb][1]>temp):
tempb-=1
max1=max(p*b[tempb][0]+q*temp2 + r*A[mini],max1)
temp-=1
temp2=A[mini]
tempb=n-1
temp=mini
while(temp<=n-1):
temp2=min(A[temp],temp2)
while(b[tempb][1]<temp):
tempb-=1
max1=max(r*b[tempb][0]+q*temp2 + p*A[mini],max1)
#print(b[tempb][1],A.index(temp2),mini)
temp+=1
print(max1)
elif(r>=0):
b=[]
if(q>=0):
r+=q
else:
p+=q
for i in range(n):
b.append((A[i],i))
b.sort()
max1=-99999999999999999999999999999999
temp=0
temp2=A[0]
tempb=n-1
while(temp<=n-1):
temp2=min(temp2,A[temp])
while(b[tempb][1]<temp):
tempb-=1
max1=max(max1,p*temp2+r*b[tempb][0])
temp+=1
print(max1)
elif(r<0):
b=[]
if(q<=0):
r+=q
else:
p+=q
for i in range(n):
b.append((A[i],i))
b.sort()
max1=-9999999999999999999999999999
temp=0
temp2=A[0]
tempb=0
while(temp<=n-1):
temp2=max(temp2,A[temp])
while(b[tempb][1]<temp):
tempb+=1
max1=max(max1,p*temp2+r*b[tempb][0])
temp+=1
print(max1)
```
Yes
| 3,875 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made.
Value of x is calculated as maximum of pΒ·ai + qΒ·aj + rΒ·ak for given p, q, r and array a1, a2, ... an such that 1 β€ i β€ j β€ k β€ n. Help Snape find the value of x. Do note that the value of x may be negative.
Input
First line of input contains 4 integers n, p, q, r ( - 109 β€ p, q, r β€ 109, 1 β€ n β€ 105).
Next line of input contains n space separated integers a1, a2, ... an ( - 109 β€ ai β€ 109).
Output
Output a single integer the maximum value of pΒ·ai + qΒ·aj + rΒ·ak that can be obtained provided 1 β€ i β€ j β€ k β€ n.
Examples
Input
5 1 2 3
1 2 3 4 5
Output
30
Input
5 1 2 -3
-1 -2 -3 -4 -5
Output
12
Note
In the first sample case, we can take i = j = k = 5, thus making the answer as 1Β·5 + 2Β·5 + 3Β·5 = 30.
In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.
Submitted Solution:
```
n,p,q,r=map(int,input().split())
a=list(map(int,input().split()))
INF=10**10
dp=[[-INF]*3 for i in range(n)]
dp[0]=[p*a[0],(p+q)*a[0],(p+q+r)*a[0]]
for i in range(1,n):
dp[i][0]=max(dp[i-1][0],p*a[i])
dp[i][1]=max(dp[i-1][1],dp[i][0]+q*a[i])
dp[i][2]=max(dp[i-1][2],dp[i][1]+r*a[i])
print(dp[n-1][2])
```
Yes
| 3,876 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made.
Value of x is calculated as maximum of pΒ·ai + qΒ·aj + rΒ·ak for given p, q, r and array a1, a2, ... an such that 1 β€ i β€ j β€ k β€ n. Help Snape find the value of x. Do note that the value of x may be negative.
Input
First line of input contains 4 integers n, p, q, r ( - 109 β€ p, q, r β€ 109, 1 β€ n β€ 105).
Next line of input contains n space separated integers a1, a2, ... an ( - 109 β€ ai β€ 109).
Output
Output a single integer the maximum value of pΒ·ai + qΒ·aj + rΒ·ak that can be obtained provided 1 β€ i β€ j β€ k β€ n.
Examples
Input
5 1 2 3
1 2 3 4 5
Output
30
Input
5 1 2 -3
-1 -2 -3 -4 -5
Output
12
Note
In the first sample case, we can take i = j = k = 5, thus making the answer as 1Β·5 + 2Β·5 + 3Β·5 = 30.
In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.
Submitted Solution:
```
cin=lambda:map(int,input().split())
n,p,q,r=cin()
A=cin()
tp,tq,tr=-1e20,-1e20,-1e20
for a in A:
tp=max(tp,p*a)
tq=max(tq,tp+q*a)
tr=max(tr,tq+r*a)
print(tr)
```
Yes
| 3,877 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made.
Value of x is calculated as maximum of pΒ·ai + qΒ·aj + rΒ·ak for given p, q, r and array a1, a2, ... an such that 1 β€ i β€ j β€ k β€ n. Help Snape find the value of x. Do note that the value of x may be negative.
Input
First line of input contains 4 integers n, p, q, r ( - 109 β€ p, q, r β€ 109, 1 β€ n β€ 105).
Next line of input contains n space separated integers a1, a2, ... an ( - 109 β€ ai β€ 109).
Output
Output a single integer the maximum value of pΒ·ai + qΒ·aj + rΒ·ak that can be obtained provided 1 β€ i β€ j β€ k β€ n.
Examples
Input
5 1 2 3
1 2 3 4 5
Output
30
Input
5 1 2 -3
-1 -2 -3 -4 -5
Output
12
Note
In the first sample case, we can take i = j = k = 5, thus making the answer as 1Β·5 + 2Β·5 + 3Β·5 = 30.
In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.
Submitted Solution:
```
_ , x, y, z = map(int, input().split())
a = list(map(int, input().split()))
def ans(x, y, z, a):
all_neg = True
for e in a:
if e >= 0:
all_neg = False
break
def helper(x):
if x == 0:
return 0
if x > 0:
if all_neg:
return x * max(a)
else:
return x * max(a)
if x < 0:
if all_neg:
return x * min(a)
else:
return x * min(a)
#print(helper(x), helper(y), helper(z))
return helper(x) + helper(y) + helper(z)
print(ans(x,y,z,a))
```
No
| 3,878 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made.
Value of x is calculated as maximum of pΒ·ai + qΒ·aj + rΒ·ak for given p, q, r and array a1, a2, ... an such that 1 β€ i β€ j β€ k β€ n. Help Snape find the value of x. Do note that the value of x may be negative.
Input
First line of input contains 4 integers n, p, q, r ( - 109 β€ p, q, r β€ 109, 1 β€ n β€ 105).
Next line of input contains n space separated integers a1, a2, ... an ( - 109 β€ ai β€ 109).
Output
Output a single integer the maximum value of pΒ·ai + qΒ·aj + rΒ·ak that can be obtained provided 1 β€ i β€ j β€ k β€ n.
Examples
Input
5 1 2 3
1 2 3 4 5
Output
30
Input
5 1 2 -3
-1 -2 -3 -4 -5
Output
12
Note
In the first sample case, we can take i = j = k = 5, thus making the answer as 1Β·5 + 2Β·5 + 3Β·5 = 30.
In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.
Submitted Solution:
```
import sys
initial_inp = []
inp = []
n = input().split()
count = int(n[0],10)
p = int(n[1],10)
q = int(n[2],10)
r = int(n[3],10)
arrString = input().split()
arr = count * [None]
for i in range(0,count):
arr[i] = int(arrString[i],10)
print(arr)
def maximum(a,b):
if a < b:
return b
else:
return a
#find prefix max
pmax = [1] * count
pmax[0] = arr[0] * p
print(arr[0],pmax[0])
print(pmax[0])
for i in range(1,count):
pmax[i] = maximum(pmax[i-1],(p*arr[i]))
print(pmax)
#find suffix max
smax = [1] * count
smax[count-1] = arr[count-1]*r
for i in range(count-2,-1,-1):
smax[i]=maximum(smax[i+1],(r*arr[i]))
print(smax)
#to find best position for q multiplier
ans = -sys.maxsize - 1
for i in range(0,count):
ans = maximum((pmax[i]+(q*arr[i])+smax[i]),ans)
print(ans)
```
No
| 3,879 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made.
Value of x is calculated as maximum of pΒ·ai + qΒ·aj + rΒ·ak for given p, q, r and array a1, a2, ... an such that 1 β€ i β€ j β€ k β€ n. Help Snape find the value of x. Do note that the value of x may be negative.
Input
First line of input contains 4 integers n, p, q, r ( - 109 β€ p, q, r β€ 109, 1 β€ n β€ 105).
Next line of input contains n space separated integers a1, a2, ... an ( - 109 β€ ai β€ 109).
Output
Output a single integer the maximum value of pΒ·ai + qΒ·aj + rΒ·ak that can be obtained provided 1 β€ i β€ j β€ k β€ n.
Examples
Input
5 1 2 3
1 2 3 4 5
Output
30
Input
5 1 2 -3
-1 -2 -3 -4 -5
Output
12
Note
In the first sample case, we can take i = j = k = 5, thus making the answer as 1Β·5 + 2Β·5 + 3Β·5 = 30.
In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.
Submitted Solution:
```
n, p, q, r = map(int, input().split())
a = list(map(int, input().split()))
def findmx(a, h):
mxi = 0
#print(len(a))
for i in range(len(a)):
if (a[mxi] * h <= a[i] * h):
mxi = i
return mxi
##a1 = [i * p for i in a]
##a2 = [i * q for i in a]
##a3 = [i * r for i in a]
##
l1 = findmx(a, r)
l2 = findmx(a[0:l1 + 1], q)
l3 = findmx(a[0:l2 + 1], p)
##print(l3, l2, l1)
##print(a1)
##print(a2)
##print(a3)
l = p * a[l3] + q * a[l2] + r * a[l1]
##print()
h2 = findmx(a, q)
h1 = findmx(a[h2::], r) + h2
h3 = findmx(a[0:h2 + 1], p)
#print(h3, h2, h1)
h = p * a[h3] + q * a[h2] + r * a[h1]
##print()
##
##b = []
##for i in range(0, n):
## for j in range(0, i + 1):
## for k in range(0, j + 1):
## b.append([k, j, i, a1[k], a2[j], a3[i], a1[k] + a2[j] + a3[i]])
##print(*b, sep = "\n")
##
y3 = findmx(a, p)
y2 = findmx(a[y3::], q) + y3
y1 = findmx(a[y2::], r) + y2
#print(y3, y2, y1)
y = p * a[y3] + q * a[y2] + r * a[y1]
#print(l, h, y)
print(max(l, h, y))
```
No
| 3,880 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made.
Value of x is calculated as maximum of pΒ·ai + qΒ·aj + rΒ·ak for given p, q, r and array a1, a2, ... an such that 1 β€ i β€ j β€ k β€ n. Help Snape find the value of x. Do note that the value of x may be negative.
Input
First line of input contains 4 integers n, p, q, r ( - 109 β€ p, q, r β€ 109, 1 β€ n β€ 105).
Next line of input contains n space separated integers a1, a2, ... an ( - 109 β€ ai β€ 109).
Output
Output a single integer the maximum value of pΒ·ai + qΒ·aj + rΒ·ak that can be obtained provided 1 β€ i β€ j β€ k β€ n.
Examples
Input
5 1 2 3
1 2 3 4 5
Output
30
Input
5 1 2 -3
-1 -2 -3 -4 -5
Output
12
Note
In the first sample case, we can take i = j = k = 5, thus making the answer as 1Β·5 + 2Β·5 + 3Β·5 = 30.
In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.
Submitted Solution:
```
b, p, q, r=[5, 1, 2, -3]
n=[-1, -2, -3, -4, -5]
ans = float('-infinity')
for ai in n:
for aj in n:
for ak in n:
ans = max(ans, p*ai+q*aj+r*ak)
print(ans)
```
No
| 3,881 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.
After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.
Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 > a2.
The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.
Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.
Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
Input
The first line contains three integers h1, a1, c1 (1 β€ h1, a1 β€ 100, 2 β€ c1 β€ 100) β Vova's health, Vova's attack power and the healing power of a potion.
The second line contains two integers h2, a2 (1 β€ h2 β€ 100, 1 β€ a2 < c1) β the Modcrab's health and his attack power.
Output
In the first line print one integer n denoting the minimum number of phases required to win the battle.
Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab.
The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action.
If there are multiple optimal solutions, print any of them.
Examples
Input
10 6 100
17 5
Output
4
STRIKE
HEAL
STRIKE
STRIKE
Input
11 6 100
12 5
Output
2
STRIKE
STRIKE
Note
In the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.
In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Tags: greedy, implementation
Correct Solution:
```
import unittest
from functools import lru_cache
import math
h1, a1, c1 = tuple(map(int, input().split()))
h2, a2 = tuple(map(int, input().split()))
num_of_moves_to_kill = int(math.ceil(h2 / a1))
health_loosed = a2 * (num_of_moves_to_kill - 1)
if health_loosed < h1:
print(num_of_moves_to_kill)
for i in range(num_of_moves_to_kill):
print("STRIKE")
else:
health_needed = health_loosed - h1
drinks = math.floor(health_needed / (c1 - a2)) + 1
print(num_of_moves_to_kill + drinks)
for i in range(drinks):
print("HEAL")
for i in range(num_of_moves_to_kill):
print("STRIKE")
# 50 10 10
# 100 5
```
| 3,882 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.
After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.
Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 > a2.
The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.
Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.
Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
Input
The first line contains three integers h1, a1, c1 (1 β€ h1, a1 β€ 100, 2 β€ c1 β€ 100) β Vova's health, Vova's attack power and the healing power of a potion.
The second line contains two integers h2, a2 (1 β€ h2 β€ 100, 1 β€ a2 < c1) β the Modcrab's health and his attack power.
Output
In the first line print one integer n denoting the minimum number of phases required to win the battle.
Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab.
The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action.
If there are multiple optimal solutions, print any of them.
Examples
Input
10 6 100
17 5
Output
4
STRIKE
HEAL
STRIKE
STRIKE
Input
11 6 100
12 5
Output
2
STRIKE
STRIKE
Note
In the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.
In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Tags: greedy, implementation
Correct Solution:
```
import math
h = [0, 0]
a = [0, 0]
c = 0
h[0], a[0], c = map(int, input().strip().split())
h[1], a[1] = map(int, input().strip().split())
res = []
count = 0
while h[1] > 0:
if h[0] > a[1] or (h[0] <= a[1] and h[1] <= a[0]):
res.append("STRIKE")
h[1] -= a[0]
else:
res.append("HEAL")
h[0] += c
h[0] -= a[1]
count += 1
print(str(count))
for item in res:
print(item)
```
| 3,883 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.
After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.
Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 > a2.
The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.
Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.
Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
Input
The first line contains three integers h1, a1, c1 (1 β€ h1, a1 β€ 100, 2 β€ c1 β€ 100) β Vova's health, Vova's attack power and the healing power of a potion.
The second line contains two integers h2, a2 (1 β€ h2 β€ 100, 1 β€ a2 < c1) β the Modcrab's health and his attack power.
Output
In the first line print one integer n denoting the minimum number of phases required to win the battle.
Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab.
The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action.
If there are multiple optimal solutions, print any of them.
Examples
Input
10 6 100
17 5
Output
4
STRIKE
HEAL
STRIKE
STRIKE
Input
11 6 100
12 5
Output
2
STRIKE
STRIKE
Note
In the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.
In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Tags: greedy, implementation
Correct Solution:
```
h1,a1,c1 = map(int,input().split())
h2,a2 = map(int,input().split())
l = []
while(h2 > 0):
if h1-a2 <= 0 and (h2-a1) > 0:
l.append("HEAL")
h1 = h1+c1
else:
l.append("STRIKE")
h2 = h2-a1
h1 = h1-a2
print(len(l))
for i in l:
print(i)
```
| 3,884 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.
After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.
Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 > a2.
The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.
Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.
Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
Input
The first line contains three integers h1, a1, c1 (1 β€ h1, a1 β€ 100, 2 β€ c1 β€ 100) β Vova's health, Vova's attack power and the healing power of a potion.
The second line contains two integers h2, a2 (1 β€ h2 β€ 100, 1 β€ a2 < c1) β the Modcrab's health and his attack power.
Output
In the first line print one integer n denoting the minimum number of phases required to win the battle.
Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab.
The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action.
If there are multiple optimal solutions, print any of them.
Examples
Input
10 6 100
17 5
Output
4
STRIKE
HEAL
STRIKE
STRIKE
Input
11 6 100
12 5
Output
2
STRIKE
STRIKE
Note
In the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.
In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Tags: greedy, implementation
Correct Solution:
```
def main():
h1, a1, c = map(int, input().split())
h2, a2 = map(int, input().split())
out = []
while h2 > 0:
if a2 < h1 or a1 >= h2:
out.append('STRIKE')
h2 -= a1
h1 -= a2
else:
out.append('HEAL')
h1 += c
h1 -= a2
print(len(out))
for s in out:
print(s)
main()
```
| 3,885 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.
After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.
Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 > a2.
The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.
Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.
Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
Input
The first line contains three integers h1, a1, c1 (1 β€ h1, a1 β€ 100, 2 β€ c1 β€ 100) β Vova's health, Vova's attack power and the healing power of a potion.
The second line contains two integers h2, a2 (1 β€ h2 β€ 100, 1 β€ a2 < c1) β the Modcrab's health and his attack power.
Output
In the first line print one integer n denoting the minimum number of phases required to win the battle.
Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab.
The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action.
If there are multiple optimal solutions, print any of them.
Examples
Input
10 6 100
17 5
Output
4
STRIKE
HEAL
STRIKE
STRIKE
Input
11 6 100
12 5
Output
2
STRIKE
STRIKE
Note
In the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.
In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Tags: greedy, implementation
Correct Solution:
```
life, attack, heal = map(int,input().split())
ml, ma = map(int,input().split())
ans=''
count=0
while ml>0:
if life <= ma and ml> attack:
life +=heal
ans+='HEAL\n'
else :
ml-=attack
ans+='STRIKE\n'
life-=ma
count+=1
ans=str(count)+"\n"+ans
print(ans)
```
| 3,886 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.
After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.
Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 > a2.
The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.
Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.
Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
Input
The first line contains three integers h1, a1, c1 (1 β€ h1, a1 β€ 100, 2 β€ c1 β€ 100) β Vova's health, Vova's attack power and the healing power of a potion.
The second line contains two integers h2, a2 (1 β€ h2 β€ 100, 1 β€ a2 < c1) β the Modcrab's health and his attack power.
Output
In the first line print one integer n denoting the minimum number of phases required to win the battle.
Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab.
The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action.
If there are multiple optimal solutions, print any of them.
Examples
Input
10 6 100
17 5
Output
4
STRIKE
HEAL
STRIKE
STRIKE
Input
11 6 100
12 5
Output
2
STRIKE
STRIKE
Note
In the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.
In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Tags: greedy, implementation
Correct Solution:
```
h1,a1,c1 = map(int,input().split())
h2,a2 = map(int,input().split())
li = []
while 1:
if (h1-a2)>0 or (h2-a1)<=0:
h2-=a1
li.append("STRIKE")
else:
li.append("HEAL")
h1+=c1
if h2<=0:
break
h1-=a2
print(len(li))
for i in li:
print(i)
```
| 3,887 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.
After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.
Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 > a2.
The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.
Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.
Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
Input
The first line contains three integers h1, a1, c1 (1 β€ h1, a1 β€ 100, 2 β€ c1 β€ 100) β Vova's health, Vova's attack power and the healing power of a potion.
The second line contains two integers h2, a2 (1 β€ h2 β€ 100, 1 β€ a2 < c1) β the Modcrab's health and his attack power.
Output
In the first line print one integer n denoting the minimum number of phases required to win the battle.
Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab.
The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action.
If there are multiple optimal solutions, print any of them.
Examples
Input
10 6 100
17 5
Output
4
STRIKE
HEAL
STRIKE
STRIKE
Input
11 6 100
12 5
Output
2
STRIKE
STRIKE
Note
In the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.
In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Tags: greedy, implementation
Correct Solution:
```
h1, a1, c = [int(i) for i in input().split()]
h2, a2 = [int(i) for i in input().split()]
y = (h2 + a1 - 1) // a1
x = max((a2 * (y - 1) - h1 + c - a2), 0) // (c - a2)
print(x + y)
for i in range(x):
print('HEAL')
for i in range(y):
print('STRIKE')
```
| 3,888 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.
After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.
Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 > a2.
The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.
Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.
Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
Input
The first line contains three integers h1, a1, c1 (1 β€ h1, a1 β€ 100, 2 β€ c1 β€ 100) β Vova's health, Vova's attack power and the healing power of a potion.
The second line contains two integers h2, a2 (1 β€ h2 β€ 100, 1 β€ a2 < c1) β the Modcrab's health and his attack power.
Output
In the first line print one integer n denoting the minimum number of phases required to win the battle.
Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab.
The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action.
If there are multiple optimal solutions, print any of them.
Examples
Input
10 6 100
17 5
Output
4
STRIKE
HEAL
STRIKE
STRIKE
Input
11 6 100
12 5
Output
2
STRIKE
STRIKE
Note
In the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.
In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Tags: greedy, implementation
Correct Solution:
```
h1, a1, c1 = map(int, input().split())
h2, a2 = map(int, input().split())
data = []
while h2 > 0:
# Attack
if h1 > a2 or a1 >= h2:
h2 -= a1
data.append("STRIKE")
# Heal
else:
h1 += c1
data.append("HEAL")
h1 -= a2
print(len(data))
for item in data:
print(item)
```
| 3,889 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.
After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.
Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 > a2.
The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.
Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.
Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
Input
The first line contains three integers h1, a1, c1 (1 β€ h1, a1 β€ 100, 2 β€ c1 β€ 100) β Vova's health, Vova's attack power and the healing power of a potion.
The second line contains two integers h2, a2 (1 β€ h2 β€ 100, 1 β€ a2 < c1) β the Modcrab's health and his attack power.
Output
In the first line print one integer n denoting the minimum number of phases required to win the battle.
Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab.
The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action.
If there are multiple optimal solutions, print any of them.
Examples
Input
10 6 100
17 5
Output
4
STRIKE
HEAL
STRIKE
STRIKE
Input
11 6 100
12 5
Output
2
STRIKE
STRIKE
Note
In the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.
In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Submitted Solution:
```
h1, a1, c1 = [int(i) for i in input().split()]
h2, a2 = [int(i) for i in input().split()]
k = (h2 + a1 - 1) // a1
#print(k)
e = []
while k > 0:
#print(k, h1, a2)
if k == 1:
e.append("STRIKE")
break
if h1 <= a2:
e.append("HEAL")
h1 += c1
else:
e.append("STRIKE")
k -= 1
h1 -= a2
print(len(e))
for el in e:
print(el)
```
Yes
| 3,890 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.
After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.
Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 > a2.
The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.
Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.
Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
Input
The first line contains three integers h1, a1, c1 (1 β€ h1, a1 β€ 100, 2 β€ c1 β€ 100) β Vova's health, Vova's attack power and the healing power of a potion.
The second line contains two integers h2, a2 (1 β€ h2 β€ 100, 1 β€ a2 < c1) β the Modcrab's health and his attack power.
Output
In the first line print one integer n denoting the minimum number of phases required to win the battle.
Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab.
The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action.
If there are multiple optimal solutions, print any of them.
Examples
Input
10 6 100
17 5
Output
4
STRIKE
HEAL
STRIKE
STRIKE
Input
11 6 100
12 5
Output
2
STRIKE
STRIKE
Note
In the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.
In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Submitted Solution:
```
l=list(map(int,input().split()))
l1=list(map(int,input().split()))
k=0
S=''
while l1[0]>0 :
k+=1
if l1[0]-l[1]<=0 :
S+="STRIKE"+"\n"
break
if l[0]-l1[1]<=0 :
S+="HEAL"+"\n"
l[0]=l[0]+l[2]
else :
l1[0]=l1[0]-l[1]
S+="STRIKE"+"\n"
l[0]-=l1[1]
print(k)
print(S)
```
Yes
| 3,891 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.
After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.
Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 > a2.
The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.
Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.
Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
Input
The first line contains three integers h1, a1, c1 (1 β€ h1, a1 β€ 100, 2 β€ c1 β€ 100) β Vova's health, Vova's attack power and the healing power of a potion.
The second line contains two integers h2, a2 (1 β€ h2 β€ 100, 1 β€ a2 < c1) β the Modcrab's health and his attack power.
Output
In the first line print one integer n denoting the minimum number of phases required to win the battle.
Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab.
The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action.
If there are multiple optimal solutions, print any of them.
Examples
Input
10 6 100
17 5
Output
4
STRIKE
HEAL
STRIKE
STRIKE
Input
11 6 100
12 5
Output
2
STRIKE
STRIKE
Note
In the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.
In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Submitted Solution:
```
R=lambda:map(int,input().split())
h,a,c=R()
g,b=R()
l=[]
while g>0:
while h<=b and g>a:
l.append('HEAL')
h+=c-b
while g>0 and (h>b or g<=a):
l.append('STRIKE')
g-=a
h-=b
print(len(l),*l,sep='\n')
```
Yes
| 3,892 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.
After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.
Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 > a2.
The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.
Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.
Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
Input
The first line contains three integers h1, a1, c1 (1 β€ h1, a1 β€ 100, 2 β€ c1 β€ 100) β Vova's health, Vova's attack power and the healing power of a potion.
The second line contains two integers h2, a2 (1 β€ h2 β€ 100, 1 β€ a2 < c1) β the Modcrab's health and his attack power.
Output
In the first line print one integer n denoting the minimum number of phases required to win the battle.
Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab.
The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action.
If there are multiple optimal solutions, print any of them.
Examples
Input
10 6 100
17 5
Output
4
STRIKE
HEAL
STRIKE
STRIKE
Input
11 6 100
12 5
Output
2
STRIKE
STRIKE
Note
In the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.
In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Submitted Solution:
```
a = list(map(int,input().split()))
b = list(map(int,input().split()))
t = []
while b[0]>0:
if b[1]>=a[0] and a[1]<b[0]:
a[0]= a[0]+a[2]
t.append("HEAL")
else:
b[0]=b[0]-a[1]
t.append("STRIKE")
a[0]=a[0]-b[1]
print(len(t))
for x in t:
print(x)
```
Yes
| 3,893 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.
After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.
Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 > a2.
The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.
Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.
Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
Input
The first line contains three integers h1, a1, c1 (1 β€ h1, a1 β€ 100, 2 β€ c1 β€ 100) β Vova's health, Vova's attack power and the healing power of a potion.
The second line contains two integers h2, a2 (1 β€ h2 β€ 100, 1 β€ a2 < c1) β the Modcrab's health and his attack power.
Output
In the first line print one integer n denoting the minimum number of phases required to win the battle.
Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab.
The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action.
If there are multiple optimal solutions, print any of them.
Examples
Input
10 6 100
17 5
Output
4
STRIKE
HEAL
STRIKE
STRIKE
Input
11 6 100
12 5
Output
2
STRIKE
STRIKE
Note
In the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.
In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Submitted Solution:
```
h1,a1,c1 = map(int, input().split()) # xiaohuang's property
h2,a2 = map(int, input().split()) # monster's property
h1_remain = h1
h2_remain = h2
record_list = []
while h2_remain >= 0:
if a2 >= h1_remain:
#print("HEAL")
record_list.append("HEAL")
h1_remain += c1
else:
#print("STRIKE")
record_list.append("STRIKE")
h2_remain -= a1
h1_remain -= a2
print(len(record_list))
for i in record_list:
print(i)
```
No
| 3,894 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.
After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.
Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 > a2.
The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.
Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.
Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
Input
The first line contains three integers h1, a1, c1 (1 β€ h1, a1 β€ 100, 2 β€ c1 β€ 100) β Vova's health, Vova's attack power and the healing power of a potion.
The second line contains two integers h2, a2 (1 β€ h2 β€ 100, 1 β€ a2 < c1) β the Modcrab's health and his attack power.
Output
In the first line print one integer n denoting the minimum number of phases required to win the battle.
Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab.
The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action.
If there are multiple optimal solutions, print any of them.
Examples
Input
10 6 100
17 5
Output
4
STRIKE
HEAL
STRIKE
STRIKE
Input
11 6 100
12 5
Output
2
STRIKE
STRIKE
Note
In the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.
In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Submitted Solution:
```
life, attack, heal = map(int,input().split())
ml, ma = map(int,input().split())
ans=''
count=0
while ml>0:
if life <= ma :
life +=heal
ans+='HEAl\n'
else :
ml-=attack
ans+='STRIKE\n'
life-=ma
count+=1
ans=str(count)+"\n"+ans
print(ans)
```
No
| 3,895 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.
After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.
Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 > a2.
The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.
Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.
Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
Input
The first line contains three integers h1, a1, c1 (1 β€ h1, a1 β€ 100, 2 β€ c1 β€ 100) β Vova's health, Vova's attack power and the healing power of a potion.
The second line contains two integers h2, a2 (1 β€ h2 β€ 100, 1 β€ a2 < c1) β the Modcrab's health and his attack power.
Output
In the first line print one integer n denoting the minimum number of phases required to win the battle.
Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab.
The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action.
If there are multiple optimal solutions, print any of them.
Examples
Input
10 6 100
17 5
Output
4
STRIKE
HEAL
STRIKE
STRIKE
Input
11 6 100
12 5
Output
2
STRIKE
STRIKE
Note
In the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.
In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Submitted Solution:
```
import math
h1, a1, c1 = map(int,input().split(' '))
h2, a2 = map(int,input().split(' '))
x=math.ceil(h2/a1)
z=x*a2
y=max(0,math.ceil((z-h1)/c1))
print(x+y)
for i in range(0,y):
print("HEAL")
for i in range(0,x):
print("STRIKE")
```
No
| 3,896 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.
After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.
Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 > a2.
The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.
Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.
Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
Input
The first line contains three integers h1, a1, c1 (1 β€ h1, a1 β€ 100, 2 β€ c1 β€ 100) β Vova's health, Vova's attack power and the healing power of a potion.
The second line contains two integers h2, a2 (1 β€ h2 β€ 100, 1 β€ a2 < c1) β the Modcrab's health and his attack power.
Output
In the first line print one integer n denoting the minimum number of phases required to win the battle.
Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab.
The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action.
If there are multiple optimal solutions, print any of them.
Examples
Input
10 6 100
17 5
Output
4
STRIKE
HEAL
STRIKE
STRIKE
Input
11 6 100
12 5
Output
2
STRIKE
STRIKE
Note
In the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.
In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Submitted Solution:
```
import math
first_line = input().split(' ')
second_line = input().split(' ')
h1 = int(first_line[0])
a1 = int(first_line[1])
c1 = int(first_line[2])
h2 = int(second_line[0])
a2 = int(second_line[1])
strike_num = math.ceil(h2 / a1)
print(strike_num)
heal_num = math.ceil(max(0, ((strike_num - 1) * a2 - h1 + 1)) / (c1 - a2))
print(heal_num)
print(strike_num + heal_num)
print('HEAL\n' * heal_num, end='')
print("STRIKE\n" * strike_num, end='')
```
No
| 3,897 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vitya has learned that the answer for The Ultimate Question of Life, the Universe, and Everything is not the integer 54 42, but an increasing integer sequence a_1, β¦, a_n. In order to not reveal the secret earlier than needed, Vitya encrypted the answer and obtained the sequence b_1, β¦, b_n using the following rules:
* b_1 = a_1;
* b_i = a_i β a_{i - 1} for all i from 2 to n, where x β y is the [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of x and y.
It is easy to see that the original sequence can be obtained using the rule a_i = b_1 β β¦ β b_i.
However, some time later Vitya discovered that the integers b_i in the cypher got shuffled, and it can happen that when decrypted using the rule mentioned above, it can produce a sequence that is not increasing. In order to save his reputation in the scientific community, Vasya decided to find some permutation of integers b_i so that the sequence a_i = b_1 β β¦ β b_i is strictly increasing. Help him find such a permutation or determine that it is impossible.
Input
The first line contains a single integer n (1 β€ n β€ 10^5).
The second line contains n integers b_1, β¦, b_n (1 β€ b_i < 2^{60}).
Output
If there are no valid permutations, print a single line containing "No".
Otherwise in the first line print the word "Yes", and in the second line print integers b'_1, β¦, b'_n β a valid permutation of integers b_i. The unordered multisets \\{b_1, β¦, b_n\} and \\{b'_1, β¦, b'_n\} should be equal, i. e. for each integer x the number of occurrences of x in the first multiset should be equal to the number of occurrences of x in the second multiset. Apart from this, the sequence a_i = b'_1 β β¦ β b'_i should be strictly increasing.
If there are multiple answers, print any of them.
Examples
Input
3
1 2 3
Output
No
Input
6
4 7 7 12 31 61
Output
Yes
4 12 7 31 7 61
Note
In the first example no permutation is valid.
In the second example the given answer lead to the sequence a_1 = 4, a_2 = 8, a_3 = 15, a_4 = 16, a_5 = 23, a_6 = 42.
Tags: constructive algorithms, math
Correct Solution:
```
n=int(input())
s=[[] for i in range(60)]
for b in list(map(int,input().split())):
for i in range(59,-1,-1):
if b>>i&1:
s[i].append(b)
break
ans=[]
cur=0
for i in range(n):
fl=False
for j in range(60):
if s[j]!=[] and cur>>j&1==0:
ans.append(s[j][-1])
cur^=s[j][-1]
s[j].pop()
fl=True
break
if not fl:
print('No')
exit()
print('Yes')
print(' '.join(str(i) for i in ans))
```
| 3,898 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vitya has learned that the answer for The Ultimate Question of Life, the Universe, and Everything is not the integer 54 42, but an increasing integer sequence a_1, β¦, a_n. In order to not reveal the secret earlier than needed, Vitya encrypted the answer and obtained the sequence b_1, β¦, b_n using the following rules:
* b_1 = a_1;
* b_i = a_i β a_{i - 1} for all i from 2 to n, where x β y is the [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of x and y.
It is easy to see that the original sequence can be obtained using the rule a_i = b_1 β β¦ β b_i.
However, some time later Vitya discovered that the integers b_i in the cypher got shuffled, and it can happen that when decrypted using the rule mentioned above, it can produce a sequence that is not increasing. In order to save his reputation in the scientific community, Vasya decided to find some permutation of integers b_i so that the sequence a_i = b_1 β β¦ β b_i is strictly increasing. Help him find such a permutation or determine that it is impossible.
Input
The first line contains a single integer n (1 β€ n β€ 10^5).
The second line contains n integers b_1, β¦, b_n (1 β€ b_i < 2^{60}).
Output
If there are no valid permutations, print a single line containing "No".
Otherwise in the first line print the word "Yes", and in the second line print integers b'_1, β¦, b'_n β a valid permutation of integers b_i. The unordered multisets \\{b_1, β¦, b_n\} and \\{b'_1, β¦, b'_n\} should be equal, i. e. for each integer x the number of occurrences of x in the first multiset should be equal to the number of occurrences of x in the second multiset. Apart from this, the sequence a_i = b'_1 β β¦ β b'_i should be strictly increasing.
If there are multiple answers, print any of them.
Examples
Input
3
1 2 3
Output
No
Input
6
4 7 7 12 31 61
Output
Yes
4 12 7 31 7 61
Note
In the first example no permutation is valid.
In the second example the given answer lead to the sequence a_1 = 4, a_2 = 8, a_3 = 15, a_4 = 16, a_5 = 23, a_6 = 42.
Submitted Solution:
```
from itertools import permutations
def check(l):
arr = [l[0]]
for i in range(1,len(l)):
a = arr[-1] ^ l[i]
if(a <= arr[-1]):
return False
else:
arr.append(a)
return l
n = int(input())
b = [int(i) for i in input().split()]
L = list(permutations(b))
for l in L:
if(check(l)!=False):
print("YES")
[print(i,end=" ") for i in l]
exit()
print("NO")
```
No
| 3,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.