text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.
All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.
Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.
The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
Output
The first line must contain the minimum possible total cost of delaying the flights.
The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
Example
Input
5 2
4 2 1 10 2
Output
20
3 6 7 4 5
Note
Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles.
However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Tags: greedy
Correct Solution:
```
from heapq import heappush,heappop,heapify
n,k=map(int,input().split())
*l,=map(int,input().split())
q=[(-l[i],i)for i in range(k)]
heapify(q)
a=[0]*n
s=0
for i in range(k,n) :
heappush(q,(-l[i],i))
x,j=heappop(q)
s-=x*(i-j)
a[j]=i+1
for i in range(n,n+k) :
x,j=heappop(q)
s-=x*(i-j)
a[j]=i+1
print(s)
print(' '.join(map(str,a)))
```
| 14,700 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.
All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.
Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.
The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
Output
The first line must contain the minimum possible total cost of delaying the flights.
The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
Example
Input
5 2
4 2 1 10 2
Output
20
3 6 7 4 5
Note
Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles.
However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Tags: greedy
Correct Solution:
```
import sys
input = sys.stdin.readline
from heapq import *
n, k = map(int, input().split())
c = list(map(int, input().split()))
ic = [(-c[i], i+1) for i in range(n)]
pq = []
idx = 0
ans_v = 0
ans_arr = [-1]*n
for t in range(k+1, k+n+1):
while idx<n:
if ic[idx][1]<=t:
heappush(pq, ic[idx])
idx += 1
else:
break
ci, i = heappop(pq)
ci *= -1
ans_v += (t-i)*ci
ans_arr[i-1] = t
print(ans_v)
print(*ans_arr)
```
| 14,701 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.
All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.
Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.
The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
Output
The first line must contain the minimum possible total cost of delaying the flights.
The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
Example
Input
5 2
4 2 1 10 2
Output
20
3 6 7 4 5
Note
Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles.
However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Submitted Solution:
```
# from debug import debug
# from heapq import heappush, heappop, heapify
from heapq import *
n, k = map(int, input().split())
c = list(map(int, input().split()))
q = [(-c[i], i) for i in range(k)]
heapify(q)
ans = 0
lis = [0]*n
for i in range(k, n):
heappush(q, (-c[i], i))
a, p = heappop(q)
ans += a*(i-p)
lis[p] = i+1
for i in range(n, n+k):
a, p = heappop(q)
ans += a*(i-p)
lis[p] = i+1
print(-ans)
print(*lis)
```
Yes
| 14,702 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.
All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.
Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.
The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
Output
The first line must contain the minimum possible total cost of delaying the flights.
The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
Example
Input
5 2
4 2 1 10 2
Output
20
3 6 7 4 5
Note
Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles.
However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Submitted Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
from heapq import heappush, heappop, heapify
n, k = map(int, input().split())
a = list(map(int, input().split()))
q = [(-a[i], i) for i in range(k)]
heapify(q)
res, s = [0] * n, 0
for i in range(k, n):
heappush(q, (-a[i], i))
x, j = heappop(q)
s -= x * (i-j)
res[j] = i+1
for i in range(n, n+k):
x, j = heappop(q)
s -= x * (i-j)
res[j] = i+1
print(s)
print(*res)
```
Yes
| 14,703 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.
All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.
Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.
The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
Output
The first line must contain the minimum possible total cost of delaying the flights.
The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
Example
Input
5 2
4 2 1 10 2
Output
20
3 6 7 4 5
Note
Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles.
However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Submitted Solution:
```
import heapq
n, k = map(int, input().split())
costs = list(map(int, input().split()))
res = 0
heap_cost = 0
h = []
for i in range(k):
res += (k - i) * costs[i]
heapq.heappush(h, (-costs[i], i))
heap_cost += costs[i]
times = [0 for i in range(n)]
for i in range(n):
if k + i < n:
heapq.heappush(h, (-costs[k + i], k + i))
heap_cost += costs[k + i]
flight = heapq.heappop(h)
times[flight[1]] = k + i
heap_cost -= -flight[0]
res += heap_cost
print(res)
for t in times:
print(t, end = ' ')
```
No
| 14,704 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.
All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.
Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.
The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
Output
The first line must contain the minimum possible total cost of delaying the flights.
The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
Example
Input
5 2
4 2 1 10 2
Output
20
3 6 7 4 5
Note
Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles.
However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Submitted Solution:
```
import re
n,k = map(int,input().split())
cost = [int(i) for i in re.findall("\d+\s",input()+" ")]
COST = 0
plan = [-1 for i in range(n)]
if k < n:
for i in range(0,n-k):
plan[i] = i+k
for i in range(0,min(k,n)):
insert = i
run = True
while run:
inspoint = 0
compare = True
while compare:
if plan[inspoint]==-1:
insert,plan[inspoint] = plan[inspoint],insert
compare = False
elif cost[insert] > cost[plan[inspoint]]:
insert,plan[inspoint] = plan[inspoint],insert
compare = False
else:
inspoint += 1
if insert == -1:
run = False
planning = [plan.index(i)+3 for i in range(0,n)]
for i in range(0,n):
COST += (planning[i]-i-1)*cost[i]
print(COST)
print(" ".join([str(i) for i in planning]))
```
No
| 14,705 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.
All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.
Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.
The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
Output
The first line must contain the minimum possible total cost of delaying the flights.
The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
Example
Input
5 2
4 2 1 10 2
Output
20
3 6 7 4 5
Note
Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles.
However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Submitted Solution:
```
l=[int(x) for x in input().split()]
m=input()
s=[]
c=1
j=[]
for x in m.split():
s.append([int(x),c])
j.append(l[1]+c)
c=c+1
s.sort(key=lambda s: (s[0], -s[1]), reverse=True)
su=0
for i in range(l[0]):
if s[i][1] in j:
j.remove(s[i][1])
else:
su=su+(j[0]-s[i][1])*s[i][0]
j.remove(j[0])
print(su)
```
No
| 14,706 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.
All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.
Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.
Input
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart.
The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.
Output
The first line must contain the minimum possible total cost of delaying the flights.
The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.
Example
Input
5 2
4 2 1 10 2
Output
20
3 6 7 4 5
Note
Let us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles.
However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.
Submitted Solution:
```
from heapq import heappush, heappop
n,k=[int(i) for i in input().split()]
l=[int(i) for i in input().split()]
if (n==1):
print (l[0])
else:
l1=[]
l2=[]
cost=0
if (k<n):
for i in range(k+1):
heappush(l1,(-l[i],i))
else:
for i in range(n):
heappush(l1,(-l[i],i))
for i in range(k,k+n):
a=heappop(l1)
cost+=((a[0]*(i-a[1]))*(-1))
l2.append((i+1,a[1]))
if (i<=n-2):
b=(-l[i+1],i+1)
heappush(l1,b)
l2.sort(key=lambda l2:l2[1])
print (cost,end="\n")
for i in range(n):
print (l2[i][0],end=" ")
```
No
| 14,707 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.
Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....
The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?
Input
First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).
Next n lines contain two numbers si and di (1 ≤ si, di ≤ 1000).
Output
Output a single integer — the minimum day at which Borya can visit the last doctor.
Examples
Input
3
2 2
1 2
2 2
Output
4
Input
2
10 1
6 5
Output
11
Note
In the first sample case, Borya can visit all doctors on days 2, 3 and 4.
In the second sample case, Borya can visit all doctors on days 10 and 11.
Tags: implementation
Correct Solution:
```
#!/bin/python
import collections
import random
import sys
n = int(input())
day = 0
for i in range(n):
s, d = map(int, input().split())
day = max(day + 1, s)
if (day - s) % d != 0:
day += d - (day - s) % d
print(day)
```
| 14,708 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.
Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....
The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?
Input
First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).
Next n lines contain two numbers si and di (1 ≤ si, di ≤ 1000).
Output
Output a single integer — the minimum day at which Borya can visit the last doctor.
Examples
Input
3
2 2
1 2
2 2
Output
4
Input
2
10 1
6 5
Output
11
Note
In the first sample case, Borya can visit all doctors on days 2, 3 and 4.
In the second sample case, Borya can visit all doctors on days 10 and 11.
Tags: implementation
Correct Solution:
```
r=0
for _ in[0]*int(input()):
s,d=map(int,input().split())
r=[(r-s+d)//d*d+s,s][r<s]
print(r)
```
| 14,709 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.
Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....
The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?
Input
First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).
Next n lines contain two numbers si and di (1 ≤ si, di ≤ 1000).
Output
Output a single integer — the minimum day at which Borya can visit the last doctor.
Examples
Input
3
2 2
1 2
2 2
Output
4
Input
2
10 1
6 5
Output
11
Note
In the first sample case, Borya can visit all doctors on days 2, 3 and 4.
In the second sample case, Borya can visit all doctors on days 10 and 11.
Tags: implementation
Correct Solution:
```
n = int(input())
s, d = map(int, input().split())
t = s + 1;
for i in range(n - 1):
s, d = map(int, input().split())
if s >= t:
t = s + 1;
elif (t - s) % d == 0:
t += 1;
else:
t += d - (t - s) % d + 1;
print(t - 1)
```
| 14,710 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.
Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....
The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?
Input
First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).
Next n lines contain two numbers si and di (1 ≤ si, di ≤ 1000).
Output
Output a single integer — the minimum day at which Borya can visit the last doctor.
Examples
Input
3
2 2
1 2
2 2
Output
4
Input
2
10 1
6 5
Output
11
Note
In the first sample case, Borya can visit all doctors on days 2, 3 and 4.
In the second sample case, Borya can visit all doctors on days 10 and 11.
Tags: implementation
Correct Solution:
```
n = int(input())
for i in range(n):
si, di = list(map(int, input().split()))
if i == 0:
sum = si
else:
if si <= sum:
if si + di <= sum:
nd = ((sum - (si + di)) // di) + 1
sum = (si + di) + nd * di
else:sum = si + di
else:sum=si
print(sum)
```
| 14,711 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.
Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....
The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?
Input
First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).
Next n lines contain two numbers si and di (1 ≤ si, di ≤ 1000).
Output
Output a single integer — the minimum day at which Borya can visit the last doctor.
Examples
Input
3
2 2
1 2
2 2
Output
4
Input
2
10 1
6 5
Output
11
Note
In the first sample case, Borya can visit all doctors on days 2, 3 and 4.
In the second sample case, Borya can visit all doctors on days 10 and 11.
Tags: implementation
Correct Solution:
```
def ii():
return int(input())
def mi():
return map(int, input().split())
def li():
return list(mi())
n = ii()
a = [mi() for i in range(n)]
p = 0
for i in range(n):
s, d = a[i]
if s>p:
p = s
else:
q = p - s
p = s + d*(q//d + 1)
print(p)
```
| 14,712 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.
Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....
The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?
Input
First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).
Next n lines contain two numbers si and di (1 ≤ si, di ≤ 1000).
Output
Output a single integer — the minimum day at which Borya can visit the last doctor.
Examples
Input
3
2 2
1 2
2 2
Output
4
Input
2
10 1
6 5
Output
11
Note
In the first sample case, Borya can visit all doctors on days 2, 3 and 4.
In the second sample case, Borya can visit all doctors on days 10 and 11.
Tags: implementation
Correct Solution:
```
#!/usr/bin/python
from math import ceil
n = int(input())
c = 1
for _ in range(n):
s, d = list(map(int, input().split()))
if s >= c:
c = s + 1
else:
i = ceil((c - s) / d)
c = s + i * d + 1
print(c - 1)
```
| 14,713 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.
Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....
The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?
Input
First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).
Next n lines contain two numbers si and di (1 ≤ si, di ≤ 1000).
Output
Output a single integer — the minimum day at which Borya can visit the last doctor.
Examples
Input
3
2 2
1 2
2 2
Output
4
Input
2
10 1
6 5
Output
11
Note
In the first sample case, Borya can visit all doctors on days 2, 3 and 4.
In the second sample case, Borya can visit all doctors on days 10 and 11.
Tags: implementation
Correct Solution:
```
count = 0
for _ in range(int(input())):
s,d = map(int,input().split())
if count == 0:
count += s
else:
if s>count:
count = s
else:
if (count-s)%d==0:
count += d
else:
count = s+((count-s)//d+1)*d
print(count)
```
| 14,714 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.
Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....
The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?
Input
First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).
Next n lines contain two numbers si and di (1 ≤ si, di ≤ 1000).
Output
Output a single integer — the minimum day at which Borya can visit the last doctor.
Examples
Input
3
2 2
1 2
2 2
Output
4
Input
2
10 1
6 5
Output
11
Note
In the first sample case, Borya can visit all doctors on days 2, 3 and 4.
In the second sample case, Borya can visit all doctors on days 10 and 11.
Tags: implementation
Correct Solution:
```
import math
n = int(input().strip())
day = 0
for _ in range(n):
day += 1
ai, di = map(int, input().strip().split())
if ai <= day:
t = math.ceil((day - ai)/di)
day = ai + t * di
else:
day = ai
print(day)
```
| 14,715 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.
Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....
The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?
Input
First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).
Next n lines contain two numbers si and di (1 ≤ si, di ≤ 1000).
Output
Output a single integer — the minimum day at which Borya can visit the last doctor.
Examples
Input
3
2 2
1 2
2 2
Output
4
Input
2
10 1
6 5
Output
11
Note
In the first sample case, Borya can visit all doctors on days 2, 3 and 4.
In the second sample case, Borya can visit all doctors on days 10 and 11.
Submitted Solution:
```
import math
n = int(input())
s = []
d = []
for i in range(n):
inp = input().split()
s.append(int(inp[0]))
d.append(int(inp[1]))
ans = s[0]
for i in range(1,len(s)):
if(s[i] < ans):
ans = (d[i] * math.floor(1+((ans - s[i])/d[i]))) + s[i]
else:
if(ans == s[i]):
ans = s[i] + d[i]
else:
ans = s[i]
print(ans)
```
Yes
| 14,716 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.
Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....
The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?
Input
First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).
Next n lines contain two numbers si and di (1 ≤ si, di ≤ 1000).
Output
Output a single integer — the minimum day at which Borya can visit the last doctor.
Examples
Input
3
2 2
1 2
2 2
Output
4
Input
2
10 1
6 5
Output
11
Note
In the first sample case, Borya can visit all doctors on days 2, 3 and 4.
In the second sample case, Borya can visit all doctors on days 10 and 11.
Submitted Solution:
```
n = int(input())
k = []
for _ in range(n):
l = list(map(int, input().split()))
k.append(l)
res = k[0][0]
for i in range(1,n):
if k[i][0]>res:
res = k[i][0]
else:
res= k[i][0] + ((((res - k[i][0])//k[i][1])+1)*k[i][1])
print(res)
```
Yes
| 14,717 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.
Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....
The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?
Input
First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).
Next n lines contain two numbers si and di (1 ≤ si, di ≤ 1000).
Output
Output a single integer — the minimum day at which Borya can visit the last doctor.
Examples
Input
3
2 2
1 2
2 2
Output
4
Input
2
10 1
6 5
Output
11
Note
In the first sample case, Borya can visit all doctors on days 2, 3 and 4.
In the second sample case, Borya can visit all doctors on days 10 and 11.
Submitted Solution:
```
ar=[]
i=0
for x in range(int(input())):
ar.append(list(map(int,input().split())))
for x in ar:
i=max(x[0],i+(x[0]-i-1)%x[1]+1)
#print(i)
print(i)
```
Yes
| 14,718 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.
Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....
The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?
Input
First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).
Next n lines contain two numbers si and di (1 ≤ si, di ≤ 1000).
Output
Output a single integer — the minimum day at which Borya can visit the last doctor.
Examples
Input
3
2 2
1 2
2 2
Output
4
Input
2
10 1
6 5
Output
11
Note
In the first sample case, Borya can visit all doctors on days 2, 3 and 4.
In the second sample case, Borya can visit all doctors on days 10 and 11.
Submitted Solution:
```
from math import ceil
d = int(input())
a = list()
for k in range(d):
s, l = input().split()
a.append((int(s), int(l)))
t = a[0][0]
for i in a[1:]:
s, l = i
if s > t:
t = s
else:
n = ceil((t - s + 1) / l)
t = s + l * n
print(t)
```
Yes
| 14,719 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.
Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....
The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?
Input
First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).
Next n lines contain two numbers si and di (1 ≤ si, di ≤ 1000).
Output
Output a single integer — the minimum day at which Borya can visit the last doctor.
Examples
Input
3
2 2
1 2
2 2
Output
4
Input
2
10 1
6 5
Output
11
Note
In the first sample case, Borya can visit all doctors on days 2, 3 and 4.
In the second sample case, Borya can visit all doctors on days 10 and 11.
Submitted Solution:
```
n = int(input())
cur = 0
for i in range(n):
start, x = [int(k) for k in input().split()]
for j in range(start,1000,x):
if j > cur:
cur = j
#print(cur)
break
print(cur)
```
No
| 14,720 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.
Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....
The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?
Input
First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).
Next n lines contain two numbers si and di (1 ≤ si, di ≤ 1000).
Output
Output a single integer — the minimum day at which Borya can visit the last doctor.
Examples
Input
3
2 2
1 2
2 2
Output
4
Input
2
10 1
6 5
Output
11
Note
In the first sample case, Borya can visit all doctors on days 2, 3 and 4.
In the second sample case, Borya can visit all doctors on days 10 and 11.
Submitted Solution:
```
n = int(input())
cur = 0
for i in range(n):
s, d = map(int, input().split())
if cur <= s:
cur = s
else:
t = 0
while cur >= s + t * d:
t += 1
cur = s + t * d
print(cur)
```
No
| 14,721 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.
Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....
The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?
Input
First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).
Next n lines contain two numbers si and di (1 ≤ si, di ≤ 1000).
Output
Output a single integer — the minimum day at which Borya can visit the last doctor.
Examples
Input
3
2 2
1 2
2 2
Output
4
Input
2
10 1
6 5
Output
11
Note
In the first sample case, Borya can visit all doctors on days 2, 3 and 4.
In the second sample case, Borya can visit all doctors on days 10 and 11.
Submitted Solution:
```
x = int(input())
day_num = 1
doctors = [[*map(int, input().split())] for _ in range(x)]
while 1:
if day_num<doctors[0][0]:
day_num = doctors[0][0]
elif day_num<doctors[0][0]+doctors[0][1]:
day_num += doctors[0][0]+doctors[0][1]-day_num
if (abs(day_num-doctors[0][0])%doctors[0][1] == 0):
doctors = doctors[1:]
day_num+=1
if not doctors:
break
print(day_num-1)
```
No
| 14,722 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.
Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....
The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?
Input
First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).
Next n lines contain two numbers si and di (1 ≤ si, di ≤ 1000).
Output
Output a single integer — the minimum day at which Borya can visit the last doctor.
Examples
Input
3
2 2
1 2
2 2
Output
4
Input
2
10 1
6 5
Output
11
Note
In the first sample case, Borya can visit all doctors on days 2, 3 and 4.
In the second sample case, Borya can visit all doctors on days 10 and 11.
Submitted Solution:
```
A = []
n = int(input())
for i in range(n):
s, d = map(int, input().split())
if not A:
A.append(s)
elif s <= A[-1]:
for j in range(s+d, 10000001, d):
if j not in A:
A.append(j)
break
else:
A.append(s)
print(A[-1])
```
No
| 14,723 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root.
Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.
Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.
The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.
Input
The first line contains a single integer h (2 ≤ h ≤ 105) — the height of the tree.
The second line contains h + 1 integers — the sequence a0, a1, ..., ah (1 ≤ ai ≤ 2·105). The sum of all ai does not exceed 2·105. It is guaranteed that there is at least one tree matching this sequence.
Output
If there is only one tree matching this sequence, print "perfect".
Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root.
These treese should be non-isomorphic and should match the given sequence.
Examples
Input
2
1 1 1
Output
perfect
Input
2
1 2 2
Output
ambiguous
0 1 1 3 3
0 1 1 3 2
Note
The only tree in the first example and the two printed trees from the second example are shown on the picture:
<image>
Tags: constructive algorithms, trees
Correct Solution:
```
def read():
return tuple(int(x) for x in input().split())
def main():
(h, ) = read()
a = read()
tree = []
fi = 0
flag = False
for i, x in enumerate(a):
if fi == 0:
if not flag and x > 1:
flag = True
elif flag and x > 1:
fi = len(tree)
else:
flag = False
tree.extend([len(tree)] * x)
if fi == 0:
print('perfect')
return
else:
print('ambiguous')
print(' '.join(str(x) for x in tree))
tree[fi] = fi - 1
print(' '.join(str(x) for x in tree))
main()
```
| 14,724 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root.
Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.
Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.
The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.
Input
The first line contains a single integer h (2 ≤ h ≤ 105) — the height of the tree.
The second line contains h + 1 integers — the sequence a0, a1, ..., ah (1 ≤ ai ≤ 2·105). The sum of all ai does not exceed 2·105. It is guaranteed that there is at least one tree matching this sequence.
Output
If there is only one tree matching this sequence, print "perfect".
Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root.
These treese should be non-isomorphic and should match the given sequence.
Examples
Input
2
1 1 1
Output
perfect
Input
2
1 2 2
Output
ambiguous
0 1 1 3 3
0 1 1 3 2
Note
The only tree in the first example and the two printed trees from the second example are shown on the picture:
<image>
Tags: constructive algorithms, trees
Correct Solution:
```
h=int(input())
l=list(map(int,input().split()))
x=False
pos=0
s=1
for i in range(h):
if (l[i]!=1) and (l[i+1]!=1) :
pos=i+1
x=True
print("ambiguous")
break
if not x:
print("perfect")
else:
ch="0"
ch1="0"
for i in range(1,len(l)):
ch+=(" "+str(s))*l[i]
if i!=pos:
ch1+=(" "+str(s))*l[i]
else:
ch1+=" "+str(s-1)+(" "+str(s))*(l[i]-1)
s+=l[i]
print(ch)
print(ch1)
```
| 14,725 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root.
Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.
Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.
The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.
Input
The first line contains a single integer h (2 ≤ h ≤ 105) — the height of the tree.
The second line contains h + 1 integers — the sequence a0, a1, ..., ah (1 ≤ ai ≤ 2·105). The sum of all ai does not exceed 2·105. It is guaranteed that there is at least one tree matching this sequence.
Output
If there is only one tree matching this sequence, print "perfect".
Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root.
These treese should be non-isomorphic and should match the given sequence.
Examples
Input
2
1 1 1
Output
perfect
Input
2
1 2 2
Output
ambiguous
0 1 1 3 3
0 1 1 3 2
Note
The only tree in the first example and the two printed trees from the second example are shown on the picture:
<image>
Tags: constructive algorithms, trees
Correct Solution:
```
n = int(input())
h = [int(i) for i in input().split()]
flag = 0
for i in range(n):
if h[i] >= 2 and h[i+1] >= 2:
flag = i
if flag:
a = []
c = 0
for i in range(n+1):
for j in range(h[i]):
a.append(c)
c += h[i]
b = []
c = 0
for i in range(n+1):
for j in range(h[i]):
if i == flag+1 and j == 0:
b.append(c-1)
else:
b.append(c)
c += h[i]
print("ambiguous")
print(" ".join([str(i) for i in a]))
print(" ".join([str(i) for i in b]))
else:
print("perfect")
```
| 14,726 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root.
Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.
Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.
The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.
Input
The first line contains a single integer h (2 ≤ h ≤ 105) — the height of the tree.
The second line contains h + 1 integers — the sequence a0, a1, ..., ah (1 ≤ ai ≤ 2·105). The sum of all ai does not exceed 2·105. It is guaranteed that there is at least one tree matching this sequence.
Output
If there is only one tree matching this sequence, print "perfect".
Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root.
These treese should be non-isomorphic and should match the given sequence.
Examples
Input
2
1 1 1
Output
perfect
Input
2
1 2 2
Output
ambiguous
0 1 1 3 3
0 1 1 3 2
Note
The only tree in the first example and the two printed trees from the second example are shown on the picture:
<image>
Tags: constructive algorithms, trees
Correct Solution:
```
h = int(input())
a = list(map(int,input().split()))
perfect = True
for i in range(h):
if a[i]>1 and a[i+1]>1:
perfect = False
break
if perfect:
print("perfect")
else:
print("ambiguous")
tree1 = list(range(h+1))
tree2 = list(tree1)
for i in range(1,h+1):
tree1.extend([i]*(a[i]-1))
for i in range(1,h+1):
p = i
if a[i]>1 and a[i-1]>1:
p = len(tree2)
tree2.extend([p]*(a[i]-1))
print(" ".join(map(str,tree1)))
print(" ".join(map(str,tree2)))
```
| 14,727 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root.
Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.
Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.
The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.
Input
The first line contains a single integer h (2 ≤ h ≤ 105) — the height of the tree.
The second line contains h + 1 integers — the sequence a0, a1, ..., ah (1 ≤ ai ≤ 2·105). The sum of all ai does not exceed 2·105. It is guaranteed that there is at least one tree matching this sequence.
Output
If there is only one tree matching this sequence, print "perfect".
Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root.
These treese should be non-isomorphic and should match the given sequence.
Examples
Input
2
1 1 1
Output
perfect
Input
2
1 2 2
Output
ambiguous
0 1 1 3 3
0 1 1 3 2
Note
The only tree in the first example and the two printed trees from the second example are shown on the picture:
<image>
Tags: constructive algorithms, trees
Correct Solution:
```
h = int(input())
a = list(map(int,input().split()))
p, c, f = 0, 0, False
s1, s2 = [], []
for i in a:
for j in range(i):
s1.append(c)
if j == i-1 and not f and p >= 2 and i >= 2:
f = True
s2.append(c-1)
else :
s2.append(c)
c += i
p = i
print('perfect' if not f else 'ambiguous')
if f:
print(*s1)
print(*s2)
```
| 14,728 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root.
Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.
Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.
The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.
Input
The first line contains a single integer h (2 ≤ h ≤ 105) — the height of the tree.
The second line contains h + 1 integers — the sequence a0, a1, ..., ah (1 ≤ ai ≤ 2·105). The sum of all ai does not exceed 2·105. It is guaranteed that there is at least one tree matching this sequence.
Output
If there is only one tree matching this sequence, print "perfect".
Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root.
These treese should be non-isomorphic and should match the given sequence.
Examples
Input
2
1 1 1
Output
perfect
Input
2
1 2 2
Output
ambiguous
0 1 1 3 3
0 1 1 3 2
Note
The only tree in the first example and the two printed trees from the second example are shown on the picture:
<image>
Tags: constructive algorithms, trees
Correct Solution:
```
import sys
#f = open('input', 'r')
f = sys.stdin
n = f.readline()
n = int(n)
cl = f.readline().split()
cl = [int(x) for x in cl]
c_index = 0
p1 = ['0']
p2 = ['0']
ambiguous = False
cur_index = 1
for i, c in enumerate(cl):
if i == 0:
continue
if i > 0 and cl[i-1] > 1 and c > 1:
ambiguous = True
p1 += [str(cur_index)] * c
p2 += [str(cur_index-1)] + [str(cur_index)] * (c-1)
else:
p1 += [str(cur_index)] * c
p2 += [str(cur_index)] * c
cur_index += c
if ambiguous:
print('ambiguous')
print(' '.join(p1))
print(' '.join(p2))
else:
print('perfect')
```
| 14,729 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root.
Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.
Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.
The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.
Input
The first line contains a single integer h (2 ≤ h ≤ 105) — the height of the tree.
The second line contains h + 1 integers — the sequence a0, a1, ..., ah (1 ≤ ai ≤ 2·105). The sum of all ai does not exceed 2·105. It is guaranteed that there is at least one tree matching this sequence.
Output
If there is only one tree matching this sequence, print "perfect".
Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root.
These treese should be non-isomorphic and should match the given sequence.
Examples
Input
2
1 1 1
Output
perfect
Input
2
1 2 2
Output
ambiguous
0 1 1 3 3
0 1 1 3 2
Note
The only tree in the first example and the two printed trees from the second example are shown on the picture:
<image>
Tags: constructive algorithms, trees
Correct Solution:
```
h = int(input())
a = list(map(int, input().split()))
perfect = True
for i in range(1, len(a)):
if (a[i] != 1 and a[i - 1] != 1):
perfect = False
print ("perfect" if perfect else "ambiguous")
ret1 = [0] * sum(a)
ret2 = [0] * sum(a)
#print (ret1)
node = 0;
p=0
if (perfect == False):
for i in range(len(a)):
for j in range(a[i]):
ret1[node] = p
node += 1;
p = node;
p1 = 0
p2 = 0
node = 0
for i in range(len(a)):
for j in range(a[i]):
if (j & 1):
ret2[node] = p1
else:
ret2[node] = p2
node += 1
p1 = node
p2 = node
if (a[i] != 1):
p1 = node;
p2 = node - 1;
print (' '.join(str(x) for x in ret1))
print (' '.join(str(x) for x in ret2))
```
| 14,730 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root.
Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.
Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.
The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.
Input
The first line contains a single integer h (2 ≤ h ≤ 105) — the height of the tree.
The second line contains h + 1 integers — the sequence a0, a1, ..., ah (1 ≤ ai ≤ 2·105). The sum of all ai does not exceed 2·105. It is guaranteed that there is at least one tree matching this sequence.
Output
If there is only one tree matching this sequence, print "perfect".
Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root.
These treese should be non-isomorphic and should match the given sequence.
Examples
Input
2
1 1 1
Output
perfect
Input
2
1 2 2
Output
ambiguous
0 1 1 3 3
0 1 1 3 2
Note
The only tree in the first example and the two printed trees from the second example are shown on the picture:
<image>
Tags: constructive algorithms, trees
Correct Solution:
```
"""
Author - Satwik Tiwari .
21th NOV , 2020 - Saturday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools import cmp_to_key
# from itertools import *
from heapq import *
from math import gcd, factorial,floor,ceil,sqrt
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
#==============================================================================================
#fast I/O region
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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
#===============================================================================================
#some shortcuts
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def testcase(t):
for pp in range(t):
solve(pp)
def google(p):
print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
y%=(p-1) #not so sure about this. used when y>p-1. if p is prime.
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) : # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))
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
inf = pow(10,20)
mod = 10**9+7
#===============================================================================================
# code here ;))
def solve(case):
n = int(inp())
a = lis()
cnt = False
for i in range(1,n+1):
if(a[i] > 1 and a[i-1] > 1):
cnt = True
if(not cnt):
print('perfect')
return
print('ambiguous')
ans = [0]
par = 1
for i in range(1,n+1):
# print(i,par)
for j in range(a[i]):
ans.append(par)
par+=a[i-1]
# print(ans)
ans2 = [0]
par = 1
for i in range(1,n+1):
# print(i,a[i-1],par)
for j in range(a[i]-1):
ans2.append(par)
if(a[i-1] > 1):
ans2.append(par+1)
else:
ans2.append(par)
par+=a[i-1]
# print(ans2)
print(' '.join(str(ans[i]) for i in range(len(ans))))
print(' '.join(str(ans2[i]) for i in range(len(ans2))))
testcase(1)
# testcase(int(inp()))
```
| 14,731 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root.
Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.
Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.
The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.
Input
The first line contains a single integer h (2 ≤ h ≤ 105) — the height of the tree.
The second line contains h + 1 integers — the sequence a0, a1, ..., ah (1 ≤ ai ≤ 2·105). The sum of all ai does not exceed 2·105. It is guaranteed that there is at least one tree matching this sequence.
Output
If there is only one tree matching this sequence, print "perfect".
Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root.
These treese should be non-isomorphic and should match the given sequence.
Examples
Input
2
1 1 1
Output
perfect
Input
2
1 2 2
Output
ambiguous
0 1 1 3 3
0 1 1 3 2
Note
The only tree in the first example and the two printed trees from the second example are shown on the picture:
<image>
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
pre = a[0]
index = -1
for i in range(1, n + 1):
if pre >= 2 and a[i] >= 2:
index = i
break
pre = a[i]
else:
print("perfect")
exit()
print("ambiguous")
N = sum(a)
R = [0]
for i in range(1, n + 1):
k = len(R)
for j in range(a[i]):
R.append(k)
L = [0]
flag = False
for i in range(1, n + 1):
k = len(L)
m = 0
if i == index:
L.append(k - a[i - 1] + 1)
m = 1
for j in range(a[i] - m):
L.append(k)
print(*R)
print(*L)
```
Yes
| 14,732 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root.
Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.
Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.
The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.
Input
The first line contains a single integer h (2 ≤ h ≤ 105) — the height of the tree.
The second line contains h + 1 integers — the sequence a0, a1, ..., ah (1 ≤ ai ≤ 2·105). The sum of all ai does not exceed 2·105. It is guaranteed that there is at least one tree matching this sequence.
Output
If there is only one tree matching this sequence, print "perfect".
Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root.
These treese should be non-isomorphic and should match the given sequence.
Examples
Input
2
1 1 1
Output
perfect
Input
2
1 2 2
Output
ambiguous
0 1 1 3 3
0 1 1 3 2
Note
The only tree in the first example and the two printed trees from the second example are shown on the picture:
<image>
Submitted Solution:
```
h = int(input())
a = list(map(int,input().split()))
ok = True
for i in range(h):
if a[i]>=2 and a[i+1]>=2:
ok = False
idx = i+1
if ok:
print('perfect')
else:
print('ambiguous')
ans = []
p = 0
for x in a:
ans.extend([p]*x)
p = len(ans)
print(' '.join(map(str,ans)))
ans[sum(a[:idx])] -= 1
print(' '.join(map(str,ans)))
```
Yes
| 14,733 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root.
Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.
Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.
The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.
Input
The first line contains a single integer h (2 ≤ h ≤ 105) — the height of the tree.
The second line contains h + 1 integers — the sequence a0, a1, ..., ah (1 ≤ ai ≤ 2·105). The sum of all ai does not exceed 2·105. It is guaranteed that there is at least one tree matching this sequence.
Output
If there is only one tree matching this sequence, print "perfect".
Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root.
These treese should be non-isomorphic and should match the given sequence.
Examples
Input
2
1 1 1
Output
perfect
Input
2
1 2 2
Output
ambiguous
0 1 1 3 3
0 1 1 3 2
Note
The only tree in the first example and the two printed trees from the second example are shown on the picture:
<image>
Submitted Solution:
```
import sys
lines = []
for line in sys.stdin:
lines.append(line.rstrip("\r\n\t "))
h = int(lines[0])
ids = lines[1].split(" ")
leafs1 = "0"
leafs2 = "0"
parents = []
last_id = 1
is_perfect = True
leafs = int(ids[1])
last_leafs = leafs
for j in range(0, leafs):
last_id += 1
leafs1 += " 1"
leafs2 += " 1"
parents.append(last_id)
for i in range(3, h + 2):
leafs = int(ids[i - 1])
s0 = " " + str(parents[0])
if last_leafs > 1 and leafs > 1:
is_perfect = False
last_id += 1
s1 = " " + str(parents[1])
parents = []
leafs1 += s0
leafs2 += s1
parents.append(last_id)
for j in range(1, leafs):
last_id += 1
leafs1 += s0
leafs2 += s0
parents.append(last_id)
else:
parents = []
for j in range(0, leafs):
last_id += 1
leafs1 += s0
leafs2 += s0
parents.append(last_id)
last_leafs = leafs
if is_perfect:
print("perfect")
else:
print("ambiguous")
print(leafs1)
print(leafs2)
```
Yes
| 14,734 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root.
Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.
Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.
The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.
Input
The first line contains a single integer h (2 ≤ h ≤ 105) — the height of the tree.
The second line contains h + 1 integers — the sequence a0, a1, ..., ah (1 ≤ ai ≤ 2·105). The sum of all ai does not exceed 2·105. It is guaranteed that there is at least one tree matching this sequence.
Output
If there is only one tree matching this sequence, print "perfect".
Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root.
These treese should be non-isomorphic and should match the given sequence.
Examples
Input
2
1 1 1
Output
perfect
Input
2
1 2 2
Output
ambiguous
0 1 1 3 3
0 1 1 3 2
Note
The only tree in the first example and the two printed trees from the second example are shown on the picture:
<image>
Submitted Solution:
```
import sys
from collections import Counter, deque
def lInt(d = None): return map(int, input().split(d))
n, *_ = lInt()
a = list(lInt())
a.append(0)
j = 0
tot = sum(a)
try:
for i, va in enumerate(a):
if va > 1 and a[i-1] > 1:
print("ambiguous")
j = i
raise
except:
p = 0
ans = []
for i in range(0, n+1):
va = a[i]
for u in range(va):
ans.append(p)
p += va
for u in ans:
sys.stdout.write(str(u)+" ")
print("")
p = 0
ans = []
for i in range(0, n+1):
va = a[i]
if i == j:
for u in range(va//2):
ans.append(p-1)
for u in range(va//2, va):
ans.append(p)
else:
for u in range(va):
ans.append(p)
p += va
for u in ans:
sys.stdout.write(str(u)+" ")
print("")
else:
print("perfect")
```
Yes
| 14,735 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root.
Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.
Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.
The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.
Input
The first line contains a single integer h (2 ≤ h ≤ 105) — the height of the tree.
The second line contains h + 1 integers — the sequence a0, a1, ..., ah (1 ≤ ai ≤ 2·105). The sum of all ai does not exceed 2·105. It is guaranteed that there is at least one tree matching this sequence.
Output
If there is only one tree matching this sequence, print "perfect".
Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root.
These treese should be non-isomorphic and should match the given sequence.
Examples
Input
2
1 1 1
Output
perfect
Input
2
1 2 2
Output
ambiguous
0 1 1 3 3
0 1 1 3 2
Note
The only tree in the first example and the two printed trees from the second example are shown on the picture:
<image>
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
ans = 0
f = 0
if a[0] >= 2:
f += 1
for i in range(1, n + 1):
if a[i] >= 2:
f += 1
if a[i] >= 2 and a[i - 1] >= 2:
ans = 1
if ans == 0:
print("perfect")
else:
s1 = "0"
s2 = "0"
p = 0
ans = 1
for i in range(1, len(a)):
if a[i - 1] == 1:
s1 += (" " + str(ans)) * a[i]
s2 += (" " + str(ans)) * a[i]
else:
f -= 1
if p == 0 and f == 1:
s1 += (" " + str(ans)) * a[i]
s2 += (" " + str(ans - 1)) * 1 + (" " + str(ans)) * (a[i] - 1)
p = 1
else:
s1 += (" " + str(ans)) * a[i]
s2 += (" " + str(ans)) * a[i]
ans += a[i]
print("ambiguous")
print(s1)
print(s2)
```
No
| 14,736 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root.
Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.
Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.
The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.
Input
The first line contains a single integer h (2 ≤ h ≤ 105) — the height of the tree.
The second line contains h + 1 integers — the sequence a0, a1, ..., ah (1 ≤ ai ≤ 2·105). The sum of all ai does not exceed 2·105. It is guaranteed that there is at least one tree matching this sequence.
Output
If there is only one tree matching this sequence, print "perfect".
Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root.
These treese should be non-isomorphic and should match the given sequence.
Examples
Input
2
1 1 1
Output
perfect
Input
2
1 2 2
Output
ambiguous
0 1 1 3 3
0 1 1 3 2
Note
The only tree in the first example and the two printed trees from the second example are shown on the picture:
<image>
Submitted Solution:
```
n=int(input())
m=[]
p=list(map(int,input().split()))
if p.count(1)<len(p)-1:
print('ambiguous')
x=1
z=0
s=['0']
for i in range(1,n+1):
a=x
for j in range(p[i]):
s.append(str(a))
x+=1
if p[i]>1 and not z:
z=len(s)+1
zx=x-1
print(' '.join(s))
s[z]=str(zx)
print(' '.join(s))
else:
print('perfect')
```
No
| 14,737 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root.
Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.
Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.
The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.
Input
The first line contains a single integer h (2 ≤ h ≤ 105) — the height of the tree.
The second line contains h + 1 integers — the sequence a0, a1, ..., ah (1 ≤ ai ≤ 2·105). The sum of all ai does not exceed 2·105. It is guaranteed that there is at least one tree matching this sequence.
Output
If there is only one tree matching this sequence, print "perfect".
Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root.
These treese should be non-isomorphic and should match the given sequence.
Examples
Input
2
1 1 1
Output
perfect
Input
2
1 2 2
Output
ambiguous
0 1 1 3 3
0 1 1 3 2
Note
The only tree in the first example and the two printed trees from the second example are shown on the picture:
<image>
Submitted Solution:
```
n=int(input())
l=list(map(int,input().split()))
f=0
for i in range(n):
#print(l[i],l[i+1])
if l[i]>1 and l[i+1]>1:
f+=1
break
if f==0:
print("perfect")
else:
g=''
cnt=0
for i in l:
for j in range(i):
g+=str(cnt)
cnt+=1
print("ambiguous")
h=''
for i in range(len(g)-1):
h+=g[i]
h+=str(len(l))
l,l1=list(g),list(h)
print(*l)
print(*l1)
```
No
| 14,738 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root.
Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.
Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.
The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.
Input
The first line contains a single integer h (2 ≤ h ≤ 105) — the height of the tree.
The second line contains h + 1 integers — the sequence a0, a1, ..., ah (1 ≤ ai ≤ 2·105). The sum of all ai does not exceed 2·105. It is guaranteed that there is at least one tree matching this sequence.
Output
If there is only one tree matching this sequence, print "perfect".
Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root.
These treese should be non-isomorphic and should match the given sequence.
Examples
Input
2
1 1 1
Output
perfect
Input
2
1 2 2
Output
ambiguous
0 1 1 3 3
0 1 1 3 2
Note
The only tree in the first example and the two printed trees from the second example are shown on the picture:
<image>
Submitted Solution:
```
n=int(input())
l=list(map(int,input().split()))
f=0
for i in range(n):
#print(l[i],l[i+1])
if l[i]>1 and l[i+1]>1:
ind=i
f+=1
break
if f==0:
print("perfect")
else:
g=''
cnt=0
for i in range(len(l)):
if i==ind+1:
if l[i]==2:
for j in range(2):
g+=str(cnt)
cnt+=1
else:
for j in range(l[i]-1):
g+=str(cnt)
cnt+=1
g+=str(cnt)
cnt+=1
else:
for j in range(l[i]):
g+=str(cnt)
cnt+=1
print("ambiguous")
h=''
h=''
cnt1=0
for i in range(len(l)):
if i==ind+1:
#print(i)
if l[i]==2:
for j in range(1):
h+=str(cnt1)
cnt1+=1
h+=str(cnt1)
cnt1+=1
else:
if l[i]%2!=0:
for j in range(l[i]//2):
h+=str(cnt1)
cnt1+=1
for j in range((l[i]//2)+1):
h+=str(cnt1)
cnt1+=1
else:
for j in range(l[i]//2):
h+=str(cnt1)
cnt1+=1
for j in range(l[i]//2):
h+=str(cnt1)
cnt1+=1
#h+=str(cnt1)
else:
for j in range(l[i]):
h+=str(cnt1)
cnt1+=1
l,l1=list(g),list(h)
print(*l)
print(*l1)
```
No
| 14,739 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem you will write a simple code generator for a 2D programming language derived from [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck).
The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usual order (top to bottom, left to right), and each 'X' character is converted a Brainfuck instruction to be executed. The instruction is defined by the left, top and right neighbors of the 'X' character using the following conversion table:
<image>
You are given a string. Output a program in the described language which prints this string.
You can download the language interpreter used for judging here: <https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp> (use C++11 to compile the code). Note several implementation details:
* The first step of the language interpretation is conversion to a Brainfuck program, which is then executed.
* The code must be rectangular, with all lines of the same length. It can have at most 10,000 lines and 10,000 columns, and can have at most 500,000 'X' characters.
* The code has toroidal topology, i.e. the 'X' on the first line will have top neighbor in the last line.
* Brainfuck interpreter has 30000 memory cells which store integers from 0 to 255 with increment/decrement done modulo 256.
* Console input (, command) is allowed in Brainfuck code but has no effect when executed.
Input
The input consists of a single string of characters with ASCII codes between 33 ('!') and 122 ('z'), inclusive. The length of the string is between 1 and 10 characters, inclusive.
Output
Output a program in the described language which, when executed, will print the given message.
Example
Input
$$$
Output
.......X.......
......XXX......
.....XXXXX.....
....XXXXXXX....
...XXXXXXXXX...
..XXXXXXXXXXX..
.XXXXXXXXXXXXX.
...............
X.............X
X..............
X..............
X..............
Note
The example corresponds to the following Brainfuck program:
-
>+<
>+++<
>+++++<
>+++++++<
>+++++++++<
>+++++++++++<
< >
.
.
.
The triangular block decrements the first memory cell and sets the value of the second memory cell to 36 - the ASCII code of '$' character. The next line after the triangular block moves the memory pointer to the second memory cell, and the next three lines print the '$' character three times.
Tags: constructive algorithms
Correct Solution:
```
# A +
# print(int(input()) % 2)
# B
# good = ['cool', 'great', 'not bad', '!']
# for i in range(10):
# print(i, flush=True)
# r = input().strip().lower()
# for g in good:
# if g in r:
# print('normal', flush=True)
# exit(0)
# print('grumpy', flush=True)
# C +
# input()
# a = [int(x) for x in input().split()]
# while a:
# for i in range(len(a)-1):
# if abs(a[i] - a[i+1]) >= 2:
# print('NO')
# exit(0)
# a.pop(a.index(max(a)))
# print('YES')
# D
# print(20)
# E +
# n = int(input())
# a, b = 0, 0
# for _ in range(n):
# _, s = input().split()
# if s == 'soft':
# a += 1
# else:
# b += 1
# if a < b:
# a, b = b, a
# x = 0
# for i in range(1, 200):
# x += 1 + (i*2 - 1) // 4 * 2
# if a <= x and b <= i**2 - x:
# print(i)
# break
# G
s = [ord(x) for x in input().strip()]
pv = 0
at = 0
wid = 600
for x in s:
dt = (x - pv) % 256
dt = -dt % 256
if dt == 0:
dt = 256
print('X.'*dt + '.'*(wid - dt*2))
print('X' + '.'*(wid - 1))
print('.'*wid)
pv = x
```
| 14,740 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem you will write a simple code generator for a 2D programming language derived from [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck).
The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usual order (top to bottom, left to right), and each 'X' character is converted a Brainfuck instruction to be executed. The instruction is defined by the left, top and right neighbors of the 'X' character using the following conversion table:
<image>
You are given a string. Output a program in the described language which prints this string.
You can download the language interpreter used for judging here: <https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp> (use C++11 to compile the code). Note several implementation details:
* The first step of the language interpretation is conversion to a Brainfuck program, which is then executed.
* The code must be rectangular, with all lines of the same length. It can have at most 10,000 lines and 10,000 columns, and can have at most 500,000 'X' characters.
* The code has toroidal topology, i.e. the 'X' on the first line will have top neighbor in the last line.
* Brainfuck interpreter has 30000 memory cells which store integers from 0 to 255 with increment/decrement done modulo 256.
* Console input (, command) is allowed in Brainfuck code but has no effect when executed.
Input
The input consists of a single string of characters with ASCII codes between 33 ('!') and 122 ('z'), inclusive. The length of the string is between 1 and 10 characters, inclusive.
Output
Output a program in the described language which, when executed, will print the given message.
Example
Input
$$$
Output
.......X.......
......XXX......
.....XXXXX.....
....XXXXXXX....
...XXXXXXXXX...
..XXXXXXXXXXX..
.XXXXXXXXXXXXX.
...............
X.............X
X..............
X..............
X..............
Note
The example corresponds to the following Brainfuck program:
-
>+<
>+++<
>+++++<
>+++++++<
>+++++++++<
>+++++++++++<
< >
.
.
.
The triangular block decrements the first memory cell and sets the value of the second memory cell to 36 - the ASCII code of '$' character. The next line after the triangular block moves the memory pointer to the second memory cell, and the next three lines print the '$' character three times.
Tags: constructive algorithms
Correct Solution:
```
import sys
s = input()
#f = open('out.txt', 'w')
f = sys.stdout
n = 0
d = '\x00'
for c in s:
n = ord(c) - ord(d)
#print(n, file=sys.stderr)
if (n < 0):
for i in range(-n):
if i % 2 == 0:
print('X....', file=f)
else:
print('.X...', file=f)
elif n > 0:
for i in range(n):
print('..X..', file=f)
print('.XXX.', file=f)
print('XXXXX', file=f)
print('.....', file=f)
print('X....', file=f)
print('.....', file=f)
print('X...X', file=f)
print('X....', file=f)
print('.....', file=f)
d = c
f.close()
```
| 14,741 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem you will write a simple code generator for a 2D programming language derived from [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck).
The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usual order (top to bottom, left to right), and each 'X' character is converted a Brainfuck instruction to be executed. The instruction is defined by the left, top and right neighbors of the 'X' character using the following conversion table:
<image>
You are given a string. Output a program in the described language which prints this string.
You can download the language interpreter used for judging here: <https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp> (use C++11 to compile the code). Note several implementation details:
* The first step of the language interpretation is conversion to a Brainfuck program, which is then executed.
* The code must be rectangular, with all lines of the same length. It can have at most 10,000 lines and 10,000 columns, and can have at most 500,000 'X' characters.
* The code has toroidal topology, i.e. the 'X' on the first line will have top neighbor in the last line.
* Brainfuck interpreter has 30000 memory cells which store integers from 0 to 255 with increment/decrement done modulo 256.
* Console input (, command) is allowed in Brainfuck code but has no effect when executed.
Input
The input consists of a single string of characters with ASCII codes between 33 ('!') and 122 ('z'), inclusive. The length of the string is between 1 and 10 characters, inclusive.
Output
Output a program in the described language which, when executed, will print the given message.
Example
Input
$$$
Output
.......X.......
......XXX......
.....XXXXX.....
....XXXXXXX....
...XXXXXXXXX...
..XXXXXXXXXXX..
.XXXXXXXXXXXXX.
...............
X.............X
X..............
X..............
X..............
Note
The example corresponds to the following Brainfuck program:
-
>+<
>+++<
>+++++<
>+++++++<
>+++++++++<
>+++++++++++<
< >
.
.
.
The triangular block decrements the first memory cell and sets the value of the second memory cell to 36 - the ASCII code of '$' character. The next line after the triangular block moves the memory pointer to the second memory cell, and the next three lines print the '$' character three times.
Tags: constructive algorithms
Correct Solution:
```
s = [ord(x) for x in input()]
val = 0
add2 = '...\n.XX\nXXX'
sub1 = '...\n.X.'
for ch in s:
delta = ch - val + 1
if delta > 0:
if delta % 3 == 1:
print(add2)
print(sub1)
delta -= 1
elif delta % 3 == 2:
print(add2)
delta -= 2
if delta >= 3:
tmp = '...' + '\nXXX' * (delta // 3 + 1)
print(tmp)
elif delta < 0:
tmp = '...' + ('\n' + sub1) * -delta
print(tmp)
print('...')
print('.X.')
print('.X.')
print('...')
val = ch
```
| 14,742 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem you will write a simple code generator for a 2D programming language derived from [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck).
The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usual order (top to bottom, left to right), and each 'X' character is converted a Brainfuck instruction to be executed. The instruction is defined by the left, top and right neighbors of the 'X' character using the following conversion table:
<image>
You are given a string. Output a program in the described language which prints this string.
You can download the language interpreter used for judging here: <https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp> (use C++11 to compile the code). Note several implementation details:
* The first step of the language interpretation is conversion to a Brainfuck program, which is then executed.
* The code must be rectangular, with all lines of the same length. It can have at most 10,000 lines and 10,000 columns, and can have at most 500,000 'X' characters.
* The code has toroidal topology, i.e. the 'X' on the first line will have top neighbor in the last line.
* Brainfuck interpreter has 30000 memory cells which store integers from 0 to 255 with increment/decrement done modulo 256.
* Console input (, command) is allowed in Brainfuck code but has no effect when executed.
Input
The input consists of a single string of characters with ASCII codes between 33 ('!') and 122 ('z'), inclusive. The length of the string is between 1 and 10 characters, inclusive.
Output
Output a program in the described language which, when executed, will print the given message.
Example
Input
$$$
Output
.......X.......
......XXX......
.....XXXXX.....
....XXXXXXX....
...XXXXXXXXX...
..XXXXXXXXXXX..
.XXXXXXXXXXXXX.
...............
X.............X
X..............
X..............
X..............
Note
The example corresponds to the following Brainfuck program:
-
>+<
>+++<
>+++++<
>+++++++<
>+++++++++<
>+++++++++++<
< >
.
.
.
The triangular block decrements the first memory cell and sets the value of the second memory cell to 36 - the ASCII code of '$' character. The next line after the triangular block moves the memory pointer to the second memory cell, and the next three lines print the '$' character three times.
Tags: constructive algorithms
Correct Solution:
```
print(*['\n'.join([*['...\n.X.' for i in range(256 - x)], '.X.', *['...\n.X.' for i in range(x)]]) for x in map(ord, input())], sep='\n')
```
| 14,743 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem you will write a simple code generator for a 2D programming language derived from [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck).
The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usual order (top to bottom, left to right), and each 'X' character is converted a Brainfuck instruction to be executed. The instruction is defined by the left, top and right neighbors of the 'X' character using the following conversion table:
<image>
You are given a string. Output a program in the described language which prints this string.
You can download the language interpreter used for judging here: <https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp> (use C++11 to compile the code). Note several implementation details:
* The first step of the language interpretation is conversion to a Brainfuck program, which is then executed.
* The code must be rectangular, with all lines of the same length. It can have at most 10,000 lines and 10,000 columns, and can have at most 500,000 'X' characters.
* The code has toroidal topology, i.e. the 'X' on the first line will have top neighbor in the last line.
* Brainfuck interpreter has 30000 memory cells which store integers from 0 to 255 with increment/decrement done modulo 256.
* Console input (, command) is allowed in Brainfuck code but has no effect when executed.
Input
The input consists of a single string of characters with ASCII codes between 33 ('!') and 122 ('z'), inclusive. The length of the string is between 1 and 10 characters, inclusive.
Output
Output a program in the described language which, when executed, will print the given message.
Example
Input
$$$
Output
.......X.......
......XXX......
.....XXXXX.....
....XXXXXXX....
...XXXXXXXXX...
..XXXXXXXXXXX..
.XXXXXXXXXXXXX.
...............
X.............X
X..............
X..............
X..............
Note
The example corresponds to the following Brainfuck program:
-
>+<
>+++<
>+++++<
>+++++++<
>+++++++++<
>+++++++++++<
< >
.
.
.
The triangular block decrements the first memory cell and sets the value of the second memory cell to 36 - the ASCII code of '$' character. The next line after the triangular block moves the memory pointer to the second memory cell, and the next three lines print the '$' character three times.
Tags: constructive algorithms
Correct Solution:
```
# python3
import math
WIDTH = 170
def add(n):
if n == 1:
add(2)
add(255)
else:
while n:
k = min(n, WIDTH - 1)
n -= k
print('.' * WIDTH)
print('X' * (k - 1) + '.' * (WIDTH - k) + 'X')
print('X' * WIDTH)
def print_mem2():
print('.' * WIDTH)
print('X' + '.' * (WIDTH - 2) + 'X')
print('X' + '.' * (WIDTH - 1))
# main
mem2 = 0
for symbol in map(ord, input()):
add((symbol - mem2) % 256)
print_mem2()
mem2 = symbol
```
| 14,744 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem you will write a simple code generator for a 2D programming language derived from [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck).
The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usual order (top to bottom, left to right), and each 'X' character is converted a Brainfuck instruction to be executed. The instruction is defined by the left, top and right neighbors of the 'X' character using the following conversion table:
<image>
You are given a string. Output a program in the described language which prints this string.
You can download the language interpreter used for judging here: <https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp> (use C++11 to compile the code). Note several implementation details:
* The first step of the language interpretation is conversion to a Brainfuck program, which is then executed.
* The code must be rectangular, with all lines of the same length. It can have at most 10,000 lines and 10,000 columns, and can have at most 500,000 'X' characters.
* The code has toroidal topology, i.e. the 'X' on the first line will have top neighbor in the last line.
* Brainfuck interpreter has 30000 memory cells which store integers from 0 to 255 with increment/decrement done modulo 256.
* Console input (, command) is allowed in Brainfuck code but has no effect when executed.
Input
The input consists of a single string of characters with ASCII codes between 33 ('!') and 122 ('z'), inclusive. The length of the string is between 1 and 10 characters, inclusive.
Output
Output a program in the described language which, when executed, will print the given message.
Example
Input
$$$
Output
.......X.......
......XXX......
.....XXXXX.....
....XXXXXXX....
...XXXXXXXXX...
..XXXXXXXXXXX..
.XXXXXXXXXXXXX.
...............
X.............X
X..............
X..............
X..............
Note
The example corresponds to the following Brainfuck program:
-
>+<
>+++<
>+++++<
>+++++++<
>+++++++++<
>+++++++++++<
< >
.
.
.
The triangular block decrements the first memory cell and sets the value of the second memory cell to 36 - the ASCII code of '$' character. The next line after the triangular block moves the memory pointer to the second memory cell, and the next three lines print the '$' character three times.
Tags: constructive algorithms
Correct Solution:
```
s = input()
for c in s:
for i in range(256 - ord(c)):
print("...\n.X.")
print(".X.")
for i in range(ord(c)):
print("...\n.X.")
```
| 14,745 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem you will write a simple code generator for a 2D programming language derived from [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck).
The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usual order (top to bottom, left to right), and each 'X' character is converted a Brainfuck instruction to be executed. The instruction is defined by the left, top and right neighbors of the 'X' character using the following conversion table:
<image>
You are given a string. Output a program in the described language which prints this string.
You can download the language interpreter used for judging here: <https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp> (use C++11 to compile the code). Note several implementation details:
* The first step of the language interpretation is conversion to a Brainfuck program, which is then executed.
* The code must be rectangular, with all lines of the same length. It can have at most 10,000 lines and 10,000 columns, and can have at most 500,000 'X' characters.
* The code has toroidal topology, i.e. the 'X' on the first line will have top neighbor in the last line.
* Brainfuck interpreter has 30000 memory cells which store integers from 0 to 255 with increment/decrement done modulo 256.
* Console input (, command) is allowed in Brainfuck code but has no effect when executed.
Input
The input consists of a single string of characters with ASCII codes between 33 ('!') and 122 ('z'), inclusive. The length of the string is between 1 and 10 characters, inclusive.
Output
Output a program in the described language which, when executed, will print the given message.
Example
Input
$$$
Output
.......X.......
......XXX......
.....XXXXX.....
....XXXXXXX....
...XXXXXXXXX...
..XXXXXXXXXXX..
.XXXXXXXXXXXXX.
...............
X.............X
X..............
X..............
X..............
Note
The example corresponds to the following Brainfuck program:
-
>+<
>+++<
>+++++<
>+++++++<
>+++++++++<
>+++++++++++<
< >
.
.
.
The triangular block decrements the first memory cell and sets the value of the second memory cell to 36 - the ASCII code of '$' character. The next line after the triangular block moves the memory pointer to the second memory cell, and the next three lines print the '$' character three times.
Tags: constructive algorithms
Correct Solution:
```
n = input()
s = ""
t = ""
for c in n:
i = ord(c)
s += ".X." + ".X.." * i + ".X.X." + ".." * i + "X.."
t += "..." + "XXX." * i + "XX.X." + "X." * i + "XX."
print(s)
print(t)
print(len(s) * ".")
```
| 14,746 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem you will write a simple code generator for a 2D programming language derived from [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck).
The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usual order (top to bottom, left to right), and each 'X' character is converted a Brainfuck instruction to be executed. The instruction is defined by the left, top and right neighbors of the 'X' character using the following conversion table:
<image>
You are given a string. Output a program in the described language which prints this string.
You can download the language interpreter used for judging here: <https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp> (use C++11 to compile the code). Note several implementation details:
* The first step of the language interpretation is conversion to a Brainfuck program, which is then executed.
* The code must be rectangular, with all lines of the same length. It can have at most 10,000 lines and 10,000 columns, and can have at most 500,000 'X' characters.
* The code has toroidal topology, i.e. the 'X' on the first line will have top neighbor in the last line.
* Brainfuck interpreter has 30000 memory cells which store integers from 0 to 255 with increment/decrement done modulo 256.
* Console input (, command) is allowed in Brainfuck code but has no effect when executed.
Input
The input consists of a single string of characters with ASCII codes between 33 ('!') and 122 ('z'), inclusive. The length of the string is between 1 and 10 characters, inclusive.
Output
Output a program in the described language which, when executed, will print the given message.
Example
Input
$$$
Output
.......X.......
......XXX......
.....XXXXX.....
....XXXXXXX....
...XXXXXXXXX...
..XXXXXXXXXXX..
.XXXXXXXXXXXXX.
...............
X.............X
X..............
X..............
X..............
Note
The example corresponds to the following Brainfuck program:
-
>+<
>+++<
>+++++<
>+++++++<
>+++++++++<
>+++++++++++<
< >
.
.
.
The triangular block decrements the first memory cell and sets the value of the second memory cell to 36 - the ASCII code of '$' character. The next line after the triangular block moves the memory pointer to the second memory cell, and the next three lines print the '$' character three times.
Tags: constructive algorithms
Correct Solution:
```
data = input()
lens = [(256 - ord(data[0]))]
for i in range(len(data) - 1):
lens.append((512 - (ord(data[i+1]) - ord(data[i]))) % 256)
line0 = "." * 512
line1 = ".X" + ("." * 510)
for i in range(len(data)):
if lens[i] == 0:
print(line1)
else:
print(line0)
print(".X" * lens[i] + ".." * (256 - lens[i]))
print(line1)
```
| 14,747 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem you will write a simple code generator for a 2D programming language derived from [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck).
The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usual order (top to bottom, left to right), and each 'X' character is converted a Brainfuck instruction to be executed. The instruction is defined by the left, top and right neighbors of the 'X' character using the following conversion table:
<image>
You are given a string. Output a program in the described language which prints this string.
You can download the language interpreter used for judging here: <https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp> (use C++11 to compile the code). Note several implementation details:
* The first step of the language interpretation is conversion to a Brainfuck program, which is then executed.
* The code must be rectangular, with all lines of the same length. It can have at most 10,000 lines and 10,000 columns, and can have at most 500,000 'X' characters.
* The code has toroidal topology, i.e. the 'X' on the first line will have top neighbor in the last line.
* Brainfuck interpreter has 30000 memory cells which store integers from 0 to 255 with increment/decrement done modulo 256.
* Console input (, command) is allowed in Brainfuck code but has no effect when executed.
Input
The input consists of a single string of characters with ASCII codes between 33 ('!') and 122 ('z'), inclusive. The length of the string is between 1 and 10 characters, inclusive.
Output
Output a program in the described language which, when executed, will print the given message.
Example
Input
$$$
Output
.......X.......
......XXX......
.....XXXXX.....
....XXXXXXX....
...XXXXXXXXX...
..XXXXXXXXXXX..
.XXXXXXXXXXXXX.
...............
X.............X
X..............
X..............
X..............
Note
The example corresponds to the following Brainfuck program:
-
>+<
>+++<
>+++++<
>+++++++<
>+++++++++<
>+++++++++++<
< >
.
.
.
The triangular block decrements the first memory cell and sets the value of the second memory cell to 36 - the ASCII code of '$' character. The next line after the triangular block moves the memory pointer to the second memory cell, and the next three lines print the '$' character three times.
Submitted Solution:
```
print(''.join('..\n.X\n' * (256 - x) + '.X\n' + '..\n.X\n' * x for x in map(ord, input())))
```
Yes
| 14,748 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem you will write a simple code generator for a 2D programming language derived from [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck).
The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usual order (top to bottom, left to right), and each 'X' character is converted a Brainfuck instruction to be executed. The instruction is defined by the left, top and right neighbors of the 'X' character using the following conversion table:
<image>
You are given a string. Output a program in the described language which prints this string.
You can download the language interpreter used for judging here: <https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp> (use C++11 to compile the code). Note several implementation details:
* The first step of the language interpretation is conversion to a Brainfuck program, which is then executed.
* The code must be rectangular, with all lines of the same length. It can have at most 10,000 lines and 10,000 columns, and can have at most 500,000 'X' characters.
* The code has toroidal topology, i.e. the 'X' on the first line will have top neighbor in the last line.
* Brainfuck interpreter has 30000 memory cells which store integers from 0 to 255 with increment/decrement done modulo 256.
* Console input (, command) is allowed in Brainfuck code but has no effect when executed.
Input
The input consists of a single string of characters with ASCII codes between 33 ('!') and 122 ('z'), inclusive. The length of the string is between 1 and 10 characters, inclusive.
Output
Output a program in the described language which, when executed, will print the given message.
Example
Input
$$$
Output
.......X.......
......XXX......
.....XXXXX.....
....XXXXXXX....
...XXXXXXXXX...
..XXXXXXXXXXX..
.XXXXXXXXXXXXX.
...............
X.............X
X..............
X..............
X..............
Note
The example corresponds to the following Brainfuck program:
-
>+<
>+++<
>+++++<
>+++++++<
>+++++++++<
>+++++++++++<
< >
.
.
.
The triangular block decrements the first memory cell and sets the value of the second memory cell to 36 - the ASCII code of '$' character. The next line after the triangular block moves the memory pointer to the second memory cell, and the next three lines print the '$' character three times.
Submitted Solution:
```
l = []
cur = 0
for c in input():
x = ord(c)
while x >= cur:
x -= 256
while x < cur:
print('...')
print('.X.')
cur -= 1
print('.X.')
```
Yes
| 14,749 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem you will write a simple code generator for a 2D programming language derived from [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck).
The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usual order (top to bottom, left to right), and each 'X' character is converted a Brainfuck instruction to be executed. The instruction is defined by the left, top and right neighbors of the 'X' character using the following conversion table:
<image>
You are given a string. Output a program in the described language which prints this string.
You can download the language interpreter used for judging here: <https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp> (use C++11 to compile the code). Note several implementation details:
* The first step of the language interpretation is conversion to a Brainfuck program, which is then executed.
* The code must be rectangular, with all lines of the same length. It can have at most 10,000 lines and 10,000 columns, and can have at most 500,000 'X' characters.
* The code has toroidal topology, i.e. the 'X' on the first line will have top neighbor in the last line.
* Brainfuck interpreter has 30000 memory cells which store integers from 0 to 255 with increment/decrement done modulo 256.
* Console input (, command) is allowed in Brainfuck code but has no effect when executed.
Input
The input consists of a single string of characters with ASCII codes between 33 ('!') and 122 ('z'), inclusive. The length of the string is between 1 and 10 characters, inclusive.
Output
Output a program in the described language which, when executed, will print the given message.
Example
Input
$$$
Output
.......X.......
......XXX......
.....XXXXX.....
....XXXXXXX....
...XXXXXXXXX...
..XXXXXXXXXXX..
.XXXXXXXXXXXXX.
...............
X.............X
X..............
X..............
X..............
Note
The example corresponds to the following Brainfuck program:
-
>+<
>+++<
>+++++<
>+++++++<
>+++++++++<
>+++++++++++<
< >
.
.
.
The triangular block decrements the first memory cell and sets the value of the second memory cell to 36 - the ASCII code of '$' character. The next line after the triangular block moves the memory pointer to the second memory cell, and the next three lines print the '$' character three times.
Submitted Solution:
```
import sys
LEN=500
def read_line():
return sys.stdin.readline().rstrip("\r\n")
s = read_line()
st = 0
for c in s:
c = ord(c) - 1 - st
print(LEN * '.')
print('..' + c * 'X' + (LEN - 2 - c) * '.')
print('.' + (c + 2) * 'X' + (LEN - 1 - (c + 2)) * '.')
print(LEN * '.')
d = c + 1 + st
st = 1
print('..XX' + '.X.' + d * '...' + '.' + 'XX..' + (LEN - 12 - 3 * d) * '.')
print('.XXX' + '.X.' + d * '.X.' + '.' + 'XXX.' + (LEN - 12 - 3 * d) * '.')
print(LEN * '.')
```
Yes
| 14,750 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem you will write a simple code generator for a 2D programming language derived from [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck).
The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usual order (top to bottom, left to right), and each 'X' character is converted a Brainfuck instruction to be executed. The instruction is defined by the left, top and right neighbors of the 'X' character using the following conversion table:
<image>
You are given a string. Output a program in the described language which prints this string.
You can download the language interpreter used for judging here: <https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp> (use C++11 to compile the code). Note several implementation details:
* The first step of the language interpretation is conversion to a Brainfuck program, which is then executed.
* The code must be rectangular, with all lines of the same length. It can have at most 10,000 lines and 10,000 columns, and can have at most 500,000 'X' characters.
* The code has toroidal topology, i.e. the 'X' on the first line will have top neighbor in the last line.
* Brainfuck interpreter has 30000 memory cells which store integers from 0 to 255 with increment/decrement done modulo 256.
* Console input (, command) is allowed in Brainfuck code but has no effect when executed.
Input
The input consists of a single string of characters with ASCII codes between 33 ('!') and 122 ('z'), inclusive. The length of the string is between 1 and 10 characters, inclusive.
Output
Output a program in the described language which, when executed, will print the given message.
Example
Input
$$$
Output
.......X.......
......XXX......
.....XXXXX.....
....XXXXXXX....
...XXXXXXXXX...
..XXXXXXXXXXX..
.XXXXXXXXXXXXX.
...............
X.............X
X..............
X..............
X..............
Note
The example corresponds to the following Brainfuck program:
-
>+<
>+++<
>+++++<
>+++++++<
>+++++++++<
>+++++++++++<
< >
.
.
.
The triangular block decrements the first memory cell and sets the value of the second memory cell to 36 - the ASCII code of '$' character. The next line after the triangular block moves the memory pointer to the second memory cell, and the next three lines print the '$' character three times.
Submitted Solution:
```
y='..\nX.\n..\n'
print(''.join(y*(255-ord(x))+'X.\n'*2+y*ord(x)for x in input()))
```
Yes
| 14,751 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem you will write a simple code generator for a 2D programming language derived from [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck).
The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usual order (top to bottom, left to right), and each 'X' character is converted a Brainfuck instruction to be executed. The instruction is defined by the left, top and right neighbors of the 'X' character using the following conversion table:
<image>
You are given a string. Output a program in the described language which prints this string.
You can download the language interpreter used for judging here: <https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp> (use C++11 to compile the code). Note several implementation details:
* The first step of the language interpretation is conversion to a Brainfuck program, which is then executed.
* The code must be rectangular, with all lines of the same length. It can have at most 10,000 lines and 10,000 columns, and can have at most 500,000 'X' characters.
* The code has toroidal topology, i.e. the 'X' on the first line will have top neighbor in the last line.
* Brainfuck interpreter has 30000 memory cells which store integers from 0 to 255 with increment/decrement done modulo 256.
* Console input (, command) is allowed in Brainfuck code but has no effect when executed.
Input
The input consists of a single string of characters with ASCII codes between 33 ('!') and 122 ('z'), inclusive. The length of the string is between 1 and 10 characters, inclusive.
Output
Output a program in the described language which, when executed, will print the given message.
Example
Input
$$$
Output
.......X.......
......XXX......
.....XXXXX.....
....XXXXXXX....
...XXXXXXXXX...
..XXXXXXXXXXX..
.XXXXXXXXXXXXX.
...............
X.............X
X..............
X..............
X..............
Note
The example corresponds to the following Brainfuck program:
-
>+<
>+++<
>+++++<
>+++++++<
>+++++++++<
>+++++++++++<
< >
.
.
.
The triangular block decrements the first memory cell and sets the value of the second memory cell to 36 - the ASCII code of '$' character. The next line after the triangular block moves the memory pointer to the second memory cell, and the next three lines print the '$' character three times.
Submitted Solution:
```
# python3
import math
import sys
WIDTH = 200
def add(n):
assert n >= 0
while n:
k = min(WIDTH - 1, n)
n -= k
print('.' * WIDTH)
print('X' * (k - 1) + '.' * (WIDTH - k) + 'X')
print('X' * WIDTH)
def print_mem2():
print('.' * WIDTH)
print('X' + '.' * (WIDTH - 2) + 'X')
print('X' + '.' * (WIDTH - 1))
# main
string = map(ord, input().strip())
mem2 = 0
for symbol in string:
diff = (symbol - mem2) % 256
mem2 = symbol
print('.' * WIDTH)
add(diff)
print_mem2()
print('.' * WIDTH)
```
No
| 14,752 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem you will write a simple code generator for a 2D programming language derived from [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck).
The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usual order (top to bottom, left to right), and each 'X' character is converted a Brainfuck instruction to be executed. The instruction is defined by the left, top and right neighbors of the 'X' character using the following conversion table:
<image>
You are given a string. Output a program in the described language which prints this string.
You can download the language interpreter used for judging here: <https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp> (use C++11 to compile the code). Note several implementation details:
* The first step of the language interpretation is conversion to a Brainfuck program, which is then executed.
* The code must be rectangular, with all lines of the same length. It can have at most 10,000 lines and 10,000 columns, and can have at most 500,000 'X' characters.
* The code has toroidal topology, i.e. the 'X' on the first line will have top neighbor in the last line.
* Brainfuck interpreter has 30000 memory cells which store integers from 0 to 255 with increment/decrement done modulo 256.
* Console input (, command) is allowed in Brainfuck code but has no effect when executed.
Input
The input consists of a single string of characters with ASCII codes between 33 ('!') and 122 ('z'), inclusive. The length of the string is between 1 and 10 characters, inclusive.
Output
Output a program in the described language which, when executed, will print the given message.
Example
Input
$$$
Output
.......X.......
......XXX......
.....XXXXX.....
....XXXXXXX....
...XXXXXXXXX...
..XXXXXXXXXXX..
.XXXXXXXXXXXXX.
...............
X.............X
X..............
X..............
X..............
Note
The example corresponds to the following Brainfuck program:
-
>+<
>+++<
>+++++<
>+++++++<
>+++++++++<
>+++++++++++<
< >
.
.
.
The triangular block decrements the first memory cell and sets the value of the second memory cell to 36 - the ASCII code of '$' character. The next line after the triangular block moves the memory pointer to the second memory cell, and the next three lines print the '$' character three times.
Submitted Solution:
```
s = input()
state = 0
for c in s:
diff = ord(c) - state
state = ord(c)
if diff < -1:
diff += 256
for _ in range((diff+1)//2):
print('....\n.XX.\nXXXX')
if ord(c)%2==1:
print('....\nX...\nX...')
else:
print('X...')
```
No
| 14,753 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem you will write a simple code generator for a 2D programming language derived from [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck).
The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usual order (top to bottom, left to right), and each 'X' character is converted a Brainfuck instruction to be executed. The instruction is defined by the left, top and right neighbors of the 'X' character using the following conversion table:
<image>
You are given a string. Output a program in the described language which prints this string.
You can download the language interpreter used for judging here: <https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp> (use C++11 to compile the code). Note several implementation details:
* The first step of the language interpretation is conversion to a Brainfuck program, which is then executed.
* The code must be rectangular, with all lines of the same length. It can have at most 10,000 lines and 10,000 columns, and can have at most 500,000 'X' characters.
* The code has toroidal topology, i.e. the 'X' on the first line will have top neighbor in the last line.
* Brainfuck interpreter has 30000 memory cells which store integers from 0 to 255 with increment/decrement done modulo 256.
* Console input (, command) is allowed in Brainfuck code but has no effect when executed.
Input
The input consists of a single string of characters with ASCII codes between 33 ('!') and 122 ('z'), inclusive. The length of the string is between 1 and 10 characters, inclusive.
Output
Output a program in the described language which, when executed, will print the given message.
Example
Input
$$$
Output
.......X.......
......XXX......
.....XXXXX.....
....XXXXXXX....
...XXXXXXXXX...
..XXXXXXXXXXX..
.XXXXXXXXXXXXX.
...............
X.............X
X..............
X..............
X..............
Note
The example corresponds to the following Brainfuck program:
-
>+<
>+++<
>+++++<
>+++++++<
>+++++++++<
>+++++++++++<
< >
.
.
.
The triangular block decrements the first memory cell and sets the value of the second memory cell to 36 - the ASCII code of '$' character. The next line after the triangular block moves the memory pointer to the second memory cell, and the next three lines print the '$' character three times.
Submitted Solution:
```
target = input()
codes = [ord(x) for x in target]
def letter(code: int):
line1 = '.' + 'X'*code + '.'
line2 = 'X' * (code+2)
return [line1, line2]
def printer(code: int):
""" -2, print, -code"""
lines = ['.X.X']
line2 = 'XX.' + 'X.'*(code-1)
line3 = '.'*(code*2 - 1) + 'XX'
return lines + [line2, line3]
def one(code):
r = []
r.extend(letter(code+2))
r.append('.')
r.extend(printer(code))
r.append('.')
r.append('.')
return r
def all(codes):
r = []
for code in codes:
r.extend(one(code))
maxlen = max(len(x) for x in r) + 3
for line in r:
print(line + '.'*(maxlen - len(line)))
# one(codes[0])
all(codes)
```
No
| 14,754 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem you will write a simple code generator for a 2D programming language derived from [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck).
The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usual order (top to bottom, left to right), and each 'X' character is converted a Brainfuck instruction to be executed. The instruction is defined by the left, top and right neighbors of the 'X' character using the following conversion table:
<image>
You are given a string. Output a program in the described language which prints this string.
You can download the language interpreter used for judging here: <https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp> (use C++11 to compile the code). Note several implementation details:
* The first step of the language interpretation is conversion to a Brainfuck program, which is then executed.
* The code must be rectangular, with all lines of the same length. It can have at most 10,000 lines and 10,000 columns, and can have at most 500,000 'X' characters.
* The code has toroidal topology, i.e. the 'X' on the first line will have top neighbor in the last line.
* Brainfuck interpreter has 30000 memory cells which store integers from 0 to 255 with increment/decrement done modulo 256.
* Console input (, command) is allowed in Brainfuck code but has no effect when executed.
Input
The input consists of a single string of characters with ASCII codes between 33 ('!') and 122 ('z'), inclusive. The length of the string is between 1 and 10 characters, inclusive.
Output
Output a program in the described language which, when executed, will print the given message.
Example
Input
$$$
Output
.......X.......
......XXX......
.....XXXXX.....
....XXXXXXX....
...XXXXXXXXX...
..XXXXXXXXXXX..
.XXXXXXXXXXXXX.
...............
X.............X
X..............
X..............
X..............
Note
The example corresponds to the following Brainfuck program:
-
>+<
>+++<
>+++++<
>+++++++<
>+++++++++<
>+++++++++++<
< >
.
.
.
The triangular block decrements the first memory cell and sets the value of the second memory cell to 36 - the ASCII code of '$' character. The next line after the triangular block moves the memory pointer to the second memory cell, and the next three lines print the '$' character three times.
Submitted Solution:
```
target = input()
codes = [ord(x) for x in target]
def letter(code: int):
line1 = '.' + 'X'*code + '.'
line2 = 'X' * (code+2)
return [line1, line2]
def printer(code: int):
""" -2, print, -code"""
lines = ['.X.X']
line2 = 'XX.' + 'X.'*(code-1)
line3 = '.'*(code*2 - 1) + 'XX'
return lines + [line2, line3]
def one(code):
r = []
r.extend(letter(code))
r.append('.')
r.extend(printer(code))
r.append('.')
r.append('.')
return r
def all(codes):
r = []
for code in codes:
r.extend(one(code))
maxlen = max(len(x) for x in r) + 3
for line in r:
print(line + '.'*(maxlen - len(line)))
# one(codes[0])
all(codes)
```
No
| 14,755 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the modification of the problem used during the official round. Unfortunately, author's solution of the original problem appeared wrong, so the problem was changed specially for the archive.
Once upon a time in a far away kingdom lived the King. The King had a beautiful daughter, Victoria. They lived happily, but not happily ever after: one day a vicious dragon attacked the kingdom and stole Victoria. The King was full of grief, yet he gathered his noble knights and promised half of his kingdom and Victoria's hand in marriage to the one who will save the girl from the infernal beast.
Having travelled for some time, the knights found the dragon's lair and all of them rushed there to save Victoria. Each knight spat on the dragon once and, as the dragon had quite a fragile and frail heart, his heart broke and poor beast died. As for the noble knights, they got Victoria right to the King and started brawling as each one wanted the girl's hand in marriage.
The problem was that all the noble knights were equally noble and equally handsome, and Victoria didn't want to marry any of them anyway. Then the King (and he was a very wise man and didn't want to hurt anybody's feelings) decided to find out who will get his daughter randomly, i.e. tossing a coin. However, there turned out to be n noble knights and the coin only has two sides. The good thing is that when a coin is tossed, the coin falls on each side with equal probability. The King got interested how to pick one noble knight using this coin so that all knights had equal probability of being chosen (the probability in that case should always be equal to 1 / n). First the King wants to know the expected number of times he will need to toss a coin to determine the winner. Besides, while tossing the coin, the King should follow the optimal tossing strategy (i.e. the strategy that minimizes the expected number of tosses). Help the King in this challenging task.
Input
The first line contains a single integer n from the problem's statement (1 ≤ n ≤ 10000).
Output
Print the sought expected number of tosses as an irreducible fraction in the following form: "a/b" (without the quotes) without leading zeroes.
Examples
Input
2
Output
1/1
Input
3
Output
8/3
Input
4
Output
2/1
Tags: implementation, probabilities, trees
Correct Solution:
```
from fractions import *
n,L=int(input()),0
while (n%2==0):n,L=n//2,L+1
if (n==1):print('%d/1'%L)
else:
s,t=1,1
for i in range(n):
t,s=t*2%n,s*2
if (t==1):
m=i+1
break
r,t,i,ans=s,s*n,L,0
while (r>1):
i,t=i+1,t//2
if (r-t>0):
r,ans=r-t,ans+i*t
print(Fraction(ans+m,s-1))
# Made By Mostafa_Khaled
```
| 14,756 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the modification of the problem used during the official round. Unfortunately, author's solution of the original problem appeared wrong, so the problem was changed specially for the archive.
Once upon a time in a far away kingdom lived the King. The King had a beautiful daughter, Victoria. They lived happily, but not happily ever after: one day a vicious dragon attacked the kingdom and stole Victoria. The King was full of grief, yet he gathered his noble knights and promised half of his kingdom and Victoria's hand in marriage to the one who will save the girl from the infernal beast.
Having travelled for some time, the knights found the dragon's lair and all of them rushed there to save Victoria. Each knight spat on the dragon once and, as the dragon had quite a fragile and frail heart, his heart broke and poor beast died. As for the noble knights, they got Victoria right to the King and started brawling as each one wanted the girl's hand in marriage.
The problem was that all the noble knights were equally noble and equally handsome, and Victoria didn't want to marry any of them anyway. Then the King (and he was a very wise man and didn't want to hurt anybody's feelings) decided to find out who will get his daughter randomly, i.e. tossing a coin. However, there turned out to be n noble knights and the coin only has two sides. The good thing is that when a coin is tossed, the coin falls on each side with equal probability. The King got interested how to pick one noble knight using this coin so that all knights had equal probability of being chosen (the probability in that case should always be equal to 1 / n). First the King wants to know the expected number of times he will need to toss a coin to determine the winner. Besides, while tossing the coin, the King should follow the optimal tossing strategy (i.e. the strategy that minimizes the expected number of tosses). Help the King in this challenging task.
Input
The first line contains a single integer n from the problem's statement (1 ≤ n ≤ 10000).
Output
Print the sought expected number of tosses as an irreducible fraction in the following form: "a/b" (without the quotes) without leading zeroes.
Examples
Input
2
Output
1/1
Input
3
Output
8/3
Input
4
Output
2/1
Tags: implementation, probabilities, trees
Correct Solution:
```
from math import gcd
def PRINT(a, b) :
print(str(int(a)) + "/" + str(int(b)))
def solve(n) :
pre = 0
while(n > 1 and (n % 2 == 0)) :
pre = pre + 1
n = n // 2
if(n == 1) :
PRINT(pre, 1)
return
arr = []
rem = 1
while(True) :
rem = rem * 2
arr.append(int(rem // n))
rem = rem % n
if(rem == 1) :
break
k = len(arr)
ans = 0
for i in range(0, k) :
if(arr[i] == 1) :
ans = ans + (2 ** (k-1-i)) * (i+1)
ans = ans * n + k
A = ans
B = 2**k - 1
G = gcd(A, B)
A = A // G
B = B // G
PRINT(A + B * pre, B)
n = int(input())
solve(n)
```
| 14,757 |
Provide a correct Python 3 solution for this coding contest problem.
Given is an integer N. Find the minimum possible positive integer k such that (1+2+\cdots+k) is a multiple of N. It can be proved that such a positive integer k always exists.
Constraints
* 1 \leq N \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer in a line.
Examples
Input
11
Output
10
Input
20200920
Output
1100144
"Correct Solution:
```
# -*- coding: utf-8 -*-
import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline
INF = 1 << 50
def read_int():
return int(readline())
def read_int_n():
return list(map(int, readline().split()))
def read_float():
return float(readline())
def read_float_n():
return list(map(float, readline().split()))
def read_str():
return readline().strip()
def read_str_n():
return readline().strip().split()
def ep(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.perf_counter()
ret = f(*args, **kwargs)
e = time.perf_counter()
ep(e - s, 'sec')
return ret
return wrap
def divisor(n):
for i in range(1, int(n**0.5)+1):
if n % i == 0:
yield i
if i != n // i:
yield n // i
def exEuclid(a, mod):
b = mod
s, u = 1, 0
while b:
q = a // b
a, b = b, a % b
s, u = u, s - q * u
return a, s % mod
def crt(R, M):
assert len(R) == len(M)
N = len(R)
r0, m0 = 0, 1
for r, m in zip(R, M):
assert m >= 1
r %= m
if m0 < m:
r0, r = r, r0
m0, m = m, m0
if m0 % m == 0:
if r0 % m != r:
return (0, 0)
continue
g, im = exEuclid(m0, m)
u = m // g
if (r - r0) % g:
return (0, 0)
x = (r - r0) // g % u * im % u
r0 += x * m0
m0 *= u
if r0 < 0:
r0 += m0
return (r0, m0)
@mt
def slv(N):
def f(n):
return (n+1)*n // 2
cand = list(divisor(2*N))
cand.sort()
ans = INF
for x in cand:
kc, _ = crt([0, -1], (x, 2*N//x))
if kc != 0:
ans = min(ans, kc)
return ans
def main():
N = read_int()
print(slv(N))
if __name__ == '__main__':
main()
```
| 14,758 |
Provide a correct Python 3 solution for this coding contest problem.
Given is an integer N. Find the minimum possible positive integer k such that (1+2+\cdots+k) is a multiple of N. It can be proved that such a positive integer k always exists.
Constraints
* 1 \leq N \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer in a line.
Examples
Input
11
Output
10
Input
20200920
Output
1100144
"Correct Solution:
```
from collections import Counter
# 拡張ユークリッド互除法
# gcd(a,b) と ax + by = gcd(a,b) の最小整数解を返す
def egcd(a, b):
if a == 0:
return b, 0, 1
else:
g, y, x = egcd(b % a, a)
return g, x - (b // a) * y, y
def chineseRem(b1, m1, b2, m2):
# 中国剰余定理
# x ≡ b1 (mod m1) ∧ x ≡ b2 (mod m2) <=> x ≡ r (mod m)
# となる(r. m)を返す
# 解無しのとき(0, -1)
d, p, q = egcd(m1, m2)
if (b2 - b1) % d != 0:
return 0, -1
m = m1 * (m2 // d) # m = lcm(m1, m2)
tmp = (b2-b1) // d * p % (m2 // d)
r = (b1 + m1 * tmp) % m
return r, m
def prime_factorize(n):
a = []
while n % 2 == 0:
a.append(2)
n //= 2
f = 3
while f * f <= n:
if n % f == 0:
a.append(f)
n //= f
else:
f += 2
if n != 1:
a.append(n)
return a
N = int(input())
p = prime_factorize(2*N)
c = Counter(p)
if N == 1:
print(1)
exit()
if len(c.keys()) == 1:
print(N-1)
exit()
d = [k ** v for k, v in c.items()]
m = len(d)
ans = N-1
for i in range(2 ** m):
a, b = 1, 1
for j in range(m):
if (i >> j) & 1:
a *= d[j]
else:
b *= d[j]
if a == 1 or b == 1:
continue
ans = min(ans, chineseRem(0, a, b-1, b)[0])
ans = min(ans, chineseRem(a-1, a, 0, b)[0])
print(ans)
```
| 14,759 |
Provide a correct Python 3 solution for this coding contest problem.
Given is an integer N. Find the minimum possible positive integer k such that (1+2+\cdots+k) is a multiple of N. It can be proved that such a positive integer k always exists.
Constraints
* 1 \leq N \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer in a line.
Examples
Input
11
Output
10
Input
20200920
Output
1100144
"Correct Solution:
```
def inv_gcd(a, b):
a = (a + b) % b
if a == 0:
return (b, 0)
s, t = b, a
m0, m1 = 0, 1
while t:
u = s // t
s -= t * u
m0 -= m1 * u
tmp = s
s = t
t = tmp
tmp = m0
m0 = m1
m1 = tmp
if m0 < 0:
m0 += b // s
return (s, m0)
def crt(r, m):
n = len(r)
r0, m0 = 0, 1
for i in range(n):
r1, m1 = (r[i] + m[i]) % m[i], m[i]
if m0 < m1:
m0, m1 = m1, m0
r0, r1 = r1, r0
if m0 % m1 == 0:
if r0 % m1 != r1:
return (0, 0)
continue
g, im = inv_gcd(m0, m1)
u1 = m1 // g
if (r1 - r0) % g:
return (0, 0)
x = (r1 - r0) // g % u1 * im % u1
r0 += x * m0
m0 *= u1
if (r0 < 0):
r0 += m0
return (r0, m0)
def divisors(n):
divisors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n//i)
divisors.sort()
return divisors
# print(divisors(z))
z=int(input())
ans = z-1 if z%2 else 2*z-1
for i in divisors(2*z):
y=2*z//i
if y == 1:
continue
a=[0,-1]
b=[i,y]
rem, mod = crt(a, b)
#print(rem)
#print(mod)
if rem == mod == 0:
continue
ans = min(ans, rem)
print(ans if z-1 else 1)
```
| 14,760 |
Provide a correct Python 3 solution for this coding contest problem.
Given is an integer N. Find the minimum possible positive integer k such that (1+2+\cdots+k) is a multiple of N. It can be proved that such a positive integer k always exists.
Constraints
* 1 \leq N \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer in a line.
Examples
Input
11
Output
10
Input
20200920
Output
1100144
"Correct Solution:
```
import sys
input = sys.stdin.readline
n = int(input()) * 2
D = []
for i in range(2, int(n**0.5) + 1):
d = 1
while n%i == 0:
n //= i
d *= i
if d != 1:
D.append(d)
if n == 1:
break
if n != 1:
D.append(n)
# print(D)
# 拡張Euclidの互除法。ap + bq = gcd(a, b) となる p, q, d=gcd(a, b) を返す。
def extgcd(a, b):
if b == 0:
return 1, 0, a
q, p, d = extgcd(b, a%b)
q -= (a // b) * p
return p, q, d
def crt(R, M): # 中国剰余定理。Rは余り、Mは割る数の配列。不定なら(0,1)、不能なら(0,0)が返る。
r = 0
m = 1
for i in range(len(R)):
p, _, d = extgcd(m, M[i])
if (R[i] - r) % d != 0:
return (0, 0)
tmp = (R[i] - r) // d * p % (M[i] // d)
r += m * tmp
m *= M[i] // d
return (r % m, m)
ans = float("inf")
# Rs = []
for i in range(1, 2**len(D)):
ib = format(i, "b").zfill(len(D))
R = [0] * len(D)
for j in range(len(D)):
if ib[j] == "1":
R[j] = D[j]-1
ans = min(ans, crt(R, D)[0])
print(ans)
```
| 14,761 |
Provide a correct Python 3 solution for this coding contest problem.
Given is an integer N. Find the minimum possible positive integer k such that (1+2+\cdots+k) is a multiple of N. It can be proved that such a positive integer k always exists.
Constraints
* 1 \leq N \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer in a line.
Examples
Input
11
Output
10
Input
20200920
Output
1100144
"Correct Solution:
```
from itertools import product
def main():
n = int(input())
n_copy = n
if n == 1:
print(1)
exit()
if n % 2 == 0:
ans = 2 * n - 1
n *= 2
else:
ans = n - 1
factors = []
for p in range(2, n):
if p * p > n:
if n > 1:
factors.append(n)
break
if n % p == 0:
cnt = 0
while n % p == 0:
cnt += 1
n //= p
factors.append(p ** cnt)
for tf in product([True, False], repeat=len(factors)):
a, b = 1, 1
for i in range(len(factors)):
if tf[i]:
a *= factors[i]
else:
b *= factors[i]
if a == 1 or b == 1:
continue
if a < b:
a, b = b, a
# Euclidean Algorithm
# a*x - b*y = 1
# quotient: 商
l = []
quo = []
while a % b > 1:
l.append(a)
a = b
quo.append(0)
quo[-1], b = divmod(l[-1], b)
x, y = 1, a//b
flag = True
while l:
if flag:
x += y * quo.pop()
b = l.pop()
else:
y += x * quo.pop()
a = l.pop()
flag = not flag
if ans > b * y:
ans = b * y
print(ans)
main()
```
| 14,762 |
Provide a correct Python 3 solution for this coding contest problem.
Given is an integer N. Find the minimum possible positive integer k such that (1+2+\cdots+k) is a multiple of N. It can be proved that such a positive integer k always exists.
Constraints
* 1 \leq N \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer in a line.
Examples
Input
11
Output
10
Input
20200920
Output
1100144
"Correct Solution:
```
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")
n = int(input())
def factor(n, m=None):
# mを与えると、高々その素因数まで見て、残りは分解せずにそのまま出力する
arr = {}
temp = n
M = int(-(-n**0.5//1))+1
if m is not None:
M = min(m+1, M)
for i in range(2, M):
if i>temp:
break
if temp%i==0:
cnt=0
while temp%i==0:
cnt+=1
temp //= i
arr[i] = cnt
if temp!=1:
arr[temp] = 1
if not arr:
arr[n] = 1
return arr
n *= 2
f = factor(n)
# print(f)
from itertools import product
ans = n-1
def gcd2(a, b):
"""a*x + b*y = gcd(a,b)なるx,yも求める
"""
l = []
while b:
l.append(divmod(a,b))
a, b = b, a%b
x, y = 1, 0
for aa,bb in l[::-1]:
x, y = y, x - aa*y
return a, x, y
def sub(x,y):
g,k,l = gcd2(x, -y)
if g!=1:
return None
return abs(k*x)
for ks in product(*[range(2) for _ in f.values()]):
val = 1
val2 = 1
for k,v in zip(ks, f.keys()):
if k:
val *= pow(v,f[v])
else:
val2 *= pow(v,f[v])
# print(val*val2)
if val==1 or val2==1:
continue
res = gcd2(val, -val2)
if res is not None and abs(res[0])==1:
# print(val,val2,res)
ans = min(ans, abs(val*res[1]))
print(ans)
```
| 14,763 |
Provide a correct Python 3 solution for this coding contest problem.
Given is an integer N. Find the minimum possible positive integer k such that (1+2+\cdots+k) is a multiple of N. It can be proved that such a positive integer k always exists.
Constraints
* 1 \leq N \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer in a line.
Examples
Input
11
Output
10
Input
20200920
Output
1100144
"Correct Solution:
```
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
N = int(input())
N *= 2
def crt(a, n, b, m, inv):
out = a
#inv = pow(n, -1, m)
out += (b - a) * n * inv
return out % (n * m)
p = []
i = 2
while i * i <= N:
curr = 1
while N % i == 0:
N//= i
curr *= i
if curr != 1:
p.append(curr)
i += 1
if N != 1:
p.append(N)
poss = [0]
mod = 1
for v in p:
new = []
#inv = pow(mod, -1, v)
inv = modinv(mod, v)
for u in poss:
new.append(crt(u, mod, 0, v, inv))
new.append(crt(u, mod, -1, v, inv))
poss = new
mod *= v
poss.sort()
poss += [mod]
print(poss[1])
```
| 14,764 |
Provide a correct Python 3 solution for this coding contest problem.
Given is an integer N. Find the minimum possible positive integer k such that (1+2+\cdots+k) is a multiple of N. It can be proved that such a positive integer k always exists.
Constraints
* 1 \leq N \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer in a line.
Examples
Input
11
Output
10
Input
20200920
Output
1100144
"Correct Solution:
```
def euclid(x, y):
c0, c1 = x, y
a0, a1 = 1, 0
b0, b1 = 0, 1
while c1 != 0:
m = c0 % c1
q = c0 // c1
c0, c1 = c1, m
a0, a1 = a1, (a0 - q * a1)
b0, b1 = b1, (b0 - q * b1)
return a0, b0
n=int(input())
n=n*2
soinsu=[]
num=n
for i in range(2,max(20,n)):
if(i*i>n):
if(num!=1):
soinsu.append([num,1])
break
if(num%i!=0):
continue
cnt=0
while(num%i==0):
cnt+=1
num//=i
soinsu.append([i,cnt])
kazu=len(soinsu)
ans=[]
for i in range(2**(kazu-1)):
a=1
for j in range(kazu):
if((i&1<<j)!=0):
a*=soinsu[j][0]**soinsu[j][1]
b=n//a
c,d=euclid(a,b)
if(c*d==0):
c+=b
d+=a
ans.append(max(a*c,b*d))
if(kazu==1):
print(min(ans)-2)
else:
print(min(ans)-1)
```
| 14,765 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is an integer N. Find the minimum possible positive integer k such that (1+2+\cdots+k) is a multiple of N. It can be proved that such a positive integer k always exists.
Constraints
* 1 \leq N \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer in a line.
Examples
Input
11
Output
10
Input
20200920
Output
1100144
Submitted Solution:
```
#素因数分解、計算量はO(√N)
from collections import defaultdict
def factorize(n):
b = 2
dic = defaultdict(lambda: 0)
while b * b <= n:
while n % b == 0:
n //= b
dic[b] += 1
b = b + 1
if n > 1:
dic[n] += 1
return dic
N = int(input())
fct = factorize(2*N)
lis = []
for k,v in fct.items():
lis.append(pow(k,v))
ans = 10**18
from itertools import groupby, accumulate, product, permutations, combinations
for pro in product([1,0],repeat=len(lis)):
prod1 = 1
for i,p in enumerate(pro):
if p==1:
prod1 *= lis[i]
prod2 = (N*2)//prod1
if prod1<prod2:
# prod1,prod2 = prod2,prod1
continue
for i in range(1,prod2+1):
if prod1*i>ans:
break
if (prod1*i-1)%prod2==0:
ans = min(ans, prod1*i-1)
break
if (prod1*i+1)%prod2==0:
ans = min(ans, prod1*i)
break
print(ans)
```
Yes
| 14,766 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is an integer N. Find the minimum possible positive integer k such that (1+2+\cdots+k) is a multiple of N. It can be proved that such a positive integer k always exists.
Constraints
* 1 \leq N \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer in a line.
Examples
Input
11
Output
10
Input
20200920
Output
1100144
Submitted Solution:
```
from math import gcd
from collections import Counter
from itertools import product
min2 = lambda x,y: x if x < y else y
# 拡張ユークリッド互除法
# ax + by = gcd(a,b)の最小整数解を返す
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
# mを法とするaの乗法的逆元
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
def chinese_remainder_theorem(R, M, prod):
"""
returns x s.t.
all(x%m == r for r,m in zip(R,M))
"""
s = 0
for m,r in zip(M,R):
p = prod//m
s += r * p * modinv(p,m)
s %= prod
return s
# 素因数分解
def prime_factors(n):
i = 2
while i * i <= n:
if n % i:
i += 1
else:
n //= i
yield i
if n > 1:
yield n
N = int(input())
factors = Counter(prime_factors(N))
if factors[2] > 0:
factors[2] += 1
N *= 2
mods = [f**p for f,p in factors.items()]
res = N
for R in product(*((0,m-1) for m in mods)):
t = chinese_remainder_theorem(R, mods, N)
if t > 0:
res = min2(res, t)
print(res)
```
Yes
| 14,767 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is an integer N. Find the minimum possible positive integer k such that (1+2+\cdots+k) is a multiple of N. It can be proved that such a positive integer k always exists.
Constraints
* 1 \leq N \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer in a line.
Examples
Input
11
Output
10
Input
20200920
Output
1100144
Submitted Solution:
```
from itertools import product
def main():
n = int(input())
# Exception Handling
if n == 1:
print(1)
exit()
# calculate the maximum answer
if n % 2 == 0:
ans = 2 * n - 1
n *= 2
else:
ans = n - 1
# Prime Factorization
factors = []
for p in range(2, n):
if p * p > n:
if n > 1:
factors.append(n)
break
if n % p == 0:
cnt = 0
while n % p == 0:
cnt += 1
n //= p
factors.append(p ** cnt)
# Full Search
# k%factor==0 or (k+1)%factor==0
for tf in product([True, False], repeat=len(factors)):
a, b = 1, 1
for i in range(len(factors)):
if tf[i]:
a *= factors[i]
else:
b *= factors[i]
if a < b or a == 1 or b == 1:
continue
# Euclidean Algorithm
# a*x - b*y = 1
l = []
quo = []
while a % b > 1:
l.append(a)
a = b
quo.append(0)
quo[-1], b = divmod(l[-1], b)
x, y = 1, a//b
flag = True
while l:
if flag:
x += y * quo.pop()
b = l.pop()
else:
y += x * quo.pop()
a = l.pop()
flag = not flag
if ans > b * y:
ans = b * y
print(ans)
main()
```
Yes
| 14,768 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is an integer N. Find the minimum possible positive integer k such that (1+2+\cdots+k) is a multiple of N. It can be proved that such a positive integer k always exists.
Constraints
* 1 \leq N \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer in a line.
Examples
Input
11
Output
10
Input
20200920
Output
1100144
Submitted Solution:
```
#素因数分解、計算量はO(√N)
from collections import defaultdict
def factorize(n):
b = 2
dic = defaultdict(lambda: 0)
while b * b <= n:
while n % b == 0:
n //= b
dic[b] += 1
b = b + 1
if n > 1:
dic[n] += 1
return dic
def extgcd(a, b):
if b:
d, y, x = extgcd(b, a%b)
y -= (a//b)*x
return d, x, y
else:
return a, 1, 0
N = int(input())
fct = factorize(2*N)
lis = []
for k,v in fct.items():
lis.append(pow(k,v))
ans = 10**18
from itertools import groupby, accumulate, product, permutations, combinations
for pro in product([0,1],repeat=len(lis)):
prod1 = 1
for i,p in enumerate(pro):
if p==1:
prod1 *= lis[i]
prod2 = (N*2)//prod1
if min(prod1,prod2)==1:
ans = min(ans, max(prod1,prod2)-1)
else:
d,a1,a2 = extgcd(prod1,prod2)
ans = min(ans, min(abs(a1*prod1),abs(a2*prod2)))
print(ans)
```
Yes
| 14,769 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is an integer N. Find the minimum possible positive integer k such that (1+2+\cdots+k) is a multiple of N. It can be proved that such a positive integer k always exists.
Constraints
* 1 \leq N \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer in a line.
Examples
Input
11
Output
10
Input
20200920
Output
1100144
Submitted Solution:
```
#dt = {} for i in x: dt[i] = dt.get(i,0)+1
import sys;input = sys.stdin.readline
inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()]
import math
_1_50 = 1 << 50 # 2**50 == 1,125,899,906,842,624
def isqrt(x):
"""Return the integer part of the square root of x, even for very
large integer values."""
if x < 0:
raise ValueError('square root not defined for negative numbers')
if x < _1_50:
return int(math.sqrt(x)) # use math's sqrt() for small parameters
n = int(x)
if n <= 1:
return n # handle sqrt(0)==0, sqrt(1)==1
# Make a high initial estimate of the result (a little lower is slower!!!)
r = 1 << ((n.bit_length() + 1) >> 1)
while True:
newr = (r + n // r) >> 1 # next estimate by Newton-Raphson
if newr >= r:
return r
r = newr
n = inp()
delta = 8*n
t = 1
from math import sqrt
while True:
t += delta
sq = isqrt(t)
if sq*sq != t:
continue
a = (-1+sq)/2
b = (-1-sq)/2
ans = float('inf')
if a > 0 and a.is_integer():
ans = min(ans,a)
if b > 0 and b.is_integer():
ans = min(ans,b)
if ans != float('inf'):
print(int(ans))
break
```
No
| 14,770 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is an integer N. Find the minimum possible positive integer k such that (1+2+\cdots+k) is a multiple of N. It can be proved that such a positive integer k always exists.
Constraints
* 1 \leq N \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer in a line.
Examples
Input
11
Output
10
Input
20200920
Output
1100144
Submitted Solution:
```
z=int(input())
def solv_quadratic_equation(a, b, c):
""" 2次方程式を解く """
D = (b**2 - 4*a*c) ** (1/2)
x_1 = (-b + D) / (2 * a)
x_2 = (-b - D) / (2 * a)
return x_1,x_2
ans=0
i=1
# print(10**15)
# a,b=solv_quadratic_equation(1,1,1000000000000000)
# print(a,b)
while True:
a,b=solv_quadratic_equation(1,1,-2*z*i)
if a>=b:
if a.is_integer():
# print(a)
# print(b)
ans=a
break
elif a<=b:
if b.is_integer():
# print(a)
# print(b)
ans=b
break
i+=1
print(int(ans))
```
No
| 14,771 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is an integer N. Find the minimum possible positive integer k such that (1+2+\cdots+k) is a multiple of N. It can be proved that such a positive integer k always exists.
Constraints
* 1 \leq N \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer in a line.
Examples
Input
11
Output
10
Input
20200920
Output
1100144
Submitted Solution:
```
N=int(input())
i = 1
while True:
k = int((N*2*i)**0.5)
for ik in range(k, k+100):
if ik*(ik+1) == 2*N*i:
print(ik)
exit()
if ik*(ik+1)>2*N*i:
break
i=i+1
```
No
| 14,772 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is an integer N. Find the minimum possible positive integer k such that (1+2+\cdots+k) is a multiple of N. It can be proved that such a positive integer k always exists.
Constraints
* 1 \leq N \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer in a line.
Examples
Input
11
Output
10
Input
20200920
Output
1100144
Submitted Solution:
```
n=int(input())
for i in range(int(n**.5)+1,1,-1):
if n % i ==0:
for j in range ( i, n + 1 ):
if (((j * (j + 1))) % (2 * n)) == 0:
print ( j )
exit(0)
else:print(n-1)
```
No
| 14,773 |
Provide a correct Python 3 solution for this coding contest problem.
You are playing a game and your goal is to maximize your expected gain. At the beginning of the game, a pawn is put, uniformly at random, at a position p\in\\{1,2,\dots, N\\}. The N positions are arranged on a circle (so that 1 is between N and 2).
The game consists of turns. At each turn you can either end the game, and get A_p dollars (where p is the current position of the pawn), or pay B_p dollar to keep playing. If you decide to keep playing, the pawn is randomly moved to one of the two adjacent positions p-1, p+1 (with the identifications 0 = N and N+1=1).
What is the expected gain of an optimal strategy?
Note: The "expected gain of an optimal strategy" shall be defined as the supremum of the expected gain among all strategies such that the game ends in a finite number of turns.
Constraints
* 2 \le N \le 200,000
* 0 \le A_p \le 10^{12} for any p = 1,\ldots, N
* 0 \le B_p \le 100 for any p = 1, \ldots, N
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 \cdots A_N
B_1 B_2 \cdots B_N
Output
Print a single real number, the expected gain of an optimal strategy. Your answer will be considered correct if its relative or absolute error does not exceed 10^{-10}.
Examples
Input
5
4 2 6 3 5
1 1 1 1 1
Output
4.700000000000
Input
4
100 0 100 0
0 100 0 100
Output
50.000000000000
Input
14
4839 5400 6231 5800 6001 5200 6350 7133 7986 8012 7537 7013 6477 5912
34 54 61 32 52 61 21 43 65 12 45 21 1 4
Output
7047.142857142857
Input
10
470606482521 533212137322 116718867454 746976621474 457112271419 815899162072 641324977314 88281100571 9231169966 455007126951
26 83 30 59 100 88 84 91 54 61
Output
815899161079.400024414062
"Correct Solution:
```
from math import gcd
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
class Seg_min():
def __init__(self,x):
#####単位元######
self.ide_ele_min = 10**10
self.func = min
self.n = len(x)
#num_max:n以上の最小の2のべき乗
self.num_max =2**(self.n-1).bit_length()
self.x = [self.ide_ele_min]*2*self.num_max
for i,num in enumerate(x, self.num_max):
self.x[i] = num
for i in range(self.num_max-1,0,-1):
self.x[i] = self.func(self.x[i<<1],self.x[(i<<1) + 1])
def update(self,i,x):
i += self.num_max
self.x[i] = x
while(i>0):
i = i//2
self.x[i] = self.func(self.x[i<<1],self.x[(i<<1) + 1])
def query(self,i,j):
res = self.ide_ele_min
if i>=j:
return res
i += self.num_max
j += self.num_max -1
while(i<=j):
if(i==j):
res = self.func(res,self.x[i])
break
if(i&1):
res = self.func(res,self.x[i])
i += 1
if(not j&1):
res = self.func(res,self.x[j])
j -= 1
i = i>>1
j = j>>1
return res
class Seg_max():
def __init__(self,x):
#####単位元######
self.ide_ele_min = 10**10 * -1
self.func = max
self.n = len(x)
#num_max:n以上の最小の2のべき乗
self.num_max =2**(self.n-1).bit_length()
self.x = [self.ide_ele_min]*2*self.num_max
for i,num in enumerate(x, self.num_max):
self.x[i] = num
for i in range(self.num_max-1,0,-1):
self.x[i] = self.func(self.x[i<<1],self.x[(i<<1) + 1])
def update(self,i,x):
i += self.num_max
self.x[i] = x
while(i>0):
i = i//2
self.x[i] = self.func(self.x[i<<1],self.x[(i<<1) + 1])
def query(self,i,j):
res = self.ide_ele_min
if i>=j:
return res
i += self.num_max
j += self.num_max -1
while(i<=j):
if(i==j):
res = self.func(res,self.x[i])
break
if(i&1):
res = self.func(res,self.x[i])
i += 1
if(not j&1):
res = self.func(res,self.x[j])
j -= 1
i = i>>1
j = j>>1
return res
# aの最大値のindexを取得
max_ind = 0
max_num = -1
for ind,i in enumerate(a):
if(i > max_num):
max_ind = ind
max_num = i
# max_ind が先頭になるように順番を変更
a = a[max_ind:] + a[:max_ind]
b = b[max_ind:] + b[:max_ind]
# Aiが小さい順に探索する。その順番を取得しておく。
order = [(i,ind) for ind,i in enumerate(a)]
order.sort()
# 累積和を作る。
# cs1は普通のBiの累積和
# cs2はi*Biの累積和
cs1_l = [0] * (n)
cs2_l = [0] * (n)
cs1_r = [0] * (n+1)
cs2_r = [0] * (n+1)
for i in range(1,n):
cs1_l[i] = cs1_l[i-1] + b[i]
cs2_l[i] = cs2_l[i-1] + b[i]*i
for i in range(1,n):
cs1_r[-(i+1)] = cs1_r[-i] + b[-i]
cs2_r[-(i+1)] = cs2_r[-i] + b[-i]*i
# 1週して戻ってくる点を追加しておく
a.append(a[0])
b.append(b[0])
# ゲームを終了する位置を記録・取得するためにセグ木を使う
seg_left = Seg_max( list(range(n+1)) )
seg_right = Seg_min( list(range(n+1)) )
# すべての点について、終了するかしないかを記録しておく。
end = [1] * (n+1)
# end[0] = 1
# end[-1] = 1
# 終了しない場合の期待値計算の関数
def calc_ex(ind):
left = seg_left.query(0,ind)
right = seg_right.query(ind+1,n+1)
div = right - left
wid_l = ind-left
wid_r = right-ind
# left-ind
base = cs2_l[ind] - cs2_l[left] - (cs1_l[ind] - cs1_l[left])*left
ex_l = base*2 * wid_r
# ind-right
base = cs2_r[ind] - cs2_r[right] - (cs1_r[ind] - cs1_r[right])*(n-right)
ex_r = base*2 * wid_l
ex = -ex_l - ex_r + b[ind]*wid_l*wid_r*2 + a[left]*wid_r + a[right]*wid_l
return ex,div
# Aiが小さい順に期待値計算をして、終了するかどうか判断。
# A0は絶対に終了すべきなのでskip
order = [j for i,j in order][::-1]
flag = True
while(flag):
flag = False
while(order):
ind = order.pop()
if(ind==0):
continue
if(end[ind]==0):
continue
ex,div = calc_ex(ind)
if(a[ind]*div < ex):
end[ind] = 0
seg_left.update(ind,0)
seg_right.update(ind,n)
left = seg_left.query(0,ind)
right = seg_right.query(ind+1,n+1)
if(left!=0):
order.append(left)
if(right!=n):
order.append(right)
flag = True
if(flag):
for i,val in enumerate(end[:-1]):
if(val==1):
order.append(i)
# 終了すべきポイントがわかったので期待値合計を計算
ans = [0] * (n)
for ind,flag in enumerate(end[:-1]):
if(flag==1):
ans[ind] = (a[ind],1)
else:
ex,div = calc_ex(ind)
ans[ind] = (ex,div)
lcm = 1
for ex,div in ans:
lcm = (lcm*div)//gcd(lcm,div)
ans_num = 0
for ex,div in ans:
ans_num += ex*(lcm//div)
print(ans_num/(lcm*n))
```
| 14,774 |
Provide a correct Python 3 solution for this coding contest problem.
You are playing a game and your goal is to maximize your expected gain. At the beginning of the game, a pawn is put, uniformly at random, at a position p\in\\{1,2,\dots, N\\}. The N positions are arranged on a circle (so that 1 is between N and 2).
The game consists of turns. At each turn you can either end the game, and get A_p dollars (where p is the current position of the pawn), or pay B_p dollar to keep playing. If you decide to keep playing, the pawn is randomly moved to one of the two adjacent positions p-1, p+1 (with the identifications 0 = N and N+1=1).
What is the expected gain of an optimal strategy?
Note: The "expected gain of an optimal strategy" shall be defined as the supremum of the expected gain among all strategies such that the game ends in a finite number of turns.
Constraints
* 2 \le N \le 200,000
* 0 \le A_p \le 10^{12} for any p = 1,\ldots, N
* 0 \le B_p \le 100 for any p = 1, \ldots, N
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 \cdots A_N
B_1 B_2 \cdots B_N
Output
Print a single real number, the expected gain of an optimal strategy. Your answer will be considered correct if its relative or absolute error does not exceed 10^{-10}.
Examples
Input
5
4 2 6 3 5
1 1 1 1 1
Output
4.700000000000
Input
4
100 0 100 0
0 100 0 100
Output
50.000000000000
Input
14
4839 5400 6231 5800 6001 5200 6350 7133 7986 8012 7537 7013 6477 5912
34 54 61 32 52 61 21 43 65 12 45 21 1 4
Output
7047.142857142857
Input
10
470606482521 533212137322 116718867454 746976621474 457112271419 815899162072 641324977314 88281100571 9231169966 455007126951
26 83 30 59 100 88 84 91 54 61
Output
815899161079.400024414062
"Correct Solution:
```
from bisect import bisect_right
def det(p1, p2, p3):
area = (p2[0] - p1[0])*(p3[1] - p1[1]) - (p2[1] - p1[1])*(p3[0] - p1[0])
return area > 0
def convex_hull(pts):
pts = sorted(pts)
n = len(pts)
extsize = 0
extpts = []
for i in range(n):
while extsize > 1:
if det(extpts[-2], extpts[-1], pts[i]):
break
extsize -= 1
extpts.pop()
extpts.append(pts[i])
extsize += 1
t = extsize
for i in range(n-1, -1, -1):
while extsize > t:
if det(extpts[-2], extpts[-1], pts[i]):
break
extsize -= 1
extpts.pop()
extpts.append(pts[i])
extsize += 1
return extpts[:-1]
n = int(input())
aa = [int(x) for x in input().split()]
bb = [int(x) for x in input().split()]
ma = max(aa)
ind = -1
for i in range(n):
if ma == aa[i]:
ind = i
break
a = aa[i:] + aa[:i+1]
b = bb[i:] + bb[:i+1]
c = [0]*(n+1)
for i in range(2, n+1):
c[i] = 2*(c[i-1]+b[i-1])-c[i-2]
pts = []
for i in range(n+1):
pts.append((i, a[i]-c[i]))
f = [-10**15]*(n+1)
ext = []
for i, val in convex_hull(pts):
if val*n < (a[0]-c[0])*(n-i)+(a[n]-c[n])*i:
continue
f[i] = val
ext.append(i)
ext = sorted(ext)
for i in range(n+1):
if f[i] == -10**15:
t = bisect_right(ext, i)
l = ext[t-1]
r = ext[t]
f[i] = f[l] + (i-l)*(f[r]-f[l])/(r-l)
ans = 0
for i in range(1, n+1):
ans += f[i]+c[i]
print(f'{ans/n:.12f}')
```
| 14,775 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are playing a game and your goal is to maximize your expected gain. At the beginning of the game, a pawn is put, uniformly at random, at a position p\in\\{1,2,\dots, N\\}. The N positions are arranged on a circle (so that 1 is between N and 2).
The game consists of turns. At each turn you can either end the game, and get A_p dollars (where p is the current position of the pawn), or pay B_p dollar to keep playing. If you decide to keep playing, the pawn is randomly moved to one of the two adjacent positions p-1, p+1 (with the identifications 0 = N and N+1=1).
What is the expected gain of an optimal strategy?
Note: The "expected gain of an optimal strategy" shall be defined as the supremum of the expected gain among all strategies such that the game ends in a finite number of turns.
Constraints
* 2 \le N \le 200,000
* 0 \le A_p \le 10^{12} for any p = 1,\ldots, N
* 0 \le B_p \le 100 for any p = 1, \ldots, N
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 \cdots A_N
B_1 B_2 \cdots B_N
Output
Print a single real number, the expected gain of an optimal strategy. Your answer will be considered correct if its relative or absolute error does not exceed 10^{-10}.
Examples
Input
5
4 2 6 3 5
1 1 1 1 1
Output
4.700000000000
Input
4
100 0 100 0
0 100 0 100
Output
50.000000000000
Input
14
4839 5400 6231 5800 6001 5200 6350 7133 7986 8012 7537 7013 6477 5912
34 54 61 32 52 61 21 43 65 12 45 21 1 4
Output
7047.142857142857
Input
10
470606482521 533212137322 116718867454 746976621474 457112271419 815899162072 641324977314 88281100571 9231169966 455007126951
26 83 30 59 100 88 84 91 54 61
Output
815899161079.400024414062
Submitted Solution:
```
def solve(n, a_list, b_list):
prev_g_list = [max(a_list)] * n
prev_res = sum(prev_g_list) / n
while True:
print(prev_g_list)
new_g_list = [0.0] * n
for i in range(n):
next_expectation = 0.5 * (prev_g_list[i - 1] + prev_g_list[(i + 1) % n]) - b_list[i]
new_g_list[i] = a_list[i] if a_list[i] >= next_expectation else next_expectation
new_res = sum(new_g_list) / n
if abs(new_res - prev_res) < 1e-10:
return new_res
prev_g_list = new_g_list
prev_res = new_res
if __name__ == "__main__":
n = int(input())
a_list = [int(s) for s in input().split()]
b_list = [int(s) for s in input().split()]
res = solve(n, a_list, b_list)
print(res)
```
No
| 14,776 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are playing a game and your goal is to maximize your expected gain. At the beginning of the game, a pawn is put, uniformly at random, at a position p\in\\{1,2,\dots, N\\}. The N positions are arranged on a circle (so that 1 is between N and 2).
The game consists of turns. At each turn you can either end the game, and get A_p dollars (where p is the current position of the pawn), or pay B_p dollar to keep playing. If you decide to keep playing, the pawn is randomly moved to one of the two adjacent positions p-1, p+1 (with the identifications 0 = N and N+1=1).
What is the expected gain of an optimal strategy?
Note: The "expected gain of an optimal strategy" shall be defined as the supremum of the expected gain among all strategies such that the game ends in a finite number of turns.
Constraints
* 2 \le N \le 200,000
* 0 \le A_p \le 10^{12} for any p = 1,\ldots, N
* 0 \le B_p \le 100 for any p = 1, \ldots, N
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 \cdots A_N
B_1 B_2 \cdots B_N
Output
Print a single real number, the expected gain of an optimal strategy. Your answer will be considered correct if its relative or absolute error does not exceed 10^{-10}.
Examples
Input
5
4 2 6 3 5
1 1 1 1 1
Output
4.700000000000
Input
4
100 0 100 0
0 100 0 100
Output
50.000000000000
Input
14
4839 5400 6231 5800 6001 5200 6350 7133 7986 8012 7537 7013 6477 5912
34 54 61 32 52 61 21 43 65 12 45 21 1 4
Output
7047.142857142857
Input
10
470606482521 533212137322 116718867454 746976621474 457112271419 815899162072 641324977314 88281100571 9231169966 455007126951
26 83 30 59 100 88 84 91 54 61
Output
815899161079.400024414062
Submitted Solution:
```
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
import sys
sys.setrecursionlimit(10**7)
def getMoney(now, money):
if money >= (a[(now+1)%n]+a[(now-1)%n])/2 - b[now]: return money
x = getMoney((now+1)%n, a[(now+1)%n] - b[now])
y = getMoney((now-1)%n, a[(now-1)%n] - b[now])
return (x+y)/2
anss = []
for i in range(n):
ans = getMoney(i,a[i])
anss.append(ans)
ans = sum(anss)/n
print(ans)
```
No
| 14,777 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are playing a game and your goal is to maximize your expected gain. At the beginning of the game, a pawn is put, uniformly at random, at a position p\in\\{1,2,\dots, N\\}. The N positions are arranged on a circle (so that 1 is between N and 2).
The game consists of turns. At each turn you can either end the game, and get A_p dollars (where p is the current position of the pawn), or pay B_p dollar to keep playing. If you decide to keep playing, the pawn is randomly moved to one of the two adjacent positions p-1, p+1 (with the identifications 0 = N and N+1=1).
What is the expected gain of an optimal strategy?
Note: The "expected gain of an optimal strategy" shall be defined as the supremum of the expected gain among all strategies such that the game ends in a finite number of turns.
Constraints
* 2 \le N \le 200,000
* 0 \le A_p \le 10^{12} for any p = 1,\ldots, N
* 0 \le B_p \le 100 for any p = 1, \ldots, N
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 \cdots A_N
B_1 B_2 \cdots B_N
Output
Print a single real number, the expected gain of an optimal strategy. Your answer will be considered correct if its relative or absolute error does not exceed 10^{-10}.
Examples
Input
5
4 2 6 3 5
1 1 1 1 1
Output
4.700000000000
Input
4
100 0 100 0
0 100 0 100
Output
50.000000000000
Input
14
4839 5400 6231 5800 6001 5200 6350 7133 7986 8012 7537 7013 6477 5912
34 54 61 32 52 61 21 43 65 12 45 21 1 4
Output
7047.142857142857
Input
10
470606482521 533212137322 116718867454 746976621474 457112271419 815899162072 641324977314 88281100571 9231169966 455007126951
26 83 30 59 100 88 84 91 54 61
Output
815899161079.400024414062
Submitted Solution:
```
N, = map(int, input().split())
X = list(map(int, input().split()))
B = list(map(int, input().split()))
for _ in range(1000):
for i in range(N):
j, k = i+1, i-1
if i == 0:
k = N-1
if i == N-1:
j = 0
X[i] = max((X[j]+X[k])/2 - B[i], X[i])
print(sum(X)/N)
```
No
| 14,778 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are playing a game and your goal is to maximize your expected gain. At the beginning of the game, a pawn is put, uniformly at random, at a position p\in\\{1,2,\dots, N\\}. The N positions are arranged on a circle (so that 1 is between N and 2).
The game consists of turns. At each turn you can either end the game, and get A_p dollars (where p is the current position of the pawn), or pay B_p dollar to keep playing. If you decide to keep playing, the pawn is randomly moved to one of the two adjacent positions p-1, p+1 (with the identifications 0 = N and N+1=1).
What is the expected gain of an optimal strategy?
Note: The "expected gain of an optimal strategy" shall be defined as the supremum of the expected gain among all strategies such that the game ends in a finite number of turns.
Constraints
* 2 \le N \le 200,000
* 0 \le A_p \le 10^{12} for any p = 1,\ldots, N
* 0 \le B_p \le 100 for any p = 1, \ldots, N
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 \cdots A_N
B_1 B_2 \cdots B_N
Output
Print a single real number, the expected gain of an optimal strategy. Your answer will be considered correct if its relative or absolute error does not exceed 10^{-10}.
Examples
Input
5
4 2 6 3 5
1 1 1 1 1
Output
4.700000000000
Input
4
100 0 100 0
0 100 0 100
Output
50.000000000000
Input
14
4839 5400 6231 5800 6001 5200 6350 7133 7986 8012 7537 7013 6477 5912
34 54 61 32 52 61 21 43 65 12 45 21 1 4
Output
7047.142857142857
Input
10
470606482521 533212137322 116718867454 746976621474 457112271419 815899162072 641324977314 88281100571 9231169966 455007126951
26 83 30 59 100 88 84 91 54 61
Output
815899161079.400024414062
Submitted Solution:
```
input()
input()
input()
print(1.0)
```
No
| 14,779 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a lowercase English letter C that is not `z`. Print the letter that follows C in alphabetical order.
Constraints
* C is a lowercase English letter that is not `z`.
Input
Input is given from Standard Input in the following format:
C
Output
Print the letter that follows C in alphabetical order.
Examples
Input
a
Output
b
Input
y
Output
z
"Correct Solution:
```
word=(input())
print(chr(ord(word)+1))
```
| 14,780 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a lowercase English letter C that is not `z`. Print the letter that follows C in alphabetical order.
Constraints
* C is a lowercase English letter that is not `z`.
Input
Input is given from Standard Input in the following format:
C
Output
Print the letter that follows C in alphabetical order.
Examples
Input
a
Output
b
Input
y
Output
z
"Correct Solution:
```
c = input()
print(chr(ord(c[0]) + 1))
```
| 14,781 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a lowercase English letter C that is not `z`. Print the letter that follows C in alphabetical order.
Constraints
* C is a lowercase English letter that is not `z`.
Input
Input is given from Standard Input in the following format:
C
Output
Print the letter that follows C in alphabetical order.
Examples
Input
a
Output
b
Input
y
Output
z
"Correct Solution:
```
#A
c = input()
print(chr(ord(c)+1))
```
| 14,782 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a lowercase English letter C that is not `z`. Print the letter that follows C in alphabetical order.
Constraints
* C is a lowercase English letter that is not `z`.
Input
Input is given from Standard Input in the following format:
C
Output
Print the letter that follows C in alphabetical order.
Examples
Input
a
Output
b
Input
y
Output
z
"Correct Solution:
```
print(str(chr(ord(input())+1)))
```
| 14,783 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a lowercase English letter C that is not `z`. Print the letter that follows C in alphabetical order.
Constraints
* C is a lowercase English letter that is not `z`.
Input
Input is given from Standard Input in the following format:
C
Output
Print the letter that follows C in alphabetical order.
Examples
Input
a
Output
b
Input
y
Output
z
"Correct Solution:
```
p = input()
print(chr(ord(p)+1))
```
| 14,784 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a lowercase English letter C that is not `z`. Print the letter that follows C in alphabetical order.
Constraints
* C is a lowercase English letter that is not `z`.
Input
Input is given from Standard Input in the following format:
C
Output
Print the letter that follows C in alphabetical order.
Examples
Input
a
Output
b
Input
y
Output
z
"Correct Solution:
```
a = input()
a = chr(ord(a)+1)
print(a)
```
| 14,785 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a lowercase English letter C that is not `z`. Print the letter that follows C in alphabetical order.
Constraints
* C is a lowercase English letter that is not `z`.
Input
Input is given from Standard Input in the following format:
C
Output
Print the letter that follows C in alphabetical order.
Examples
Input
a
Output
b
Input
y
Output
z
"Correct Solution:
```
x = ord(input())
x += 1
print(chr(x))
```
| 14,786 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a lowercase English letter C that is not `z`. Print the letter that follows C in alphabetical order.
Constraints
* C is a lowercase English letter that is not `z`.
Input
Input is given from Standard Input in the following format:
C
Output
Print the letter that follows C in alphabetical order.
Examples
Input
a
Output
b
Input
y
Output
z
"Correct Solution:
```
S=input()
num=ord(S)
print(chr(num+1))
```
| 14,787 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a lowercase English letter C that is not `z`. Print the letter that follows C in alphabetical order.
Constraints
* C is a lowercase English letter that is not `z`.
Input
Input is given from Standard Input in the following format:
C
Output
Print the letter that follows C in alphabetical order.
Examples
Input
a
Output
b
Input
y
Output
z
Submitted Solution:
```
il = input()
print(chr(ord(il)+1))
```
Yes
| 14,788 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a lowercase English letter C that is not `z`. Print the letter that follows C in alphabetical order.
Constraints
* C is a lowercase English letter that is not `z`.
Input
Input is given from Standard Input in the following format:
C
Output
Print the letter that follows C in alphabetical order.
Examples
Input
a
Output
b
Input
y
Output
z
Submitted Solution:
```
A=ord(input())
print(chr(A+1))
```
Yes
| 14,789 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a lowercase English letter C that is not `z`. Print the letter that follows C in alphabetical order.
Constraints
* C is a lowercase English letter that is not `z`.
Input
Input is given from Standard Input in the following format:
C
Output
Print the letter that follows C in alphabetical order.
Examples
Input
a
Output
b
Input
y
Output
z
Submitted Solution:
```
s = input()
s = chr(ord(s) + 1)
print(s)
```
Yes
| 14,790 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a lowercase English letter C that is not `z`. Print the letter that follows C in alphabetical order.
Constraints
* C is a lowercase English letter that is not `z`.
Input
Input is given from Standard Input in the following format:
C
Output
Print the letter that follows C in alphabetical order.
Examples
Input
a
Output
b
Input
y
Output
z
Submitted Solution:
```
a = ord(input())
a += 1
print(chr(a))
```
Yes
| 14,791 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a lowercase English letter C that is not `z`. Print the letter that follows C in alphabetical order.
Constraints
* C is a lowercase English letter that is not `z`.
Input
Input is given from Standard Input in the following format:
C
Output
Print the letter that follows C in alphabetical order.
Examples
Input
a
Output
b
Input
y
Output
z
Submitted Solution:
```
c=input()
l="qwertyuioplkjhgfdsazxcvbnm"
l.sort()
print(l[l.index(c)+1])
```
No
| 14,792 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a lowercase English letter C that is not `z`. Print the letter that follows C in alphabetical order.
Constraints
* C is a lowercase English letter that is not `z`.
Input
Input is given from Standard Input in the following format:
C
Output
Print the letter that follows C in alphabetical order.
Examples
Input
a
Output
b
Input
y
Output
z
Submitted Solution:
```
A = str(input(''))
if A = 'a':
print('b')
elif A = 'b':
print('c')
elif A = 'c':
print('d')
elif A = 'd':
print('e')
elif A = 'e':
print('f')
elif A = 'f':
print('g')
elif A = 'g':
print('h')
elif A = 'h':
print('i')
elif A = 'i':
print('j')
elif A = 'j':
print('k')
elif A = 'k':
print('l')
elif A = 'l':
print('m')
elif A = 'm':
print('n')
elif A = 'n':
print('o')
elif A = 'o':
print('p')
elif A = 'p':
print('q')
elif A = 'q':
print('r')
elif A = 'r':
print('s')
elif A = 's':
print('t')
elif A = 't':
print('u')
elif A = 'u':
print('v')
elif A = 'v':
print('w')
elif A = 'w':
print('x')
elif A = 'x':
print('y')
else:
print('z')
```
No
| 14,793 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a lowercase English letter C that is not `z`. Print the letter that follows C in alphabetical order.
Constraints
* C is a lowercase English letter that is not `z`.
Input
Input is given from Standard Input in the following format:
C
Output
Print the letter that follows C in alphabetical order.
Examples
Input
a
Output
b
Input
y
Output
z
Submitted Solution:
```
s = input() #alphabet hitotsu sakino moji
print(chr(ord(s) + 1)
```
No
| 14,794 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a lowercase English letter C that is not `z`. Print the letter that follows C in alphabetical order.
Constraints
* C is a lowercase English letter that is not `z`.
Input
Input is given from Standard Input in the following format:
C
Output
Print the letter that follows C in alphabetical order.
Examples
Input
a
Output
b
Input
y
Output
z
Submitted Solution:
```
n,m = map(int,input().split())
PS = [list(input().split()) for i in range(m)]
AC = []
WA = 0
for i in range(m):
if PS[i][1] == "AC":
p = PS[i][0]
if p not in AC:
WA += PS[:i+1].count([p,"WA"])
AC.append(p)
print(len(AC),WA)
```
No
| 14,795 |
Provide a correct Python 3 solution for this coding contest problem.
Given are two strings s and t consisting of lowercase English letters. Determine if there exists an integer i satisfying the following condition, and find the minimum such i if it exists.
* Let s' be the concatenation of 10^{100} copies of s. t is a subsequence of the string {s'}_1{s'}_2\ldots{s'}_i (the first i characters in s').
Constraints
* 1 \leq |s| \leq 10^5
* 1 \leq |t| \leq 10^5
* s and t consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
t
Output
If there exists an integer i satisfying the following condition, print the minimum such i; otherwise, print `-1`.
Examples
Input
contest
son
Output
10
Input
contest
programming
Output
-1
Input
contest
sentence
Output
33
"Correct Solution:
```
from string import ascii_lowercase
from bisect import bisect_right
s = input()
t = input()
p = {c: [] for c in s}
for x, c in enumerate(s):
p[c].append(x)
z = 0
l = -1
for c in t:
if c not in p:
print(-1)
break
x = bisect_right(p[c], l)
if x == len(p[c]):
x = 0
z += 1
l = p[c][x]
else:
print(z * len(s) + l + 1)
```
| 14,796 |
Provide a correct Python 3 solution for this coding contest problem.
Given are two strings s and t consisting of lowercase English letters. Determine if there exists an integer i satisfying the following condition, and find the minimum such i if it exists.
* Let s' be the concatenation of 10^{100} copies of s. t is a subsequence of the string {s'}_1{s'}_2\ldots{s'}_i (the first i characters in s').
Constraints
* 1 \leq |s| \leq 10^5
* 1 \leq |t| \leq 10^5
* s and t consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
t
Output
If there exists an integer i satisfying the following condition, print the minimum such i; otherwise, print `-1`.
Examples
Input
contest
son
Output
10
Input
contest
programming
Output
-1
Input
contest
sentence
Output
33
"Correct Solution:
```
s=input()
t=input()
ans1=0
ans2=0
m=len(s)
n=len(t)
s=s+s
for i in range(n):
a=s.find(t[i],ans2)
if a==-1:
print(-1)
exit()
if a>=m:
ans1+=1
ans2=a%m+1
print((ans1*m)+ans2)
```
| 14,797 |
Provide a correct Python 3 solution for this coding contest problem.
Given are two strings s and t consisting of lowercase English letters. Determine if there exists an integer i satisfying the following condition, and find the minimum such i if it exists.
* Let s' be the concatenation of 10^{100} copies of s. t is a subsequence of the string {s'}_1{s'}_2\ldots{s'}_i (the first i characters in s').
Constraints
* 1 \leq |s| \leq 10^5
* 1 \leq |t| \leq 10^5
* s and t consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
t
Output
If there exists an integer i satisfying the following condition, print the minimum such i; otherwise, print `-1`.
Examples
Input
contest
son
Output
10
Input
contest
programming
Output
-1
Input
contest
sentence
Output
33
"Correct Solution:
```
import bisect
s = list(input())
t = list(input())
if len(set(t)-set(s)) > 0:
print(-1)
exit()
c = set(s)
dic = {}
for char in c:
dic[char] = []
for i in range(len(s)):
dic[s[i]] += [i]
last = -1
r = 0
for char in t:
tmp = last
idx = bisect.bisect_right(dic[char], last)
if idx < len(dic[char]):
last = dic[char][idx]
if tmp == last:
r += 1
last = dic[char][0]
print(len(s)*r + last + 1)
```
| 14,798 |
Provide a correct Python 3 solution for this coding contest problem.
Given are two strings s and t consisting of lowercase English letters. Determine if there exists an integer i satisfying the following condition, and find the minimum such i if it exists.
* Let s' be the concatenation of 10^{100} copies of s. t is a subsequence of the string {s'}_1{s'}_2\ldots{s'}_i (the first i characters in s').
Constraints
* 1 \leq |s| \leq 10^5
* 1 \leq |t| \leq 10^5
* s and t consists of lowercase English letters.
Input
Input is given from Standard Input in the following format:
s
t
Output
If there exists an integer i satisfying the following condition, print the minimum such i; otherwise, print `-1`.
Examples
Input
contest
son
Output
10
Input
contest
programming
Output
-1
Input
contest
sentence
Output
33
"Correct Solution:
```
s = input()
t = input()
temp = s[:]
cnt = 0
strmax = len(t)
ans = 0
for i in t:
if s.find(i)==-1:
print("-1")
exit(0)
while cnt<strmax:
num = temp.find(t[cnt])
if num != -1:
ans+=num+1
temp = temp[num+1:]
cnt+=1
else:
ans+=len(temp)
temp = s[:]
print(ans)
```
| 14,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.