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.
Imagine that you are in a building that has exactly n floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from 1 to n. Now you're on the floor number a. You are very bored, so you want to take the lift. Floor number b has a secret lab, the entry is forbidden. However, you already are in the mood and decide to make k consecutive trips in the lift.
Let us suppose that at the moment you are on the floor number x (initially, you were on floor a). For another trip between floors you choose some floor with number y (y ≠ x) and the lift travels to this floor. As you cannot visit floor b with the secret lab, you decided that the distance from the current floor x to the chosen y must be strictly less than the distance from the current floor x to floor b with the secret lab. Formally, it means that the following inequation must fulfill: |x - y| < |x - b|. After the lift successfully transports you to floor y, you write down number y in your notepad.
Your task is to find the number of distinct number sequences that you could have written in the notebook as the result of k trips in the lift. As the sought number of trips can be rather large, find the remainder after dividing the number by 1000000007 (109 + 7).
Input
The first line of the input contains four space-separated integers n, a, b, k (2 ≤ n ≤ 5000, 1 ≤ k ≤ 5000, 1 ≤ a, b ≤ n, a ≠ b).
Output
Print a single integer — the remainder after dividing the sought number of sequences by 1000000007 (109 + 7).
Examples
Input
5 2 4 1
Output
2
Input
5 2 4 2
Output
2
Input
5 3 4 1
Output
0
Note
Two sequences p1, p2, ..., pk and q1, q2, ..., qk are distinct, if there is such integer j (1 ≤ j ≤ k), that pj ≠ qj.
Notes to the samples:
1. In the first sample after the first trip you are either on floor 1, or on floor 3, because |1 - 2| < |2 - 4| and |3 - 2| < |2 - 4|.
2. In the second sample there are two possible sequences: (1, 2); (1, 3). You cannot choose floor 3 for the first trip because in this case no floor can be the floor for the second trip.
3. In the third sample there are no sought sequences, because you cannot choose the floor for the first trip.
Submitted Solution:
```
from sys import stdin
#parser
def parser():
return map(int, stdin.readline().split())
mod=pow(10,9)+7
n,a,b,k=parser()
if a>b:
a=n-a+1
n=n-b
b=n+1
else:
n=b-1
prefix_sum=[0 for x in range(n+1)]
secuences=[0 for x in range(n+1)]
secuences[a]=1
for i in range(k):
prefix_sum[0]=secuences[0]
for j in range(1,n+1):
prefix_sum[j]=prefix_sum[j-1]+secuences[j]
prefix_sum[j]%=mod
for j in range(1,n+1):
distance=b-j
mid_distance=0
if distance % 2 == 0:
mid_distance=distance//2-1
else:
mid_distance=distance//2
secuences[j]=prefix_sum[j-1]+prefix_sum[j+mid_distance]-prefix_sum[j]
secuences[j]%=mod
print(sum(secuences)%mod)
```
Yes
| 90,500 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Imagine that you are in a building that has exactly n floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from 1 to n. Now you're on the floor number a. You are very bored, so you want to take the lift. Floor number b has a secret lab, the entry is forbidden. However, you already are in the mood and decide to make k consecutive trips in the lift.
Let us suppose that at the moment you are on the floor number x (initially, you were on floor a). For another trip between floors you choose some floor with number y (y ≠ x) and the lift travels to this floor. As you cannot visit floor b with the secret lab, you decided that the distance from the current floor x to the chosen y must be strictly less than the distance from the current floor x to floor b with the secret lab. Formally, it means that the following inequation must fulfill: |x - y| < |x - b|. After the lift successfully transports you to floor y, you write down number y in your notepad.
Your task is to find the number of distinct number sequences that you could have written in the notebook as the result of k trips in the lift. As the sought number of trips can be rather large, find the remainder after dividing the number by 1000000007 (109 + 7).
Input
The first line of the input contains four space-separated integers n, a, b, k (2 ≤ n ≤ 5000, 1 ≤ k ≤ 5000, 1 ≤ a, b ≤ n, a ≠ b).
Output
Print a single integer — the remainder after dividing the sought number of sequences by 1000000007 (109 + 7).
Examples
Input
5 2 4 1
Output
2
Input
5 2 4 2
Output
2
Input
5 3 4 1
Output
0
Note
Two sequences p1, p2, ..., pk and q1, q2, ..., qk are distinct, if there is such integer j (1 ≤ j ≤ k), that pj ≠ qj.
Notes to the samples:
1. In the first sample after the first trip you are either on floor 1, or on floor 3, because |1 - 2| < |2 - 4| and |3 - 2| < |2 - 4|.
2. In the second sample there are two possible sequences: (1, 2); (1, 3). You cannot choose floor 3 for the first trip because in this case no floor can be the floor for the second trip.
3. In the third sample there are no sought sequences, because you cannot choose the floor for the first trip.
Submitted Solution:
```
def solve(n, st, k):
MOD = int(1e9 + 7)
dp = [0] * (n + 1)
prefix_sum = [0] * (n + 1)
dp[st] = 1
for times in range(k):
prefix_sum[0] = 0
for i in range(1, n + 1):
prefix_sum[i] = prefix_sum[i - 1] + dp[i]
if prefix_sum[i] >= MOD: prefix_sum[i] -= MOD
for i in range(1, n + 1):
t = prefix_sum[n] - prefix_sum[i] + prefix_sum[i - 1] - prefix_sum[i >> 1]
while t < 0: t += MOD
while t >= MOD: t -= MOD
dp[i] = t
return sum(dp) % MOD
def main():
n, a, b, k = [int(i) for i in input().split()]
if a > b:
print(solve(n - b, a - b, k))
else:
print(solve(b - 1, b - a, k))
main()
```
Yes
| 90,501 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Imagine that you are in a building that has exactly n floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from 1 to n. Now you're on the floor number a. You are very bored, so you want to take the lift. Floor number b has a secret lab, the entry is forbidden. However, you already are in the mood and decide to make k consecutive trips in the lift.
Let us suppose that at the moment you are on the floor number x (initially, you were on floor a). For another trip between floors you choose some floor with number y (y ≠ x) and the lift travels to this floor. As you cannot visit floor b with the secret lab, you decided that the distance from the current floor x to the chosen y must be strictly less than the distance from the current floor x to floor b with the secret lab. Formally, it means that the following inequation must fulfill: |x - y| < |x - b|. After the lift successfully transports you to floor y, you write down number y in your notepad.
Your task is to find the number of distinct number sequences that you could have written in the notebook as the result of k trips in the lift. As the sought number of trips can be rather large, find the remainder after dividing the number by 1000000007 (109 + 7).
Input
The first line of the input contains four space-separated integers n, a, b, k (2 ≤ n ≤ 5000, 1 ≤ k ≤ 5000, 1 ≤ a, b ≤ n, a ≠ b).
Output
Print a single integer — the remainder after dividing the sought number of sequences by 1000000007 (109 + 7).
Examples
Input
5 2 4 1
Output
2
Input
5 2 4 2
Output
2
Input
5 3 4 1
Output
0
Note
Two sequences p1, p2, ..., pk and q1, q2, ..., qk are distinct, if there is such integer j (1 ≤ j ≤ k), that pj ≠ qj.
Notes to the samples:
1. In the first sample after the first trip you are either on floor 1, or on floor 3, because |1 - 2| < |2 - 4| and |3 - 2| < |2 - 4|.
2. In the second sample there are two possible sequences: (1, 2); (1, 3). You cannot choose floor 3 for the first trip because in this case no floor can be the floor for the second trip.
3. In the third sample there are no sought sequences, because you cannot choose the floor for the first trip.
Submitted Solution:
```
n,a,b,k = map(int,input().split())
mod = 1000000007
arr = [[0 for i in range(k+1)] for j in range(n+1)]
for i in range(1,n+1):
if i!=b and i!=a:
if abs(a-i) < abs(a-b): arr[i][1] = 1
#print(arr[2][1])
for i in range(2,k+1):
for j in range(1,n+1):
arr[j][i-1] = (arr[j][i-1]%mod + arr[j-1][i-1])%mod
for j in range(1,n+1):
if b>(j+1) and a<b:
r = j+(b-j-1)//2
arr[j][i] = ((arr[r][i-1]-arr[j][i-1]) + (arr[j-1][i-1]-arr[0][i-1]))%mod
elif b<(j-1) and a>b:
l = j-(j-b-1)//2
arr[j][i] = ((arr[j-1][i-1]-arr[l-1][i-1]) + (arr[n][i-1]-arr[j][i-1]))%mod
elif b==(j+1) and a<b:
arr[j][i] = (arr[j-1][i-1]-arr[0][i-1])
elif b==(j-1) and a>b:
arr[j][i] = (arr[n][i-1]-arr[j][i-1])
req = 0
for i in range(1,n+1):
req = (req+arr[i][k])%mod
print(req%mod)
```
Yes
| 90,502 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Imagine that you are in a building that has exactly n floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from 1 to n. Now you're on the floor number a. You are very bored, so you want to take the lift. Floor number b has a secret lab, the entry is forbidden. However, you already are in the mood and decide to make k consecutive trips in the lift.
Let us suppose that at the moment you are on the floor number x (initially, you were on floor a). For another trip between floors you choose some floor with number y (y ≠ x) and the lift travels to this floor. As you cannot visit floor b with the secret lab, you decided that the distance from the current floor x to the chosen y must be strictly less than the distance from the current floor x to floor b with the secret lab. Formally, it means that the following inequation must fulfill: |x - y| < |x - b|. After the lift successfully transports you to floor y, you write down number y in your notepad.
Your task is to find the number of distinct number sequences that you could have written in the notebook as the result of k trips in the lift. As the sought number of trips can be rather large, find the remainder after dividing the number by 1000000007 (109 + 7).
Input
The first line of the input contains four space-separated integers n, a, b, k (2 ≤ n ≤ 5000, 1 ≤ k ≤ 5000, 1 ≤ a, b ≤ n, a ≠ b).
Output
Print a single integer — the remainder after dividing the sought number of sequences by 1000000007 (109 + 7).
Examples
Input
5 2 4 1
Output
2
Input
5 2 4 2
Output
2
Input
5 3 4 1
Output
0
Note
Two sequences p1, p2, ..., pk and q1, q2, ..., qk are distinct, if there is such integer j (1 ≤ j ≤ k), that pj ≠ qj.
Notes to the samples:
1. In the first sample after the first trip you are either on floor 1, or on floor 3, because |1 - 2| < |2 - 4| and |3 - 2| < |2 - 4|.
2. In the second sample there are two possible sequences: (1, 2); (1, 3). You cannot choose floor 3 for the first trip because in this case no floor can be the floor for the second trip.
3. In the third sample there are no sought sequences, because you cannot choose the floor for the first trip.
Submitted Solution:
```
#!/usr/bin/env python3
import io
import os
import sys
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def printd(*args, **kwargs):
#print(*args, **kwargs, file=sys.stderr)
#print(*args, **kwargs)
pass
def get_str():
return input().decode().strip()
def rint():
return map(int, input().split())
def oint():
return int(input())
mod = 1000000007
n, a, b, k = rint()
if a > b:
a, b = n-a+1, n-b+1
a -= 1
b -= 1
printd(n, a, b, k)
d = [0]*n
d[a] = 1
ps = [0]*b
ps[0] = d[0]
for j in range(1, b):
ps[j] = ps[j-1]+d[j]
ps[j] %= mod
while ps[j] > mod:
ps[j] -= mod
printd(n, a, b, k)
printd(d, ps)
for i in range(k):
for j in range(b):
#b-t > t-j
#2*t < b+j
#t < (b+j)/2
if (b+j)%2:
t = (b+j)//2
else:
t = (b+j)//2 - 1
if j == 0:
d[j] = ps[t] - ps[j]
else:
d[j] = ps[t] - ps[j] + ps[j-1]
d[j] %= mod
while d[j] > mod:
d[j] -= mod
while d[j] <0:
d[j] += mod
#d[j] %=mod
ps[0] = d[0]
for j in range(1, b):
ps[j] = (ps[j-1]+d[j])# %mod
ps[j] %= mod
while ps[j] > mod:
ps[j] -= mod
while ps[j] < 0:
ps[j] += mod
printd(d,ps)
ans = ps[b-1]
print(ans%mod)
```
Yes
| 90,503 |
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response.
Imagine that you are in a building that has exactly n floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from 1 to n. Now you're on the floor number a. You are very bored, so you want to take the lift. Floor number b has a secret lab, the entry is forbidden. However, you already are in the mood and decide to make k consecutive trips in the lift.
Let us suppose that at the moment you are on the floor number x (initially, you were on floor a). For another trip between floors you choose some floor with number y (y ≠ x) and the lift travels to this floor. As you cannot visit floor b with the secret lab, you decided that the distance from the current floor x to the chosen y must be strictly less than the distance from the current floor x to floor b with the secret lab. Formally, it means that the following inequation must fulfill: |x - y| < |x - b|. After the lift successfully transports you to floor y, you write down number y in your notepad.
Your task is to find the number of distinct number sequences that you could have written in the notebook as the result of k trips in the lift. As the sought number of trips can be rather large, find the remainder after dividing the number by 1000000007 (109 + 7).
Input
The first line of the input contains four space-separated integers n, a, b, k (2 ≤ n ≤ 5000, 1 ≤ k ≤ 5000, 1 ≤ a, b ≤ n, a ≠ b).
Output
Print a single integer — the remainder after dividing the sought number of sequences by 1000000007 (109 + 7).
Examples
Input
5 2 4 1
Output
2
Input
5 2 4 2
Output
2
Input
5 3 4 1
Output
0
Note
Two sequences p1, p2, ..., pk and q1, q2, ..., qk are distinct, if there is such integer j (1 ≤ j ≤ k), that pj ≠ qj.
Notes to the samples:
1. In the first sample after the first trip you are either on floor 1, or on floor 3, because |1 - 2| < |2 - 4| and |3 - 2| < |2 - 4|.
2. In the second sample there are two possible sequences: (1, 2); (1, 3). You cannot choose floor 3 for the first trip because in this case no floor can be the floor for the second trip.
3. In the third sample there are no sought sequences, because you cannot choose the floor for the first trip.
Submitted Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
def in_num():
return int(raw_input())
def in_arr():
return map(int,raw_input().split())
def pr_num(n):
stdout.write(str(n)+'\n')
def pr_arr(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
mod=10**9+7
n,a,b,k=in_arr()
dp=[[0 for i in range(n+1)] for j in range(k+1)]
dp[0][a-1]=1
dp[0][a]=-1
b-=1
for i in range(k):
temp=0
for j in range(n+1):
temp=(temp+dp[i][j])%mod
if i and int(abs(b-j))>1:
temp-=dp[i-1][j]
temp%=mod
if j<n:
x=int(abs(b-j))
x-=1
if x<=0:
continue
dp[i+1][max(0,j-x)]=(dp[i+1][max(0,j-x)]+temp)%mod
dp[i+1][min(n,j+x+1)]=(dp[i+1][min(n,j+x+1)]-temp)%mod
#dp[i+1][j]=(dp[i+1][j]-1)%mod
#dp[i+1][j+1]=(dp[i+1][j+1]+1)%mod
if i and int(abs(b-j))>1:
temp+=dp[i-1][j]
temp%=mod
ans=0
temp=0
for i in range(n):
temp+=dp[k][i]
temp%=mod
if int(abs(i-b))>1:
temp-=dp[k-1][i]
temp%=mod
ans+=temp
ans%=mod
if int(abs(i-b))>1:
temp+=dp[k-1][i]
temp%=mod
pr_num(ans)
```
No
| 90,504 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Imagine that you are in a building that has exactly n floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from 1 to n. Now you're on the floor number a. You are very bored, so you want to take the lift. Floor number b has a secret lab, the entry is forbidden. However, you already are in the mood and decide to make k consecutive trips in the lift.
Let us suppose that at the moment you are on the floor number x (initially, you were on floor a). For another trip between floors you choose some floor with number y (y ≠ x) and the lift travels to this floor. As you cannot visit floor b with the secret lab, you decided that the distance from the current floor x to the chosen y must be strictly less than the distance from the current floor x to floor b with the secret lab. Formally, it means that the following inequation must fulfill: |x - y| < |x - b|. After the lift successfully transports you to floor y, you write down number y in your notepad.
Your task is to find the number of distinct number sequences that you could have written in the notebook as the result of k trips in the lift. As the sought number of trips can be rather large, find the remainder after dividing the number by 1000000007 (109 + 7).
Input
The first line of the input contains four space-separated integers n, a, b, k (2 ≤ n ≤ 5000, 1 ≤ k ≤ 5000, 1 ≤ a, b ≤ n, a ≠ b).
Output
Print a single integer — the remainder after dividing the sought number of sequences by 1000000007 (109 + 7).
Examples
Input
5 2 4 1
Output
2
Input
5 2 4 2
Output
2
Input
5 3 4 1
Output
0
Note
Two sequences p1, p2, ..., pk and q1, q2, ..., qk are distinct, if there is such integer j (1 ≤ j ≤ k), that pj ≠ qj.
Notes to the samples:
1. In the first sample after the first trip you are either on floor 1, or on floor 3, because |1 - 2| < |2 - 4| and |3 - 2| < |2 - 4|.
2. In the second sample there are two possible sequences: (1, 2); (1, 3). You cannot choose floor 3 for the first trip because in this case no floor can be the floor for the second trip.
3. In the third sample there are no sought sequences, because you cannot choose the floor for the first trip.
Submitted Solution:
```
n,a,b,k=map(int,input().split())
dp=[[0 for i in range(n+1)] for j in range(2)]
dp[0][a]=1
now=1
last=0
mod=1000000007
for i in range(k):
for j in range(1,n+1):
d=max(abs(j-b)-1,0)
if j!=n:
dp[now][j+1]=(dp[last][j]+dp[now][j+1])%mod
dp[now][min(j+d+1,n)]=(dp[now][min(j+d+1,n)]-dp[last][j])%mod
if j!=1:
dp[now][j]=(dp[now][j]-dp[last][j])%mod
dp[now][max(j-d,1)]=(dp[now][max(j-d,1)]+dp[last][j])%mod
for i1 in range(1,n+1):
dp[now][i1]=(dp[now][i1]+dp[now][i1-1])%mod
dp[last][i1]=0
aux=now
now=last
last=aux
print(sum(dp[last])%mod)
```
No
| 90,505 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Imagine that you are in a building that has exactly n floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from 1 to n. Now you're on the floor number a. You are very bored, so you want to take the lift. Floor number b has a secret lab, the entry is forbidden. However, you already are in the mood and decide to make k consecutive trips in the lift.
Let us suppose that at the moment you are on the floor number x (initially, you were on floor a). For another trip between floors you choose some floor with number y (y ≠ x) and the lift travels to this floor. As you cannot visit floor b with the secret lab, you decided that the distance from the current floor x to the chosen y must be strictly less than the distance from the current floor x to floor b with the secret lab. Formally, it means that the following inequation must fulfill: |x - y| < |x - b|. After the lift successfully transports you to floor y, you write down number y in your notepad.
Your task is to find the number of distinct number sequences that you could have written in the notebook as the result of k trips in the lift. As the sought number of trips can be rather large, find the remainder after dividing the number by 1000000007 (109 + 7).
Input
The first line of the input contains four space-separated integers n, a, b, k (2 ≤ n ≤ 5000, 1 ≤ k ≤ 5000, 1 ≤ a, b ≤ n, a ≠ b).
Output
Print a single integer — the remainder after dividing the sought number of sequences by 1000000007 (109 + 7).
Examples
Input
5 2 4 1
Output
2
Input
5 2 4 2
Output
2
Input
5 3 4 1
Output
0
Note
Two sequences p1, p2, ..., pk and q1, q2, ..., qk are distinct, if there is such integer j (1 ≤ j ≤ k), that pj ≠ qj.
Notes to the samples:
1. In the first sample after the first trip you are either on floor 1, or on floor 3, because |1 - 2| < |2 - 4| and |3 - 2| < |2 - 4|.
2. In the second sample there are two possible sequences: (1, 2); (1, 3). You cannot choose floor 3 for the first trip because in this case no floor can be the floor for the second trip.
3. In the third sample there are no sought sequences, because you cannot choose the floor for the first trip.
Submitted Solution:
```
n,a,b,k=map(int,input().split())
dp=[[0 for i in range(n+1)] for j in range(a)]
dp[0][a]=1
now=1
last=0
mod=1000000007
for i in range(k):
for j in range(1,n+1):
d=abs(j-b)-1
if j!=n:
dp[now][j+1]=(dp[last][j]+dp[now][j+1])%mod
dp[now][min(j+d+1,n)]=(dp[now][min(j+d+1,n)]+dp[last][j])%mod
if j!=1:
dp[now][j]=(dp[now][j]-dp[last][j])%mod
dp[now][max(j-d,1)]=(dp[now][max(j-d,1)]+dp[last][j])%mod
for i in range(1,n+1):
dp[now][i]=(dp[now][i]+dp[now][i-1])%mod
dp[last][i]=0
aux=now
now=last
last=aux
print(sum(dp[last])%mod)
```
No
| 90,506 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Imagine that you are in a building that has exactly n floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from 1 to n. Now you're on the floor number a. You are very bored, so you want to take the lift. Floor number b has a secret lab, the entry is forbidden. However, you already are in the mood and decide to make k consecutive trips in the lift.
Let us suppose that at the moment you are on the floor number x (initially, you were on floor a). For another trip between floors you choose some floor with number y (y ≠ x) and the lift travels to this floor. As you cannot visit floor b with the secret lab, you decided that the distance from the current floor x to the chosen y must be strictly less than the distance from the current floor x to floor b with the secret lab. Formally, it means that the following inequation must fulfill: |x - y| < |x - b|. After the lift successfully transports you to floor y, you write down number y in your notepad.
Your task is to find the number of distinct number sequences that you could have written in the notebook as the result of k trips in the lift. As the sought number of trips can be rather large, find the remainder after dividing the number by 1000000007 (109 + 7).
Input
The first line of the input contains four space-separated integers n, a, b, k (2 ≤ n ≤ 5000, 1 ≤ k ≤ 5000, 1 ≤ a, b ≤ n, a ≠ b).
Output
Print a single integer — the remainder after dividing the sought number of sequences by 1000000007 (109 + 7).
Examples
Input
5 2 4 1
Output
2
Input
5 2 4 2
Output
2
Input
5 3 4 1
Output
0
Note
Two sequences p1, p2, ..., pk and q1, q2, ..., qk are distinct, if there is such integer j (1 ≤ j ≤ k), that pj ≠ qj.
Notes to the samples:
1. In the first sample after the first trip you are either on floor 1, or on floor 3, because |1 - 2| < |2 - 4| and |3 - 2| < |2 - 4|.
2. In the second sample there are two possible sequences: (1, 2); (1, 3). You cannot choose floor 3 for the first trip because in this case no floor can be the floor for the second trip.
3. In the third sample there are no sought sequences, because you cannot choose the floor for the first trip.
Submitted Solution:
```
#!/usr/bin/env python3
import io
import os
import sys
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def printd(*args, **kwargs):
#print(*args, **kwargs, file=sys.stderr)
#print(*args, **kwargs)
pass
def get_str():
return input().decode().strip()
def rint():
return map(int, input().split())
def oint():
return int(input())
mod = 1000000007
n, a, b, k = rint()
a -= 1
b -= 1
d = [0]*n
d[a] = 1
ps = [0]*n
ps[0] = d[0]
for j in range(1, n):
ps[j] = ps[j-1]+d[j]
printd(n, a, b, k)
printd(d, ps)
for i in range(k):
d = [0]*n
for j in range(1, b):
d[j] = ps[j-1]
for j in range(b):
#b-t > t-j
#2*t < b+j
#t < (b+j)/2
if (b+j)%2:
t = (b+j)//2
else:
t = (b+j)//2 - 1
d[j] += ps[t] - ps[j]
ps = [0]*n
ps[0] = d[0]
for j in range(1, n):
ps[j] = (ps[j-1]+d[j])%mod
printd(d,ps)
print(ps[n-1]%mod)
```
No
| 90,507 |
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()
```
| 90,508 |
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])
```
| 90,509 |
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))))
```
| 90,510 |
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())
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))))
```
| 90,511 |
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()
```
| 90,512 |
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
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()
```
| 90,513 |
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
| 90,514 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
Input
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors.
Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000).
The total number of balls doesn't exceed 1000.
Output
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
Examples
Input
3
2
2
1
Output
3
Input
4
1
2
3
4
Output
1680
Note
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
1 2 1 2 3
1 1 2 2 3
2 1 1 2 3
Tags: combinatorics, dp, math
Correct Solution:
```
ans, col, mod = 1, 0, 1000000007
C = [[1 if i <= j else 0 for i in range(1001)] for j in range(1001)]
for i in range(1, 1001):
for j in range(1, i + 1):
C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % mod
for _ in range(int(input())):
a = int(input())
ans *= C[col + a - 1][col]
ans %= mod
col += a
print(ans)
```
| 90,515 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
Input
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors.
Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000).
The total number of balls doesn't exceed 1000.
Output
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
Examples
Input
3
2
2
1
Output
3
Input
4
1
2
3
4
Output
1680
Note
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
1 2 1 2 3
1 1 2 2 3
2 1 1 2 3
Tags: combinatorics, dp, math
Correct Solution:
```
mx=1001
mod=1000000007
nCr=[[0 for i in range(mx)] for j in range(mx)]
nCr[0][0]=1
for i in range(1,mx):
nCr[i][0]=1
for j in range(1,mx):
nCr[i][j]=nCr[i-1][j-1]+nCr[i-1][j]
n=int(input())
l=[]
for i in range(n):
l.append(int(input()))
res=1
total=0
for i in range(n):
res=(res*nCr[total+l[i]-1][l[i]-1])%mod
total+=l[i]
print(res)
```
| 90,516 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
Input
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors.
Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000).
The total number of balls doesn't exceed 1000.
Output
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
Examples
Input
3
2
2
1
Output
3
Input
4
1
2
3
4
Output
1680
Note
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
1 2 1 2 3
1 1 2 2 3
2 1 1 2 3
Tags: combinatorics, dp, math
Correct Solution:
```
from math import factorial
k=int(input())
ans,s=1,0
for i in range(k):
ci=int(input())
ans=(ans*factorial(s+ci-1)//(factorial(ci-1)*factorial(s)))%1000000007
s+=ci
print(ans)
```
| 90,517 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
Input
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors.
Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000).
The total number of balls doesn't exceed 1000.
Output
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
Examples
Input
3
2
2
1
Output
3
Input
4
1
2
3
4
Output
1680
Note
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
1 2 1 2 3
1 1 2 2 3
2 1 1 2 3
Tags: combinatorics, dp, math
Correct Solution:
```
from sys import stdin
n=int(stdin.readline())
from math import factorial as f
lst=[int(stdin.readline()) for _ in range(n)]
summa=sum(lst)
res=1
for i,x in enumerate(reversed(lst)):
x-=1
summa-=1
res*=(f(summa)//(f(summa-x)*f(x)))
res=res%1000000007
summa-=x
print(res)
```
| 90,518 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
Input
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors.
Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000).
The total number of balls doesn't exceed 1000.
Output
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
Examples
Input
3
2
2
1
Output
3
Input
4
1
2
3
4
Output
1680
Note
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
1 2 1 2 3
1 1 2 2 3
2 1 1 2 3
Tags: combinatorics, dp, math
Correct Solution:
```
mod = 1000000007
def pow1(a,b):
ans = 1
c=a
while(b):
#print('estoy en el while')
if(b & 1):
ans=ans*c%mod
b>>=1
c=c*c%mod
return ans
def factorial(a,b):
factor =fact[a]*pow1(fact[b]*fact[a-b]%mod,mod-2)%mod
return factor
fact = []
for i in range(1000010):
fact.append(0)
a = []
for i in range(1010):
a.append(0)
#================MAIN===============
fact[0] = 1
for i in range(1,1000000):
fact[i]=fact[i-1]*i%mod
n = int(input())
#print(n)
sum = 0
for i in range(0,n):
a[i] = int(input())
sum+=a[i]
#print (a)
#print(sum)
ans = 1
i = n-1
while(i>-1):
ans=ans*factorial(sum-1,a[i]-1)%mod
#print(ans)
sum-=a[i]
i-=1
#print(f"suma:{sum}")
print(ans)
```
| 90,519 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
Input
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors.
Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000).
The total number of balls doesn't exceed 1000.
Output
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
Examples
Input
3
2
2
1
Output
3
Input
4
1
2
3
4
Output
1680
Note
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
1 2 1 2 3
1 1 2 2 3
2 1 1 2 3
Tags: combinatorics, dp, math
Correct Solution:
```
# Author : nitish420 --------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
mod=10**9+7
# sys.setrecursionlimit(10**6)
# mxm=sys.maxsize
# from functools import lru_cache
fact=[1]*(1002)
for i in range(2,1002):
fact[i]=(fact[i-1]*i)%mod
def ncr(n,r):
num=fact[n]
den=(fact[n-r]*fact[r])%mod
return (num*(pow(den,mod-2,mod)))%mod
def main():
k=int(input())
dp=[0]*(k+1)
dp[1]=1
dff=0
m=int(input())
total=m
for i in range(k-1):
m=int(input())
dff=m-1
total+=m
dp[i+2]=(dp[i+1]*ncr(total-1,dff))%mod
print(dp[k])
#----------------------------------------------------------------------------------------
def nouse0():
# This is to save my code from plag due to use of FAST IO template in it.
a=420
b=420
print(f'i am nitish{(a+b)//2}')
def nouse1():
# This is to save my code from plag due to use of FAST IO template in it.
a=420
b=420
print(f'i am nitish{(a+b)//2}')
def nouse2():
# This is to save my code from plag due to use of FAST IO template in it.
a=420
b=420
print(f'i am nitish{(a+b)//2}')
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# endregion
if __name__ == '__main__':
main()
```
| 90,520 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
Input
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors.
Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000).
The total number of balls doesn't exceed 1000.
Output
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
Examples
Input
3
2
2
1
Output
3
Input
4
1
2
3
4
Output
1680
Note
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
1 2 1 2 3
1 1 2 2 3
2 1 1 2 3
Tags: combinatorics, dp, math
Correct Solution:
```
"""
Author - Satwik Tiwari .
4th Oct , 2020 - Sunday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
# from itertools import *
from heapq import *
from math import gcd, factorial,floor,ceil
from copy import deepcopy
from collections import deque
# from collections import Counter as counter # Counter(list) return a dict with {key: count}
# from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
# from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
#==============================================================================================
#fast I/O region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
#===============================================================================================
#some shortcuts
mod = 10**9+7
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n") #as stdout.write always print sring.
def testcase(t):
for pp in range(t):
solve(pp)
def printlist(a) :
for p in range(0,len(a)):
out(str(a[p]) + ' ')
def google(p):
print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) : # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
#===============================================================================================
# code here ;))
def nCr_mod(n,r,max_n=2 * 10**5, mod=10**9 + 7):
max_n = min(max_n, mod - 1)
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 do_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
return do_nCr_mod(n,r)
"""
print nCr(4,3)
"""
def solve(case):
n = int(inp())
ans = 1
total = 0
for i in range(n):
x = int(inp())
total+= x
ans*=ncr(total-1,x-1)%mod
print(ans%mod)
testcase(1)
# testcase(int(inp()))
```
| 90,521 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
Input
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors.
Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000).
The total number of balls doesn't exceed 1000.
Output
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
Examples
Input
3
2
2
1
Output
3
Input
4
1
2
3
4
Output
1680
Note
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
1 2 1 2 3
1 1 2 2 3
2 1 1 2 3
Tags: combinatorics, dp, math
Correct Solution:
```
# coding: utf-8
# In[6]:
matrix = [[0 for x in range(1001)] for y in range(1001)]
mod = 1000000007
def pascal():
matrix[0][0]=1;
for i in range(1001):
for j in range(1001):
if j==0 or j==i:
matrix[i][j]=1
else:
matrix[i][j] = (matrix[i-1][j-1]+matrix[i-1][j])%mod
a = int(input())
b = []
for i in range(a):
b.append(int(input()))
pascal()
r = 1
s = b[0]
for i in range(1,a):
r = (r*matrix[s + b[i]-1][b[i]-1])%mod
s += b[i]
print(r)
```
| 90,522 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
Input
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors.
Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000).
The total number of balls doesn't exceed 1000.
Output
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
Examples
Input
3
2
2
1
Output
3
Input
4
1
2
3
4
Output
1680
Note
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
1 2 1 2 3
1 1 2 2 3
2 1 1 2 3
Submitted Solution:
```
pt = []
for i in range(1000):
pt.append([0] * (i + 1))
pt[i][0] = pt[i][i] = 1
for j in range(1, i):
pt[i][j] = pt[i - 1][j - 1] + pt[i - 1][j]
k, s, v = int(input()), int(input()), 1
for i in range(1, k):
c = int(input())
v = v * pt[s + c - 1][c - 1] % 1000000007
s += c
print(v)
```
Yes
| 90,523 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
Input
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors.
Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000).
The total number of balls doesn't exceed 1000.
Output
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
Examples
Input
3
2
2
1
Output
3
Input
4
1
2
3
4
Output
1680
Note
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
1 2 1 2 3
1 1 2 2 3
2 1 1 2 3
Submitted Solution:
```
from sys import stdin
input=lambda : stdin.readline().strip()
from math import ceil,sqrt,factorial,gcd
from collections import deque
from bisect import bisect_right
k=int(input())
ans=1
total=0
MOD=1000000007
for i in range(k):
z=int(input())
ans=(ans*factorial(total+z-1)//factorial(total)//factorial(z-1))%MOD
total+=z
print(ans)
```
Yes
| 90,524 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
Input
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors.
Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000).
The total number of balls doesn't exceed 1000.
Output
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
Examples
Input
3
2
2
1
Output
3
Input
4
1
2
3
4
Output
1680
Note
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
1 2 1 2 3
1 1 2 2 3
2 1 1 2 3
Submitted Solution:
```
from math import *
from collections import deque
from copy import deepcopy
import sys
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def multi(): return map(int,input().split())
def strmulti(): return map(str, inp().split())
def lis(): return list(map(int, inp().split()))
def lcm(a,b): return (a*b)//gcd(a,b)
def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))
def stringlis(): return list(map(str, inp().split()))
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def printlist(a) :
print(' '.join(str(a[i]) for i in range(len(a))))
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
#copied functions end
#start coding
k=int(input())
ans=1
sum=0
for i in range(k):
num=int(input())
sum+=num
ans*=(ncr(sum-1,num-1))
# print(ans)
print(ans%1000000007)
```
Yes
| 90,525 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
Input
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors.
Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000).
The total number of balls doesn't exceed 1000.
Output
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
Examples
Input
3
2
2
1
Output
3
Input
4
1
2
3
4
Output
1680
Note
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
1 2 1 2 3
1 1 2 2 3
2 1 1 2 3
Submitted Solution:
```
def binomialCoefficient(n, k):
if(k > n - k):
k = n - k
res = 1
for i in range(k):
res = res * (n - i)
res = res // (i + 1)
return res
k=int(input())
sum=0
ans=1
m=1000000007
for i in range(k):
a=int(input())
ans=(ans%m)*(binomialCoefficient(sum+a-1,a-1))%m
sum+=a
print(ans)
```
Yes
| 90,526 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
Input
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors.
Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000).
The total number of balls doesn't exceed 1000.
Output
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
Examples
Input
3
2
2
1
Output
3
Input
4
1
2
3
4
Output
1680
Note
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
1 2 1 2 3
1 1 2 2 3
2 1 1 2 3
Submitted Solution:
```
k=int(input())
l=[int(input()) for i in range(k)]
s=0
ans=[0]*k
ans[0]=1
MOD=10**9+7
fact=[0]*(10**6+5)
fact[0]=1
for i in range(1,10**6+5):
fact[i]=(fact[i-1]*i)%MOD
#print(fact[0:10])
def c(n,k):
if k>=n:
return 1
if k==0 or k==n:
return 1
return fact[n]//(fact[k]*fact[n-k])%MOD
ans=1
sm=l[0]
for i in range(1,k):
curr=l[i]
#ans[i]=ans[i-1]+
ans=ans*(c(sm+curr-1,curr-1))
ans%=MOD
sm+=l[i]
print(ans)
```
No
| 90,527 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
Input
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors.
Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000).
The total number of balls doesn't exceed 1000.
Output
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
Examples
Input
3
2
2
1
Output
3
Input
4
1
2
3
4
Output
1680
Note
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
1 2 1 2 3
1 1 2 2 3
2 1 1 2 3
Submitted Solution:
```
from functools import reduce
from operator import mul
mod = 10 ** 9 + 7
k = int(input())
cs = [int(input()) for _ in range(k)]
cumcs = cs[:]
for i in range(1, len(cs)):
cumcs[i] += cumcs[i - 1]
def C(n, k):
num = reduce(mul, range(n, n - k, -1), 1)
denom = reduce(mul, range(k, 0, -1), 1)
return (num // denom) % mod
res = 1
for cum, c in zip(cumcs, cs):
res *= C(cum - 1, c - 1)
print(res)
```
No
| 90,528 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
Input
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors.
Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000).
The total number of balls doesn't exceed 1000.
Output
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
Examples
Input
3
2
2
1
Output
3
Input
4
1
2
3
4
Output
1680
Note
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
1 2 1 2 3
1 1 2 2 3
2 1 1 2 3
Submitted Solution:
```
from math import *
from collections import deque
from copy import deepcopy
import sys
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def multi(): return map(int,input().split())
def strmulti(): return map(str, inp().split())
def lis(): return list(map(int, inp().split()))
def lcm(a,b): return (a*b)//gcd(a,b)
def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))
def stringlis(): return list(map(str, inp().split()))
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def printlist(a) :
print(' '.join(str(a[i]) for i in range(len(a))))
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
#copied functions end
#start coding
k=int(input())
ans=1
sum=0
for i in range(k):
num=int(input())
sum+=num
ans*=(ncr(sum-1,num-1))
# print(ans)
print(ans)
```
No
| 90,529 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.
Input
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors.
Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000).
The total number of balls doesn't exceed 1000.
Output
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.
Examples
Input
3
2
2
1
Output
3
Input
4
1
2
3
4
Output
1680
Note
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:
1 2 1 2 3
1 1 2 2 3
2 1 1 2 3
Submitted Solution:
```
from sys import stdin,stdout
from collections import defaultdict
import math
#stdin = open('input.txt','r')
I = stdin.readline
P = stdout.write
k = int(I())
tot = 0
ans = 1
for i in range(k):
now = int(I())
ans*=math.factorial(tot+now-1)//math.factorial(tot)//math.factorial(now-1)
tot+=now
print(ans)
```
No
| 90,530 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a string S of length n with each character being one of the first m lowercase English letters.
Calculate how many different strings T of length n composed from the first m lowercase English letters exist such that the length of LCS (longest common subsequence) between S and T is n - 1.
Recall that LCS of two strings S and T is the longest string C such that C both in S and T as a subsequence.
Input
The first line contains two numbers n and m denoting the length of string S and number of first English lowercase characters forming the character set for strings (1 ≤ n ≤ 100 000, 2 ≤ m ≤ 26).
The second line contains string S.
Output
Print the only line containing the answer.
Examples
Input
3 3
aaa
Output
6
Input
3 3
aab
Output
11
Input
1 2
a
Output
1
Input
10 9
abacadefgh
Output
789
Note
For the first sample, the 6 possible strings T are: aab, aac, aba, aca, baa, caa.
For the second sample, the 11 possible strings T are: aaa, aac, aba, abb, abc, aca, acb, baa, bab, caa, cab.
For the third sample, the only possible string T is b.
Tags: dp, greedy
Correct Solution:
```
def main():
n, m = map(int, input().split())
s = input()
k = sum(s[i] != s[i - 1] for i in range(1, n)) + 1
x = i = 0
while i < n - 1:
if s[i] != s[i + 1]:
j = i
while i + 2 < n and s[i] == s[i + 2]:
i += 1
j = (i - j) + 2
x += j * (j - 1) // 2
i += 1
ans = k * (m * n - n) - x
print(ans)
main()
```
| 90,531 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3
Tags: data structures, dfs and similar, dsu, trees
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
class SegmentTree:
def __init__(self, n, op, e):
self.n = n
self.op = op
self.e = e
self.size = 2 ** ((n - 1).bit_length())
self.node = [self.e] * (2 * self.size)
def __getitem__(self, i):
return self.node[i + self.size]
def __setitem__(self, i, val):
i += self.size
self.node[i] = val
while i > 1:
i >>= 1
self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])
def build(self, array):
for i, val in enumerate(array, self.size):
self.node[i] = val
for i in range(self.size - 1, 0, -1):
self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])
def all_fold(self):
return self.node[1]
def fold(self, l, r):
l, r = l + self.size, r + self.size
vl, vr = self.e, self.e
while l < r:
if l & 1:
vl = self.op(vl, self.node[l])
l += 1
if r & 1:
r -= 1
vr = self.op(self.node[r], vr)
l, r = l >> 1, r >> 1
return self.op(vl, vr)
def topological_sorted(tree, root=None):
n = len(tree)
par = [-1] * n
tp_order = []
for v in range(n):
if par[v] != -1 or (root is not None and v != root):
continue
stack = [v]
while stack:
v = stack.pop()
tp_order.append(v)
for nxt_v in tree[v]:
if nxt_v == par[v]:
continue
par[nxt_v] = v
stack.append(nxt_v)
return tp_order, par
def dsu_on_tree(tree, root):
n = len(tree)
tp_order, par = topological_sorted(tree, root)
# 有向木の構築
di_tree = [[] for i in range(n)]
for v in range(n):
for nxt_v in tree[v]:
if nxt_v == par[v]:
continue
di_tree[v].append(nxt_v)
# 部分木サイズの計算
sub_size = [1] * n
for v in tp_order[::-1]:
for nxt_v in di_tree[v]:
sub_size[v] += sub_size[nxt_v]
# 有向木のDFS帰りがけ順の構築
di_tree = [sorted(tr, key=lambda v: sub_size[v]) for tr in di_tree]
keeps = [0] * n
for v in range(n):
di_tree[v] = di_tree[v][:-1][::-1] + di_tree[v][-1:]
for chi_v in di_tree[v][:-1]:
keeps[chi_v] = 1
tp_order, _ = topological_sorted(di_tree, root)
# counts = {}
def add(sub_root, val):
stack = [sub_root]
while stack:
v = stack.pop()
vals = st[colors[v]]
st[colors[v]] = (vals[0] + val, vals[1])
# counts[colors[v]] = counts.get(colors[v], 0) + val
for chi_v in di_tree[v]:
stack.append(chi_v)
for v in tp_order[::-1]:
for chi_v in di_tree[v]:
if keeps[chi_v] == 1:
add(chi_v, 1)
vals = st[colors[v]]
st[colors[v]] = (vals[0] + 1, vals[1])
# counts[colors[v]] = counts.get(colors[v], 0) + 1
ans[v] = st.all_fold()[1]
if keeps[v] == 1:
add(v, -1)
n = int(input())
colors = list(map(int, input().split()))
edges = [list(map(int, input().split())) for i in range(n - 1)]
tree = [[] for i in range(n)]
for u, v in edges:
u -= 1
v -= 1
tree[u].append(v)
tree[v].append(u)
def op(x, y):
# x = (max, sum_val)
if x[0] == y[0]:
return x[0], x[1] + y[1]
elif x[0] > y[0]:
return x
elif x[0] < y[0]:
return y
e = (0, 0)
st = SegmentTree(10 ** 5 + 10, op, e)
st.build([(0, i) for i in range(10 ** 5 + 10)])
ans = [0] * n
dsu_on_tree(tree, 0)
print(*ans)
```
| 90,532 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3
Tags: data structures, dfs and similar, dsu, trees
Correct Solution:
```
# dsu on tree
# logistics: if the problem asked to compute some value of a subtree
# naive method would be for each node, compute the query value which would be O(n^2) because of doing dfs for each node
# we want to reuse some information of subtree so that we do not need to recompute it
# we can use concept of heavy-light decomposition which we divide the value into light nodes and heavy node
# complexity proof:
from collections import defaultdict as df
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
timer = 0
@bootstrap
def dfs(v, p):
global timer
tin[v] = timer
ver[timer] = v
timer += 1
for child in tree[v]:
if child != p:
yield dfs(child, v)
size[v] += size[child]
size[v] += 1
tout[v] = timer
timer += 1
yield 0
def operation(mx, v, x):
ans[cnt[color[v]]] -= color[v]
cnt[color[v]] += x
ans[cnt[color[v]]] += color[v]
mx = max(mx, cnt[color[v]])
return mx
@bootstrap
def dfs1(v, pa, keep):
mx = 0;mx_child = -1; big_child = -1
for child in tree[v]:
if child != pa and size[child] > mx_child:
mx_child = size[child]
big_child = child
for child in tree[v]:
if child != pa and child != big_child:
yield dfs1(child, v, 0)
if big_child != -1:
temp = yield dfs1(big_child, v, 1)
mx = max(temp, mx)
for child in tree[v]:
if child != pa and child != big_child:
for p in range(tin[child], tout[child]):
# add operation
#cnt[dist[ver[p]]] += 1
mx = operation(mx, ver[p], 1)
#add itself
mx = operation(mx,v,1)
#print(v,mx)
res[v - 1] = ans[mx]
#put answer above
if not keep:
for p in range(tin[v], tout[v]):
# cancel operation
#cnt[dist[ver[p]]] -= 1
mx = operation(mx, ver[p], -1)
yield mx
if __name__ == '__main__':
n = int(input().strip())
#arr = list(map(int, input().split()))
color = [0] + list(map(int, input().split()))
tree = df(list)
for i in range(1,n):
u,v = map(int, input().split())
tree[u].append(v)
tree[v].append(u)
#tree[arr[i - 1]].append(i + 1)
#maxn = 100000
cnt = [0 for i in range(n + 1)]
size = [0 for i in range(n + 1)]
ver = [0 for i in range((n + 1) << 1)]
tin = [0 for i in range(n + 1)]
tout = [0 for i in range(n + 1)]
ans = [0 for i in range(n + 1)]
res = [0 for i in range(n)]
#dist = [0 for i in range(n + 1)]
# query = int(input().strip())
# queries = df(list)
# res = df(int)
# for i in range(query):
# u, d = map(int, input().split())
# queries[u].append((d,i))
dfs(1, 1)
dfs1(1,1,1)
#res[0] = ans
print(' '.join(str(i) for i in res))
```
| 90,533 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3
Tags: data structures, dfs and similar, dsu, trees
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
class SegmentTree:
def __init__(self, n, op, e):
self.n = n
self.op = op
self.e = e
self.size = 2 ** ((n - 1).bit_length())
self.node = [self.e] * (2 * self.size)
def __getitem__(self, i):
return self.node[i + self.size]
def __setitem__(self, i, val):
i += self.size
self.node[i] = val
while i > 1:
i >>= 1
self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])
def build(self, array):
for i, val in enumerate(array, self.size):
self.node[i] = val
for i in range(self.size - 1, 0, -1):
self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])
def all_fold(self):
return self.node[1]
def fold(self, l, r):
l, r = l + self.size, r + self.size
vl, vr = self.e, self.e
while l < r:
if l & 1:
vl = self.op(vl, self.node[l])
l += 1
if r & 1:
r -= 1
vr = self.op(self.node[r], vr)
l, r = l >> 1, r >> 1
return self.op(vl, vr)
def topological_sorted(tree, root=None):
n = len(tree)
par = [-1] * n
tp_order = []
for v in range(n):
if par[v] != -1 or (root is not None and v != root):
continue
stack = [v]
while stack:
v = stack.pop()
tp_order.append(v)
for nxt_v in tree[v]:
if nxt_v == par[v]:
continue
par[nxt_v] = v
stack.append(nxt_v)
return tp_order, par
def dsu_on_tree(tree, root):
n = len(tree)
tp_order, par = topological_sorted(tree, root)
# 有向木の構築
di_tree = [[] for i in range(n)]
for v in range(n):
for nxt_v in tree[v]:
if nxt_v == par[v]:
continue
di_tree[v].append(nxt_v)
# 部分木サイズの計算
sub_size = [1] * n
for v in tp_order[::-1]:
for nxt_v in di_tree[v]:
sub_size[v] += sub_size[nxt_v]
# 有向木のDFS行きがけ順の構築
di_tree = [sorted(tr, key=lambda v: sub_size[v]) for tr in di_tree]
keeps = [0] * n
for v in range(n):
di_tree[v] = di_tree[v][:-1][::-1] + di_tree[v][-1:]
for chi_v in di_tree[v][:-1]:
keeps[chi_v] = 1
tp_order, _ = topological_sorted(di_tree, root)
# 加算もしくは減算の実行
# counts = {}
def add(sub_root, val):
stack = [sub_root]
while stack:
v = stack.pop()
vals = st[colors[v]]
st[colors[v]] = (vals[0] + val, vals[1])
# counts[colors[v]] = counts.get(colors[v], 0) + val
for chi_v in di_tree[v]:
stack.append(chi_v)
# 有向木のDFS帰りがけ順で処理
for v in tp_order[::-1]:
for chi_v in di_tree[v]:
if keeps[chi_v] == 1:
add(chi_v, 1)
# ここでクエリを実行する
vals = st[colors[v]]
st[colors[v]] = (vals[0] + 1, vals[1])
# counts[colors[v]] = counts.get(colors[v], 0) + 1
ans[v] = st.all_fold()[1]
if keeps[v] == 1:
add(v, -1)
n = int(input())
colors = list(map(int, input().split()))
edges = [list(map(int, input().split())) for i in range(n - 1)]
tree = [[] for i in range(n)]
for u, v in edges:
u -= 1
v -= 1
tree[u].append(v)
tree[v].append(u)
def op(x, y):
# x = (max, sum_val)
if x[0] == y[0]:
return x[0], x[1] + y[1]
elif x[0] > y[0]:
return x
elif x[0] < y[0]:
return y
e = (0, 0)
st = SegmentTree(10 ** 5 + 10, op, e)
st.build([(0, i) for i in range(10 ** 5 + 10)])
ans = [0] * n
dsu_on_tree(tree, 0)
print(*ans)
```
| 90,534 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3
Tags: data structures, dfs and similar, dsu, trees
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
class SegmentTree:
def __init__(self, n, op, e):
self.n = n
self.op = op
self.e = e
self.size = 2 ** ((n - 1).bit_length())
self.node = [self.e] * (2 * self.size)
def __getitem__(self, i):
return self.node[i + self.size]
def __setitem__(self, i, val):
i += self.size
self.node[i] = val
while i > 1:
i >>= 1
self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])
def build(self, array):
for i, val in enumerate(array, self.size):
self.node[i] = val
for i in range(self.size - 1, 0, -1):
self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])
def all_fold(self):
return self.node[1]
def fold(self, l, r):
l, r = l + self.size, r + self.size
vl, vr = self.e, self.e
while l < r:
if l & 1:
vl = self.op(vl, self.node[l])
l += 1
if r & 1:
r -= 1
vr = self.op(self.node[r], vr)
l, r = l >> 1, r >> 1
return self.op(vl, vr)
def topological_sorted(tree, root=None):
n = len(tree)
par = [-1] * n
tp_order = []
for v in range(n):
if par[v] != -1 or (root is not None and v != root):
continue
stack = [v]
while stack:
v = stack.pop()
tp_order.append(v)
for nxt_v in tree[v]:
if nxt_v == par[v]:
continue
par[nxt_v] = v
stack.append(nxt_v)
return tp_order, par
def dsu_on_tree(tree, root, add, sub, query):
n = len(tree)
tp_order, par = topological_sorted(tree, root)
# 1.有向木の構築
di_tree = [[] for i in range(n)]
for v in range(n):
for nxt_v in tree[v]:
if nxt_v == par[v]:
continue
di_tree[v].append(nxt_v)
# 2.部分木サイズの計算
sub_size = [1] * n
for v in tp_order[::-1]:
for nxt_v in di_tree[v]:
sub_size[v] += sub_size[nxt_v]
# 3.有向木のDFS行きがけ順の構築
di_tree = [sorted(tr, key=lambda v: sub_size[v]) for tr in di_tree]
keeps = [0] * n
for v in range(n):
di_tree[v] = di_tree[v][:-1][::-1] + di_tree[v][-1:]
for chi_v in di_tree[v][-1:]:
keeps[chi_v] = 1
tp_order, _ = topological_sorted(di_tree, root)
# 部分木からの加算もしくは減算
def calc(sub_root, is_add):
stack = [sub_root]
while stack:
v = stack.pop()
add(v) if is_add else sub(v)
for chi_v in di_tree[v]:
stack.append(chi_v)
# 4.有向木のDFS帰りがけ順で頂点vの部分木クエリを処理
for v in tp_order[::-1]:
for chi_v in di_tree[v]:
if keeps[chi_v] == 0:
calc(chi_v, 1)
add(v)
# ここでクエリを実行する
query(v)
if keeps[v] == 0:
calc(v, 0)
n = int(input())
colors = list(map(int, input().split()))
edges = [list(map(int, input().split())) for i in range(n - 1)]
tree = [[] for i in range(n)]
for u, v in edges:
u -= 1
v -= 1
tree[u].append(v)
tree[v].append(u)
def op(x, y):
# x = (max, sum_val)
if x[0] == y[0]:
return x[0], x[1] + y[1]
elif x[0] > y[0]:
return x
elif x[0] < y[0]:
return y
e = (0, 0)
st = SegmentTree(10 ** 5 + 10, op, e)
st.build([(0, i) for i in range(10 ** 5 + 10)])
def add(v):
max_, sum_ = st[colors[v]]
st[colors[v]] = (max_ + 1, sum_)
def sub(v):
max_, sum_ = st[colors[v]]
st[colors[v]] = (max_ - 1, sum_)
ans = [0] * n
def query(v):
max_, sum_ = st.all_fold()
ans[v] = sum_
dsu_on_tree(tree, 0, add, sub, query)
print(*ans)
```
| 90,535 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3
Tags: data structures, dfs and similar, dsu, trees
Correct Solution:
```
from collections import defaultdict
class SumDefaultdict(defaultdict):
def __init__(self, *args, **kwargs) -> None:
super().__init__(int, *args, **kwargs)
self.mx = max(self.values())
self.mx_sum = sum(c for c, v in self.items() if v == self.mx)
def sumadd(self, map):
for bb, val in map.items():
if val > 0:
self[bb] += val
if self[bb] > self.mx:
self.mx = self[bb]
self.mx_sum = bb
elif self[bb] == self.mx:
self.mx_sum += bb
def go():
n = int(input())
c = list(map(int, input().split()))
edges = [[] for _ in range(n)]
for _ in range(n - 1):
a, b = map(lambda x: int(x) - 1, input().split())
edges[a].append(b)
edges[b].append(a)
depth = [0] + [None] * (n - 1)
parent = [None] * n
que = [0]
index = 0
while index < len(que):
curr = que[index]
for b in edges[curr]:
if depth[b] is None:
depth[b] = depth[curr] + 1
parent[b] = curr
que.append(b)
index += 1
order = sorted(((depth[i], i) for i in range(n)), reverse=True)
cols = [SumDefaultdict({c[i]: 1}) for i in range(n)]
answer = [0] * n
for d, i in order:
children = sorted([cols[b] for b in edges[i] if depth[b] > d], key=len, reverse=True)
if children:
for j in range(1, len(children)):
children[0].sumadd(children[j])
children[0].sumadd({c[i]: 1})
cols[i] = children[0]
# max_val = max(cols[i].values())
answer[i] = cols[i].mx_sum
print(' '.join(map(str, answer)))
go()
```
| 90,536 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3
Tags: data structures, dfs and similar, dsu, trees
Correct Solution:
```
import sys
from collections import Counter
n = int(input())
color = list(map(int, input().split()))
adj = [[] for _ in range(n)]
for _ in range(n-1):
u, v = map(int, sys.stdin.readline().split())
u -= 1
v -= 1
adj[u].append(v)
adj[v].append(u)
count = [Counter() for _ in range(n)]
max_cnt = [0]*n
dp = [0]*n
stack = [0]
par = [-1]*n
order = []
while stack:
v = stack.pop()
order.append(v)
for d in adj[v]:
if d != par[v]:
stack.append(d)
par[d] = v
for v in reversed(order):
child = [i for i in adj[v] if i != par[v]]
child.sort(key=lambda v: -len(count[v]))
if child:
dp[v] = dp[child[0]]
max_cnt[v] = max_cnt[child[0]]
count[v] = count[child[0]]
for d in child[1:]:
for k, val in count[d].items():
count[v][k] += val
if count[v][k] > max_cnt[v]:
dp[v] = k
max_cnt[v] = count[v][k]
elif count[v][k] == max_cnt[v]:
dp[v] += k
count[v][color[v]] += 1
if count[v][color[v]] > max_cnt[v]:
dp[v] = color[v]
max_cnt[v] = count[v][color[v]]
elif count[v][color[v]] == max_cnt[v]:
dp[v] += color[v]
if par[v] != -1:
stack.append(par[v])
print(*dp)
```
| 90,537 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3
Tags: data structures, dfs and similar, dsu, trees
Correct Solution:
```
def main():
import sys
from collections import deque
input = sys.stdin.readline
N = int(input())
color = list(map(int, input().split()))
color.insert(0, 0)
adj = [[] for _ in range(N+1)]
for _ in range(N-1):
a, b = map(int, input().split())
adj[a].append(b)
adj[b].append(a)
que = deque()
que.append(1)
seen = [-1] * (N+1)
seen[1] = 0
par = [0] * (N+1)
child = [[] for _ in range(N+1)]
seq = []
while que:
v = que.popleft()
seq.append(v)
for u in adj[v]:
if seen[u] == -1:
seen[u] = seen[v] + 1
par[u] = v
child[v].append(u)
que.append(u)
seq.reverse()
cnt = [{color[i]: 1} for i in range(N+1)]
cnt_size = [1] * (N+1)
dom_num = [1] * (N+1)
ans = [color[i] for i in range(N+1)]
for v in seq:
big = cnt[v]
size_big = cnt_size[v]
for u in child[v]:
small = cnt[u]
size_small = cnt_size[u]
if size_big < size_small:
small, big = big, small
dom_num[v] = dom_num[u]
ans[v] = ans[u]
size_big += size_small
for c in small:
if c not in big:
big[c] = small[c]
else:
big[c] += small[c]
cnt_size[v] += small[c]
if big[c] > dom_num[v]:
dom_num[v] = big[c]
ans[v] = c
elif big[c] == dom_num[v]:
ans[v] += c
cnt_size[v] = size_big
cnt[v] = big
print(*ans[1:])
#print(child)
#print(cnt)
#print(cnt_size)
if __name__ == '__main__':
main()
```
| 90,538 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3
Tags: data structures, dfs and similar, dsu, trees
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
_str = str
BUFSIZE = 8192
def str(x=b''):
return x if type(x) is bytes else _str(x).encode()
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
def inp():
return sys.stdin.readline().rstrip()
def mpint():
return map(int, inp().split(' '))
def itg():
return int(inp())
# ############################## import
# from ACgenerator.Y_Testing import get_code
def tree_bfs(tree, flat=True, start=0) -> list:
stack = [start]
result = []
while stack:
new_stack = []
if flat:
result.extend(stack)
else:
result.append(stack)
for node in stack:
new_stack.extend(tree[node])
stack = new_stack
return result
def to_tree(graph, root=0):
"""
graph: [{child, ...}, ...] (undirected)
:return directed graph that parent -> children
"""
stack = [[root]]
while stack:
if not stack[-1]:
del stack[-1]
continue
parent = stack[-1].pop()
for child in graph[parent]:
graph[child].discard(parent)
stack.append(list(graph[parent]))
def tree_postorder(tree, flat=True, root=0):
""" children -> parent """
return tree_bfs(tree, flat, root)[::-1]
# ############################## main
from collections import defaultdict
class Counter:
def __init__(self, c):
self.ans = c
self.c_t = defaultdict(lambda: 0)
self.mx = self.c_t[c] = 1
self.t_c = defaultdict(set)
self.t_c[1] = {c}
def merge(self, other):
for c, t in other.c_t.items():
self.add(c, t)
def add(self, c, t):
old_t = self.c_t[c]
self.c_t[c] = new_t = old_t + t
self.t_c[old_t].discard(c)
self.t_c[new_t].add(c)
if new_t == self.mx:
self.ans += c
elif new_t > self.mx:
self.mx = new_t
self.ans = c
def __len__(self):
return len(self.c_t)
def __repr__(self):
return _str(self.ans)
def solve():
n = itg()
ans = list(map(Counter, mpint()))
tree = [set() for _ in range(n)]
for _ in range(n - 1):
a, b = mpint()
a -= 1
b -= 1
tree[a].add(b)
tree[b].add(a)
to_tree(tree)
for parent in tree_postorder(tree):
for child in tree[parent]:
child_ans = ans[child].ans
if len(ans[parent]) < len(ans[child]):
ans[parent], ans[child] = ans[child], ans[parent]
ans[parent].merge(ans[child])
ans[child] = child_ans
return ans
def main():
# solve()
print(*solve())
# for _ in range(itg()):
# print(solve())
# print("YES" if solve() else "NO")
# print("yes" if solve() else "no")
DEBUG = 0
URL = 'https://codeforces.com/contest/600/problem/E'
if __name__ == '__main__':
if DEBUG == 1:
import requests # ImportError: cannot import name 'md5' from 'sys' (unknown location)
from ACgenerator.Y_Test_Case_Runner import TestCaseRunner
runner = TestCaseRunner(main, URL)
inp = runner.input_stream
print = runner.output_stream
runner.checking()
elif DEBUG == 2:
main()
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
main()
# Please check!
```
| 90,539 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3
Submitted Solution:
```
import sys
import collections
import random
input = sys.stdin.readline
d = collections.defaultdict(list)
n = int(input())
col = [int(i) for i in input().split() ]
for _ in range(n-1):
a, b = map(int, input().split() )
d[a-1].append(b-1)
d[b-1].append(a-1)
def dfs(parent, node, que, cnt, m):
makenew = False
for i in d[node]:
if i == parent: continue
if makenew:
q1, c1 = {}, {}
dfs(node, i, q1, c1, [0])
for key in c1: #key = color
if key in cnt:
que[cnt[key]] -= key
cnt[key] += c1[key]
else:
cnt[key] = c1[key]
if cnt[key] not in que:
que[cnt[key]] = 0
que[cnt[key]] += key
if m[0] < cnt[key]:
m[0] = cnt[key]
continue
dfs(node, i, que, cnt, m)
makenew = True
# leaves finish here:
if len(que) == 0:
que[1] = col[node]
cnt[col[node]] = 1
m[0] = 1
return
# nodes accumulating:
if col[node] in cnt:
que[cnt[col[node]]] -= col[node]
cnt[col[node]] += 1
if cnt[col[node]] not in que:
que[cnt[col[node]]] = 0
que[cnt[col[node]]] += col[node]
if m[0] < cnt[col[node]]:
m[0] = cnt[col[node]]
else:
cnt[col[node]] = 1
if 1 not in que:
que[1] = 0
que[1] += col[node]
col[node] = que[ m[0] ]
return
try:
dfs(-1, 0, {}, {}, [0])
except RuntimeError as e:
print(e)
print( " ".join(list(map(str, col ))))
```
No
| 90,540 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3
Submitted Solution:
```
#600E
cin = lambda:map(int,input().split())
n=int(input())
color=list(cin())
D=dict()
for i in range(n-1):
a,b=cin()
if a not in D:
D[a]={b}
else:
D[a].add(b)
colorres=[0]*n
def myadd(x, y):
return list(map(lambda a, b: a + b, x, y))
def maxsum(l):
maxc=max(l)
res=0
for i in range(n+1):
if l[i]==maxc:
res+=i
return(res)
def myf(v):
if v not in D:
colorres[v-1]=color[v-1]
l=[0]*(n+1)
l[color[v-1]]=1
return l
else:
l=[0]*(n+1)
l[color[v-1]]+=1
for vc in D[v]:
l=myadd(l,myf(vc))
colorres[v-1]=maxsum(l)
return(l)
myf(1)
print(' '.join(map(str, colorres )))
```
No
| 90,541 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3
Submitted Solution:
```
import sys
sys.setrecursionlimit(100000)
input = sys.stdin.readline
n = int(input())
vertexes = list(map(int, input().split()))
tree_map = {}
for i in range(n - 1):
a, b = map(int, input().split())
if a in tree_map:
tree_map[a].append(b)
else:
tree_map[a] = [b]
freq = [-1 for i in range(n)]
result = [-1 for i in range(n)]
def sum_dict(a, b):
for key in a:
if key in b:
b[key] += a[key]
else:
b[key] = a[key]
return b
def solve(node):
if result[node - 1] != -1:
return freq[node - 1]
if node in tree_map:
frequency = {vertexes[node - 1]: 1}
for next_node in tree_map[node]:
f = solve(next_node)
frequency = sum_dict(f, frequency)
n = max(frequency.values())
s = 0
for i in frequency:
if frequency[i] == n:
s += i
result[node - 1] = s
freq[node - 1] = frequency
return frequency
else:
freq[node - 1] = {vertexes[node - 1]: 1}
result[node - 1] = vertexes[node - 1]
return freq[node - 1]
solve(1)
for i, n in enumerate(result):
if n == -1:
result[i] = vertexes[i]
print(*result)
```
No
| 90,542 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3
Submitted Solution:
```
import sys
sys.setrecursionlimit(100000)
input = sys.stdin.readline
n = int(input())
vertexes = list(map(int, input().split()))
tree_map = {}
for i in range(n - 1):
a, b = map(int, input().split())
if a in tree_map:
tree_map[a].append(b)
else:
tree_map[a] = [b]
freq = [-1 for i in range(n)]
result = [-1 for i in range(n)]
def sum_dict(a, b):
for key in a:
if key in b:
b[key] += a[key]
else:
b[key] = a[key]
return b
def solve(node):
if result[node - 1] != -1:
return freq[node - 1]
if node in tree_map:
frequency = {vertexes[node - 1]: 1}
for next_node in tree_map[node]:
f = solve(next_node)
frequency = sum_dict(f, frequency)
n = max(frequency.values())
s = 0
for i in frequency:
if frequency[i] == n:
s += i
result[node - 1] = s
freq[node - 1] = frequency
return frequency
else:
freq[node - 1] = {vertexes[node - 1]: 1}
result[node - 1] = vertexes[node - 1]
return freq[node - 1]
solve(1)
if n == 4 or n == 15:
print(*result)
else:
print(tree_map[1])
```
No
| 90,543 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given array ai of length n. You may consecutively apply two operations to this array:
* remove some subsegment (continuous subsequence) of length m < n and pay for it m·a coins;
* change some elements of the array by at most 1, and pay b coins for each change.
Please note that each of operations may be applied at most once (and may be not applied at all) so you can remove only one segment and each number may be changed (increased or decreased) by at most 1. Also note, that you are not allowed to delete the whole array.
Your goal is to calculate the minimum number of coins that you need to spend in order to make the greatest common divisor of the elements of the resulting array be greater than 1.
Input
The first line of the input contains integers n, a and b (1 ≤ n ≤ 1 000 000, 0 ≤ a, b ≤ 109) — the length of the array, the cost of removing a single element in the first operation and the cost of changing an element, respectively.
The second line contains n integers ai (2 ≤ ai ≤ 109) — elements of the array.
Output
Print a single number — the minimum cost of changes needed to obtain an array, such that the greatest common divisor of all its elements is greater than 1.
Examples
Input
3 1 4
4 2 3
Output
1
Input
5 3 2
5 17 13 5 6
Output
8
Input
8 3 4
3 7 5 4 3 12 9 4
Output
13
Note
In the first sample the optimal way is to remove number 3 and pay 1 coin for it.
In the second sample you need to remove a segment [17, 13] and then decrease number 6. The cost of these changes is equal to 2·3 + 2 = 8 coins.
Submitted Solution:
```
from itertools import accumulate
from fractions import gcd
import math
n, a, b = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
N = math.ceil(10 ** 4.5)
sqN = math.ceil(N ** 0.5)
isprime = [True for i in range(N+1)]
isprime[0], isprime[1] = False, False
for p in range(2, sqN + 1):
if isprime[p]:
for i in range(p ** 2, N+1, p):
isprime[i] = False
primes = [p for p in range(2, N+1) if isprime[p]]
def div(n):
dividers = []
for p in primes:
if n % p == 0:
dividers.append(p)
while n % p == 0: n //= p
if n == 1: break
else:
dividers.append(n)
return dividers
L = {p: 0 for p in div(A[0]-1) + div(A[0]) + div(A[0]+1) + div(A[-1]-1) + div(A[-1]) + div(A[-1]+1)}
print(L)
R = {p: n*a for p in L}
def dynamic_update(D, m):
D1 = {}
for p in D:
if (m-1) % p == 0: D1[p] = D[p] + b - a
if (m+1) % p == 0: D1[p] = D[p] + b - a
if m % p == 0: D1[p] = D[p] - a
return D1
def min_compare(D1, D2): return {p: min(D2.get(p, math.inf), D1[p]) for p in D1}
B = accumulate([L] + A, dynamic_update)
A.reverse()
C = accumulate([R] + A, dynamic_update)
C1 = list(accumulate(C, min_compare))
ans = min(min(D[p] + C1[-k-1][p] for p in D) for k, D in enumerate(B))
print(ans)
```
No
| 90,544 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given array ai of length n. You may consecutively apply two operations to this array:
* remove some subsegment (continuous subsequence) of length m < n and pay for it m·a coins;
* change some elements of the array by at most 1, and pay b coins for each change.
Please note that each of operations may be applied at most once (and may be not applied at all) so you can remove only one segment and each number may be changed (increased or decreased) by at most 1. Also note, that you are not allowed to delete the whole array.
Your goal is to calculate the minimum number of coins that you need to spend in order to make the greatest common divisor of the elements of the resulting array be greater than 1.
Input
The first line of the input contains integers n, a and b (1 ≤ n ≤ 1 000 000, 0 ≤ a, b ≤ 109) — the length of the array, the cost of removing a single element in the first operation and the cost of changing an element, respectively.
The second line contains n integers ai (2 ≤ ai ≤ 109) — elements of the array.
Output
Print a single number — the minimum cost of changes needed to obtain an array, such that the greatest common divisor of all its elements is greater than 1.
Examples
Input
3 1 4
4 2 3
Output
1
Input
5 3 2
5 17 13 5 6
Output
8
Input
8 3 4
3 7 5 4 3 12 9 4
Output
13
Note
In the first sample the optimal way is to remove number 3 and pay 1 coin for it.
In the second sample you need to remove a segment [17, 13] and then decrease number 6. The cost of these changes is equal to 2·3 + 2 = 8 coins.
Submitted Solution:
```
def gharbal(n):
L=[1]*(n+1)
for p in range(2,int(n**0.5)+1):
if L[p]:
for i in range(p**2,n+1):
L[i]=0
for i in range(2,n+1):
if L[i]:
yield i
return
n,x,y=map(int,input().split())
z=min(x,y)
score=list(map(int,input().split()))
out=[]
for p in gharbal(max(score)+1):
a=b=0
for i in score:
c=i%p
if c==0:
a+=1
if c==p-1:
b+=1
d=n-(a+b)
out.append(z*b+d*x)
print(min(out))
```
No
| 90,545 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given array ai of length n. You may consecutively apply two operations to this array:
* remove some subsegment (continuous subsequence) of length m < n and pay for it m·a coins;
* change some elements of the array by at most 1, and pay b coins for each change.
Please note that each of operations may be applied at most once (and may be not applied at all) so you can remove only one segment and each number may be changed (increased or decreased) by at most 1. Also note, that you are not allowed to delete the whole array.
Your goal is to calculate the minimum number of coins that you need to spend in order to make the greatest common divisor of the elements of the resulting array be greater than 1.
Input
The first line of the input contains integers n, a and b (1 ≤ n ≤ 1 000 000, 0 ≤ a, b ≤ 109) — the length of the array, the cost of removing a single element in the first operation and the cost of changing an element, respectively.
The second line contains n integers ai (2 ≤ ai ≤ 109) — elements of the array.
Output
Print a single number — the minimum cost of changes needed to obtain an array, such that the greatest common divisor of all its elements is greater than 1.
Examples
Input
3 1 4
4 2 3
Output
1
Input
5 3 2
5 17 13 5 6
Output
8
Input
8 3 4
3 7 5 4 3 12 9 4
Output
13
Note
In the first sample the optimal way is to remove number 3 and pay 1 coin for it.
In the second sample you need to remove a segment [17, 13] and then decrease number 6. The cost of these changes is equal to 2·3 + 2 = 8 coins.
Submitted Solution:
```
from itertools import accumulate
from fractions import gcd
import math
n, a, b = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
N = math.ceil(10 ** 4.5)
sqN = math.ceil(N ** 0.5)
isprime = [True for i in range(N+1)]
isprime[0], isprime[1] = False, False
for p in range(2, sqN + 1):
if isprime[p]:
for i in range(p ** 2, N+1, p):
isprime[i] = False
check = lambda x, p: ((x-1)%p == 0) or (x%p == 0) or ((x+1)%p == 0)
L = {p: 0 for p in range(N+1) if isprime[p] and check(A[0], p)}
R = {p: n*a for p in range(N+1) if isprime[p] and check(A[-1], p)}
def dynamic_update(D, m):
D1 = {}
for p in D:
if (m-1) % p == 0: D1[p] = D[p] + b - a
if (m+1) % p == 0: D1[p] = D[p] + b - a
if m % p == 0: D1[p] = D[p] - a
return D1
def min_compare(D1, D2): return {p: min(D2[p], D1[p]) for p in D2}
B = accumulate([L] + A, dynamic_update)
A.reverse()
C = accumulate([R] + A, dynamic_update)
C1 = list(accumulate(C, min_compare))
ans = min(min(D[p] + C1[-k-1].get(p, math.inf) for p in D) for k, D in enumerate(B))
print(ans)
```
No
| 90,546 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given array ai of length n. You may consecutively apply two operations to this array:
* remove some subsegment (continuous subsequence) of length m < n and pay for it m·a coins;
* change some elements of the array by at most 1, and pay b coins for each change.
Please note that each of operations may be applied at most once (and may be not applied at all) so you can remove only one segment and each number may be changed (increased or decreased) by at most 1. Also note, that you are not allowed to delete the whole array.
Your goal is to calculate the minimum number of coins that you need to spend in order to make the greatest common divisor of the elements of the resulting array be greater than 1.
Input
The first line of the input contains integers n, a and b (1 ≤ n ≤ 1 000 000, 0 ≤ a, b ≤ 109) — the length of the array, the cost of removing a single element in the first operation and the cost of changing an element, respectively.
The second line contains n integers ai (2 ≤ ai ≤ 109) — elements of the array.
Output
Print a single number — the minimum cost of changes needed to obtain an array, such that the greatest common divisor of all its elements is greater than 1.
Examples
Input
3 1 4
4 2 3
Output
1
Input
5 3 2
5 17 13 5 6
Output
8
Input
8 3 4
3 7 5 4 3 12 9 4
Output
13
Note
In the first sample the optimal way is to remove number 3 and pay 1 coin for it.
In the second sample you need to remove a segment [17, 13] and then decrease number 6. The cost of these changes is equal to 2·3 + 2 = 8 coins.
Submitted Solution:
```
#!/usr/bin/python3
'''
Created on Feb 04, 2016
@author: kate
'''
def nod(a, b):
while a != b:
if a > b:
a = a - b
else:
b = b - a
return a
def check(n, a):
if n == 1:
print (0)
return False
return True
def get_sum(elem, mas, a, b):
sum = 0
a_count = 0
a_flag = False
b_flag = False
for i in range(len(mas)):
if nod(elem, mas[i]) > 1:
if elem > mas[i]:
return False
if a_count > 0:
a_flag = True
sum = a_count * a
else:
if not a_flag:
a_count += 1
elif not b_flag:
b_flag = True
sum += b
else:
return False
if not a_flag and a_count > 0:
sum = a_count * a
return sum
n, a, b = [int(x) for x in input().split()]
if check(n, a):
mas = [int(x) for x in input().split()]
sum = False
for elem in mas:
current_sum = get_sum(elem, mas, a, b)
if current_sum:
if sum == False or sum > current_sum:
sum = current_sum
print(sum or 0)
```
No
| 90,547 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below:
<image>
In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.
Input
The first two lines of the input consist of a 2 × 2 grid describing the initial configuration of Bessie's puzzle. The next two lines contain a 2 × 2 grid describing the initial configuration of Elsie's puzzle. The positions of the tiles are labeled 'A', 'B', and 'C', while the empty cell is labeled 'X'. It's guaranteed that both puzzles contain exactly one tile with each letter and exactly one empty position.
Output
Output "YES"(without quotes) if the puzzles can reach the same configuration (and Bessie and Elsie are truly BFFLs). Otherwise, print "NO" (without quotes).
Examples
Input
AB
XC
XB
AC
Output
YES
Input
AB
XC
AC
BX
Output
NO
Note
The solution to the first sample is described by the image. All Bessie needs to do is slide her 'A' tile down.
In the second sample, the two puzzles can never be in the same configuration. Perhaps Bessie and Elsie are not meant to be friends after all...
Tags: brute force, constructive algorithms, implementation
Correct Solution:
```
a = input()
b = input()
c = input()
d = input()
s = list(a + b[1] + b[0])
t = list(c + d[1] + d[0])
s.remove('X')
t.remove('X')
for i in range(5):
t = t[1:] + [t[0]]
if s == t:
print("YES")
break
else:
print("NO")
```
| 90,548 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below:
<image>
In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.
Input
The first two lines of the input consist of a 2 × 2 grid describing the initial configuration of Bessie's puzzle. The next two lines contain a 2 × 2 grid describing the initial configuration of Elsie's puzzle. The positions of the tiles are labeled 'A', 'B', and 'C', while the empty cell is labeled 'X'. It's guaranteed that both puzzles contain exactly one tile with each letter and exactly one empty position.
Output
Output "YES"(without quotes) if the puzzles can reach the same configuration (and Bessie and Elsie are truly BFFLs). Otherwise, print "NO" (without quotes).
Examples
Input
AB
XC
XB
AC
Output
YES
Input
AB
XC
AC
BX
Output
NO
Note
The solution to the first sample is described by the image. All Bessie needs to do is slide her 'A' tile down.
In the second sample, the two puzzles can never be in the same configuration. Perhaps Bessie and Elsie are not meant to be friends after all...
Tags: brute force, constructive algorithms, implementation
Correct Solution:
```
count = 12
ans = False
first = [list(input())]
first.append(list(input()))
second = [list(input())]
second.append(list(input()))
for i in range(count):
if first == second:
ans = True
break
if first[0][0] == 'X':
first[0][0], first[0][1] = first[0][1], first[0][0]
elif first[0][1] == 'X':
first[0][1], first[1][1] = first[1][1], first[0][1]
elif first[1][1] == 'X':
first[1][1], first[1][0] = first[1][0], first[1][1]
elif first[1][0] == 'X':
first[1][0], first[0][0] = first[0][0], first[1][0]
if ans:
print('YES')
else:
print('NO')
```
| 90,549 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below:
<image>
In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.
Input
The first two lines of the input consist of a 2 × 2 grid describing the initial configuration of Bessie's puzzle. The next two lines contain a 2 × 2 grid describing the initial configuration of Elsie's puzzle. The positions of the tiles are labeled 'A', 'B', and 'C', while the empty cell is labeled 'X'. It's guaranteed that both puzzles contain exactly one tile with each letter and exactly one empty position.
Output
Output "YES"(without quotes) if the puzzles can reach the same configuration (and Bessie and Elsie are truly BFFLs). Otherwise, print "NO" (without quotes).
Examples
Input
AB
XC
XB
AC
Output
YES
Input
AB
XC
AC
BX
Output
NO
Note
The solution to the first sample is described by the image. All Bessie needs to do is slide her 'A' tile down.
In the second sample, the two puzzles can never be in the same configuration. Perhaps Bessie and Elsie are not meant to be friends after all...
Tags: brute force, constructive algorithms, implementation
Correct Solution:
```
a = input()
a = a + input()[::-1]
a = a.replace('X','')
b = input()
b = b + input()[::-1]
b = b.replace('X','')
b = b * 2
if b.find(a) == -1:
print('NO')
else:
print('YES')
```
| 90,550 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below:
<image>
In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.
Input
The first two lines of the input consist of a 2 × 2 grid describing the initial configuration of Bessie's puzzle. The next two lines contain a 2 × 2 grid describing the initial configuration of Elsie's puzzle. The positions of the tiles are labeled 'A', 'B', and 'C', while the empty cell is labeled 'X'. It's guaranteed that both puzzles contain exactly one tile with each letter and exactly one empty position.
Output
Output "YES"(without quotes) if the puzzles can reach the same configuration (and Bessie and Elsie are truly BFFLs). Otherwise, print "NO" (without quotes).
Examples
Input
AB
XC
XB
AC
Output
YES
Input
AB
XC
AC
BX
Output
NO
Note
The solution to the first sample is described by the image. All Bessie needs to do is slide her 'A' tile down.
In the second sample, the two puzzles can never be in the same configuration. Perhaps Bessie and Elsie are not meant to be friends after all...
Tags: brute force, constructive algorithms, implementation
Correct Solution:
```
#!/usr/bin/python3
def main():
a = input() + "".join(reversed(input()))
b = input() + "".join(reversed(input()))
a = a[:a.find("X")] + a[a.find("X") + 1:]
b = b[:b.find("X")] + b[b.find("X") + 1:]
for i in range(3):
if a[i:] + a[:i] == b:
return True
return False
if main():
print("YES")
else:
print("NO")
```
| 90,551 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below:
<image>
In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.
Input
The first two lines of the input consist of a 2 × 2 grid describing the initial configuration of Bessie's puzzle. The next two lines contain a 2 × 2 grid describing the initial configuration of Elsie's puzzle. The positions of the tiles are labeled 'A', 'B', and 'C', while the empty cell is labeled 'X'. It's guaranteed that both puzzles contain exactly one tile with each letter and exactly one empty position.
Output
Output "YES"(without quotes) if the puzzles can reach the same configuration (and Bessie and Elsie are truly BFFLs). Otherwise, print "NO" (without quotes).
Examples
Input
AB
XC
XB
AC
Output
YES
Input
AB
XC
AC
BX
Output
NO
Note
The solution to the first sample is described by the image. All Bessie needs to do is slide her 'A' tile down.
In the second sample, the two puzzles can never be in the same configuration. Perhaps Bessie and Elsie are not meant to be friends after all...
Tags: brute force, constructive algorithms, implementation
Correct Solution:
```
def find_order(A, B):
d = dict()
i = 0
if A[0] != 'X':
d[i] = A[0]
i += 1
if A[1] != 'X':
d[i] = A[1]
i += 1
if B[1] != 'X':
d[i] = B[1]
i += 1
if B[0] != 'X':
d[i] = B[0]
i += 1
return d
a = input()
b = input()
c = input()
d = input()
m = find_order(a, b)
n = find_order(c, d)
m[3] = m[0]
m[4] = m[1]
if m[0] == n[0]:
if m[1] == n[1] and m[2] == n[2]:
print('YES')
else:
print('NO')
elif m[1] == n[0]:
if m[2] == n[1] and m[3] == n[2]:
print('YES')
else:
print('NO')
elif m[2] == n[0]:
if m[3] == n[1] and m[4] == n[2]:
print('YES')
else:
print('NO')
```
| 90,552 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below:
<image>
In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.
Input
The first two lines of the input consist of a 2 × 2 grid describing the initial configuration of Bessie's puzzle. The next two lines contain a 2 × 2 grid describing the initial configuration of Elsie's puzzle. The positions of the tiles are labeled 'A', 'B', and 'C', while the empty cell is labeled 'X'. It's guaranteed that both puzzles contain exactly one tile with each letter and exactly one empty position.
Output
Output "YES"(without quotes) if the puzzles can reach the same configuration (and Bessie and Elsie are truly BFFLs). Otherwise, print "NO" (without quotes).
Examples
Input
AB
XC
XB
AC
Output
YES
Input
AB
XC
AC
BX
Output
NO
Note
The solution to the first sample is described by the image. All Bessie needs to do is slide her 'A' tile down.
In the second sample, the two puzzles can never be in the same configuration. Perhaps Bessie and Elsie are not meant to be friends after all...
Tags: brute force, constructive algorithms, implementation
Correct Solution:
```
s1 = ""
s2 = ""
a = input()
b = input()
c = input()
d = input()
s1 = list(a + b[1] + b[0])
s2 = list(c + d[1] + d[0])
t = s1.index('X')
if t != 3:
s1 = s1[:t] + s1[t+1:]
else:
s1 = s1[:3]
t = s2.index('X')
if t != 3:
s2 = s2[:t] + s2[t+1:]
else:
s2 = s2[:3]
if s1[0] + s1[1] + s1[2] == s2[0] + s2[1] + s2[2] or s1[1] + s1[2] + s1[0] == s2[0] + s2[1] + s2[2] or s1[2] + s1[0] + s1[1] == s2[0] + s2[1] + s2[2]:
print("YES")
else:
print("NO")
```
| 90,553 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below:
<image>
In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.
Input
The first two lines of the input consist of a 2 × 2 grid describing the initial configuration of Bessie's puzzle. The next two lines contain a 2 × 2 grid describing the initial configuration of Elsie's puzzle. The positions of the tiles are labeled 'A', 'B', and 'C', while the empty cell is labeled 'X'. It's guaranteed that both puzzles contain exactly one tile with each letter and exactly one empty position.
Output
Output "YES"(without quotes) if the puzzles can reach the same configuration (and Bessie and Elsie are truly BFFLs). Otherwise, print "NO" (without quotes).
Examples
Input
AB
XC
XB
AC
Output
YES
Input
AB
XC
AC
BX
Output
NO
Note
The solution to the first sample is described by the image. All Bessie needs to do is slide her 'A' tile down.
In the second sample, the two puzzles can never be in the same configuration. Perhaps Bessie and Elsie are not meant to be friends after all...
Tags: brute force, constructive algorithms, implementation
Correct Solution:
```
f = lambda: 'ABC' in 2 * (input()+input()[::-1]).replace('X', '')
print('NO' if f()^f() else 'YES')
```
| 90,554 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below:
<image>
In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.
Input
The first two lines of the input consist of a 2 × 2 grid describing the initial configuration of Bessie's puzzle. The next two lines contain a 2 × 2 grid describing the initial configuration of Elsie's puzzle. The positions of the tiles are labeled 'A', 'B', and 'C', while the empty cell is labeled 'X'. It's guaranteed that both puzzles contain exactly one tile with each letter and exactly one empty position.
Output
Output "YES"(without quotes) if the puzzles can reach the same configuration (and Bessie and Elsie are truly BFFLs). Otherwise, print "NO" (without quotes).
Examples
Input
AB
XC
XB
AC
Output
YES
Input
AB
XC
AC
BX
Output
NO
Note
The solution to the first sample is described by the image. All Bessie needs to do is slide her 'A' tile down.
In the second sample, the two puzzles can never be in the same configuration. Perhaps Bessie and Elsie are not meant to be friends after all...
Tags: brute force, constructive algorithms, implementation
Correct Solution:
```
s1 = input() + input()[::-1]
s2 = input() + input()[::-1]
s1 = s1[:s1.find('X')] + s1[s1.find('X') + 1:]
s2 = s2[:s2.find('X')] + s2[s2.find('X') + 1:]
flag = False
for i in range(3):
if s1 == s2:
flag = True
break
s1 = s1[-1] + s1[:-1]
print('YES' if flag else 'NO')
```
| 90,555 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below:
<image>
In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.
Input
The first two lines of the input consist of a 2 × 2 grid describing the initial configuration of Bessie's puzzle. The next two lines contain a 2 × 2 grid describing the initial configuration of Elsie's puzzle. The positions of the tiles are labeled 'A', 'B', and 'C', while the empty cell is labeled 'X'. It's guaranteed that both puzzles contain exactly one tile with each letter and exactly one empty position.
Output
Output "YES"(without quotes) if the puzzles can reach the same configuration (and Bessie and Elsie are truly BFFLs). Otherwise, print "NO" (without quotes).
Examples
Input
AB
XC
XB
AC
Output
YES
Input
AB
XC
AC
BX
Output
NO
Note
The solution to the first sample is described by the image. All Bessie needs to do is slide her 'A' tile down.
In the second sample, the two puzzles can never be in the same configuration. Perhaps Bessie and Elsie are not meant to be friends after all...
Submitted Solution:
```
a1 = input()
a2 = input()
b1 = input()
b2 = input()
bel = [a1,a2]
el = [b1,b2]
checker = False
for i in range(100):
if not( a1 == b1 and a2 == b2):
if 'X' in a1:
if a1.find('X') == 0:
a1 = a2[0]+a1[1]
a2 = 'X'+a2[1]
else:
a1 = 'X'+a1[0]
else:
if a2.find('X') == 0:
a2 = a2[1] + 'X'
else:
a2 = a2[0] + a1[1]
a1 = a1[0] +'X'
else:
checker = True
break
if checker == True:
print('YES')
else:
print('NO')
```
Yes
| 90,556 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below:
<image>
In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.
Input
The first two lines of the input consist of a 2 × 2 grid describing the initial configuration of Bessie's puzzle. The next two lines contain a 2 × 2 grid describing the initial configuration of Elsie's puzzle. The positions of the tiles are labeled 'A', 'B', and 'C', while the empty cell is labeled 'X'. It's guaranteed that both puzzles contain exactly one tile with each letter and exactly one empty position.
Output
Output "YES"(without quotes) if the puzzles can reach the same configuration (and Bessie and Elsie are truly BFFLs). Otherwise, print "NO" (without quotes).
Examples
Input
AB
XC
XB
AC
Output
YES
Input
AB
XC
AC
BX
Output
NO
Note
The solution to the first sample is described by the image. All Bessie needs to do is slide her 'A' tile down.
In the second sample, the two puzzles can never be in the same configuration. Perhaps Bessie and Elsie are not meant to be friends after all...
Submitted Solution:
```
list1 = [(i)for i in input()]
list2 = [(i)for i in input()]
list3 = [(i)for i in input()]
list4 = [(i)for i in input()]
chars1 = ""
chars2 = ""
if list1[0]!="X":
chars1+=list1[0]
if list1[1]!="X":
chars1+=list1[1]
if list2[1]!="X":
chars1+=list2[1]
if list2[0]!="X":
chars1+=list2[0]
chars1*=2
if list3[0]!="X":
chars2+=list3[0]
if list3[1]!="X":
chars2+=list3[1]
if list4[1]!="X":
chars2+=list4[1]
if list4[0]!="X":
chars2+=list4[0]
if chars2 in chars1:
print("YES")
else:
print("NO")
```
Yes
| 90,557 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below:
<image>
In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.
Input
The first two lines of the input consist of a 2 × 2 grid describing the initial configuration of Bessie's puzzle. The next two lines contain a 2 × 2 grid describing the initial configuration of Elsie's puzzle. The positions of the tiles are labeled 'A', 'B', and 'C', while the empty cell is labeled 'X'. It's guaranteed that both puzzles contain exactly one tile with each letter and exactly one empty position.
Output
Output "YES"(without quotes) if the puzzles can reach the same configuration (and Bessie and Elsie are truly BFFLs). Otherwise, print "NO" (without quotes).
Examples
Input
AB
XC
XB
AC
Output
YES
Input
AB
XC
AC
BX
Output
NO
Note
The solution to the first sample is described by the image. All Bessie needs to do is slide her 'A' tile down.
In the second sample, the two puzzles can never be in the same configuration. Perhaps Bessie and Elsie are not meant to be friends after all...
Submitted Solution:
```
s1=input()
s2=input()
s3=input()
s4=input()
s11=s1+s2[::-1]
s22=s3+s4[::-1]
k1=""
k2=""
for i in range(4):
if s11[i]!='X':
k1+=s11[i]
for i in range(4):
if s22[i]!='X':
k2+=s22[i]
k1=k1*3
#print(k1)
#print(k2)
if k2 in k1:
print('YES')
else:
print('NO')
```
Yes
| 90,558 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below:
<image>
In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.
Input
The first two lines of the input consist of a 2 × 2 grid describing the initial configuration of Bessie's puzzle. The next two lines contain a 2 × 2 grid describing the initial configuration of Elsie's puzzle. The positions of the tiles are labeled 'A', 'B', and 'C', while the empty cell is labeled 'X'. It's guaranteed that both puzzles contain exactly one tile with each letter and exactly one empty position.
Output
Output "YES"(without quotes) if the puzzles can reach the same configuration (and Bessie and Elsie are truly BFFLs). Otherwise, print "NO" (without quotes).
Examples
Input
AB
XC
XB
AC
Output
YES
Input
AB
XC
AC
BX
Output
NO
Note
The solution to the first sample is described by the image. All Bessie needs to do is slide her 'A' tile down.
In the second sample, the two puzzles can never be in the same configuration. Perhaps Bessie and Elsie are not meant to be friends after all...
Submitted Solution:
```
per1 = input()
per2 = input()
per3 = input()
per4 = input()
s= []
s.append(per1[0])
s.append (per1[1])
s.append (per2[1])
s.append (per2[0])
for i in range(len(s)):
if s[i] == 'X':
s.pop(i)
break
d= []
d.append(per3[0])
d.append (per3[1])
d.append (per4[1])
d.append (per4[0])
for i in range(len(d)):
if d[i] == 'X':
d.pop(i)
break
per2 = False
for i in range(3):
if s != d:
t = d.pop(0)
d.append(t)
else:
per2 = True
break
if per2:
print('YES')
else:
print('NO')
```
Yes
| 90,559 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below:
<image>
In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.
Input
The first two lines of the input consist of a 2 × 2 grid describing the initial configuration of Bessie's puzzle. The next two lines contain a 2 × 2 grid describing the initial configuration of Elsie's puzzle. The positions of the tiles are labeled 'A', 'B', and 'C', while the empty cell is labeled 'X'. It's guaranteed that both puzzles contain exactly one tile with each letter and exactly one empty position.
Output
Output "YES"(without quotes) if the puzzles can reach the same configuration (and Bessie and Elsie are truly BFFLs). Otherwise, print "NO" (without quotes).
Examples
Input
AB
XC
XB
AC
Output
YES
Input
AB
XC
AC
BX
Output
NO
Note
The solution to the first sample is described by the image. All Bessie needs to do is slide her 'A' tile down.
In the second sample, the two puzzles can never be in the same configuration. Perhaps Bessie and Elsie are not meant to be friends after all...
Submitted Solution:
```
s=str(input())
s1=str(input())
s2=str(input())
s3=str(input())
e=''
f=''
flag=0
for i in range(0,len(s)):
if(s[i]!='X'):
e=e+s[i]
for i in range(0,len(s1)):
if(s1[i]!='X'):
f=f+s1[i]
if((e=='AB' and f=='C') or (e=='BC' and f=='A') or (e=='CA' and f=='B') or (e=='A' and f=='CB') or (e=='B' and f=='AC')or(e=='C' and f=='BA')):
pass
else:
flag=1
if(flag==0):
e=''
f=''
for i in range(0,len(s2)):
if(s2[i]!='X'):
e=e+s2[i]
for i in range(0,len(s3)):
if(s3[i]!='X'):
f=f+s3[i]
if(e=='AB' and f=='C' or (e=='BC' and f=='A') or (e=='CA' and f=='B') or (e=='A' and f=='CB') or (e=='B' and f=='AC')or(e=='C' and f=='BA')):
pass
else:
flag=1
if(flag==0):
print('YES')
else:
print('NO')
```
No
| 90,560 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below:
<image>
In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.
Input
The first two lines of the input consist of a 2 × 2 grid describing the initial configuration of Bessie's puzzle. The next two lines contain a 2 × 2 grid describing the initial configuration of Elsie's puzzle. The positions of the tiles are labeled 'A', 'B', and 'C', while the empty cell is labeled 'X'. It's guaranteed that both puzzles contain exactly one tile with each letter and exactly one empty position.
Output
Output "YES"(without quotes) if the puzzles can reach the same configuration (and Bessie and Elsie are truly BFFLs). Otherwise, print "NO" (without quotes).
Examples
Input
AB
XC
XB
AC
Output
YES
Input
AB
XC
AC
BX
Output
NO
Note
The solution to the first sample is described by the image. All Bessie needs to do is slide her 'A' tile down.
In the second sample, the two puzzles can never be in the same configuration. Perhaps Bessie and Elsie are not meant to be friends after all...
Submitted Solution:
```
a = [list(input()), list(input())]
b = [list(input()), list(input())]
def nxt(a):
x, y = 0, 0
for i in range(2):
for j in range(2):
if a[i][j] == 'X':
x, y = i, j
if (x, y) == (0, 0):
a[x][y] = a[x+1][y]
a[x+1][y] = 'X'
elif (x, y) == (0, 1):
a[x][y] = a[x][y-1]
a[x][y-1] = 'X'
elif (x, y) == (1, 0):
a[x][y] = a[x][y+1]
a[x][y+1] = 'X'
else:
a[x][y] = a[x-1][y]
a[x-1][y] = 'X'
return a
def prv(a):
x, y = 0, 0
for i in range(2):
for j in range(2):
if a[i][j] == 'X':
x, y = i, j
if (x, y) == (0, 0):
a[x][y] = a[x][y+1]
a[x][y+1] = 'X'
elif (x, y) == (0, 1):
a[x][y] = a[x+1][y]
a[x+1][y] = 'X'
elif (x, y) == (1, 0):
a[x][y] = a[x-1][y]
a[x-1][y] = 'X'
else:
a[x][y] = a[x][y-1]
a[x][y-1] = 'X'
return a
c = b[:]
if b == a:
print('YES')
else:
b = nxt(b)
if b == a:
print('YES')
else:
b = nxt(b)
if b == a:
print('YES')
else:
b = nxt(b)
if b == a:
print('YES')
else:
b = c[:]
if b == a:
print('YES')
else:
b = prv(b)
if b == a:
print('YES')
else:
b = prv(b)
if b == a:
print('YES')
else:
b = prv(b)
if b == a:
print('YES')
else:
print('NO')
```
No
| 90,561 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below:
<image>
In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.
Input
The first two lines of the input consist of a 2 × 2 grid describing the initial configuration of Bessie's puzzle. The next two lines contain a 2 × 2 grid describing the initial configuration of Elsie's puzzle. The positions of the tiles are labeled 'A', 'B', and 'C', while the empty cell is labeled 'X'. It's guaranteed that both puzzles contain exactly one tile with each letter and exactly one empty position.
Output
Output "YES"(without quotes) if the puzzles can reach the same configuration (and Bessie and Elsie are truly BFFLs). Otherwise, print "NO" (without quotes).
Examples
Input
AB
XC
XB
AC
Output
YES
Input
AB
XC
AC
BX
Output
NO
Note
The solution to the first sample is described by the image. All Bessie needs to do is slide her 'A' tile down.
In the second sample, the two puzzles can never be in the same configuration. Perhaps Bessie and Elsie are not meant to be friends after all...
Submitted Solution:
```
mas = ["ABXC", "XBAC", "BXAC", "BCAX", "BCXA", "XCBA", "CXBA", "CABX", "CAXB", "XACB", "AXCB", "ABCX"]
a = input()
a += input()
b = input()
b += input()
if a in mas and b in mas:
print("YES")
else:
print("NO")
```
No
| 90,562 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the empty cell as shown below:
<image>
In order to determine if they are truly Best Friends For Life (BFFLs), Bessie and Elsie would like to know if there exists a sequence of moves that takes their puzzles to the same configuration (moves can be performed in both puzzles). Two puzzles are considered to be in the same configuration if each tile is on top of the same grid cell in both puzzles. Since the tiles are labeled with letters, rotations and reflections are not allowed.
Input
The first two lines of the input consist of a 2 × 2 grid describing the initial configuration of Bessie's puzzle. The next two lines contain a 2 × 2 grid describing the initial configuration of Elsie's puzzle. The positions of the tiles are labeled 'A', 'B', and 'C', while the empty cell is labeled 'X'. It's guaranteed that both puzzles contain exactly one tile with each letter and exactly one empty position.
Output
Output "YES"(without quotes) if the puzzles can reach the same configuration (and Bessie and Elsie are truly BFFLs). Otherwise, print "NO" (without quotes).
Examples
Input
AB
XC
XB
AC
Output
YES
Input
AB
XC
AC
BX
Output
NO
Note
The solution to the first sample is described by the image. All Bessie needs to do is slide her 'A' tile down.
In the second sample, the two puzzles can never be in the same configuration. Perhaps Bessie and Elsie are not meant to be friends after all...
Submitted Solution:
```
s=str(input())
s1=str(input())
s2=str(input())
s3=str(input())
e=''
f=''
flag=0
for i in range(0,len(s)):
if(s[i]!='X'):
e=e+s[i]
for i in range(0,len(s1)):
if(s1[i]!='X'):
f=f+s1[i]
print(e,f)
if((e=='AB' and f=='C') or (e=='BC' and f=='A') or (e=='CA' and f=='B') or (e=='A' and f=='CB') or (e=='B' and f=='AC')or(e=='C' and f=='BA')):
pass
else:
flag=1
if(flag==0):
e=''
f=''
for i in range(0,len(s2)):
if(s2[i]!='X'):
e=e+s2[i]
for i in range(0,len(s3)):
if(s3[i]!='X'):
f=f+s3[i]
if(e=='AB' and f=='C' or (e=='BC' and f=='A') or (e=='CA' and f=='B') or (e=='A' and f=='CB') or (e=='B' and f=='AC')or(e=='C' and f=='BA')):
pass
else:
flag=1
if(flag==0):
print('NO')
else:
print('YES')
```
No
| 90,563 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.
<image>
Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time x (in seconds), so he asked you to tell him if it's gonna bark at that time.
Input
The first and only line of input contains three integers t, s and x (0 ≤ t, x ≤ 109, 2 ≤ s ≤ 109) — the time the pineapple barks for the first time, the pineapple barking interval, and the time Barney wants to eat the pineapple respectively.
Output
Print a single "YES" (without quotes) if the pineapple will bark at time x or a single "NO" (without quotes) otherwise in the only line of output.
Examples
Input
3 10 4
Output
NO
Input
3 10 3
Output
YES
Input
3 8 51
Output
YES
Input
3 8 52
Output
YES
Note
In the first and the second sample cases pineapple will bark at moments 3, 13, 14, ..., so it won't bark at the moment 4 and will bark at the moment 3.
In the third and fourth sample cases pineapple will bark at moments 3, 11, 12, 19, 20, 27, 28, 35, 36, 43, 44, 51, 52, 59, ..., so it will bark at both moments 51 and 52.
Tags: implementation, math
Correct Solution:
```
t, s, x = map(int, input().split())
if (x - 1 == t and s != 1) or t > x:
print('NO')
elif (x - t) % s == 0 or (x - t) % s == 1:
print('YES')
else:
print('NO')
```
| 90,564 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.
<image>
Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time x (in seconds), so he asked you to tell him if it's gonna bark at that time.
Input
The first and only line of input contains three integers t, s and x (0 ≤ t, x ≤ 109, 2 ≤ s ≤ 109) — the time the pineapple barks for the first time, the pineapple barking interval, and the time Barney wants to eat the pineapple respectively.
Output
Print a single "YES" (without quotes) if the pineapple will bark at time x or a single "NO" (without quotes) otherwise in the only line of output.
Examples
Input
3 10 4
Output
NO
Input
3 10 3
Output
YES
Input
3 8 51
Output
YES
Input
3 8 52
Output
YES
Note
In the first and the second sample cases pineapple will bark at moments 3, 13, 14, ..., so it won't bark at the moment 4 and will bark at the moment 3.
In the third and fourth sample cases pineapple will bark at moments 3, 11, 12, 19, 20, 27, 28, 35, 36, 43, 44, 51, 52, 59, ..., so it will bark at both moments 51 and 52.
Tags: implementation, math
Correct Solution:
```
i = input().split()
for j in range(3):
i[j]=int(i[j])
if (i[2]+i[1]-i[0])%i[1]==0 and i[2]>=i[0]:
print("YES\n")
else:
i[2]-=1
if(i[2]+i[1]-i[0])%i[1]==0 and i[2]!=i[0] and i[2]>=i[0]:
print("YES\n")
else:
print("NO\n")
```
| 90,565 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.
<image>
Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time x (in seconds), so he asked you to tell him if it's gonna bark at that time.
Input
The first and only line of input contains three integers t, s and x (0 ≤ t, x ≤ 109, 2 ≤ s ≤ 109) — the time the pineapple barks for the first time, the pineapple barking interval, and the time Barney wants to eat the pineapple respectively.
Output
Print a single "YES" (without quotes) if the pineapple will bark at time x or a single "NO" (without quotes) otherwise in the only line of output.
Examples
Input
3 10 4
Output
NO
Input
3 10 3
Output
YES
Input
3 8 51
Output
YES
Input
3 8 52
Output
YES
Note
In the first and the second sample cases pineapple will bark at moments 3, 13, 14, ..., so it won't bark at the moment 4 and will bark at the moment 3.
In the third and fourth sample cases pineapple will bark at moments 3, 11, 12, 19, 20, 27, 28, 35, 36, 43, 44, 51, 52, 59, ..., so it will bark at both moments 51 and 52.
Tags: implementation, math
Correct Solution:
```
t, s, x = [int(i) for i in input().split()]
if x < t+s:
if x == t:
print("YES")
else:
print("NO")
else:
if (x-t)%s == 0 or (x-t)%s == 1:
print("YES")
else:
print("NO")
```
| 90,566 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.
<image>
Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time x (in seconds), so he asked you to tell him if it's gonna bark at that time.
Input
The first and only line of input contains three integers t, s and x (0 ≤ t, x ≤ 109, 2 ≤ s ≤ 109) — the time the pineapple barks for the first time, the pineapple barking interval, and the time Barney wants to eat the pineapple respectively.
Output
Print a single "YES" (without quotes) if the pineapple will bark at time x or a single "NO" (without quotes) otherwise in the only line of output.
Examples
Input
3 10 4
Output
NO
Input
3 10 3
Output
YES
Input
3 8 51
Output
YES
Input
3 8 52
Output
YES
Note
In the first and the second sample cases pineapple will bark at moments 3, 13, 14, ..., so it won't bark at the moment 4 and will bark at the moment 3.
In the third and fourth sample cases pineapple will bark at moments 3, 11, 12, 19, 20, 27, 28, 35, 36, 43, 44, 51, 52, 59, ..., so it will bark at both moments 51 and 52.
Tags: implementation, math
Correct Solution:
```
a=list(map(int,input().split()))
if a[0]>a[2]:
print("NO")
else :
if abs((a[2]-a[0]))%a[1]==1 and abs(a[2]-a[0])!=1 or abs((a[2]-a[0]))%a[1]==0 and abs(a[2]-a[0])!=1 :
print('YES')
else :
print('NO')
```
| 90,567 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.
<image>
Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time x (in seconds), so he asked you to tell him if it's gonna bark at that time.
Input
The first and only line of input contains three integers t, s and x (0 ≤ t, x ≤ 109, 2 ≤ s ≤ 109) — the time the pineapple barks for the first time, the pineapple barking interval, and the time Barney wants to eat the pineapple respectively.
Output
Print a single "YES" (without quotes) if the pineapple will bark at time x or a single "NO" (without quotes) otherwise in the only line of output.
Examples
Input
3 10 4
Output
NO
Input
3 10 3
Output
YES
Input
3 8 51
Output
YES
Input
3 8 52
Output
YES
Note
In the first and the second sample cases pineapple will bark at moments 3, 13, 14, ..., so it won't bark at the moment 4 and will bark at the moment 3.
In the third and fourth sample cases pineapple will bark at moments 3, 11, 12, 19, 20, 27, 28, 35, 36, 43, 44, 51, 52, 59, ..., so it will bark at both moments 51 and 52.
Tags: implementation, math
Correct Solution:
```
t, s, x = map(int, input().split())
print('YES' if x - t >= 0 and x - t != 1 and (x - t) % s <= 1 else 'NO')
```
| 90,568 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.
<image>
Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time x (in seconds), so he asked you to tell him if it's gonna bark at that time.
Input
The first and only line of input contains three integers t, s and x (0 ≤ t, x ≤ 109, 2 ≤ s ≤ 109) — the time the pineapple barks for the first time, the pineapple barking interval, and the time Barney wants to eat the pineapple respectively.
Output
Print a single "YES" (without quotes) if the pineapple will bark at time x or a single "NO" (without quotes) otherwise in the only line of output.
Examples
Input
3 10 4
Output
NO
Input
3 10 3
Output
YES
Input
3 8 51
Output
YES
Input
3 8 52
Output
YES
Note
In the first and the second sample cases pineapple will bark at moments 3, 13, 14, ..., so it won't bark at the moment 4 and will bark at the moment 3.
In the third and fourth sample cases pineapple will bark at moments 3, 11, 12, 19, 20, 27, 28, 35, 36, 43, 44, 51, 52, 59, ..., so it will bark at both moments 51 and 52.
Tags: implementation, math
Correct Solution:
```
read = lambda: map(int, input().split())
t, s, x = read()
f1 = (x - t) % s == 0 and x >= t
f2 = (x - t - 1) % s == 0 and x > t + 1
print('YES' if (f1 or f2) else 'NO')
```
| 90,569 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.
<image>
Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time x (in seconds), so he asked you to tell him if it's gonna bark at that time.
Input
The first and only line of input contains three integers t, s and x (0 ≤ t, x ≤ 109, 2 ≤ s ≤ 109) — the time the pineapple barks for the first time, the pineapple barking interval, and the time Barney wants to eat the pineapple respectively.
Output
Print a single "YES" (without quotes) if the pineapple will bark at time x or a single "NO" (without quotes) otherwise in the only line of output.
Examples
Input
3 10 4
Output
NO
Input
3 10 3
Output
YES
Input
3 8 51
Output
YES
Input
3 8 52
Output
YES
Note
In the first and the second sample cases pineapple will bark at moments 3, 13, 14, ..., so it won't bark at the moment 4 and will bark at the moment 3.
In the third and fourth sample cases pineapple will bark at moments 3, 11, 12, 19, 20, 27, 28, 35, 36, 43, 44, 51, 52, 59, ..., so it will bark at both moments 51 and 52.
Tags: implementation, math
Correct Solution:
```
# Description of the problem can be found at http://codeforces.com/problemset/problem/697/A
t, s, x = map(int, input().split())
if t == x:
print("YES")
else:
if (x - t) % s <= 1 and (x - t) // s > 0:
print("YES")
else:
print("NO")
```
| 90,570 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.
<image>
Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time x (in seconds), so he asked you to tell him if it's gonna bark at that time.
Input
The first and only line of input contains three integers t, s and x (0 ≤ t, x ≤ 109, 2 ≤ s ≤ 109) — the time the pineapple barks for the first time, the pineapple barking interval, and the time Barney wants to eat the pineapple respectively.
Output
Print a single "YES" (without quotes) if the pineapple will bark at time x or a single "NO" (without quotes) otherwise in the only line of output.
Examples
Input
3 10 4
Output
NO
Input
3 10 3
Output
YES
Input
3 8 51
Output
YES
Input
3 8 52
Output
YES
Note
In the first and the second sample cases pineapple will bark at moments 3, 13, 14, ..., so it won't bark at the moment 4 and will bark at the moment 3.
In the third and fourth sample cases pineapple will bark at moments 3, 11, 12, 19, 20, 27, 28, 35, 36, 43, 44, 51, 52, 59, ..., so it will bark at both moments 51 and 52.
Tags: implementation, math
Correct Solution:
```
a = input().split()
t = int(a[0])
s = int(a[1])
x = int(a[2])
if (((x-t)%s!=0) and (((x-t)-1)%s!=0)) or (x-1==t) or x<t:
print("NO")
else:
print("YES")
```
| 90,571 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.
<image>
Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time x (in seconds), so he asked you to tell him if it's gonna bark at that time.
Input
The first and only line of input contains three integers t, s and x (0 ≤ t, x ≤ 109, 2 ≤ s ≤ 109) — the time the pineapple barks for the first time, the pineapple barking interval, and the time Barney wants to eat the pineapple respectively.
Output
Print a single "YES" (without quotes) if the pineapple will bark at time x or a single "NO" (without quotes) otherwise in the only line of output.
Examples
Input
3 10 4
Output
NO
Input
3 10 3
Output
YES
Input
3 8 51
Output
YES
Input
3 8 52
Output
YES
Note
In the first and the second sample cases pineapple will bark at moments 3, 13, 14, ..., so it won't bark at the moment 4 and will bark at the moment 3.
In the third and fourth sample cases pineapple will bark at moments 3, 11, 12, 19, 20, 27, 28, 35, 36, 43, 44, 51, 52, 59, ..., so it will bark at both moments 51 and 52.
Submitted Solution:
```
t,s,x=map(int,input().split())
if(x==t):
print("YES")
exit(0)
else:
if(x>t):
if((x-t)%s==0 and (x-t)/s>=1):
print("YES")
exit(0)
if((x-t-1)%s==0 and (x-t-1)/s>=1):
print("YES")
exit(0)
print("NO")
```
Yes
| 90,572 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.
<image>
Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time x (in seconds), so he asked you to tell him if it's gonna bark at that time.
Input
The first and only line of input contains three integers t, s and x (0 ≤ t, x ≤ 109, 2 ≤ s ≤ 109) — the time the pineapple barks for the first time, the pineapple barking interval, and the time Barney wants to eat the pineapple respectively.
Output
Print a single "YES" (without quotes) if the pineapple will bark at time x or a single "NO" (without quotes) otherwise in the only line of output.
Examples
Input
3 10 4
Output
NO
Input
3 10 3
Output
YES
Input
3 8 51
Output
YES
Input
3 8 52
Output
YES
Note
In the first and the second sample cases pineapple will bark at moments 3, 13, 14, ..., so it won't bark at the moment 4 and will bark at the moment 3.
In the third and fourth sample cases pineapple will bark at moments 3, 11, 12, 19, 20, 27, 28, 35, 36, 43, 44, 51, 52, 59, ..., so it will bark at both moments 51 and 52.
Submitted Solution:
```
[t,s,x]=[int(x) for x in input().split()]
x-=t
if (x%s==0 or x%s==1 and x!=1) and x>=0:
print("YES")
else:
print("NO")
```
Yes
| 90,573 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.
<image>
Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time x (in seconds), so he asked you to tell him if it's gonna bark at that time.
Input
The first and only line of input contains three integers t, s and x (0 ≤ t, x ≤ 109, 2 ≤ s ≤ 109) — the time the pineapple barks for the first time, the pineapple barking interval, and the time Barney wants to eat the pineapple respectively.
Output
Print a single "YES" (without quotes) if the pineapple will bark at time x or a single "NO" (without quotes) otherwise in the only line of output.
Examples
Input
3 10 4
Output
NO
Input
3 10 3
Output
YES
Input
3 8 51
Output
YES
Input
3 8 52
Output
YES
Note
In the first and the second sample cases pineapple will bark at moments 3, 13, 14, ..., so it won't bark at the moment 4 and will bark at the moment 3.
In the third and fourth sample cases pineapple will bark at moments 3, 11, 12, 19, 20, 27, 28, 35, 36, 43, 44, 51, 52, 59, ..., so it will bark at both moments 51 and 52.
Submitted Solution:
```
t,s,x=map(int,input().split())
print('NO'if(x<t)or(x-t)%s>>(x!=t+1)else'YES')
```
Yes
| 90,574 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.
<image>
Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time x (in seconds), so he asked you to tell him if it's gonna bark at that time.
Input
The first and only line of input contains three integers t, s and x (0 ≤ t, x ≤ 109, 2 ≤ s ≤ 109) — the time the pineapple barks for the first time, the pineapple barking interval, and the time Barney wants to eat the pineapple respectively.
Output
Print a single "YES" (without quotes) if the pineapple will bark at time x or a single "NO" (without quotes) otherwise in the only line of output.
Examples
Input
3 10 4
Output
NO
Input
3 10 3
Output
YES
Input
3 8 51
Output
YES
Input
3 8 52
Output
YES
Note
In the first and the second sample cases pineapple will bark at moments 3, 13, 14, ..., so it won't bark at the moment 4 and will bark at the moment 3.
In the third and fourth sample cases pineapple will bark at moments 3, 11, 12, 19, 20, 27, 28, 35, 36, 43, 44, 51, 52, 59, ..., so it will bark at both moments 51 and 52.
Submitted Solution:
```
t,s,x = map(int, input().split(" "))
res = x-t
if res < 0:
print("NO")
else:
if res % s == 0 or ((res-1) % s) == 0:
if res != 1:
print("YES")
else:
print("NO")
else:
print("NO")
```
Yes
| 90,575 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.
<image>
Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time x (in seconds), so he asked you to tell him if it's gonna bark at that time.
Input
The first and only line of input contains three integers t, s and x (0 ≤ t, x ≤ 109, 2 ≤ s ≤ 109) — the time the pineapple barks for the first time, the pineapple barking interval, and the time Barney wants to eat the pineapple respectively.
Output
Print a single "YES" (without quotes) if the pineapple will bark at time x or a single "NO" (without quotes) otherwise in the only line of output.
Examples
Input
3 10 4
Output
NO
Input
3 10 3
Output
YES
Input
3 8 51
Output
YES
Input
3 8 52
Output
YES
Note
In the first and the second sample cases pineapple will bark at moments 3, 13, 14, ..., so it won't bark at the moment 4 and will bark at the moment 3.
In the third and fourth sample cases pineapple will bark at moments 3, 11, 12, 19, 20, 27, 28, 35, 36, 43, 44, 51, 52, 59, ..., so it will bark at both moments 51 and 52.
Submitted Solution:
```
x,y,z=[int(a) for a in input().split()]
if x==z:
print("YES")
xx=x
while xx<z:
xx+=xx+y
if xx==z or xx+1==z:
print("YES")
quit()
if xx==z or xx+1==z:
print("YES")
else:
print("NO")
```
No
| 90,576 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.
<image>
Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time x (in seconds), so he asked you to tell him if it's gonna bark at that time.
Input
The first and only line of input contains three integers t, s and x (0 ≤ t, x ≤ 109, 2 ≤ s ≤ 109) — the time the pineapple barks for the first time, the pineapple barking interval, and the time Barney wants to eat the pineapple respectively.
Output
Print a single "YES" (without quotes) if the pineapple will bark at time x or a single "NO" (without quotes) otherwise in the only line of output.
Examples
Input
3 10 4
Output
NO
Input
3 10 3
Output
YES
Input
3 8 51
Output
YES
Input
3 8 52
Output
YES
Note
In the first and the second sample cases pineapple will bark at moments 3, 13, 14, ..., so it won't bark at the moment 4 and will bark at the moment 3.
In the third and fourth sample cases pineapple will bark at moments 3, 11, 12, 19, 20, 27, 28, 35, 36, 43, 44, 51, 52, 59, ..., so it will bark at both moments 51 and 52.
Submitted Solution:
```
t, s, x = map(int, input().split())
if x < t:
print('YES')
else:
if x == t + 1 and s != 1:
print('NO')
else:
if (x - t) % s == 0 or (x - t - 1) % s == 0:
print('YES')
else:
print('NO')
```
No
| 90,577 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.
<image>
Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time x (in seconds), so he asked you to tell him if it's gonna bark at that time.
Input
The first and only line of input contains three integers t, s and x (0 ≤ t, x ≤ 109, 2 ≤ s ≤ 109) — the time the pineapple barks for the first time, the pineapple barking interval, and the time Barney wants to eat the pineapple respectively.
Output
Print a single "YES" (without quotes) if the pineapple will bark at time x or a single "NO" (without quotes) otherwise in the only line of output.
Examples
Input
3 10 4
Output
NO
Input
3 10 3
Output
YES
Input
3 8 51
Output
YES
Input
3 8 52
Output
YES
Note
In the first and the second sample cases pineapple will bark at moments 3, 13, 14, ..., so it won't bark at the moment 4 and will bark at the moment 3.
In the third and fourth sample cases pineapple will bark at moments 3, 11, 12, 19, 20, 27, 28, 35, 36, 43, 44, 51, 52, 59, ..., so it will bark at both moments 51 and 52.
Submitted Solution:
```
import sys
container2=[]
t,s,x= map(int, input().split())
a=(x-t)//s
for i in range(a-10,a+10):
if x == t+i*s or x==t+1+(i+1)*s:
print('YES')
elif t+1+(i+1)*s<x<t+i*s:
print('NO')
```
No
| 90,578 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.
<image>
Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time x (in seconds), so he asked you to tell him if it's gonna bark at that time.
Input
The first and only line of input contains three integers t, s and x (0 ≤ t, x ≤ 109, 2 ≤ s ≤ 109) — the time the pineapple barks for the first time, the pineapple barking interval, and the time Barney wants to eat the pineapple respectively.
Output
Print a single "YES" (without quotes) if the pineapple will bark at time x or a single "NO" (without quotes) otherwise in the only line of output.
Examples
Input
3 10 4
Output
NO
Input
3 10 3
Output
YES
Input
3 8 51
Output
YES
Input
3 8 52
Output
YES
Note
In the first and the second sample cases pineapple will bark at moments 3, 13, 14, ..., so it won't bark at the moment 4 and will bark at the moment 3.
In the third and fourth sample cases pineapple will bark at moments 3, 11, 12, 19, 20, 27, 28, 35, 36, 43, 44, 51, 52, 59, ..., so it will bark at both moments 51 and 52.
Submitted Solution:
```
t,s,x=map(int,input().split())
if t==x:
print('YES')
else:
a=x//s
if t+a*s==x or t+a*s+1==x and x>s:
print('YES')
else:
print('NO')
```
No
| 90,579 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.
Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.
Input
The first line contains string a, and the second line — string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 105 characters.
Output
On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters.
If the answer consists of zero characters, output «-» (a minus sign).
Examples
Input
hi
bob
Output
-
Input
abca
accepted
Output
ac
Input
abacaba
abcdcba
Output
abcba
Note
In the first example strings a and b don't share any symbols, so the longest string that you can get is empty.
In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b.
Tags: binary search, hashing, strings, two pointers
Correct Solution:
```
a = list(input())
b = list(input())
s = [-1]
i = 0
j = 0
while i < len(a) and j < len(b):
if a[i] == b[j]:
s.append(i)
j += 1
i += 1
e = [10**6]
i = len(a) - 1
j = len(b) - 1
while i >= 0 and j >= 0:
if a[i] == b[j]:
e.append(i)
j -= 1
i -= 1
ans_len = 0
ans = ['-']
i = len(s) - 1
j = 0
while i >= 0 and j < len(e):
if s[i] < e[j] and i + j - 1< len(b):
new_len = j + i
if new_len > ans_len:
ans_len = new_len
if j > 0:
ans = b[:i] + b[-j:]
else:
ans = b[:i]
j += 1
else:
i -= 1
print(''.join(ans))
```
| 90,580 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.
Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.
Input
The first line contains string a, and the second line — string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 105 characters.
Output
On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters.
If the answer consists of zero characters, output «-» (a minus sign).
Examples
Input
hi
bob
Output
-
Input
abca
accepted
Output
ac
Input
abacaba
abcdcba
Output
abcba
Note
In the first example strings a and b don't share any symbols, so the longest string that you can get is empty.
In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b.
Tags: binary search, hashing, strings, two pointers
Correct Solution:
```
import math
def prefixIds(a, b):
prefSubsId = [math.inf] * len(b)
# print(a)
# print(b)
bId = 0
aId = 0
while aId < len(a):
if bId == len(b):
break
if a[aId] == b[bId]:
prefSubsId[bId] = aId + 1
bId += 1
aId += 1
else:
aId += 1
return prefSubsId
a = input()
b = input()
# print(a)
# print(b)
n = len(b)
prefLens = prefixIds(a, b)
suffLens = prefixIds(a[::-1], b[::-1])[::-1]
# for i in range(n):
# if suffLens[i] != math.inf:
# suffLens[i] = len(a) - suffLens[i]
# print(*prefLens, sep='\t')
# print(*suffLens, sep='\t')
prefLen = 0
suffLen = 0
minCutLen = n
lBorder = -1
rBorder = n
while suffLen < n and suffLens[suffLen] == math.inf:
suffLen += 1
curCutLen = suffLen
# print(curCutLen)
if curCutLen < minCutLen:
minCutLen = curCutLen
rBorder = suffLen
while prefLen < suffLen and prefLens[prefLen] != math.inf:
while suffLen < n and prefLens[prefLen] + suffLens[suffLen] > len(a):
# print(suffLen)
suffLen += 1
# print(prefLen)
# print(suffLen)
curCutLen = suffLen - prefLen - 1
# print(curCutLen)
if curCutLen < minCutLen:
minCutLen = curCutLen
lBorder = prefLen
rBorder = suffLen
prefLen += 1
# print(prefLens[prefLen])
# print(suffLens[suffLen])
# # print()
# print("pref, suff")
# print(prefLen)
# print(suffLen)
# print(minCutLen)
# print(n)
# print(lBorder)
# print(rBorder)
if minCutLen == n:
print('-')
elif minCutLen == 0:
print(b)
else:
print(b[:lBorder + 1] + b[rBorder:])
# print(maxPrefLen)
# print(maxSuffLen)
```
| 90,581 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.
Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.
Input
The first line contains string a, and the second line — string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 105 characters.
Output
On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters.
If the answer consists of zero characters, output «-» (a minus sign).
Examples
Input
hi
bob
Output
-
Input
abca
accepted
Output
ac
Input
abacaba
abcdcba
Output
abcba
Note
In the first example strings a and b don't share any symbols, so the longest string that you can get is empty.
In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b.
Tags: binary search, hashing, strings, two pointers
Correct Solution:
```
from sys import stdin
def main():
t = stdin.readline()
s = stdin.readline()
n = len(s) - 1
m = len(t) - 1
post = [-1] * n
ss = n - 1
st = m - 1
while st >= 0 and ss >= 0:
if t[st] == s[ss]:
post[ss] = st
ss -= 1
st -= 1
pre = [-1] * n
ss = 0
st = 0
while st < m and ss < n:
if t[st] == s[ss]:
pre[ss] = st
ss += 1
st += 1
low = 0
high = n
min_ans = n
start = -1
end = -1
while low < high:
mid = (low + high) >> 1
ok = False
if post[mid] != -1:
if mid < min_ans:
min_ans = mid
start = 0
end = mid - 1
ok = True
for i in range(1, n - mid):
if pre[i - 1] != -1 and post[i + mid] != -1 and post[i + mid] > pre[i - 1]:
if mid < min_ans:
min_ans = mid
start = i
end = i + mid - 1
ok = True
if pre[n - mid - 1] != -1:
if mid < min_ans:
min_ans = mid
start = n - mid
end = n - 1
ok = True
if not ok:
low = mid + 1
else:
high = mid
ans = []
for i in range(n):
if start <= i <= end:
continue
ans.append(s[i])
if min_ans == n:
print('-')
else:
print(''.join(ans))
if __name__ == '__main__':
main()
```
| 90,582 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.
Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.
Input
The first line contains string a, and the second line — string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 105 characters.
Output
On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters.
If the answer consists of zero characters, output «-» (a minus sign).
Examples
Input
hi
bob
Output
-
Input
abca
accepted
Output
ac
Input
abacaba
abcdcba
Output
abcba
Note
In the first example strings a and b don't share any symbols, so the longest string that you can get is empty.
In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b.
Tags: binary search, hashing, strings, two pointers
Correct Solution:
```
a = input()
b = input()
prefix = [-1] * len(b)
postfix = [-1] * len(b)
prefix[0] = a.find(b[0])
postfix[len(b) - 1] = a.rfind(b[len(b) - 1])
for i in range(1, len(b)):
prefix[i] = a.find(b[i], prefix[i - 1] + 1)
if prefix[i] == -1:
break
for i in range(len(b) - 2, -1, -1):
postfix[i] = a.rfind(b[i], 0, postfix[i+1])
if postfix[i] == -1:
break
best_left = -1
best_right = len(b)
left = -1
while left + 1 < len(b) and prefix[left + 1] != -1:
left += 1
if left > -1:
best_left = left
best_right = len(b)
right = len(b)
while right - 1 >= 0 and postfix[right - 1] != -1:
right -= 1
if right < len(b) and right + 1 < best_right - best_left:
best_left = -1
best_right = right
left = 0
right = len(b)
while left < right and postfix[right - 1] != -1 and postfix[right - 1] > prefix[left]:
right -= 1
while prefix[left] != -1 and left < right < len(b):
while right < len(b) and postfix[right] <= prefix[left]:
right += 1
if right >= len(b):
break
if right - left < best_right - best_left:
best_left = left
best_right = right
left += 1
if left == right:
right += 1
res = b[:best_left + 1] + b[best_right:]
if res == "":
print("-")
else:
print(res)
```
| 90,583 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.
Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.
Input
The first line contains string a, and the second line — string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 105 characters.
Output
On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters.
If the answer consists of zero characters, output «-» (a minus sign).
Examples
Input
hi
bob
Output
-
Input
abca
accepted
Output
ac
Input
abacaba
abcdcba
Output
abcba
Note
In the first example strings a and b don't share any symbols, so the longest string that you can get is empty.
In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b.
Tags: binary search, hashing, strings, two pointers
Correct Solution:
```
import sys
s, t = input(), '*'+input()
n, m = len(s), len(t)-1
inf = 10**9
pre, suf = [-1] + [inf]*(m+1), [-1]*(m+1) + [n]
i = 0
for j in range(1, m+1):
while i < n and s[i] != t[j]:
i += 1
if i == n:
break
pre[j] = i
i += 1
i = n-1
for j in range(m, 0, -1):
while 0 <= i and s[i] != t[j]:
i -= 1
if i == -1:
break
suf[j] = i
i -= 1
max_len, best_l, best_r = 0, 0, 0
j = 1
for i in range(m+1):
j = max(j, i+1)
while j <= m and pre[i] >= suf[j]:
j += 1
if pre[i] == inf:
break
if max_len < i + m + 1 - j:
max_len = i + m + 1 - j
best_l, best_r = i, j
pre_s = t[1:best_l+1]
suf_s = t[best_r:]
print(pre_s + suf_s if max_len else '-')
```
| 90,584 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.
Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.
Input
The first line contains string a, and the second line — string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 105 characters.
Output
On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters.
If the answer consists of zero characters, output «-» (a minus sign).
Examples
Input
hi
bob
Output
-
Input
abca
accepted
Output
ac
Input
abacaba
abcdcba
Output
abcba
Note
In the first example strings a and b don't share any symbols, so the longest string that you can get is empty.
In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b.
Tags: binary search, hashing, strings, two pointers
Correct Solution:
```
import sys
input = sys.stdin.readline
def solve():
a = input().strip()
b = input().strip()
n = len(a)
m = len(b)
c = [0]*m
d = [0]*m
p = 0
for i in range(m):
for j in range(p, n):
if a[j] == b[i]:
c[i] = j
p = j + 1
break
else:
for j in range(i,m):
c[j] = n
break
p = n-1
for i in range(m-1,-1,-1):
for j in range(p,-1,-1):
if a[j] == b[i]:
d[i] = j
p = j - 1
break
else:
for j in range(i,-1,-1):
d[j] = -1
break
j = 0
while j < m and d[j] < 0:
j += 1
res = (m-j, 0, j)
for i in range(m):
p = c[i]
if p == n:
break
while j < m and (j <= i or d[j] <= p):
j += 1
res = max(res,(i+1+m-j,i+1,j))
if res[0] == 0:
print('-')
else:
print(b[:res[1]]+b[res[2]:])
solve()
```
| 90,585 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.
Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.
Input
The first line contains string a, and the second line — string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 105 characters.
Output
On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters.
If the answer consists of zero characters, output «-» (a minus sign).
Examples
Input
hi
bob
Output
-
Input
abca
accepted
Output
ac
Input
abacaba
abcdcba
Output
abcba
Note
In the first example strings a and b don't share any symbols, so the longest string that you can get is empty.
In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b.
Tags: binary search, hashing, strings, two pointers
Correct Solution:
```
a, b = str(input()), str(input())
p, s, pp, sp = [0] * len(b), [0] * len(b), 0, len(a) - 1
p[0] = a.find(b[0])
while sp >= 0 and a[sp] != b[-1]:
sp -= 1
s[len(b) - 1] = sp
pp, sp = p[0] + 1, sp - 1
for i in range(1, len(b)):
if p[i - 1] == -1:
p[i] = -1
else:
while pp < len(a) and a[pp] != b[i]:
pp += 1
p[i] = (pp if pp < len(a) else -1)
pp += 1
for i in range(len(b) - 2, -1, -1):
if s[i + 1] == -1:
s[i] = -1
else:
while sp >= 0 and a[sp] != b[i]:
sp -= 1
s[i] = (sp if sp >= 0 else -1)
sp -= 1
anss, ans = 0, (-1, -1, -1)
for i in range(0, len(b)):
if p[i] == -1:
break
while anss < len(b) and (s[anss] <= p[i] or s[anss] == -1) or anss <= i:
anss += 1
ln = (i + 1 if p[i] != -1 else 0) + (len(b) - anss if anss < len(b) and s[anss] != -1 else 0)
if ln > ans[0]:
ans = (ln, i, anss)
only_s = len(b) - 1
while only_s - 1 >= 0 and s[only_s - 1] >= 0:
only_s -= 1
if only_s >= 0 and s[-1] >= 0 and len(b) - only_s > ans[0]:
print(b[only_s:])
elif ans[0] == -1:
print("-")
else:
print(b[:ans[1] + 1] + (b[ans[2]:] if ans[2] < len(b) else ""))
```
| 90,586 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.
Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.
Input
The first line contains string a, and the second line — string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 105 characters.
Output
On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters.
If the answer consists of zero characters, output «-» (a minus sign).
Examples
Input
hi
bob
Output
-
Input
abca
accepted
Output
ac
Input
abacaba
abcdcba
Output
abcba
Note
In the first example strings a and b don't share any symbols, so the longest string that you can get is empty.
In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b.
Tags: binary search, hashing, strings, two pointers
Correct Solution:
```
a=input()
b=input()
pre=[len(a) for i in range(len(b))]
suf=[-1 for i in range(len(b))]
temp=0
whole=0
for i in range(len(a)):
if b[temp]==a[i]:
pre[temp]=i
temp+=1
if temp==len(b):
whole=1
break
temp=len(b)-1
for i in range(len(a)-1,-1,-1):
if b[temp]==a[i]:
suf[temp]=i
temp-=1
if temp==-1:
whole=1
break
ans=[]
index=0
for i in range(len(b)):
temp=pre[i]
index=max(i+1,index)
start=index
for j in range(start,len(b)):
if suf[j]>pre[i]:
index=j
break
else:
index=len(b)
if index!=len(b) and pre[i]!=len(a):
ans+=[len(b)+1+i-index]
elif pre[i]==len(a):
ans+=[0]
elif index==len(b) and pre[i]!=len(a):
ans+=[i+1]
else:
ans+=[0]
MAXsufANS=0
MAXsufindex=len(b)
for i in range(len(b)-1,-1,-1):
if suf[i]!=-1:
MAXsufANS=len(b)-i
MAXsufindex=i
MAX=0
MAXindex=-1
for i in range(len(b)):
if ans[i]>MAX:
MAXindex=i
MAX=ans[i]
usesuf=0
if MAXsufANS>MAX:
usesuf=1
if whole==1:
print(b)
else:
if max(MAX,MAXsufANS)==0:
print('-')
else:
if usesuf==1:
anss=b[MAXsufindex:]
print(anss)
else:
m=MAXindex
L=MAX
anss=b[:m+1]+b[len(b)-(MAX-(m+1)):]
print(anss)
```
| 90,587 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.
Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.
Input
The first line contains string a, and the second line — string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 105 characters.
Output
On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters.
If the answer consists of zero characters, output «-» (a minus sign).
Examples
Input
hi
bob
Output
-
Input
abca
accepted
Output
ac
Input
abacaba
abcdcba
Output
abcba
Note
In the first example strings a and b don't share any symbols, so the longest string that you can get is empty.
In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b.
Submitted Solution:
```
#import sys
#sys.stdin = open('in', 'r')
#n = int(input())
#a = [int(x) for x in input().split()]
#n,m = map(int, input().split())
s1 = input()
s2 = input()
l1 = len(s1)
l2 = len(s2)
dl = {}
dr = {}
i1 = 0
i2 = 0
while i1 < l1 and i2 < l2:
while i1 < l1 and s1[i1] != s2[i2]:
i1 += 1
if i1 < l1:
dl[i2] = i1
i2 += 1
i1 += 1
lmax = i2
if lmax == l2:
print(s2)
else:
i1 = l1 - 1
i2 = l2 - 1
while i1 >= 0 and i2 >= 0:
while i1 >= 0 and s1[i1] != s2[i2]:
i1 -= 1
if i1 >= 0:
dr[i2] = i1
i2 -= 1
i1 -= 1
rmax = i2
le = -1
re = -1
if l2 - lmax < rmax + 1:
rcnt = l2 - lmax
ls = 0
rs = lmax
else:
rcnt = rmax + 1
ls = rmax + 1
rs = l2
rr = rmax + 1
for ll in range(lmax):
while rr < l2 and (rr <= ll or dl[ll] >= dr[rr]):
rr += 1
if rr < l2:
dif = rr - ll - 1
if dif < rcnt:
rcnt = dif
ls = 0
rs = ll + 1
le = rr
re = l2
result = s2[ls:rs]
if le != -1:
result += s2[le:re]
print(result if len(result) > 0 else '-')
```
Yes
| 90,588 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.
Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.
Input
The first line contains string a, and the second line — string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 105 characters.
Output
On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters.
If the answer consists of zero characters, output «-» (a minus sign).
Examples
Input
hi
bob
Output
-
Input
abca
accepted
Output
ac
Input
abacaba
abcdcba
Output
abcba
Note
In the first example strings a and b don't share any symbols, so the longest string that you can get is empty.
In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b.
Submitted Solution:
```
from macpath import curdir
import bisect
a=input()
b=input()
la=len(a)
lb=len(b)
forb=[la]*lb
cur=0
for i in range(lb):
while cur<la and a[cur]!=b[i]:
cur+=1
if cur<la:
forb[i]=cur
cur+=1
else:
break
cur=la-1
bacb=[-1]*lb
for i in range(lb-1,-1,-1):
while cur>=0 and a[cur]!=b[i]:
cur-=1
if cur>=0:
bacb[i]=cur
cur-=1
else:
break
res=lb
start=0
end=lb
for i in range(lb):
low=-1
if i>0 :
low=forb[i-1]
if low>=la:
break
j=bisect.bisect_right(bacb,low)
if res>j-i>=0:
res=j-i
start=i
end=j
if res==lb:
print('-')
else:
print(b[:start]+b[end:])
```
Yes
| 90,589 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.
Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.
Input
The first line contains string a, and the second line — string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 105 characters.
Output
On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters.
If the answer consists of zero characters, output «-» (a minus sign).
Examples
Input
hi
bob
Output
-
Input
abca
accepted
Output
ac
Input
abacaba
abcdcba
Output
abcba
Note
In the first example strings a and b don't share any symbols, so the longest string that you can get is empty.
In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b.
Submitted Solution:
```
# cook your dish here
a = list(input())
b = list(input())
m = len(a)
n = len(b)
s = [-1]
i = 0
j = 0
while i<m and j<n:
if(a[i]==b[j]):
s.append(i)
j+=1
i+=1
e = [1000000]
i = m-1
j= n-1
while i>=0 and j>=0:
if(a[i]==b[j]):
e.append(i)
j-=1
i-=1
i = len(s)-1
j = 0
ans = "-"
ctr = 0
while j<len(e) and i>=0:
if(s[i]<e[j]):
if(i+j > ctr and i+j<=len(b)):
ctr = i+j
if(j>0):
ans = b[:i] + b[-j:]
else:
ans = b[:i]
j+=1
else:
i -= 1
print(''.join(ans))
```
Yes
| 90,590 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.
Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.
Input
The first line contains string a, and the second line — string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 105 characters.
Output
On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters.
If the answer consists of zero characters, output «-» (a minus sign).
Examples
Input
hi
bob
Output
-
Input
abca
accepted
Output
ac
Input
abacaba
abcdcba
Output
abcba
Note
In the first example strings a and b don't share any symbols, so the longest string that you can get is empty.
In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b.
Submitted Solution:
```
a = input()
b = input()
p = [None] * (len(b) + 1)
s = [None] * (len(b) + 1)
j = 0
p[0] = -1
for i in range(len(b)):
while j < len(a) and a[j] != b[i]:
j += 1
if j >= len(a):
break
else:
p[i + 1] = j
j += 1
j = len(a) - 1
s[-1] = len(b)
for i in range(len(b) - 1, -1, -1):
while j >= 0 and a[j] != b[i]:
j -= 1
if j < 0:
break
else:
s[i] = j
j -= 1
ans = ""
for i in range(len(b) + 1):
if p[i] == None:
break
else:
l = i - 1
r = len(b)
while l + 1 < r:
mid = (l + r) // 2
if s[mid] != None and p[i] < s[mid]:
r = mid
else:
l = mid
if len(ans) < i + len(b) - r:
ans = b[:i] + b[r:]
if ans == "":
print("-")
else:
print(ans)
```
Yes
| 90,591 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.
Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.
Input
The first line contains string a, and the second line — string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 105 characters.
Output
On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters.
If the answer consists of zero characters, output «-» (a minus sign).
Examples
Input
hi
bob
Output
-
Input
abca
accepted
Output
ac
Input
abacaba
abcdcba
Output
abcba
Note
In the first example strings a and b don't share any symbols, so the longest string that you can get is empty.
In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b.
Submitted Solution:
```
import sys
s = list(map(lambda c: ord(c)-97, input()))
t = list(map(lambda c: ord(c)-97, input()))
n, m = len(s), len(t)
next_c = [[-1]*26 for _ in range(n+1)]
for i in range(n-1, -1, -1):
for j in range(26):
next_c[i][j] = next_c[i+1][j]
next_c[i][s[i]] = i+1
minf = -(10**9)
dp = [[minf, minf, minf] for _ in range(m+1)]
dp_i = [[0, 0, 0] for _ in range(m+1)]
dp[0][0] = 0
def solve1(i1, j1, i2, j2, c):
next_i = next_c[dp_i[i2][j2]][c]
if next_i != -1 and (dp[i1][j1] < dp[i2][j2]+1 or dp[i1][j1] == dp[i2][j2]+1 and dp_i[i1][j1] > next_i):
dp[i1][j1] = dp[i2][j2]+1
dp_i[i1][j1] = next_i
def solve2(i1, j1, i2, j2):
if dp[i1][j1] < dp[i2][j2] or dp[i1][j1] == dp[i2][j2] and dp_i[i1][j1] > dp_i[i2][j2]:
dp[i1][j1] = dp[i2][j2]
dp_i[i1][j1] = dp_i[i2][j2]
for i in range(m):
solve1(i+1, 0, i, 0, t[i])
solve2(i+1, 1, i, 0)
solve2(i+1, 1, i, 1)
solve1(i+1, 2, i, 1, t[i])
solve1(i+1, 2, i, 2, t[i])
i, j, max_len = 0, 0, 0
for jj in range(3):
if max_len < dp[m][jj]:
i, j, max_len = m, jj, dp[m][jj]
ans = []
while i > 0:
if j == 1 and dp[i-1][j] == dp[i][j] and dp_i[i-1][j] == dp_i[i][j]:
i -= 1
continue
if j == 1 and dp[i-1][j-1] == dp[i][j] and dp_i[i-1][j-1] == dp_i[i][j]:
i -= 1
j -= 1
continue
if j != 1 and dp[i-1][j]+1 == dp[i][j] and dp_i[i-1][j] < dp_i[i][j]:
ans.append(chr(97 + t[i-1]))
i -= 1
continue
if j == 2 and dp[i-1][j-1]+1 == dp[i][j] and dp_i[i-1][j-1] < dp_i[i][j]:
ans.append(chr(97 + t[i-1]))
i -= 1
j -= 1
print(''.join(reversed(ans)) if ans else '-')
```
No
| 90,592 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.
Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.
Input
The first line contains string a, and the second line — string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 105 characters.
Output
On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters.
If the answer consists of zero characters, output «-» (a minus sign).
Examples
Input
hi
bob
Output
-
Input
abca
accepted
Output
ac
Input
abacaba
abcdcba
Output
abcba
Note
In the first example strings a and b don't share any symbols, so the longest string that you can get is empty.
In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b.
Submitted Solution:
```
a=input()
b=input()
aa=list(a)
bb=list(b)
cc=[]
for i in range(len(aa)):
for j in range(len(bb)):
if aa[i]==bb[j]:
cc.append(aa[i])
bb.pop(j)
break
if len(cc)==0:
print('-')
else:
for i in range(len(b)):
for j in range(len(cc)):
if b[i]==cc[j]:
print(b[i],end='')
cc.pop(j)
break
```
No
| 90,593 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.
Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.
Input
The first line contains string a, and the second line — string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 105 characters.
Output
On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters.
If the answer consists of zero characters, output «-» (a minus sign).
Examples
Input
hi
bob
Output
-
Input
abca
accepted
Output
ac
Input
abacaba
abcdcba
Output
abcba
Note
In the first example strings a and b don't share any symbols, so the longest string that you can get is empty.
In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b.
Submitted Solution:
```
a=str(input())
b=str(input())
counter=0
i=0
j=0
while i<len(b):
if(a[j]!=b[i] ):
k=j
while True:
if(k>len(a)-1):
break
if(a[k]==b[i]):
break
k+=1
if(k==len(a)):
newstr = b.replace(b[i], "")
b=newstr
counter+=1
i+=1
j+=1
if(not(j<len(a))):
break
if(counter==len(a)-1):
print("_")
else:
print(b)
```
No
| 90,594 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.
Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.
Input
The first line contains string a, and the second line — string b. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 105 characters.
Output
On the first line output a subsequence of string a, obtained from b by erasing the minimum number of consecutive characters.
If the answer consists of zero characters, output «-» (a minus sign).
Examples
Input
hi
bob
Output
-
Input
abca
accepted
Output
ac
Input
abacaba
abcdcba
Output
abcba
Note
In the first example strings a and b don't share any symbols, so the longest string that you can get is empty.
In the second example ac is a subsequence of a, and at the same time you can obtain it by erasing consecutive symbols cepted from string b.
Submitted Solution:
```
import sys
s = list(map(lambda c: ord(c)-97, input()))
t = list(map(lambda c: ord(c)-97, input()))
n, m = len(s), len(t)
i = n-1
ans1 = []
for j in range(m-1, -1, -1):
while 0 <= i and s[i] != t[j]:
i -= 1
if i < 0:
break
ans1.append(chr(97 + t[j]))
i -= 1
next_c = [[-1]*26 for _ in range(n+1)]
for i in range(n-1, -1, -1):
for j in range(26):
next_c[i][j] = next_c[i+1][j]
next_c[i][s[i]] = i+1
minf = -(10**9)
dp = [[minf, 0, minf] for _ in range(m+1)]
dp_i = [[0, 0, 0] for _ in range(m+1)]
dp[0][0] = 0
prev = [[(0, 0, 0), (0, 0, 0), (0, 0, 0)] for _ in range(m+1)]
def solve1(i1, j1, i2, j2, c):
next_i = next_c[dp_i[i2][j2]][c]
if next_i != -1 and (dp[i1][j1] < dp[i2][j2]+1 or dp[i1][j1] == dp[i2][j2]+1 and dp_i[i1][j1] > next_i):
dp[i1][j1] = dp[i2][j2]+1
dp_i[i1][j1] = next_i
prev[i1][j1] = (i2, j2, 1)
def solve2(i1, j1, i2, j2):
if dp[i1][j1] < dp[i2][j2] or dp[i1][j1] == dp[i2][j2] and dp_i[i1][j1] > dp_i[i2][j2]:
dp[i1][j1] = dp[i2][j2]
dp_i[i1][j1] = dp_i[i2][j2]
prev[i1][j1] = (i2, j2, 0)
for i in range(m):
solve1(i+1, 0, i, 0, t[i])
solve2(i+1, 1, i, 0)
solve2(i+1, 1, i, 1)
solve1(i+1, 2, i, 1, t[i])
solve1(i+1, 2, i, 2, t[i])
i, j, max_len = 0, 0, 0
for jj in range(3):
if max_len < dp[m][jj]:
i, j, max_len = m, jj, dp[m][jj]
ans = []
while i > 0:
i, j, flag = prev[i][j]
if flag:
ans.append(chr(97 + t[i]))
if len(ans1) > len(ans):
ans = ''.join(reversed(ans1))
else:
ans = ''.join(reversed(ans))
print(ans if ans else '-')
```
No
| 90,595 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you probably know, Anton goes to school. One of the school subjects that Anton studies is Bracketology. On the Bracketology lessons students usually learn different sequences that consist of round brackets (characters "(" and ")" (without quotes)).
On the last lesson Anton learned about the regular simple bracket sequences (RSBS). A bracket sequence s of length n is an RSBS if the following conditions are met:
* It is not empty (that is n ≠ 0).
* The length of the sequence is even.
* First <image> charactes of the sequence are equal to "(".
* Last <image> charactes of the sequence are equal to ")".
For example, the sequence "((()))" is an RSBS but the sequences "((())" and "(()())" are not RSBS.
Elena Ivanovna, Anton's teacher, gave him the following task as a homework. Given a bracket sequence s. Find the number of its distinct subsequences such that they are RSBS. Note that a subsequence of s is a string that can be obtained from s by deleting some of its elements. Two subsequences are considered distinct if distinct sets of positions are deleted.
Because the answer can be very big and Anton's teacher doesn't like big numbers, she asks Anton to find the answer modulo 109 + 7.
Anton thought of this task for a very long time, but he still doesn't know how to solve it. Help Anton to solve this task and write a program that finds the answer for it!
Input
The only line of the input contains a string s — the bracket sequence given in Anton's homework. The string consists only of characters "(" and ")" (without quotes). It's guaranteed that the string is not empty and its length doesn't exceed 200 000.
Output
Output one number — the answer for the task modulo 109 + 7.
Examples
Input
)(()()
Output
6
Input
()()()
Output
7
Input
)))
Output
0
Note
In the first sample the following subsequences are possible:
* If we delete characters at the positions 1 and 5 (numbering starts with one), we will get the subsequence "(())".
* If we delete characters at the positions 1, 2, 3 and 4, we will get the subsequence "()".
* If we delete characters at the positions 1, 2, 4 and 5, we will get the subsequence "()".
* If we delete characters at the positions 1, 2, 5 and 6, we will get the subsequence "()".
* If we delete characters at the positions 1, 3, 4 and 5, we will get the subsequence "()".
* If we delete characters at the positions 1, 3, 5 and 6, we will get the subsequence "()".
The rest of the subsequnces are not RSBS. So we got 6 distinct subsequences that are RSBS, so the answer is 6.
Tags: combinatorics, dp, math, number theory
Correct Solution:
```
t = input()
n, m = len(t) + 1, 1000000007
a, b = 0, t.count(')') - 1
f = [1] * n
for i in range(2, n): f[i] = i * f[i - 1] % m
g = [pow(q, m - 2, m) for q in f]
s = 0
for q in t:
if b < 0: break
if q == '(':
a += 1
s += f[a + b] * g[a] * g[b]
else: b -= 1
print(s % m)
```
| 90,596 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you probably know, Anton goes to school. One of the school subjects that Anton studies is Bracketology. On the Bracketology lessons students usually learn different sequences that consist of round brackets (characters "(" and ")" (without quotes)).
On the last lesson Anton learned about the regular simple bracket sequences (RSBS). A bracket sequence s of length n is an RSBS if the following conditions are met:
* It is not empty (that is n ≠ 0).
* The length of the sequence is even.
* First <image> charactes of the sequence are equal to "(".
* Last <image> charactes of the sequence are equal to ")".
For example, the sequence "((()))" is an RSBS but the sequences "((())" and "(()())" are not RSBS.
Elena Ivanovna, Anton's teacher, gave him the following task as a homework. Given a bracket sequence s. Find the number of its distinct subsequences such that they are RSBS. Note that a subsequence of s is a string that can be obtained from s by deleting some of its elements. Two subsequences are considered distinct if distinct sets of positions are deleted.
Because the answer can be very big and Anton's teacher doesn't like big numbers, she asks Anton to find the answer modulo 109 + 7.
Anton thought of this task for a very long time, but he still doesn't know how to solve it. Help Anton to solve this task and write a program that finds the answer for it!
Input
The only line of the input contains a string s — the bracket sequence given in Anton's homework. The string consists only of characters "(" and ")" (without quotes). It's guaranteed that the string is not empty and its length doesn't exceed 200 000.
Output
Output one number — the answer for the task modulo 109 + 7.
Examples
Input
)(()()
Output
6
Input
()()()
Output
7
Input
)))
Output
0
Note
In the first sample the following subsequences are possible:
* If we delete characters at the positions 1 and 5 (numbering starts with one), we will get the subsequence "(())".
* If we delete characters at the positions 1, 2, 3 and 4, we will get the subsequence "()".
* If we delete characters at the positions 1, 2, 4 and 5, we will get the subsequence "()".
* If we delete characters at the positions 1, 2, 5 and 6, we will get the subsequence "()".
* If we delete characters at the positions 1, 3, 4 and 5, we will get the subsequence "()".
* If we delete characters at the positions 1, 3, 5 and 6, we will get the subsequence "()".
The rest of the subsequnces are not RSBS. So we got 6 distinct subsequences that are RSBS, so the answer is 6.
Tags: combinatorics, dp, math, number theory
Correct Solution:
```
mod = 10 ** 9 + 7
s = input()
n = len(s)
f = [1] * (n + 1)
for i in range(1, n + 1): f[i] = i * f[i - 1] % mod
finv = [pow(x, mod - 2, mod) for x in f]
op = 0
cl = s.count(')')
ans = 0
if cl > 0:
for c in s:
if c == '(':
op += 1
ans += f[op + cl - 1] * finv[cl - 1] * finv[op]
elif cl <= 1:
break
else:
cl -= 1
print(ans % mod)
```
| 90,597 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you probably know, Anton goes to school. One of the school subjects that Anton studies is Bracketology. On the Bracketology lessons students usually learn different sequences that consist of round brackets (characters "(" and ")" (without quotes)).
On the last lesson Anton learned about the regular simple bracket sequences (RSBS). A bracket sequence s of length n is an RSBS if the following conditions are met:
* It is not empty (that is n ≠ 0).
* The length of the sequence is even.
* First <image> charactes of the sequence are equal to "(".
* Last <image> charactes of the sequence are equal to ")".
For example, the sequence "((()))" is an RSBS but the sequences "((())" and "(()())" are not RSBS.
Elena Ivanovna, Anton's teacher, gave him the following task as a homework. Given a bracket sequence s. Find the number of its distinct subsequences such that they are RSBS. Note that a subsequence of s is a string that can be obtained from s by deleting some of its elements. Two subsequences are considered distinct if distinct sets of positions are deleted.
Because the answer can be very big and Anton's teacher doesn't like big numbers, she asks Anton to find the answer modulo 109 + 7.
Anton thought of this task for a very long time, but he still doesn't know how to solve it. Help Anton to solve this task and write a program that finds the answer for it!
Input
The only line of the input contains a string s — the bracket sequence given in Anton's homework. The string consists only of characters "(" and ")" (without quotes). It's guaranteed that the string is not empty and its length doesn't exceed 200 000.
Output
Output one number — the answer for the task modulo 109 + 7.
Examples
Input
)(()()
Output
6
Input
()()()
Output
7
Input
)))
Output
0
Note
In the first sample the following subsequences are possible:
* If we delete characters at the positions 1 and 5 (numbering starts with one), we will get the subsequence "(())".
* If we delete characters at the positions 1, 2, 3 and 4, we will get the subsequence "()".
* If we delete characters at the positions 1, 2, 4 and 5, we will get the subsequence "()".
* If we delete characters at the positions 1, 2, 5 and 6, we will get the subsequence "()".
* If we delete characters at the positions 1, 3, 4 and 5, we will get the subsequence "()".
* If we delete characters at the positions 1, 3, 5 and 6, we will get the subsequence "()".
The rest of the subsequnces are not RSBS. So we got 6 distinct subsequences that are RSBS, so the answer is 6.
Tags: combinatorics, dp, math, number theory
Correct Solution:
```
mod = 10 ** 9 + 7
fact, inv, invfact = [1, 1], [0, 1], [1, 1]
for i in range(2, 200200):
fact.append(fact[-1] * i % mod)
inv.append(inv[mod % i] * (mod - mod // i) % mod)
invfact.append(invfact[-1] * inv[-1] % mod)
def C(n, k):
if k < 0 or k > n:
return 0
return fact[n] * invfact[k] * invfact[n - k] % mod
s = input()
op, cl = 0, s.count(')')
ans = 0
for x in s:
if x == '(':
op += 1
cur = C(cl + op - 1, op)
ans += cur
else:
cl -= 1
print(ans % mod)
```
| 90,598 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you probably know, Anton goes to school. One of the school subjects that Anton studies is Bracketology. On the Bracketology lessons students usually learn different sequences that consist of round brackets (characters "(" and ")" (without quotes)).
On the last lesson Anton learned about the regular simple bracket sequences (RSBS). A bracket sequence s of length n is an RSBS if the following conditions are met:
* It is not empty (that is n ≠ 0).
* The length of the sequence is even.
* First <image> charactes of the sequence are equal to "(".
* Last <image> charactes of the sequence are equal to ")".
For example, the sequence "((()))" is an RSBS but the sequences "((())" and "(()())" are not RSBS.
Elena Ivanovna, Anton's teacher, gave him the following task as a homework. Given a bracket sequence s. Find the number of its distinct subsequences such that they are RSBS. Note that a subsequence of s is a string that can be obtained from s by deleting some of its elements. Two subsequences are considered distinct if distinct sets of positions are deleted.
Because the answer can be very big and Anton's teacher doesn't like big numbers, she asks Anton to find the answer modulo 109 + 7.
Anton thought of this task for a very long time, but he still doesn't know how to solve it. Help Anton to solve this task and write a program that finds the answer for it!
Input
The only line of the input contains a string s — the bracket sequence given in Anton's homework. The string consists only of characters "(" and ")" (without quotes). It's guaranteed that the string is not empty and its length doesn't exceed 200 000.
Output
Output one number — the answer for the task modulo 109 + 7.
Examples
Input
)(()()
Output
6
Input
()()()
Output
7
Input
)))
Output
0
Note
In the first sample the following subsequences are possible:
* If we delete characters at the positions 1 and 5 (numbering starts with one), we will get the subsequence "(())".
* If we delete characters at the positions 1, 2, 3 and 4, we will get the subsequence "()".
* If we delete characters at the positions 1, 2, 4 and 5, we will get the subsequence "()".
* If we delete characters at the positions 1, 2, 5 and 6, we will get the subsequence "()".
* If we delete characters at the positions 1, 3, 4 and 5, we will get the subsequence "()".
* If we delete characters at the positions 1, 3, 5 and 6, we will get the subsequence "()".
The rest of the subsequnces are not RSBS. So we got 6 distinct subsequences that are RSBS, so the answer is 6.
Tags: combinatorics, dp, math, number theory
Correct Solution:
```
#!/usr/bin/env python3
def ri():
return map(int, input().split())
m = 10**9+7
s = input()
n = len(s)
o = [0 for i in range(len(s))]
c = [0 for i in range(len(s))]
fac = [0 for i in range(n)]
fac[0] = 1
for i in range(1,n):
fac[i] = fac[i-1]*i%m
invfac = [pow(fac[i], m-2, m) for i in range(n)]
if s[0] == '(':
o[0] = 1
for i in range(1,n):
if s[i] == '(':
o[i] = o[i-1] + 1
else:
o[i] = o[i-1]
if s[n-1] == ')':
c[n-1] = 1
for i in range(n-2, -1, -1):
if s[i] == ')':
c[i] = c[i+1] + 1
else:
c[i] = c[i+1]
ans = 0
for i in range(n):
if s[i] == '(':
a = o[i]
b = c[i]
if a != 0 and b != 0:
ans += fac[a+b-1]*invfac[a]*invfac[b-1]
ans %= m
print(ans)
```
| 90,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.