text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Once little Vasya read an article in a magazine on how to make beautiful handmade garland from colored paper. Vasya immediately went to the store and bought n colored sheets of paper, the area of each sheet is 1 square meter.
The garland must consist of exactly m pieces of colored paper of arbitrary area, each piece should be of a certain color. To make the garland, Vasya can arbitrarily cut his existing colored sheets into pieces. Vasya is not obliged to use all the sheets to make the garland.
Vasya wants the garland to be as attractive as possible, so he wants to maximize the total area of ββm pieces of paper in the garland. Calculate what the maximum total area of ββthe pieces of paper in the garland Vasya can get.
Input
The first line contains a non-empty sequence of n (1 β€ n β€ 1000) small English letters ("a"..."z"). Each letter means that Vasya has a sheet of paper of the corresponding color.
The second line contains a non-empty sequence of m (1 β€ m β€ 1000) small English letters that correspond to the colors of the pieces of paper in the garland that Vasya wants to make.
Output
Print an integer that is the maximum possible total area of the pieces of paper in the garland Vasya wants to get or -1, if it is impossible to make the garland from the sheets he's got. It is guaranteed that the answer is always an integer.
Examples
Input
aaabbac
aabbccac
Output
6
Input
a
z
Output
-1
Note
In the first test sample Vasya can make an garland of area 6: he can use both sheets of color b, three (but not four) sheets of color a and cut a single sheet of color c in three, for example, equal pieces. Vasya can use the resulting pieces to make a garland of area 6.
In the second test sample Vasya cannot make a garland at all β he doesn't have a sheet of color z.
Submitted Solution:
```
def main():
import sys
material = input()
scheme = input()
flag = True
for i in range(len(scheme)):
if not scheme[i] in material:
print(-1)
flag = False
if flag:
counter = 0
SIZE = len(scheme) - 1
saver = []
result = 0
while counter <= SIZE:
saver += [scheme[counter]]
if (scheme.count(scheme[counter]) <=
material.count(scheme[counter])):
result += scheme.count(scheme[counter])
else:
result += material.count(scheme[counter])
while scheme[counter] in saver:
if counter < SIZE:
counter += 1
else:
print(result)
sys.exit()
print(result)
main()
```
No
| 108,200 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 β€ n β€ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 β€ ai β€ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either Β« / Β» (slash), Β« \ Β» (backslash), Β« Β» (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">β/β</span><span class="tex-span">\</span><span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Input
3
1 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Tags: implementation
Correct Solution:
```
import sys
from math import *
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
n = mint()
y = 0
x = 0
a = []
t = 0
mx = dict()
my = 10**9
for i in mints():
for j in range(i):
if t == 0:
a.append((x,y,'/'))
mx[y] = max(mx.get(y, -1), x)
my = min(my, y)
y -= 1
else:
y += 1
a.append((x,y,'\\'))
mx[y] = max(mx.get(y, -1), x)
my = min(my, y)
x += 1
t ^= 1
i = 0
b = []
while (my+i) in mx:
b.append([' ']*(mx[my+i]+1))
i += 1
for i in a:
b[i[1]-my][i[0]] = i[2]
for i in b:
print(*(i+[' ']*(x-len(i))),sep='')
```
| 108,201 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 β€ n β€ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 β€ ai β€ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either Β« / Β» (slash), Β« \ Β» (backslash), Β« Β» (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">β/β</span><span class="tex-span">\</span><span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Input
3
1 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Tags: implementation
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
x = [0] * (n + 1)
y = [0] * (n + 1)
for i in range(1, n + 1):
x[i] = x[i - 1] + a[i - 1]
y[i] = y[i - 1]
if i % 2 == 0:
y[i] -= a[i - 1]
else:
y[i] += a[i - 1]
m = min(y)
if m < 0:
for i in range(n + 1):
y[i] -= m
w = max(x)
h = max(y)
d = [[" "] * w for i in range(h)]
for i in range(n):
if y[i] < y[i + 1]:
for j in range(a[i]):
d[y[i] + j][x[i] + j] = "/"
else:
for j in range(a[i]):
d[y[i] - j - 1][x[i] + j] = "\\"
print("\n".join("".join(d[i]) for i in reversed(range(h))))
```
| 108,202 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 β€ n β€ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 β€ ai β€ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either Β« / Β» (slash), Β« \ Β» (backslash), Β« Β» (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">β/β</span><span class="tex-span">\</span><span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Input
3
1 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Tags: implementation
Correct Solution:
```
n = input()
a = list(map(int,input().split()))
l = sum(a)
h = maxh = minh = 1000
table = [[" "]*l for i in range(2001)]
k = 0
sign = 1
for i in a:
if sign == 1:
for j in range(i):
table[h+j][k+j] = "/"
maxh = max(maxh,h+(i-1))
h += i-1
else:
for j in range(i):
table[h-j][k+j] = "\\"
minh = min(minh,h-(i-1))
h -= i-1
k += i
sign *= -1
for i in range(maxh,minh-1,-1):
print (''.join(table[i]))
```
| 108,203 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 β€ n β€ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 β€ ai β€ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either Β« / Β» (slash), Β« \ Β» (backslash), Β« Β» (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">β/β</span><span class="tex-span">\</span><span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Input
3
1 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Tags: implementation
Correct Solution:
```
n=int(input())
l=list(map(int, input().split()))
mx=0
mn=0
s=0
sm=0
a=[0]*(n+1)
for i in range(n):
sm+=l[i]
if i%2==0:
s+=l[i]
else:
s-=l[i]
mx=max(mx,s)
mn=min(mn,s)
a[i+1]=s
for i in range(n+1):
a[i]-=mn
mat=[]
for i in range(mx-mn):
ll=[" "]*sm
mat.append(ll)
j=a[0]
k=0
a.append(5)
# print(a,mx,mn,sm)
f=0
for i in range(n):
for g in range(l[i]):
# print(i,j,k)
if i%2==0:
if f==1:
j+=1
f=0
mat[j][k]="/"
k+=1
j+=1
if j>=a[i+1]:
j-=1
else:
# print(j,k)
mat[j][k]='\\'
k+=1
j-=1
f=1
# if j<=a[i+1]:
# j+=1
i=len(mat)-1
while(i>=0):
for j in mat[i]:
print(j,end="")
print()
i-=1
# for i in l:
# print(i)
# print(1)
```
| 108,204 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 β€ n β€ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 β€ ai β€ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either Β« / Β» (slash), Β« \ Β» (backslash), Β« Β» (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">β/β</span><span class="tex-span">\</span><span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Input
3
1 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Tags: implementation
Correct Solution:
```
N = int(2e3+3)
n = int(input())
a = list(map(int, input().split()))
maxi, mini = N//2, N//2
res = [[' '] * N for i in range(N)]
x, y = N//2, 0
for i in range(n):
if i % 2 == 0:
for j in range(a[i]):
res[x][y] = '/'
x -= 1
y += 1
x += 1
else:
for j in range(a[i]):
res[x][y] = '\\'
x += 1
y += 1
x -= 1
maxi = max(maxi, x)
mini = min(mini, x)
for i in range(mini, maxi+1):
print(''.join(res[i][:y]))
```
| 108,205 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 β€ n β€ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 β€ ai β€ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either Β« / Β» (slash), Β« \ Β» (backslash), Β« Β» (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">β/β</span><span class="tex-span">\</span><span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Input
3
1 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Tags: implementation
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
x = [0] * (n + 1)
y = [0] * (n + 1)
for i in range(1, n + 1):
x[i] = x[i - 1] + a[i - 1]
y[i] = y[i - 1]
if i % 2 == 0:
y[i] -= a[i - 1]
else:
y[i] += a[i - 1]
# print(x)
# print(y)
m = min(y)
if m < 0:
for i in range(n + 1):
y[i] -= m
# print(y)
w = max(x)
h = max(y)
# print(h, w)
d = [[" "] * w for i in range(h)]
for i in range(n):
if y[i] < y[i + 1]:
for j in range(a[i]):
# print(y[i] + j, x[i] + j, "/")
d[y[i] + j][x[i] + j] = "/"
else:
for j in range(a[i]):
# print(y[i] - j - 1, x[i] + j, "\\")
d[y[i] - j - 1][x[i] + j] = "\\"
print("\n".join("".join(d[i]) for i in reversed(range(h))))
```
| 108,206 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 β€ n β€ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 β€ ai β€ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either Β« / Β» (slash), Β« \ Β» (backslash), Β« Β» (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">β/β</span><span class="tex-span">\</span><span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Input
3
1 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Tags: implementation
Correct Solution:
```
n, a = int(input()), list(map(int, input().split()))
if n & 1: a.append(0)
x, t = 0, [[' '] * sum(a) for i in range(2001)]
y = u = v = 1000
for i in range(0, n, 2):
for j in range(a[i]):
t[y][x] = '/'
x += 1
y += 1
v = max(v, y)
for j in range(a[i + 1]):
y -= 1
t[y][x] = '\\'
x += 1
u = min(u, y)
for i in range(v - 1, u - 1, -1): print(''.join(t[i]))
# Made By Mostafa_Khaled
```
| 108,207 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 β€ n β€ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 β€ ai β€ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either Β« / Β» (slash), Β« \ Β» (backslash), Β« Β» (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">β/β</span><span class="tex-span">\</span><span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Input
3
1 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Tags: implementation
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
graph = [[' '] * 1000 for _ in range(2001)]
x, y = 0, 1000
for i in range(n):
for j in range(a[i]):
if i % 2:
graph[y][x] = '\\'
if j != a[i] - 1:
y += 1
else:
graph[y][x] = '/'
if j != a[i] - 1:
y -= 1
x += 1
for i in range(2000, -1, -1):
graph[i] = ''.join(graph[i][:x])
if not len(set(graph[i]) & set(['/', '\\'])):
graph.pop(i)
print('\n'.join(graph))
```
| 108,208 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 β€ n β€ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 β€ ai β€ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either Β« / Β» (slash), Β« \ Β» (backslash), Β« Β» (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">β/β</span><span class="tex-span">\</span><span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Input
3
1 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Submitted Solution:
```
import operator
n = int(input())
a = tuple(map(int, str.split(input())))
p = [(0, 0)]
for i, x in enumerate(a):
p.append((p[-1][0] + x, p[-1][1] + (-1) ** i * x))
ymax = max(p, key=operator.itemgetter(1))[1]
ymin = min(p, key=operator.itemgetter(1))[1]
columns = []
for i in range(n):
x1, y1 = p[i]
x2, y2 = p[i + 1]
while x1 != x2:
if y1 < y2:
columns.append(" " * (ymax - y1 - 1) + "/" + " " * (y1 - ymin))
y1 += 1
else:
columns.append(" " * (ymax - y1) + "\\" + " " * (y1 - ymin - 1))
y1 -= 1
x1 += 1
print(str.join("\n", map(lambda t: str.join("", t), zip(*columns))))
```
Yes
| 108,209 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 β€ n β€ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 β€ ai β€ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either Β« / Β» (slash), Β« \ Β» (backslash), Β« Β» (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">β/β</span><span class="tex-span">\</span><span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Input
3
1 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Submitted Solution:
```
import math,sys
#from itertools import permutations, combinations;import heapq,random;
from collections import defaultdict,deque
import bisect as bi
def yes():print('YES')
def no():print('NO')
def I():return (int(sys.stdin.readline()))
def In():return(map(int,sys.stdin.readline().split()))
def Sn():return sys.stdin.readline().strip()
#sys.setrecursionlimit(1500)
def dict(a):
d={}
for x in a:
if d.get(x,-1)!=-1:
d[x]+=1
else:
d[x]=1
return d
def find_gt(a, x):
'Find leftmost value greater than x'
i = bi.bisect_left(a, x)
if i != len(a):
return i
else:
return -1
def main():
try:
n=I()
l=list(In())
su,mx,t=0,0,0
for i in range(n):
su+=l[i]
if i&1:
t-=l[i]
else:
t+=l[i]
mx=max(l[i],mx,abs(t))
ans=[[' ' for i in range(su)] for j in range(2*(mx+1))]
st_y=mx
st_x=0
for i in range(n):
for j in range(l[i]):
if i%2==0:
ans[st_y][st_x]='/'
if j!=l[i]-1:
st_y-=1
st_x+=1
else:
ans[st_y][st_x]="\\"
if j!=l[i]-1:
st_y+=1
st_x+=1
for x in ans:
if x.count('\\')+x.count('/'):
print(''.join(x))
except:
pass
M = 998244353
P = 1000000007
if __name__ == '__main__':
# for _ in range(I()):main()
for _ in range(1):main()
# ******************* All The Best ******************* #
```
Yes
| 108,210 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 β€ n β€ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 β€ ai β€ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either Β« / Β» (slash), Β« \ Β» (backslash), Β« Β» (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">β/β</span><span class="tex-span">\</span><span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Input
3
1 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Submitted Solution:
```
n = int(input())
a = [int(i) for i in input().split()]
miny = 0
maxy = 0
s = 0
for i in range(n):
if i % 2 == 0:
s += a[i]
else:
s -= a[i]
maxy = max(s, maxy)
miny = min(s, miny)
dif = maxy - miny
size = sum(a)
res = [[" "] * size for i in range(dif)]
cur = [maxy, 0]
for i in range(n):
if i % 2 == 0:
cur[0] -= 1
else:
cur[0] += 1
for j in range(a[i]):
if i % 2 == 0:
res[cur[0]][cur[1]] = "/"
cur[0] -= 1
else:
res[cur[0]][cur[1]] = "\\"
cur[0] += 1
cur[1] += 1
for i in res:
print("".join(i))
```
Yes
| 108,211 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 β€ n β€ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 β€ ai β€ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either Β« / Β» (slash), Β« \ Β» (backslash), Β« Β» (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">β/β</span><span class="tex-span">\</span><span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Input
3
1 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Submitted Solution:
```
import operator
n = int(input())
points = list(map(int, input().split()))
def praf(g):
for i in g[1:]:
print(''.join(i))
def calc(n):
global points
a = b = 0
step = 1
for i in range(n):
a += points[i]
b += points[i] * step
step = -step
return (a, b)
seq = [(0, 0)]
for i in range(len(points)):
seq.append(calc(i+1))
seq = sorted(seq, key=lambda x: x[0])
seq = {i: seq[i] for i in range(len(seq))}
#print(seq)
for i in range(len(seq)):
r = 0
if i != len(seq)-1:
if seq[i][1] > seq[i+1][1]:
r = -1
else:
r = 1
seq[i] = seq[i] + tuple([r])
seqy = sorted(seq.items(), key=lambda x: x[1][1], reverse=True)
pts = {x[0]: x[2] for x in seq.values()}
pts[seq[len(seq)-1][0]] = 1
#print('---seq---')
#print(seq)
#print('----seqy---')
#print(seqy)
#print('---pts---')
#print(pts)
graph = [[' '] * seq[len(seq)-1][0] for x in range(seqy[0][1][1]-seqy[-1][1][1]+1)]
y = seqy[0][1][1]
way = pts[0]
for i in range(len(graph[0])):
if i in pts.keys():
if pts[i] != way:
if way == 1:
y+=1
else:
y-=1
way = pts[i]
graph[y][i] = '/' if way == 1 else '\\'
y -= way
# praf(graph)
#print('----------------graph-----------------------------------------------------------')
praf(graph)
#praf(graph)
```
Yes
| 108,212 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 β€ n β€ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 β€ ai β€ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either Β« / Β» (slash), Β« \ Β» (backslash), Β« Β» (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">β/β</span><span class="tex-span">\</span><span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Input
3
1 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Submitted Solution:
```
n = int(input())
cardio = list(map(int, input().split()))
strings = [' ' * (sum(cardio) + 1) for i in range(2500)]
xc = 0
yc = 1250
for i in range(n):
for j in range(cardio[i]):
xc += 1
if i % 2 == 0:
yc -= 1
strings[yc] = strings[yc][:xc] + '/' + strings[yc][xc + 1:]
else:
yc += 1
strings[yc] = strings[yc][:xc] + chr(92) + strings[yc][xc + 1:]
if i % 2 == 0:
yc -= 1
else:
yc += 1
i = 0
while max(strings[i]) == ' ':
i += 1
for j in range(i, i + max(cardio)):
print(strings[j][1:])
```
No
| 108,213 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 β€ n β€ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 β€ ai β€ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either Β« / Β» (slash), Β« \ Β» (backslash), Β« Β» (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">β/β</span><span class="tex-span">\</span><span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Input
3
1 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Submitted Solution:
```
import math,sys
#from itertools import permutations, combinations;import heapq,random;
from collections import defaultdict,deque
import bisect as bi
def yes():print('YES')
def no():print('NO')
def I():return (int(sys.stdin.readline()))
def In():return(map(int,sys.stdin.readline().split()))
def Sn():return sys.stdin.readline().strip()
#sys.setrecursionlimit(1500)
def dict(a):
d={}
for x in a:
if d.get(x,-1)!=-1:
d[x]+=1
else:
d[x]=1
return d
def find_gt(a, x):
'Find leftmost value greater than x'
i = bi.bisect_left(a, x)
if i != len(a):
return i
else:
return -1
def main():
try:
n=I()
l=list(In())
su,mx,t=0,0,0
for i in range(n):
su+=l[i]
if i&1:
t-=l[i]
else:
t+=l[i]
mx=max(l[i],mx,abs(t))
ans=[[' ' for i in range(su)] for j in range(2*(mx+1))]
st_y=mx
st_x=0
for i in range(n):
for j in range(l[i]):
if i%2==0:
ans[st_y][st_x]='/'
if j!=l[i]-1:
st_y-=1
st_x+=1
else:
ans[st_y][st_x]="\\"
if j!=l[i]-1:
st_y+=1
st_x+=1
for x in ans:
if x.count('\\')+x.count('/'):
print(*x)
except:
pass
M = 998244353
P = 1000000007
if __name__ == '__main__':
# for _ in range(I()):main()
for _ in range(1):main()
# ******************* All The Best ******************* #
```
No
| 108,214 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 β€ n β€ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 β€ ai β€ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either Β« / Β» (slash), Β« \ Β» (backslash), Β« Β» (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">β/β</span><span class="tex-span">\</span><span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Input
3
1 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Submitted Solution:
```
n = input()
a = list(map(int,input().split()))
l = sum(a)
h = maxh = minh = 1000
table = [[" "]*l for i in range(2001)]
k = 0
sign = 1
for i in a:
if sign == 1:
for j in range(i):
table[h+j][k+j] = "/"
maxh = max(maxh,h+(i-1))
h += i-1
else:
for j in range(i):
table[h-j][k+j] = "\\"
minh = min(minh,h-(i-1))
h -= i-1
k += i
sign *= -1
for i in range(maxh,minh-1,-1):
print (" ".join(table[i]))
```
No
| 108,215 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In this problem, your task is to use ASCII graphics to paint a cardiogram.
A cardiogram is a polyline with the following corners:
<image>
That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.
Your task is to paint a cardiogram by given sequence ai.
Input
The first line contains integer n (2 β€ n β€ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 β€ ai β€ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.
Output
Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print <image> characters. Each character must equal either Β« / Β» (slash), Β« \ Β» (backslash), Β« Β» (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.
Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.
Examples
Input
5
3 1 2 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">β/β</span><span class="tex-span">\</span><span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">β/β</span> <span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Input
3
1 5 1
Output
<span class="tex-span">β/β</span><span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span>
<span class="tex-span">\</span><span class="tex-span">β/β</span>
Note
Due to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.
http://assets.codeforces.com/rounds/435/1.txt
http://assets.codeforces.com/rounds/435/2.txt
Submitted Solution:
```
n = int(input())
lis = list(map(int,input().split()))
ma=r=0
mi=a=0
for i in range(n):
if i%2==0:
a+=lis[i]
else:
a-=lis[i]
ma=max(ma,a)
mi=min(mi,a)
r+=lis[i]
mat=[[' ']*(r) for i in range(ma+abs(mi)+2)]
ro=ma
col=0
for i in range(n):
if i%2==0:
ro-=1
for k in range(lis[i]):
mat[ro][col]='/'
ro-=1
col+=1
else:
ro+=1
for k in range(lis[i]):
mat[ro][col]='\\'
ro+=1
col+=1
for i in mat[:]:
print(*i)
```
No
| 108,216 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplΠ΅ type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity sign, not necessarily symmetrical.
The top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification.
Help Vasya β compose a crossword of the described type using the given six words. It is allowed to use the words in any order.
Input
Six lines contain the given words. Every word consists of no more than 30 and no less than 3 uppercase Latin letters.
Output
If it is impossible to solve the problem, print Impossible. Otherwise, print the sought crossword. All the empty squares should be marked as dots.
If there can be several solutions to that problem, print the lexicographically minimum one. I.e. the solution where the first line is less than the first line of other solutions should be printed. If the two lines are equal, compare the second lines and so on. The lexicographical comparison of lines is realized by the < operator in the modern programming languages.
Examples
Input
NOD
BAA
YARD
AIRWAY
NEWTON
BURN
Output
BAA...
U.I...
R.R...
NEWTON
..A..O
..YARD
Input
AAA
AAA
AAAAA
AAA
AAA
AAAAA
Output
AAA..
A.A..
AAAAA
..A.A
..AAA
Input
PTC
JYNYFDSGI
ZGPPC
IXEJNDOP
JJFS
SSXXQOFGJUZ
Output
JJFS....
Y..S....
N..X....
Y..X....
F..Q....
D..O....
S..F....
G..G....
IXEJNDOP
...U...T
...ZGPPC
Tags: implementation
Correct Solution:
```
ar = [input() for i in range(6)]
ar.sort()
ans = []
for i in range(6):
for j in range(6):
if(i == j): continue
if(ar[i][0] != ar[j][0]): continue
for k in range(6):
if(i==k or j==k): continue
if(len(ar[k]) < 5): continue
if(len(ar[j])+2 > len(ar[k])): continue
if(ar[i][-1] != ar[k][0]): continue
for l in range(6):
if(i==l or j==l or k==l): continue
if(len(ar[l]) < 5): continue
if(len(ar[i])+2 > len(ar[l])): continue
if(ar[j][-1] != ar[l][0]): continue
if(ar[k][len(ar[j])-1] != ar[l][len(ar[i])-1]): continue
for m in range(6):
if(i==m or j==m or k==m or l==m): continue
if((len(ar[j])+len(ar[m]) - 1) != len(ar[k])): continue
if(ar[l][-1] != ar[m][0]): continue
for n in range(6):
if(i==n or j==n or k==n or l==n or m==n): continue
if((len(ar[i])+len(ar[n]) - 1) != len(ar[l])): continue
if(ar[k][-1] != ar[n][0]): continue
if(ar[m][-1] != ar[n][-1]): continue
tmp = []
s = ar[i] + ('.' * (len(ar[n])-1))
tmp.append(s)
for a in range(1, len(ar[j])-1):
s = ar[j][a] + ('.' * (len(ar[i])-2)) + ar[k][a] + ('.' * (len(ar[n])-1))
tmp.append(s)
s = ar[l]
tmp.append(s)
for a in range(1, len(ar[m])-1):
s = ('.' * (len(ar[i])-1)) + ar[k][len(ar[j])-1 + a] + ('.' * (len(ar[n])-2)) + ar[m][a]
tmp.append(s)
s = ('.' * (len(ar[i])-1)) + ar[n]
tmp.append(s)
ans.append(tmp)
if(len(ans) == 0):
print("Impossible")
else:
tmp = min(ans)
for t in tmp:
print(t)
```
| 108,217 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplΠ΅ type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity sign, not necessarily symmetrical.
The top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification.
Help Vasya β compose a crossword of the described type using the given six words. It is allowed to use the words in any order.
Input
Six lines contain the given words. Every word consists of no more than 30 and no less than 3 uppercase Latin letters.
Output
If it is impossible to solve the problem, print Impossible. Otherwise, print the sought crossword. All the empty squares should be marked as dots.
If there can be several solutions to that problem, print the lexicographically minimum one. I.e. the solution where the first line is less than the first line of other solutions should be printed. If the two lines are equal, compare the second lines and so on. The lexicographical comparison of lines is realized by the < operator in the modern programming languages.
Examples
Input
NOD
BAA
YARD
AIRWAY
NEWTON
BURN
Output
BAA...
U.I...
R.R...
NEWTON
..A..O
..YARD
Input
AAA
AAA
AAAAA
AAA
AAA
AAAAA
Output
AAA..
A.A..
AAAAA
..A.A
..AAA
Input
PTC
JYNYFDSGI
ZGPPC
IXEJNDOP
JJFS
SSXXQOFGJUZ
Output
JJFS....
Y..S....
N..X....
Y..X....
F..Q....
D..O....
S..F....
G..G....
IXEJNDOP
...U...T
...ZGPPC
Tags: implementation
Correct Solution:
```
from itertools import permutations
v = []
for p in permutations(input() for i in range(6)):
if len(p[1]) != len(p[0]) + len(p[2]) - 1 or len(p[4]) != len(p[3]) + len(p[5]) - 1:
continue
elif p[0][0] != p[3][0] or p[0][-1] != p[4][0]:
continue
elif p[1][0] != p[3][-1] or p[1][len(p[0]) - 1] != p[4][len(p[3]) - 1] or p[1][-1] != p[5][0]:
continue
elif p[2][0] != p[4][-1] or p[2][-1] != p[5][-1]:
continue
else:
x, y, c = '.' * (len(p[1]) - len(p[0])), '.' * \
(len(p[1]) - len(p[2])), []
c.append(p[0] + x)
for i in range(1, len(p[3]) - 1):
c.append(p[3][i] + '.' * (len(p[0]) - 2) + p[4][i] + x)
c.append(p[1])
for i in range(1, len(p[5]) - 1):
c.append(y + p[4][len(p[3]) + i - 1] +
'.' * (len(p[2]) - 2) + p[5][i])
c.append(y + p[2])
v.append(c)
print('\n'.join(sorted(v)[0]) if v else 'Impossible')
```
| 108,218 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplΠ΅ type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity sign, not necessarily symmetrical.
The top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification.
Help Vasya β compose a crossword of the described type using the given six words. It is allowed to use the words in any order.
Input
Six lines contain the given words. Every word consists of no more than 30 and no less than 3 uppercase Latin letters.
Output
If it is impossible to solve the problem, print Impossible. Otherwise, print the sought crossword. All the empty squares should be marked as dots.
If there can be several solutions to that problem, print the lexicographically minimum one. I.e. the solution where the first line is less than the first line of other solutions should be printed. If the two lines are equal, compare the second lines and so on. The lexicographical comparison of lines is realized by the < operator in the modern programming languages.
Examples
Input
NOD
BAA
YARD
AIRWAY
NEWTON
BURN
Output
BAA...
U.I...
R.R...
NEWTON
..A..O
..YARD
Input
AAA
AAA
AAAAA
AAA
AAA
AAAAA
Output
AAA..
A.A..
AAAAA
..A.A
..AAA
Input
PTC
JYNYFDSGI
ZGPPC
IXEJNDOP
JJFS
SSXXQOFGJUZ
Output
JJFS....
Y..S....
N..X....
Y..X....
F..Q....
D..O....
S..F....
G..G....
IXEJNDOP
...U...T
...ZGPPC
Tags: implementation
Correct Solution:
```
from itertools import permutations
v = []
for p in permutations(input() for i in range(6)):
if len(p[1]) != len(p[0]) + len(p[2]) - 1 or len(p[4]) != len(p[3]) + len(p[5]) - 1:
continue
elif p[0][0] != p[3][0] or p[0][-1] != p[4][0]:
continue
elif p[1][0] != p[3][-1] or p[1][len(p[0]) - 1] != p[4][len(p[3]) - 1] or p[1][-1] != p[5][0]:
continue
elif p[2][0] != p[4][-1] or p[2][-1] != p[5][-1]:
continue
else:
x, y, c = '.' * (len(p[1]) - len(p[0])), '.' * (len(p[1]) - len(p[2])), []
c.append(p[0] + x)
for i in range(1, len(p[3]) - 1):
c.append(p[3][i] + '.' * (len(p[0]) - 2) + p[4][i] + x)
c.append(p[1])
for i in range(1, len(p[5]) - 1):
c.append(y + p[4][len(p[3]) + i - 1] + '.' * (len(p[2]) - 2) + p[5][i])
c.append(y + p[2])
v.append(c)
print('\n'.join(sorted(v)[0]) if v else 'Impossible')
```
| 108,219 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplΠ΅ type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity sign, not necessarily symmetrical.
The top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification.
Help Vasya β compose a crossword of the described type using the given six words. It is allowed to use the words in any order.
Input
Six lines contain the given words. Every word consists of no more than 30 and no less than 3 uppercase Latin letters.
Output
If it is impossible to solve the problem, print Impossible. Otherwise, print the sought crossword. All the empty squares should be marked as dots.
If there can be several solutions to that problem, print the lexicographically minimum one. I.e. the solution where the first line is less than the first line of other solutions should be printed. If the two lines are equal, compare the second lines and so on. The lexicographical comparison of lines is realized by the < operator in the modern programming languages.
Examples
Input
NOD
BAA
YARD
AIRWAY
NEWTON
BURN
Output
BAA...
U.I...
R.R...
NEWTON
..A..O
..YARD
Input
AAA
AAA
AAAAA
AAA
AAA
AAAAA
Output
AAA..
A.A..
AAAAA
..A.A
..AAA
Input
PTC
JYNYFDSGI
ZGPPC
IXEJNDOP
JJFS
SSXXQOFGJUZ
Output
JJFS....
Y..S....
N..X....
Y..X....
F..Q....
D..O....
S..F....
G..G....
IXEJNDOP
...U...T
...ZGPPC
Tags: implementation
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
from itertools import permutations
def main():
s = [input().strip() for _ in range(6)]
ans = ['a'*30 for _ in range(30)]
dx = [0,1,0,-1,0,-1]
dy = [1,0,1,0,-1,0]
for i in enumerate(permutations(s)):
i = list(i[1])
i[3],i[4],i[5] = i[3][::-1],i[4][::-1],i[5][::-1]
fl = 0
for j in range(1,7):
if i[j%6][0] != i[j-1][-1]:
fl = 1
break
if fl:
continue
ans1 = [['a']*30 for _ in range(30)]
x,y,fl,s = 0,0,0,-1
for ind,j in enumerate(i):
for ch in j:
if x < 0 or y < 0 or x >= 30 or y >= 30:
fl = 1
break
ans1[x][y] = ch
x += dx[ind]
y += dy[ind]
if fl:
break
x -= dx[ind]
y -= dy[ind]
if s == -1:
s = y
if s != -1:
ii = 0
for xx in i[1]:
if ans1[ii][s] != xx:
fl = 1
break
ii += 1
if fl or x or y:
continue
ma = 0
for ii in range(30):
ma = max(ma,30-ans1[ii].count('a'))
fin = []
for ii in range(30):
fin.append(''.join(ans1[ii][:ma]))
fin[-1] = fin[-1].replace('a','.')
if fin[-1] == '.'*ma:
fin.pop()
break
fll = 0
for ii in range(min(len(fin),len(ans))):
if fin[ii] < ans[ii]:
fll = 1
ans = fin
break
elif fin[ii] > ans[ii]:
fll = 1
break
if not fll:
if len(fin) < len(ans):
ans = fin
if ans == ['a'*30 for _ in range(30)]:
print('Impossible')
exit()
print(*ans,sep='\n')
# Fast IO 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")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
```
| 108,220 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplΠ΅ type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity sign, not necessarily symmetrical.
The top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification.
Help Vasya β compose a crossword of the described type using the given six words. It is allowed to use the words in any order.
Input
Six lines contain the given words. Every word consists of no more than 30 and no less than 3 uppercase Latin letters.
Output
If it is impossible to solve the problem, print Impossible. Otherwise, print the sought crossword. All the empty squares should be marked as dots.
If there can be several solutions to that problem, print the lexicographically minimum one. I.e. the solution where the first line is less than the first line of other solutions should be printed. If the two lines are equal, compare the second lines and so on. The lexicographical comparison of lines is realized by the < operator in the modern programming languages.
Examples
Input
NOD
BAA
YARD
AIRWAY
NEWTON
BURN
Output
BAA...
U.I...
R.R...
NEWTON
..A..O
..YARD
Input
AAA
AAA
AAAAA
AAA
AAA
AAAAA
Output
AAA..
A.A..
AAAAA
..A.A
..AAA
Input
PTC
JYNYFDSGI
ZGPPC
IXEJNDOP
JJFS
SSXXQOFGJUZ
Output
JJFS....
Y..S....
N..X....
Y..X....
F..Q....
D..O....
S..F....
G..G....
IXEJNDOP
...U...T
...ZGPPC
Tags: implementation
Correct Solution:
```
import sys
from array import array # noqa: F401
from itertools import permutations
def input():
return sys.stdin.buffer.readline().decode('utf-8')
a = [input().rstrip() for _ in range(6)]
ans = ['z' * 100 for _ in range(6)]
inf = ['z' * 100 for _ in range(6)]
for words in permutations(a):
if (
len(words[0]) + len(words[4]) - 1 == len(words[2])
and len(words[1]) + len(words[5]) - 1 == len(words[3])
and words[0][0] == words[1][0]
and words[1][-1] == words[2][0]
and words[0][-1] == words[3][0]
and words[2][len(words[0]) - 1] == words[3][len(words[1]) - 1]
and words[2][-1] == words[5][0]
and words[3][-1] == words[4][0]
and words[4][-1] == words[5][-1]
):
res = [['.'] * len(words[2]) for _ in range(len(words[3]))]
for i in range(len(words[0])):
res[0][i] = words[0][i]
for i in range(len(words[1])):
res[i][0] = words[1][i]
for i in range(len(words[2])):
res[len(words[1]) - 1][i] = words[2][i]
for i in range(len(words[3])):
res[i][len(words[0]) - 1] = words[3][i]
for i in range(len(words[4])):
res[len(words[3]) - 1][len(words[0]) - 1 + i] = words[4][i]
for i in range(len(words[5])):
res[len(words[1]) - 1 + i][len(words[2]) - 1] = words[5][i]
res = [''.join(row) for row in res]
if ans > res:
ans = res
if ans == inf:
print('Impossible')
else:
print('\n'.join(ans))
```
| 108,221 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplΠ΅ type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity sign, not necessarily symmetrical.
The top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification.
Help Vasya β compose a crossword of the described type using the given six words. It is allowed to use the words in any order.
Input
Six lines contain the given words. Every word consists of no more than 30 and no less than 3 uppercase Latin letters.
Output
If it is impossible to solve the problem, print Impossible. Otherwise, print the sought crossword. All the empty squares should be marked as dots.
If there can be several solutions to that problem, print the lexicographically minimum one. I.e. the solution where the first line is less than the first line of other solutions should be printed. If the two lines are equal, compare the second lines and so on. The lexicographical comparison of lines is realized by the < operator in the modern programming languages.
Examples
Input
NOD
BAA
YARD
AIRWAY
NEWTON
BURN
Output
BAA...
U.I...
R.R...
NEWTON
..A..O
..YARD
Input
AAA
AAA
AAAAA
AAA
AAA
AAAAA
Output
AAA..
A.A..
AAAAA
..A.A
..AAA
Input
PTC
JYNYFDSGI
ZGPPC
IXEJNDOP
JJFS
SSXXQOFGJUZ
Output
JJFS....
Y..S....
N..X....
Y..X....
F..Q....
D..O....
S..F....
G..G....
IXEJNDOP
...U...T
...ZGPPC
Submitted Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
from itertools import permutations
def main():
s = [input().strip() for _ in range(6)]
ans = [['a']*30 for _ in range(30)]
dx = [0,1,0,-1,0,-1]
dy = [1,0,1,0,-1,0]
for i in enumerate(permutations(s)):
i = list(i[1])
i[3],i[4],i[5] = i[3][::-1],i[4][::-1],i[5][::-1]
fl = 0
for j in range(1,7):
if i[j%6][0] != i[j-1][-1]:
fl = 1
break
if fl:
continue
ans1 = [['a']*30 for _ in range(30)]
x,y,fl = 0,0,0
for ind,j in enumerate(i):
for ch in j:
if x < 0 or y < 0:
fl = 1
break
ans1[x][y] = ch
x += dx[ind]
y += dy[ind]
if fl:
break
x -= dx[ind]
y -= dy[ind]
if fl or x or y:
continue
ans = min(ans,ans1)
if ans == [['a']*30 for _ in range(30)]:
print('Impossible')
exit()
ma = 0
for i in range(30):
ma = max(ma,30-ans[i].count('a'))
fin = []
for i in range(30):
fin.append(''.join(ans[i][:ma]))
fin[-1] = fin[-1].replace('a','.')
if fin[-1] == '.'*ma:
fin.pop()
break
print(*fin,sep='\n')
# Fast IO 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")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
```
No
| 108,222 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplΠ΅ type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity sign, not necessarily symmetrical.
The top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification.
Help Vasya β compose a crossword of the described type using the given six words. It is allowed to use the words in any order.
Input
Six lines contain the given words. Every word consists of no more than 30 and no less than 3 uppercase Latin letters.
Output
If it is impossible to solve the problem, print Impossible. Otherwise, print the sought crossword. All the empty squares should be marked as dots.
If there can be several solutions to that problem, print the lexicographically minimum one. I.e. the solution where the first line is less than the first line of other solutions should be printed. If the two lines are equal, compare the second lines and so on. The lexicographical comparison of lines is realized by the < operator in the modern programming languages.
Examples
Input
NOD
BAA
YARD
AIRWAY
NEWTON
BURN
Output
BAA...
U.I...
R.R...
NEWTON
..A..O
..YARD
Input
AAA
AAA
AAAAA
AAA
AAA
AAAAA
Output
AAA..
A.A..
AAAAA
..A.A
..AAA
Input
PTC
JYNYFDSGI
ZGPPC
IXEJNDOP
JJFS
SSXXQOFGJUZ
Output
JJFS....
Y..S....
N..X....
Y..X....
F..Q....
D..O....
S..F....
G..G....
IXEJNDOP
...U...T
...ZGPPC
Submitted Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
from itertools import permutations
def main():
s = [input().strip() for _ in range(6)]
ans = [['a']*30 for _ in range(30)]
dx = [0,1,0,-1,0,-1]
dy = [1,0,1,0,-1,0]
for i in enumerate(permutations(s)):
i = list(i[1])
i[3],i[4],i[5] = i[3][::-1],i[4][::-1],i[5][::-1]
fl = 0
for j in range(1,7):
if i[j%6][0] != i[j-1][-1]:
fl = 1
break
if fl:
continue
ans1 = [['a']*30 for _ in range(30)]
x,y,fl,s = 0,0,0,-1
for ind,j in enumerate(i):
for ch in j:
if x < 0 or y < 0 or x >= 30 or y >= 30:
fl = 1
break
ans1[x][y] = ch
x += dx[ind]
y += dy[ind]
if fl:
break
x -= dx[ind]
y -= dy[ind]
if s == -1:
s = y
if s != -1:
ii = 0
for xx in i[1]:
if ans1[ii][s] != xx:
fl = 1
break
ii += 1
if fl or x or y:
continue
for ii in range(30):
if ans1[ii] < ans[ii]:
ans = ans1
break
elif ans1[ii] > ans[ii]:
break
if ans == [['a']*30 for _ in range(30)]:
print('Impossible')
exit()
ma = 0
for i in range(30):
ma = max(ma,30-ans[i].count('a'))
fin = []
for i in range(30):
fin.append(''.join(ans[i][:ma]))
fin[-1] = fin[-1].replace('a','.')
if fin[-1] == '.'*ma:
fin.pop()
break
print(*fin,sep='\n')
# Fast IO 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")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
```
No
| 108,223 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplΠ΅ type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity sign, not necessarily symmetrical.
The top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification.
Help Vasya β compose a crossword of the described type using the given six words. It is allowed to use the words in any order.
Input
Six lines contain the given words. Every word consists of no more than 30 and no less than 3 uppercase Latin letters.
Output
If it is impossible to solve the problem, print Impossible. Otherwise, print the sought crossword. All the empty squares should be marked as dots.
If there can be several solutions to that problem, print the lexicographically minimum one. I.e. the solution where the first line is less than the first line of other solutions should be printed. If the two lines are equal, compare the second lines and so on. The lexicographical comparison of lines is realized by the < operator in the modern programming languages.
Examples
Input
NOD
BAA
YARD
AIRWAY
NEWTON
BURN
Output
BAA...
U.I...
R.R...
NEWTON
..A..O
..YARD
Input
AAA
AAA
AAAAA
AAA
AAA
AAAAA
Output
AAA..
A.A..
AAAAA
..A.A
..AAA
Input
PTC
JYNYFDSGI
ZGPPC
IXEJNDOP
JJFS
SSXXQOFGJUZ
Output
JJFS....
Y..S....
N..X....
Y..X....
F..Q....
D..O....
S..F....
G..G....
IXEJNDOP
...U...T
...ZGPPC
Submitted Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
from itertools import permutations
def main():
s = [input().strip() for _ in range(6)]
ma = max(map(len,s))
ans = [['a']*30 for _ in range(30)]
dx = [0,1,0,-1,0,-1]
dy = [1,0,1,0,-1,0]
for i in enumerate(permutations(s)):
i = list(i[1])
i[3],i[4],i[5] = i[3][::-1],i[4][::-1],i[5][::-1]
fl = 0
for j in range(1,7):
if i[j%6][0] != i[j-1][-1]:
fl = 1
break
if fl:
continue
ans1 = [['a']*30 for _ in range(30)]
x,y,fl = 0,0,0
for ind,j in enumerate(i):
for ch in j:
if x < 0 or y < 0 or x >= ma or y >= ma:
fl = 1
break
ans1[x][y] = ch
x += dx[ind]
y += dy[ind]
if fl:
break
x -= dx[ind]
y -= dy[ind]
if fl:
continue
ans = min(ans,ans1)
if ans == [['a']*30 for _ in range(30)]:
print('Impossible')
exit()
fin = []
for i in range(30):
fin.append(''.join(ans[i][:ma]))
fin[-1] = fin[-1].replace('a','.')
if fin[-1] == '.'*ma:
fin.pop()
break
print(*fin,sep='\n')
# Fast IO 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")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
```
No
| 108,224 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplΠ΅ type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity sign, not necessarily symmetrical.
The top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification.
Help Vasya β compose a crossword of the described type using the given six words. It is allowed to use the words in any order.
Input
Six lines contain the given words. Every word consists of no more than 30 and no less than 3 uppercase Latin letters.
Output
If it is impossible to solve the problem, print Impossible. Otherwise, print the sought crossword. All the empty squares should be marked as dots.
If there can be several solutions to that problem, print the lexicographically minimum one. I.e. the solution where the first line is less than the first line of other solutions should be printed. If the two lines are equal, compare the second lines and so on. The lexicographical comparison of lines is realized by the < operator in the modern programming languages.
Examples
Input
NOD
BAA
YARD
AIRWAY
NEWTON
BURN
Output
BAA...
U.I...
R.R...
NEWTON
..A..O
..YARD
Input
AAA
AAA
AAAAA
AAA
AAA
AAAAA
Output
AAA..
A.A..
AAAAA
..A.A
..AAA
Input
PTC
JYNYFDSGI
ZGPPC
IXEJNDOP
JJFS
SSXXQOFGJUZ
Output
JJFS....
Y..S....
N..X....
Y..X....
F..Q....
D..O....
S..F....
G..G....
IXEJNDOP
...U...T
...ZGPPC
Submitted Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
from itertools import permutations
def main():
s = [input().strip() for _ in range(6)]
ans = [['a']*30 for _ in range(30)]
dx = [0,1,0,-1,0,-1]
dy = [1,0,1,0,-1,0]
for i in enumerate(permutations(s)):
i = list(i[1])
i[3],i[4],i[5] = i[3][::-1],i[4][::-1],i[5][::-1]
fl = 0
for j in range(1,7):
if i[j%6][0] != i[j-1][-1]:
fl = 1
break
if fl:
continue
ans1 = [['a']*30 for _ in range(30)]
x,y,fl,s,s1 = 0,0,0,-1,-1
for ind,j in enumerate(i):
for ch in j:
if x < 0 or y < 0 or x >= 30 or y >= 30:
fl = 1
break
ans1[x][y] = ch
x += dx[ind]
y += dy[ind]
if fl:
break
x -= dx[ind]
y -= dy[ind]
if s == -1 and s1 == -1:
s,s1 = x,y
if s != -1:
for xx in i[1]:
if ans1[s][s1] != xx:
fl = 1
break
s += 1
if fl or x or y:
continue
ans = min(ans,ans1)
if ans == [['a']*30 for _ in range(30)]:
print('Impossible')
exit()
ma = 0
for i in range(30):
ma = max(ma,30-ans[i].count('a'))
fin = []
for i in range(30):
fin.append(''.join(ans[i][:ma]))
fin[-1] = fin[-1].replace('a','.')
if fin[-1] == '.'*ma:
fin.pop()
break
print(*fin,sep='\n')
# Fast IO 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")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
```
No
| 108,225 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm Γ h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor β he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 β€ w, h β€ 200 000, 1 β€ n β€ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 β€ y β€ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 β€ x β€ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image>
Tags: binary search, data structures, implementation
Correct Solution:
```
def main():
from sys import stdin
w, h, n = map(int, stdin.readline().split())
res, vrt, hor = [], [], []
vh = (vrt, hor)
for i, s in enumerate(stdin.read().splitlines()):
x = int(s[2:])
flag = s[0] == 'V'
vh[flag].append(i)
res.append([x, flag])
dim = []
for tmp, m in zip(vh, (h, w)):
tmp.sort(key=lambda e: res[e][0])
u = [None, [0]]
dim.append(u)
j = z = 0
for i in tmp:
x = res[i][0]
if z < x - j:
z = x - j
j = x
v = [u, res[i]]
u.append(v)
u = v
res[i].append(u)
v = [u, [m], None]
u.append(v)
dim.append(v)
if z < m - j:
z = m - j
dim.append(z)
l, r, wmax, u, d, hmax = dim
whmax = [wmax, hmax]
for i in range(n - 1, -1, -1):
x, flag, link = res[i]
u = whmax[flag]
res[i] = u * whmax[not flag]
link[0][2] = link[2]
link[2][0] = link[0]
v = link[2][1][0] - link[0][1][0]
if u < v:
whmax[flag] = v
print('\n'.join(map(str, res)))
if __name__ == '__main__':
main()
# Made By Mostafa_Khaled
```
| 108,226 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm Γ h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor β he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 β€ w, h β€ 200 000, 1 β€ n β€ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 β€ y β€ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 β€ x β€ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image>
Tags: binary search, data structures, implementation
Correct Solution:
```
def main():
from sys import stdin
w, h, n = map(int, stdin.readline().split())
res, vrt, hor = [], [], []
vh = (vrt, hor)
for i, s in enumerate(stdin.read().splitlines()):
x = int(s[2:])
flag = s[0] == 'V'
vh[flag].append(i)
res.append([x, flag])
dim = []
for tmp, m in zip(vh, (h, w)):
tmp.sort(key=lambda e: res[e][0])
u = [None, [0]]
dim.append(u)
j = z = 0
for i in tmp:
x = res[i][0]
if z < x - j:
z = x - j
j = x
v = [u, res[i]]
u.append(v)
u = v
res[i].append(u)
v = [u, [m], None]
u.append(v)
dim.append(v)
if z < m - j:
z = m - j
dim.append(z)
l, r, wmax, u, d, hmax = dim
whmax = [wmax, hmax]
for i in range(n - 1, -1, -1):
x, flag, link = res[i]
u = whmax[flag]
res[i] = u * whmax[not flag]
link[0][2] = link[2]
link[2][0] = link[0]
v = link[2][1][0] - link[0][1][0]
if u < v:
whmax[flag] = v
print('\n'.join(map(str, res)))
if __name__ == '__main__':
main()
```
| 108,227 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm Γ h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor β he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 β€ w, h β€ 200 000, 1 β€ n β€ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 β€ y β€ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 β€ x β€ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image>
Tags: binary search, data structures, implementation
Correct Solution:
```
w,h,n=map(int,input().split())
l=[-1]*(w+1)
r=[-1]*(w+1)
t=[-1]*(h+1)
b=[-1]*(h+1)
l[0]=0
b[0]=0
t[h]=h
r[w]=w
V=[0]*(n)
H=[0]*(n)
for i in range(n):
line,index=input().split()
index=int(index)
if line=="V":
r[index]=w
V[i]=index
else:
t[index]=h
H[i]=index
left=0
mxw=0
for i in range(1,w+1):
if r[i]!=-1:
l[i]=left
r[left]=i
mxw=max(mxw,i-left)
left=i
bottom=0
mxh=0
for i in range(1,h+1):
if t[i]!=-1:
b[i]=bottom
t[bottom]=i
mxh=max(mxh,i-bottom)
bottom=i
ans=[0]*(n)
ans[n-1]=mxh*mxw
for i in range(n-1,0,-1):
if V[i]!=0:
mxw=max(mxw,r[V[i]]-l[V[i]])
r[l[V[i]]]=r[V[i]]
l[r[V[i]]]=l[V[i]]
else:
mxh=max(mxh,t[H[i]]-b[H[i]])
b[t[H[i]]]=b[H[i]]
t[b[H[i]]]=t[H[i]]
ans[i-1]=mxh*mxw
for i in range(n):
print(ans[i])
```
| 108,228 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm Γ h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor β he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 β€ w, h β€ 200 000, 1 β€ n β€ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 β€ y β€ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 β€ x β€ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image>
Tags: binary search, data structures, implementation
Correct Solution:
```
w, h, n = map(int, input().split())
l, r = [-1] * (w+1), [-1] * (w+1)
t, b = [-1] * (h+1), [-1] * (h+1)
l[0], b[0], t[h], r[w] = 0, 0, h, w
V, H = [0] * n, [0] * n
for i in range(n):
line, idx = input().split()
idx = int(idx)
if line == 'V':
r[idx] = w
V[i] = idx
else:
t[idx] = h
H[i] = idx
left, max_w = 0, 0
for i in range(1, w+1):
if r[i] != -1:
l[i] = left
r[left] = i
max_w = max(max_w, i - left)
left = i
bottom, max_h = 0, 0
for i in range(1 ,h+1):
if t[i] != -1:
b[i] = bottom
t[bottom] = i
max_h = max(max_h, i - bottom)
bottom = i
res = [0] * n
res[n-1] = max_h * max_w
for i in range(n-1, 0, -1):
if V[i] != 0:
max_w = max(max_w, r[V[i]] - l[V[i]])
r[l[V[i]]] = r[V[i]]
l[r[V[i]]] = l[V[i]]
else:
max_h = max(max_h, t[H[i]] - b[H[i]])
b[t[H[i]]] = b[H[i]]
t[b[H[i]]] = t[H[i]]
res[i-1] = max_h * max_w
for i in range(n):
print(res[i])
```
| 108,229 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm Γ h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor β he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 β€ w, h β€ 200 000, 1 β€ n β€ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 β€ y β€ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 β€ x β€ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image>
Tags: binary search, data structures, implementation
Correct Solution:
```
# -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 1/7/20
reverse thinking of merging instead of split
"""
import collections
import time
import os
import sys
import bisect
import heapq
from typing import List
class Node:
val = None
def __init__(self, val):
self.val = val
self.left = Node
self.right = None
def solve(W, H, N, A):
xs = [0] + [v for t, v in A if t == 0] + [W]
ys = [0] + [v for t, v in A if t == 1] + [H]
xs.sort()
ys.sort()
xlist = Node(0)
h = xlist
xnodes = {0: h}
maxw = max([xs[i+1] - xs[i] for i in range(len(xs)-1)] or [0])
maxh = max([ys[i+1] - ys[i] for i in range(len(ys)-1)] or [0])
for v in xs[1:]:
n = Node(v)
xnodes[v] = n
h.right = n
n.left = h
h = n
ylist = Node(0)
h = ylist
ynodes = {0: h}
for v in ys[1:]:
n = Node(v)
ynodes[v] = n
h.right = n
n.left = h
h = n
ans = []
maxarea = maxh * maxw
for t, v in reversed(A):
ans.append(maxarea)
if t == 0:
node = xnodes[v]
w = node.right.val - node.left.val
maxw = max(maxw, w)
else:
node = ynodes[v]
h = node.right.val - node.left.val
maxh = max(maxh, h)
node.left.right = node.right
node.right.left = node.left
maxarea = maxh * maxw
return ans[::-1]
def solve2(W, H, N, A):
ws = [(-W, 0, W)]
hs = [(-H, 0, H)]
iw, ih = set(), set()
ans = []
xs, ys = [0, W], [0, H]
for t, v in A:
if t == 0:
bisect.insort_left(xs, v)
i = bisect.bisect_left(xs, v)
l, m, r = xs[i-1], xs[i], xs[i+1]
iw.add((l-r, l, r))
heapq.heappush(ws, (l - m, l, m))
heapq.heappush(ws, (m - r, m, r))
while ws[0] in iw:
heapq.heappop(ws)
else:
bisect.insort(ys, v)
i = bisect.bisect_left(ys, v)
l, m, r = ys[i-1], ys[i], ys[i+1]
ih.add((l-r, l, r))
heapq.heappush(hs, (l - m, l, m))
heapq.heappush(hs, (m - r, m, r))
while hs[0] in ih:
heapq.heappop(hs)
w, h = ws[0], hs[0]
ans.append(w[0] * h[0])
return ans
W, H, N = map(int,input().split())
A = []
for i in range(N):
a, b = input().split()
c = 0 if a == 'V' else 1
A.append((c, int(b)))
print('\n'.join(map(str, solve(W, H, N, A))))
```
| 108,230 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm Γ h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor β he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 β€ w, h β€ 200 000, 1 β€ n β€ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 β€ y β€ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 β€ x β€ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image>
Tags: binary search, data structures, implementation
Correct Solution:
```
from sys import stdin, stdout
w, h, n = map(int, stdin.readline().split())
a = [stdin.readline().split() for _ in range(n)]
y = [0, h]
x = [0, w]
for m in a:
m[1] = int(m[1])
if m[0] == 'H':
y.append(m[1])
else:
x.append(m[1])
y.sort()
x.sort()
iy = {t: i for i, t in enumerate(y)}
ix = {t: i for i, t in enumerate(x)}
ny = len(y)
nx = len(x)
pary = list(range(len(y)))
parx = list(range(len(x)))
p = 0
dy = [0] * ny
for i in range(ny - 1):
dy[i] = y[i+1] - y[i]
my = max(dy)
dx = [0] * nx
for i in range(nx - 1):
dx[i] = x[i+1] - x[i]
mx = max(dx)
ans = [my * mx]
for t in reversed(a):
if t[0] == 'H':
i = iy[t[1]]
st = [i]
while pary[i] != i:
i = pary[i]
st.append(i)
nl = dy[i]
i = iy[t[1]] - 1
st.append(i)
while pary[i] != i:
i = pary[i]
st.append(i)
dy[i] += nl
if my < dy[i]:
my = dy[i]
i = st.pop()
for j in st:
pary[j] = i
else:
i = ix[t[1]]
st = [i]
while parx[i] != i:
i = parx[i]
st.append(i)
nl = dx[i]
i = ix[t[1]] - 1
st.append(i)
while parx[i] != i:
i = parx[i]
st.append(i)
dx[i] += nl
if mx < dx[i]:
mx = dx[i]
i = st.pop()
for j in st:
parx[j] = i
ans.append(mx * my)
ans.pop()
stdout.write('\n'.join(map(str, reversed(ans))))
```
| 108,231 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm Γ h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor β he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 β€ w, h β€ 200 000, 1 β€ n β€ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 β€ y β€ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 β€ x β€ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image>
Tags: binary search, data structures, implementation
Correct Solution:
```
# import itertools
# import bisect
# import math
from collections import defaultdict, Counter
import os
import sys
from io import BytesIO, IOBase
# sys.setrecursionlimit(10 ** 5)
ii = lambda: int(input())
lmii = lambda: list(map(int, input().split()))
slmii = lambda: sorted(map(int, input().split()))
li = lambda: list(input())
mii = lambda: map(int, input().split())
msi = lambda: map(str, input().split())
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
def gcd(a, b):
if b == 0: return a
return gcd(b, a % b)
def lcm(a, b): return (a * b) // gcd(a, b)
def main():
# for _ in " " * int(input()):
w, h, n = mii()
ws, dws, hs, dhs, hsm, wsm = SortedList([]), defaultdict(int), SortedList([]), defaultdict(int), SortedList(
[]), SortedList([])
hsm.add(h);
wsm.add(w);
hs.add(0);
ws.add(0);
hs.add(h);
ws.add(w);
dhs[h] = 1;
dhs[0] = 1;
dws[0] = 1;
dws[w] = 1
for i in range(n):
t, p = map(str, input().split())
p = int(p)
if t == "H":
if dhs[p] == 0:
hs.add(p)
dhs[p] = 1
ind = hs.bisect_left(p)
pre, nex = hs[ind - 1], hs[ind + 1]
hsm.__delitem__(hsm.bisect_left(nex - pre));
hsm.add(p - pre);
hsm.add(nex - p)
else:
if dws[p] == 0:
ws.add(p)
dws[p] = 1
ind = ws.bisect_left(p)
pre, nex = ws[ind - 1], ws[ind + 1]
wsm.__delitem__(wsm.bisect_left(nex - pre));
wsm.add(p - pre);
wsm.add(nex - p)
print(wsm[-1] * hsm[-1])
pass
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")
if __name__ == "__main__":
main()
```
| 108,232 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm Γ h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor β he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 β€ w, h β€ 200 000, 1 β€ n β€ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 β€ y β€ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 β€ x β€ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image>
Tags: binary search, data structures, implementation
Correct Solution:
```
def main():
w, h, n = map(int, input().split())
res, vrt, hor = [], [], []
vh = (vrt, hor)
for i in range(n):
s = input()
x = int(s[2:])
flag = s[0] == 'V'
vh[flag].append(i)
res.append([x, flag])
dim = []
for tmp, m in zip(vh, (h, w)):
tmp.sort(key=lambda e: res[e][0])
u = [None, [0]]
dim.append(u)
j = z = 0
for i in tmp:
x = res[i][0]
if z < x - j:
z = x - j
j = x
v = [u, res[i]]
u.append(v)
u = v
res[i].append(u)
v = [u, [m], None]
u.append(v)
dim.append(v)
if z < m - j:
z = m - j
dim.append(z)
l, r, wmax, u, d, hmax = dim
whmax = [wmax, hmax]
for i in range(n - 1, -1, -1):
x, flag, link = res[i]
u = whmax[flag]
res[i] = u * whmax[not flag]
link[0][2] = link[2]
link[2][0] = link[0]
v = link[2][1][0] - link[0][1][0]
if u < v:
whmax[flag] = v
print('\n'.join(map(str, res)))
if __name__ == '__main__':
main()
```
| 108,233 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm Γ h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor β he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 β€ w, h β€ 200 000, 1 β€ n β€ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 β€ y β€ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 β€ x β€ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image>
Submitted Solution:
```
w, h, n = map(int, input().split())
x = [0, w]
y = [0, h]
rev = []
for _ in range(n):
s, d = input().split()
if s == 'H':
y.append(int(d))
else:
x.append(int(d))
rev.append((s, int(d)))
x.sort()
y.sort()
_max = 0
if len(x) > 1:
for idx in range(len(x) - 1):
_max = max(_max, x[idx + 1] - x[idx])
else:
_max = w
max_x = _max
_max = 0
if len(y) > 1:
for idx in range(len(y) - 1):
_max = max(_max, y[idx + 1] - y[idx])
else:
_max = w
max_y = _max
enum_x = {num : idx for idx, num in enumerate(x)}
enum_y = {num : idx for idx, num in enumerate(y)}
old_x = x
old_y = y
x = [[0, 0, 0]] * len(old_x)
y = [[0, 0, 0]] * len(old_y)
for idx in range(1, len(x) - 1):
x[idx] = [old_x[idx], idx-1, idx+1]
for idx in range(1, len(y) - 1):
y[idx] = [old_y[idx], idx-1, idx+1]
x[-1] = [w, 0, 0]
y[-1] = [h, 0, 0]
rev.reverse()
ans = [max_x * max_y]
for item in rev:
if item[0] == 'H':
elem = y[enum_y[item[1]]]
max_y = max(max_y, y[elem[2]][0] - y[elem[1]][0])
y[elem[1]][2] = elem[2]
y[elem[2]][1] = elem[1]
else:
elem = x[enum_x[item[1]]]
max_x = max(max_x, x[elem[2]][0] - x[elem[1]][0])
x[elem[1]][2] = elem[2]
x[elem[2]][1] = elem[1]
ans.append(max_x * max_y)
ans.pop()
print('\n'.join(map(str, reversed(ans))))
```
Yes
| 108,234 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm Γ h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor β he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 β€ w, h β€ 200 000, 1 β€ n β€ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 β€ y β€ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 β€ x β€ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image>
Submitted Solution:
```
def main():
from sys import stdin
w, h, n = map(int, stdin.readline().split())
res, vrt, hor = [], [], []
vh = (vrt, hor)
for i, s in enumerate(stdin.read().splitlines()):
x = int(s[2:])
flag = s[0] == 'V'
vh[flag].append(i)
res.append([x, flag])
dim = []
for tmp, m in zip(vh, (h, w)):
tmp.sort(key=lambda e: res[e][0])
u = [None, [0]]
dim.append(u)
j = z = 0
for i in tmp:
x = res[i][0]
if z < x - j:
z = x - j
j = x
v = [u, res[i]]
u.append(v)
u = v
res[i].append(u)
v = [u, [m], None]
u.append(v)
dim.append(v)
if z < m - j:
z = m - j
dim.append(z)
l, r, wmax, u, d, hmax = dim
s = str(wmax * hmax)
for i in range(n - 1, -1, -1):
x, flag, link = res[i]
u = hmax if flag else wmax
res[i] = s
link[0][2] = link[2]
link[2][0] = link[0]
v = link[2][1][0] - link[0][1][0]
if u < v:
if flag:
hmax = v
else:
wmax = v
s = str(wmax * hmax)
print('\n'.join(res))
if __name__ == '__main__':
main()
```
Yes
| 108,235 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm Γ h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor β he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 β€ w, h β€ 200 000, 1 β€ n β€ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 β€ y β€ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 β€ x β€ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image>
Submitted Solution:
```
w, h, n = (int(x) for x in input().split())
squares = [((0, 0), (w, h), w*h)]
for i in range(n):
s = input().split()
key, val = s[0], int(s[1])
max = 0
if key == "H":
k = 0
while k < len(squares):
block = squares[k]
if block[0][1] < h-val < block[1][1]:
squares.remove(block)
s = (block[1][0]-block[0][0])*(h-val-block[0][1])
if s > max:
max = s
if block[2] - s > max:
max = block[2] - s
squares.append((block[0], (block[1][0], h-val), s))
squares.append(((block[0][0], h-val), block[1], block[2] - s))
else:
k += 1
if key == "V":
k = 0
while k < len(squares):
block = squares[k]
if block[0][0] < w-val < block[1][0]:
squares.remove(block)
s = (w-val-block[0][0])*(block[1][1]-block[0][1])
if s > max:
max = s
if block[2] - s > max:
max = block[2] - s
squares.append((block[0], (w-val, block[1][1]), s))
squares.append(((w-val, block[0][1]), block[1], block[2] - s))
else:
k += 1
print(max)
```
No
| 108,236 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm Γ h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor β he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 β€ w, h β€ 200 000, 1 β€ n β€ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 β€ y β€ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 β€ x β€ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image>
Submitted Solution:
```
w, h, n = (int(x) for x in input().split())
squares = [((0, 0), (w, h), w*h)]
for i in range(n):
s = input().split()
key, val = s[0], int(s[1])
max = 0
if key == "H":
k = 0
while k < len(squares):
block = squares[k]
if block[2] > max:
max = block[2]
if block[0][1] < h-val < block[1][1]:
squares.remove(block)
s = (block[1][0]-block[0][0])*(h-val-block[0][1])
if s > max:
max = s
if block[2] - s > max:
max = block[2] - s
squares.append((block[0], (block[1][0], h-val), s))
squares.append(((block[0][0], h-val), block[1], block[2] - s))
else:
k += 1
if key == "V":
k = 0
while k < len(squares):
block = squares[k]
if block[2] > max:
max = block[2]
if block[0][0] < w-val < block[1][0]:
squares.remove(block)
s = (w-val-block[0][0])*(block[1][1]-block[0][1])
if s > max:
max = s
if block[2] - s > max:
max = block[2] - s
squares.append((block[0], (w-val, block[1][1]), s))
squares.append(((w-val, block[0][1]), block[1], block[2] - s))
else:
k += 1
print(max)
```
No
| 108,237 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm Γ h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor β he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 β€ w, h β€ 200 000, 1 β€ n β€ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 β€ y β€ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 β€ x β€ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image>
Submitted Solution:
```
w,h,n=map(int,input().split())
l=[-1]*(w+1)
r=[-1]*(w+1)
t=[-1]*(h+1)
b=[-1]*(h+1)
l[0]=0
b[0]=0
V=[0]*(n)
H=[0]*(n)
for i in range(n):
line,index=input().split()
index=int(index)
if line=="V":
r[index]=w
V[i]=index
else:
t[index]=h
H[i]=index
left=0
mxw=0
for i in range(1,w+1):
if r[i]!=-1:
l[i]=left
r[left]=i
mxw=max(mxw,i-left)
left=i
bottom=0
mxh=0
for i in range(1,h+1):
if t[i]!=-1:
b[i]=bottom
t[bottom]=i
mxh=max(mxh,i-bottom)
bottom=i
ans=[0]*(n)
ans[n-1]=mxh*mxw
for i in range(n-1,0,-1):
if H[i]==0:
mxw=max(mxw,r[V[i]]-l[V[i]])
r[l[V[i]]]=r[V[i]]
l[r[V[i]]]=l[V[i]]
else:
mxh=max(mxh,t[H[i]]-b[H[i]])
b[t[H[i]]]=b[H[i]]
t[b[H[i]]]=t[H[i]]
ans[i-1]=mxh*mxw
for i in range(n):
print(ans[i])
```
No
| 108,238 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm Γ h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.
After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.
Leonid offers to divide the labor β he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?
Input
The first line contains three integers w, h, n (2 β€ w, h β€ 200 000, 1 β€ n β€ 200 000).
Next n lines contain the descriptions of the cuts. Each description has the form H y or V x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 β€ y β€ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 β€ x β€ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.
Output
After each cut print on a single line the area of the maximum available glass fragment in mm2.
Examples
Input
4 3 4
H 2
V 2
V 3
V 1
Output
8
4
4
2
Input
7 6 5
H 4
V 3
V 5
H 2
V 1
Output
28
16
12
6
4
Note
Picture for the first sample test:
<image> Picture for the second sample test: <image>
Submitted Solution:
```
from heapq import *
w, h, n = map(int, input().split())
wSegments = dict()
hSegments = dict()
wSegments[0] = w - 1
hSegments[0] = h - 1
maxW = w
maxH = h
for i in range(n):
info = input().split()
value = int(info[1])
value -= 1
if info[0] == "V":
maxW = 0
tW = None
for segment in wSegments:
if segment <= value and wSegments[segment] >= value:
tW = segment
else:
maxW = max(maxW, wSegments[segment] - segment + 1)
maxW = max([value - tW + 1, wSegments[tW] - value, maxW])
wSegments[value + 1] = wSegments[tW]
wSegments[tW] = value
else:
maxH = 0
tH = None
for segment in hSegments:
if segment <= value and hSegments[segment] >= value:
tH = segment
else:
maxH = max(maxH, hSegments[segment] - segment + 1)
maxH = max([value - tH + 1, hSegments[tH] - value + 1, maxH])
hSegments[value + 1] = hSegments[tH]
hSegments[tH] = value
#for key in hSegments:
# print(key, end= ' ')
# print(hSegments[key])
#print()
#print(maxH)
#print(maxW)
print(maxH * maxW)
```
No
| 108,239 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nudist Beach is planning a military operation to attack the Life Fibers. In this operation, they will attack and capture several cities which are currently under the control of the Life Fibers.
There are n cities, labeled from 1 to n, and m bidirectional roads between them. Currently, there are Life Fibers in every city. In addition, there are k cities that are fortresses of the Life Fibers that cannot be captured under any circumstances. So, the Nudist Beach can capture an arbitrary non-empty subset of cities with no fortresses.
After the operation, Nudist Beach will have to defend the captured cities from counterattack. If they capture a city and it is connected to many Life Fiber controlled cities, it will be easily defeated. So, Nudist Beach would like to capture a set of cities such that for each captured city the ratio of Nudist Beach controlled neighbors among all neighbors of that city is as high as possible.
More formally, they would like to capture a non-empty set of cities S with no fortresses of Life Fibers. The strength of a city <image> is defined as (number of neighbors of x in S) / (total number of neighbors of x). Here, two cities are called neighbors if they are connnected with a road. The goal is to maximize the strength of the weakest city in S.
Given a description of the graph, and the cities with fortresses, find a non-empty subset that maximizes the strength of the weakest city.
Input
The first line of input contains three integers n, m, k (2 β€ n β€ 100 000, 1 β€ m β€ 100 000, 1 β€ k β€ n - 1).
The second line of input contains k integers, representing the cities with fortresses. These cities will all be distinct.
The next m lines contain the roads. The i-th of these lines will have 2 integers ai, bi (1 β€ ai, bi β€ n, ai β bi). Every city will have at least one road adjacent to it.
There is no more than one road between each pair of the cities.
Output
The first line should contain an integer r, denoting the size of an optimum set (1 β€ r β€ n - k).
The second line should contain r integers, denoting the cities in the set. Cities may follow in an arbitrary order. This line should not contain any of the cities with fortresses.
If there are multiple possible answers, print any of them.
Examples
Input
9 8 4
3 9 6 8
1 2
1 3
1 4
1 5
2 6
2 7
2 8
2 9
Output
3
1 4 5
Input
10 8 2
2 9
1 3
2 9
4 5
5 6
6 7
7 8
8 10
10 4
Output
8
1 5 4 8 10 6 3 7
Note
The first example case achieves a strength of 1/2. No other subset is strictly better.
The second example case achieves a strength of 1. Note that the subset doesn't necessarily have to be connected.
Tags: binary search, graphs, greedy
Correct Solution:
```
import heapq
def read_data():
'''
n: number of cities
m: number of roads
k: initial numuber of fortresses of Life Fibers
Es: list of edges
fs: fs[i] = True -> city i is under control of Life Fibers
gs: gs[i] number of edges connected to city i
hs: hs[i] number of adjacent cities under control of Life Fibers
'''
n, m, k = map(int, input().split())
Es = [[] for i in range(n)]
fs = [False] * n
gs = [0.0] * n
hs = [0.0] * n
fortresses = list(map(int, input().split()))
for f in fortresses:
fs[f-1] = True
for i in range(m):
a, b = map(int, input().split())
a -= 1
b -= 1
Es[a].append(b)
Es[b].append(a)
gs[a] += 1
gs[b] += 1
hs[a] += fs[b]
hs[b] += fs[a]
return n, m, k, fs, gs, hs, Es
def solve(n, m, k, fs, gs, hs, Es):
hq = [(-h/g, i) for i, (g, h) in enumerate(zip(gs, hs))]
hq.sort()
f_diff = set()
while hq:
p, i = heapq.heappop(hq)
if fs[i] or i in f_diff:
continue
update_fs(fs, f_diff)
f_diff = set()
dfs(p, i, hq, f_diff, fs, gs, hs, Es)
return [i + 1 for i, f in enumerate(fs) if not f]
def update_fs(fs, f_diff):
for f in f_diff:
fs[f] = True
def dfs(p, i, hq, f_diff, fs, gs, hs, Es):
fifo = [i]
f_diff.add(i)
while fifo:
i = fifo.pop(-1)
for j in Es[i]:
if fs[j] or j in f_diff:
continue
hs[j] += 1
pj = -hs[j]/gs[j]
if pj > p:
heapq.heappush(hq, (pj, j))
else:
fifo.append(j)
f_diff.add(j)
if __name__ == '__main__':
n, m, k, fs, gs, hs, Es = read_data()
beaches = solve(n, m, k, fs, gs, hs, Es)
print(len(beaches))
print(*beaches)
```
| 108,240 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nudist Beach is planning a military operation to attack the Life Fibers. In this operation, they will attack and capture several cities which are currently under the control of the Life Fibers.
There are n cities, labeled from 1 to n, and m bidirectional roads between them. Currently, there are Life Fibers in every city. In addition, there are k cities that are fortresses of the Life Fibers that cannot be captured under any circumstances. So, the Nudist Beach can capture an arbitrary non-empty subset of cities with no fortresses.
After the operation, Nudist Beach will have to defend the captured cities from counterattack. If they capture a city and it is connected to many Life Fiber controlled cities, it will be easily defeated. So, Nudist Beach would like to capture a set of cities such that for each captured city the ratio of Nudist Beach controlled neighbors among all neighbors of that city is as high as possible.
More formally, they would like to capture a non-empty set of cities S with no fortresses of Life Fibers. The strength of a city <image> is defined as (number of neighbors of x in S) / (total number of neighbors of x). Here, two cities are called neighbors if they are connnected with a road. The goal is to maximize the strength of the weakest city in S.
Given a description of the graph, and the cities with fortresses, find a non-empty subset that maximizes the strength of the weakest city.
Input
The first line of input contains three integers n, m, k (2 β€ n β€ 100 000, 1 β€ m β€ 100 000, 1 β€ k β€ n - 1).
The second line of input contains k integers, representing the cities with fortresses. These cities will all be distinct.
The next m lines contain the roads. The i-th of these lines will have 2 integers ai, bi (1 β€ ai, bi β€ n, ai β bi). Every city will have at least one road adjacent to it.
There is no more than one road between each pair of the cities.
Output
The first line should contain an integer r, denoting the size of an optimum set (1 β€ r β€ n - k).
The second line should contain r integers, denoting the cities in the set. Cities may follow in an arbitrary order. This line should not contain any of the cities with fortresses.
If there are multiple possible answers, print any of them.
Examples
Input
9 8 4
3 9 6 8
1 2
1 3
1 4
1 5
2 6
2 7
2 8
2 9
Output
3
1 4 5
Input
10 8 2
2 9
1 3
2 9
4 5
5 6
6 7
7 8
8 10
10 4
Output
8
1 5 4 8 10 6 3 7
Note
The first example case achieves a strength of 1/2. No other subset is strictly better.
The second example case achieves a strength of 1. Note that the subset doesn't necessarily have to be connected.
Submitted Solution:
```
#
```
No
| 108,241 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of n, containing only integers from 1 to n. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions:
* each elements, starting from the second one, is no more than the preceding one
* each element, starting from the second one, is no less than the preceding one
Having got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last.
Input
The single line contains an integer n which is the size of the array (1 β€ n β€ 105).
Output
You must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007.
Examples
Input
2
Output
4
Input
3
Output
17
Tags: combinatorics, math
Correct Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import gcd, ceil
def prod(a, mod=10**9+7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def modInverse(a, m) :
a = a % m;
for x in range(1, m) :
if ((a * x) % m == 1) :
return x
return 1
for _ in range(int(input()) if not True else 1):
n = int(input())
#n, k = map(int, input().split())
#a, b = map(int, input().split())
#c, d = map(int, input().split())
#a = list(map(int, input().split()))
#b = list(map(int, input().split()))
#s = input()
mod = 10**9 + 7
if 1:
max_n = 250000
fact, inv_fact = [0] * (max_n + 1), [0] * (max_n + 1)
fact[0] = 1
for i in range(max_n):
fact[i + 1] = fact[i] * (i + 1) % mod
inv_fact[-1] = pow(fact[-1], mod - 2, mod)
for i in reversed(range(max_n)):
inv_fact[i] = inv_fact[i + 1] * (i + 1) % mod
def nCr_mod(n, r):
res = 1
while n or r:
a, b = n % mod, r % mod
if a < b:
return 0
res = res * fact[a] % mod * inv_fact[b] % mod * inv_fact[a - b] % mod
n //= mod
r //= mod
return res
print((nCr_mod(2*n,n) - n)%mod)
```
| 108,242 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of n, containing only integers from 1 to n. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions:
* each elements, starting from the second one, is no more than the preceding one
* each element, starting from the second one, is no less than the preceding one
Having got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last.
Input
The single line contains an integer n which is the size of the array (1 β€ n β€ 105).
Output
You must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007.
Examples
Input
2
Output
4
Input
3
Output
17
Tags: combinatorics, math
Correct Solution:
```
def fact(n):
res=1
for i in range(2,n+1):
res=(res*i)%(10**9+7)
return res
def rev(a):
return pow(a,10**9+5,10**9+7)
def c2nn(n):
return (fact(2*n+1)*(rev(fact(n))*rev(fact(n+1))))%(10**9+7)
n=int(input())
print(((c2nn(n-1)*2-n)%(10**9+7)+10**9+7)%(10**9+7))
```
| 108,243 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of n, containing only integers from 1 to n. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions:
* each elements, starting from the second one, is no more than the preceding one
* each element, starting from the second one, is no less than the preceding one
Having got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last.
Input
The single line contains an integer n which is the size of the array (1 β€ n β€ 105).
Output
You must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007.
Examples
Input
2
Output
4
Input
3
Output
17
Tags: combinatorics, math
Correct Solution:
```
n,a,b,M,I=int(input()),1,1,1000000007,1000000005
for i in range(1,n):
a=a*i%M
a=pow(a,I,M)
for i in range(n+1,n*2):
b=b*i%M
print(((2*a*b)%M-n)%M)
```
| 108,244 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of n, containing only integers from 1 to n. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions:
* each elements, starting from the second one, is no more than the preceding one
* each element, starting from the second one, is no less than the preceding one
Having got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last.
Input
The single line contains an integer n which is the size of the array (1 β€ n β€ 105).
Output
You must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007.
Examples
Input
2
Output
4
Input
3
Output
17
Tags: combinatorics, math
Correct Solution:
```
#love python :)
#medo journy to icpc
n = int(input())
m = int(1e9 + 7)
p = 1
for i in range(1, n + 1):
p *= 2 * n - i
p *= pow(i, m - 2, m)
p %= m
print((2 * p - n) % m)
```
| 108,245 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of n, containing only integers from 1 to n. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions:
* each elements, starting from the second one, is no more than the preceding one
* each element, starting from the second one, is no less than the preceding one
Having got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last.
Input
The single line contains an integer n which is the size of the array (1 β€ n β€ 105).
Output
You must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007.
Examples
Input
2
Output
4
Input
3
Output
17
Tags: combinatorics, math
Correct Solution:
```
def fact(n):
res=1
for i in range(2,n+1):
res=(res*i)%(10**9+7)
return res
def rev(a):
return pow(a,10**9+5,10**9+7)
def c2nn(n):
return fact(2*n)*(rev(fact(n))**2)%(10**9+7)
n=int(input())
print(c2nn(n)-n)
```
| 108,246 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of n, containing only integers from 1 to n. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions:
* each elements, starting from the second one, is no more than the preceding one
* each element, starting from the second one, is no less than the preceding one
Having got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last.
Input
The single line contains an integer n which is the size of the array (1 β€ n β€ 105).
Output
You must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007.
Examples
Input
2
Output
4
Input
3
Output
17
Tags: combinatorics, math
Correct Solution:
```
MOD=10**9+7
def power(x, a):
if(a==0):
return(1)
z=power(x, a//2)
z=(z*z)%MOD
if(a%2):
z=(z*x)%MOD
return(z)
def fact(n):
factn=1
for i in range(2, n+1):
factn=(factn*i)%MOD
return(factn)
def ncr(n, r):
return((fact(n)*power(fact(r), MOD-2)*power(fact(n-r), MOD-2))%MOD)
n=int(input())
print((2*ncr(2*n-1,n)-n)%MOD)
```
| 108,247 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of n, containing only integers from 1 to n. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions:
* each elements, starting from the second one, is no more than the preceding one
* each element, starting from the second one, is no less than the preceding one
Having got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last.
Input
The single line contains an integer n which is the size of the array (1 β€ n β€ 105).
Output
You must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007.
Examples
Input
2
Output
4
Input
3
Output
17
Tags: combinatorics, math
Correct Solution:
```
prod = 1
n = int(input())
for i in range(n+1, 2*n+1):
prod *= i
prod %= (10**9+7)
for i in range(1,n+1):
prod *= pow(i, 10**9+5, 10**9+7)
prod %= 10**9+7
print((prod-n)%(10**9+7))
```
| 108,248 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of n, containing only integers from 1 to n. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions:
* each elements, starting from the second one, is no more than the preceding one
* each element, starting from the second one, is no less than the preceding one
Having got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last.
Input
The single line contains an integer n which is the size of the array (1 β€ n β€ 105).
Output
You must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007.
Examples
Input
2
Output
4
Input
3
Output
17
Tags: combinatorics, math
Correct Solution:
```
n = int(input())
m = int(1e9 + 7)
# binom(2n - 1, n)
p = 1
for i in range(1, n + 1):
p *= 2 * n - i
p *= pow(i, m - 2, m)
p %= m
print((2 * p - n) % m)
# Made By Mostafa_Khaled
```
| 108,249 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of n, containing only integers from 1 to n. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions:
* each elements, starting from the second one, is no more than the preceding one
* each element, starting from the second one, is no less than the preceding one
Having got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last.
Input
The single line contains an integer n which is the size of the array (1 β€ n β€ 105).
Output
You must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007.
Examples
Input
2
Output
4
Input
3
Output
17
Submitted Solution:
```
# from math import factorial
import re
def factorial(n):
if n == 0:
return 1
else:
for i in range(1, n):
n = (n * i) % 1000000007
return n
def exgcd(a, b, c):
if b == 0:
c[0] = 1
c[1] = 0
return a
else:
ret = exgcd(b, a % b, c)
tmp = c[0] - a // b * c[1]
c[0] = c[1]
c[1] = tmp
return ret
def inv(a, b):
c = [0, 1]
exgcd(a, b, c)
return c[0] % b
def slove(n):
f2n = factorial(2 * n - 1) % 1000000007
fn = factorial(n) % 1000000007
fn1 = factorial(n - 1) % 1000000007
div = (fn * fn1) % 1000000007
ninv = inv(div, 1000000007)
ret = (2 * f2n * ninv - n) % 1000000007
return ret
n = int(input())
print(slove(n))
```
Yes
| 108,250 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of n, containing only integers from 1 to n. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions:
* each elements, starting from the second one, is no more than the preceding one
* each element, starting from the second one, is no less than the preceding one
Having got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last.
Input
The single line contains an integer n which is the size of the array (1 β€ n β€ 105).
Output
You must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007.
Examples
Input
2
Output
4
Input
3
Output
17
Submitted Solution:
```
n = int(input())
m = int(1e9 + 7)
# binom(2n - 1, n)
p = 1
for i in range(1, n + 1):
p *= 2 * n - i
p *= pow(i, m - 2, m)
p %= m
print((2 * p - n) % m)
```
Yes
| 108,251 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of n, containing only integers from 1 to n. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions:
* each elements, starting from the second one, is no more than the preceding one
* each element, starting from the second one, is no less than the preceding one
Having got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last.
Input
The single line contains an integer n which is the size of the array (1 β€ n β€ 105).
Output
You must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007.
Examples
Input
2
Output
4
Input
3
Output
17
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# import string
# characters = string.ascii_lowercase
# digits = string.digits
# sys.setrecursionlimit(int(1e6))
# dir = [-1,0,1,0,-1]
# moves = 'NESW'
inf = float('inf')
from functools import cmp_to_key
from collections import defaultdict as dd
from collections import Counter, deque
from heapq import *
import math
from math import floor, ceil, sqrt
def geti(): return map(int, input().strip().split())
def getl(): return list(map(int, input().strip().split()))
def getis(): return map(str, input().strip().split())
def getls(): return list(map(str, input().strip().split()))
def gets(): return input().strip()
def geta(): return int(input())
def print_s(s): stdout.write(s+'\n')
mod=int(1e9+7)
maxi=int(2e5+2)
factorial=[0]*maxi
factorial[0]=1
for i in range(1,maxi):
factorial[i]=(factorial[i-1]*i)%mod
inverse = [0]*(maxi)
inverse[0]=inverse[1]=1
for i in range(2,maxi):
inverse[i]=(mod-(mod//i))*inverse[mod%i]%mod
for i in range(1,maxi):
inverse[i]=(inverse[i-1]*inverse[i])%mod
def ncr(n,r):
return (((factorial[n]*inverse[r])%mod)*inverse[n-r])%mod
def solve():
n = geta()
# dp = [[0] * n for _ in range(n)]
# dp[0][:] = [1]*n
# for i in range(1, n):
# for j in range(n):
# dp[i][j] += dp[i-1][j] + (dp[i-1][j-1] if j else 0) + (dp[i-1][j+1] if j+1 < n else 0)
# dp[i][j] %= mod
# ans = 0
# for i in dp:
# print(i)
# for i in range(n):
# ans += dp[n-1][i]
# ans %= mod
print((ncr(2*n-1, n) * 2 - n) % mod)
# Fast IO 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")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__=='__main__':
solve()
```
Yes
| 108,252 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of n, containing only integers from 1 to n. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions:
* each elements, starting from the second one, is no more than the preceding one
* each element, starting from the second one, is no less than the preceding one
Having got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last.
Input
The single line contains an integer n which is the size of the array (1 β€ n β€ 105).
Output
You must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007.
Examples
Input
2
Output
4
Input
3
Output
17
Submitted Solution:
```
def po(a,b,m):
if b == 0:
return 1
if b % 2 == 0:
return (po(a, b // 2, m) ** 2) % m
return (po(a, b - 1, m) * a) % m
def rev(a,m):
return po(a, m - 2, m)
def fact(a, m):
t = a
for i in range(1, a):
t=(t * i) % m
return t
def main(n):
m = 10 ** 9 + 7
if n == 1:
return 1
return (2*(fact(2 * n - 1, m) * rev(fact(n, m) * fact(n - 1, m), m)) - n) % m
print(main(int(input())))
```
Yes
| 108,253 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of n, containing only integers from 1 to n. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions:
* each elements, starting from the second one, is no more than the preceding one
* each element, starting from the second one, is no less than the preceding one
Having got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last.
Input
The single line contains an integer n which is the size of the array (1 β€ n β€ 105).
Output
You must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007.
Examples
Input
2
Output
4
Input
3
Output
17
Submitted Solution:
```
def ncr(n,r):
if(n==r):
return 1
if(n<r):
return 0
if(r==0):
return 1
return ncr(n-1,r)+ncr(n-1,r-1)
x=int(input())
print(ncr(2*x-1, x))
```
No
| 108,254 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of n, containing only integers from 1 to n. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions:
* each elements, starting from the second one, is no more than the preceding one
* each element, starting from the second one, is no less than the preceding one
Having got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last.
Input
The single line contains an integer n which is the size of the array (1 β€ n β€ 105).
Output
You must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007.
Examples
Input
2
Output
4
Input
3
Output
17
Submitted Solution:
```
def fact(n):
if n==1:
return 1
return fact(n-1)*n%(10**9+7)
def rev(a):
return pow(a,10**9+5,10**9+7)
def c2nn(n):
return fact(2*n)*rev(fact(n)**2)%(10**9+7)
n=int(input())
print(c2nn(n)*2-n)
```
No
| 108,255 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of n, containing only integers from 1 to n. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions:
* each elements, starting from the second one, is no more than the preceding one
* each element, starting from the second one, is no less than the preceding one
Having got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last.
Input
The single line contains an integer n which is the size of the array (1 β€ n β€ 105).
Output
You must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007.
Examples
Input
2
Output
4
Input
3
Output
17
Submitted Solution:
```
n = int(input())
m = int(1e9 + 7)
# binom(2n - 1, n)
p = 1
for i in range(1, n + 1):
p *= 2 * n - i
p //= i
print(2 * p - n)
```
No
| 108,256 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of n, containing only integers from 1 to n. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions:
* each elements, starting from the second one, is no more than the preceding one
* each element, starting from the second one, is no less than the preceding one
Having got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last.
Input
The single line contains an integer n which is the size of the array (1 β€ n β€ 105).
Output
You must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007.
Examples
Input
2
Output
4
Input
3
Output
17
Submitted Solution:
```
n = int(input())
# result = choose(2*n, n) - n
mod = 1000000007
x = 1
left, right = n, 2
for a in range(2 * n, n, -1):
if left >= right and a % left == 0:
a //= left
left -= 1
if left >= right and a % right == 0:
a //= right
right += 1
x = (a * x) % mod
#print(x, left, right)
#print(x)
x = (x - n + mod) % mod
print(x)
```
No
| 108,257 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A function <image> is called Lipschitz continuous if there is a real constant K such that the inequality |f(x) - f(y)| β€ KΒ·|x - y| holds for all <image>. We'll deal with a more... discrete version of this term.
For an array <image>, we define it's Lipschitz constant <image> as follows:
* if n < 2, <image>
* if n β₯ 2, <image> over all 1 β€ i < j β€ n
In other words, <image> is the smallest non-negative integer such that |h[i] - h[j]| β€ LΒ·|i - j| holds for all 1 β€ i, j β€ n.
You are given an array <image> of size n and q queries of the form [l, r]. For each query, consider the subarray <image>; determine the sum of Lipschitz constants of all subarrays of <image>.
Input
The first line of the input contains two space-separated integers n and q (2 β€ n β€ 100 000 and 1 β€ q β€ 100) β the number of elements in array <image> and the number of queries respectively.
The second line contains n space-separated integers <image> (<image>).
The following q lines describe queries. The i-th of those lines contains two space-separated integers li and ri (1 β€ li < ri β€ n).
Output
Print the answers to all queries in the order in which they are given in the input. For the i-th query, print one line containing a single integer β the sum of Lipschitz constants of all subarrays of <image>.
Examples
Input
10 4
1 5 2 9 1 3 4 2 1 7
2 4
3 8
7 10
1 9
Output
17
82
23
210
Input
7 6
5 7 7 4 6 6 2
1 2
2 3
2 6
1 7
4 7
3 5
Output
2
0
22
59
16
8
Note
In the first query of the first sample, the Lipschitz constants of subarrays of <image> with length at least 2 are:
* <image>
* <image>
* <image>
The answer to the query is their sum.
Tags: data structures, math
Correct Solution:
```
def read_data():
n, q = map(int, input().split())
As = list(map(int, input().split()))
LRs = []
for i in range(q):
L, R = list(map(int, input().split()))
LRs.append((L, R))
return n, q, As, LRs
def solve(n, q, As, LRs):
difs = calc_difs(As)
Ls = get_Ls(difs)
Rs = get_Rs_allow_ties(difs)
for L, R in LRs:
print(calc(L-1, R-2, Ls, Rs, difs))
def calc_difs(As):
difs = [abs(a0 - a1) for a0, a1 in zip(As, As[1:])]
return difs
def get_Ls(Vs):
L = []
st = []
for i, v in enumerate(Vs):
while st and Vs[st[-1]] < v:
st.pop()
if st:
L.append(st[-1] + 1)
else:
L.append(0)
st.append(i)
return L
def get_Ls_allow_ties(Vs):
L = []
st = []
for i, v in enumerate(Vs):
while st and Vs[st[-1]] <= v:
st.pop()
if st:
L.append(st[-1] + 1)
else:
L.append(0)
st.append(i)
return L
def get_Rs(Vs):
n = len(Vs)
revVs = Vs[::-1]
revRs = get_Ls(revVs)
revRs.reverse()
return [n - 1 - R for R in revRs]
def get_Rs_allow_ties(Vs):
n = len(Vs)
revVs = Vs[::-1]
revRs = get_Ls_allow_ties(revVs)
revRs.reverse()
return [n - 1 - R for R in revRs]
def calc(L, R, Ls, Rs, difs):
ans = 0
for i in range(L, R + 1):
ans += difs[i] * (i - max(Ls[i], L) + 1) * (min(Rs[i], R) - i + 1)
return ans
n, q, As, LRs = read_data()
solve(n, q, As, LRs)
```
| 108,258 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A function <image> is called Lipschitz continuous if there is a real constant K such that the inequality |f(x) - f(y)| β€ KΒ·|x - y| holds for all <image>. We'll deal with a more... discrete version of this term.
For an array <image>, we define it's Lipschitz constant <image> as follows:
* if n < 2, <image>
* if n β₯ 2, <image> over all 1 β€ i < j β€ n
In other words, <image> is the smallest non-negative integer such that |h[i] - h[j]| β€ LΒ·|i - j| holds for all 1 β€ i, j β€ n.
You are given an array <image> of size n and q queries of the form [l, r]. For each query, consider the subarray <image>; determine the sum of Lipschitz constants of all subarrays of <image>.
Input
The first line of the input contains two space-separated integers n and q (2 β€ n β€ 100 000 and 1 β€ q β€ 100) β the number of elements in array <image> and the number of queries respectively.
The second line contains n space-separated integers <image> (<image>).
The following q lines describe queries. The i-th of those lines contains two space-separated integers li and ri (1 β€ li < ri β€ n).
Output
Print the answers to all queries in the order in which they are given in the input. For the i-th query, print one line containing a single integer β the sum of Lipschitz constants of all subarrays of <image>.
Examples
Input
10 4
1 5 2 9 1 3 4 2 1 7
2 4
3 8
7 10
1 9
Output
17
82
23
210
Input
7 6
5 7 7 4 6 6 2
1 2
2 3
2 6
1 7
4 7
3 5
Output
2
0
22
59
16
8
Note
In the first query of the first sample, the Lipschitz constants of subarrays of <image> with length at least 2 are:
* <image>
* <image>
* <image>
The answer to the query is their sum.
Tags: data structures, math
Correct Solution:
```
f = lambda: map(int, input().split())
n, m = f()
t = list(f())
p = [1e9] + [abs(b - a) for a, b in zip(t, t[1:])] + [1e9]
L, R = [0] * n, [0] * n
for i in range(1, n):
j = n - i
x, y = i - 1, j + 1
a, b = p[i], p[j]
while a > p[x]: x = L[x]
while b >= p[y]: y = R[y]
L[i], R[j] = x, y
for k in range(m):
l, r = f()
print(sum((i - max(l - 1, L[i])) * (min(r, R[i]) - i) * p[i] for i in range(l, r)))
```
| 108,259 |
Provide tags and a correct Python 3 solution for this coding contest problem.
While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot i will beat robot j if and only if robot i has a higher skill level than robot j. And if robot i beats robot j and robot j beats robot k, then robot i will beat robot k. Since rapping is such a subtle art, two robots can never have the same skill level.
Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level.
Input
The first line of the input consists of two integers, the number of robots n (2 β€ n β€ 100 000) and the number of rap battles m (<image>).
The next m lines describe the results of the rap battles in the order they took place. Each consists of two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), indicating that robot ui beat robot vi in the i-th rap battle. No two rap battles involve the same pair of robots.
It is guaranteed that at least one ordering of the robots satisfies all m relations.
Output
Print the minimum k such that the ordering of the robots by skill level is uniquely defined by the first k rap battles. If there exists more than one ordering that satisfies all m relations, output -1.
Examples
Input
4 5
2 1
1 3
2 3
4 2
4 3
Output
4
Input
3 2
1 2
3 2
Output
-1
Note
In the first sample, the robots from strongest to weakest must be (4, 2, 1, 3), which Bessie can deduce after knowing the results of the first four rap battles.
In the second sample, both (1, 3, 2) and (3, 1, 2) are possible orderings of the robots from strongest to weakest after both rap battles.
Tags: binary search, dp, graphs
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO,IOBase
def topsort(n,path,indeg):
ans = []
for i in range(n):
if not indeg[i]:
ans.append(i)
i = 0
if len(ans) > 1:
return 0
while i != len(ans):
for x in path[ans[i]]:
indeg[x] -= 1
if not indeg[x]:
ans.append(x)
i += 1
if len(ans)-i > 1:
return 0
return ans
def main():
n,m = map(int,input().split())
path = [[] for _ in range(n)]
indeg = [0]*n
edg = []
for _ in range(m):
u1,v1 = map(lambda xx:int(xx)-1,input().split())
edg.append((u1,v1))
path[u1].append(v1)
indeg[v1] += 1
top = topsort(n,path,indeg)
if not top:
return -1
inde = [0]*n
for ind,i in enumerate(top):
inde[i] = ind
ls = -1
for i in range(m):
x,y = edg[i]
if abs(inde[x]-inde[y]) == 1:
ls = i+1
return ls
# Fast IO 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")
sys.stdin,sys.stdout = IOWrapper(sys.stdin),IOWrapper(sys.stdout)
input = lambda:sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
print(main())
```
| 108,260 |
Provide tags and a correct Python 3 solution for this coding contest problem.
While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot i will beat robot j if and only if robot i has a higher skill level than robot j. And if robot i beats robot j and robot j beats robot k, then robot i will beat robot k. Since rapping is such a subtle art, two robots can never have the same skill level.
Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level.
Input
The first line of the input consists of two integers, the number of robots n (2 β€ n β€ 100 000) and the number of rap battles m (<image>).
The next m lines describe the results of the rap battles in the order they took place. Each consists of two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), indicating that robot ui beat robot vi in the i-th rap battle. No two rap battles involve the same pair of robots.
It is guaranteed that at least one ordering of the robots satisfies all m relations.
Output
Print the minimum k such that the ordering of the robots by skill level is uniquely defined by the first k rap battles. If there exists more than one ordering that satisfies all m relations, output -1.
Examples
Input
4 5
2 1
1 3
2 3
4 2
4 3
Output
4
Input
3 2
1 2
3 2
Output
-1
Note
In the first sample, the robots from strongest to weakest must be (4, 2, 1, 3), which Bessie can deduce after knowing the results of the first four rap battles.
In the second sample, both (1, 3, 2) and (3, 1, 2) are possible orderings of the robots from strongest to weakest after both rap battles.
Tags: binary search, dp, graphs
Correct Solution:
```
from collections import defaultdict,deque
def bfs(q,n,mid):
g=defaultdict(list)
vis=[0]*(n)
for i in range(mid):
x,y=q[i]
g[x].append(y)
vis[y]+=1
q=deque()
for i in range(n):
if vis[i]==0:
q.append(i)
flag=True
cnt=0
while q and flag:
# print(q)
if len(q)!=1 : # ek se zyada winner us pos ke liye
flag=False
t=q.popleft()
cnt+=1
for i in g[t]:
vis[i]-=1
if vis[i]==0:
q.append(i)
return cnt==n and flag==True
def f(q,n):
lo=0
hi=len(q)
ans=-1
while lo<=hi:
mid=(lo+hi)//2
if bfs(q,n,mid):
ans=mid
hi=mid-1
else:
lo=mid+1
return ans
q=[]
n,m=map(int,input().strip().split())
for _ in range(m):
x,y=map(int,input().strip().split())
q.append((x-1,y-1))
print(f(q,n))
```
| 108,261 |
Provide tags and a correct Python 3 solution for this coding contest problem.
While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot i will beat robot j if and only if robot i has a higher skill level than robot j. And if robot i beats robot j and robot j beats robot k, then robot i will beat robot k. Since rapping is such a subtle art, two robots can never have the same skill level.
Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level.
Input
The first line of the input consists of two integers, the number of robots n (2 β€ n β€ 100 000) and the number of rap battles m (<image>).
The next m lines describe the results of the rap battles in the order they took place. Each consists of two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), indicating that robot ui beat robot vi in the i-th rap battle. No two rap battles involve the same pair of robots.
It is guaranteed that at least one ordering of the robots satisfies all m relations.
Output
Print the minimum k such that the ordering of the robots by skill level is uniquely defined by the first k rap battles. If there exists more than one ordering that satisfies all m relations, output -1.
Examples
Input
4 5
2 1
1 3
2 3
4 2
4 3
Output
4
Input
3 2
1 2
3 2
Output
-1
Note
In the first sample, the robots from strongest to weakest must be (4, 2, 1, 3), which Bessie can deduce after knowing the results of the first four rap battles.
In the second sample, both (1, 3, 2) and (3, 1, 2) are possible orderings of the robots from strongest to weakest after both rap battles.
Tags: binary search, dp, graphs
Correct Solution:
```
from heapq import heappop,heappush
n,m = map(int,input().split())
C = [[] for _ in range(n)]
indeg = [0]*n
def toposort():
S = [i for i in range(n) if indeg[i] == 0]
nparent = indeg[:]
topo = []
while S:
cur = S.pop()
topo.append(cur)
for neigh,_ in C[cur]:
nparent[neigh] -= 1
if nparent[neigh] == 0:
S.append(neigh)
return topo
def solve():
topo = toposort()
D = [(0,0)]*n
for cur in topo:
for neigh,t in C[cur]:
cd,ct = D[cur]
nd,_ = D[neigh]
if nd <= cd + 1:
D[neigh] = cd + 1, max(ct,t)
d,t = max(D)
return t+1 if d == n-1 else -1
for _ in range(m):
a,b = map(int,input().split())
C[a-1].append((b-1, _))
indeg[b-1] += 1
print(solve())
```
| 108,262 |
Provide tags and a correct Python 3 solution for this coding contest problem.
While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot i will beat robot j if and only if robot i has a higher skill level than robot j. And if robot i beats robot j and robot j beats robot k, then robot i will beat robot k. Since rapping is such a subtle art, two robots can never have the same skill level.
Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level.
Input
The first line of the input consists of two integers, the number of robots n (2 β€ n β€ 100 000) and the number of rap battles m (<image>).
The next m lines describe the results of the rap battles in the order they took place. Each consists of two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), indicating that robot ui beat robot vi in the i-th rap battle. No two rap battles involve the same pair of robots.
It is guaranteed that at least one ordering of the robots satisfies all m relations.
Output
Print the minimum k such that the ordering of the robots by skill level is uniquely defined by the first k rap battles. If there exists more than one ordering that satisfies all m relations, output -1.
Examples
Input
4 5
2 1
1 3
2 3
4 2
4 3
Output
4
Input
3 2
1 2
3 2
Output
-1
Note
In the first sample, the robots from strongest to weakest must be (4, 2, 1, 3), which Bessie can deduce after knowing the results of the first four rap battles.
In the second sample, both (1, 3, 2) and (3, 1, 2) are possible orderings of the robots from strongest to weakest after both rap battles.
Tags: binary search, dp, graphs
Correct Solution:
```
from collections import defaultdict
class RobotRapping():
def __init__(self, n, m, battles):
self.n, self.m = n, m
self.battles = battles
def generate_graph(self, k):
edge_map = defaultdict(list)
rev_map = defaultdict(list)
for i in range(k):
edge_map[self.battles[i][0]-1].append((self.battles[i][1]-1, i))
rev_map[self.battles[i][1]-1].append((self.battles[i][0]-1, i))
return edge_map, rev_map
def check_order(self, num_battles):
edge_map, rev_map = self.generate_graph(num_battles)
outgoing_cnt = defaultdict(int)
for k in edge_map:
outgoing_cnt[k] = len(edge_map[k])
s = []
cntr = 0
for i in range(self.n):
if outgoing_cnt[i] == 0:
s.append(i)
while len(s) > cntr:
if len(s) > cntr+1 :
return False
else:
node = s[cntr]
for v in rev_map[node]:
outgoing_cnt[v] -= 1
if outgoing_cnt[v] == 0:
s.append(v)
cntr += 1
return True
def min_battles(self):
if not self.check_order(self.m):
print(-1)
else:
mn, mx = 0, self.m
while mn < mx-1:
md = int((mn+mx)/2)
if self.check_order(md):
mx = md
else:
mn = md
print(mx)
def min_battles2(self):
edge_map, rev_map = self.generate_graph(self.m)
outgoing_cnt = defaultdict(int)
for k in edge_map:
outgoing_cnt[k] = len(edge_map[k])
s = []
cntr = 0
order = []
for i in range(self.n):
if outgoing_cnt[i] == 0:
s.append(i)
while len(s) > cntr:
if len(s) > cntr+1 :
print(-1)
return
else:
node = s[cntr]
order.append(node)
for v,_ in rev_map[node]:
outgoing_cnt[v] -= 1
if outgoing_cnt[v] == 0:
s.append(v)
cntr += 1
mn_pos = -1
for i in range(1,self.n):
for v,ind in edge_map[order[i]]:
if v == order[i-1]:
mn_pos = max(mn_pos, ind)
break
print(mn_pos+1)
n,m = list(map(int,input().strip(' ').split(' ')))
battles = []
for i in range(m):
x,y = list(map(int,input().strip(' ').split(' ')))
battles.append((x,y))
rr = RobotRapping(n,m,battles)
rr.min_battles2()
```
| 108,263 |
Provide tags and a correct Python 3 solution for this coding contest problem.
While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot i will beat robot j if and only if robot i has a higher skill level than robot j. And if robot i beats robot j and robot j beats robot k, then robot i will beat robot k. Since rapping is such a subtle art, two robots can never have the same skill level.
Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level.
Input
The first line of the input consists of two integers, the number of robots n (2 β€ n β€ 100 000) and the number of rap battles m (<image>).
The next m lines describe the results of the rap battles in the order they took place. Each consists of two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), indicating that robot ui beat robot vi in the i-th rap battle. No two rap battles involve the same pair of robots.
It is guaranteed that at least one ordering of the robots satisfies all m relations.
Output
Print the minimum k such that the ordering of the robots by skill level is uniquely defined by the first k rap battles. If there exists more than one ordering that satisfies all m relations, output -1.
Examples
Input
4 5
2 1
1 3
2 3
4 2
4 3
Output
4
Input
3 2
1 2
3 2
Output
-1
Note
In the first sample, the robots from strongest to weakest must be (4, 2, 1, 3), which Bessie can deduce after knowing the results of the first four rap battles.
In the second sample, both (1, 3, 2) and (3, 1, 2) are possible orderings of the robots from strongest to weakest after both rap battles.
Tags: binary search, dp, graphs
Correct Solution:
```
from sys import stdin, stdout
import sys
import bisect
import heapq
input = sys.stdin.readline
def solve(n, m, edges):
lo = 0
hi = m
curr_k = -1
while lo <= hi:
mid = lo + (hi - lo) // 2
can_do = True
# condition
adj_list = {x: [] for x in range(0, n)}
in_degree = [0] * n
for ed in range(min(mid, len(edges))):
edge = edges[ed]
adj_list[edge[0]].append(edge[1])
in_degree[edge[1]] += 1
candidates = []
for i in range(len(in_degree)):
if in_degree[i] == 0:
candidates.append(i)
res = []
while candidates:
ele = candidates.pop(0)
if len(candidates) > 0:
can_do = False
break
res.append(ele)
for i in adj_list[ele]:
in_degree[i] -= 1
if in_degree[i] == 0:
candidates.append(i)
if len(res) < n:
can_do = False
if can_do:
curr_k = mid
hi = mid - 1
else:
lo = mid + 1
return curr_k
def main():
n, m = map(int, input().split())
edges = []
for i in range(m):
a, b = map(int, input().split())
edges.append([a - 1, b - 1])
stdout.write(str(solve(n, m, edges)))
stdout.write("\n")
if __name__ == "__main__":
main()
```
| 108,264 |
Provide tags and a correct Python 3 solution for this coding contest problem.
While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot i will beat robot j if and only if robot i has a higher skill level than robot j. And if robot i beats robot j and robot j beats robot k, then robot i will beat robot k. Since rapping is such a subtle art, two robots can never have the same skill level.
Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level.
Input
The first line of the input consists of two integers, the number of robots n (2 β€ n β€ 100 000) and the number of rap battles m (<image>).
The next m lines describe the results of the rap battles in the order they took place. Each consists of two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), indicating that robot ui beat robot vi in the i-th rap battle. No two rap battles involve the same pair of robots.
It is guaranteed that at least one ordering of the robots satisfies all m relations.
Output
Print the minimum k such that the ordering of the robots by skill level is uniquely defined by the first k rap battles. If there exists more than one ordering that satisfies all m relations, output -1.
Examples
Input
4 5
2 1
1 3
2 3
4 2
4 3
Output
4
Input
3 2
1 2
3 2
Output
-1
Note
In the first sample, the robots from strongest to weakest must be (4, 2, 1, 3), which Bessie can deduce after knowing the results of the first four rap battles.
In the second sample, both (1, 3, 2) and (3, 1, 2) are possible orderings of the robots from strongest to weakest after both rap battles.
Tags: binary search, dp, graphs
Correct Solution:
```
from sys import stdin
def main():
def f(k):
g, cnt = [[] for _ in range(n)], [0] * n
for u, v in data[:k]:
g[u].append(v)
cnt[v] += 1
if cnt.count(0) > 1:
return False
w, u = cnt.index(0), -1
while u != w:
u = w
for v in g[u]:
cnt[v] -= 1
if not cnt[v]:
if u != w:
return False
w = v
return True
n, m = map(int, input().split())
data = stdin.read().splitlines()
for i, s in enumerate(data):
u, v = map(int, s.split())
data[i] = (u - 1, v - 1)
lo, hi = n - 1, m + 1
while lo < hi:
mid = (lo + hi) // 2
if f(mid):
hi = mid
else:
lo = mid + 1
print(-1 if hi > m else lo)
if __name__ == '__main__':
main()
```
| 108,265 |
Provide tags and a correct Python 3 solution for this coding contest problem.
While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot i will beat robot j if and only if robot i has a higher skill level than robot j. And if robot i beats robot j and robot j beats robot k, then robot i will beat robot k. Since rapping is such a subtle art, two robots can never have the same skill level.
Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level.
Input
The first line of the input consists of two integers, the number of robots n (2 β€ n β€ 100 000) and the number of rap battles m (<image>).
The next m lines describe the results of the rap battles in the order they took place. Each consists of two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), indicating that robot ui beat robot vi in the i-th rap battle. No two rap battles involve the same pair of robots.
It is guaranteed that at least one ordering of the robots satisfies all m relations.
Output
Print the minimum k such that the ordering of the robots by skill level is uniquely defined by the first k rap battles. If there exists more than one ordering that satisfies all m relations, output -1.
Examples
Input
4 5
2 1
1 3
2 3
4 2
4 3
Output
4
Input
3 2
1 2
3 2
Output
-1
Note
In the first sample, the robots from strongest to weakest must be (4, 2, 1, 3), which Bessie can deduce after knowing the results of the first four rap battles.
In the second sample, both (1, 3, 2) and (3, 1, 2) are possible orderings of the robots from strongest to weakest after both rap battles.
Tags: binary search, dp, graphs
Correct Solution:
```
n, m = [int(i) for i in input().split()]
n += 1 # one-indexed
A = [[int(i) for i in input().split()] for j in range(m)]
m += 1
def check(upper):
p = [[] for i in range(n)]
d = [0] * n #record num of parents
for u, v in A[:upper]:
p[u].append(v) # form arc from u to v
d[v] += 1
if d.count(0) > 2:
return False
x = d.index(0, 1) # find the real ancestor, should only be one
while x:
q, x = p[x], 0
for y in q:
d[y] -= 1
if d[y] == 0:
if x:
return False
x = y
return True
left, right = 1, m
while left < right:
mid = (left + right)//2
if check(mid):
right = mid
else:
left = mid + 1
if check(left):
print(left)
else:
print(-1)
```
| 108,266 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot i will beat robot j if and only if robot i has a higher skill level than robot j. And if robot i beats robot j and robot j beats robot k, then robot i will beat robot k. Since rapping is such a subtle art, two robots can never have the same skill level.
Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level.
Input
The first line of the input consists of two integers, the number of robots n (2 β€ n β€ 100 000) and the number of rap battles m (<image>).
The next m lines describe the results of the rap battles in the order they took place. Each consists of two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), indicating that robot ui beat robot vi in the i-th rap battle. No two rap battles involve the same pair of robots.
It is guaranteed that at least one ordering of the robots satisfies all m relations.
Output
Print the minimum k such that the ordering of the robots by skill level is uniquely defined by the first k rap battles. If there exists more than one ordering that satisfies all m relations, output -1.
Examples
Input
4 5
2 1
1 3
2 3
4 2
4 3
Output
4
Input
3 2
1 2
3 2
Output
-1
Note
In the first sample, the robots from strongest to weakest must be (4, 2, 1, 3), which Bessie can deduce after knowing the results of the first four rap battles.
In the second sample, both (1, 3, 2) and (3, 1, 2) are possible orderings of the robots from strongest to weakest after both rap battles.
Submitted Solution:
```
n, m = map(int, input().split())
curWin, curLos = map(int, input().split())
done = 2
if done == n:
print(1)
else:
flag = False
for i in range(1, m):
u, v = map(int, input().split())
if v == curWin:
curWin = u
done += 1
if u == curLos:
curLos = v
done += 1
if done == n:
flag = True
print(i + 1)
break
if not flag:
print(-1)
```
No
| 108,267 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot i will beat robot j if and only if robot i has a higher skill level than robot j. And if robot i beats robot j and robot j beats robot k, then robot i will beat robot k. Since rapping is such a subtle art, two robots can never have the same skill level.
Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level.
Input
The first line of the input consists of two integers, the number of robots n (2 β€ n β€ 100 000) and the number of rap battles m (<image>).
The next m lines describe the results of the rap battles in the order they took place. Each consists of two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), indicating that robot ui beat robot vi in the i-th rap battle. No two rap battles involve the same pair of robots.
It is guaranteed that at least one ordering of the robots satisfies all m relations.
Output
Print the minimum k such that the ordering of the robots by skill level is uniquely defined by the first k rap battles. If there exists more than one ordering that satisfies all m relations, output -1.
Examples
Input
4 5
2 1
1 3
2 3
4 2
4 3
Output
4
Input
3 2
1 2
3 2
Output
-1
Note
In the first sample, the robots from strongest to weakest must be (4, 2, 1, 3), which Bessie can deduce after knowing the results of the first four rap battles.
In the second sample, both (1, 3, 2) and (3, 1, 2) are possible orderings of the robots from strongest to weakest after both rap battles.
Submitted Solution:
```
def main():
line = input().split(" ")
n = int(line[0])
m = int(line[1])
min_count = -1
d = {}
d_win = {}
q = []
waiting = []
for x in range(m):
# Π½ΠΎΠ²Π°Ρ ΡΡΡΠΎΠΊΠ°
line = input().split(" ")
rob_win = int(line[0])
rob_lose = int(line[1])
# ΡΠ»ΠΎΠ²Π°ΡΡ
losers = d.get(rob_win)
if losers is None:
losers = list()
losers.append(rob_lose)
d.update({rob_win: losers})
else:
losers.append(rob_lose)
d.update({rob_win: losers})
# ΡΠ»ΠΎΠ²Π°ΡΡ Π΄Π»Ρ Π»ΡΠ·Π΅ΡΠ°
winners = d_win.get(rob_lose)
if winners is None:
winners = list()
winners.append(rob_win)
d_win.update({rob_lose: winners})
else:
winners.append(rob_win)
d_win.update({rob_lose: winners})
# Π·Π°ΠΏΠΈΡΡΠ²Π°Π΅ΠΌ Π² ΠΌΠ°ΡΡΠΈΠ²
if (rob_lose in q) and (rob_win in q):
continue
elif rob_lose in q:
index = q.index(rob_lose) - 1 # ΠΈΠ½Π΄Π΅ΠΊΡΡ Π²ΠΈΠ³ΡΠ°Π²ΡΠΈΡ
Ρ rob_lose
if index == -1:
q.insert(0, rob_win)
else:
while index != -1:
# ΠΏΡΠΎΠ²Π΅ΡΡΠ΅ΠΌ, Π΅ΡΡΡ Π»ΠΈ ΡΠ»Π΅ΠΌΠ΅Π½Ρ Π² ΡΠΏΠΈΡΠΊΠ΅ ΠΏΠΎΠ±Π΅ΠΆΠ΄Π΅Π½Π½ΡΡ
Π΄Π»Ρ Π½Π°ΡΠ΅Π³ΠΎ winner'a
if rob_win in d.get(q[index]):
# Π·Π°ΠΏΠΈΡΡΠ²Π°Π΅ΠΌ ΠΏΠΎΡΠ»Π΅ Π½Π°ΠΉΠ΄Π΅Π½Π½ΠΎΠ³ΠΎ ΡΠ»Π΅ΠΌΠ΅Π½ΡΠ°
q.insert(index + 1, rob_win)
break
elif q[index] in losers:
# Π΅ΡΠ»ΠΈ ΠΊΠΎΠ½Π΅Ρ ΠΎΡΠ΅ΡΠ΅Π΄ΠΈ, Π²ΡΡΠ°Π²Π»ΡΠ΅ΠΌ ΡΠΈΡΠ»ΠΎ
if index == 0:
q.insert(index, rob_win)
break
continue # Π½Π°Ρ ΡΠ»Π΅ΠΌΠ΅Π½Ρ Π±ΠΎΠ»ΡΡΠ΅, ΠΈΡΠ΅ΠΌ Π΄Π°Π»ΡΡΠ΅
else:
waiting.append(rob_win) # Π½Π΅Π΄ΠΎΡΡΠ°ΡΠΎΡΠ½ΠΎ Π΄Π°Π½Π½ΡΡ
, Π² ΠΆΠ΄ΡΡΡΡ ΠΎΡΠ΅ΡΠ΅Π΄Ρ
break
elif rob_win in q:
index = q.index(rob_win) + 1 # ΠΈΠ½Π΄Π΅ΠΊΡΡ ΠΏΡΠΎΠΈΠ³ΡΠ°Π²ΡΠΈΡ
Ρ rob_win
if index == len(q):
q.append(rob_lose)
else:
while index != len(q):
# ΠΏΡΠΎΠ²Π΅ΡΡΠ΅ΠΌ, Π΅ΡΡΡ Π»ΠΈ ΡΠ»Π΅ΠΌΠ΅Π½Ρ Π² ΡΠΏΠΈΡΠΊΠ΅ Π²ΡΠΈΠ³ΡΠ°Π²ΡΠΈΡ
Π΄Π»Ρ Π½Π°ΡΠ΅Π³ΠΎ loser'a
if rob_lose in d_win.get(q[index]):
# Π·Π°ΠΏΠΈΡΡΠ²Π°Π΅ΠΌ ΠΏΠ΅ΡΠ΅Π΄ Π½Π°ΠΉΠ΄Π΅Π½Π½ΡΠΌ ΡΠ»Π΅ΠΌΠ΅Π½ΡΠΎΠΌ
q.insert(index - 1, rob_lose)
break
elif q[index] in winners:
# Π΅ΡΠ»ΠΈ ΠΊΠΎΠ½Π΅Ρ ΠΎΡΠ΅ΡΠ΅Π΄ΠΈ, Π²ΡΡΠ°Π²Π»ΡΠ΅ΠΌ ΡΠΈΡΠ»ΠΎ
if index == len(q) - 1:
q.insert(index, rob_lose)
break
continue # Π½Π°Ρ ΡΠ»Π΅ΠΌΠ΅Π½Ρ ΠΌΠ΅Π½ΡΡΠ΅, ΠΈΡΠ΅ΠΌ Π΄Π°Π»ΡΡΠ΅
else:
waiting.append(rob_lose) # Π½Π΅Π΄ΠΎΡΡΠ°ΡΠΎΡΠ½ΠΎ Π΄Π°Π½Π½ΡΡ
,
break
elif x == 0:
# ΠΏΠΎΠ±Π΅Π΄ΠΈΡΠ΅Π»ΠΈ -> ΠΏΡΠΎΠΈΠ³ΡΠ°Π²ΡΠΈΠ΅
q.append(rob_win)
q.append(rob_lose)
else:
# Π² ΠΎΡΠ΅ΡΠ΅Π΄Ρ
waiting.append(rob_win)
waiting.append(rob_lose)
# ΠΏΡΠΎΠ²Π΅ΡΡΠ΅ΠΌ ΠΆΠ΄ΡΡΠΈΡ
for waits in waiting:
if waits in q:
continue
winners = d_win.get(waits) # waits ΠΈΠΌ ΠΏΡΠΎΠΈΠ³ΡΠ°Π»
losers = d.get(waits) # waits ΠΈΡ
ΠΏΠΎΠ±Π΅Π΄ΠΈΠ»
index = len(q) - 2
while index != -1:
if q[index] in losers:
if q[index + 1] in winners:
q.insert(index + 1, waits)
waiting.pop(waiting.index(waits))
break
index -= 1
else:
break
# ΠΏΡΠΎΠ²Π΅ΡΡΠ΅ΠΌ, Π΅ΡΡΡ Π»ΠΈ Π·Π°ΠΏΠΎΠ»Π½Π΅Π½ΠΈΠ΅
if len(q) == n:
min_count = x + 1
break
# Π²ΡΠ²ΠΎΠ΄
if len(waiting) > 0:
print(-1)
else:
print(min_count)
print(q)
main()
```
No
| 108,268 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot i will beat robot j if and only if robot i has a higher skill level than robot j. And if robot i beats robot j and robot j beats robot k, then robot i will beat robot k. Since rapping is such a subtle art, two robots can never have the same skill level.
Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level.
Input
The first line of the input consists of two integers, the number of robots n (2 β€ n β€ 100 000) and the number of rap battles m (<image>).
The next m lines describe the results of the rap battles in the order they took place. Each consists of two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), indicating that robot ui beat robot vi in the i-th rap battle. No two rap battles involve the same pair of robots.
It is guaranteed that at least one ordering of the robots satisfies all m relations.
Output
Print the minimum k such that the ordering of the robots by skill level is uniquely defined by the first k rap battles. If there exists more than one ordering that satisfies all m relations, output -1.
Examples
Input
4 5
2 1
1 3
2 3
4 2
4 3
Output
4
Input
3 2
1 2
3 2
Output
-1
Note
In the first sample, the robots from strongest to weakest must be (4, 2, 1, 3), which Bessie can deduce after knowing the results of the first four rap battles.
In the second sample, both (1, 3, 2) and (3, 1, 2) are possible orderings of the robots from strongest to weakest after both rap battles.
Submitted Solution:
```
n, m = list(map(int, input().split()))
forces = [[set(), set()] for i in range(n)]
goal = 0
for i in range(m):
a, b = list(map(int, input().split()))
if a not in forces[b-1][0]:
goal += 1
forces[b-1][0].add(a)
if b not in forces[a-1][1]:
forces[a-1][1].add(b)
goal += 1
for j in forces[a-1][0]:
if b not in forces[j-1][1]:
forces[j-1][1].add(b)
goal += 1
if j not in forces[b-1][0]:
goal += 1
forces[b-1][0].add(j)
for j in forces[b-1][1]:
if a not in forces[j-1][0]:
forces[j-1][0].add(a)
goal += 1
if j not in forces[a-1][1]:
forces[a-1][1].add(j)
goal += 1
if goal >= n * (n - 1):
print(i + 1)
break
if goal < n * (n - 1):
print(-1)
```
No
| 108,269 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot i will beat robot j if and only if robot i has a higher skill level than robot j. And if robot i beats robot j and robot j beats robot k, then robot i will beat robot k. Since rapping is such a subtle art, two robots can never have the same skill level.
Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level.
Input
The first line of the input consists of two integers, the number of robots n (2 β€ n β€ 100 000) and the number of rap battles m (<image>).
The next m lines describe the results of the rap battles in the order they took place. Each consists of two integers ui and vi (1 β€ ui, vi β€ n, ui β vi), indicating that robot ui beat robot vi in the i-th rap battle. No two rap battles involve the same pair of robots.
It is guaranteed that at least one ordering of the robots satisfies all m relations.
Output
Print the minimum k such that the ordering of the robots by skill level is uniquely defined by the first k rap battles. If there exists more than one ordering that satisfies all m relations, output -1.
Examples
Input
4 5
2 1
1 3
2 3
4 2
4 3
Output
4
Input
3 2
1 2
3 2
Output
-1
Note
In the first sample, the robots from strongest to weakest must be (4, 2, 1, 3), which Bessie can deduce after knowing the results of the first four rap battles.
In the second sample, both (1, 3, 2) and (3, 1, 2) are possible orderings of the robots from strongest to weakest after both rap battles.
Submitted Solution:
```
n, m = list(map(int, input().split()))
forces = [[set(), set()] for i in range(n)]
goal = 0
for i in range(m):
a, b = list(map(int, input().split()))
if a not in forces[b-1][0]:
goal += 1
forces[b-1][0].add(a)
if b not in forces[a-1][1]:
forces[a-1][1].add(b)
goal += 1
for j in forces[a-1][0]:
for k in forces[a - 1][1]:
if k not in forces[j-1][1]:
forces[j-1][1].add(k)
goal += 1
if j not in forces[k-1][0]:
goal += 1
forces[k-1][0].add(j)
if b not in forces[j-1][1]:
forces[j-1][1].add(b)
goal += 1
if j not in forces[b-1][0]:
goal += 1
forces[b-1][0].add(j)
for j in forces[b-1][1]:
for k in forces[b-1][0]:
if k not in forces[j-1][0]:
forces[j-1][0].add(k)
goal += 1
if k not in forces[a-1][1]:
forces[a-1][1].add(k)
goal += 1
if a not in forces[j-1][0]:
forces[j-1][0].add(a)
goal += 1
if j not in forces[a-1][1]:
forces[a-1][1].add(j)
goal += 1
print(a, b, goal, forces)
if goal >= n * (n - 1):
print(i + 1)
break
if goal < n * (n - 1):
print(-1)
```
No
| 108,270 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 β€ n β€ 100 000) β the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
n = int(input())
s = input()
if n > 26:
print(-1)
else:
az = [0 for i in range(26)]
cnt = 0
for i in s:
ind = ord(i)-97
az[ind] += 1
if az[ind] > 1:
cnt += 1
print(cnt)
```
| 108,271 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 β€ n β€ 100 000) β the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
def different_is_good(mystr):
if len(mystr) > 26:
print(-1)
return
hash_, diff = [0] * 128, 0
for char in mystr:
if hash_[ord(char)] == 1:
diff += 1
else:
hash_[ord(char)] = 1
print(diff)
_ = int(input())
different_is_good(str(input()))
```
| 108,272 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 β€ n β€ 100 000) β the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
n=int(input())
string=input()
if(n>26):
print(-1)
else:
char_dict={}
for i in string:
if i in char_dict.keys():
char_dict[i]=char_dict[i]+1
else:
char_dict[i]=1
characters_to_change=0
for key,value in char_dict.items():
characters_to_change=characters_to_change+value-1
print(characters_to_change)
```
| 108,273 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 β€ n β€ 100 000) β the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
n = int(input())
s = input()
if n == 1:
print(0)
exit(0)
visited = set()
visited.add(s[0])
ans = 0
d = {}
d[s[0]] = 1
for i in range(1, n):
if s[i] in visited:
d[s[i]] += 1
else:
visited.add(s[i])
d[s[i]] = 1
x = len(visited)
for i in d:
x += d[i] - 1
ans += d[i] - 1
if x > 26:
print(-1)
else:
print(ans)
```
| 108,274 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 β€ n β€ 100 000) β the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
def check(s1):
if len(s1)==len(set(s1)):
return False
else:
return True
n=int(input())
s=input()
s1=list(s)
res=[]
c=0
if(n>26):
print(-1)
elif(check(s1)==True):
for i in s1:
if i not in res:
res.append(i)
else:
c+=1
print(c)
else:
print(0)
```
| 108,275 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 β€ n β€ 100 000) β the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
n=int(input())
k=len(set(input()))
if n<=26:
print(n-k)
else: print(-1)
```
| 108,276 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 β€ n β€ 100 000) β the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
n = int(input())
word = input()
newWord = ""
LETTERS = "abcdefghijklmnopqrstuvwxyz"
usedChars = {}
moves = 0
if n > 26:
print("-1")
else:
for c in word:
if c not in usedChars:
usedChars[c] = 0
for c in word:
if usedChars[c] > 0:
for l in LETTERS:
if l not in usedChars:
usedChars[l] = 0
newWord = newWord + str(l)
moves = moves + 1
break
else:
usedChars[c] += 1
print(moves)
```
| 108,277 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 β€ n β€ 100 000) β the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Tags: constructive algorithms, implementation, strings
Correct Solution:
```
from collections import Counter
n = int(input().strip())
s = input().strip()
def solve(s):
freq = Counter(s)
l = len(freq.keys())
c = 0
for i in freq.values():
if i > 1:
l += i-1
c += i-1
if l > 26:
return -1
return c
print(solve(s))
```
| 108,278 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 β€ n β€ 100 000) β the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Submitted Solution:
```
num = int(input())
arr = list(input())
if num > 26:
print(-1)
else:
print(num - len(set(arr)))
```
Yes
| 108,279 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 β€ n β€ 100 000) β the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Submitted Solution:
```
p=int(input())
s=input()
z=set(s)
if(p>26):
print('-1')
else:
print(p-len(z))
```
Yes
| 108,280 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 β€ n β€ 100 000) β the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Submitted Solution:
```
n = int(input())
st = input()
if(n > 26):
print(-1)
else:
li = [0] * 26
for i in range(n):
ch = ord(st[i]) - 97
li[ch] = li[ch] + 1
total = 0
count = 0
for i in range(26):
if(li[i] == 0):
count = count + 1
else:
total = total + (li[i] - 1)
if(total <= count):
print(total)
else:
print(-1)
```
Yes
| 108,281 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 β€ n β€ 100 000) β the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Submitted Solution:
```
from sys import stdin
n = int(input())
str = stdin.readline()
alphabet = "abcdefghijklmnopqrstuvwxyz"
count = [0] * 26
res = 0
if(n > 26):
print("-1")
else:
for ch in range(n):
for i in range(26):
if(str[ch] == alphabet[i]):
if(count[i] == 0):
count[i] = 1
else:
res += 1
print (res)
```
Yes
| 108,282 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 β€ n β€ 100 000) β the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Submitted Solution:
```
a=int(input())
t=input()
print(a-len(set(t)))
```
No
| 108,283 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 β€ n β€ 100 000) β the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Submitted Solution:
```
# https://codeforces.com/problemset/problem/672/B
n = input()
s = input()
l = []
l.extend(s)
print(len(l) - len(set(l)))
```
No
| 108,284 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 β€ n β€ 100 000) β the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Submitted Solution:
```
def check(s1):
if len(s1)==len(set(s1)):
return False
else:
return True
n=int(input())
s=input()
s1=list(s)
res=[]
c=0
if(check(s1)==True):
for i in s1:
if i not in res:
res.append(i)
c+=1
else:
print(0)
print(c)
```
No
| 108,285 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different.
Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".
If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.
Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
Input
The first line of the input contains an integer n (1 β€ n β€ 100 000) β the length of the string s.
The second line contains the string s of length n consisting of only lowercase English letters.
Output
If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.
Examples
Input
2
aa
Output
1
Input
4
koko
Output
2
Input
5
murat
Output
0
Note
In the first sample one of the possible solutions is to change the first character to 'b'.
In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Submitted Solution:
```
n=int(input(""))
str=input("")
cnt=0
for i in range(n-1):
if str[i] in str[i+1:]:
cnt+=1
if cnt==0:
print(-1)
else:
print(cnt)
```
No
| 108,286 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 β€ n β€ 105) β the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
Tags: dfs and similar, math, probabilities, trees
Correct Solution:
```
n = int(input())
if n == 1:
print(1.0)
exit()
val = [1] + list(map(int, input().split()))
for i in range(n):
val[i] -= 1
size = [1] * n
par = [[] for i in range(n)]
for i in reversed(range(n)):
if val[i] != i:
size[val[i]] += size[i]
par[val[i]].append(i)
ans = [0.0] * n
ans[0] = 1.0
def solve(v):
c = size[v] - 1
k = len(par[v])
if k > 1:
t = sum((1.0 / k) * i / (k - 1) for i in range(k))
else:
t = 0.0
for child in par[v]:
ans[child] = ans[v] + 1.0 + t * (c - size[child])
for i in range(1, n):
if ans[i] > 0.0:
continue
solve(val[i])
print(*ans)
```
| 108,287 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 β€ n β€ 105) β the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
Tags: dfs and similar, math, probabilities, trees
Correct Solution:
```
import sys
input = sys.stdin.readline
n = int(input())
par = [-1] + [int(i) - 1 for i in input().split()]
child = [[] for i in range(n)]
for i in range(1, n):
child[par[i]].append(i)
size = [1] * n
def dfs():
stack = [0]
visit = [False] * n
while stack:
u = stack[-1]
if not visit[u]:
for v in child[u]:
stack.append(v)
visit[u] = True
else:
for v in child[u]:
size[u] += size[v]
stack.pop()
ans = [0] * n
ans[0] = 1
def dfs2():
stack = [0]
while stack:
u = stack.pop()
sm = 0
for v in child[u]:
sm += size[v]
for v in child[u]:
ans[v] = (sm - size[v]) * 0.5 + 1 + ans[u]
stack.append(v)
dfs()
dfs2()
print(*ans)
```
| 108,288 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 β€ n β€ 105) β the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
Tags: dfs and similar, math, probabilities, trees
Correct Solution:
```
class tree_node():
def __init__(self):
self.children = []
self.parent = None
self.time = 0
self.downstream = 0
def addChild(self, node):
self.children.append(node)
num_cities = int(input())
if num_cities > 1:
other_cities = [int(x) for x in input().split(" ")]
else:
other_cities = []
root = tree_node()
cities = [root]
for parent_city in other_cities:
node = tree_node()
cities.append(node)
parent = cities[parent_city - 1]
node.parent = parent
parent.addChild(node)
def calculate_downstream(node):
children = node.children
if len(children) == 0: return 1
return sum(c.downstream for c in children) + 1
def set_all_downstreams(cities):
for node in cities[::-1]:
node.downstream = calculate_downstream(node)
def expected_starting_time(node):
parent = node.parent
if parent == None: return 1.0
other_ds = parent.downstream - node.downstream - 1
return parent.time + other_ds/2 + 1
def set_starting_times(cities):
for c in cities:
c.time = expected_starting_time(c)
set_all_downstreams(cities)
set_starting_times(cities)
for c in cities:
print(c.time)
```
| 108,289 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 β€ n β€ 105) β the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
Tags: dfs and similar, math, probabilities, trees
Correct Solution:
```
import sys
def main():
n = int(sys.stdin.readline())
parent = [0] * (n + 1)
children = [list() for i in range(n + 1)]
d = list(map(int, sys.stdin.readline().split()))
for i, value in enumerate(d):
i += 2
parent[i] = value
children[value].append(i)
parent[1] = -1
depth = [0] * (n + 1)
subtree = [0] * (n + 1)
depth[1] = 1
for i in range(2, n + 1):
depth[i] = depth[parent[i]] + 1
for i in range(n, 0, -1):
subtree[i] = 1
for child in children[i]:
subtree[i] += subtree[child]
sys.stdout.write(' '.join(map(str, [(n - subtree[i] - (depth[i] - 1)) / 2 + depth[i] for i in range(1, n + 1)])))
main()
```
| 108,290 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 β€ n β€ 105) β the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
Tags: dfs and similar, math, probabilities, trees
Correct Solution:
```
n = int(input())
pos, tree, ans, sz = list(map(int,input().split())) if n > 1 else [],[],[],[]
for i in range(n):
tree.append([])
ans.append(0.0)
sz.append(0)
for i in range(n - 1):
tree[pos[i] - 1].append(i + 1)
for i in range(n)[::-1]:
sz[i] = 1
for to in tree[i]:
sz[i] += sz[to]
for i in range(n):
for to in tree[i]:
ans[to] = ans[i] + 1 + (sz[i] - 1 - sz[to]) * 0.5
st = lambda i: str(i + 1)
print(' '.join(list(map(st, ans))))
# Made By Mostafa_Khaled
```
| 108,291 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 β€ n β€ 105) β the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
Tags: dfs and similar, math, probabilities, trees
Correct Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 18 23:02:10 2016
@author: pinku
"""
n = int(input())
if n>1:
p = input().split(' ')
else:
p = []
g = []
ans = []
sz = []
for i in range(0,n):
g.append([]) #creating 2d array
ans.append(0.0)
sz.append(0)
for i in range(0,n-1):
g[int(p[i])-1].append(i+1)
for i in range(0,n)[::-1]:
sz[i]=1
for v in g[i]:
sz[i]+=sz[v]
for i in range(0,n):
for v in g[i]:
ans[v] = ans[i]+1+(sz[i]-1-sz[v])*0.5 #sz[i] -1-sz[v] , the -1 is for deducting i,the parent of v
print(' '.join([str(a+1) for a in ans]))
```
| 108,292 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 β€ n β€ 105) β the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
Tags: dfs and similar, math, probabilities, trees
Correct Solution:
```
n = int(input())
if n ==1:
print(1)
exit(0)
l = list(map(int,input().split()))
w = [[]for i in range(n)]
sz = [1]*n
for i in range(n-1):
w[l[i]-1].append(i+1)
for i in range(n-1,-1,-1):
for j in range(len(w[i])):
sz[i]+=sz[w[i][j]]
ans = [0]*n
for i in range(n):
for j in range(len(w[i])):
ans[w[i][j]] = ans[i]+1+(sz[i]-1-sz[w[i][j]])/2
for i in range(n):
print(ans[i]+1,end = " ")
```
| 108,293 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 β€ n β€ 105) β the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
Tags: dfs and similar, math, probabilities, trees
Correct Solution:
```
import queue
n = int(input())
if (n > 1):
ps = [None, None] + list(map(int, input().split()))
else:
ps = [None, None]
tree_sizes = [None] + [0] * n
children = [None] + [[] for _ in range(n)]
expected = [None] + [0] * n
for i, p in enumerate(ps[2:], 2):
children[p].append(i)
#def dfs(v):
#for ch in children[v]:
#tree_sizes[v] += dfs(ch)
#tree_sizes[v] += 1
#return tree_sizes[v]
stack = [(1, 0)]
while stack:
v, phase = stack.pop()
if phase == 0:
tree_sizes[v] += 1
stack.append((v, 1))
for ch in children[v]:
stack.append((ch, 0))
else:
if ps[v] is not None:
tree_sizes[ps[v]] += tree_sizes[v]
#dfs(1)
expected[1] = 1.0
for v in range(2, n+1):
len_ch = len(children[ps[v]])
if len_ch == 1:
expected[v] = expected[ps[v]] + 1
else:
other = (tree_sizes[ps[v]] - tree_sizes[v] - 1) / (len_ch - 1)
expected[v] = expected[ps[v]] + ((len_ch - 1) / 2 * other + 1)
print(" ".join(map(str, expected[1:])))
```
| 108,294 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 β€ n β€ 105) β the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
Submitted Solution:
```
# [https://gitlab.com/amirmd76/cf-round-362/-/blob/master/B/dans.py <- https://gitlab.com/amirmd76/cf-round-362/tree/master/B <- https://codeforces.com/blog/entry/46031 <- https://codeforces.com/problemset/problem/696/B <- https://algoprog.ru/material/pc696pB]
n = int(input())
if n > 1:
p = input().split(' ')
else:
p = []
g = []
ans = []
sz = []
for i in range(0, n):
g.append([])
ans.append(0.0)
sz.append(0)
for i in range(0, n - 1):
g[int(p[i]) - 1].append(i + 1)
for i in range(0, n)[::-1]:
sz[i] = 1
for to in g[i]:
sz[i] += sz[to]
for i in range(0, n):
for to in g[i]:
ans[to] = ans[i] + 1 + (sz[i] - 1 - sz[to]) * 0.5
print(' '.join([str(a + 1) for a in ans]))
```
Yes
| 108,295 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 β€ n β€ 105) β the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
Submitted Solution:
```
import sys
#def dfs(v, children, depth, cnt = 1):
#depth[v] = cnt
#print(cnt)
#for elem in children[v]:
#dfs(elem, children, depth, cnt + 1)
def main():
#sys.setrecursionlimit(10 ** 9)
#sys.stdin = open('input.txt')
n = int(sys.stdin.readline())
parent = [0] * (n + 1)
children = [list() for i in range(n + 1)]
d = list(map(int, sys.stdin.readline().split()))
for i, value in enumerate(d):
i += 2
parent[i] = value
children[value].append(i)
parent[1] = -1
depth = [0] * (n + 1)
subtree = [0] * (n + 1)
depth[1] = 1
for i in range(2, n + 1):
depth[i] = depth[parent[i]] + 1
#dfs(1, children, depth)
#for i in range(1, n + 1):
#t = i
#depth[t] = 1
#while parent[t] != -1:
#t = parent[t]
#depth[i] += 1
for i in range(n, 0, -1):
subtree[i] = 1
for child in children[i]:
subtree[i] += subtree[child]
sys.stdout.write(' '.join(map(str, [(n - subtree[i] - (depth[i] - 1)) / 2 + depth[i] for i in range(1, n + 1)])))
main()
```
Yes
| 108,296 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 β€ n β€ 105) β the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
Submitted Solution:
```
n = int(input())
pos,tree,ans,sz = list(map(int,input().split())) if n > 1 else [],[],[],[]
for i in range(n):
tree.append([])
ans.append(0.0)
sz.append(0)
for i in range(n-1):
tree[pos[i]-1].append(i+1)
for i in range(n)[::-1]:
sz[i] = 1
for to in tree[i]:
sz[i] += sz[to]
for i in range(n):
for to in tree[i]:
ans[to] = ans[i] + 1 + (sz[i]-1-sz[to]) * 0.5
st = lambda i: str(i+1)
print(' '.join(list(map(st,ans))))
```
Yes
| 108,297 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 β€ n β€ 105) β the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
Submitted Solution:
```
# You lost the game.
n = int(input())
L = list(map(int, input().split()))
T = [[] for _ in range(n)]
for i in range(n-1):
T[L[i]-1] += [i+1]
P = [1 for _ in range(n)]
for i in range(n-2,-1,-1):
P[L[i]-1] += P[i+1]
print(P)
R = [0 for _ in range(n)]
R[0] = 1
afaire = T[0][:]
ind = 0
while len(afaire) > ind:
x = afaire[ind]
ind += 1
parent = L[x-1]-1
nbv = 0
for v in T[parent]:
if x != v:
nbv += P[v]
R[x] = R[parent] + 1 + nbv/2
afaire += T[x]
for i in range(n):
print(R[i],end=" ")
```
No
| 108,298 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
<image>
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
Input
The first line of input contains a single integer n (1 β€ n β€ 105) β the number of cities in USC.
The second line contains n - 1 integers p2, p3, ..., pn (1 β€ pi < i), where pi is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered pi and i in USC.
Output
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10 - 6.
Examples
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0
Submitted Solution:
```
n = int(input())
parent = dict()
children = dict()
d = list(map(int, input().split()))
for i, value in enumerate(d):
i += 2
parent[i] = value
if value in children:
children[value] += [i]
else:
children[value] = [i]
parent[1] = -1
depth = dict()
subtree = dict()
for i in range(1, n + 1):
t = i
depth[t] = 1
while parent[t] != -1:
t = parent[t]
depth[i] += 1
def calc_subtree(v):
if v in children:
subtree[v] = sum([calc_subtree(elem) + 1 for elem in children[v]]) + 1
else:
subtree[v] = 1
return subtree[v]
calc_subtree(1)
for i in range(1, n + 1):
print((n - subtree[i] - (depth[i] - 1)) / 2 + depth[i])
```
No
| 108,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.