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.
Little Petya loves counting. He wants to count the number of ways to paint a rectangular checkered board of size n Γ m (n rows, m columns) in k colors. Besides, the coloring should have the following property: for any vertical line that passes along the grid lines and divides the board in two non-empty parts the number of distinct colors in both these parts should be the same. Help Petya to count these colorings.
Input
The first line contains space-separated integers n, m and k (1 β€ n, m β€ 1000, 1 β€ k β€ 106) β the board's vertical and horizontal sizes and the number of colors respectively.
Output
Print the answer to the problem. As the answer can be quite a large number, you should print it modulo 109 + 7 (1000000007).
Examples
Input
2 2 1
Output
1
Input
2 2 2
Output
8
Input
3 2 2
Output
40
Submitted Solution:
```
def inv(x):
return pow(x, mod - 2, mod)
def C(n, k):
if (k > n):
return 0
return f[n] * inv(f[k]) % mod * inv(f[n - k]) % mod
def calc(x, y):
if not y:
return pow(x, n, mod) - pow(x - 1, n, mod)
return (pow(x, n, mod) * C(k, y) - pow(x - 1, n, mod) * C(k, y - 1)) % mod
n, m, k = map(int, input().split())
mod = 1000000007
f = [1]
for i in range(1, 1000001):
f.append(f[-1] * i % mod)
ans = 0
if m == 1:
print(pow(k, n, mod))
exit()
for x in range(1, min(k, n) + 1):
if m == 2:
ans += calc(x, x) * calc(x, x)
ans %= mod
else:
for y in range(0, x + 1):
ans += calc(x, x) * calc(x, x - y) % mod * pow(y, n * (m - 2), mod)
ans %= mod
print(ans)
```
No
| 8,400 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Petya loves counting. He wants to count the number of ways to paint a rectangular checkered board of size n Γ m (n rows, m columns) in k colors. Besides, the coloring should have the following property: for any vertical line that passes along the grid lines and divides the board in two non-empty parts the number of distinct colors in both these parts should be the same. Help Petya to count these colorings.
Input
The first line contains space-separated integers n, m and k (1 β€ n, m β€ 1000, 1 β€ k β€ 106) β the board's vertical and horizontal sizes and the number of colors respectively.
Output
Print the answer to the problem. As the answer can be quite a large number, you should print it modulo 109 + 7 (1000000007).
Examples
Input
2 2 1
Output
1
Input
2 2 2
Output
8
Input
3 2 2
Output
40
Submitted Solution:
```
#!/usr/bin/env python3
import math
MODULO = 1000000007
def nr_choices(total, to_pick):
# n choose k function
return int(math.factorial(total) / math.factorial(to_pick) * math.factorial(total-to_pick))
(n,m,k) = map(int, input().split())
prev_combinations = k
answer = k**m % MODULO
for nr_colors in range(2, k+1):
new_combinations = ((nr_colors**n) - prev_combinations) % MODULO
prev_combinations = new_combinations
answer += nr_choices(k, nr_colors) * new_combinations**m
print(answer % MODULO)
```
No
| 8,401 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Petya loves counting. He wants to count the number of ways to paint a rectangular checkered board of size n Γ m (n rows, m columns) in k colors. Besides, the coloring should have the following property: for any vertical line that passes along the grid lines and divides the board in two non-empty parts the number of distinct colors in both these parts should be the same. Help Petya to count these colorings.
Input
The first line contains space-separated integers n, m and k (1 β€ n, m β€ 1000, 1 β€ k β€ 106) β the board's vertical and horizontal sizes and the number of colors respectively.
Output
Print the answer to the problem. As the answer can be quite a large number, you should print it modulo 109 + 7 (1000000007).
Examples
Input
2 2 1
Output
1
Input
2 2 2
Output
8
Input
3 2 2
Output
40
Submitted Solution:
```
def inv(x):
return pow(x, mod - 2, mod)
def C(n, k):
if (k > n):
return 0
return f[n] * inv(f[k]) % mod * inv(f[n - k]) % mod
def calc(x):
return (pow(x, n, mod) * C(k, x) - pow(x - 1, n, mod) * C(k, x - 1)) % mod
n, m, k = map(int, input().split())
mod = 1000000007
f = [1]
for i in range(1, 1000001):
f.append(f[-1] * i % mod)
ans = 0
for x in range(1, k + 1):
if (2 * x >= k):
ans += calc(x) * calc(x) % mod * pow(max(1, n * (m - 2)), 2 * x - k, mod) % mod
print(ans)
```
No
| 8,402 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent.
Alice initially has a token on some cell on the line, and Bob tries to guess where it is.
Bob guesses a sequence of line cell numbers x_1, x_2, β¦, x_k in order. In the i-th question, Bob asks Alice if her token is currently on cell x_i. That is, Alice can answer either "YES" or "NO" to each Bob's question.
At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.
Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.
You are given n and Bob's questions x_1, β¦, x_k. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Let (a,b) denote a scenario where Alice starts at cell a and ends at cell b. Two scenarios (a_i, b_i) and (a_j, b_j) are different if a_i β a_j or b_i β b_j.
Input
The first line contains two integers n and k (1 β€ n,k β€ 10^5) β the number of cells and the number of questions Bob asked.
The second line contains k integers x_1, x_2, β¦, x_k (1 β€ x_i β€ n) β Bob's questions.
Output
Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Examples
Input
5 3
5 1 4
Output
9
Input
4 8
1 2 3 4 4 3 2 1
Output
0
Input
100000 1
42
Output
299997
Note
The notation (i,j) denotes a scenario where Alice starts at cell i and ends at cell j.
In the first example, the valid scenarios are (1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5). For example, (3,4) is valid since Alice can start at cell 3, stay there for the first three questions, then move to cell 4 after the last question.
(4,5) is valid since Alice can start at cell 4, stay there for the first question, the move to cell 5 for the next two questions. Note that (4,5) is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.
In the second example, Alice has no valid scenarios.
In the last example, all (i,j) where |i-j| β€ 1 except for (42, 42) are valid scenarios.
Tags: graphs
Correct Solution:
```
n,k=map(int,input().split())
arr=list(map(int,input().split()))
dict1={}
for i in range(1,n+1):
dict1[i]=[]
for i in range(k):
dict1[arr[i]].append(i)
ans=0
for i in range(1,n+1):
if(i==1):
if(n==1):
break
if(len(dict1[1])==0):
ans+=2
else:
if(len(dict1[2])==0):
ans+=1
else:
if(dict1[2][-1]<dict1[1][0]):
ans+=1
elif(i==n):
if(len(dict1[n])==0):
ans+=2
else:
if(len(dict1[n-1])==0):
ans+=1
else:
if(dict1[n-1][-1]<dict1[n][0]):
ans+=1
else:
if(len(dict1[i])==0):
ans+=3
else:
if(len(dict1[i-1])==0):
ans+=1
else:
if(dict1[i-1][-1]<dict1[i][0]):
ans+=1
if(len(dict1[i+1])==0):
ans+=1
else:
if(dict1[i+1][-1]<dict1[i][0]):
ans+=1
print(ans)
```
| 8,403 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent.
Alice initially has a token on some cell on the line, and Bob tries to guess where it is.
Bob guesses a sequence of line cell numbers x_1, x_2, β¦, x_k in order. In the i-th question, Bob asks Alice if her token is currently on cell x_i. That is, Alice can answer either "YES" or "NO" to each Bob's question.
At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.
Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.
You are given n and Bob's questions x_1, β¦, x_k. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Let (a,b) denote a scenario where Alice starts at cell a and ends at cell b. Two scenarios (a_i, b_i) and (a_j, b_j) are different if a_i β a_j or b_i β b_j.
Input
The first line contains two integers n and k (1 β€ n,k β€ 10^5) β the number of cells and the number of questions Bob asked.
The second line contains k integers x_1, x_2, β¦, x_k (1 β€ x_i β€ n) β Bob's questions.
Output
Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Examples
Input
5 3
5 1 4
Output
9
Input
4 8
1 2 3 4 4 3 2 1
Output
0
Input
100000 1
42
Output
299997
Note
The notation (i,j) denotes a scenario where Alice starts at cell i and ends at cell j.
In the first example, the valid scenarios are (1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5). For example, (3,4) is valid since Alice can start at cell 3, stay there for the first three questions, then move to cell 4 after the last question.
(4,5) is valid since Alice can start at cell 4, stay there for the first question, the move to cell 5 for the next two questions. Note that (4,5) is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.
In the second example, Alice has no valid scenarios.
In the last example, all (i,j) where |i-j| β€ 1 except for (42, 42) are valid scenarios.
Tags: graphs
Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().strip("\r\n")
n, k = map(int, input().split())
x = list(map(int, input().split()))
first = [k] * (n+1)
last = [-1] * (n+1)
for i in range(1, k+1):
last[x[i-1]] = i
for i in range(k, 0, -1):
first[x[i-1]] = i
ans = 0
# print(first)
# print(last)
for i in range(1, n+1):
if last[i] == -1:
ans += 1
for i in range(1, n):
if first[i] >= last[i+1]:
ans += 1
if first[i+1] >= last[i]:
ans += 1
print(ans)
```
| 8,404 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent.
Alice initially has a token on some cell on the line, and Bob tries to guess where it is.
Bob guesses a sequence of line cell numbers x_1, x_2, β¦, x_k in order. In the i-th question, Bob asks Alice if her token is currently on cell x_i. That is, Alice can answer either "YES" or "NO" to each Bob's question.
At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.
Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.
You are given n and Bob's questions x_1, β¦, x_k. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Let (a,b) denote a scenario where Alice starts at cell a and ends at cell b. Two scenarios (a_i, b_i) and (a_j, b_j) are different if a_i β a_j or b_i β b_j.
Input
The first line contains two integers n and k (1 β€ n,k β€ 10^5) β the number of cells and the number of questions Bob asked.
The second line contains k integers x_1, x_2, β¦, x_k (1 β€ x_i β€ n) β Bob's questions.
Output
Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Examples
Input
5 3
5 1 4
Output
9
Input
4 8
1 2 3 4 4 3 2 1
Output
0
Input
100000 1
42
Output
299997
Note
The notation (i,j) denotes a scenario where Alice starts at cell i and ends at cell j.
In the first example, the valid scenarios are (1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5). For example, (3,4) is valid since Alice can start at cell 3, stay there for the first three questions, then move to cell 4 after the last question.
(4,5) is valid since Alice can start at cell 4, stay there for the first question, the move to cell 5 for the next two questions. Note that (4,5) is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.
In the second example, Alice has no valid scenarios.
In the last example, all (i,j) where |i-j| β€ 1 except for (42, 42) are valid scenarios.
Tags: graphs
Correct Solution:
```
import sys
n, k = map(int, input().split())
q = list(map(int, input().split()))
if n == 1:
print(0)
sys.exit()
res = max(n - 2, 0) * 3 + 4
#
# st = set(q)
# res -= len(st)
#
# arr = [2] + [3] * max(n - 2, 0) + [2]
arr = [0] * n
l_flags = [False] * n
r_flags = [False] * n
for i in q:
i -= 1
if arr[i] == 0:
res -= 1
arr[i] += 1
if i > 0 and arr[i - 1] > 0 and not l_flags[i]:
res -= 1
l_flags[i] = True
if i < n - 1 and arr[i + 1] > 0 and not r_flags[i]:
res -= 1
r_flags[i] = True
print(res)
```
| 8,405 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent.
Alice initially has a token on some cell on the line, and Bob tries to guess where it is.
Bob guesses a sequence of line cell numbers x_1, x_2, β¦, x_k in order. In the i-th question, Bob asks Alice if her token is currently on cell x_i. That is, Alice can answer either "YES" or "NO" to each Bob's question.
At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.
Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.
You are given n and Bob's questions x_1, β¦, x_k. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Let (a,b) denote a scenario where Alice starts at cell a and ends at cell b. Two scenarios (a_i, b_i) and (a_j, b_j) are different if a_i β a_j or b_i β b_j.
Input
The first line contains two integers n and k (1 β€ n,k β€ 10^5) β the number of cells and the number of questions Bob asked.
The second line contains k integers x_1, x_2, β¦, x_k (1 β€ x_i β€ n) β Bob's questions.
Output
Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Examples
Input
5 3
5 1 4
Output
9
Input
4 8
1 2 3 4 4 3 2 1
Output
0
Input
100000 1
42
Output
299997
Note
The notation (i,j) denotes a scenario where Alice starts at cell i and ends at cell j.
In the first example, the valid scenarios are (1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5). For example, (3,4) is valid since Alice can start at cell 3, stay there for the first three questions, then move to cell 4 after the last question.
(4,5) is valid since Alice can start at cell 4, stay there for the first question, the move to cell 5 for the next two questions. Note that (4,5) is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.
In the second example, Alice has no valid scenarios.
In the last example, all (i,j) where |i-j| β€ 1 except for (42, 42) are valid scenarios.
Tags: graphs
Correct Solution:
```
from math import *
from collections import *
from bisect import *
import sys
input=sys.stdin.readline
t=1
while(t):
t-=1
n,k=map(int,input().split())
a=list(map(int,input().split()))
vis=set()
for i in a:
vis.add((i,i))
if((i-1,i-1) in vis):
vis.add((i-1,i))
if((i+1,i+1) in vis):
vis.add((i+1,i))
r=n+(2*n)-2
print(r-len(vis))
```
| 8,406 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent.
Alice initially has a token on some cell on the line, and Bob tries to guess where it is.
Bob guesses a sequence of line cell numbers x_1, x_2, β¦, x_k in order. In the i-th question, Bob asks Alice if her token is currently on cell x_i. That is, Alice can answer either "YES" or "NO" to each Bob's question.
At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.
Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.
You are given n and Bob's questions x_1, β¦, x_k. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Let (a,b) denote a scenario where Alice starts at cell a and ends at cell b. Two scenarios (a_i, b_i) and (a_j, b_j) are different if a_i β a_j or b_i β b_j.
Input
The first line contains two integers n and k (1 β€ n,k β€ 10^5) β the number of cells and the number of questions Bob asked.
The second line contains k integers x_1, x_2, β¦, x_k (1 β€ x_i β€ n) β Bob's questions.
Output
Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Examples
Input
5 3
5 1 4
Output
9
Input
4 8
1 2 3 4 4 3 2 1
Output
0
Input
100000 1
42
Output
299997
Note
The notation (i,j) denotes a scenario where Alice starts at cell i and ends at cell j.
In the first example, the valid scenarios are (1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5). For example, (3,4) is valid since Alice can start at cell 3, stay there for the first three questions, then move to cell 4 after the last question.
(4,5) is valid since Alice can start at cell 4, stay there for the first question, the move to cell 5 for the next two questions. Note that (4,5) is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.
In the second example, Alice has no valid scenarios.
In the last example, all (i,j) where |i-j| β€ 1 except for (42, 42) are valid scenarios.
Tags: graphs
Correct Solution:
```
def getn():
return int(input())
def getns():
return [int(x)for x in input().split()]
# n=getn()
# ns=getns()
n,k=getns()
ks=getns()
f=[None]*(n+1)
l=[None]*(n+1)
ans=3*n-2
for i in range(k):
c=ks[i]
if f[c]==None:
f[c]=i
ans-=1
l[c]=i
for i in range(1,n):
if f[i]!=None and l[i+1]!=None and f[i]<l[i+1]:
ans-=1
for i in range(2,n+1):
if f[i]!=None and l[i-1]!=None and f[i]<l[i-1]:
ans-=1
print(ans)
```
| 8,407 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent.
Alice initially has a token on some cell on the line, and Bob tries to guess where it is.
Bob guesses a sequence of line cell numbers x_1, x_2, β¦, x_k in order. In the i-th question, Bob asks Alice if her token is currently on cell x_i. That is, Alice can answer either "YES" or "NO" to each Bob's question.
At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.
Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.
You are given n and Bob's questions x_1, β¦, x_k. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Let (a,b) denote a scenario where Alice starts at cell a and ends at cell b. Two scenarios (a_i, b_i) and (a_j, b_j) are different if a_i β a_j or b_i β b_j.
Input
The first line contains two integers n and k (1 β€ n,k β€ 10^5) β the number of cells and the number of questions Bob asked.
The second line contains k integers x_1, x_2, β¦, x_k (1 β€ x_i β€ n) β Bob's questions.
Output
Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Examples
Input
5 3
5 1 4
Output
9
Input
4 8
1 2 3 4 4 3 2 1
Output
0
Input
100000 1
42
Output
299997
Note
The notation (i,j) denotes a scenario where Alice starts at cell i and ends at cell j.
In the first example, the valid scenarios are (1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5). For example, (3,4) is valid since Alice can start at cell 3, stay there for the first three questions, then move to cell 4 after the last question.
(4,5) is valid since Alice can start at cell 4, stay there for the first question, the move to cell 5 for the next two questions. Note that (4,5) is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.
In the second example, Alice has no valid scenarios.
In the last example, all (i,j) where |i-j| β€ 1 except for (42, 42) are valid scenarios.
Tags: graphs
Correct Solution:
```
def solve():
n,k = map(int,input().split())
x = list(map(int,input().split()))
fpos = [k for i in range(n+1)]
lpos = [-1 for i in range(n+1)]
for i in range(1,k+1):
lpos[x[i-1]] = i
for i in range(k,0,-1):
fpos[x[i-1]] = i
ans = 0
for i in range(1,n+1):
if lpos[i] == -1:
ans+=1
# print(ans)
for i in range(1,n):
if fpos[i] >= lpos[i+1]:
ans += 1
if fpos[i+1] >= lpos[i]:
ans += 1
# print(i,i+1,ans)
print(ans)
if __name__ == '__main__':
solve()
```
| 8,408 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent.
Alice initially has a token on some cell on the line, and Bob tries to guess where it is.
Bob guesses a sequence of line cell numbers x_1, x_2, β¦, x_k in order. In the i-th question, Bob asks Alice if her token is currently on cell x_i. That is, Alice can answer either "YES" or "NO" to each Bob's question.
At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.
Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.
You are given n and Bob's questions x_1, β¦, x_k. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Let (a,b) denote a scenario where Alice starts at cell a and ends at cell b. Two scenarios (a_i, b_i) and (a_j, b_j) are different if a_i β a_j or b_i β b_j.
Input
The first line contains two integers n and k (1 β€ n,k β€ 10^5) β the number of cells and the number of questions Bob asked.
The second line contains k integers x_1, x_2, β¦, x_k (1 β€ x_i β€ n) β Bob's questions.
Output
Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Examples
Input
5 3
5 1 4
Output
9
Input
4 8
1 2 3 4 4 3 2 1
Output
0
Input
100000 1
42
Output
299997
Note
The notation (i,j) denotes a scenario where Alice starts at cell i and ends at cell j.
In the first example, the valid scenarios are (1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5). For example, (3,4) is valid since Alice can start at cell 3, stay there for the first three questions, then move to cell 4 after the last question.
(4,5) is valid since Alice can start at cell 4, stay there for the first question, the move to cell 5 for the next two questions. Note that (4,5) is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.
In the second example, Alice has no valid scenarios.
In the last example, all (i,j) where |i-j| β€ 1 except for (42, 42) are valid scenarios.
Tags: graphs
Correct Solution:
```
(n,k)=[int(x) for x in input().split()]
q =[int(x) for x in input().split()]
f = 0
incl = set()
counted={}
for i in range(k-1,-1,-1):
if q[i]+1 in incl and str(q[i])+"+1" not in counted:
f+=1
counted[str(q[i])+"+1"]=True
if q[i]-1 in incl and str(q[i])+"-1" not in counted:
f+=1
counted[str(q[i])+"-1"]=True
incl.add(q[i])
print(3*n-2-f-len(incl))
```
| 8,409 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent.
Alice initially has a token on some cell on the line, and Bob tries to guess where it is.
Bob guesses a sequence of line cell numbers x_1, x_2, β¦, x_k in order. In the i-th question, Bob asks Alice if her token is currently on cell x_i. That is, Alice can answer either "YES" or "NO" to each Bob's question.
At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.
Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.
You are given n and Bob's questions x_1, β¦, x_k. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Let (a,b) denote a scenario where Alice starts at cell a and ends at cell b. Two scenarios (a_i, b_i) and (a_j, b_j) are different if a_i β a_j or b_i β b_j.
Input
The first line contains two integers n and k (1 β€ n,k β€ 10^5) β the number of cells and the number of questions Bob asked.
The second line contains k integers x_1, x_2, β¦, x_k (1 β€ x_i β€ n) β Bob's questions.
Output
Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Examples
Input
5 3
5 1 4
Output
9
Input
4 8
1 2 3 4 4 3 2 1
Output
0
Input
100000 1
42
Output
299997
Note
The notation (i,j) denotes a scenario where Alice starts at cell i and ends at cell j.
In the first example, the valid scenarios are (1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5). For example, (3,4) is valid since Alice can start at cell 3, stay there for the first three questions, then move to cell 4 after the last question.
(4,5) is valid since Alice can start at cell 4, stay there for the first question, the move to cell 5 for the next two questions. Note that (4,5) is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.
In the second example, Alice has no valid scenarios.
In the last example, all (i,j) where |i-j| β€ 1 except for (42, 42) are valid scenarios.
Tags: graphs
Correct Solution:
```
n, k = map(int, input().split())
a = list(map(int, input().split()))
first_appear = {}
last_appear = {}
for i in range(k):
last_appear[a[i]] = i
for i in range(k)[::-1]:
first_appear[a[i]] = i
count = 0
for i in range(1,n+1):
for j in range(i-1,i+2):
if 1 <= j <= n:
if i not in first_appear:
count += 1
elif j not in last_appear:
count += 1
else:
if last_appear[j] < first_appear[i]:
count += 1
print(count)
```
| 8,410 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent.
Alice initially has a token on some cell on the line, and Bob tries to guess where it is.
Bob guesses a sequence of line cell numbers x_1, x_2, β¦, x_k in order. In the i-th question, Bob asks Alice if her token is currently on cell x_i. That is, Alice can answer either "YES" or "NO" to each Bob's question.
At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.
Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.
You are given n and Bob's questions x_1, β¦, x_k. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Let (a,b) denote a scenario where Alice starts at cell a and ends at cell b. Two scenarios (a_i, b_i) and (a_j, b_j) are different if a_i β a_j or b_i β b_j.
Input
The first line contains two integers n and k (1 β€ n,k β€ 10^5) β the number of cells and the number of questions Bob asked.
The second line contains k integers x_1, x_2, β¦, x_k (1 β€ x_i β€ n) β Bob's questions.
Output
Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Examples
Input
5 3
5 1 4
Output
9
Input
4 8
1 2 3 4 4 3 2 1
Output
0
Input
100000 1
42
Output
299997
Note
The notation (i,j) denotes a scenario where Alice starts at cell i and ends at cell j.
In the first example, the valid scenarios are (1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5). For example, (3,4) is valid since Alice can start at cell 3, stay there for the first three questions, then move to cell 4 after the last question.
(4,5) is valid since Alice can start at cell 4, stay there for the first question, the move to cell 5 for the next two questions. Note that (4,5) is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.
In the second example, Alice has no valid scenarios.
In the last example, all (i,j) where |i-j| β€ 1 except for (42, 42) are valid scenarios.
Submitted Solution:
```
s = input().split()
n = int(s[0])
k = int(s[1])
s = input().split()
l = [int(x) for x in s]
f = [False for i in range(n + 1)]
for i in range(k):
f[l[i]] = True
ans = 0
L = [0 for i in range(n + 1)]
R = [0 for i in range(n + 1)]
for i in range(k):
R[l[i]] = i
for i in range(k - 1, -1, -1):
L[l[i]] = i
for i in range(1, n + 1):
ans += not f[i]
for i in range(1, n):
if not f[i] or not f[i + 1]:
ans += 2
continue
if L[i] > R[i + 1]:
ans += 1
if L[i + 1] > R[i]:
ans += 1
print(ans)
```
Yes
| 8,411 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent.
Alice initially has a token on some cell on the line, and Bob tries to guess where it is.
Bob guesses a sequence of line cell numbers x_1, x_2, β¦, x_k in order. In the i-th question, Bob asks Alice if her token is currently on cell x_i. That is, Alice can answer either "YES" or "NO" to each Bob's question.
At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.
Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.
You are given n and Bob's questions x_1, β¦, x_k. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Let (a,b) denote a scenario where Alice starts at cell a and ends at cell b. Two scenarios (a_i, b_i) and (a_j, b_j) are different if a_i β a_j or b_i β b_j.
Input
The first line contains two integers n and k (1 β€ n,k β€ 10^5) β the number of cells and the number of questions Bob asked.
The second line contains k integers x_1, x_2, β¦, x_k (1 β€ x_i β€ n) β Bob's questions.
Output
Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Examples
Input
5 3
5 1 4
Output
9
Input
4 8
1 2 3 4 4 3 2 1
Output
0
Input
100000 1
42
Output
299997
Note
The notation (i,j) denotes a scenario where Alice starts at cell i and ends at cell j.
In the first example, the valid scenarios are (1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5). For example, (3,4) is valid since Alice can start at cell 3, stay there for the first three questions, then move to cell 4 after the last question.
(4,5) is valid since Alice can start at cell 4, stay there for the first question, the move to cell 5 for the next two questions. Note that (4,5) is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.
In the second example, Alice has no valid scenarios.
In the last example, all (i,j) where |i-j| β€ 1 except for (42, 42) are valid scenarios.
Submitted Solution:
```
from collections import defaultdict
n, k = [int(item) for item in input().split()]
x = [int(item) for item in input().split()]
occ = defaultdict(list)
for i in range(k):
occ[x[i]].append(i)
ans = 0
for i in range(1, n + 1):
old = ans
if not i in occ:
if i == 1 or i == n:
ans += 2
else:
ans += 3
continue
if i < n and (i + 1 not in occ or occ[i][0] > occ[i + 1][-1]):
ans += 1
if i > 1 and (i - 1 not in occ or occ[i][0] > occ[i - 1][-1]):
ans += 1
print(ans)
```
Yes
| 8,412 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent.
Alice initially has a token on some cell on the line, and Bob tries to guess where it is.
Bob guesses a sequence of line cell numbers x_1, x_2, β¦, x_k in order. In the i-th question, Bob asks Alice if her token is currently on cell x_i. That is, Alice can answer either "YES" or "NO" to each Bob's question.
At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.
Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.
You are given n and Bob's questions x_1, β¦, x_k. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Let (a,b) denote a scenario where Alice starts at cell a and ends at cell b. Two scenarios (a_i, b_i) and (a_j, b_j) are different if a_i β a_j or b_i β b_j.
Input
The first line contains two integers n and k (1 β€ n,k β€ 10^5) β the number of cells and the number of questions Bob asked.
The second line contains k integers x_1, x_2, β¦, x_k (1 β€ x_i β€ n) β Bob's questions.
Output
Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Examples
Input
5 3
5 1 4
Output
9
Input
4 8
1 2 3 4 4 3 2 1
Output
0
Input
100000 1
42
Output
299997
Note
The notation (i,j) denotes a scenario where Alice starts at cell i and ends at cell j.
In the first example, the valid scenarios are (1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5). For example, (3,4) is valid since Alice can start at cell 3, stay there for the first three questions, then move to cell 4 after the last question.
(4,5) is valid since Alice can start at cell 4, stay there for the first question, the move to cell 5 for the next two questions. Note that (4,5) is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.
In the second example, Alice has no valid scenarios.
In the last example, all (i,j) where |i-j| β€ 1 except for (42, 42) are valid scenarios.
Submitted Solution:
```
N,cnt=[int(1e5+5000),int(0)]
class edg:
pnt,nxt=[int(0),int(0)]
fir=[0]*N
ed=[edg()]
for i in range(1,N):
ed.append(edg())
def link(u,v):
global cnt
cnt+=1
ed[cnt].nxt=fir[u]
fir[u]=cnt
ed[cnt].pnt=v
# print(ed[1].pnt,ed[2].pnt,ed[3].pnt)
# print(cnt,ed[1].pnt,ed[1].nxt)
# print(ed[2].pnt)
#print(ed[0].pnt)
n,k=list(map(int,input().split(" ")))
#print(n," ",k)
q=[0]+list(map(int,input().split(" ")))
#print(q[1])
#link(1,1)
#'''
for i in range(1,k+1):
# u,v=[1,1]
u,v=[q[i],i]
link(u,v)
# print(u,v)
#'''
#stay
'''
print(q)
u=5
e=fir[u]
print(ed[2].pnt)
'''
'''
print(ed[2].pnt,ed[3].pnt)
ed[2].pnt=1
print(ed[2].pnt,ed[3].pnt)
'''
ans=int(0)
for i in range(1,n+1):
if(fir[i]==0):
ans+=1
#left
for i in range(2,n+1):
minx,maxx=[(1<<27),-(1<<27)]
u=i
e=fir[u]
while(e!=0):
minx=min(minx,ed[e].pnt)
e=ed[e].nxt
u=i-1
e=fir[u]
while(e!=0):
maxx=max(maxx,ed[e].pnt)
e=ed[e].nxt
if(minx>maxx):
ans+=1
# print(i,i-1)
#right
for i in range(1,n):
minx,maxx=[(1<<27),-(1<<27)]
u=i
e=fir[u]
while(e!=0):
minx=min(minx,ed[e].pnt)
e=ed[e].nxt
u=i+1
e=fir[u]
while(e!=0):
maxx=max(maxx,ed[e].pnt)
e=ed[e].nxt
if(minx>maxx):
ans+=1
# print(i,i+1)
'''
if(i==4):
# print(minx,maxx)
u=i+1
e=fir[u]
while(e!=0):
print(ed[e].pnt)
e=ed[e].nxt
'''
print(ans)
```
Yes
| 8,413 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent.
Alice initially has a token on some cell on the line, and Bob tries to guess where it is.
Bob guesses a sequence of line cell numbers x_1, x_2, β¦, x_k in order. In the i-th question, Bob asks Alice if her token is currently on cell x_i. That is, Alice can answer either "YES" or "NO" to each Bob's question.
At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.
Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.
You are given n and Bob's questions x_1, β¦, x_k. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Let (a,b) denote a scenario where Alice starts at cell a and ends at cell b. Two scenarios (a_i, b_i) and (a_j, b_j) are different if a_i β a_j or b_i β b_j.
Input
The first line contains two integers n and k (1 β€ n,k β€ 10^5) β the number of cells and the number of questions Bob asked.
The second line contains k integers x_1, x_2, β¦, x_k (1 β€ x_i β€ n) β Bob's questions.
Output
Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Examples
Input
5 3
5 1 4
Output
9
Input
4 8
1 2 3 4 4 3 2 1
Output
0
Input
100000 1
42
Output
299997
Note
The notation (i,j) denotes a scenario where Alice starts at cell i and ends at cell j.
In the first example, the valid scenarios are (1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5). For example, (3,4) is valid since Alice can start at cell 3, stay there for the first three questions, then move to cell 4 after the last question.
(4,5) is valid since Alice can start at cell 4, stay there for the first question, the move to cell 5 for the next two questions. Note that (4,5) is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.
In the second example, Alice has no valid scenarios.
In the last example, all (i,j) where |i-j| β€ 1 except for (42, 42) are valid scenarios.
Submitted Solution:
```
n, k = map(int, input().split())
a = list(map(int, input().split()))
count = (n - 1) * 2 + n
b = [[0, -1] for i in range(n + 2)]
c = set()
for i in range(len(a)):
if b[a[i] - 1][0] != 0 and b[a[i]][0] == 0:
count -= 1
if b[a[i] + 1][0] != 0 and b[a[i]][0] == 0:
count -= 1
if b[a[i]][0] == 0:
count -= 1
l1 = (a[i] + 1, a[i])
l2 = (a[i], a[i] + 1)
if b[a[i] + 1][1] > b[a[i]][1] and b[a[i] + 1][0] != 0 and b[a[i]][0] != 0 and l1 not in c and l2 not in c:
count -= 1
c.add(l1)
c.add(l2)
l3 = (a[i], a[i] - 1)
l4 = (a[i] - 1, a[i])
if b[a[i] - 1][1] > b[a[i]][1] and b[a[i] - 1][0] != 0 and b[a[i]][0] != 0 and l3 not in c and l4 not in c:
count -= 1
c.add(l3)
c.add(l4)
b[a[i]][0] = 1
b[a[i]][1] = i
print(count)
```
Yes
| 8,414 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent.
Alice initially has a token on some cell on the line, and Bob tries to guess where it is.
Bob guesses a sequence of line cell numbers x_1, x_2, β¦, x_k in order. In the i-th question, Bob asks Alice if her token is currently on cell x_i. That is, Alice can answer either "YES" or "NO" to each Bob's question.
At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.
Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.
You are given n and Bob's questions x_1, β¦, x_k. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Let (a,b) denote a scenario where Alice starts at cell a and ends at cell b. Two scenarios (a_i, b_i) and (a_j, b_j) are different if a_i β a_j or b_i β b_j.
Input
The first line contains two integers n and k (1 β€ n,k β€ 10^5) β the number of cells and the number of questions Bob asked.
The second line contains k integers x_1, x_2, β¦, x_k (1 β€ x_i β€ n) β Bob's questions.
Output
Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Examples
Input
5 3
5 1 4
Output
9
Input
4 8
1 2 3 4 4 3 2 1
Output
0
Input
100000 1
42
Output
299997
Note
The notation (i,j) denotes a scenario where Alice starts at cell i and ends at cell j.
In the first example, the valid scenarios are (1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5). For example, (3,4) is valid since Alice can start at cell 3, stay there for the first three questions, then move to cell 4 after the last question.
(4,5) is valid since Alice can start at cell 4, stay there for the first question, the move to cell 5 for the next two questions. Note that (4,5) is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.
In the second example, Alice has no valid scenarios.
In the last example, all (i,j) where |i-j| β€ 1 except for (42, 42) are valid scenarios.
Submitted Solution:
```
n, k = map(int, input().split())
array = list(map(int, input().split()))
d = {i: 0 for i in range(1, n + 1)}
dind = {}
ind = 1
for e in array:
d[e] += 1
dind[e] = ind
ind += 1
sum = 0
prooved = set()
for i, x in enumerate(array):
if x > 1 and (x, x - 1) not in prooved:
if d[x - 1] == 0:
sum += 1
prooved.add((x, x - 1))
else:
if dind[x - 1] < i:
sum += 1
prooved.add((x, x - 1))
if x < n:
if d[x + 1] == 0 and (x, x + 1) not in prooved:
sum += 1
prooved.add((x, x + 1))
else:
if dind[x + 1] < i:
sum += 1
prooved.add((x, x + 1))
for i in range(1, n+1):
if d[i] == 0:
sum += 1
if i != 1:
sum += 1
if i != n:
sum += 1
print(sum)
```
No
| 8,415 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent.
Alice initially has a token on some cell on the line, and Bob tries to guess where it is.
Bob guesses a sequence of line cell numbers x_1, x_2, β¦, x_k in order. In the i-th question, Bob asks Alice if her token is currently on cell x_i. That is, Alice can answer either "YES" or "NO" to each Bob's question.
At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.
Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.
You are given n and Bob's questions x_1, β¦, x_k. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Let (a,b) denote a scenario where Alice starts at cell a and ends at cell b. Two scenarios (a_i, b_i) and (a_j, b_j) are different if a_i β a_j or b_i β b_j.
Input
The first line contains two integers n and k (1 β€ n,k β€ 10^5) β the number of cells and the number of questions Bob asked.
The second line contains k integers x_1, x_2, β¦, x_k (1 β€ x_i β€ n) β Bob's questions.
Output
Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Examples
Input
5 3
5 1 4
Output
9
Input
4 8
1 2 3 4 4 3 2 1
Output
0
Input
100000 1
42
Output
299997
Note
The notation (i,j) denotes a scenario where Alice starts at cell i and ends at cell j.
In the first example, the valid scenarios are (1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5). For example, (3,4) is valid since Alice can start at cell 3, stay there for the first three questions, then move to cell 4 after the last question.
(4,5) is valid since Alice can start at cell 4, stay there for the first question, the move to cell 5 for the next two questions. Note that (4,5) is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.
In the second example, Alice has no valid scenarios.
In the last example, all (i,j) where |i-j| β€ 1 except for (42, 42) are valid scenarios.
Submitted Solution:
```
n,k=map(int,input().split())
a=list(map(int,input().split()))
d={i:0 for i in range(1,n+1)}
for i in range(k):
d[a[i]]+=i+1
s=0
#print(d)
if(n==1):
if(k==0):
print(1)
exit()
else:
print(0)
exit()
for i in range(1,n+1):
if(d[i]==0):
if(i==1)or(i==n):
s+=2
else:
s+=3
else:
if(i==1):
if(d[i]>d[i+1]):
s+=1
elif(i==n):
if(d[i]>d[i-1]):
s+=1
else:
if(d[i+1]>=d[i])and(d[i-1]>=d[i]):
continue
elif(d[i+1]<d[i])and(d[i-1]<d[i]):
s+=2
else:
s+=1
print(s)
```
No
| 8,416 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent.
Alice initially has a token on some cell on the line, and Bob tries to guess where it is.
Bob guesses a sequence of line cell numbers x_1, x_2, β¦, x_k in order. In the i-th question, Bob asks Alice if her token is currently on cell x_i. That is, Alice can answer either "YES" or "NO" to each Bob's question.
At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.
Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.
You are given n and Bob's questions x_1, β¦, x_k. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Let (a,b) denote a scenario where Alice starts at cell a and ends at cell b. Two scenarios (a_i, b_i) and (a_j, b_j) are different if a_i β a_j or b_i β b_j.
Input
The first line contains two integers n and k (1 β€ n,k β€ 10^5) β the number of cells and the number of questions Bob asked.
The second line contains k integers x_1, x_2, β¦, x_k (1 β€ x_i β€ n) β Bob's questions.
Output
Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Examples
Input
5 3
5 1 4
Output
9
Input
4 8
1 2 3 4 4 3 2 1
Output
0
Input
100000 1
42
Output
299997
Note
The notation (i,j) denotes a scenario where Alice starts at cell i and ends at cell j.
In the first example, the valid scenarios are (1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5). For example, (3,4) is valid since Alice can start at cell 3, stay there for the first three questions, then move to cell 4 after the last question.
(4,5) is valid since Alice can start at cell 4, stay there for the first question, the move to cell 5 for the next two questions. Note that (4,5) is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.
In the second example, Alice has no valid scenarios.
In the last example, all (i,j) where |i-j| β€ 1 except for (42, 42) are valid scenarios.
Submitted Solution:
```
from collections import defaultdict
n,k=map(int,input().split())
ar=[int(x) for x in input().split()]
d=defaultdict(int)
for i in ar:
d[i]+=1
ans=0
ok=False
for i in range(1,n+1):
if(i not in d):
ans+=1
ok=True
if(i<n):
if(i not in d and i+1 not in d):
ans+=2
prev=defaultdict(int)
for i in ar:
d[i]-=1
if(d[i]==0):
d.pop(i)
prev[i]+=1
if (i - 1 > 0 and i - 1 not in d):
ans += 1
ok=True
#print(i-1,i)
if (i + 1 <= n and i + 1 not in d):
ans += 1
ok=True
#print(i,i+1)
if(i-1>0 and i-1 not in d and i-1 not in prev):
ans+=1
ok=True
if(i+1<=n and i+1 not in d and i+1 not in prev):
ans+=1
ok=True
if(not ok):
ans=0
break
print(ans)
```
No
| 8,417 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent.
Alice initially has a token on some cell on the line, and Bob tries to guess where it is.
Bob guesses a sequence of line cell numbers x_1, x_2, β¦, x_k in order. In the i-th question, Bob asks Alice if her token is currently on cell x_i. That is, Alice can answer either "YES" or "NO" to each Bob's question.
At most one time in this process, before or after answering a question, Alice is allowed to move her token from her current cell to some adjacent cell. Alice acted in such a way that she was able to answer "NO" to all of Bob's questions.
Note that Alice can even move her token before answering the first question or after answering the last question. Alice can also choose to not move at all.
You are given n and Bob's questions x_1, β¦, x_k. You would like to count the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Let (a,b) denote a scenario where Alice starts at cell a and ends at cell b. Two scenarios (a_i, b_i) and (a_j, b_j) are different if a_i β a_j or b_i β b_j.
Input
The first line contains two integers n and k (1 β€ n,k β€ 10^5) β the number of cells and the number of questions Bob asked.
The second line contains k integers x_1, x_2, β¦, x_k (1 β€ x_i β€ n) β Bob's questions.
Output
Print a single integer, the number of scenarios that let Alice answer "NO" to all of Bob's questions.
Examples
Input
5 3
5 1 4
Output
9
Input
4 8
1 2 3 4 4 3 2 1
Output
0
Input
100000 1
42
Output
299997
Note
The notation (i,j) denotes a scenario where Alice starts at cell i and ends at cell j.
In the first example, the valid scenarios are (1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3), (3, 4), (4, 3), (4, 5). For example, (3,4) is valid since Alice can start at cell 3, stay there for the first three questions, then move to cell 4 after the last question.
(4,5) is valid since Alice can start at cell 4, stay there for the first question, the move to cell 5 for the next two questions. Note that (4,5) is only counted once, even though there are different questions that Alice can choose to do the move, but remember, we only count each pair of starting and ending positions once.
In the second example, Alice has no valid scenarios.
In the last example, all (i,j) where |i-j| β€ 1 except for (42, 42) are valid scenarios.
Submitted Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
import threading
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
n,k=map(int,input().split())
first=[n]*max(n,k)
last=[-1]*max(n,k)
a=list(map(int,input().split()))
for i in range (k):
last[a[i]-1]=i
if first[a[i]-1]==max(n,k):
first[a[i]-1]=i
c=0
for i in range (n):
if first[i]==n:
c+=1
if i!=n-1:
if first[i+1]>=last[i]:
c+=1
if i!=0:
if first[i-1]>=last[i]:
c+=1
print(c)
```
No
| 8,418 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Toad Rash has a binary string s. A binary string consists only of zeros and ones.
Let n be the length of s.
Rash needs to find the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Find this number of pairs for Rash.
Input
The first line contains the string s (1 β€ |s| β€ 300 000), consisting of zeros and ones.
Output
Output one integer: the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Examples
Input
010101
Output
3
Input
11001100
Output
0
Note
In the first example, there are three l, r pairs we need to count: 1, 6; 2, 6; and 1, 5.
In the second example, there are no values x, k for the initial string, so the answer is 0.
Tags: brute force, two pointers
Correct Solution:
```
import sys
input = sys.stdin.readline
S=input().strip()
L=len(S)
ANS1=[0]*(L+10)
ANS2=[0]*(L+10)
ANS3=[0]*(L+10)
for i in range(L-2):
if S[i]==S[i+1]==S[i+2]:
ANS1[i]=1
for i in range(L-4):
if S[i]==S[i+2]==S[i+4]:
ANS2[i]=1
for i in range(L-6):
if S[i]==S[i+3]==S[i+6]:
ANS3[i]=1
SCORE=0
for i in range(L):
if ANS1[i]==1:
SCORE+=max(0,L-i-2)
elif ANS1[i+1]==1:
SCORE+=max(0,L-i-3)
elif ANS1[i+2]==1:
SCORE+=max(0,L-i-4)
elif ANS2[i]==1:
SCORE+=max(0,L-i-4)
elif ANS2[i+1]==1:
SCORE+=max(0,L-i-5)
elif ANS1[i+3]==1:
SCORE+=max(0,L-i-5)
elif ANS1[i+4]==1:
SCORE+=max(0,L-i-6)
elif ANS2[i+2]==1:
SCORE+=max(0,L-i-6)
elif ANS3[i]==1:
SCORE+=max(0,L-i-6)
elif ANS1[i+5]==1:
SCORE+=max(0,L-i-7)
elif ANS2[i+3]==1:
SCORE+=max(0,L-i-7)
elif ANS3[i+1]==1:
SCORE+=max(0,L-i-7)
else:
SCORE+=max(0,L-i-8)
#print(SCORE)
print(SCORE)
```
| 8,419 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Toad Rash has a binary string s. A binary string consists only of zeros and ones.
Let n be the length of s.
Rash needs to find the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Find this number of pairs for Rash.
Input
The first line contains the string s (1 β€ |s| β€ 300 000), consisting of zeros and ones.
Output
Output one integer: the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Examples
Input
010101
Output
3
Input
11001100
Output
0
Note
In the first example, there are three l, r pairs we need to count: 1, 6; 2, 6; and 1, 5.
In the second example, there are no values x, k for the initial string, so the answer is 0.
Tags: brute force, two pointers
Correct Solution:
```
def parse(c, n):
l = [-1] * n
for x in c:
se = set(x)
for i in range(len(x) - 1):
for j in range(i + 1, len(x)):
k = x[j] - x[i]
if k > 20:
break
if x[i] + k + k >= n:
break
if x[i] + k + k in se:
l[x[i] + k + k] = x[i]
break
res = 0
prex = -1
# print(l)
for i in range(n):
if l[i] <= prex:
continue
res = res + (l[i] - prex) * (n - i);
# print(prex + 1, l[i], i + 1, n)
prex = l[i]
return res
if __name__ == '__main__':
s = input()
one = [i for i in range(len(s)) if s[i] == '1']
zero = [i for i in range(len(s)) if s[i] == '0']
# print(one)
# print(zero)
ans = parse((one, zero), len(s))
print(ans)
```
| 8,420 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Toad Rash has a binary string s. A binary string consists only of zeros and ones.
Let n be the length of s.
Rash needs to find the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Find this number of pairs for Rash.
Input
The first line contains the string s (1 β€ |s| β€ 300 000), consisting of zeros and ones.
Output
Output one integer: the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Examples
Input
010101
Output
3
Input
11001100
Output
0
Note
In the first example, there are three l, r pairs we need to count: 1, 6; 2, 6; and 1, 5.
In the second example, there are no values x, k for the initial string, so the answer is 0.
Tags: brute force, two pointers
Correct Solution:
```
from math import *
from collections import *
import sys
sys.setrecursionlimit(10**9)
s = input()
n = len(s)
ans = 0
for i in range(n):
m = 10**6
for k in range(1,5):
for j in range(i,i+7):
if(j + 2*k >= n):
break
if(s[j] == s[j+k] and s[j] == s[j+2*k]):
m = min(m,j+2*k)
if(m != 10**6):
ans += n-m
print(ans)
```
| 8,421 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Toad Rash has a binary string s. A binary string consists only of zeros and ones.
Let n be the length of s.
Rash needs to find the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Find this number of pairs for Rash.
Input
The first line contains the string s (1 β€ |s| β€ 300 000), consisting of zeros and ones.
Output
Output one integer: the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Examples
Input
010101
Output
3
Input
11001100
Output
0
Note
In the first example, there are three l, r pairs we need to count: 1, 6; 2, 6; and 1, 5.
In the second example, there are no values x, k for the initial string, so the answer is 0.
Tags: brute force, two pointers
Correct Solution:
```
s=input()
def pri(l,r):
k=1
while r-2*k>=l:
if s[r]!=s[r-k] or s[r-k]!=s[r-2*k]:
k+=1
continue
return False
return True
ans=0
for i in range(len(s)):
j=i
while j<len(s) and pri(i,j):
j+=1
ans+=len(s)-j
print(ans)
```
| 8,422 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Toad Rash has a binary string s. A binary string consists only of zeros and ones.
Let n be the length of s.
Rash needs to find the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Find this number of pairs for Rash.
Input
The first line contains the string s (1 β€ |s| β€ 300 000), consisting of zeros and ones.
Output
Output one integer: the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Examples
Input
010101
Output
3
Input
11001100
Output
0
Note
In the first example, there are three l, r pairs we need to count: 1, 6; 2, 6; and 1, 5.
In the second example, there are no values x, k for the initial string, so the answer is 0.
Tags: brute force, two pointers
Correct Solution:
```
s = input()
n = len(s)
l = 0
ans = 0
for i in range(n):
for j in range(i - 1, l, -1):
if 2 * j - i < l:
break
if s[i] == s[j] == s[j + j - i]:
ans += ((2 * j - i) - l + 1) * (n - i)
l = (2 * j - i + 1)
print(ans)
```
| 8,423 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Toad Rash has a binary string s. A binary string consists only of zeros and ones.
Let n be the length of s.
Rash needs to find the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Find this number of pairs for Rash.
Input
The first line contains the string s (1 β€ |s| β€ 300 000), consisting of zeros and ones.
Output
Output one integer: the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Examples
Input
010101
Output
3
Input
11001100
Output
0
Note
In the first example, there are three l, r pairs we need to count: 1, 6; 2, 6; and 1, 5.
In the second example, there are no values x, k for the initial string, so the answer is 0.
Tags: brute force, two pointers
Correct Solution:
```
import sys
S = sys.stdin.readline()
S = S.strip()
n = len(S)
ans = 0
def check(i, j) :
if j - i < 3 :
return False
for x in range(i, j) :
for k in range(1, j - i) :
if x + 2 * k >= j :
break
if S[x] == S[x+k] == S[x + 2 * k] :
return True
return False
for i in range(n) :
for j in range(i + 1, min(i + 100, n+1)) :
if check(i, j) :
ans += n - j + 1
break
print(ans)
```
| 8,424 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Toad Rash has a binary string s. A binary string consists only of zeros and ones.
Let n be the length of s.
Rash needs to find the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Find this number of pairs for Rash.
Input
The first line contains the string s (1 β€ |s| β€ 300 000), consisting of zeros and ones.
Output
Output one integer: the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Examples
Input
010101
Output
3
Input
11001100
Output
0
Note
In the first example, there are three l, r pairs we need to count: 1, 6; 2, 6; and 1, 5.
In the second example, there are no values x, k for the initial string, so the answer is 0.
Tags: brute force, two pointers
Correct Solution:
```
s = input()
n = len(s)
a = [n] * (n + 1)
ans = 0
for i in range(n - 1, -1, -1):
a[i] = a[i + 1]
j = 1
while i + j + j < a[i]:
if s[i] == s[i + j] and s[i] == s[i + j + j]:
a[i] = i + j + j
j += 1
ans += n - a[i]
print(ans)
```
| 8,425 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Toad Rash has a binary string s. A binary string consists only of zeros and ones.
Let n be the length of s.
Rash needs to find the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Find this number of pairs for Rash.
Input
The first line contains the string s (1 β€ |s| β€ 300 000), consisting of zeros and ones.
Output
Output one integer: the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Examples
Input
010101
Output
3
Input
11001100
Output
0
Note
In the first example, there are three l, r pairs we need to count: 1, 6; 2, 6; and 1, 5.
In the second example, there are no values x, k for the initial string, so the answer is 0.
Tags: brute force, two pointers
Correct Solution:
```
s = input()
cur, ans = - 1, 0
for i in range(len(s)):
for j in range(cur + 1, i - 1):
if (i + j) % 2 == 0 and s[i] == s[j] and s[i] == s[(i + j) // 2]:
cur = j
ans += cur + 1
print(ans)
```
| 8,426 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Toad Rash has a binary string s. A binary string consists only of zeros and ones.
Let n be the length of s.
Rash needs to find the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Find this number of pairs for Rash.
Input
The first line contains the string s (1 β€ |s| β€ 300 000), consisting of zeros and ones.
Output
Output one integer: the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Examples
Input
010101
Output
3
Input
11001100
Output
0
Note
In the first example, there are three l, r pairs we need to count: 1, 6; 2, 6; and 1, 5.
In the second example, there are no values x, k for the initial string, so the answer is 0.
Submitted Solution:
```
s = input()
le = len(s)
m = [le] * (le + 1)
ans = 0
for i in range(le - 1, -1, -1):
m[i] = m[i + 1]
k = 1
while k * 2 + i < m[i]:
if s[i] == s[i + k] and s[i] == s[i + 2 * k]:
m[i] = i + 2 * k
k += 1
ans += le - m[i]
print(ans)
```
Yes
| 8,427 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Toad Rash has a binary string s. A binary string consists only of zeros and ones.
Let n be the length of s.
Rash needs to find the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Find this number of pairs for Rash.
Input
The first line contains the string s (1 β€ |s| β€ 300 000), consisting of zeros and ones.
Output
Output one integer: the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Examples
Input
010101
Output
3
Input
11001100
Output
0
Note
In the first example, there are three l, r pairs we need to count: 1, 6; 2, 6; and 1, 5.
In the second example, there are no values x, k for the initial string, so the answer is 0.
Submitted Solution:
```
from sys import stdin
s=stdin.readline().strip()
x=-1
ans=0
for i in range(len(s)):
for j in range(1,10):
if (i-2*j)>=0 and s[i]==s[i-j] and s[i-j]==s[i-2*j]:
if (i-2*j)>x:
ans+=(i-2*j-x)*(len(s)-i)
x=i-2*j
print(ans)
```
Yes
| 8,428 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Toad Rash has a binary string s. A binary string consists only of zeros and ones.
Let n be the length of s.
Rash needs to find the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Find this number of pairs for Rash.
Input
The first line contains the string s (1 β€ |s| β€ 300 000), consisting of zeros and ones.
Output
Output one integer: the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Examples
Input
010101
Output
3
Input
11001100
Output
0
Note
In the first example, there are three l, r pairs we need to count: 1, 6; 2, 6; and 1, 5.
In the second example, there are no values x, k for the initial string, so the answer is 0.
Submitted Solution:
```
#!/usr/bin/env python
# https://github.com/cheran-senthil/PyRival/blob/master/templates/template_py3.py
import os
import sys,math
from io import BytesIO, IOBase
s=None
def isGood(l,r):
global s
for i in range(l,r+1):
p1=i-1; p2=i+1
while p1>=l and p2<=r:
if s[p1]==s[p2]==s[i]:
return True
p1-=1; p2+=1
return False
def main():
global s
s=input()
n=len(s)
ans = 0
for i in range(n):
for j in range(9):
if i+j<n and isGood(i,i+j):
ans+=(n-i-j)
break
print(ans)
# 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()
```
Yes
| 8,429 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Toad Rash has a binary string s. A binary string consists only of zeros and ones.
Let n be the length of s.
Rash needs to find the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Find this number of pairs for Rash.
Input
The first line contains the string s (1 β€ |s| β€ 300 000), consisting of zeros and ones.
Output
Output one integer: the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Examples
Input
010101
Output
3
Input
11001100
Output
0
Note
In the first example, there are three l, r pairs we need to count: 1, 6; 2, 6; and 1, 5.
In the second example, there are no values x, k for the initial string, so the answer is 0.
Submitted Solution:
```
import sys
from collections import deque
#from functools import *
#from fractions import Fraction as f
#from copy import *
#from bisect import *
#from heapq import *
#from math import gcd,ceil,sqrt
#from itertools import permutations as prm,product
def eprint(*args):
print(*args, file=sys.stderr)
zz=1
#sys.setrecursionlimit(10**6)
if zz:
input=sys.stdin.readline
else:
sys.stdin=open('input.txt', 'r')
sys.stdout=open('all.txt','w')
di=[[-1,0],[1,0],[0,1],[0,-1]]
def string(s):
return "".join(s)
def fori(n):
return [fi() for i in range(n)]
def inc(d,c,x=1):
d[c]=d[c]+x if c in d else x
def bo(i):
return ord(i)-ord('A')
def li():
return [int(xx) for xx in input().split()]
def fli():
return [float(x) for x in input().split()]
def comp(a,b):
if(a>b):
return 2
return 2 if a==b else 0
def gi():
return [xx for xx in input().split()]
def cil(n,m):
return n//m+int(n%m>0)
def fi():
return int(input())
def pro(a):
return reduce(lambda a,b:a*b,a)
def swap(a,i,j):
a[i],a[j]=a[j],a[i]
def si():
return list(input().rstrip())
def mi():
return map(int,input().split())
def gh():
sys.stdout.flush()
def isvalid(i,j):
return 0<=i<n and 0<=j<m and a[i][j]!="."
def bo(i):
return ord(i)-ord('a')
def graph(n,m):
for i in range(m):
x,y=mi()
a[x].append(y)
a[y].append(x)
t=1
while t>0:
t-=1
s=si()
n=len(s)
p=[n]*(n+1)
ans=0
for i in range(n):
k=1
while i+2*k<n:
if s[i]==s[i+k]==s[i+2*k]:
p[i]=i+2*k
break
k+=1
for i in range(n-2,-1,-1):
p[i]=min(p[i],p[i+1])
ans+=(n-p[i])
print(ans)
```
Yes
| 8,430 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Toad Rash has a binary string s. A binary string consists only of zeros and ones.
Let n be the length of s.
Rash needs to find the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Find this number of pairs for Rash.
Input
The first line contains the string s (1 β€ |s| β€ 300 000), consisting of zeros and ones.
Output
Output one integer: the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Examples
Input
010101
Output
3
Input
11001100
Output
0
Note
In the first example, there are three l, r pairs we need to count: 1, 6; 2, 6; and 1, 5.
In the second example, there are no values x, k for the initial string, so the answer is 0.
Submitted Solution:
```
s = input()
l = 0
r = len(s)
count = 0
def findxk(l, r):
for x in range(l, r-2):
for k in range(1, (r+1-x)//2):
if s[x] == s[x+k] and s[x] == s[x+2*k]:
return True, x, k
return False, 0, 0
while l < len(s) -2:
valid, x, k = findxk(l,r)
if valid:
count += (x-l+1) * (r-x-2*k)
l = x+1
else:
break
print(count)
```
No
| 8,431 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Toad Rash has a binary string s. A binary string consists only of zeros and ones.
Let n be the length of s.
Rash needs to find the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Find this number of pairs for Rash.
Input
The first line contains the string s (1 β€ |s| β€ 300 000), consisting of zeros and ones.
Output
Output one integer: the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Examples
Input
010101
Output
3
Input
11001100
Output
0
Note
In the first example, there are three l, r pairs we need to count: 1, 6; 2, 6; and 1, 5.
In the second example, there are no values x, k for the initial string, so the answer is 0.
Submitted Solution:
```
s = input()
n = len(s)
ans = 0
for l in range(n):
for k in range(1,n):
if l+2*k >= n:
break
if s[l] == s[l+k] and s[l+k] == s[l+2*k]:
ans += n - (l+2*k)
break
print(ans)
```
No
| 8,432 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Toad Rash has a binary string s. A binary string consists only of zeros and ones.
Let n be the length of s.
Rash needs to find the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Find this number of pairs for Rash.
Input
The first line contains the string s (1 β€ |s| β€ 300 000), consisting of zeros and ones.
Output
Output one integer: the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Examples
Input
010101
Output
3
Input
11001100
Output
0
Note
In the first example, there are three l, r pairs we need to count: 1, 6; 2, 6; and 1, 5.
In the second example, there are no values x, k for the initial string, so the answer is 0.
Submitted Solution:
```
s = input()
l = 0
count = 0
def findxk(l):
for x in range(l, len(s)):
k = 1
while x + 2 * k < len(s):
if s[x] == s[x+k] and s[x] == s[x+k*2]:
return True, x+2*k
k += 1
return False, 0
while l < len(s) -2:
valid, r = findxk(l)
if valid:
count += len(s) - r
l+=1
else:
break
print(count)
```
No
| 8,433 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Toad Rash has a binary string s. A binary string consists only of zeros and ones.
Let n be the length of s.
Rash needs to find the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Find this number of pairs for Rash.
Input
The first line contains the string s (1 β€ |s| β€ 300 000), consisting of zeros and ones.
Output
Output one integer: the number of such pairs of integers l, r that 1 β€ l β€ r β€ n and there is at least one pair of integers x, k such that 1 β€ x, k β€ n, l β€ x < x + 2k β€ r, and s_x = s_{x+k} = s_{x+2k}.
Examples
Input
010101
Output
3
Input
11001100
Output
0
Note
In the first example, there are three l, r pairs we need to count: 1, 6; 2, 6; and 1, 5.
In the second example, there are no values x, k for the initial string, so the answer is 0.
Submitted Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
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")
#-------------------------------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=-10**6, func=lambda a, b: max(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SegmentTree1:
def __init__(self, data, default=10**6, func=lambda a, b: min(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
MOD=10**9+7
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(50001)]
pp=[]
def SieveOfEratosthenes(n=50000):
# Create a boolean array "prime[0..n]" and initialize
# all entries it as true. A value in prime[i] will
# finally be false if i is Not a prime, else true.
p = 2
while (p * p <= n):
# If prime[p] is not changed, then it is a prime
if (prime[p] == True):
# Update all multiples of p
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
for i in range(50001):
if prime[i]:
pp.append(i)
#---------------------------------running code------------------------------------------
s=input()
n=len(s)
c=0
for i in range (n-2):
for j in range (i+2,n):
if (i+j)%2==0:
if s[i]==s[(i+j)//2]==s[j]:
c+=n-j
print(i,j,n-j)
break
print(c)
```
No
| 8,434 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vus the Cossack has a field with dimensions n Γ m, which consists of "0" and "1". He is building an infinite field from this field. He is doing this in this way:
1. He takes the current field and finds a new inverted field. In other words, the new field will contain "1" only there, where "0" was in the current field, and "0" there, where "1" was.
2. To the current field, he adds the inverted field to the right.
3. To the current field, he adds the inverted field to the bottom.
4. To the current field, he adds the current field to the bottom right.
5. He repeats it.
For example, if the initial field was:
\begin{matrix} 1 & 0 & \\\ 1 & 1 & \\\ \end{matrix}
After the first iteration, the field will be like this:
\begin{matrix} 1 & 0 & 0 & 1 \\\ 1 & 1 & 0 & 0 \\\ 0 & 1 & 1 & 0 \\\ 0 & 0 & 1 & 1 \\\ \end{matrix}
After the second iteration, the field will be like this:
\begin{matrix} 1 & 0 & 0 & 1 & 0 & 1 & 1 & 0 \\\ 1 & 1 & 0 & 0 & 0 & 0 & 1 & 1 \\\ 0 & 1 & 1 & 0 & 1 & 0 & 0 & 1 \\\ 0 & 0 & 1 & 1 & 1 & 1 & 0 & 0 \\\ 0 & 1 & 1 & 0 & 1 & 0 & 0 & 1 \\\ 0 & 0 & 1 & 1 & 1 & 1 & 0 & 0 \\\ 1 & 0 & 0 & 1 & 0 & 1 & 1 & 0 \\\ 1 & 1 & 0& 0 & 0 & 0 & 1 & 1 \\\ \end{matrix}
And so on...
Let's numerate lines from top to bottom from 1 to infinity, and columns from left to right from 1 to infinity. We call the submatrix (x_1, y_1, x_2, y_2) all numbers that have coordinates (x, y) such that x_1 β€ x β€ x_2 and y_1 β€ y β€ y_2.
The Cossack needs sometimes to find the sum of all the numbers in submatrices. Since he is pretty busy right now, he is asking you to find the answers!
Input
The first line contains three integers n, m, q (1 β€ n, m β€ 1 000, 1 β€ q β€ 10^5) β the dimensions of the initial matrix and the number of queries.
Each of the next n lines contains m characters c_{ij} (0 β€ c_{ij} β€ 1) β the characters in the matrix.
Each of the next q lines contains four integers x_1, y_1, x_2, y_2 (1 β€ x_1 β€ x_2 β€ 10^9, 1 β€ y_1 β€ y_2 β€ 10^9) β the coordinates of the upper left cell and bottom right cell, between which you need to find the sum of all numbers.
Output
For each query, print the answer.
Examples
Input
2 2 5
10
11
1 1 8 8
2 4 5 6
1 2 7 8
3 3 6 8
5 6 7 8
Output
32
5
25
14
4
Input
2 3 7
100
101
4 12 5 17
5 4 9 4
1 4 13 18
12 1 14 9
3 10 7 18
3 15 12 17
8 6 8 12
Output
6
3
98
13
22
15
3
Note
The first example is explained in the legend.
Tags: divide and conquer, implementation, math
Correct Solution:
```
from sys import stdin,stdout
n,m,q = map(int, stdin.readline().split())
mat = [[0]*m for i in range(n)]
for i in range(n):
row = stdin.readline().strip()
for j,c in enumerate(row):
mat[i][j] = 1 if c == '1' else -1
#print(mat)
def get(a,b):
if a < 0 or b < 0:
return 0
x = a^b
ans = 1
while x > 0:
if x % 2 == 1:
ans *= -1
x //= 2
return ans
row_sums = [[0]*(m+1) for i in range(n+1)]
for i in range(n):
for j in range(m):
row_sums[i+1][j+1] = row_sums[i][j+1] + mat[i][j]
#print(row_sums)
mat_sums = [[0]*(m+1) for i in range(n+1)]
for i in range(n):
for j in range(m):
mat_sums[i+1][j+1] = mat_sums[i+1][j] + row_sums[i+1][j+1]
#print(mat_sums)
total = mat_sums[n][m]
def rect_sum(a, b):
if a == 0 or b == 0:
return 0
top_edge = 0
right_edge = 0
small = 0
x = a//n
x_rem = a%n
y = b // m
y_rem = b%m
# print("x", x, "y", y, "x_rem", x_rem, "y_rem", y_rem)
big = 0 if x % 2 == 0 or y % 2 == 0 else total
big *= get(x-1,y-1)
if x % 2 == 1:
right_edge= mat_sums[n][y_rem]
right_edge *= get(x-1,y)
if y % 2 == 1:
top_edge = mat_sums[x_rem][m]
top_edge *= get(x,y-1)
small = mat_sums[x_rem][y_rem]
small *= get(x,y)
# print("big", big, "top", top_edge, "right", right_edge, "small", small)
return top_edge + right_edge+small+big
for it in range(q):
x1,y1,x2,y2 = map(int, stdin.readline().split())
ans = rect_sum(x2,y2) - rect_sum(x1-1, y2) - rect_sum(x2, y1-1) + rect_sum(x1-1,y1-1)
ans = ((x2-x1+1)*(y2-y1+1) + ans)//2
stdout.write(str(ans) + '\n')
```
| 8,435 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vus the Cossack has a field with dimensions n Γ m, which consists of "0" and "1". He is building an infinite field from this field. He is doing this in this way:
1. He takes the current field and finds a new inverted field. In other words, the new field will contain "1" only there, where "0" was in the current field, and "0" there, where "1" was.
2. To the current field, he adds the inverted field to the right.
3. To the current field, he adds the inverted field to the bottom.
4. To the current field, he adds the current field to the bottom right.
5. He repeats it.
For example, if the initial field was:
\begin{matrix} 1 & 0 & \\\ 1 & 1 & \\\ \end{matrix}
After the first iteration, the field will be like this:
\begin{matrix} 1 & 0 & 0 & 1 \\\ 1 & 1 & 0 & 0 \\\ 0 & 1 & 1 & 0 \\\ 0 & 0 & 1 & 1 \\\ \end{matrix}
After the second iteration, the field will be like this:
\begin{matrix} 1 & 0 & 0 & 1 & 0 & 1 & 1 & 0 \\\ 1 & 1 & 0 & 0 & 0 & 0 & 1 & 1 \\\ 0 & 1 & 1 & 0 & 1 & 0 & 0 & 1 \\\ 0 & 0 & 1 & 1 & 1 & 1 & 0 & 0 \\\ 0 & 1 & 1 & 0 & 1 & 0 & 0 & 1 \\\ 0 & 0 & 1 & 1 & 1 & 1 & 0 & 0 \\\ 1 & 0 & 0 & 1 & 0 & 1 & 1 & 0 \\\ 1 & 1 & 0& 0 & 0 & 0 & 1 & 1 \\\ \end{matrix}
And so on...
Let's numerate lines from top to bottom from 1 to infinity, and columns from left to right from 1 to infinity. We call the submatrix (x_1, y_1, x_2, y_2) all numbers that have coordinates (x, y) such that x_1 β€ x β€ x_2 and y_1 β€ y β€ y_2.
The Cossack needs sometimes to find the sum of all the numbers in submatrices. Since he is pretty busy right now, he is asking you to find the answers!
Input
The first line contains three integers n, m, q (1 β€ n, m β€ 1 000, 1 β€ q β€ 10^5) β the dimensions of the initial matrix and the number of queries.
Each of the next n lines contains m characters c_{ij} (0 β€ c_{ij} β€ 1) β the characters in the matrix.
Each of the next q lines contains four integers x_1, y_1, x_2, y_2 (1 β€ x_1 β€ x_2 β€ 10^9, 1 β€ y_1 β€ y_2 β€ 10^9) β the coordinates of the upper left cell and bottom right cell, between which you need to find the sum of all numbers.
Output
For each query, print the answer.
Examples
Input
2 2 5
10
11
1 1 8 8
2 4 5 6
1 2 7 8
3 3 6 8
5 6 7 8
Output
32
5
25
14
4
Input
2 3 7
100
101
4 12 5 17
5 4 9 4
1 4 13 18
12 1 14 9
3 10 7 18
3 15 12 17
8 6 8 12
Output
6
3
98
13
22
15
3
Note
The first example is explained in the legend.
Submitted Solution:
```
def tm(a,b):
if a | b == 0:
return 0
else:
return (a & 1) ^ (b & 1) ^ tm(a >> 1, b >> 1)
def conv(c):
if c == '0':
return 0
else:
return 1
n,m,q = list(map(int,input().split()))
l = []
for r in range(n):
l.append(list(map(conv,list(input()))))
pre = []
for r in range(n):
pre.append([])
for c in range(m):
if r + c == 0:
pre[0].append(l[0][0])
elif r == 0:
pre[r].append(pre[r][c-1]+l[r][c])
elif c == 0:
pre[r].append(pre[r-1][c]+l[r][c])
else:
pre[r].append(pre[r][c-1]+pre[r-1][c]-pre[r-1][c-1]+l[r][c])
def findsize(x,xx,y,yy):
xp = xx//m
yp = yy//n
if xp > x // m:
split = xp * m
return findsize(x,split-1,y,yy)+findsize(split,xx,y,yy)
if yp > y // n:
split = yp * n
return findsize(x,xx,y,split-1)+findsize(x,xx,split,yy)
flip = tm(xp,yp)
xt = x - xp*m
xtt = xx - xp*m
yt = y - yp*n
ytt = yy - yp*n
if xt == 0 and yt == 0:
out = pre[ytt][xtt]
elif xt == 0:
out = pre[ytt][xtt] - pre[yt - 1][xtt]
elif yt == 0:
out = pre[ytt][xtt] - pre[ytt][xt - 1]
else:
out = pre[ytt][xtt] - pre[yt - 1][xtt] - pre[ytt][xt - 1] + pre[yt - 1][xt - 1]
if flip == 1:
out = (xx-x+1)*(yy-y+1)-out
# print(x,xx,y,yy,out)
return out
for _ in range(q):
x1, y1, x2, y2 = list(map(int,input().split()))
BASE = (x2-x1+1)*(y2-y1+1)
xstart = x1 - 1
xsize = (x2-x1) % (2*m) + 1
ystart = y1 - 1
ysize = (y2-y1) % (2*n) + 1
SIZEA = 2*findsize(xstart,xstart+xsize-1,ystart,ystart+ysize-1)
SIZEB = xsize*ysize
REAL = (SIZEA-SIZEB)+BASE
assert(REAL % 2 == 0)
print(REAL//2)
```
No
| 8,436 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vus the Cossack has a field with dimensions n Γ m, which consists of "0" and "1". He is building an infinite field from this field. He is doing this in this way:
1. He takes the current field and finds a new inverted field. In other words, the new field will contain "1" only there, where "0" was in the current field, and "0" there, where "1" was.
2. To the current field, he adds the inverted field to the right.
3. To the current field, he adds the inverted field to the bottom.
4. To the current field, he adds the current field to the bottom right.
5. He repeats it.
For example, if the initial field was:
\begin{matrix} 1 & 0 & \\\ 1 & 1 & \\\ \end{matrix}
After the first iteration, the field will be like this:
\begin{matrix} 1 & 0 & 0 & 1 \\\ 1 & 1 & 0 & 0 \\\ 0 & 1 & 1 & 0 \\\ 0 & 0 & 1 & 1 \\\ \end{matrix}
After the second iteration, the field will be like this:
\begin{matrix} 1 & 0 & 0 & 1 & 0 & 1 & 1 & 0 \\\ 1 & 1 & 0 & 0 & 0 & 0 & 1 & 1 \\\ 0 & 1 & 1 & 0 & 1 & 0 & 0 & 1 \\\ 0 & 0 & 1 & 1 & 1 & 1 & 0 & 0 \\\ 0 & 1 & 1 & 0 & 1 & 0 & 0 & 1 \\\ 0 & 0 & 1 & 1 & 1 & 1 & 0 & 0 \\\ 1 & 0 & 0 & 1 & 0 & 1 & 1 & 0 \\\ 1 & 1 & 0& 0 & 0 & 0 & 1 & 1 \\\ \end{matrix}
And so on...
Let's numerate lines from top to bottom from 1 to infinity, and columns from left to right from 1 to infinity. We call the submatrix (x_1, y_1, x_2, y_2) all numbers that have coordinates (x, y) such that x_1 β€ x β€ x_2 and y_1 β€ y β€ y_2.
The Cossack needs sometimes to find the sum of all the numbers in submatrices. Since he is pretty busy right now, he is asking you to find the answers!
Input
The first line contains three integers n, m, q (1 β€ n, m β€ 1 000, 1 β€ q β€ 10^5) β the dimensions of the initial matrix and the number of queries.
Each of the next n lines contains m characters c_{ij} (0 β€ c_{ij} β€ 1) β the characters in the matrix.
Each of the next q lines contains four integers x_1, y_1, x_2, y_2 (1 β€ x_1 β€ x_2 β€ 10^9, 1 β€ y_1 β€ y_2 β€ 10^9) β the coordinates of the upper left cell and bottom right cell, between which you need to find the sum of all numbers.
Output
For each query, print the answer.
Examples
Input
2 2 5
10
11
1 1 8 8
2 4 5 6
1 2 7 8
3 3 6 8
5 6 7 8
Output
32
5
25
14
4
Input
2 3 7
100
101
4 12 5 17
5 4 9 4
1 4 13 18
12 1 14 9
3 10 7 18
3 15 12 17
8 6 8 12
Output
6
3
98
13
22
15
3
Note
The first example is explained in the legend.
Submitted Solution:
```
import sys
N, M, Q = map(int, input().split())
print(N, M, Q)
X = []
for _ in range(N):
X.append(list(map(int, list(sys.stdin.readline().rstrip()))))
Y = [[0]*(2*M+1) for _ in range(2*N+1)]
for i in range(N):
s = 0
for j in range(M):
s += X[i][j]
Y[i+1][j+1] = Y[i][j+1] + s
for j in range(M):
s += X[i][j]^1
Y[i+1][j+M+1] = Y[i][j+M+1] + s
for i in range(N):
s = 0
for j in range(M):
s += X[i][j]^1
Y[i+N+1][j+1] = Y[i+N][j+1] + s
for j in range(M):
s += X[i][j]
Y[i+N+1][j+M+1] = Y[i+N][j+M+1] + s
def calc(x, y):
if x >= 2*N:
n = N
while n*2 <= x:
n *= 2
return n*y//2 + (x-n)*y - calc(x-n, y)
if y >= 2*M:
m = M
while m*2 <= y:
m *= 2
return m*x//2 + (y-m)*x - calc(x, y-m)
return Y[x][y]
for _ in range(Q):
x1, y1, x2, y2 = map(int, sys.stdin.readline().rstrip().split())
x1, y1 = x1-1, y1-1
print(calc(x2, y2) - calc(x1, y2) - calc(x2, y1) + calc(x1, y1))
```
No
| 8,437 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree with n nodes. You have to write non-negative integers on its edges so that the following condition would be satisfied:
For every two nodes i, j, look at the path between them and count the sum of numbers on the edges of this path. Write all obtained sums on the blackboard. Then every integer from 1 to β (2n^2)/(9) β has to be written on the blackboard at least once.
It is guaranteed that such an arrangement exists.
Input
The first line contains a single integer n (1 β€ n β€ 1000) β the number of nodes.
Each of the next n-1 lines contains two integers u and v (1 β€ u, v β€ n, u β v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.
Output
Output n-1 lines, each of form u v x (0 β€ x β€ 10^6), which will mean that you wrote number x on the edge between u, v.
Set of edges (u, v) has to coincide with the set of edges of the input graph, but you can output edges in any order. You can also output ends of edges in an order different from the order in input.
Examples
Input
3
2 3
2 1
Output
3 2 1
1 2 2
Input
4
2 4
2 3
2 1
Output
4 2 1
3 2 2
1 2 3
Input
5
1 2
1 3
1 4
2 5
Output
2 1 1
5 2 1
3 1 3
4 1 6
Note
In the first example, distance between nodes 1 and 2 is equal to 2, between nodes 2 and 3 to 1, between 1 and 3 to 3.
In the third example, numbers from 1 to 9 (inclusive) will be written on the blackboard, while we need just from 1 to 5 to pass the test.
Tags: constructive algorithms, trees
Correct Solution:
```
import math
n = int(input())
if n == 1:
print()
else:
edge = [list(map(int, input().split())) for i in range(1, n) ]
g = {}
for x, y in edge:
if x not in g:
g[x] = []
if y not in g:
g[y] = []
g[x].append(y)
g[y].append(x)
def find_centroid(g):
p = {}
size = {}
p[1] = -1
Q = [1]
i = 0
while i < len(Q):
u = Q[i]
for v in g[u]:
if p[u] == v: continue
p[v] = u
Q.append(v)
i+=1
for u in Q[::-1]:
size[u] = 1
for v in g[u]:
if p[u] == v:
continue
size[u] += size[v]
cur = 1
n = size[cur]
while True:
max_ = n - size[cur]
ind_ = p[cur]
for v in g[cur]:
if v == p[cur]: continue
if size[v] > max_:
max_ = size[v]
ind_ = v
if max_ <= n // 2:
return cur
cur = ind_
def find_center(g):
d = {}
d[1] = 0
Q = [(1, 0)]
while len(Q) > 0:
u, dis = Q.pop(0)
for v in g[u]:
if v not in d:
d[v] = dis +1
Q.append((v, d[v]))
max_length = -1
s = None
for u, dis in d.items():
if dis > max_length:
max_length = dis
s = u
d = {}
pre = {}
d[s] = 0
Q = [(s, 0)]
while len(Q) > 0:
u, dis = Q.pop(0)
for v in g[u]:
if v not in d:
pre[v] = u
d[v] = dis +1
Q.append((v, d[v]))
max_length = -1
e = None
for u, dis in d.items():
if dis > max_length:
max_length = dis
e = u
route = [e]
while pre[route[-1]] != s:
route.append(pre[route[-1]])
print(route)
return route[len(route) // 2]
root = find_centroid(g)
p = {}
size = {}
Q = [root]
p[root] = -1
i = 0
while i < len(Q):
u = Q[i]
for v in g[u]:
if p[u] == v: continue
p[v] = u
Q.append(v)
i+=1
for u in Q[::-1]:
size[u] = 1
for v in g[u]:
if p[u] == v:
continue
size[u] += size[v]
gr = [(u, size[u]) for u in g[root]]
gr = sorted(gr, key=lambda x:x[1])
thres = math.ceil((n-1) / 3)
sum_ = 0
gr1 = []
gr2 = []
i = 0
while sum_ < thres:
gr1.append(gr[i][0])
sum_ += gr[i][1]
i+=1
while i < len(gr):
gr2.append(gr[i][0])
i+=1
def asign(u, W, ew):
if size[u] == 1:
return
cur = 0
for v in g[u]:
if v == p[u]: continue
first = W[cur]
ew.append((u, v, first))
W_ = [x - first for x in W[cur+1: cur+size[v]]]
asign(v, W_, ew)
cur+=size[v]
a, b = 0, 0
for x in gr1:
a += size[x]
for x in gr2:
b += size[x]
arr_1 = [x for x in range(1, a+1)]
arr_2 = [i*(a+1) for i in range(1, b+1)]
ew = []
cur = 0
for u in gr1:
first = arr_1[cur]
ew.append((root, u, first))
W_ = [x - first for x in arr_1[cur+1:cur+size[u]]]
cur += size[u]
#print(u, W_)
asign(u, W_, ew)
cur = 0
for u in gr2:
first = arr_2[cur]
ew.append((root, u, first))
W_ = [x - first for x in arr_2[cur+1:cur+size[u]]]
cur += size[u]
#print(u, W_)
asign(u, W_, ew)
for u, v, w in ew:
print('{} {} {}'.format(u, v, w))
```
| 8,438 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with n nodes. You have to write non-negative integers on its edges so that the following condition would be satisfied:
For every two nodes i, j, look at the path between them and count the sum of numbers on the edges of this path. Write all obtained sums on the blackboard. Then every integer from 1 to β (2n^2)/(9) β has to be written on the blackboard at least once.
It is guaranteed that such an arrangement exists.
Input
The first line contains a single integer n (1 β€ n β€ 1000) β the number of nodes.
Each of the next n-1 lines contains two integers u and v (1 β€ u, v β€ n, u β v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.
Output
Output n-1 lines, each of form u v x (0 β€ x β€ 10^6), which will mean that you wrote number x on the edge between u, v.
Set of edges (u, v) has to coincide with the set of edges of the input graph, but you can output edges in any order. You can also output ends of edges in an order different from the order in input.
Examples
Input
3
2 3
2 1
Output
3 2 1
1 2 2
Input
4
2 4
2 3
2 1
Output
4 2 1
3 2 2
1 2 3
Input
5
1 2
1 3
1 4
2 5
Output
2 1 1
5 2 1
3 1 3
4 1 6
Note
In the first example, distance between nodes 1 and 2 is equal to 2, between nodes 2 and 3 to 1, between 1 and 3 to 3.
In the third example, numbers from 1 to 9 (inclusive) will be written on the blackboard, while we need just from 1 to 5 to pass the test.
Submitted Solution:
```
import math
n = int(input())
if n == 1:
print()
else:
edge = [list(map(int, input().split())) for _ in range(n-1) ]
g = {}
for x, y in edge:
if x not in g:
g[x] = []
if y not in g:
g[y] = []
g[x].append(y)
g[y].append(x)
def find_center(g):
d = {}
d[1] = 0
Q = [(1, 0)]
while len(Q) > 0:
u, dis = Q.pop(0)
for v in g[u]:
if v not in d:
d[v] = dis +1
Q.append((v, d[v]))
max_length = -1
s = None
for u, dis in d.items():
if dis > max_length:
max_length = dis
s = u
d = {}
pre = {}
d[s] = 0
Q = [(s, 0)]
while len(Q) > 0:
u, dis = Q.pop(0)
for v in g[u]:
if v not in d:
pre[v] = u
d[v] = dis +1
Q.append((v, d[v]))
max_length = -1
e = None
for u, dis in d.items():
if dis > max_length:
max_length = dis
e = u
route = [e]
while pre[route[-1]] != s:
route.append(pre[route[-1]])
return route[len(route) // 2]
root = find_center(g)
p = {}
size = {}
Q = [root]
p[root] = -1
i = 0
while i < len(Q):
u = Q[i]
for v in g[u]:
if p[u] == v: continue
p[v] = u
Q.append(v)
i+=1
for u in Q[::-1]:
size[u] = 1
for v in g[u]:
if p[u] == v:
continue
size[u] += size[v]
gr = [(u, size[u]) for u in g[root]]
gr = sorted(gr, key=lambda x:x[1])
thres = math.ceil((n-1) / 3)
sum_ = 0
gr1 = []
gr2 = []
i = 0
while sum_ < thres:
gr1.append(gr[i][0])
sum_ += gr[i][1]
i+=1
while i < len(gr):
gr2.append(gr[i][0])
i+=1
def asign(u, W, ew):
if size[u] == 1:
return
cur = 0
for v in g[u]:
if v == p[u]: continue
first = W[cur]
ew.append((u, v, first))
W_ = [x - first for x in W[cur+1: cur+size[v]]]
asign(v, W_, ew)
cur+=size[v]
a, b = 0, 0
for x in gr1:
a += size[x]
for x in gr2:
b += size[x]
arr_1 = [x for x in range(1, a+1)]
arr_2 = [i*(a+1) for i in range(1, b+1)]
ew = []
cur = 0
for u in gr1:
first = arr_1[cur]
ew.append((root, u, first))
W_ = [x - first for x in arr_1[cur+1:cur+size[u]]]
cur += size[u]
#print(u, W_)
asign(u, W_, ew)
cur = 0
for u in gr2:
first = arr_2[cur]
ew.append((root, u, first))
W_ = [x - first for x in arr_2[cur+1:cur+size[u]]]
cur += size[u]
#print(u, W_)
asign(u, W_, ew)
for u, v, w in ew:
print('{} {} {}'.format(u, v, w))
```
No
| 8,439 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero.
For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not.
Now, you have n matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!
For example, if n = 2, you can buy two matches and assemble |+|=||, and if n = 5 you can buy one match and assemble ||+|=|||.
<image>
Calculate the minimum number of matches which you have to buy for assembling CME.
Note, that you have to answer q independent queries.
Input
The first line contains one integer q (1 β€ q β€ 100) β the number of queries.
The only line of each query contains one integer n (2 β€ n β€ 10^9) β the number of matches.
Output
For each test case print one integer in single line β the minimum number of matches which you have to buy for assembling CME.
Example
Input
4
2
5
8
11
Output
2
1
0
1
Note
The first and second queries are explained in the statement.
In the third query, you can assemble 1 + 3 = 4 (|+|||=||||) without buying matches.
In the fourth query, buy one match and assemble 2 + 4 = 6 (||+||||=||||||).
Tags: math
Correct Solution:
```
def CME(n):
if (n==1):
return 3
elif (n==2):
return 2
elif (n%2==0):
return 0
elif (n%2!=0):
return 1
t=int(input())
for i in range (t):
a=int(input())
ans = CME(a)
print(ans)
```
| 8,440 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero.
For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not.
Now, you have n matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!
For example, if n = 2, you can buy two matches and assemble |+|=||, and if n = 5 you can buy one match and assemble ||+|=|||.
<image>
Calculate the minimum number of matches which you have to buy for assembling CME.
Note, that you have to answer q independent queries.
Input
The first line contains one integer q (1 β€ q β€ 100) β the number of queries.
The only line of each query contains one integer n (2 β€ n β€ 10^9) β the number of matches.
Output
For each test case print one integer in single line β the minimum number of matches which you have to buy for assembling CME.
Example
Input
4
2
5
8
11
Output
2
1
0
1
Note
The first and second queries are explained in the statement.
In the third query, you can assemble 1 + 3 = 4 (|+|||=||||) without buying matches.
In the fourth query, buy one match and assemble 2 + 4 = 6 (||+||||=||||||).
Tags: math
Correct Solution:
```
def f(n):
if n == 2:
return 2
if n % 2 == 0:
return 0
return 1
for i in range(int(input())):
print(f(int(input())))
```
| 8,441 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero.
For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not.
Now, you have n matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!
For example, if n = 2, you can buy two matches and assemble |+|=||, and if n = 5 you can buy one match and assemble ||+|=|||.
<image>
Calculate the minimum number of matches which you have to buy for assembling CME.
Note, that you have to answer q independent queries.
Input
The first line contains one integer q (1 β€ q β€ 100) β the number of queries.
The only line of each query contains one integer n (2 β€ n β€ 10^9) β the number of matches.
Output
For each test case print one integer in single line β the minimum number of matches which you have to buy for assembling CME.
Example
Input
4
2
5
8
11
Output
2
1
0
1
Note
The first and second queries are explained in the statement.
In the third query, you can assemble 1 + 3 = 4 (|+|||=||||) without buying matches.
In the fourth query, buy one match and assemble 2 + 4 = 6 (||+||||=||||||).
Tags: math
Correct Solution:
```
n = int(input())
a =[int(input()) for i in range(n)]
for i in a:
if i>2 and i%2==1:
print(1)
elif i>2 and i%2==0:
print(0)
elif i==2:
print(2)
```
| 8,442 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero.
For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not.
Now, you have n matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!
For example, if n = 2, you can buy two matches and assemble |+|=||, and if n = 5 you can buy one match and assemble ||+|=|||.
<image>
Calculate the minimum number of matches which you have to buy for assembling CME.
Note, that you have to answer q independent queries.
Input
The first line contains one integer q (1 β€ q β€ 100) β the number of queries.
The only line of each query contains one integer n (2 β€ n β€ 10^9) β the number of matches.
Output
For each test case print one integer in single line β the minimum number of matches which you have to buy for assembling CME.
Example
Input
4
2
5
8
11
Output
2
1
0
1
Note
The first and second queries are explained in the statement.
In the third query, you can assemble 1 + 3 = 4 (|+|||=||||) without buying matches.
In the fourth query, buy one match and assemble 2 + 4 = 6 (||+||||=||||||).
Tags: math
Correct Solution:
```
q = int(input())
for j in range(q):
inp = int(input())
if inp == 1:
print("3")
elif inp == 2:
print("2")
else:
if inp % 2 == 0:
print("0")
else:
print("1")
```
| 8,443 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero.
For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not.
Now, you have n matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!
For example, if n = 2, you can buy two matches and assemble |+|=||, and if n = 5 you can buy one match and assemble ||+|=|||.
<image>
Calculate the minimum number of matches which you have to buy for assembling CME.
Note, that you have to answer q independent queries.
Input
The first line contains one integer q (1 β€ q β€ 100) β the number of queries.
The only line of each query contains one integer n (2 β€ n β€ 10^9) β the number of matches.
Output
For each test case print one integer in single line β the minimum number of matches which you have to buy for assembling CME.
Example
Input
4
2
5
8
11
Output
2
1
0
1
Note
The first and second queries are explained in the statement.
In the third query, you can assemble 1 + 3 = 4 (|+|||=||||) without buying matches.
In the fourth query, buy one match and assemble 2 + 4 = 6 (||+||||=||||||).
Tags: math
Correct Solution:
```
q=int(input())
for i in range(q):
n=int(input())
if n==2:
print(2)
elif n%2!=0:
print(1)
else:
print(0)
```
| 8,444 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero.
For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not.
Now, you have n matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!
For example, if n = 2, you can buy two matches and assemble |+|=||, and if n = 5 you can buy one match and assemble ||+|=|||.
<image>
Calculate the minimum number of matches which you have to buy for assembling CME.
Note, that you have to answer q independent queries.
Input
The first line contains one integer q (1 β€ q β€ 100) β the number of queries.
The only line of each query contains one integer n (2 β€ n β€ 10^9) β the number of matches.
Output
For each test case print one integer in single line β the minimum number of matches which you have to buy for assembling CME.
Example
Input
4
2
5
8
11
Output
2
1
0
1
Note
The first and second queries are explained in the statement.
In the third query, you can assemble 1 + 3 = 4 (|+|||=||||) without buying matches.
In the fourth query, buy one match and assemble 2 + 4 = 6 (||+||||=||||||).
Tags: math
Correct Solution:
```
for i in range(int(input())):
n = int(input())
print(4 - n) if n < 4 else print(n % 2)
```
| 8,445 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero.
For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not.
Now, you have n matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!
For example, if n = 2, you can buy two matches and assemble |+|=||, and if n = 5 you can buy one match and assemble ||+|=|||.
<image>
Calculate the minimum number of matches which you have to buy for assembling CME.
Note, that you have to answer q independent queries.
Input
The first line contains one integer q (1 β€ q β€ 100) β the number of queries.
The only line of each query contains one integer n (2 β€ n β€ 10^9) β the number of matches.
Output
For each test case print one integer in single line β the minimum number of matches which you have to buy for assembling CME.
Example
Input
4
2
5
8
11
Output
2
1
0
1
Note
The first and second queries are explained in the statement.
In the third query, you can assemble 1 + 3 = 4 (|+|||=||||) without buying matches.
In the fourth query, buy one match and assemble 2 + 4 = 6 (||+||||=||||||).
Tags: math
Correct Solution:
```
n=int(input())
for i in range(n):
t=int(input())
if(t%2==0):
if(t==2):
print(2)
else:
print(0)
else:
if(t==1):
print(3)
else:
print(1)
```
| 8,446 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero.
For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not.
Now, you have n matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!
For example, if n = 2, you can buy two matches and assemble |+|=||, and if n = 5 you can buy one match and assemble ||+|=|||.
<image>
Calculate the minimum number of matches which you have to buy for assembling CME.
Note, that you have to answer q independent queries.
Input
The first line contains one integer q (1 β€ q β€ 100) β the number of queries.
The only line of each query contains one integer n (2 β€ n β€ 10^9) β the number of matches.
Output
For each test case print one integer in single line β the minimum number of matches which you have to buy for assembling CME.
Example
Input
4
2
5
8
11
Output
2
1
0
1
Note
The first and second queries are explained in the statement.
In the third query, you can assemble 1 + 3 = 4 (|+|||=||||) without buying matches.
In the fourth query, buy one match and assemble 2 + 4 = 6 (||+||||=||||||).
Tags: math
Correct Solution:
```
# ki holo vai ? Bujlam na...
# Court station Bollam r chere dilo
import math
t=int(input())
for __ in range(t):
n=int(input())
print(4-n) if n<=3 else print(n%2)
```
| 8,447 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero.
For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not.
Now, you have n matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!
For example, if n = 2, you can buy two matches and assemble |+|=||, and if n = 5 you can buy one match and assemble ||+|=|||.
<image>
Calculate the minimum number of matches which you have to buy for assembling CME.
Note, that you have to answer q independent queries.
Input
The first line contains one integer q (1 β€ q β€ 100) β the number of queries.
The only line of each query contains one integer n (2 β€ n β€ 10^9) β the number of matches.
Output
For each test case print one integer in single line β the minimum number of matches which you have to buy for assembling CME.
Example
Input
4
2
5
8
11
Output
2
1
0
1
Note
The first and second queries are explained in the statement.
In the third query, you can assemble 1 + 3 = 4 (|+|||=||||) without buying matches.
In the fourth query, buy one match and assemble 2 + 4 = 6 (||+||||=||||||).
Submitted Solution:
```
for _ in range(int(input())):
n=int(input())
if n<4:
print(4-n)
elif n%2==0:
print(0)
else:
print(1)
```
Yes
| 8,448 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero.
For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not.
Now, you have n matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!
For example, if n = 2, you can buy two matches and assemble |+|=||, and if n = 5 you can buy one match and assemble ||+|=|||.
<image>
Calculate the minimum number of matches which you have to buy for assembling CME.
Note, that you have to answer q independent queries.
Input
The first line contains one integer q (1 β€ q β€ 100) β the number of queries.
The only line of each query contains one integer n (2 β€ n β€ 10^9) β the number of matches.
Output
For each test case print one integer in single line β the minimum number of matches which you have to buy for assembling CME.
Example
Input
4
2
5
8
11
Output
2
1
0
1
Note
The first and second queries are explained in the statement.
In the third query, you can assemble 1 + 3 = 4 (|+|||=||||) without buying matches.
In the fourth query, buy one match and assemble 2 + 4 = 6 (||+||||=||||||).
Submitted Solution:
```
n=int(input())
for i in range(n):
m=int(input())
if(m<=4):
print(4-m)
else:
if(m%2==0):
print(0)
else:
print(1)
```
Yes
| 8,449 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero.
For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not.
Now, you have n matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!
For example, if n = 2, you can buy two matches and assemble |+|=||, and if n = 5 you can buy one match and assemble ||+|=|||.
<image>
Calculate the minimum number of matches which you have to buy for assembling CME.
Note, that you have to answer q independent queries.
Input
The first line contains one integer q (1 β€ q β€ 100) β the number of queries.
The only line of each query contains one integer n (2 β€ n β€ 10^9) β the number of matches.
Output
For each test case print one integer in single line β the minimum number of matches which you have to buy for assembling CME.
Example
Input
4
2
5
8
11
Output
2
1
0
1
Note
The first and second queries are explained in the statement.
In the third query, you can assemble 1 + 3 = 4 (|+|||=||||) without buying matches.
In the fourth query, buy one match and assemble 2 + 4 = 6 (||+||||=||||||).
Submitted Solution:
```
a=int(input())
for i in range(a):
n=int(input())
if n==2:
print(2)
elif n%2==0:
print(0)
else:
print(1)
```
Yes
| 8,450 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero.
For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not.
Now, you have n matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!
For example, if n = 2, you can buy two matches and assemble |+|=||, and if n = 5 you can buy one match and assemble ||+|=|||.
<image>
Calculate the minimum number of matches which you have to buy for assembling CME.
Note, that you have to answer q independent queries.
Input
The first line contains one integer q (1 β€ q β€ 100) β the number of queries.
The only line of each query contains one integer n (2 β€ n β€ 10^9) β the number of matches.
Output
For each test case print one integer in single line β the minimum number of matches which you have to buy for assembling CME.
Example
Input
4
2
5
8
11
Output
2
1
0
1
Note
The first and second queries are explained in the statement.
In the third query, you can assemble 1 + 3 = 4 (|+|||=||||) without buying matches.
In the fourth query, buy one match and assemble 2 + 4 = 6 (||+||||=||||||).
Submitted Solution:
```
h = int(input())
for i in range(h):
a = int(input())
if a < 4:
print(4 - a)
elif a % 2 != 0:
print(1)
else:
print(0)
```
Yes
| 8,451 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero.
For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not.
Now, you have n matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!
For example, if n = 2, you can buy two matches and assemble |+|=||, and if n = 5 you can buy one match and assemble ||+|=|||.
<image>
Calculate the minimum number of matches which you have to buy for assembling CME.
Note, that you have to answer q independent queries.
Input
The first line contains one integer q (1 β€ q β€ 100) β the number of queries.
The only line of each query contains one integer n (2 β€ n β€ 10^9) β the number of matches.
Output
For each test case print one integer in single line β the minimum number of matches which you have to buy for assembling CME.
Example
Input
4
2
5
8
11
Output
2
1
0
1
Note
The first and second queries are explained in the statement.
In the third query, you can assemble 1 + 3 = 4 (|+|||=||||) without buying matches.
In the fourth query, buy one match and assemble 2 + 4 = 6 (||+||||=||||||).
Submitted Solution:
```
n = input()
n = int(n)
for _ in range(n):
k = input()
k = int(k)
if k == 2:
print(2)
if k % 2 == 0 and k > 2:
print(0)
else:
print(1)
```
No
| 8,452 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero.
For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not.
Now, you have n matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!
For example, if n = 2, you can buy two matches and assemble |+|=||, and if n = 5 you can buy one match and assemble ||+|=|||.
<image>
Calculate the minimum number of matches which you have to buy for assembling CME.
Note, that you have to answer q independent queries.
Input
The first line contains one integer q (1 β€ q β€ 100) β the number of queries.
The only line of each query contains one integer n (2 β€ n β€ 10^9) β the number of matches.
Output
For each test case print one integer in single line β the minimum number of matches which you have to buy for assembling CME.
Example
Input
4
2
5
8
11
Output
2
1
0
1
Note
The first and second queries are explained in the statement.
In the third query, you can assemble 1 + 3 = 4 (|+|||=||||) without buying matches.
In the fourth query, buy one match and assemble 2 + 4 = 6 (||+||||=||||||).
Submitted Solution:
```
for i in range(int(input())):
q=int(input())
if q==2:
print(2)
elif q/2!=0:
print(1)
elif q/2==0:
print(0)
```
No
| 8,453 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero.
For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not.
Now, you have n matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!
For example, if n = 2, you can buy two matches and assemble |+|=||, and if n = 5 you can buy one match and assemble ||+|=|||.
<image>
Calculate the minimum number of matches which you have to buy for assembling CME.
Note, that you have to answer q independent queries.
Input
The first line contains one integer q (1 β€ q β€ 100) β the number of queries.
The only line of each query contains one integer n (2 β€ n β€ 10^9) β the number of matches.
Output
For each test case print one integer in single line β the minimum number of matches which you have to buy for assembling CME.
Example
Input
4
2
5
8
11
Output
2
1
0
1
Note
The first and second queries are explained in the statement.
In the third query, you can assemble 1 + 3 = 4 (|+|||=||||) without buying matches.
In the fourth query, buy one match and assemble 2 + 4 = 6 (||+||||=||||||).
Submitted Solution:
```
q = int(input())
for i in range(q):
t = int(input())
if t < 4:
otv = 4 - t
print(t)
else:
if t % 2 == 0:
print(0)
else:
print(1)
```
No
| 8,454 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero.
For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not.
Now, you have n matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!
For example, if n = 2, you can buy two matches and assemble |+|=||, and if n = 5 you can buy one match and assemble ||+|=|||.
<image>
Calculate the minimum number of matches which you have to buy for assembling CME.
Note, that you have to answer q independent queries.
Input
The first line contains one integer q (1 β€ q β€ 100) β the number of queries.
The only line of each query contains one integer n (2 β€ n β€ 10^9) β the number of matches.
Output
For each test case print one integer in single line β the minimum number of matches which you have to buy for assembling CME.
Example
Input
4
2
5
8
11
Output
2
1
0
1
Note
The first and second queries are explained in the statement.
In the third query, you can assemble 1 + 3 = 4 (|+|||=||||) without buying matches.
In the fourth query, buy one match and assemble 2 + 4 = 6 (||+||||=||||||).
Submitted Solution:
```
num_q = int(input())
inps = []
for i in range(num_q):
inps.append(int(input()))
for i in inps:
if i <= 2:
print(4-i)
if i % 2 == 0:
print("0")
else:
print("1")
```
No
| 8,455 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version, n β€ 300 000.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.
To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.
We remind that bracket sequence s is called correct if:
* s is empty;
* s is equal to "(t)", where t is correct bracket sequence;
* s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not.
The cyclical shift of the string s of length n by k (0 β€ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".
Cyclical shifts i and j are considered different, if i β j.
Input
The first line contains an integer n (1 β€ n β€ 300 000), the length of the string.
The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".
Output
The first line should contain a single integer β the largest beauty of the string, which can be achieved by swapping some two characters.
The second line should contain integers l and r (1 β€ l, r β€ n) β the indices of two characters, which should be swapped in order to maximize the string's beauty.
In case there are several possible swaps, print any of them.
Examples
Input
10
()()())(()
Output
5
8 7
Input
12
)(()(()())()
Output
4
5 10
Input
6
)))(()
Output
0
1 1
Note
In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.
In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.
In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences.
Tags: implementation
Correct Solution:
```
n = int(input())
s = input()
r = 0
l = n-1
root = []
buf = []
to_the_right = True
for count in range(n):
if to_the_right:
i = r
r += 1
else:
i = l
l -= 1
b = s[i]
if b == '(':
if len(buf) == 0 or buf[-1][0] != -1:
buf.append([-1,-1,[]])
buf[-1][0] = i
else:
if len(buf) == 0 or buf[-1][1] != -1:
buf.append([-1,-1,root])
root = []
to_the_right = False
buf[-1][1] = i
if buf[-1][0] != -1 and buf[-1][1] != -1:
tmp = buf.pop()
if len(buf):
buf[-1][2].append(tmp)
else:
root.append(tmp)
to_the_right = True
sol = [[0,1,1]]
if len(buf) == 0:
sol.append([len(root), 1, 1])
for child in root:
sol.append([len(child[2])+1, child[0]+1, child[1]+1])
for gr_child in child[2]:
sol.append([len(root)+len(gr_child[2])+1, gr_child[0]+1, gr_child[1]+1])
print('%d\n%d %d'%tuple(max(sol)))
```
| 8,456 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version, n β€ 300 000.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.
To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.
We remind that bracket sequence s is called correct if:
* s is empty;
* s is equal to "(t)", where t is correct bracket sequence;
* s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not.
The cyclical shift of the string s of length n by k (0 β€ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".
Cyclical shifts i and j are considered different, if i β j.
Input
The first line contains an integer n (1 β€ n β€ 300 000), the length of the string.
The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".
Output
The first line should contain a single integer β the largest beauty of the string, which can be achieved by swapping some two characters.
The second line should contain integers l and r (1 β€ l, r β€ n) β the indices of two characters, which should be swapped in order to maximize the string's beauty.
In case there are several possible swaps, print any of them.
Examples
Input
10
()()())(()
Output
5
8 7
Input
12
)(()(()())()
Output
4
5 10
Input
6
)))(()
Output
0
1 1
Note
In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.
In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.
In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences.
Tags: implementation
Correct Solution:
```
n = int(input())
ddd = input()
d = [0]
for dd in ddd:
if dd == '(':
d.append(d[-1] + 1)
else:
d.append(d[-1] - 1)
if d[-1] != 0:
print("0\n1 1")
exit(0)
d.pop()
mn = min(d)
ind = d.index(mn)
d = d[ind:] + d[:ind]
d = [i - mn for i in d]
fi = -1
crfi = -1
li = -1
mx = 0
cr = 0
cnt0 = 0
for i in range(n):
dd = d[i]
if dd == 0:
cnt0 += 1
if dd == 2:
if cr == 0:
crfi = i
cr += 1
if cr > mx:
fi = crfi
li = i
mx = cr
elif dd < 2:
cr = 0
# print('=========')
# print(d)
# print(cnt0)
# print(fi, li)
# print(mx)
# print("=========")
# if fi == -1:
# print(cnt0)
# print(1, 1)
# else:
# print(cnt0 + mx)
# print(fi, li + 2)
if fi == -1:
ans1 = [cnt0, 0, 0]
else:
ans1 = [cnt0 + mx, fi-1, li]
fi = -1
crfi = -1
li = -1
mx = 0
cr = 0
for i in range(n):
dd = d[i]
if dd == 1:
if cr == 0:
crfi = i
cr += 1
if cr > mx:
fi = crfi
li = i
mx = cr
elif dd < 1:
cr = 0
ans2 = [mx, fi-1, li]
if ans1[0] > ans2[0]:
print(ans1[0])
print(((ans1[1] + ind)%n) + 1, ((ans1[2] + ind)%n) + 1)
else:
print(ans2[0])
print(((ans2[1] + ind)%n) + 1, ((ans2[2] + ind)%n) + 1)
```
| 8,457 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is a harder version of the problem. In this version, n β€ 300 000.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.
To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.
We remind that bracket sequence s is called correct if:
* s is empty;
* s is equal to "(t)", where t is correct bracket sequence;
* s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not.
The cyclical shift of the string s of length n by k (0 β€ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".
Cyclical shifts i and j are considered different, if i β j.
Input
The first line contains an integer n (1 β€ n β€ 300 000), the length of the string.
The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".
Output
The first line should contain a single integer β the largest beauty of the string, which can be achieved by swapping some two characters.
The second line should contain integers l and r (1 β€ l, r β€ n) β the indices of two characters, which should be swapped in order to maximize the string's beauty.
In case there are several possible swaps, print any of them.
Examples
Input
10
()()())(()
Output
5
8 7
Input
12
)(()(()())()
Output
4
5 10
Input
6
)))(()
Output
0
1 1
Note
In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.
In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.
In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences.
Tags: implementation
Correct Solution:
```
n = int(input().strip())
s= input().strip()
ss= 0
mina = 0
ti = 0
for k in range(len(s)):
if(s[k] == "("):
ss+=1
else:
ss-=1
if(ss<0):
ti = k+1
ss = 0
s=s[ti:]+s[:ti]
#print(s)
ss= 0
for k in range(len(s)):
if(s[k] == "("):
ss+=1
else:
ss-=1
if(ss<0):
print(0)
print(1,1)
break
else:
if(ss == 0):
pre=[0 for k in range(len(s))]
ss=0
for k in range(len(s)):
if (s[k] == "("):
ss += 1
else:
ss -= 1
pre[k] = ss
tt = 0
a =(1,1)
for k in range(0,len(s)):
if(pre[k] == 0):
tt+=1
maxi= tt
#print(pre)
g =0
gg =0
while(gg<len(s)):
if(pre[gg] == 0):
#print(gg,g,"g")
if(gg != g+1):
yy = g+1
y = g+1
q = 0
while(yy<gg):
if(pre[yy] == 1):
# print(yy,y,"y")
if(yy !=y+1):
rr = y+1
r = y+1
h = 0
while(rr<yy):
if(pre[rr] == 2):
h+=1
rr+=1
if(tt+h+1>maxi):
maxi = tt + h + 1
a=(y,yy)
else:
if(tt+1>maxi):
maxi =tt+1
a=(y,yy)
#print(a, a)
q+=1
y = yy+1
yy = y
else:
yy+=1
if (q + 1 > maxi):
maxi = q+1
a = (g, gg)
g= gg+1
gg= g
else:
gg+=1
print(maxi)
# print(a)
print((a[0]+ti)%len(s)+1,(a[1]+ti)%len(s)+1)
else:
print(0)
print(1,1)
```
| 8,458 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version, n β€ 300 000.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.
To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.
We remind that bracket sequence s is called correct if:
* s is empty;
* s is equal to "(t)", where t is correct bracket sequence;
* s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not.
The cyclical shift of the string s of length n by k (0 β€ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".
Cyclical shifts i and j are considered different, if i β j.
Input
The first line contains an integer n (1 β€ n β€ 300 000), the length of the string.
The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".
Output
The first line should contain a single integer β the largest beauty of the string, which can be achieved by swapping some two characters.
The second line should contain integers l and r (1 β€ l, r β€ n) β the indices of two characters, which should be swapped in order to maximize the string's beauty.
In case there are several possible swaps, print any of them.
Examples
Input
10
()()())(()
Output
5
8 7
Input
12
)(()(()())()
Output
4
5 10
Input
6
)))(()
Output
0
1 1
Note
In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.
In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.
In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences.
Submitted Solution:
```
n = int(input().strip())
s= input().strip()
ss= 0
mina = 0
ti = 0
for k in range(len(s)):
if(s[k] == "("):
ss+=1
else:
ss-=1
if(ss<0):
ti = k+1
ss = 0
s=s[ti:]+s[:ti]
ss= 0
for k in range(len(s)):
if(s[k] == "("):
ss+=1
else:
ss-=1
if(ss<0):
print(0)
print(1,1)
break
else:
if(ss == 0):
pre=[0 for k in range(len(s))]
for k in range(len(s)):
if (s[k] == "("):
ss += 1
else:
ss -= 1
pre[k] = ss
tt = 0
a =(1,1)
for k in range(0,len(s)):
if(pre[k] == 0):
tt+=1
maxi= tt
g =0
gg =0
while(gg<len(s)):
if(pre[gg] == 0):
if(gg != g+1):
yy = g+1
y = g+1
q = 0
while(yy<gg):
if(pre[yy] == 1):
if(yy !=y+1):
rr = y+1
r = y+1
h = 0
while(rr<yy):
if(pre[rr] == 2):
h+=1
rr+=1
if(tt+h+1>maxi):
maxi = tt + h + 1
a=(y,yy)
q+=1
y = yy+1
yy = y
else:
yy+=1
if (q + 1 > maxi):
maxi = q+1
a = (g, gg)
g= gg+1
gg= g
else:
gg+=1
print(maxi)
print((a[0]+ti)%len(s)+1,(a[1]+ti)%len(s)+1)
else:
print(0)
print(1,1)
```
No
| 8,459 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version, n β€ 300 000.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.
To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.
We remind that bracket sequence s is called correct if:
* s is empty;
* s is equal to "(t)", where t is correct bracket sequence;
* s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not.
The cyclical shift of the string s of length n by k (0 β€ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".
Cyclical shifts i and j are considered different, if i β j.
Input
The first line contains an integer n (1 β€ n β€ 300 000), the length of the string.
The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".
Output
The first line should contain a single integer β the largest beauty of the string, which can be achieved by swapping some two characters.
The second line should contain integers l and r (1 β€ l, r β€ n) β the indices of two characters, which should be swapped in order to maximize the string's beauty.
In case there are several possible swaps, print any of them.
Examples
Input
10
()()())(()
Output
5
8 7
Input
12
)(()(()())()
Output
4
5 10
Input
6
)))(()
Output
0
1 1
Note
In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.
In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.
In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences.
Submitted Solution:
```
n = int(input().strip())
s= input().strip()
ss= 0
mina = 0
ti = 0
for k in range(len(s)):
if(s[k] == "("):
ss+=1
else:
ss-=1
if(ss<0):
ti = k+1
ss = 0
s=s[ti:]+s[:ti]
print(s)
ss= 0
for k in range(len(s)):
if(s[k] == "("):
ss+=1
else:
ss-=1
if(ss<0):
print(0)
print(1,1)
break
else:
if(ss == 0):
pre=[0 for k in range(len(s))]
for k in range(len(s)):
if (s[k] == "("):
ss += 1
else:
ss -= 1
pre[k] = ss
tt = 0
a =(1,1)
for k in range(0,len(s)):
if(pre[k] == 0):
tt+=1
maxi= tt
g =0
gg =0
while(gg<len(s)):
if(pre[gg] == 0):
if(gg != g+1):
yy = g+1
y = g+1
q = 0
while(yy<gg):
if(pre[yy] == 1):
if(yy !=y+1):
rr = y+1
r = y+1
h = 0
while(rr<yy):
if(pre[rr] == 2):
h+=1
rr+=1
if(tt+h+1>maxi):
maxi = tt + h + 1
a=(y,yy)
q+=1
y = yy+1
yy = y
else:
yy+=1
if (q + 1 > maxi):
maxi = q+1
a = (g, gg)
g= gg+1
gg= g
else:
gg+=1
print(maxi)
print((a[0]+ti)%len(s)+1,(a[1]+ti)%len(s)+1)
else:
print(0)
print(1,1)
```
No
| 8,460 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is a harder version of the problem. In this version, n β€ 300 000.
Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.
To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.
We remind that bracket sequence s is called correct if:
* s is empty;
* s is equal to "(t)", where t is correct bracket sequence;
* s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences.
For example, "(()())", "()" are correct, while ")(" and "())" are not.
The cyclical shift of the string s of length n by k (0 β€ k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".
Cyclical shifts i and j are considered different, if i β j.
Input
The first line contains an integer n (1 β€ n β€ 300 000), the length of the string.
The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".
Output
The first line should contain a single integer β the largest beauty of the string, which can be achieved by swapping some two characters.
The second line should contain integers l and r (1 β€ l, r β€ n) β the indices of two characters, which should be swapped in order to maximize the string's beauty.
In case there are several possible swaps, print any of them.
Examples
Input
10
()()())(()
Output
5
8 7
Input
12
)(()(()())()
Output
4
5 10
Input
6
)))(()
Output
0
1 1
Note
In the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.
In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.
In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences.
Submitted Solution:
```
n = int(input())
ddd = input()
d = [0]
for dd in ddd:
if dd == '(':
d.append(d[-1] + 1)
else:
d.append(d[-1] - 1)
if d[-1] != 0:
print("0\n1 1")
exit(0)
d.pop()
mn = min(d)
ind = d.index(mn)
d = d[ind:] + d[:ind]
d = [i - mn for i in d]
fi = -1
crfi = -1
li = -1
mx = 0
cr = 0
cnt0 = 0
for i in range(n):
dd = d[i]
if dd == 0:
cnt0 += 1
if dd == 2:
if cr == 0:
crfi = i
cr += 1
if cr > mx:
fi = crfi
li = i
mx = cr
elif dd < 2:
cr = 0
print('=========')
print(d)
print(cnt0)
print(fi, li)
print(mx)
print("=========")
# if fi == -1:
# print(cnt0)
# print(1, 1)
# else:
# print(cnt0 + mx)
# print(fi, li + 2)
if fi == -1:
ans1 = [cnt0, 0, 0]
else:
ans1 = [cnt0 + mx, fi-1, li]
fi = -1
crfi = -1
li = -1
mx = 0
cr = 0
for i in range(n):
dd = d[i]
if dd == 1:
if cr == 0:
crfi = i
cr += 1
if cr > mx:
fi = crfi
li = i
mx = cr
elif dd < 1:
cr = 0
ans2 = [mx, fi-1, li]
if ans1[0] > ans2[0]:
print(ans1[0])
print(((ans1[1] + ind)%n) + 1, ((ans1[2] + ind)%n) + 1)
else:
print(ans2[0])
print(((ans2[1] + ind)%n) + 1, ((ans2[2] + ind)%n) + 1)
```
No
| 8,461 |
Provide a correct Python 3 solution for this coding contest problem.
Balph is learning to play a game called Buma. In this game, he is given a row of colored balls. He has to choose the color of one new ball and the place to insert it (between two balls, or to the left of all the balls, or to the right of all the balls).
When the ball is inserted the following happens repeatedly: if some segment of balls of the same color became longer as a result of a previous action and its length became at least 3, then all the balls of this segment are eliminated.
Consider, for example, a row of balls 'AAABBBWWBB'. Suppose Balph chooses a ball of color 'W' and the place to insert it after the sixth ball, i. e. to the left of the two 'W's. After Balph inserts this ball, the balls of color 'W' are eliminated, since this segment was made longer and has length 3 now, so the row becomes 'AAABBBBB'. The balls of color 'B' are eliminated now, because the segment of balls of color 'B' became longer and has length 5 now. Thus, the row becomes 'AAA'. However, none of the balls are eliminated now, because there is no elongated segment.
Help Balph count the number of possible ways to choose a color of a new ball and a place to insert it that leads to the elimination of all the balls.
Input
The only line contains a non-empty string of uppercase English letters of length at most 3 β
10^5. Each letter represents a ball with the corresponding color.
Output
Output the number of ways to choose a color and a position of a new ball in order to eliminate all the balls.
Examples
Input
BBWWBB
Output
3
Input
BWWB
Output
0
Input
BBWBB
Output
0
Input
OOOWWW
Output
0
Input
WWWOOOOOOWWW
Output
7
"Correct Solution:
```
s=list(input())
i=0
l=len(s)-1
t=0
while i<=l :
a=s[i]
c=0
if s[i]!=s[l]:
print(0)
exit()
while i<=l and s[i]==a:
c+=1
i+=1
while i<=l and s[l]==a:
c+=1
l-=1
if c<=2 and i<l:
print(0)
exit()
if c>1:
print(c+1)
else:
print(0)
```
| 8,462 |
Provide a correct Python 3 solution for this coding contest problem.
Balph is learning to play a game called Buma. In this game, he is given a row of colored balls. He has to choose the color of one new ball and the place to insert it (between two balls, or to the left of all the balls, or to the right of all the balls).
When the ball is inserted the following happens repeatedly: if some segment of balls of the same color became longer as a result of a previous action and its length became at least 3, then all the balls of this segment are eliminated.
Consider, for example, a row of balls 'AAABBBWWBB'. Suppose Balph chooses a ball of color 'W' and the place to insert it after the sixth ball, i. e. to the left of the two 'W's. After Balph inserts this ball, the balls of color 'W' are eliminated, since this segment was made longer and has length 3 now, so the row becomes 'AAABBBBB'. The balls of color 'B' are eliminated now, because the segment of balls of color 'B' became longer and has length 5 now. Thus, the row becomes 'AAA'. However, none of the balls are eliminated now, because there is no elongated segment.
Help Balph count the number of possible ways to choose a color of a new ball and a place to insert it that leads to the elimination of all the balls.
Input
The only line contains a non-empty string of uppercase English letters of length at most 3 β
10^5. Each letter represents a ball with the corresponding color.
Output
Output the number of ways to choose a color and a position of a new ball in order to eliminate all the balls.
Examples
Input
BBWWBB
Output
3
Input
BWWB
Output
0
Input
BBWBB
Output
0
Input
OOOWWW
Output
0
Input
WWWOOOOOOWWW
Output
7
"Correct Solution:
```
from collections import defaultdict as dd
s=input()
l=[s[0]]
n=s[0]
d=dd(int)
d[s[0]]+=1
cou=1
li=[]
for i in range(1,len(s)):
d[s[i]]+=1
if(s[i]==n):
cou+=1
if(s[i]!=n):
l.append(s[i])
n=s[i]
li.append(cou)
cou=1
li.append(cou)
#print(l,d)
if(l==l[::-1]):
mid=len(l)//2
lol=0
for i in range(len(li)):
j=len(li)-i-1
if(i!=j and li[i]+li[j]<=2):
lol=1
break
if(i==j and li[i]<2):
lol=1
break
if(lol):
print(0)
else:
print(li[mid]+1)
else:
print(0)
```
| 8,463 |
Provide a correct Python 3 solution for this coding contest problem.
Balph is learning to play a game called Buma. In this game, he is given a row of colored balls. He has to choose the color of one new ball and the place to insert it (between two balls, or to the left of all the balls, or to the right of all the balls).
When the ball is inserted the following happens repeatedly: if some segment of balls of the same color became longer as a result of a previous action and its length became at least 3, then all the balls of this segment are eliminated.
Consider, for example, a row of balls 'AAABBBWWBB'. Suppose Balph chooses a ball of color 'W' and the place to insert it after the sixth ball, i. e. to the left of the two 'W's. After Balph inserts this ball, the balls of color 'W' are eliminated, since this segment was made longer and has length 3 now, so the row becomes 'AAABBBBB'. The balls of color 'B' are eliminated now, because the segment of balls of color 'B' became longer and has length 5 now. Thus, the row becomes 'AAA'. However, none of the balls are eliminated now, because there is no elongated segment.
Help Balph count the number of possible ways to choose a color of a new ball and a place to insert it that leads to the elimination of all the balls.
Input
The only line contains a non-empty string of uppercase English letters of length at most 3 β
10^5. Each letter represents a ball with the corresponding color.
Output
Output the number of ways to choose a color and a position of a new ball in order to eliminate all the balls.
Examples
Input
BBWWBB
Output
3
Input
BWWB
Output
0
Input
BBWBB
Output
0
Input
OOOWWW
Output
0
Input
WWWOOOOOOWWW
Output
7
"Correct Solution:
```
#!/usr/bin/env python3
from functools import lru_cache, reduce
from sys import setrecursionlimit
import math
ran = []
def success(i):
if ran[i][1]+1<3:
return False
l = i
r = i
while l>=0 and r<len(ran):
if ran[l][0] != ran[r][0] or ran[l][1] + ran[r][1] < 3:
return False
l -= 1
r += 1
if (l<0) ^ (r>=len(ran)):
return False
return True
if __name__ == "__main__":
for v in input().strip():
if len(ran)>0:
if ran[-1][0] == v:
ran[-1][1] += 1
else:
ran.append([v,1])
else:
ran.append([v,1])
res = 0
#for i in range(len(ran)):
if len(ran) % 2 != 0:
i = len(ran) // 2
if(success(i)):
res=ran[i][1]+1
print(res)
```
| 8,464 |
Provide a correct Python 3 solution for this coding contest problem.
Balph is learning to play a game called Buma. In this game, he is given a row of colored balls. He has to choose the color of one new ball and the place to insert it (between two balls, or to the left of all the balls, or to the right of all the balls).
When the ball is inserted the following happens repeatedly: if some segment of balls of the same color became longer as a result of a previous action and its length became at least 3, then all the balls of this segment are eliminated.
Consider, for example, a row of balls 'AAABBBWWBB'. Suppose Balph chooses a ball of color 'W' and the place to insert it after the sixth ball, i. e. to the left of the two 'W's. After Balph inserts this ball, the balls of color 'W' are eliminated, since this segment was made longer and has length 3 now, so the row becomes 'AAABBBBB'. The balls of color 'B' are eliminated now, because the segment of balls of color 'B' became longer and has length 5 now. Thus, the row becomes 'AAA'. However, none of the balls are eliminated now, because there is no elongated segment.
Help Balph count the number of possible ways to choose a color of a new ball and a place to insert it that leads to the elimination of all the balls.
Input
The only line contains a non-empty string of uppercase English letters of length at most 3 β
10^5. Each letter represents a ball with the corresponding color.
Output
Output the number of ways to choose a color and a position of a new ball in order to eliminate all the balls.
Examples
Input
BBWWBB
Output
3
Input
BWWB
Output
0
Input
BBWBB
Output
0
Input
OOOWWW
Output
0
Input
WWWOOOOOOWWW
Output
7
"Correct Solution:
```
s = list(input())
p0 = 0
p1 = len(s)-1
if(s[p0]!= s[p1]):
print(0)
else:
possible = 1
curr_len = 2
while p1 > p0:
if s[p0+1] == s[p0]:
curr_len += 1
p0+=1
elif s[p1-1] == s[p1]:
curr_len += 1
p1-=1
else:
if(curr_len<3 or s[p0+1]!=s[p1-1]):
possible = 0
break
else:
p0+=1
p1-=1
curr_len = 2
if not possible:
print(0)
else:
if p1==p0:
if(curr_len>2):
print(curr_len)
else:
print(0)
else:
print(0)
```
| 8,465 |
Provide a correct Python 3 solution for this coding contest problem.
Balph is learning to play a game called Buma. In this game, he is given a row of colored balls. He has to choose the color of one new ball and the place to insert it (between two balls, or to the left of all the balls, or to the right of all the balls).
When the ball is inserted the following happens repeatedly: if some segment of balls of the same color became longer as a result of a previous action and its length became at least 3, then all the balls of this segment are eliminated.
Consider, for example, a row of balls 'AAABBBWWBB'. Suppose Balph chooses a ball of color 'W' and the place to insert it after the sixth ball, i. e. to the left of the two 'W's. After Balph inserts this ball, the balls of color 'W' are eliminated, since this segment was made longer and has length 3 now, so the row becomes 'AAABBBBB'. The balls of color 'B' are eliminated now, because the segment of balls of color 'B' became longer and has length 5 now. Thus, the row becomes 'AAA'. However, none of the balls are eliminated now, because there is no elongated segment.
Help Balph count the number of possible ways to choose a color of a new ball and a place to insert it that leads to the elimination of all the balls.
Input
The only line contains a non-empty string of uppercase English letters of length at most 3 β
10^5. Each letter represents a ball with the corresponding color.
Output
Output the number of ways to choose a color and a position of a new ball in order to eliminate all the balls.
Examples
Input
BBWWBB
Output
3
Input
BWWB
Output
0
Input
BBWBB
Output
0
Input
OOOWWW
Output
0
Input
WWWOOOOOOWWW
Output
7
"Correct Solution:
```
from itertools import groupby
s = input()
lst = []
grp_i = []
for i, grp in groupby(s):
grp_i.append(i)
lst.append(list(grp))
if len(grp_i) % 2 == 0 or grp_i != grp_i[::-1]:
print(0)
else:
mid = grp_i[len(grp_i)//2]
nm = len(grp_i)//2
l = nm -1
r = nm + 1
ln = len(grp_i)
while l >= 0 and r < ln:
if len(lst[l]) + len(lst[r]) < 3:
print(0)
exit()
l -= 1
r += 1
if len(lst[len(grp_i)//2]) < 2:
print(0)
else:
ans = len(lst[len(grp_i)//2])+1
print(ans)
```
| 8,466 |
Provide a correct Python 3 solution for this coding contest problem.
Balph is learning to play a game called Buma. In this game, he is given a row of colored balls. He has to choose the color of one new ball and the place to insert it (between two balls, or to the left of all the balls, or to the right of all the balls).
When the ball is inserted the following happens repeatedly: if some segment of balls of the same color became longer as a result of a previous action and its length became at least 3, then all the balls of this segment are eliminated.
Consider, for example, a row of balls 'AAABBBWWBB'. Suppose Balph chooses a ball of color 'W' and the place to insert it after the sixth ball, i. e. to the left of the two 'W's. After Balph inserts this ball, the balls of color 'W' are eliminated, since this segment was made longer and has length 3 now, so the row becomes 'AAABBBBB'. The balls of color 'B' are eliminated now, because the segment of balls of color 'B' became longer and has length 5 now. Thus, the row becomes 'AAA'. However, none of the balls are eliminated now, because there is no elongated segment.
Help Balph count the number of possible ways to choose a color of a new ball and a place to insert it that leads to the elimination of all the balls.
Input
The only line contains a non-empty string of uppercase English letters of length at most 3 β
10^5. Each letter represents a ball with the corresponding color.
Output
Output the number of ways to choose a color and a position of a new ball in order to eliminate all the balls.
Examples
Input
BBWWBB
Output
3
Input
BWWB
Output
0
Input
BBWBB
Output
0
Input
OOOWWW
Output
0
Input
WWWOOOOOOWWW
Output
7
"Correct Solution:
```
S = input().strip()
P = []
j = 0
for i in range(1, len(S)+1):
if i == len(S) or S[i] != S[j]:
P.append((S[j], i-j))
j = i
l = 0
r = len(P)-1
while l < r:
if P[l][0] != P[r][0] or P[l][1] + P[r][1] < 3:
break
l += 1
r -= 1
if l == r and P[l][1] >= 2:
print(P[l][1]+1)
else:
print(0)
```
| 8,467 |
Provide a correct Python 3 solution for this coding contest problem.
Balph is learning to play a game called Buma. In this game, he is given a row of colored balls. He has to choose the color of one new ball and the place to insert it (between two balls, or to the left of all the balls, or to the right of all the balls).
When the ball is inserted the following happens repeatedly: if some segment of balls of the same color became longer as a result of a previous action and its length became at least 3, then all the balls of this segment are eliminated.
Consider, for example, a row of balls 'AAABBBWWBB'. Suppose Balph chooses a ball of color 'W' and the place to insert it after the sixth ball, i. e. to the left of the two 'W's. After Balph inserts this ball, the balls of color 'W' are eliminated, since this segment was made longer and has length 3 now, so the row becomes 'AAABBBBB'. The balls of color 'B' are eliminated now, because the segment of balls of color 'B' became longer and has length 5 now. Thus, the row becomes 'AAA'. However, none of the balls are eliminated now, because there is no elongated segment.
Help Balph count the number of possible ways to choose a color of a new ball and a place to insert it that leads to the elimination of all the balls.
Input
The only line contains a non-empty string of uppercase English letters of length at most 3 β
10^5. Each letter represents a ball with the corresponding color.
Output
Output the number of ways to choose a color and a position of a new ball in order to eliminate all the balls.
Examples
Input
BBWWBB
Output
3
Input
BWWB
Output
0
Input
BBWBB
Output
0
Input
OOOWWW
Output
0
Input
WWWOOOOOOWWW
Output
7
"Correct Solution:
```
def main():
freq = []
symb = []
s = input()
symb.append(s[0]);
freq.append(1);
for ch in s[1:]:
if ch == symb[-1]:
freq[-1] += 1
continue
symb.append(ch)
freq.append(1)
if (len(freq) % 2 == 0) or (freq[len(freq) // 2] == 1):
print(0)
return
for i in range(len(freq) // 2):
if (symb[i] != symb[-i-1]) or (freq[i] + freq[-i-1] < 3):
print(0)
return
print(freq[len(freq) // 2] + 1)
if __name__ == '__main__':
main()
```
| 8,468 |
Provide a correct Python 3 solution for this coding contest problem.
Balph is learning to play a game called Buma. In this game, he is given a row of colored balls. He has to choose the color of one new ball and the place to insert it (between two balls, or to the left of all the balls, or to the right of all the balls).
When the ball is inserted the following happens repeatedly: if some segment of balls of the same color became longer as a result of a previous action and its length became at least 3, then all the balls of this segment are eliminated.
Consider, for example, a row of balls 'AAABBBWWBB'. Suppose Balph chooses a ball of color 'W' and the place to insert it after the sixth ball, i. e. to the left of the two 'W's. After Balph inserts this ball, the balls of color 'W' are eliminated, since this segment was made longer and has length 3 now, so the row becomes 'AAABBBBB'. The balls of color 'B' are eliminated now, because the segment of balls of color 'B' became longer and has length 5 now. Thus, the row becomes 'AAA'. However, none of the balls are eliminated now, because there is no elongated segment.
Help Balph count the number of possible ways to choose a color of a new ball and a place to insert it that leads to the elimination of all the balls.
Input
The only line contains a non-empty string of uppercase English letters of length at most 3 β
10^5. Each letter represents a ball with the corresponding color.
Output
Output the number of ways to choose a color and a position of a new ball in order to eliminate all the balls.
Examples
Input
BBWWBB
Output
3
Input
BWWB
Output
0
Input
BBWBB
Output
0
Input
OOOWWW
Output
0
Input
WWWOOOOOOWWW
Output
7
"Correct Solution:
```
#!/usr/bin/env python3
import sys
def main_proc():
res = 0
data = sys.stdin.buffer.read()
data = data.strip()
s = 0; e = len(data) - 1
while True:
cnt = 0
if data[s] != data[e]: break
t = s
while data[s] == data[t] and t != e: t += 1; cnt += 1
if t == e:
res = cnt + 2 if cnt >= 1 else res
break
else:
s = t
t = e
while data[t] == data[e]: cnt += 1; t -= 1
if cnt < 3: break
e = t
print(res)
if __name__ == '__main__':
main_proc()
```
| 8,469 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Balph is learning to play a game called Buma. In this game, he is given a row of colored balls. He has to choose the color of one new ball and the place to insert it (between two balls, or to the left of all the balls, or to the right of all the balls).
When the ball is inserted the following happens repeatedly: if some segment of balls of the same color became longer as a result of a previous action and its length became at least 3, then all the balls of this segment are eliminated.
Consider, for example, a row of balls 'AAABBBWWBB'. Suppose Balph chooses a ball of color 'W' and the place to insert it after the sixth ball, i. e. to the left of the two 'W's. After Balph inserts this ball, the balls of color 'W' are eliminated, since this segment was made longer and has length 3 now, so the row becomes 'AAABBBBB'. The balls of color 'B' are eliminated now, because the segment of balls of color 'B' became longer and has length 5 now. Thus, the row becomes 'AAA'. However, none of the balls are eliminated now, because there is no elongated segment.
Help Balph count the number of possible ways to choose a color of a new ball and a place to insert it that leads to the elimination of all the balls.
Input
The only line contains a non-empty string of uppercase English letters of length at most 3 β
10^5. Each letter represents a ball with the corresponding color.
Output
Output the number of ways to choose a color and a position of a new ball in order to eliminate all the balls.
Examples
Input
BBWWBB
Output
3
Input
BWWB
Output
0
Input
BBWBB
Output
0
Input
OOOWWW
Output
0
Input
WWWOOOOOOWWW
Output
7
Submitted Solution:
```
def main():
s=input()
# first check if it's possible...
n=len(s)
l=0
r=n-1
ok=True
while True:
if s[l]!=s[r]:
ok=False
break
c=s[l]
lCnt=0
rCnt=0
while s[l]==c and l<r:
l+=1
lCnt+=1
while s[r]==c and r>l:
r-=1
rCnt+=1
if l==r: # possible
break
if lCnt+rCnt<3:
ok=False
break
if ok:
c=s[l]
while l-1>=0 and s[l-1]==c:
l-=1
while r+1<n and s[r+1]==c:
r+=1
if l==r: # only 1 ball... cannot
print(0)
else:
print(r-l+2)
else:
print(0)
return
import sys
# input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultVal,dimensionArr): # eg. makeArr(0,[n,m])
dv=defaultVal;da=dimensionArr
if len(da)==1:return [dv for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(x,y):
print('? {} {}'.format(x,y))
sys.stdout.flush()
return int(input())
def answerInteractive(ans):
print('! {}'.format(ans))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
for _abc in range(1):
main()
```
Yes
| 8,470 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Balph is learning to play a game called Buma. In this game, he is given a row of colored balls. He has to choose the color of one new ball and the place to insert it (between two balls, or to the left of all the balls, or to the right of all the balls).
When the ball is inserted the following happens repeatedly: if some segment of balls of the same color became longer as a result of a previous action and its length became at least 3, then all the balls of this segment are eliminated.
Consider, for example, a row of balls 'AAABBBWWBB'. Suppose Balph chooses a ball of color 'W' and the place to insert it after the sixth ball, i. e. to the left of the two 'W's. After Balph inserts this ball, the balls of color 'W' are eliminated, since this segment was made longer and has length 3 now, so the row becomes 'AAABBBBB'. The balls of color 'B' are eliminated now, because the segment of balls of color 'B' became longer and has length 5 now. Thus, the row becomes 'AAA'. However, none of the balls are eliminated now, because there is no elongated segment.
Help Balph count the number of possible ways to choose a color of a new ball and a place to insert it that leads to the elimination of all the balls.
Input
The only line contains a non-empty string of uppercase English letters of length at most 3 β
10^5. Each letter represents a ball with the corresponding color.
Output
Output the number of ways to choose a color and a position of a new ball in order to eliminate all the balls.
Examples
Input
BBWWBB
Output
3
Input
BWWB
Output
0
Input
BBWBB
Output
0
Input
OOOWWW
Output
0
Input
WWWOOOOOOWWW
Output
7
Submitted Solution:
```
s = input()
j = len(s)-1
i = 0
while i<=j:
c = 0
p = s[i]
if p!=s[j]:
exit(print(0))
while i<=j and s[i]==p:
i+=1
c+=1
while i<=j and s[j]==p:
j-=1
c+=1
if c<=2 and i<j:
exit(print(0))
if c>1:
print(c+1)
else:
print(0)
```
Yes
| 8,471 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Balph is learning to play a game called Buma. In this game, he is given a row of colored balls. He has to choose the color of one new ball and the place to insert it (between two balls, or to the left of all the balls, or to the right of all the balls).
When the ball is inserted the following happens repeatedly: if some segment of balls of the same color became longer as a result of a previous action and its length became at least 3, then all the balls of this segment are eliminated.
Consider, for example, a row of balls 'AAABBBWWBB'. Suppose Balph chooses a ball of color 'W' and the place to insert it after the sixth ball, i. e. to the left of the two 'W's. After Balph inserts this ball, the balls of color 'W' are eliminated, since this segment was made longer and has length 3 now, so the row becomes 'AAABBBBB'. The balls of color 'B' are eliminated now, because the segment of balls of color 'B' became longer and has length 5 now. Thus, the row becomes 'AAA'. However, none of the balls are eliminated now, because there is no elongated segment.
Help Balph count the number of possible ways to choose a color of a new ball and a place to insert it that leads to the elimination of all the balls.
Input
The only line contains a non-empty string of uppercase English letters of length at most 3 β
10^5. Each letter represents a ball with the corresponding color.
Output
Output the number of ways to choose a color and a position of a new ball in order to eliminate all the balls.
Examples
Input
BBWWBB
Output
3
Input
BWWB
Output
0
Input
BBWBB
Output
0
Input
OOOWWW
Output
0
Input
WWWOOOOOOWWW
Output
7
Submitted Solution:
```
s = input()
lista = []
aux = s[0]
cont = 0
for i in s:
if i == aux:
cont += 1
else:
lista.append([aux, cont])
cont = 1
aux = i
lista.append([aux, cont])
if len(lista)%2 == 0:
print(0)
else:
flag = False
while len(lista) > 1:
a = lista.pop(0)
b = lista.pop(len(lista) - 1)
if a[0] != b[0]:
flag = True
break
else:
if a[1] + b[1] < 3:
flag = True
break
if flag:
print(0)
else:
if lista[0][1] == 1:
print(0)
else:
print(lista[0][1] + 1)
```
Yes
| 8,472 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Balph is learning to play a game called Buma. In this game, he is given a row of colored balls. He has to choose the color of one new ball and the place to insert it (between two balls, or to the left of all the balls, or to the right of all the balls).
When the ball is inserted the following happens repeatedly: if some segment of balls of the same color became longer as a result of a previous action and its length became at least 3, then all the balls of this segment are eliminated.
Consider, for example, a row of balls 'AAABBBWWBB'. Suppose Balph chooses a ball of color 'W' and the place to insert it after the sixth ball, i. e. to the left of the two 'W's. After Balph inserts this ball, the balls of color 'W' are eliminated, since this segment was made longer and has length 3 now, so the row becomes 'AAABBBBB'. The balls of color 'B' are eliminated now, because the segment of balls of color 'B' became longer and has length 5 now. Thus, the row becomes 'AAA'. However, none of the balls are eliminated now, because there is no elongated segment.
Help Balph count the number of possible ways to choose a color of a new ball and a place to insert it that leads to the elimination of all the balls.
Input
The only line contains a non-empty string of uppercase English letters of length at most 3 β
10^5. Each letter represents a ball with the corresponding color.
Output
Output the number of ways to choose a color and a position of a new ball in order to eliminate all the balls.
Examples
Input
BBWWBB
Output
3
Input
BWWB
Output
0
Input
BBWBB
Output
0
Input
OOOWWW
Output
0
Input
WWWOOOOOOWWW
Output
7
Submitted Solution:
```
from collections import deque
from collections import OrderedDict
import math
import sys
import os
from io import BytesIO
import threading
import bisect
import operator
import heapq
#sys.stdin = open("F:\PY\\test.txt", "r")
input = lambda: sys.stdin.readline().rstrip("\r\n")
s = input()
l = len(s)
dp = [s[0]]
dpC = [1]
idx = 0
for i in range(1,l):
if s[i]==s[i-1]:
dpC[idx]+=1
else:
idx+=1
dp.append(s[i])
dpC.append(1)
if len(dp)%2==0 or dpC[len(dpC)//2]<2:
print(0)
else:
for i in range(0,len(dp)//2):
#print(i, len(dp)-1-i)
if dpC[i]+dpC[len(dp)-1-i]<3 or dp[i]!=dp[len(dp)-1-i]:
print(0)
break
else:
print(dpC[len(dpC)//2]+1)
```
Yes
| 8,473 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Balph is learning to play a game called Buma. In this game, he is given a row of colored balls. He has to choose the color of one new ball and the place to insert it (between two balls, or to the left of all the balls, or to the right of all the balls).
When the ball is inserted the following happens repeatedly: if some segment of balls of the same color became longer as a result of a previous action and its length became at least 3, then all the balls of this segment are eliminated.
Consider, for example, a row of balls 'AAABBBWWBB'. Suppose Balph chooses a ball of color 'W' and the place to insert it after the sixth ball, i. e. to the left of the two 'W's. After Balph inserts this ball, the balls of color 'W' are eliminated, since this segment was made longer and has length 3 now, so the row becomes 'AAABBBBB'. The balls of color 'B' are eliminated now, because the segment of balls of color 'B' became longer and has length 5 now. Thus, the row becomes 'AAA'. However, none of the balls are eliminated now, because there is no elongated segment.
Help Balph count the number of possible ways to choose a color of a new ball and a place to insert it that leads to the elimination of all the balls.
Input
The only line contains a non-empty string of uppercase English letters of length at most 3 β
10^5. Each letter represents a ball with the corresponding color.
Output
Output the number of ways to choose a color and a position of a new ball in order to eliminate all the balls.
Examples
Input
BBWWBB
Output
3
Input
BWWB
Output
0
Input
BBWBB
Output
0
Input
OOOWWW
Output
0
Input
WWWOOOOOOWWW
Output
7
Submitted Solution:
```
s = input()
n = len(s)
a = ''
b = []
t = 1
for i in range(n-1):
if s[i] != s[i+1]:
a += s[i]
b.append(t)
t = 1
else:
t += 1
a += s[n-1]
b.append(t)
k = len(a)
if s == 'BWWB' or s == 'BBWBB' or s == 'OOOWWW' or 'ABCDEF':
print(0)
else:
if k % 2 == 0:
print(1)
else:
if k > 1:
for i in range((k - 1) // 2):
if a[i] != a[k - 1 - i] or b[i] + b[k - 1 - i] < 3:
print(2)
break
elif i == ((k - 1) // 2 - 1) and b[(k + 1) // 2 - 1] >= 2:
print(b[(k + 1) // 2 - 1] + 1)
break
else:
print(3)
break
elif b[0] >= 2:
print(b[0] + 1)
else:
print(4)
```
No
| 8,474 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Balph is learning to play a game called Buma. In this game, he is given a row of colored balls. He has to choose the color of one new ball and the place to insert it (between two balls, or to the left of all the balls, or to the right of all the balls).
When the ball is inserted the following happens repeatedly: if some segment of balls of the same color became longer as a result of a previous action and its length became at least 3, then all the balls of this segment are eliminated.
Consider, for example, a row of balls 'AAABBBWWBB'. Suppose Balph chooses a ball of color 'W' and the place to insert it after the sixth ball, i. e. to the left of the two 'W's. After Balph inserts this ball, the balls of color 'W' are eliminated, since this segment was made longer and has length 3 now, so the row becomes 'AAABBBBB'. The balls of color 'B' are eliminated now, because the segment of balls of color 'B' became longer and has length 5 now. Thus, the row becomes 'AAA'. However, none of the balls are eliminated now, because there is no elongated segment.
Help Balph count the number of possible ways to choose a color of a new ball and a place to insert it that leads to the elimination of all the balls.
Input
The only line contains a non-empty string of uppercase English letters of length at most 3 β
10^5. Each letter represents a ball with the corresponding color.
Output
Output the number of ways to choose a color and a position of a new ball in order to eliminate all the balls.
Examples
Input
BBWWBB
Output
3
Input
BWWB
Output
0
Input
BBWBB
Output
0
Input
OOOWWW
Output
0
Input
WWWOOOOOOWWW
Output
7
Submitted Solution:
```
def build_ball_dictionary(ball_arrangement):
"""
Helper function for 'compute_ways_2_eliminate_all_balls' that builds a
dictionary that maps the starting position of a ball to a list that
contains the color of the ball as well as 1 + the number of balls of the
same color that follow it.
This function only needs to be called once.
Input:
ball_arrangement : <str>
# Contains arrangement of original row of balls
# Output :
ball_dictionary : < <int> : <str, int> >
Dictionary that maps the starting position of a ball to a list that
contains the color of the ball as well as 1 + the number of balls of the
same color that follow consecutively.
num_unique_colors : int
Represents the number of unique colors found in the initial set of balls
"""
# Initialize dictionary object
ball_dictionary = {}
# Initialize list object
unique_ball_colors_list = []
# Initialize counter that points to a location in the string representing
# the initial set of balls
index = 0
# Get number of balls at game's outset
n_balls = len(ball_arrangement)
while index < n_balls:
# Get the color of the ball at location 'index' in the
# ball_arrangement variable
current_ball_color = ball_arrangement[index]
# Reset length of current ball segment that contains all balls of
# the same color
current_segment_length = 1
# If ball color has not yet been encountered, add to list tracking
# unique ball colors
if current_ball_color not in unique_ball_colors_list:
unique_ball_colors_list.append(current_ball_color)
# Continue extending search towards the end of the original string
# until a new ball color is found. However, if we are at the end of
# the string, then there is no need to extend search (unless we want
# an 'index out of bounds' exception error)
while index < n_balls and index+current_segment_length < n_balls \
and ball_arrangement[index + current_segment_length] == \
current_ball_color:
current_segment_length += 1
ball_dictionary[index] = [current_ball_color, current_segment_length]
index += current_segment_length
# Get number of unique colors in row of balls
if "X"*int(511) in ball_arrangement:
print(unique_ball_colors_list)
num_unique_colors = len(unique_ball_colors_list)
return ball_dictionary, num_unique_colors
def compute_ways_2_eliminate_all_balls(ball_arrangement):
"""
Balph is learning to play a game called Buma. In this game, he is given
a row of colored balls. He has to choose the color of one new ball as
well as the place to insert it (between two balls, or to the left
of all the balls, or to the right of all the balls).
When the ball is inserted the following happens repeatedly: if some
segment of balls of the same color became longer as a result of a
previous action, and the length of this segment becomes at least 3,
then all the balls of this segment are eliminated.
Consider, for example, a row of balls 'AAABBBWWBB'. Suppose Balph
chooses a ball of color 'W' and the places it after the
sixth ball, i. e. to the left of the two 'W's. After Balph inserts
this ball, the balls of color 'W' are eliminated, since this segment
was made longer and now has length 3. The row then becomes 'AAABBBBB'.
The balls of color 'B' are now eliminated, because the segment of balls
of color 'B' became longer, and have length 5 now. Thus, the row becomes
'AAA'. However, balls of color 'A' remain, because they have not become
elongated (i.e. the number of consecutive A's did not change).
Help Balph count the number of possible ways to choose a color of a
new ball, and a place to insert it such that the insertion leads to the
elimination of all balls.
Input :
colored_balls_arrangement : <str>
Contains a non-empty string of uppercase English letters of length at
most 3*10^5. Each letter represents a ball with the corresponding color.
Output :
Output the number of ways to choose a color and a position of a new ball
in order to eliminate all the balls.
"""
# Condition 1:
# In order for any segment of colored balls to be eliminated, a ball of
# the same color must be placed next to a segment that contains at least
# two balls of that color. Ball can be inserted anywhere next to that
# segment.
# Create a dictionary from 'ball_arrangement'
ball_segments_map, n_unique_colors = build_ball_dictionary(ball_arrangement)
# Since the keys of 'ball_dict' refer to starting positions of a distinct
# ball segment, we can use a list of sorted keys to look through the
# collection of balls in an ordered manner.
sorted_ball_segments_by_pos = sorted(ball_segments_map.keys())
# There are several situations where it is quick and easy to determine
# that a total elimination of the original row of balls is not possible.
# This is the case when:
# 1) There are an even number of distinct ball segments in the original
# row of balls. Can be determined by the number of key entries in the
# ball segments map/dictionary
# 2) The total number of balls is fewer than 1 less than three times
# the number of uniquely colored ball colors
# 3) The ball segments at each end of the original row of balls do not
# share the same color
# 4) The ball segments at each end share the same color, but their sum
# does not exceed 2
# Condition 1 for no solution
if len(sorted_ball_segments_by_pos) // 2 == 0:
print(0)
return 0
# Condition 2 for no solution
if len(ball_arrangement) < 3 * n_unique_colors - 1:
print(0)
return 0
first_ball_segment_pos = sorted_ball_segments_by_pos[0]
last_ball_segment_pos = sorted_ball_segments_by_pos[-1]
first_ball_segment_color = ball_segments_map[first_ball_segment_pos][0]
last_ball_segment_color = ball_segments_map[last_ball_segment_pos][0]
# Condition 3 for no solution
if first_ball_segment_color != last_ball_segment_color:
print(0)
return 0
first_ball_segment_length = ball_segments_map[first_ball_segment_pos][1]
last_ball_segment_length = ball_segments_map[last_ball_segment_pos][1]
# Condition 4 for no solution
if first_ball_segment_length + last_ball_segment_length < 3:
print(0)
return 0
# The key to determining if all balls can be eliminated is by starting from
# the ball segment that has an equal number of ball segments on either
# side of it. If there is no complete collapse of balls by inserting a ball
# into the middle segment, then no solution exists.
# Find middle index of the sorted key list
middle_ball_segment_index = len(sorted_ball_segments_by_pos)//2
# Get the starting position of the current ball segment<key> from the
# list of sorted ball segment positions<list of keys> using the
# current ball segment index<int>
middle_ball_segment_pos = \
sorted_ball_segments_by_pos[middle_ball_segment_index]
# Determine if the length of the ball segment (i.e. the 2nd element of
# the list) associated with the middle ball segment is greater than
# or equal to 2.
min_initial_length = 2
if ball_segments_map[middle_ball_segment_pos][1] >= min_initial_length:
# If length requirement is satisfied, determine whether the ball
# segments equidistant from the the middle ball segment share the
# same color
count_left_segments = 1
count_right_segments = 1
# Continue process outwards until either:
# 1) one end of the ball segment dictionary has been reached or
# 2) surrounding ball segments do not share the same ball color or
# 3) the sum of the outer two surrounding ball segments is not of
# sufficient length.
# Ensure that the bounds of the sorted key list are not exceeded
while middle_ball_segment_index - count_left_segments >= 0:
left_segment_index = middle_ball_segment_index - \
count_left_segments
right_segment_index = middle_ball_segment_index + \
count_right_segments
left_ball_segment_pos = \
sorted_ball_segments_by_pos[left_segment_index]
right_ball_segment_pos =\
sorted_ball_segments_by_pos[right_segment_index]
if ball_segments_map[left_ball_segment_pos][0] == \
ball_segments_map[right_ball_segment_pos][0]:
# If the two ball segments equidistant from the middle
# ball segment are of the same color, check if the sum of
# the lengths of those two ball segments is greater than 3.
left_segment_length = ball_segments_map[
left_ball_segment_pos][1]
right_segment_length = ball_segments_map[
right_ball_segment_pos][1]
# If ball segments equidistant from middle ball segment
# satisfy all constraints, continue search on the next two
# ball segments outwards from the middle.
if left_segment_length + right_segment_index >= 3:
count_left_segments += 1
count_right_segments += 1
# If the ball segments equidistant from the middle ball
# segment share the same color but, when joined, do not
# become elongated enough to exceed a length of three,
# end search, print zero, and return no solution.
else:
print(0)
return 0
# If ball segments equidistant from middle ball segment do not
# share the same color, end search, print zero, and return no
# solution
else:
print(0)
return 0
# if end of while loop is reached, then all balls have been
# successfully eliminated. Number of solutions is just the length of
# the middle ball segment + 1
num_solutions = ball_segments_map[middle_ball_segment_pos][1]+1
print(num_solutions)
# if middle ball segment does not have at least two balls of the same
# color, then end search, print 0, and return no solution
else:
print(0)
return 0
if __name__ == "__main__":
new_ball_arrangement = input()
compute_ways_2_eliminate_all_balls(new_ball_arrangement)
# Examples
# inputCopy
# BBWWBB
# outputCopy
# 3
# inputCopy
# BWWB
# outputCopy
# 0
# inputCopy
# BBWBB
# outputCopy
# 0
# inputCopy
# OOOWWW
# outputCopy
# 0
# inputCopy
# WWWOOOOOOWWW
# outputCopy
# 7
```
No
| 8,475 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Balph is learning to play a game called Buma. In this game, he is given a row of colored balls. He has to choose the color of one new ball and the place to insert it (between two balls, or to the left of all the balls, or to the right of all the balls).
When the ball is inserted the following happens repeatedly: if some segment of balls of the same color became longer as a result of a previous action and its length became at least 3, then all the balls of this segment are eliminated.
Consider, for example, a row of balls 'AAABBBWWBB'. Suppose Balph chooses a ball of color 'W' and the place to insert it after the sixth ball, i. e. to the left of the two 'W's. After Balph inserts this ball, the balls of color 'W' are eliminated, since this segment was made longer and has length 3 now, so the row becomes 'AAABBBBB'. The balls of color 'B' are eliminated now, because the segment of balls of color 'B' became longer and has length 5 now. Thus, the row becomes 'AAA'. However, none of the balls are eliminated now, because there is no elongated segment.
Help Balph count the number of possible ways to choose a color of a new ball and a place to insert it that leads to the elimination of all the balls.
Input
The only line contains a non-empty string of uppercase English letters of length at most 3 β
10^5. Each letter represents a ball with the corresponding color.
Output
Output the number of ways to choose a color and a position of a new ball in order to eliminate all the balls.
Examples
Input
BBWWBB
Output
3
Input
BWWB
Output
0
Input
BBWBB
Output
0
Input
OOOWWW
Output
0
Input
WWWOOOOOOWWW
Output
7
Submitted Solution:
```
from collections import defaultdict as dd
s=input()
l=[s[0]]
n=s[0]
d=dd(int)
d[s[0]]+=1
cou=1
for i in range(1,len(s)):
d[s[i]]+=1
if(s[i]!=n):
l.append(s[i])
n=s[i]
if(l==l[::-1]):
mid=len(l)//2
lol=0
for i in d:
if(d[i]<=2 and i!=l[mid]):
lol=1
if(lol):
print(0)
else:
print(d[l[mid]]+1)
else:
print(0)
```
No
| 8,476 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Balph is learning to play a game called Buma. In this game, he is given a row of colored balls. He has to choose the color of one new ball and the place to insert it (between two balls, or to the left of all the balls, or to the right of all the balls).
When the ball is inserted the following happens repeatedly: if some segment of balls of the same color became longer as a result of a previous action and its length became at least 3, then all the balls of this segment are eliminated.
Consider, for example, a row of balls 'AAABBBWWBB'. Suppose Balph chooses a ball of color 'W' and the place to insert it after the sixth ball, i. e. to the left of the two 'W's. After Balph inserts this ball, the balls of color 'W' are eliminated, since this segment was made longer and has length 3 now, so the row becomes 'AAABBBBB'. The balls of color 'B' are eliminated now, because the segment of balls of color 'B' became longer and has length 5 now. Thus, the row becomes 'AAA'. However, none of the balls are eliminated now, because there is no elongated segment.
Help Balph count the number of possible ways to choose a color of a new ball and a place to insert it that leads to the elimination of all the balls.
Input
The only line contains a non-empty string of uppercase English letters of length at most 3 β
10^5. Each letter represents a ball with the corresponding color.
Output
Output the number of ways to choose a color and a position of a new ball in order to eliminate all the balls.
Examples
Input
BBWWBB
Output
3
Input
BWWB
Output
0
Input
BBWBB
Output
0
Input
OOOWWW
Output
0
Input
WWWOOOOOOWWW
Output
7
Submitted Solution:
```
from collections import defaultdict as dd
s=input()
l=[s[0]]
n=s[0]
d=dd(int)
d[s[0]]+=1
cou=1
li=[]
for i in range(1,len(s)):
d[s[i]]+=1
if(s[i]==n):
cou+=1
if(s[i]!=n):
l.append(s[i])
n=s[i]
li.append(cou)
cou=1
li.append(cou)
#print(l,d)
if(l==l[::-1]):
mid=len(l)//2
lol=0
for i in d:
if(d[i]<=2 and i!=l[mid]) or (d[i]<2 and i==l[mid]):
lol=1
if(lol):
print(0)
else:
print(li[mid]+1)
else:
print(0)
```
No
| 8,477 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.
You have to choose two arrays a_i and a_j (1 β€ i, j β€ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k β [1, m] b_k = max(a_{i, k}, a_{j, k}).
Your goal is to choose i and j so that the value of min _{k = 1}^{m} b_k is maximum possible.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^5, 1 β€ m β€ 8) β the number of arrays and the number of elements in each array, respectively.
Then n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 β€ a_{x, y} β€ 10^9).
Output
Print two integers i and j (1 β€ i, j β€ n, it is possible that i = j) β the indices of the two arrays you have to choose so that the value of min _{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.
Example
Input
6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
Output
1 5
Tags: binary search, bitmasks, dp
Correct Solution:
```
from collections import defaultdict
from sys import stdin
input = stdin.readline
def check(mid, m):
d = defaultdict(int)
for idx, i in enumerate(a):
string = ''
for j in i:
if j >= mid:
string+='1'
else:
string+='0'
d[int(string, 2)] = idx
for i in d.keys():
for j in d.keys():
if i|j == 2**m - 1:
return [d[i], d[j]]
return []
def binarySearch(lo, hi, m):
ans = []
while lo < hi:
mid = lo + (hi-lo+1)//2
x = check(mid, m)
if x:
lo = mid
ans = [x[0]+1, x[1]+1]
else:
hi = mid-1
return ans
n, m = map(int, input().split())
a = []
for i in range(n):
a.append(list(map(int, input().split())))
print(*binarySearch(-1, 10**9+1, m))
```
| 8,478 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.
You have to choose two arrays a_i and a_j (1 β€ i, j β€ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k β [1, m] b_k = max(a_{i, k}, a_{j, k}).
Your goal is to choose i and j so that the value of min _{k = 1}^{m} b_k is maximum possible.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^5, 1 β€ m β€ 8) β the number of arrays and the number of elements in each array, respectively.
Then n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 β€ a_{x, y} β€ 10^9).
Output
Print two integers i and j (1 β€ i, j β€ n, it is possible that i = j) β the indices of the two arrays you have to choose so that the value of min _{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.
Example
Input
6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
Output
1 5
Tags: binary search, bitmasks, dp
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def check(mid,arr,m,n):
ls = [[] for _ in range(1<<m)]
for i in range(n):
ans = 0
for j in range(m):
if arr[i][j] >= mid:
ans += 1<<j
ls[ans].append(i+1)
for i in range(len(ls)):
for j in range(len(ls)):
if len(ls[i]) and len(ls[j]) and i|j == (1<<m)-1:
return ls[i][0],ls[j][0]
return 0
def main():
n,m = map(int,input().split())
arr = [list(map(int,input().split())) for _ in range(n)]
hi,lo,ind1 = 10**9,0,(1,1)
while hi >= lo:
mid = (hi+lo)//2
ind = check(mid,arr,m,n)
if ind:
ind1 = ind
lo = mid+1
else:
hi = mid-1
print(*ind1)
#Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == '__main__':
main()
```
| 8,479 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.
You have to choose two arrays a_i and a_j (1 β€ i, j β€ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k β [1, m] b_k = max(a_{i, k}, a_{j, k}).
Your goal is to choose i and j so that the value of min _{k = 1}^{m} b_k is maximum possible.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^5, 1 β€ m β€ 8) β the number of arrays and the number of elements in each array, respectively.
Then n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 β€ a_{x, y} β€ 10^9).
Output
Print two integers i and j (1 β€ i, j β€ n, it is possible that i = j) β the indices of the two arrays you have to choose so that the value of min _{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.
Example
Input
6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
Output
1 5
Tags: binary search, bitmasks, dp
Correct Solution:
```
MAX=10**9 #O((n*m+(2**m)**2)*log(MAX))
def main():
n,m=readIntArr()
arrs=[]
for _ in range(n):
arrs.append(readIntArr())
def checkPossible(minB):
binRepresentations=set()
for arr in arrs:
binRepresentations.add(convertToBinary(arr,minB))
binList=list(binRepresentations)
ii=jj=-1
n=len(binList)
for i in range(n):
for j in range(i,n):
if binList[i]|binList[j]==(1<<m)-1: #ok
ii=binList[i]
jj=binList[j]
if ii!=-1: #ok
ansi=ansj=-1
for i in range(len(arrs)):
b=convertToBinary(arrs[i],minB)
if b==ii:
ansi=i
if b==jj:
ansj=i
# print('ii:{} jj:{}'.format(ii,jj))
# print('ok minB:{} ansi:{} ansj:{}'.format(minB,ansi,ansj))
return (ansi,ansj)
else:
return None
def convertToBinary(arr,minB):
b=0
for i in range(m):
if arr[i]>=minB:
b|=(1<<i)
return b
minB=-1
i=j=-1
b=MAX
while b>0:
temp=checkPossible(minB+b)
if temp==None: #cannot
b//=2
else: #can
minB+=b
i,j=temp
i+=1;j+=1
print('{} {}'.format(i,j))
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(*args):
"""
*args : (default value, dimension 1, dimension 2,...)
Returns : arr[dim1][dim2]... filled with default value
"""
assert len(args) >= 2, "makeArr args should be (default value, dimension 1, dimension 2,..."
if len(args) == 2:
return [args[0] for _ in range(args[1])]
else:
return [makeArr(args[0],*args[2:]) for _ in range(args[1])]
def queryInteractive(x,y):
print('? {} {}'.format(x,y))
sys.stdout.flush()
return int(input())
def answerInteractive(ans):
print('! {}'.format(ans))
sys.stdout.flush()
inf=float('inf')
MOD=10**9+7
for _abc in range(1):
main()
```
| 8,480 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.
You have to choose two arrays a_i and a_j (1 β€ i, j β€ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k β [1, m] b_k = max(a_{i, k}, a_{j, k}).
Your goal is to choose i and j so that the value of min _{k = 1}^{m} b_k is maximum possible.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^5, 1 β€ m β€ 8) β the number of arrays and the number of elements in each array, respectively.
Then n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 β€ a_{x, y} β€ 10^9).
Output
Print two integers i and j (1 β€ i, j β€ n, it is possible that i = j) β the indices of the two arrays you have to choose so that the value of min _{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.
Example
Input
6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
Output
1 5
Tags: binary search, bitmasks, dp
Correct Solution:
```
hell=1000000007
id1=0
id2=0
a = []
def check(n,m,x):
global id1,id2
b = [0]*(1<<m)
idx = [0]*(1<<m)
for i in range(n):
mask=0
for j in range(m):
if a[i][j]>=x:
mask=mask^(1<<j)
b[mask]=1
idx[mask]=i+1
for i in range(1<<m):
if b[i]:
for j in range(1<<m):
if b[j]:
mask=i|j
if mask==((1<<m)-1):
id1=idx[i]
id2=idx[j]
return 1
return 0
def meowmeow321():
n,m = map(int,input().split())
for i in range(n):
dog = [int(x) for x in input().split()]
a.append(dog)
lo=0
hi=hell
while hi-lo>0:
mid=(hi+lo+1)//2
if check(n,m,mid):
lo=mid
else:
hi=mid-1
check(n,m,lo)
print(id1,id2)
t=1
#t=int(input())
for xxx in range(t):
meowmeow321()
```
| 8,481 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.
You have to choose two arrays a_i and a_j (1 β€ i, j β€ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k β [1, m] b_k = max(a_{i, k}, a_{j, k}).
Your goal is to choose i and j so that the value of min _{k = 1}^{m} b_k is maximum possible.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^5, 1 β€ m β€ 8) β the number of arrays and the number of elements in each array, respectively.
Then n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 β€ a_{x, y} β€ 10^9).
Output
Print two integers i and j (1 β€ i, j β€ n, it is possible that i = j) β the indices of the two arrays you have to choose so that the value of min _{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.
Example
Input
6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
Output
1 5
Tags: binary search, bitmasks, dp
Correct Solution:
```
#!/usr/bin/env python3
import sys
input = sys.stdin.readline
max_val = 0
n, m = [int(item) for item in input().split()]
array = []
for i in range(n):
line = [int(item) for item in input().split()]
array.append(line)
max_val = max(max_val, max(line))
good = (1 << m) - 1
l = 0; r = max_val + 1
a = 0; b = 0
while r - l > 1:
mid = (l + r) // 2
bit_array = dict()
for k, line in enumerate(array):
val = 0
for i, item in enumerate(line):
if item >= mid:
val |= 1 << i
bit_array[val] = k
ok = False
for key1 in bit_array.keys():
for key2 in bit_array.keys():
if key1 | key2 == good:
ok = True
i = bit_array[key1]
j = bit_array[key2]
break
if ok:
a = i; b = j
l = mid
else:
r = mid
print(a+1, b+1)
```
| 8,482 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.
You have to choose two arrays a_i and a_j (1 β€ i, j β€ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k β [1, m] b_k = max(a_{i, k}, a_{j, k}).
Your goal is to choose i and j so that the value of min _{k = 1}^{m} b_k is maximum possible.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^5, 1 β€ m β€ 8) β the number of arrays and the number of elements in each array, respectively.
Then n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 β€ a_{x, y} β€ 10^9).
Output
Print two integers i and j (1 β€ i, j β€ n, it is possible that i = j) β the indices of the two arrays you have to choose so that the value of min _{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.
Example
Input
6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
Output
1 5
Tags: binary search, bitmasks, dp
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
#threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
#sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**30, func=lambda a, b: min(a , b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b:a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] > k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.isEndOfWord = False
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def _charToIndex(self, ch):
return ord(ch) - ord('a')
def insert(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
pCrawl.children[index] = self.getNode()
pCrawl = pCrawl.children[index]
pCrawl.isEndOfWord = True
def search(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
return False
pCrawl = pCrawl.children[index]
return pCrawl != None and pCrawl.isEndOfWord
#-----------------------------------------trie---------------------------------
class Node:
def __init__(self, data):
self.data = data
self.count=0
self.left = None # left node for 0
self.right = None # right node for 1
class BinaryTrie:
def __init__(self):
self.root = Node(0)
def insert(self, pre_xor):
self.temp = self.root
for i in range(31, -1, -1):
val = pre_xor & (1 << i)
if val:
if not self.temp.right:
self.temp.right = Node(0)
self.temp = self.temp.right
self.temp.count+=1
if not val:
if not self.temp.left:
self.temp.left = Node(0)
self.temp = self.temp.left
self.temp.count += 1
self.temp.data = pre_xor
def query(self, xor):
self.temp = self.root
for i in range(31, -1, -1):
val = xor & (1 << i)
if not val:
if self.temp.left and self.temp.left.count>0:
self.temp = self.temp.left
elif self.temp.right:
self.temp = self.temp.right
else:
if self.temp.right and self.temp.right.count>0:
self.temp = self.temp.right
elif self.temp.left:
self.temp = self.temp.left
self.temp.count-=1
return xor ^ self.temp.data
#-------------------------bin trie-------------------------------------------
n,m=map(int,input().split())
l=[]
pm=2**m-1
for i in range(n):
l.append(list(map(int,input().split())))
def find (x):
s=set()
d=defaultdict(int)
for i in range(n):
a=""
for j in range(m):
if l[i][j]>=x:
a+='1'
else:
a+='0'
d[int(a,2)]=i
s.add(int(a,2))
s=list(s)
#print(s)
for i in range(len(s)):
for j in range(i,len(s)):
if s[i]|s[j]==pm:
return [d[s[i]]+1,d[s[j]]+1]
return [-1,-1]
st=0
end=10**9
ans=(0,0)
while(st<=end):
mid=(st+end)//2
s=find(mid)
if s[0]!=-1:
ans=s
st=mid+1
else:
end=mid-1
print(*ans)
```
| 8,483 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.
You have to choose two arrays a_i and a_j (1 β€ i, j β€ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k β [1, m] b_k = max(a_{i, k}, a_{j, k}).
Your goal is to choose i and j so that the value of min _{k = 1}^{m} b_k is maximum possible.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^5, 1 β€ m β€ 8) β the number of arrays and the number of elements in each array, respectively.
Then n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 β€ a_{x, y} β€ 10^9).
Output
Print two integers i and j (1 β€ i, j β€ n, it is possible that i = j) β the indices of the two arrays you have to choose so that the value of min _{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.
Example
Input
6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
Output
1 5
Tags: binary search, bitmasks, dp
Correct Solution:
```
import sys
def find_pair(candidate,data,m):
ans = (-1,-1)
binary_bit = [False for i in range(1 << m)]
for i in data:
bit_tmp = 0
for j in range(len(i)):
if i[j] >= candidate: bit_tmp |= 1 << j
binary_bit[bit_tmp] = True
for i in range(1 << m):
for j in range(1 << m):
if i | j == (( 1 << m ) - 1) and binary_bit[i] and binary_bit[j]:
ans = i , j
break
return ans
def backtracking(candidate,ans,data):
idx_i = -1 ; idx_j = -1
for i in range(len(data)):
bit_tmp = 0
for j in range(len(data[i])):
if data[i][j] >= candidate: bit_tmp |= 1 << j
if bit_tmp == ans[0]: idx_i = i
if bit_tmp == ans[1]: idx_j = i
print(str(idx_i + 1) + " " + str(idx_j + 1))
def main():
n , m = [int(i) for i in input().split()]
data = [[int(i) for i in input().split()] for i in range(n)]
a = 0 ; b = 10**9 + 7
ans = (-1,-1)
candidate = -1
while a <= b:
mid = (a + b)//2
bin_ans = find_pair(mid,data,m)
if bin_ans[0] != -1 and bin_ans[1] != -1:
ans = bin_ans
candidate = mid
a = mid + 1
else:
b = mid - 1
backtracking(candidate,ans,data)
main()
```
| 8,484 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.
You have to choose two arrays a_i and a_j (1 β€ i, j β€ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k β [1, m] b_k = max(a_{i, k}, a_{j, k}).
Your goal is to choose i and j so that the value of min _{k = 1}^{m} b_k is maximum possible.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^5, 1 β€ m β€ 8) β the number of arrays and the number of elements in each array, respectively.
Then n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 β€ a_{x, y} β€ 10^9).
Output
Print two integers i and j (1 β€ i, j β€ n, it is possible that i = j) β the indices of the two arrays you have to choose so that the value of min _{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.
Example
Input
6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
Output
1 5
Tags: binary search, bitmasks, dp
Correct Solution:
```
def main():
N, M = map(int, input().split())
L = [tuple(map(int, input().split())) for _ in range(N)]
maxi = max(max(t) for t in L)+1
mini, res = max((min(t), i) for i, t in enumerate(L))
res = res, res
BITMASK = (1 << M)
while True:
mid = (maxi+mini)//2
#print(f'{mini} {mid} {maxi}')
if mid == mini:
break
masks = [None]*BITMASK
for i, t in enumerate(L):
tmask = 0
for v in t:
tmask *= 2
if v >= mid:
tmask += 1
if masks[tmask] is not None:
continue
masks[tmask] = i
for k in range(BITMASK):
if masks[k] is not None and k | tmask == BITMASK-1:
res = masks[k], i
mini = mid = min(max(a, b) for a, b in zip(L[res[0]], L[res[1]]))
break
else:
continue
break
else:
maxi = mid
#print(masks)
print(res[0]+1, res[1]+1)
main()
```
| 8,485 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.
You have to choose two arrays a_i and a_j (1 β€ i, j β€ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k β [1, m] b_k = max(a_{i, k}, a_{j, k}).
Your goal is to choose i and j so that the value of min _{k = 1}^{m} b_k is maximum possible.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^5, 1 β€ m β€ 8) β the number of arrays and the number of elements in each array, respectively.
Then n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 β€ a_{x, y} β€ 10^9).
Output
Print two integers i and j (1 β€ i, j β€ n, it is possible that i = j) β the indices of the two arrays you have to choose so that the value of min _{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.
Example
Input
6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
Output
1 5
Submitted Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
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")
#-------------------------------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a+b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SegmentTree1:
def __init__(self, data, default=10**6, func=lambda a, b: min(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
MOD=10**9+7
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(10)]
pp=[0]*10
def SieveOfEratosthenes(n=10):
p = 2
c=0
while (p * p <= n):
if (prime[p] == True):
c+=1
for i in range(p, n+1, p):
pp[i]+=1
prime[i] = False
p += 1
#---------------------------------Binary Search------------------------------------------
def binarySearch(arr, n, key):
left = 0
right = n-1
mid = 0
res=arr[n-1]
while (left <= right):
mid = (right + left)//2
if (arr[mid] >= key):
res=arr[mid]
right = mid-1
else:
left = mid + 1
return res
def binarySearch1(arr, n, key):
left = 0
right = n-1
mid = 0
res=arr[0]
while (left <= right):
mid = (right + left)//2
if (arr[mid] > key):
right = mid-1
else:
res=arr[mid]
left = mid + 1
return res
#---------------------------------running code------------------------------------------
n,m=map(int,input().split())
l=[]
pm=2**m-1
for i in range(n):
l.append(list(map(int,input().split())))
def find (x):
s=set()
d=defaultdict(int)
for i in range(n):
a=""
for j in range(m):
if l[i][j]>=x:
a+='1'
else:
a+='0'
d[int(a,2)]=i
s.add(int(a,2))
s=list(s)
#print(s)
for i in range(len(s)):
for j in range(i,len(s)):
if s[i]|s[j]==pm:
return [d[s[i]]+1,d[s[j]]+1]
return [-1,-1]
st=0
end=10**9
ans=(0,0)
while(st<=end):
mid=(st+end)//2
s=find(mid)
if s[0]!=-1:
ans=s
st=mid+1
else:
end=mid-1
print(*ans)
```
Yes
| 8,486 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.
You have to choose two arrays a_i and a_j (1 β€ i, j β€ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k β [1, m] b_k = max(a_{i, k}, a_{j, k}).
Your goal is to choose i and j so that the value of min _{k = 1}^{m} b_k is maximum possible.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^5, 1 β€ m β€ 8) β the number of arrays and the number of elements in each array, respectively.
Then n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 β€ a_{x, y} β€ 10^9).
Output
Print two integers i and j (1 β€ i, j β€ n, it is possible that i = j) β the indices of the two arrays you have to choose so that the value of min _{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.
Example
Input
6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
Output
1 5
Submitted Solution:
```
import sys
from collections import defaultdict
reader = (map(int, line.split()) for line in sys.stdin)
input = reader.__next__
n, m = input()
# n, m = 3 * 10 ** 5, 8
vals = set()
locs = defaultdict(list)
for i in range(n):
for pos, v in enumerate(input()):
vals.add(v)
locs[v].append((pos, i))
masks = [0] * n
full = (1<<m) - 1
met = {0:0}
for v in sorted(vals, reverse=True):
for pos, i in locs[v]:
curr_mask = masks[i] = masks[i] | (1<<pos)
met[curr_mask] = i
complement = full ^ curr_mask
if complement in met:
print(i+1, met[complement]+1)
sys.exit()
```
Yes
| 8,487 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.
You have to choose two arrays a_i and a_j (1 β€ i, j β€ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k β [1, m] b_k = max(a_{i, k}, a_{j, k}).
Your goal is to choose i and j so that the value of min _{k = 1}^{m} b_k is maximum possible.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^5, 1 β€ m β€ 8) β the number of arrays and the number of elements in each array, respectively.
Then n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 β€ a_{x, y} β€ 10^9).
Output
Print two integers i and j (1 β€ i, j β€ n, it is possible that i = j) β the indices of the two arrays you have to choose so that the value of min _{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.
Example
Input
6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
Output
1 5
Submitted Solution:
```
def isPoss(n, arrs, nvals):
masks = set()
midx = {}
for pos,arr in enumerate(arrs):
mask = 0
for i in range(nvals):
if arr[i]>=n:
mask += 1<<i
midx[mask] = pos+1
masks.add(mask)
for m1 in masks:
for m2 in masks:
if m1|m2 == (1<<nvals)-1:
return midx[m1], midx[m2]
return -1, -1
narr, nvals = map(int, input().split())
arrs = []
for i in range(narr):
arrs.append(list(map(int, input().split())))
mn = -1
mx = 10**9+1
while mn < mx-1:
mid = (mn + mx) // 2
a,b = isPoss(mid, arrs, nvals)
if a != -1:
mn = mid
else:
mx = mid - 1
for i in range(1,-1,-1):
a,b = isPoss(mn+i, arrs, nvals)
if a != -1:
print(a,b)
break
```
Yes
| 8,488 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.
You have to choose two arrays a_i and a_j (1 β€ i, j β€ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k β [1, m] b_k = max(a_{i, k}, a_{j, k}).
Your goal is to choose i and j so that the value of min _{k = 1}^{m} b_k is maximum possible.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^5, 1 β€ m β€ 8) β the number of arrays and the number of elements in each array, respectively.
Then n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 β€ a_{x, y} β€ 10^9).
Output
Print two integers i and j (1 β€ i, j β€ n, it is possible that i = j) β the indices of the two arrays you have to choose so that the value of min _{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.
Example
Input
6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
Output
1 5
Submitted Solution:
```
from sys import stdin
def solve(x: int) -> bool:
global ans
dp = {}
for i in range(n):
temp = 0
for j in range(m):
if a[i][j] >= x:
temp = temp | (1 << j)
dp[temp] = i
for aa, bb in dp.items():
for cc, dd in dp.items():
if aa | cc == 2 ** m - 1:
ans = (bb + 1, dd + 1)
return True
return False
ans = (-1, -1)
n, m = map(int, stdin.readline().split())
a = []
for i in range(n):
a.append(list(map(int, stdin.readline().split())))
l, r = 0, 10 ** 9
while l <= r:
mid = (l + r) // 2
if solve(mid):
l = mid + 1
else:
r = mid - 1
print(*ans)
```
Yes
| 8,489 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.
You have to choose two arrays a_i and a_j (1 β€ i, j β€ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k β [1, m] b_k = max(a_{i, k}, a_{j, k}).
Your goal is to choose i and j so that the value of min _{k = 1}^{m} b_k is maximum possible.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^5, 1 β€ m β€ 8) β the number of arrays and the number of elements in each array, respectively.
Then n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 β€ a_{x, y} β€ 10^9).
Output
Print two integers i and j (1 β€ i, j β€ n, it is possible that i = j) β the indices of the two arrays you have to choose so that the value of min _{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.
Example
Input
6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
Output
1 5
Submitted Solution:
```
import random
def want(p,q):
ans = float("inf")
for i in range(m):
ans = min(ans , max(a[p][i],a[q][i]))
return ans
n,m = map(int,input().split())
a = []
for i in range(n):
A = list(map(int,input().split()))
a.append(A)
x = random.randint(0,n-1)
y = random.randint(0,n-1)
q = []
for j in range(50):
nd = random.randint(0,n-1)
for i in range(n):
i = (i + nd) % n
now = want(x,y)
planA = want(x,i)
planB = want(i,y)
if max(now,planA,planB) == planA:
y = i
elif max(now,planA,planB) == planB:
x = i
q.append([x,y])
minind = 0
for i in range(50):
if want(q[minind][0],q[minind][1]) > want(q[i][0],q[i][1]):
minind = i
print (q[minind][0] + 1, q[minind][1] + 1)
```
No
| 8,490 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.
You have to choose two arrays a_i and a_j (1 β€ i, j β€ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k β [1, m] b_k = max(a_{i, k}, a_{j, k}).
Your goal is to choose i and j so that the value of min _{k = 1}^{m} b_k is maximum possible.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^5, 1 β€ m β€ 8) β the number of arrays and the number of elements in each array, respectively.
Then n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 β€ a_{x, y} β€ 10^9).
Output
Print two integers i and j (1 β€ i, j β€ n, it is possible that i = j) β the indices of the two arrays you have to choose so that the value of min _{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.
Example
Input
6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
Output
1 5
Submitted Solution:
```
import sys
input = sys.stdin.readline
n,m = list(map(int,input().split()))
mat = []
for i in range(n):
mat.append(list(map(int,input().split())))
d = {}
for i in range(n):
arr1 = mat[i]
for j in range(i+1,n):
arr2 = mat[j]
temp = []
for k in range(m):
temp.append(max(arr1[k],arr2[k]))
key = str(i)+':'+str(j)
d[key] = min(temp)
cur = -1
u,v = -1,-1
for i in d:
if d[i]>cur:
u,v = list(map(int,i.split(':')))
print(u+1,v+1)
```
No
| 8,491 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.
You have to choose two arrays a_i and a_j (1 β€ i, j β€ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k β [1, m] b_k = max(a_{i, k}, a_{j, k}).
Your goal is to choose i and j so that the value of min _{k = 1}^{m} b_k is maximum possible.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^5, 1 β€ m β€ 8) β the number of arrays and the number of elements in each array, respectively.
Then n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 β€ a_{x, y} β€ 10^9).
Output
Print two integers i and j (1 β€ i, j β€ n, it is possible that i = j) β the indices of the two arrays you have to choose so that the value of min _{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.
Example
Input
6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
Output
1 5
Submitted Solution:
```
''' Hey stalker :) '''
INF = 10**10
def main():
#print = out.append
''' Cook your dish here! '''
n, m = get_list()
mat = [get_list() for _ in range(n)]
def fn(x):
#print(x, end=": ")
st = [-1]*(1<<m)
st[0] = 0
for index, li in enumerate(mat):
no = 0
for i, ele in enumerate(li):
if ele>=x:
no |= 1<<i
li = [0]
k = 2**m -1 - no
if st[k]>-1:
#print(True, st[k], index)
return True, st[k], index
b = 0
while(b!=0):
st[b] = index
b = (b-no)&no
# for i in range(m):
# if (no & (1<<i))==(1<<i):
# for j in range(len(li)):
# li.append(li[j] | 1<<i)
# st[li[-1]] = index
continue
return False, -1, -1
x = 0
base = 10**8
while base>0:
while fn(x+base)[0]: x+= base
base //= 2
res, a,b = fn(x)
print(a+1, b+1)
''' Pythonista fLite 1.1 '''
import sys
#from collections import defaultdict, Counter
#from functools import reduce
#import math
#input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
out = []
get_int = lambda: int(input())
get_list = lambda: list(map(int, input().split()))
main()
#[main() for _ in range(int(input()))]
#print(*out, sep='\n')
```
No
| 8,492 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n arrays a_1, a_2, ..., a_n; each array consists of exactly m integers. We denote the y-th element of the x-th array as a_{x, y}.
You have to choose two arrays a_i and a_j (1 β€ i, j β€ n, it is possible that i = j). After that, you will obtain a new array b consisting of m integers, such that for every k β [1, m] b_k = max(a_{i, k}, a_{j, k}).
Your goal is to choose i and j so that the value of min _{k = 1}^{m} b_k is maximum possible.
Input
The first line contains two integers n and m (1 β€ n β€ 3 β
10^5, 1 β€ m β€ 8) β the number of arrays and the number of elements in each array, respectively.
Then n lines follow, the x-th line contains the array a_x represented by m integers a_{x, 1}, a_{x, 2}, ..., a_{x, m} (0 β€ a_{x, y} β€ 10^9).
Output
Print two integers i and j (1 β€ i, j β€ n, it is possible that i = j) β the indices of the two arrays you have to choose so that the value of min _{k = 1}^{m} b_k is maximum possible. If there are multiple answers, print any of them.
Example
Input
6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
Output
1 5
Submitted Solution:
```
# Enter your code here. Read input from STDIN. Print output to STDOUT# ===============================================================================================
# 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 *
import bisect
from heapq import *
from math import ceil, floor
from copy import *
from collections import deque, defaultdict
from collections import Counter as counter # Counter(list) return a dict with {key: count}
from itertools import combinations # 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 operator import *
# If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
# If the element is already present in the list,
# the right most position where element has to be inserted is returned
# ==============================================================================================
# fast I/O region
BUFSIZE = 8192
from sys import stderr
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 ####
###########################
# Sorted list
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))
# ===============================================================================================
# some shortcuts
mod = 1000000007
def testcase(t):
for p in range(t):
solve()
def pow(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
from functools import reduce
def factors(n):
return set(reduce(list.__add__,
([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
def gcd(a, b):
if a == b: return a
while b > 0: a, b = b, a % b
return a
# discrete binary search
# minimise:
# def search():
# l = 0
# r = 10 ** 15
#
# for i in range(200):
# if isvalid(l):
# return l
# if l == r:
# return l
# m = (l + r) // 2
# if isvalid(m) and not isvalid(m - 1):
# return m
# if isvalid(m):
# r = m + 1
# else:
# l = m
# return m
# maximise:
# def search():
# l = 0
# r = 10 ** 15
#
# for i in range(200):
# # print(l,r)
# if isvalid(r):
# return r
# if l == r:
# return l
# m = (l + r) // 2
# if isvalid(m) and not isvalid(m + 1):
# return m
# if isvalid(m):
# l = m
# else:
# r = m - 1
# return m
##############Find sum of product of subsets of size k in a array
# ar=[0,1,2,3]
# k=3
# n=len(ar)-1
# dp=[0]*(n+1)
# dp[0]=1
# for pos in range(1,n+1):
# dp[pos]=0
# l=max(1,k+pos-n-1)
# for j in range(min(pos,k),l-1,-1):
# dp[j]=dp[j]+ar[pos]*dp[j-1]
# print(dp[k])
def prefix_sum(ar): # [1,2,3,4]->[1,3,6,10]
return list(accumulate(ar))
def suffix_sum(ar): # [1,2,3,4]->[10,9,7,4]
return list(accumulate(ar[::-1]))[::-1]
def N():
return int(inp())
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
def YES():
print("YES")
def NO():
print("NO")
def Yes():
print("Yes")
def No():
print("No")
# =========================================================================================
from collections import defaultdict
def numberOfSetBits(i):
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24
class MergeFind:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
self.num_sets = n
# self.lista = [[_] for _ in range(n)]
def find(self, a):
to_update = []
while a != self.parent[a]:
to_update.append(a)
a = self.parent[a]
for b in to_update:
self.parent[b] = a
return self.parent[a]
def merge(self, a, b):
a = self.find(a)
b = self.find(b)
if a == b:
return
if self.size[a] < self.size[b]:
a, b = b, a
self.num_sets -= 1
self.parent[b] = a
self.size[a] += self.size[b]
# self.lista[a] += self.lista[b]
# self.lista[b] = []
def set_size(self, a):
return self.size[self.find(a)]
def __len__(self):
return self.num_sets
def lcm(a, b):
return abs((a // gcd(a, b)) * b)
#
# to find factorial and ncr
# tot = 200005
# mod = 10**9 + 7
# fac = [1, 1]
# finv = [1, 1]
# inv = [0, 1]
#
# for i in range(2, tot + 1):
# fac.append((fac[-1] * i) % mod)
# inv.append(mod - (inv[mod % i] * (mod // i) % mod))
# finv.append(finv[-1] * inv[-1] % mod)
def comb(n, r):
if n < r:
return 0
else:
return fac[n] * (finv[r] * finv[n - r] % mod) % mod
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 fsep(): return map(float, inp().split())
def nextline(): out("\n") # as stdout.write always print sring.
def arr1d(n, v):
return [v] * n
def arr2d(n, m, v):
return [[v] * m for _ in range(n)]
def arr3d(n, m, p, v):
return [[[v] * p for _ in range(m)] for i in range(n)]
def solve():
n, m = sep()
ar = []
for i in range(n):
ar.append(lis())
def isvalid(k):
val = [0] * (2 ** m )
for i in range(n):
temp = 0
for j in range(m):
if ar[i][j] >= k:
temp += (1 << j)
val[temp] = 1
valu = []
for i in range(2 ** m ):
if val[i] == 1: valu.append(i)
req = 2 ** m - 1
for i in valu:
for j in valu:
if (i | j == req):
return 1
return 0
def search():
l = 0
r = 10 ** 9 +1
for i in range(30):
# print(l,r)
if l == r:
return l
m = (l + r) // 2
tempc=isvalid(m)
if tempc and not isvalid(m + 1):
return m
if tempc:
l = m
else:
r = m - 1
return m
k=search()
# print(isvalid(k))
val = defaultdict(int)
for i in range(n):
temp = 0
for j in range(m):
if ar[i][j] >= k:
temp += (1 << j)
val[(temp)]=i
req = 2 ** m - 1
for i in val.keys():
for j in val.keys():
if (i | j == req):
print(val[i]+1,val[j]+1)
return
solve()
#testcase(int(inp()))
```
No
| 8,493 |
Provide tags and a correct Python 3 solution for this coding contest problem.
per nextum in unam tum XI conscribementis fac sic
vestibulo perlegementum da varo.
morde varo.
seqis cumula varum.
cis
per nextum in unam tum XI conscribementis fac sic
seqis decumulamenta da varo.
varum privamentum fodementum da aresulto.
varum tum III elevamentum tum V multiplicamentum da bresulto.
aresultum tum bresultum addementum da resulto.
si CD tum resultum non praestantiam fac sic
dictum sic f(%d) = %.2f cis tum varum tum resultum egresso describe.
novumversum egresso scribe.
cis
si CD tum resultum praestantiam fac sic
dictum sic f(%d) = MAGNA NIMIS! cis tum varum egresso describe.
novumversum egresso scribe.
cis
cis
Input
The input consists of several integers, one per line. Each integer is between -50 and 50, inclusive.
Output
As described in the problem statement.
Example
Input
0
1
-2
-3
-4
-5
-6
-7
-8
-9
10
Output
f(10) = MAGNA NIMIS!
f(-9) = -3642.00
f(-8) = -2557.17
f(-7) = -1712.35
f(-6) = -1077.55
f(-5) = -622.76
f(-4) = -318.00
f(-3) = -133.27
f(-2) = -38.59
f(1) = 6.00
f(0) = 0.00
Tags: *special
Correct Solution:
```
from math import sqrt
f = lambda x: sqrt(abs(x))
g = lambda x: x**3*5
arr = []
for _ in range(11):
arr.append(int(input()))
arr.reverse()
for e in arr:
r = f(e)+g(e)
if 400 < r:
print("f(%d) = " % (e) + "MAGNA NIMIS!")
continue
print("f(%d) = %.2f" % (e, r))
```
| 8,494 |
Provide tags and a correct Python 3 solution for this coding contest problem.
per nextum in unam tum XI conscribementis fac sic
vestibulo perlegementum da varo.
morde varo.
seqis cumula varum.
cis
per nextum in unam tum XI conscribementis fac sic
seqis decumulamenta da varo.
varum privamentum fodementum da aresulto.
varum tum III elevamentum tum V multiplicamentum da bresulto.
aresultum tum bresultum addementum da resulto.
si CD tum resultum non praestantiam fac sic
dictum sic f(%d) = %.2f cis tum varum tum resultum egresso describe.
novumversum egresso scribe.
cis
si CD tum resultum praestantiam fac sic
dictum sic f(%d) = MAGNA NIMIS! cis tum varum egresso describe.
novumversum egresso scribe.
cis
cis
Input
The input consists of several integers, one per line. Each integer is between -50 and 50, inclusive.
Output
As described in the problem statement.
Example
Input
0
1
-2
-3
-4
-5
-6
-7
-8
-9
10
Output
f(10) = MAGNA NIMIS!
f(-9) = -3642.00
f(-8) = -2557.17
f(-7) = -1712.35
f(-6) = -1077.55
f(-5) = -622.76
f(-4) = -318.00
f(-3) = -133.27
f(-2) = -38.59
f(1) = 6.00
f(0) = 0.00
Tags: *special
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
self.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")
import time
start_time = time.time()
import collections as col
import math, string
from functools import reduce
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input()
def listStr():
return list(input())
MOD = 10**9+7
"""
"""
def solve():
A = []
for i in range(11):
A.append(getInt())
A = A[::-1]
def f_(x): return math.sqrt(abs(x))+5*(x**3)
for a in A:
y = f_(a)
if y > 400:
print("f({}) =".format(a),"MAGNA NIMIS!")
else:
print("f({}) =".format(a),"%.2f"%y)
return
#for _ in range(getInt()):
solve()
```
| 8,495 |
Provide tags and a correct Python 3 solution for this coding contest problem.
per nextum in unam tum XI conscribementis fac sic
vestibulo perlegementum da varo.
morde varo.
seqis cumula varum.
cis
per nextum in unam tum XI conscribementis fac sic
seqis decumulamenta da varo.
varum privamentum fodementum da aresulto.
varum tum III elevamentum tum V multiplicamentum da bresulto.
aresultum tum bresultum addementum da resulto.
si CD tum resultum non praestantiam fac sic
dictum sic f(%d) = %.2f cis tum varum tum resultum egresso describe.
novumversum egresso scribe.
cis
si CD tum resultum praestantiam fac sic
dictum sic f(%d) = MAGNA NIMIS! cis tum varum egresso describe.
novumversum egresso scribe.
cis
cis
Input
The input consists of several integers, one per line. Each integer is between -50 and 50, inclusive.
Output
As described in the problem statement.
Example
Input
0
1
-2
-3
-4
-5
-6
-7
-8
-9
10
Output
f(10) = MAGNA NIMIS!
f(-9) = -3642.00
f(-8) = -2557.17
f(-7) = -1712.35
f(-6) = -1077.55
f(-5) = -622.76
f(-4) = -318.00
f(-3) = -133.27
f(-2) = -38.59
f(1) = 6.00
f(0) = 0.00
Tags: *special
Correct Solution:
```
stack = []
for _ in range(11):
stack += int(input()),
while stack:
v = stack.pop()
a = abs(v) ** (1/2)
b = v **3 * 5
r = a + b
if r > 400:
print('f({}) = MAGNA NIMIS!'.format(v))
else:
print('f({}) = {:.2f}'.format(v, r))
```
| 8,496 |
Provide tags and a correct Python 3 solution for this coding contest problem.
per nextum in unam tum XI conscribementis fac sic
vestibulo perlegementum da varo.
morde varo.
seqis cumula varum.
cis
per nextum in unam tum XI conscribementis fac sic
seqis decumulamenta da varo.
varum privamentum fodementum da aresulto.
varum tum III elevamentum tum V multiplicamentum da bresulto.
aresultum tum bresultum addementum da resulto.
si CD tum resultum non praestantiam fac sic
dictum sic f(%d) = %.2f cis tum varum tum resultum egresso describe.
novumversum egresso scribe.
cis
si CD tum resultum praestantiam fac sic
dictum sic f(%d) = MAGNA NIMIS! cis tum varum egresso describe.
novumversum egresso scribe.
cis
cis
Input
The input consists of several integers, one per line. Each integer is between -50 and 50, inclusive.
Output
As described in the problem statement.
Example
Input
0
1
-2
-3
-4
-5
-6
-7
-8
-9
10
Output
f(10) = MAGNA NIMIS!
f(-9) = -3642.00
f(-8) = -2557.17
f(-7) = -1712.35
f(-6) = -1077.55
f(-5) = -622.76
f(-4) = -318.00
f(-3) = -133.27
f(-2) = -38.59
f(1) = 6.00
f(0) = 0.00
Tags: *special
Correct Solution:
```
import math
def f(t):
return math.sqrt(abs(t)) + 5 * t ** 3
a = [int(input()) for _ in range(11)]
for i, t in reversed(list(enumerate(a))):
y = f(t)
if y > 400:
print('f(', t, ') = MAGNA NIMIS!', sep='')
else:
print('f(', t, ') = %.2f' % y, sep='')
```
| 8,497 |
Provide tags and a correct Python 3 solution for this coding contest problem.
per nextum in unam tum XI conscribementis fac sic
vestibulo perlegementum da varo.
morde varo.
seqis cumula varum.
cis
per nextum in unam tum XI conscribementis fac sic
seqis decumulamenta da varo.
varum privamentum fodementum da aresulto.
varum tum III elevamentum tum V multiplicamentum da bresulto.
aresultum tum bresultum addementum da resulto.
si CD tum resultum non praestantiam fac sic
dictum sic f(%d) = %.2f cis tum varum tum resultum egresso describe.
novumversum egresso scribe.
cis
si CD tum resultum praestantiam fac sic
dictum sic f(%d) = MAGNA NIMIS! cis tum varum egresso describe.
novumversum egresso scribe.
cis
cis
Input
The input consists of several integers, one per line. Each integer is between -50 and 50, inclusive.
Output
As described in the problem statement.
Example
Input
0
1
-2
-3
-4
-5
-6
-7
-8
-9
10
Output
f(10) = MAGNA NIMIS!
f(-9) = -3642.00
f(-8) = -2557.17
f(-7) = -1712.35
f(-6) = -1077.55
f(-5) = -622.76
f(-4) = -318.00
f(-3) = -133.27
f(-2) = -38.59
f(1) = 6.00
f(0) = 0.00
Tags: *special
Correct Solution:
```
from math import sqrt, pow
def f(x):
sign = 1 if x > 0 else -1 if x < 0 else 0
aresult = sqrt(abs(x))
bresult = pow(x, 3)*5
result = bresult + aresult
# result *= sign
return result
arr = []
for i in range(11):
x = int(input())
arr.append(x)
for x in reversed(arr):
result = f(x)
print(f"f({x}) = ", end="")
if result >= 400:
print("MAGNA NIMIS!")
else:
print(f"{result:.2f}")
```
| 8,498 |
Provide tags and a correct Python 3 solution for this coding contest problem.
per nextum in unam tum XI conscribementis fac sic
vestibulo perlegementum da varo.
morde varo.
seqis cumula varum.
cis
per nextum in unam tum XI conscribementis fac sic
seqis decumulamenta da varo.
varum privamentum fodementum da aresulto.
varum tum III elevamentum tum V multiplicamentum da bresulto.
aresultum tum bresultum addementum da resulto.
si CD tum resultum non praestantiam fac sic
dictum sic f(%d) = %.2f cis tum varum tum resultum egresso describe.
novumversum egresso scribe.
cis
si CD tum resultum praestantiam fac sic
dictum sic f(%d) = MAGNA NIMIS! cis tum varum egresso describe.
novumversum egresso scribe.
cis
cis
Input
The input consists of several integers, one per line. Each integer is between -50 and 50, inclusive.
Output
As described in the problem statement.
Example
Input
0
1
-2
-3
-4
-5
-6
-7
-8
-9
10
Output
f(10) = MAGNA NIMIS!
f(-9) = -3642.00
f(-8) = -2557.17
f(-7) = -1712.35
f(-6) = -1077.55
f(-5) = -622.76
f(-4) = -318.00
f(-3) = -133.27
f(-2) = -38.59
f(1) = 6.00
f(0) = 0.00
Tags: *special
Correct Solution:
```
from math import sqrt as s
def main():
inp = list()
for _ in range(11):
inp.append(int(input()))
for num in reversed(inp):
result = s(abs(num)) + num * num * num * 5
print(f"f({num}) = ", end = '', sep = '')
if result >= 400:
print('MAGNA NIMIS!')
else:
print('%.2f' % result)
if __name__ == '__main__':
main()
```
| 8,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.