lang
stringclasses 1
value | prompt
stringlengths 1.38k
11.3k
| eval_prompt
stringlengths 37
8.09k
| ground_truth
stringlengths 1
328
| unit_tests
stringclasses 145
values | task_id
stringlengths 23
25
| split
stringclasses 2
values |
|---|---|---|---|---|---|---|
python
|
Complete the code in python to solve this programming problem:
Description: Let's call a string $$$s$$$ perfectly balanced if for all possible triplets $$$(t,u,v)$$$ such that $$$t$$$ is a non-empty substring of $$$s$$$ and $$$u$$$ and $$$v$$$ are characters present in $$$s$$$, the difference between the frequencies of $$$u$$$ and $$$v$$$ in $$$t$$$ is not more than $$$1$$$.For example, the strings "aba" and "abc" are perfectly balanced but "abb" is not because for the triplet ("bb",'a','b'), the condition is not satisfied.You are given a string $$$s$$$ consisting of lowercase English letters only. Your task is to determine whether $$$s$$$ is perfectly balanced or not.A string $$$b$$$ is called a substring of another string $$$a$$$ if $$$b$$$ can be obtained by deleting some characters (possibly $$$0$$$) from the start and some characters (possibly $$$0$$$) from the end of $$$a$$$.
Input Specification: The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 2\cdot 10^4$$$) denoting the number of testcases. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\leq |s|\leq 2\cdot 10^5$$$), consisting of lowercase English letters. It is guaranteed that the sum of $$$|s|$$$ over all testcases does not exceed $$$2\cdot 10^5$$$.
Output Specification: For each test case, print "YES" if $$$s$$$ is a perfectly balanced string, and "NO" otherwise. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).
Notes: NoteLet $$$f_t(c)$$$ represent the frequency of character $$$c$$$ in string $$$t$$$.For the first testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$a$$$$$$1$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$aba$$$$$$2$$$$$$1$$$$$$b$$$$$$0$$$$$$1$$$$$$ba$$$$$$1$$$$$$1$$$ It can be seen that for any substring $$$t$$$ of $$$s$$$, the difference between $$$f_t(a)$$$ and $$$f_t(b)$$$ is not more than $$$1$$$. Hence the string $$$s$$$ is perfectly balanced.For the second testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$a$$$$$$1$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$abb$$$$$$1$$$$$$2$$$$$$b$$$$$$0$$$$$$1$$$$$$bb$$$$$$0$$$$$$2$$$ It can be seen that for the substring $$$t=bb$$$, the difference between $$$f_t(a)$$$ and $$$f_t(b)$$$ is $$$2$$$ which is greater than $$$1$$$. Hence the string $$$s$$$ is not perfectly balanced.For the third testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$f_t(c)$$$$$$a$$$$$$1$$$$$$0$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$0$$$$$$abc$$$$$$1$$$$$$1$$$$$$1$$$$$$b$$$$$$0$$$$$$1$$$$$$0$$$$$$bc$$$$$$0$$$$$$1$$$$$$1$$$$$$c$$$$$$0$$$$$$0$$$$$$1$$$It can be seen that for any substring $$$t$$$ of $$$s$$$ and any two characters $$$u,v\in\{a,b,c\}$$$, the difference between $$$f_t(u)$$$ and $$$f_t(v)$$$ is not more than $$$1$$$. Hence the string $$$s$$$ is perfectly balanced.
Code:
for _ in range(int(input())):
# TODO: Your code here
|
for _ in range(int(input())):
{{completion}}
|
s = input()
c = len(set(s))
print("Yes" if all(len(set(s[i::c])) == 1 for i in range(c)) else "No")
|
[{"input": "5\naba\nabb\nabc\naaaaa\nabcba", "output": ["YES\nNO\nYES\nYES\nNO"]}]
|
block_completion_004801
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Let's call a string $$$s$$$ perfectly balanced if for all possible triplets $$$(t,u,v)$$$ such that $$$t$$$ is a non-empty substring of $$$s$$$ and $$$u$$$ and $$$v$$$ are characters present in $$$s$$$, the difference between the frequencies of $$$u$$$ and $$$v$$$ in $$$t$$$ is not more than $$$1$$$.For example, the strings "aba" and "abc" are perfectly balanced but "abb" is not because for the triplet ("bb",'a','b'), the condition is not satisfied.You are given a string $$$s$$$ consisting of lowercase English letters only. Your task is to determine whether $$$s$$$ is perfectly balanced or not.A string $$$b$$$ is called a substring of another string $$$a$$$ if $$$b$$$ can be obtained by deleting some characters (possibly $$$0$$$) from the start and some characters (possibly $$$0$$$) from the end of $$$a$$$.
Input Specification: The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 2\cdot 10^4$$$) denoting the number of testcases. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\leq |s|\leq 2\cdot 10^5$$$), consisting of lowercase English letters. It is guaranteed that the sum of $$$|s|$$$ over all testcases does not exceed $$$2\cdot 10^5$$$.
Output Specification: For each test case, print "YES" if $$$s$$$ is a perfectly balanced string, and "NO" otherwise. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).
Notes: NoteLet $$$f_t(c)$$$ represent the frequency of character $$$c$$$ in string $$$t$$$.For the first testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$a$$$$$$1$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$aba$$$$$$2$$$$$$1$$$$$$b$$$$$$0$$$$$$1$$$$$$ba$$$$$$1$$$$$$1$$$ It can be seen that for any substring $$$t$$$ of $$$s$$$, the difference between $$$f_t(a)$$$ and $$$f_t(b)$$$ is not more than $$$1$$$. Hence the string $$$s$$$ is perfectly balanced.For the second testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$a$$$$$$1$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$abb$$$$$$1$$$$$$2$$$$$$b$$$$$$0$$$$$$1$$$$$$bb$$$$$$0$$$$$$2$$$ It can be seen that for the substring $$$t=bb$$$, the difference between $$$f_t(a)$$$ and $$$f_t(b)$$$ is $$$2$$$ which is greater than $$$1$$$. Hence the string $$$s$$$ is not perfectly balanced.For the third testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$f_t(c)$$$$$$a$$$$$$1$$$$$$0$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$0$$$$$$abc$$$$$$1$$$$$$1$$$$$$1$$$$$$b$$$$$$0$$$$$$1$$$$$$0$$$$$$bc$$$$$$0$$$$$$1$$$$$$1$$$$$$c$$$$$$0$$$$$$0$$$$$$1$$$It can be seen that for any substring $$$t$$$ of $$$s$$$ and any two characters $$$u,v\in\{a,b,c\}$$$, the difference between $$$f_t(u)$$$ and $$$f_t(v)$$$ is not more than $$$1$$$. Hence the string $$$s$$$ is perfectly balanced.
Code:
import sys
input = sys.stdin.readline
n = int(input())
for _ in range(n):
s = input()[:-1]
a = len(s)
b = len(set(s))
if b == 1 or a == b:
print('YES')
else:
for i in range(1, a):
if s[i] in s[:i]:
w = (s[:i]*a)[:a]
if s == w:
print("YES")
else:
# TODO: Your code here
break
|
import sys
input = sys.stdin.readline
n = int(input())
for _ in range(n):
s = input()[:-1]
a = len(s)
b = len(set(s))
if b == 1 or a == b:
print('YES')
else:
for i in range(1, a):
if s[i] in s[:i]:
w = (s[:i]*a)[:a]
if s == w:
print("YES")
else:
{{completion}}
break
|
print("NO")
|
[{"input": "5\naba\nabb\nabc\naaaaa\nabcba", "output": ["YES\nNO\nYES\nYES\nNO"]}]
|
block_completion_004802
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Let's call a string $$$s$$$ perfectly balanced if for all possible triplets $$$(t,u,v)$$$ such that $$$t$$$ is a non-empty substring of $$$s$$$ and $$$u$$$ and $$$v$$$ are characters present in $$$s$$$, the difference between the frequencies of $$$u$$$ and $$$v$$$ in $$$t$$$ is not more than $$$1$$$.For example, the strings "aba" and "abc" are perfectly balanced but "abb" is not because for the triplet ("bb",'a','b'), the condition is not satisfied.You are given a string $$$s$$$ consisting of lowercase English letters only. Your task is to determine whether $$$s$$$ is perfectly balanced or not.A string $$$b$$$ is called a substring of another string $$$a$$$ if $$$b$$$ can be obtained by deleting some characters (possibly $$$0$$$) from the start and some characters (possibly $$$0$$$) from the end of $$$a$$$.
Input Specification: The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 2\cdot 10^4$$$) denoting the number of testcases. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\leq |s|\leq 2\cdot 10^5$$$), consisting of lowercase English letters. It is guaranteed that the sum of $$$|s|$$$ over all testcases does not exceed $$$2\cdot 10^5$$$.
Output Specification: For each test case, print "YES" if $$$s$$$ is a perfectly balanced string, and "NO" otherwise. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).
Notes: NoteLet $$$f_t(c)$$$ represent the frequency of character $$$c$$$ in string $$$t$$$.For the first testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$a$$$$$$1$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$aba$$$$$$2$$$$$$1$$$$$$b$$$$$$0$$$$$$1$$$$$$ba$$$$$$1$$$$$$1$$$ It can be seen that for any substring $$$t$$$ of $$$s$$$, the difference between $$$f_t(a)$$$ and $$$f_t(b)$$$ is not more than $$$1$$$. Hence the string $$$s$$$ is perfectly balanced.For the second testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$a$$$$$$1$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$abb$$$$$$1$$$$$$2$$$$$$b$$$$$$0$$$$$$1$$$$$$bb$$$$$$0$$$$$$2$$$ It can be seen that for the substring $$$t=bb$$$, the difference between $$$f_t(a)$$$ and $$$f_t(b)$$$ is $$$2$$$ which is greater than $$$1$$$. Hence the string $$$s$$$ is not perfectly balanced.For the third testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$f_t(c)$$$$$$a$$$$$$1$$$$$$0$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$0$$$$$$abc$$$$$$1$$$$$$1$$$$$$1$$$$$$b$$$$$$0$$$$$$1$$$$$$0$$$$$$bc$$$$$$0$$$$$$1$$$$$$1$$$$$$c$$$$$$0$$$$$$0$$$$$$1$$$It can be seen that for any substring $$$t$$$ of $$$s$$$ and any two characters $$$u,v\in\{a,b,c\}$$$, the difference between $$$f_t(u)$$$ and $$$f_t(v)$$$ is not more than $$$1$$$. Hence the string $$$s$$$ is perfectly balanced.
Code:
t = int(input())
while (t > 0):
t -= 1
s = str(input())
var = set(s)
ans = "YES"
for i in range(len(s)-len(var)+1):
if len(set(s[i:i+len(var)])) != len(var):
# TODO: Your code here
print(ans)
|
t = int(input())
while (t > 0):
t -= 1
s = str(input())
var = set(s)
ans = "YES"
for i in range(len(s)-len(var)+1):
if len(set(s[i:i+len(var)])) != len(var):
{{completion}}
print(ans)
|
ans = "NO"
break
|
[{"input": "5\naba\nabb\nabc\naaaaa\nabcba", "output": ["YES\nNO\nYES\nYES\nNO"]}]
|
block_completion_004803
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Let's call a string $$$s$$$ perfectly balanced if for all possible triplets $$$(t,u,v)$$$ such that $$$t$$$ is a non-empty substring of $$$s$$$ and $$$u$$$ and $$$v$$$ are characters present in $$$s$$$, the difference between the frequencies of $$$u$$$ and $$$v$$$ in $$$t$$$ is not more than $$$1$$$.For example, the strings "aba" and "abc" are perfectly balanced but "abb" is not because for the triplet ("bb",'a','b'), the condition is not satisfied.You are given a string $$$s$$$ consisting of lowercase English letters only. Your task is to determine whether $$$s$$$ is perfectly balanced or not.A string $$$b$$$ is called a substring of another string $$$a$$$ if $$$b$$$ can be obtained by deleting some characters (possibly $$$0$$$) from the start and some characters (possibly $$$0$$$) from the end of $$$a$$$.
Input Specification: The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 2\cdot 10^4$$$) denoting the number of testcases. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\leq |s|\leq 2\cdot 10^5$$$), consisting of lowercase English letters. It is guaranteed that the sum of $$$|s|$$$ over all testcases does not exceed $$$2\cdot 10^5$$$.
Output Specification: For each test case, print "YES" if $$$s$$$ is a perfectly balanced string, and "NO" otherwise. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).
Notes: NoteLet $$$f_t(c)$$$ represent the frequency of character $$$c$$$ in string $$$t$$$.For the first testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$a$$$$$$1$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$aba$$$$$$2$$$$$$1$$$$$$b$$$$$$0$$$$$$1$$$$$$ba$$$$$$1$$$$$$1$$$ It can be seen that for any substring $$$t$$$ of $$$s$$$, the difference between $$$f_t(a)$$$ and $$$f_t(b)$$$ is not more than $$$1$$$. Hence the string $$$s$$$ is perfectly balanced.For the second testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$a$$$$$$1$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$abb$$$$$$1$$$$$$2$$$$$$b$$$$$$0$$$$$$1$$$$$$bb$$$$$$0$$$$$$2$$$ It can be seen that for the substring $$$t=bb$$$, the difference between $$$f_t(a)$$$ and $$$f_t(b)$$$ is $$$2$$$ which is greater than $$$1$$$. Hence the string $$$s$$$ is not perfectly balanced.For the third testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$f_t(c)$$$$$$a$$$$$$1$$$$$$0$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$0$$$$$$abc$$$$$$1$$$$$$1$$$$$$1$$$$$$b$$$$$$0$$$$$$1$$$$$$0$$$$$$bc$$$$$$0$$$$$$1$$$$$$1$$$$$$c$$$$$$0$$$$$$0$$$$$$1$$$It can be seen that for any substring $$$t$$$ of $$$s$$$ and any two characters $$$u,v\in\{a,b,c\}$$$, the difference between $$$f_t(u)$$$ and $$$f_t(v)$$$ is not more than $$$1$$$. Hence the string $$$s$$$ is perfectly balanced.
Code:
def solve(s):
st=set(s)
a=len(st)
f=1
for i in range(len(s)):
if s[i]!=s[i%a] :
# TODO: Your code here
if not f:
return "NO"
else:
return "YES"
for i in range(int(input())):
s=input()
print(solve(s))
|
def solve(s):
st=set(s)
a=len(st)
f=1
for i in range(len(s)):
if s[i]!=s[i%a] :
{{completion}}
if not f:
return "NO"
else:
return "YES"
for i in range(int(input())):
s=input()
print(solve(s))
|
f=0
|
[{"input": "5\naba\nabb\nabc\naaaaa\nabcba", "output": ["YES\nNO\nYES\nYES\nNO"]}]
|
block_completion_004804
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Let's call a string $$$s$$$ perfectly balanced if for all possible triplets $$$(t,u,v)$$$ such that $$$t$$$ is a non-empty substring of $$$s$$$ and $$$u$$$ and $$$v$$$ are characters present in $$$s$$$, the difference between the frequencies of $$$u$$$ and $$$v$$$ in $$$t$$$ is not more than $$$1$$$.For example, the strings "aba" and "abc" are perfectly balanced but "abb" is not because for the triplet ("bb",'a','b'), the condition is not satisfied.You are given a string $$$s$$$ consisting of lowercase English letters only. Your task is to determine whether $$$s$$$ is perfectly balanced or not.A string $$$b$$$ is called a substring of another string $$$a$$$ if $$$b$$$ can be obtained by deleting some characters (possibly $$$0$$$) from the start and some characters (possibly $$$0$$$) from the end of $$$a$$$.
Input Specification: The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 2\cdot 10^4$$$) denoting the number of testcases. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\leq |s|\leq 2\cdot 10^5$$$), consisting of lowercase English letters. It is guaranteed that the sum of $$$|s|$$$ over all testcases does not exceed $$$2\cdot 10^5$$$.
Output Specification: For each test case, print "YES" if $$$s$$$ is a perfectly balanced string, and "NO" otherwise. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).
Notes: NoteLet $$$f_t(c)$$$ represent the frequency of character $$$c$$$ in string $$$t$$$.For the first testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$a$$$$$$1$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$aba$$$$$$2$$$$$$1$$$$$$b$$$$$$0$$$$$$1$$$$$$ba$$$$$$1$$$$$$1$$$ It can be seen that for any substring $$$t$$$ of $$$s$$$, the difference between $$$f_t(a)$$$ and $$$f_t(b)$$$ is not more than $$$1$$$. Hence the string $$$s$$$ is perfectly balanced.For the second testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$a$$$$$$1$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$abb$$$$$$1$$$$$$2$$$$$$b$$$$$$0$$$$$$1$$$$$$bb$$$$$$0$$$$$$2$$$ It can be seen that for the substring $$$t=bb$$$, the difference between $$$f_t(a)$$$ and $$$f_t(b)$$$ is $$$2$$$ which is greater than $$$1$$$. Hence the string $$$s$$$ is not perfectly balanced.For the third testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$f_t(c)$$$$$$a$$$$$$1$$$$$$0$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$0$$$$$$abc$$$$$$1$$$$$$1$$$$$$1$$$$$$b$$$$$$0$$$$$$1$$$$$$0$$$$$$bc$$$$$$0$$$$$$1$$$$$$1$$$$$$c$$$$$$0$$$$$$0$$$$$$1$$$It can be seen that for any substring $$$t$$$ of $$$s$$$ and any two characters $$$u,v\in\{a,b,c\}$$$, the difference between $$$f_t(u)$$$ and $$$f_t(v)$$$ is not more than $$$1$$$. Hence the string $$$s$$$ is perfectly balanced.
Code:
for _ in range(int(input())):
n=input()
s=len(set(n))
for i in range(len(n)-s):
if n[i]!=n[i+s]:# TODO: Your code here
else:print("YES")
|
for _ in range(int(input())):
n=input()
s=len(set(n))
for i in range(len(n)-s):
if n[i]!=n[i+s]:{{completion}}
else:print("YES")
|
print("NO");break
|
[{"input": "5\naba\nabb\nabc\naaaaa\nabcba", "output": ["YES\nNO\nYES\nYES\nNO"]}]
|
block_completion_004805
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Let's call a string $$$s$$$ perfectly balanced if for all possible triplets $$$(t,u,v)$$$ such that $$$t$$$ is a non-empty substring of $$$s$$$ and $$$u$$$ and $$$v$$$ are characters present in $$$s$$$, the difference between the frequencies of $$$u$$$ and $$$v$$$ in $$$t$$$ is not more than $$$1$$$.For example, the strings "aba" and "abc" are perfectly balanced but "abb" is not because for the triplet ("bb",'a','b'), the condition is not satisfied.You are given a string $$$s$$$ consisting of lowercase English letters only. Your task is to determine whether $$$s$$$ is perfectly balanced or not.A string $$$b$$$ is called a substring of another string $$$a$$$ if $$$b$$$ can be obtained by deleting some characters (possibly $$$0$$$) from the start and some characters (possibly $$$0$$$) from the end of $$$a$$$.
Input Specification: The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 2\cdot 10^4$$$) denoting the number of testcases. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\leq |s|\leq 2\cdot 10^5$$$), consisting of lowercase English letters. It is guaranteed that the sum of $$$|s|$$$ over all testcases does not exceed $$$2\cdot 10^5$$$.
Output Specification: For each test case, print "YES" if $$$s$$$ is a perfectly balanced string, and "NO" otherwise. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).
Notes: NoteLet $$$f_t(c)$$$ represent the frequency of character $$$c$$$ in string $$$t$$$.For the first testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$a$$$$$$1$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$aba$$$$$$2$$$$$$1$$$$$$b$$$$$$0$$$$$$1$$$$$$ba$$$$$$1$$$$$$1$$$ It can be seen that for any substring $$$t$$$ of $$$s$$$, the difference between $$$f_t(a)$$$ and $$$f_t(b)$$$ is not more than $$$1$$$. Hence the string $$$s$$$ is perfectly balanced.For the second testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$a$$$$$$1$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$abb$$$$$$1$$$$$$2$$$$$$b$$$$$$0$$$$$$1$$$$$$bb$$$$$$0$$$$$$2$$$ It can be seen that for the substring $$$t=bb$$$, the difference between $$$f_t(a)$$$ and $$$f_t(b)$$$ is $$$2$$$ which is greater than $$$1$$$. Hence the string $$$s$$$ is not perfectly balanced.For the third testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$f_t(c)$$$$$$a$$$$$$1$$$$$$0$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$0$$$$$$abc$$$$$$1$$$$$$1$$$$$$1$$$$$$b$$$$$$0$$$$$$1$$$$$$0$$$$$$bc$$$$$$0$$$$$$1$$$$$$1$$$$$$c$$$$$$0$$$$$$0$$$$$$1$$$It can be seen that for any substring $$$t$$$ of $$$s$$$ and any two characters $$$u,v\in\{a,b,c\}$$$, the difference between $$$f_t(u)$$$ and $$$f_t(v)$$$ is not more than $$$1$$$. Hence the string $$$s$$$ is perfectly balanced.
Code:
for i in range(int(input())):
count={}
str = input()
for char in str:
count[char] = 0
res = True
for i in range(len(str) - len(count.keys())):
if (str[i]!=str[i + len(count.keys())]):
# TODO: Your code here
print("YES" if res else "NO")
|
for i in range(int(input())):
count={}
str = input()
for char in str:
count[char] = 0
res = True
for i in range(len(str) - len(count.keys())):
if (str[i]!=str[i + len(count.keys())]):
{{completion}}
print("YES" if res else "NO")
|
res = False
|
[{"input": "5\naba\nabb\nabc\naaaaa\nabcba", "output": ["YES\nNO\nYES\nYES\nNO"]}]
|
block_completion_004806
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Let's call a string $$$s$$$ perfectly balanced if for all possible triplets $$$(t,u,v)$$$ such that $$$t$$$ is a non-empty substring of $$$s$$$ and $$$u$$$ and $$$v$$$ are characters present in $$$s$$$, the difference between the frequencies of $$$u$$$ and $$$v$$$ in $$$t$$$ is not more than $$$1$$$.For example, the strings "aba" and "abc" are perfectly balanced but "abb" is not because for the triplet ("bb",'a','b'), the condition is not satisfied.You are given a string $$$s$$$ consisting of lowercase English letters only. Your task is to determine whether $$$s$$$ is perfectly balanced or not.A string $$$b$$$ is called a substring of another string $$$a$$$ if $$$b$$$ can be obtained by deleting some characters (possibly $$$0$$$) from the start and some characters (possibly $$$0$$$) from the end of $$$a$$$.
Input Specification: The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 2\cdot 10^4$$$) denoting the number of testcases. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\leq |s|\leq 2\cdot 10^5$$$), consisting of lowercase English letters. It is guaranteed that the sum of $$$|s|$$$ over all testcases does not exceed $$$2\cdot 10^5$$$.
Output Specification: For each test case, print "YES" if $$$s$$$ is a perfectly balanced string, and "NO" otherwise. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).
Notes: NoteLet $$$f_t(c)$$$ represent the frequency of character $$$c$$$ in string $$$t$$$.For the first testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$a$$$$$$1$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$aba$$$$$$2$$$$$$1$$$$$$b$$$$$$0$$$$$$1$$$$$$ba$$$$$$1$$$$$$1$$$ It can be seen that for any substring $$$t$$$ of $$$s$$$, the difference between $$$f_t(a)$$$ and $$$f_t(b)$$$ is not more than $$$1$$$. Hence the string $$$s$$$ is perfectly balanced.For the second testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$a$$$$$$1$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$abb$$$$$$1$$$$$$2$$$$$$b$$$$$$0$$$$$$1$$$$$$bb$$$$$$0$$$$$$2$$$ It can be seen that for the substring $$$t=bb$$$, the difference between $$$f_t(a)$$$ and $$$f_t(b)$$$ is $$$2$$$ which is greater than $$$1$$$. Hence the string $$$s$$$ is not perfectly balanced.For the third testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$f_t(c)$$$$$$a$$$$$$1$$$$$$0$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$0$$$$$$abc$$$$$$1$$$$$$1$$$$$$1$$$$$$b$$$$$$0$$$$$$1$$$$$$0$$$$$$bc$$$$$$0$$$$$$1$$$$$$1$$$$$$c$$$$$$0$$$$$$0$$$$$$1$$$It can be seen that for any substring $$$t$$$ of $$$s$$$ and any two characters $$$u,v\in\{a,b,c\}$$$, the difference between $$$f_t(u)$$$ and $$$f_t(v)$$$ is not more than $$$1$$$. Hence the string $$$s$$$ is perfectly balanced.
Code:
t = int(input())
while(t):
s = input()
d = len(set(s))
for i in range(d, len(s)):
if(s[i] != s[i - d]):
# TODO: Your code here
else:
print("Yes")
t -= 1
|
t = int(input())
while(t):
s = input()
d = len(set(s))
for i in range(d, len(s)):
if(s[i] != s[i - d]):
{{completion}}
else:
print("Yes")
t -= 1
|
print("No")
break
|
[{"input": "5\naba\nabb\nabc\naaaaa\nabcba", "output": ["YES\nNO\nYES\nYES\nNO"]}]
|
block_completion_004807
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Let's call a string $$$s$$$ perfectly balanced if for all possible triplets $$$(t,u,v)$$$ such that $$$t$$$ is a non-empty substring of $$$s$$$ and $$$u$$$ and $$$v$$$ are characters present in $$$s$$$, the difference between the frequencies of $$$u$$$ and $$$v$$$ in $$$t$$$ is not more than $$$1$$$.For example, the strings "aba" and "abc" are perfectly balanced but "abb" is not because for the triplet ("bb",'a','b'), the condition is not satisfied.You are given a string $$$s$$$ consisting of lowercase English letters only. Your task is to determine whether $$$s$$$ is perfectly balanced or not.A string $$$b$$$ is called a substring of another string $$$a$$$ if $$$b$$$ can be obtained by deleting some characters (possibly $$$0$$$) from the start and some characters (possibly $$$0$$$) from the end of $$$a$$$.
Input Specification: The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 2\cdot 10^4$$$) denoting the number of testcases. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\leq |s|\leq 2\cdot 10^5$$$), consisting of lowercase English letters. It is guaranteed that the sum of $$$|s|$$$ over all testcases does not exceed $$$2\cdot 10^5$$$.
Output Specification: For each test case, print "YES" if $$$s$$$ is a perfectly balanced string, and "NO" otherwise. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).
Notes: NoteLet $$$f_t(c)$$$ represent the frequency of character $$$c$$$ in string $$$t$$$.For the first testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$a$$$$$$1$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$aba$$$$$$2$$$$$$1$$$$$$b$$$$$$0$$$$$$1$$$$$$ba$$$$$$1$$$$$$1$$$ It can be seen that for any substring $$$t$$$ of $$$s$$$, the difference between $$$f_t(a)$$$ and $$$f_t(b)$$$ is not more than $$$1$$$. Hence the string $$$s$$$ is perfectly balanced.For the second testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$a$$$$$$1$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$abb$$$$$$1$$$$$$2$$$$$$b$$$$$$0$$$$$$1$$$$$$bb$$$$$$0$$$$$$2$$$ It can be seen that for the substring $$$t=bb$$$, the difference between $$$f_t(a)$$$ and $$$f_t(b)$$$ is $$$2$$$ which is greater than $$$1$$$. Hence the string $$$s$$$ is not perfectly balanced.For the third testcase we have $$$t$$$$$$f_t(a)$$$$$$f_t(b)$$$$$$f_t(c)$$$$$$a$$$$$$1$$$$$$0$$$$$$0$$$$$$ab$$$$$$1$$$$$$1$$$$$$0$$$$$$abc$$$$$$1$$$$$$1$$$$$$1$$$$$$b$$$$$$0$$$$$$1$$$$$$0$$$$$$bc$$$$$$0$$$$$$1$$$$$$1$$$$$$c$$$$$$0$$$$$$0$$$$$$1$$$It can be seen that for any substring $$$t$$$ of $$$s$$$ and any two characters $$$u,v\in\{a,b,c\}$$$, the difference between $$$f_t(u)$$$ and $$$f_t(v)$$$ is not more than $$$1$$$. Hence the string $$$s$$$ is perfectly balanced.
Code:
n = int(input())
for i in range(n):
str1 = input()
set_char = set(str1)
req = len(set_char)
prev = dict()
truth = True
ind = 0
for i1 in str1:
if( i1 in prev and ind - prev[i1] != req):
# TODO: Your code here
prev[i1] = ind
ind += 1
print(truth and 'YES' or 'NO')
|
n = int(input())
for i in range(n):
str1 = input()
set_char = set(str1)
req = len(set_char)
prev = dict()
truth = True
ind = 0
for i1 in str1:
if( i1 in prev and ind - prev[i1] != req):
{{completion}}
prev[i1] = ind
ind += 1
print(truth and 'YES' or 'NO')
|
truth = False
break
|
[{"input": "5\naba\nabb\nabc\naaaaa\nabcba", "output": ["YES\nNO\nYES\nYES\nNO"]}]
|
block_completion_004808
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Alice and Bob are playing a game with strings. There will be $$$t$$$ rounds in the game. In each round, there will be a string $$$s$$$ consisting of lowercase English letters. Alice moves first and both the players take alternate turns. Alice is allowed to remove any substring of even length (possibly empty) and Bob is allowed to remove any substring of odd length from $$$s$$$.More formally, if there was a string $$$s = s_1s_2 \ldots s_k$$$ the player can choose a substring $$$s_ls_{l+1} \ldots s_{r-1}s_r$$$ with length of corresponding parity and remove it. After that the string will become $$$s = s_1 \ldots s_{l-1}s_{r+1} \ldots s_k$$$.After the string becomes empty, the round ends and each player calculates his/her score for this round. The score of a player is the sum of values of all characters removed by him/her. The value of $$$\texttt{a}$$$ is $$$1$$$, the value of $$$\texttt{b}$$$ is $$$2$$$, the value of $$$\texttt{c}$$$ is $$$3$$$, $$$\ldots$$$, and the value of $$$\texttt{z}$$$ is $$$26$$$. The player with higher score wins the round. For each round, determine the winner and the difference between winner's and loser's scores. Assume that both players play optimally to maximize their score. It can be proved that a draw is impossible.
Input Specification: The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 5\cdot 10^4$$$) denoting the number of rounds. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\leq |s|\leq 2\cdot 10^5$$$) consisting of lowercase English letters, denoting the string used for the round. Here $$$|s|$$$ denotes the length of the string $$$s$$$. It is guaranteed that the sum of $$$|s|$$$ over all rounds does not exceed $$$2\cdot 10^5$$$.
Output Specification: For each round, print a single line containing a string and an integer. If Alice wins the round, the string must be "Alice". If Bob wins the round, the string must be "Bob". The integer must be the difference between their scores assuming both players play optimally.
Notes: NoteFor the first round, $$$\texttt{"aba"}\xrightarrow{\texttt{Alice}}\texttt{"}{\color{red}{\texttt{ab}}}\texttt{a"}\xrightarrow{} \texttt{"a"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{a}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$1+2=3$$$. Bob's total score is $$$1$$$.For the second round, $$$\texttt{"abc"}\xrightarrow{\texttt{Alice}}\texttt{"a}{\color{red}{\texttt{bc}}}\texttt{"}\xrightarrow{} \texttt{"a"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{a}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$2+3=5$$$. Bob's total score is $$$1$$$.For the third round, $$$\texttt{"cba"}\xrightarrow{\texttt{Alice}}\texttt{"}{\color{red}{\texttt{cb}}}\texttt{a"}\xrightarrow{} \texttt{"a"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{a}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$3+2=5$$$. Bob's total score is $$$1$$$.For the fourth round, $$$\texttt{"n"}\xrightarrow{\texttt{Alice}}\texttt{"n"}\xrightarrow{} \texttt{"n"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{n}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$0$$$. Bob's total score is $$$14$$$.For the fifth round, $$$\texttt{"codeforces"}\xrightarrow{\texttt{Alice}}\texttt{"}{\color{red}{\texttt{codeforces}}}\texttt{"}\xrightarrow{} \texttt{""}$$$. Alice's total score is $$$3+15+4+5+6+15+18+3+5+19=93$$$. Bob's total score is $$$0$$$.
Code:
from sys import stdin
from collections import deque
lst = stdin.read().split()
_s = 0
def inp(n=1):
global _s
ret = lst[_s:_s + n]
_s += n
return ret
def inp1():
return inp()[0]
t = int(inp1())
for _ in range(t):
alph = "abcdefghijklmnopqrstuvwxyz"
a = list(map(lambda c: alph.index(c) + 1, inp1()))
l = len(a)
s = sum(a)
if l % 2 == 0:
print(f"Alice {s}")
elif l == 1:
print(f"Bob {s}")
else:
o1 = sum(a[1:]) - a[0]
o2 = sum(a[:l-1]) - a[-1]
if o1 > o2:
print(f"Alice {o1}")
else:
# TODO: Your code here
|
from sys import stdin
from collections import deque
lst = stdin.read().split()
_s = 0
def inp(n=1):
global _s
ret = lst[_s:_s + n]
_s += n
return ret
def inp1():
return inp()[0]
t = int(inp1())
for _ in range(t):
alph = "abcdefghijklmnopqrstuvwxyz"
a = list(map(lambda c: alph.index(c) + 1, inp1()))
l = len(a)
s = sum(a)
if l % 2 == 0:
print(f"Alice {s}")
elif l == 1:
print(f"Bob {s}")
else:
o1 = sum(a[1:]) - a[0]
o2 = sum(a[:l-1]) - a[-1]
if o1 > o2:
print(f"Alice {o1}")
else:
{{completion}}
|
print(f"Alice {o2}")
|
[{"input": "5\n\naba\n\nabc\n\ncba\n\nn\n\ncodeforces", "output": ["Alice 2\nAlice 4\nAlice 4\nBob 14\nAlice 93"]}]
|
block_completion_004850
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Consider every tree (connected undirected acyclic graph) with $$$n$$$ vertices ($$$n$$$ is odd, vertices numbered from $$$1$$$ to $$$n$$$), and for each $$$2 \le i \le n$$$ the $$$i$$$-th vertex is adjacent to exactly one vertex with a smaller index.For each $$$i$$$ ($$$1 \le i \le n$$$) calculate the number of trees for which the $$$i$$$-th vertex will be the centroid. The answer can be huge, output it modulo $$$998\,244\,353$$$.A vertex is called a centroid if its removal splits the tree into subtrees with at most $$$(n-1)/2$$$ vertices each.
Input Specification: The first line contains an odd integer $$$n$$$ ($$$3 \le n < 2 \cdot 10^5$$$, $$$n$$$ is odd) β the number of the vertices in the tree.
Output Specification: Print $$$n$$$ integers in a single line, the $$$i$$$-th integer is the answer for the $$$i$$$-th vertex (modulo $$$998\,244\,353$$$).
Notes: NoteExample $$$1$$$: there are two possible trees: with edges $$$(1-2)$$$, and $$$(1-3)$$$ β here the centroid is $$$1$$$; and with edges $$$(1-2)$$$, and $$$(2-3)$$$ β here the centroid is $$$2$$$. So the answer is $$$1, 1, 0$$$.Example $$$2$$$: there are $$$24$$$ possible trees, for example with edges $$$(1-2)$$$, $$$(2-3)$$$, $$$(3-4)$$$, and $$$(4-5)$$$. Here the centroid is $$$3$$$.
Code:
MOD = 998244353
def modmul(x, y, c = 0):
# TODO: Your code here
def inv(x):
return pow(x, MOD - 2, MOD)
MAX = 10 ** 6
fact = [1]
for i in range(1, MAX):
fact.append(modmul(i, fact[i-1]))
invfact = [1] * (MAX)
invfact[MAX - 1] = inv(fact[MAX - 1])
for i in range(MAX - 2, -1, -1):
invfact[i] = modmul(i + 1, invfact[i+1])
def comb(x, y):
return modmul(fact[x], modmul(invfact[y], invfact[x - y]))
def invcomb(x, y):
return modmul(invfact[x], modmul(fact[y], fact[x - y]))
def invs(x):
return modmul(fact[x - 1], invfact[x])
n = int(input())
out = [0] * n
for i in range((n + 1) // 2):
base = fact[n - 1]
frac = modmul(comb(n//2, i), invcomb(n - 1, i))
out[i] = modmul(base, frac)
rem = 0
for i in range(n - 1, -1, -1):
oldrem = rem
rem += modmul(out[i], invs(i))
out[i] -= oldrem
rem %= MOD
out[i] %= MOD
print(' '.join(map(str,out)))
|
MOD = 998244353
def modmul(x, y, c = 0):
{{completion}}
def inv(x):
return pow(x, MOD - 2, MOD)
MAX = 10 ** 6
fact = [1]
for i in range(1, MAX):
fact.append(modmul(i, fact[i-1]))
invfact = [1] * (MAX)
invfact[MAX - 1] = inv(fact[MAX - 1])
for i in range(MAX - 2, -1, -1):
invfact[i] = modmul(i + 1, invfact[i+1])
def comb(x, y):
return modmul(fact[x], modmul(invfact[y], invfact[x - y]))
def invcomb(x, y):
return modmul(invfact[x], modmul(fact[y], fact[x - y]))
def invs(x):
return modmul(fact[x - 1], invfact[x])
n = int(input())
out = [0] * n
for i in range((n + 1) // 2):
base = fact[n - 1]
frac = modmul(comb(n//2, i), invcomb(n - 1, i))
out[i] = modmul(base, frac)
rem = 0
for i in range(n - 1, -1, -1):
oldrem = rem
rem += modmul(out[i], invs(i))
out[i] -= oldrem
rem %= MOD
out[i] %= MOD
print(' '.join(map(str,out)))
|
return (x * y + c) % MOD
|
[{"input": "3", "output": ["1 1 0"]}, {"input": "5", "output": ["10 10 4 0 0"]}, {"input": "7", "output": ["276 276 132 36 0 0 0"]}]
|
block_completion_005082
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Consider every tree (connected undirected acyclic graph) with $$$n$$$ vertices ($$$n$$$ is odd, vertices numbered from $$$1$$$ to $$$n$$$), and for each $$$2 \le i \le n$$$ the $$$i$$$-th vertex is adjacent to exactly one vertex with a smaller index.For each $$$i$$$ ($$$1 \le i \le n$$$) calculate the number of trees for which the $$$i$$$-th vertex will be the centroid. The answer can be huge, output it modulo $$$998\,244\,353$$$.A vertex is called a centroid if its removal splits the tree into subtrees with at most $$$(n-1)/2$$$ vertices each.
Input Specification: The first line contains an odd integer $$$n$$$ ($$$3 \le n < 2 \cdot 10^5$$$, $$$n$$$ is odd) β the number of the vertices in the tree.
Output Specification: Print $$$n$$$ integers in a single line, the $$$i$$$-th integer is the answer for the $$$i$$$-th vertex (modulo $$$998\,244\,353$$$).
Notes: NoteExample $$$1$$$: there are two possible trees: with edges $$$(1-2)$$$, and $$$(1-3)$$$ β here the centroid is $$$1$$$; and with edges $$$(1-2)$$$, and $$$(2-3)$$$ β here the centroid is $$$2$$$. So the answer is $$$1, 1, 0$$$.Example $$$2$$$: there are $$$24$$$ possible trees, for example with edges $$$(1-2)$$$, $$$(2-3)$$$, $$$(3-4)$$$, and $$$(4-5)$$$. Here the centroid is $$$3$$$.
Code:
MOD = 998244353
def modmul(x, y, c = 0):
return (x * y + c) % MOD
def inv(x):
# TODO: Your code here
MAX = 10 ** 6
fact = [1]
for i in range(1, MAX):
fact.append(modmul(i, fact[i-1]))
invfact = [1] * (MAX)
invfact[MAX - 1] = inv(fact[MAX - 1])
for i in range(MAX - 2, -1, -1):
invfact[i] = modmul(i + 1, invfact[i+1])
def comb(x, y):
return modmul(fact[x], modmul(invfact[y], invfact[x - y]))
def invcomb(x, y):
return modmul(invfact[x], modmul(fact[y], fact[x - y]))
def invs(x):
return modmul(fact[x - 1], invfact[x])
n = int(input())
out = [0] * n
for i in range((n + 1) // 2):
base = fact[n - 1]
frac = modmul(comb(n//2, i), invcomb(n - 1, i))
out[i] = modmul(base, frac)
rem = 0
for i in range(n - 1, -1, -1):
oldrem = rem
rem += modmul(out[i], invs(i))
out[i] -= oldrem
rem %= MOD
out[i] %= MOD
print(' '.join(map(str,out)))
|
MOD = 998244353
def modmul(x, y, c = 0):
return (x * y + c) % MOD
def inv(x):
{{completion}}
MAX = 10 ** 6
fact = [1]
for i in range(1, MAX):
fact.append(modmul(i, fact[i-1]))
invfact = [1] * (MAX)
invfact[MAX - 1] = inv(fact[MAX - 1])
for i in range(MAX - 2, -1, -1):
invfact[i] = modmul(i + 1, invfact[i+1])
def comb(x, y):
return modmul(fact[x], modmul(invfact[y], invfact[x - y]))
def invcomb(x, y):
return modmul(invfact[x], modmul(fact[y], fact[x - y]))
def invs(x):
return modmul(fact[x - 1], invfact[x])
n = int(input())
out = [0] * n
for i in range((n + 1) // 2):
base = fact[n - 1]
frac = modmul(comb(n//2, i), invcomb(n - 1, i))
out[i] = modmul(base, frac)
rem = 0
for i in range(n - 1, -1, -1):
oldrem = rem
rem += modmul(out[i], invs(i))
out[i] -= oldrem
rem %= MOD
out[i] %= MOD
print(' '.join(map(str,out)))
|
return pow(x, MOD - 2, MOD)
|
[{"input": "3", "output": ["1 1 0"]}, {"input": "5", "output": ["10 10 4 0 0"]}, {"input": "7", "output": ["276 276 132 36 0 0 0"]}]
|
block_completion_005083
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: A triple of points $$$i$$$, $$$j$$$ and $$$k$$$ on a coordinate line is called beautiful if $$$i < j < k$$$ and $$$k - i \le d$$$.You are given a set of points on a coordinate line, initially empty. You have to process queries of three types: add a point; remove a point; calculate the number of beautiful triples consisting of points belonging to the set.
Input Specification: The first line contains two integers $$$q$$$ and $$$d$$$ ($$$1 \le q, d \le 2 \cdot 10^5$$$) β the number of queries and the parameter for defining if a triple is beautiful, respectively. The second line contains $$$q$$$ integers $$$a_1, a_2, \dots, a_q$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$) denoting the queries. The integer $$$a_i$$$ denotes the $$$i$$$-th query in the following way: if the point $$$a_i$$$ belongs to the set, remove it; otherwise, add it; after adding or removing the point, print the number of beautiful triples.
Output Specification: For each query, print one integer β the number of beautiful triples after processing the respective query.
Code:
import sys
# https://codeforces.com/contest/1701/problem/F
MAXN = 200000
class SegmentTree:
def __init__(self):
self.lazy = []
self.v0 = []
self.v1 = []
self.v2 = []
self.active = []
for _ in range(4 * MAXN + 1):
self.lazy.append(0)
self.v0.append(1)
self.v1.append(0)
self.v2.append(0)
self.active.append(True)
self._init_active(1, 1, MAXN)
def _init_active(self, x, l, r):
if l == r:
self.active[x] = False
else:
m = (l + r) // 2
self._init_active(x * 2, l, m)
self._init_active(x * 2 + 1, m + 1, r)
self._reclac(x)
def _reclac(self, x):
self.v0[x] = 0
self.v1[x] = 0
self.v2[x] = 0
if self.active[x * 2]:
self.v0[x] += self.v0[x * 2]
self.v1[x] += self.v1[x * 2]
self.v2[x] += self.v2[x * 2]
if self.active[x * 2 + 1]:
self.v0[x] += self.v0[x * 2 + 1]
self.v1[x] += self.v1[x * 2 + 1]
self.v2[x] += self.v2[x * 2 + 1]
def _push(self, x, l, r):
la = self.lazy[x]
if la == 0:
return
if l != r:
self.v2[x * 2] = self.v2[x * 2] + 2 * la * self.v1[x * 2] + la * la * self.v0[x * 2]
self.v1[x * 2] += la * self.v0[x * 2]
self.v2[x * 2 + 1] = self.v2[x * 2 + 1] + 2 * la * self.v1[x * 2 + 1] + la * la * self.v0[x * 2 + 1]
self.v1[x * 2 + 1] += la * self.v0[x * 2 + 1]
self.lazy[x * 2] += la
self.lazy[x * 2 + 1] += la
self.lazy[x] = 0
def update(self, x, l, r, a, b, up: bool):
if r < a or b < l:
return
if a <= l and r <= b:
if up:
self.v2[x] = self.v2[x] + 2 * self.v1[x] + self.v0[x]
self.v1[x] += self.v0[x]
self.lazy[x] += 1
else:
# TODO: Your code here
return
m = (l + r) // 2
self._push(x, l, r)
self.update(x * 2, l, m, a, b, up)
self.update(x * 2 + 1, m + 1, r, a, b, up)
self._reclac(x)
def set_state(self, x, l, r, pos, up: bool):
if pos < l or r < pos:
return
if l == r:
self.active[x] = up
return
m = (l + r) // 2
self._push(x, l, r)
self.set_state(x * 2, l, m, pos, up)
self.set_state(x * 2 + 1, m + 1, r, pos, up)
self._reclac(x)
def solve():
q, d = map(int, input().split())
points = map(int, sys.stdin.readline().split())
tree = SegmentTree()
check = [0] * (MAXN + 1)
ans = []
for point in points:
if check[point]:
check[point] = 0
tree.update(1, 1, MAXN, max(1, point - d), point - 1, False)
tree.set_state(1, 1, MAXN, point, False)
else:
check[point] = 1
tree.update(1, 1, MAXN, max(1, point - d), point - 1, True)
tree.set_state(1, 1, MAXN, point, True)
v1 = tree.v1[1]
v2 = tree.v2[1]
ans.append((v2 - v1) // 2)
print('\n'.join(map(str, ans)))
if __name__ == '__main__':
solve()
|
import sys
# https://codeforces.com/contest/1701/problem/F
MAXN = 200000
class SegmentTree:
def __init__(self):
self.lazy = []
self.v0 = []
self.v1 = []
self.v2 = []
self.active = []
for _ in range(4 * MAXN + 1):
self.lazy.append(0)
self.v0.append(1)
self.v1.append(0)
self.v2.append(0)
self.active.append(True)
self._init_active(1, 1, MAXN)
def _init_active(self, x, l, r):
if l == r:
self.active[x] = False
else:
m = (l + r) // 2
self._init_active(x * 2, l, m)
self._init_active(x * 2 + 1, m + 1, r)
self._reclac(x)
def _reclac(self, x):
self.v0[x] = 0
self.v1[x] = 0
self.v2[x] = 0
if self.active[x * 2]:
self.v0[x] += self.v0[x * 2]
self.v1[x] += self.v1[x * 2]
self.v2[x] += self.v2[x * 2]
if self.active[x * 2 + 1]:
self.v0[x] += self.v0[x * 2 + 1]
self.v1[x] += self.v1[x * 2 + 1]
self.v2[x] += self.v2[x * 2 + 1]
def _push(self, x, l, r):
la = self.lazy[x]
if la == 0:
return
if l != r:
self.v2[x * 2] = self.v2[x * 2] + 2 * la * self.v1[x * 2] + la * la * self.v0[x * 2]
self.v1[x * 2] += la * self.v0[x * 2]
self.v2[x * 2 + 1] = self.v2[x * 2 + 1] + 2 * la * self.v1[x * 2 + 1] + la * la * self.v0[x * 2 + 1]
self.v1[x * 2 + 1] += la * self.v0[x * 2 + 1]
self.lazy[x * 2] += la
self.lazy[x * 2 + 1] += la
self.lazy[x] = 0
def update(self, x, l, r, a, b, up: bool):
if r < a or b < l:
return
if a <= l and r <= b:
if up:
self.v2[x] = self.v2[x] + 2 * self.v1[x] + self.v0[x]
self.v1[x] += self.v0[x]
self.lazy[x] += 1
else:
{{completion}}
return
m = (l + r) // 2
self._push(x, l, r)
self.update(x * 2, l, m, a, b, up)
self.update(x * 2 + 1, m + 1, r, a, b, up)
self._reclac(x)
def set_state(self, x, l, r, pos, up: bool):
if pos < l or r < pos:
return
if l == r:
self.active[x] = up
return
m = (l + r) // 2
self._push(x, l, r)
self.set_state(x * 2, l, m, pos, up)
self.set_state(x * 2 + 1, m + 1, r, pos, up)
self._reclac(x)
def solve():
q, d = map(int, input().split())
points = map(int, sys.stdin.readline().split())
tree = SegmentTree()
check = [0] * (MAXN + 1)
ans = []
for point in points:
if check[point]:
check[point] = 0
tree.update(1, 1, MAXN, max(1, point - d), point - 1, False)
tree.set_state(1, 1, MAXN, point, False)
else:
check[point] = 1
tree.update(1, 1, MAXN, max(1, point - d), point - 1, True)
tree.set_state(1, 1, MAXN, point, True)
v1 = tree.v1[1]
v2 = tree.v2[1]
ans.append((v2 - v1) // 2)
print('\n'.join(map(str, ans)))
if __name__ == '__main__':
solve()
|
self.v2[x] = self.v2[x] - 2 * self.v1[x] + self.v0[x]
self.v1[x] -= self.v0[x]
self.lazy[x] -= 1
|
[{"input": "7 5\n8 5 3 2 1 5 6", "output": ["0\n0\n1\n2\n5\n1\n5"]}]
|
block_completion_005215
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: A triple of points $$$i$$$, $$$j$$$ and $$$k$$$ on a coordinate line is called beautiful if $$$i < j < k$$$ and $$$k - i \le d$$$.You are given a set of points on a coordinate line, initially empty. You have to process queries of three types: add a point; remove a point; calculate the number of beautiful triples consisting of points belonging to the set.
Input Specification: The first line contains two integers $$$q$$$ and $$$d$$$ ($$$1 \le q, d \le 2 \cdot 10^5$$$) β the number of queries and the parameter for defining if a triple is beautiful, respectively. The second line contains $$$q$$$ integers $$$a_1, a_2, \dots, a_q$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$) denoting the queries. The integer $$$a_i$$$ denotes the $$$i$$$-th query in the following way: if the point $$$a_i$$$ belongs to the set, remove it; otherwise, add it; after adding or removing the point, print the number of beautiful triples.
Output Specification: For each query, print one integer β the number of beautiful triples after processing the respective query.
Code:
import sys
# https://codeforces.com/contest/1701/problem/F
MAXN = 200000
class SegmentTree:
def __init__(self):
self.lazy = []
self.v0 = []
self.v1 = []
self.v2 = []
self.active = []
for _ in range(4 * MAXN + 1):
self.lazy.append(0)
self.v0.append(1)
self.v1.append(0)
self.v2.append(0)
self.active.append(True)
self._init_active(1, 1, MAXN)
def _init_active(self, x, l, r):
if l == r:
self.active[x] = False
else:
m = (l + r) // 2
self._init_active(x * 2, l, m)
self._init_active(x * 2 + 1, m + 1, r)
self._reclac(x)
def _reclac(self, x):
self.v0[x] = 0
self.v1[x] = 0
self.v2[x] = 0
if self.active[x * 2]:
self.v0[x] += self.v0[x * 2]
self.v1[x] += self.v1[x * 2]
self.v2[x] += self.v2[x * 2]
if self.active[x * 2 + 1]:
self.v0[x] += self.v0[x * 2 + 1]
self.v1[x] += self.v1[x * 2 + 1]
self.v2[x] += self.v2[x * 2 + 1]
def _push(self, x, l, r):
la = self.lazy[x]
if la == 0:
return
if l != r:
self.v2[x * 2] = self.v2[x * 2] + 2 * la * self.v1[x * 2] + la * la * self.v0[x * 2]
self.v1[x * 2] += la * self.v0[x * 2]
self.v2[x * 2 + 1] = self.v2[x * 2 + 1] + 2 * la * self.v1[x * 2 + 1] + la * la * self.v0[x * 2 + 1]
self.v1[x * 2 + 1] += la * self.v0[x * 2 + 1]
self.lazy[x * 2] += la
self.lazy[x * 2 + 1] += la
self.lazy[x] = 0
def update(self, x, l, r, a, b, up: bool):
if r < a or b < l:
return
if a <= l and r <= b:
if up:
# TODO: Your code here
else:
self.v2[x] = self.v2[x] - 2 * self.v1[x] + self.v0[x]
self.v1[x] -= self.v0[x]
self.lazy[x] -= 1
return
m = (l + r) // 2
self._push(x, l, r)
self.update(x * 2, l, m, a, b, up)
self.update(x * 2 + 1, m + 1, r, a, b, up)
self._reclac(x)
def set_state(self, x, l, r, pos, up: bool):
if pos < l or r < pos:
return
if l == r:
self.active[x] = up
return
m = (l + r) // 2
self._push(x, l, r)
self.set_state(x * 2, l, m, pos, up)
self.set_state(x * 2 + 1, m + 1, r, pos, up)
self._reclac(x)
def solve():
q, d = map(int, input().split())
points = map(int, sys.stdin.readline().split())
tree = SegmentTree()
check = [0] * (MAXN + 1)
ans = []
for point in points:
if check[point]:
check[point] = 0
tree.update(1, 1, MAXN, max(1, point - d), point - 1, False)
tree.set_state(1, 1, MAXN, point, False)
else:
check[point] = 1
tree.update(1, 1, MAXN, max(1, point - d), point - 1, True)
tree.set_state(1, 1, MAXN, point, True)
v1 = tree.v1[1]
v2 = tree.v2[1]
ans.append((v2 - v1) // 2)
print('\n'.join(map(str, ans)))
if __name__ == '__main__':
solve()
|
import sys
# https://codeforces.com/contest/1701/problem/F
MAXN = 200000
class SegmentTree:
def __init__(self):
self.lazy = []
self.v0 = []
self.v1 = []
self.v2 = []
self.active = []
for _ in range(4 * MAXN + 1):
self.lazy.append(0)
self.v0.append(1)
self.v1.append(0)
self.v2.append(0)
self.active.append(True)
self._init_active(1, 1, MAXN)
def _init_active(self, x, l, r):
if l == r:
self.active[x] = False
else:
m = (l + r) // 2
self._init_active(x * 2, l, m)
self._init_active(x * 2 + 1, m + 1, r)
self._reclac(x)
def _reclac(self, x):
self.v0[x] = 0
self.v1[x] = 0
self.v2[x] = 0
if self.active[x * 2]:
self.v0[x] += self.v0[x * 2]
self.v1[x] += self.v1[x * 2]
self.v2[x] += self.v2[x * 2]
if self.active[x * 2 + 1]:
self.v0[x] += self.v0[x * 2 + 1]
self.v1[x] += self.v1[x * 2 + 1]
self.v2[x] += self.v2[x * 2 + 1]
def _push(self, x, l, r):
la = self.lazy[x]
if la == 0:
return
if l != r:
self.v2[x * 2] = self.v2[x * 2] + 2 * la * self.v1[x * 2] + la * la * self.v0[x * 2]
self.v1[x * 2] += la * self.v0[x * 2]
self.v2[x * 2 + 1] = self.v2[x * 2 + 1] + 2 * la * self.v1[x * 2 + 1] + la * la * self.v0[x * 2 + 1]
self.v1[x * 2 + 1] += la * self.v0[x * 2 + 1]
self.lazy[x * 2] += la
self.lazy[x * 2 + 1] += la
self.lazy[x] = 0
def update(self, x, l, r, a, b, up: bool):
if r < a or b < l:
return
if a <= l and r <= b:
if up:
{{completion}}
else:
self.v2[x] = self.v2[x] - 2 * self.v1[x] + self.v0[x]
self.v1[x] -= self.v0[x]
self.lazy[x] -= 1
return
m = (l + r) // 2
self._push(x, l, r)
self.update(x * 2, l, m, a, b, up)
self.update(x * 2 + 1, m + 1, r, a, b, up)
self._reclac(x)
def set_state(self, x, l, r, pos, up: bool):
if pos < l or r < pos:
return
if l == r:
self.active[x] = up
return
m = (l + r) // 2
self._push(x, l, r)
self.set_state(x * 2, l, m, pos, up)
self.set_state(x * 2 + 1, m + 1, r, pos, up)
self._reclac(x)
def solve():
q, d = map(int, input().split())
points = map(int, sys.stdin.readline().split())
tree = SegmentTree()
check = [0] * (MAXN + 1)
ans = []
for point in points:
if check[point]:
check[point] = 0
tree.update(1, 1, MAXN, max(1, point - d), point - 1, False)
tree.set_state(1, 1, MAXN, point, False)
else:
check[point] = 1
tree.update(1, 1, MAXN, max(1, point - d), point - 1, True)
tree.set_state(1, 1, MAXN, point, True)
v1 = tree.v1[1]
v2 = tree.v2[1]
ans.append((v2 - v1) // 2)
print('\n'.join(map(str, ans)))
if __name__ == '__main__':
solve()
|
self.v2[x] = self.v2[x] + 2 * self.v1[x] + self.v0[x]
self.v1[x] += self.v0[x]
self.lazy[x] += 1
|
[{"input": "7 5\n8 5 3 2 1 5 6", "output": ["0\n0\n1\n2\n5\n1\n5"]}]
|
block_completion_005216
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: A triple of points $$$i$$$, $$$j$$$ and $$$k$$$ on a coordinate line is called beautiful if $$$i < j < k$$$ and $$$k - i \le d$$$.You are given a set of points on a coordinate line, initially empty. You have to process queries of three types: add a point; remove a point; calculate the number of beautiful triples consisting of points belonging to the set.
Input Specification: The first line contains two integers $$$q$$$ and $$$d$$$ ($$$1 \le q, d \le 2 \cdot 10^5$$$) β the number of queries and the parameter for defining if a triple is beautiful, respectively. The second line contains $$$q$$$ integers $$$a_1, a_2, \dots, a_q$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$) denoting the queries. The integer $$$a_i$$$ denotes the $$$i$$$-th query in the following way: if the point $$$a_i$$$ belongs to the set, remove it; otherwise, add it; after adding or removing the point, print the number of beautiful triples.
Output Specification: For each query, print one integer β the number of beautiful triples after processing the respective query.
Code:
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
# TODO: Your code here
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")
class LazySegmentTree():
def __init__(self, n, op, e, mapping, composition, id):
self.n = n
self.op = op
self.e = e
self.mapping = mapping
self.composition = composition
self.id = id
self.log = (n - 1).bit_length()
self.size = 1 << self.log
self.data = [e] * (2 * self.size)
self.lazy = [id] * self.size
def update(self, k):
self.data[k] = self.op(self.data[2 * k], self.data[2 * k + 1])
def all_apply(self, k, f):
self.data[k] = self.mapping(f, self.data[k])
if k < self.size:
self.lazy[k] = self.composition(f, self.lazy[k])
def push(self, k):
self.all_apply(2 * k, self.lazy[k])
self.all_apply(2 * k + 1, self.lazy[k])
self.lazy[k] = self.id
def build(self, arr):
# assert len(arr) == self.n
for i, a in enumerate(arr):
self.data[self.size + i] = a
for i in range(self.size - 1, 0, -1):
self.update(i)
def set(self, p, x):
# assert 0 <= p < self.n
p += self.size
for i in range(self.log, 0, -1):
self.push(p >> i)
self.data[p] = x
for i in range(1, self.log + 1):
self.update(p >> i)
def get(self, p):
# assert 0 <= p < self.n
p += self.size
for i in range(self.log, 0, -1):
self.push(p >> i)
return self.data[p]
def prod(self, l, r):
# assert 0 <= l <= r <= self.n
if l == r: return self.e
l += self.size
r += self.size
for i in range(self.log, 0, -1):
if ((l >> i) << i) != l: self.push(l >> i)
if ((r >> i) << i) != r: self.push(r >> i)
sml = smr = self.e
while l < r:
if l & 1:
sml = self.op(sml, self.data[l])
l += 1
if r & 1:
r -= 1
smr = self.op(self.data[r], smr)
l >>= 1
r >>= 1
return self.op(sml, smr)
def all_prod(self):
return self.data[1]
def apply(self, p, f):
# assert 0 <= p < self.n
p += self.size
for i in range(self.log, 0, -1):
self.push(p >> i)
self.data[p] = self.mapping(f, self.data[p])
for i in range(1, self.log + 1):
self.update(p >> i)
def range_apply(self, l, r, f):
# assert 0 <= l <= r <= self.n
if l == r: return
l += self.size
r += self.size
for i in range(self.log, 0, -1):
if ((l >> i) << i) != l: self.push(l >> i)
if ((r >> i) << i) != r: self.push((r - 1) >> i)
l2 = l
r2 = r
while l < r:
if l & 1:
self.all_apply(l, f)
l += 1
if r & 1:
r -= 1
self.all_apply(r, f)
l >>= 1
r >>= 1
l = l2
r = r2
for i in range(1, self.log + 1):
if ((l >> i) << i) != l: self.update(l >> i)
if ((r >> i) << i) != r: self.update((r - 1) >> i)
n = 2*10**5+1
q, d = map(int, input().split())
arr = list(map(int, input().split()))
v = [0]*n
def op(x, y):
return [x[0]+y[0], x[1]+y[1], x[2]+y[2], x[3]]
def mapping(k, x):
return [x[0], k*x[0]+x[1], k*k*x[0]+2*k*x[1]+x[2], x[3]+k]
def composition(f, g):
return f+g
e = [0, 0, 0, 0]
id = 0
st = LazySegmentTree(n, op, e, mapping, composition, id)
st.build([[0, 0, 0, 0] for i in range(n)])
for x in arr:
v[x] ^= 1
m = st.get(x)[3]
if v[x]:
st.range_apply(x+1, min(x+d+1, n), 1)
st.set(x, [1, m, m*m, m])
else:
st.range_apply(x+1, min(x+d+1, n), -1)
st.set(x, [0, 0, 0, m])
a = st.all_prod()
print((a[2]-a[1])//2)
|
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
{{completion}}
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")
class LazySegmentTree():
def __init__(self, n, op, e, mapping, composition, id):
self.n = n
self.op = op
self.e = e
self.mapping = mapping
self.composition = composition
self.id = id
self.log = (n - 1).bit_length()
self.size = 1 << self.log
self.data = [e] * (2 * self.size)
self.lazy = [id] * self.size
def update(self, k):
self.data[k] = self.op(self.data[2 * k], self.data[2 * k + 1])
def all_apply(self, k, f):
self.data[k] = self.mapping(f, self.data[k])
if k < self.size:
self.lazy[k] = self.composition(f, self.lazy[k])
def push(self, k):
self.all_apply(2 * k, self.lazy[k])
self.all_apply(2 * k + 1, self.lazy[k])
self.lazy[k] = self.id
def build(self, arr):
# assert len(arr) == self.n
for i, a in enumerate(arr):
self.data[self.size + i] = a
for i in range(self.size - 1, 0, -1):
self.update(i)
def set(self, p, x):
# assert 0 <= p < self.n
p += self.size
for i in range(self.log, 0, -1):
self.push(p >> i)
self.data[p] = x
for i in range(1, self.log + 1):
self.update(p >> i)
def get(self, p):
# assert 0 <= p < self.n
p += self.size
for i in range(self.log, 0, -1):
self.push(p >> i)
return self.data[p]
def prod(self, l, r):
# assert 0 <= l <= r <= self.n
if l == r: return self.e
l += self.size
r += self.size
for i in range(self.log, 0, -1):
if ((l >> i) << i) != l: self.push(l >> i)
if ((r >> i) << i) != r: self.push(r >> i)
sml = smr = self.e
while l < r:
if l & 1:
sml = self.op(sml, self.data[l])
l += 1
if r & 1:
r -= 1
smr = self.op(self.data[r], smr)
l >>= 1
r >>= 1
return self.op(sml, smr)
def all_prod(self):
return self.data[1]
def apply(self, p, f):
# assert 0 <= p < self.n
p += self.size
for i in range(self.log, 0, -1):
self.push(p >> i)
self.data[p] = self.mapping(f, self.data[p])
for i in range(1, self.log + 1):
self.update(p >> i)
def range_apply(self, l, r, f):
# assert 0 <= l <= r <= self.n
if l == r: return
l += self.size
r += self.size
for i in range(self.log, 0, -1):
if ((l >> i) << i) != l: self.push(l >> i)
if ((r >> i) << i) != r: self.push((r - 1) >> i)
l2 = l
r2 = r
while l < r:
if l & 1:
self.all_apply(l, f)
l += 1
if r & 1:
r -= 1
self.all_apply(r, f)
l >>= 1
r >>= 1
l = l2
r = r2
for i in range(1, self.log + 1):
if ((l >> i) << i) != l: self.update(l >> i)
if ((r >> i) << i) != r: self.update((r - 1) >> i)
n = 2*10**5+1
q, d = map(int, input().split())
arr = list(map(int, input().split()))
v = [0]*n
def op(x, y):
return [x[0]+y[0], x[1]+y[1], x[2]+y[2], x[3]]
def mapping(k, x):
return [x[0], k*x[0]+x[1], k*k*x[0]+2*k*x[1]+x[2], x[3]+k]
def composition(f, g):
return f+g
e = [0, 0, 0, 0]
id = 0
st = LazySegmentTree(n, op, e, mapping, composition, id)
st.build([[0, 0, 0, 0] for i in range(n)])
for x in arr:
v[x] ^= 1
m = st.get(x)[3]
if v[x]:
st.range_apply(x+1, min(x+d+1, n), 1)
st.set(x, [1, m, m*m, m])
else:
st.range_apply(x+1, min(x+d+1, n), -1)
st.set(x, [0, 0, 0, m])
a = st.all_prod()
print((a[2]-a[1])//2)
|
break
|
[{"input": "7 5\n8 5 3 2 1 5 6", "output": ["0\n0\n1\n2\n5\n1\n5"]}]
|
block_completion_005217
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: A triple of points $$$i$$$, $$$j$$$ and $$$k$$$ on a coordinate line is called beautiful if $$$i < j < k$$$ and $$$k - i \le d$$$.You are given a set of points on a coordinate line, initially empty. You have to process queries of three types: add a point; remove a point; calculate the number of beautiful triples consisting of points belonging to the set.
Input Specification: The first line contains two integers $$$q$$$ and $$$d$$$ ($$$1 \le q, d \le 2 \cdot 10^5$$$) β the number of queries and the parameter for defining if a triple is beautiful, respectively. The second line contains $$$q$$$ integers $$$a_1, a_2, \dots, a_q$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$) denoting the queries. The integer $$$a_i$$$ denotes the $$$i$$$-th query in the following way: if the point $$$a_i$$$ belongs to the set, remove it; otherwise, add it; after adding or removing the point, print the number of beautiful triples.
Output Specification: For each query, print one integer β the number of beautiful triples after processing the respective query.
Code:
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
class LazySegmentTree():
def __init__(self, n, op, e, mapping, composition, id):
self.n = n
self.op = op
self.e = e
self.mapping = mapping
self.composition = composition
self.id = id
self.log = (n - 1).bit_length()
self.size = 1 << self.log
self.data = [e] * (2 * self.size)
self.lazy = [id] * self.size
def update(self, k):
self.data[k] = self.op(self.data[2 * k], self.data[2 * k + 1])
def all_apply(self, k, f):
self.data[k] = self.mapping(f, self.data[k])
if k < self.size:
self.lazy[k] = self.composition(f, self.lazy[k])
def push(self, k):
self.all_apply(2 * k, self.lazy[k])
self.all_apply(2 * k + 1, self.lazy[k])
self.lazy[k] = self.id
def build(self, arr):
# assert len(arr) == self.n
for i, a in enumerate(arr):
self.data[self.size + i] = a
for i in range(self.size - 1, 0, -1):
self.update(i)
def set(self, p, x):
# assert 0 <= p < self.n
p += self.size
for i in range(self.log, 0, -1):
self.push(p >> i)
self.data[p] = x
for i in range(1, self.log + 1):
self.update(p >> i)
def get(self, p):
# assert 0 <= p < self.n
p += self.size
for i in range(self.log, 0, -1):
self.push(p >> i)
return self.data[p]
def prod(self, l, r):
# assert 0 <= l <= r <= self.n
if l == r: return self.e
l += self.size
r += self.size
for i in range(self.log, 0, -1):
if ((l >> i) << i) != l: # TODO: Your code here
if ((r >> i) << i) != r: self.push(r >> i)
sml = smr = self.e
while l < r:
if l & 1:
sml = self.op(sml, self.data[l])
l += 1
if r & 1:
r -= 1
smr = self.op(self.data[r], smr)
l >>= 1
r >>= 1
return self.op(sml, smr)
def all_prod(self):
return self.data[1]
def apply(self, p, f):
# assert 0 <= p < self.n
p += self.size
for i in range(self.log, 0, -1):
self.push(p >> i)
self.data[p] = self.mapping(f, self.data[p])
for i in range(1, self.log + 1):
self.update(p >> i)
def range_apply(self, l, r, f):
# assert 0 <= l <= r <= self.n
if l == r: return
l += self.size
r += self.size
for i in range(self.log, 0, -1):
if ((l >> i) << i) != l: self.push(l >> i)
if ((r >> i) << i) != r: self.push((r - 1) >> i)
l2 = l
r2 = r
while l < r:
if l & 1:
self.all_apply(l, f)
l += 1
if r & 1:
r -= 1
self.all_apply(r, f)
l >>= 1
r >>= 1
l = l2
r = r2
for i in range(1, self.log + 1):
if ((l >> i) << i) != l: self.update(l >> i)
if ((r >> i) << i) != r: self.update((r - 1) >> i)
n = 2*10**5+1
q, d = map(int, input().split())
arr = list(map(int, input().split()))
v = [0]*n
def op(x, y):
return [x[0]+y[0], x[1]+y[1], x[2]+y[2], x[3]]
def mapping(k, x):
return [x[0], k*x[0]+x[1], k*k*x[0]+2*k*x[1]+x[2], x[3]+k]
def composition(f, g):
return f+g
e = [0, 0, 0, 0]
id = 0
st = LazySegmentTree(n, op, e, mapping, composition, id)
st.build([[0, 0, 0, 0] for i in range(n)])
for x in arr:
v[x] ^= 1
m = st.get(x)[3]
if v[x]:
st.range_apply(x+1, min(x+d+1, n), 1)
st.set(x, [1, m, m*m, m])
else:
st.range_apply(x+1, min(x+d+1, n), -1)
st.set(x, [0, 0, 0, m])
a = st.all_prod()
print((a[2]-a[1])//2)
|
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
class LazySegmentTree():
def __init__(self, n, op, e, mapping, composition, id):
self.n = n
self.op = op
self.e = e
self.mapping = mapping
self.composition = composition
self.id = id
self.log = (n - 1).bit_length()
self.size = 1 << self.log
self.data = [e] * (2 * self.size)
self.lazy = [id] * self.size
def update(self, k):
self.data[k] = self.op(self.data[2 * k], self.data[2 * k + 1])
def all_apply(self, k, f):
self.data[k] = self.mapping(f, self.data[k])
if k < self.size:
self.lazy[k] = self.composition(f, self.lazy[k])
def push(self, k):
self.all_apply(2 * k, self.lazy[k])
self.all_apply(2 * k + 1, self.lazy[k])
self.lazy[k] = self.id
def build(self, arr):
# assert len(arr) == self.n
for i, a in enumerate(arr):
self.data[self.size + i] = a
for i in range(self.size - 1, 0, -1):
self.update(i)
def set(self, p, x):
# assert 0 <= p < self.n
p += self.size
for i in range(self.log, 0, -1):
self.push(p >> i)
self.data[p] = x
for i in range(1, self.log + 1):
self.update(p >> i)
def get(self, p):
# assert 0 <= p < self.n
p += self.size
for i in range(self.log, 0, -1):
self.push(p >> i)
return self.data[p]
def prod(self, l, r):
# assert 0 <= l <= r <= self.n
if l == r: return self.e
l += self.size
r += self.size
for i in range(self.log, 0, -1):
if ((l >> i) << i) != l: {{completion}}
if ((r >> i) << i) != r: self.push(r >> i)
sml = smr = self.e
while l < r:
if l & 1:
sml = self.op(sml, self.data[l])
l += 1
if r & 1:
r -= 1
smr = self.op(self.data[r], smr)
l >>= 1
r >>= 1
return self.op(sml, smr)
def all_prod(self):
return self.data[1]
def apply(self, p, f):
# assert 0 <= p < self.n
p += self.size
for i in range(self.log, 0, -1):
self.push(p >> i)
self.data[p] = self.mapping(f, self.data[p])
for i in range(1, self.log + 1):
self.update(p >> i)
def range_apply(self, l, r, f):
# assert 0 <= l <= r <= self.n
if l == r: return
l += self.size
r += self.size
for i in range(self.log, 0, -1):
if ((l >> i) << i) != l: self.push(l >> i)
if ((r >> i) << i) != r: self.push((r - 1) >> i)
l2 = l
r2 = r
while l < r:
if l & 1:
self.all_apply(l, f)
l += 1
if r & 1:
r -= 1
self.all_apply(r, f)
l >>= 1
r >>= 1
l = l2
r = r2
for i in range(1, self.log + 1):
if ((l >> i) << i) != l: self.update(l >> i)
if ((r >> i) << i) != r: self.update((r - 1) >> i)
n = 2*10**5+1
q, d = map(int, input().split())
arr = list(map(int, input().split()))
v = [0]*n
def op(x, y):
return [x[0]+y[0], x[1]+y[1], x[2]+y[2], x[3]]
def mapping(k, x):
return [x[0], k*x[0]+x[1], k*k*x[0]+2*k*x[1]+x[2], x[3]+k]
def composition(f, g):
return f+g
e = [0, 0, 0, 0]
id = 0
st = LazySegmentTree(n, op, e, mapping, composition, id)
st.build([[0, 0, 0, 0] for i in range(n)])
for x in arr:
v[x] ^= 1
m = st.get(x)[3]
if v[x]:
st.range_apply(x+1, min(x+d+1, n), 1)
st.set(x, [1, m, m*m, m])
else:
st.range_apply(x+1, min(x+d+1, n), -1)
st.set(x, [0, 0, 0, m])
a = st.all_prod()
print((a[2]-a[1])//2)
|
self.push(l >> i)
|
[{"input": "7 5\n8 5 3 2 1 5 6", "output": ["0\n0\n1\n2\n5\n1\n5"]}]
|
block_completion_005218
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You like the card board game "Set". Each card contains $$$k$$$ features, each of which is equal to a value from the set $$$\{0, 1, 2\}$$$. The deck contains all possible variants of cards, that is, there are $$$3^k$$$ different cards in total.A feature for three cards is called good if it is the same for these cards or pairwise distinct. Three cards are called a set if all $$$k$$$ features are good for them.For example, the cards $$$(0, 0, 0)$$$, $$$(0, 2, 1)$$$, and $$$(0, 1, 2)$$$ form a set, but the cards $$$(0, 2, 2)$$$, $$$(2, 1, 2)$$$, and $$$(1, 2, 0)$$$ do not, as, for example, the last feature is not good.A group of five cards is called a meta-set, if there is strictly more than one set among them. How many meta-sets there are among given $$$n$$$ distinct cards?
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^3$$$, $$$1 \le k \le 20$$$) β the number of cards on a table and the number of card features. The description of the cards follows in the next $$$n$$$ lines. Each line describing a card contains $$$k$$$ integers $$$c_{i, 1}, c_{i, 2}, \ldots, c_{i, k}$$$ ($$$0 \le c_{i, j} \le 2$$$)Β β card features. It is guaranteed that all cards are distinct.
Output Specification: Output one integer β the number of meta-sets.
Notes: NoteLet's draw the cards indicating the first four features. The first feature will indicate the number of objects on a card: $$$1$$$, $$$2$$$, $$$3$$$. The second one is the color: red, green, purple. The third is the shape: oval, diamond, squiggle. The fourth is filling: open, striped, solid.You can see the first three tests below. For the first two tests, the meta-sets are highlighted.In the first test, the only meta-set is the five cards $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$. The sets in it are the triples $$$(0000,\ 0001,\ 0002)$$$ and $$$(0000,\ 0010,\ 0020)$$$. Also, a set is the triple $$$(0100,\ 1000,\ 2200)$$$ which does not belong to any meta-set. In the second test, the following groups of five cards are meta-sets: $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$, $$$(0000,\ 0001,\ 0002,\ 0100,\ 0200)$$$, $$$(0000,\ 0010,\ 0020,\ 0100,\ 0200)$$$. In there third test, there are $$$54$$$ meta-sets.
Code:
n,k = map(int,input().split())
ns = set()
for _ in range(n):
# TODO: Your code here
arr = [[tuple((6-v1[i]-v2[i])%3 for i in range(k)) in ns for v1 in ns] for v2 in ns]
ans = 0
for i in range(n):
s = sum(arr[i])-2
ans += s*s//8
print(ans)
|
n,k = map(int,input().split())
ns = set()
for _ in range(n):
{{completion}}
arr = [[tuple((6-v1[i]-v2[i])%3 for i in range(k)) in ns for v1 in ns] for v2 in ns]
ans = 0
for i in range(n):
s = sum(arr[i])-2
ans += s*s//8
print(ans)
|
s = tuple(int(v) for v in input().split())
ns.add(s)
|
[{"input": "8 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n1 0 0 0\n2 2 0 0", "output": ["1"]}, {"input": "7 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n0 2 0 0", "output": ["3"]}, {"input": "9 2\n0 0\n0 1\n0 2\n1 0\n1 1\n1 2\n2 0\n2 1\n2 2", "output": ["54"]}, {"input": "20 4\n0 2 0 0\n0 2 2 2\n0 2 2 1\n0 2 0 1\n1 2 2 0\n1 2 1 0\n1 2 2 1\n1 2 0 1\n1 1 2 2\n1 1 0 2\n1 1 2 1\n1 1 1 1\n2 1 2 0\n2 1 1 2\n2 1 2 1\n2 1 1 1\n0 1 1 2\n0 0 1 0\n2 2 0 0\n2 0 0 2", "output": ["0"]}]
|
block_completion_005312
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You like the card board game "Set". Each card contains $$$k$$$ features, each of which is equal to a value from the set $$$\{0, 1, 2\}$$$. The deck contains all possible variants of cards, that is, there are $$$3^k$$$ different cards in total.A feature for three cards is called good if it is the same for these cards or pairwise distinct. Three cards are called a set if all $$$k$$$ features are good for them.For example, the cards $$$(0, 0, 0)$$$, $$$(0, 2, 1)$$$, and $$$(0, 1, 2)$$$ form a set, but the cards $$$(0, 2, 2)$$$, $$$(2, 1, 2)$$$, and $$$(1, 2, 0)$$$ do not, as, for example, the last feature is not good.A group of five cards is called a meta-set, if there is strictly more than one set among them. How many meta-sets there are among given $$$n$$$ distinct cards?
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^3$$$, $$$1 \le k \le 20$$$) β the number of cards on a table and the number of card features. The description of the cards follows in the next $$$n$$$ lines. Each line describing a card contains $$$k$$$ integers $$$c_{i, 1}, c_{i, 2}, \ldots, c_{i, k}$$$ ($$$0 \le c_{i, j} \le 2$$$)Β β card features. It is guaranteed that all cards are distinct.
Output Specification: Output one integer β the number of meta-sets.
Notes: NoteLet's draw the cards indicating the first four features. The first feature will indicate the number of objects on a card: $$$1$$$, $$$2$$$, $$$3$$$. The second one is the color: red, green, purple. The third is the shape: oval, diamond, squiggle. The fourth is filling: open, striped, solid.You can see the first three tests below. For the first two tests, the meta-sets are highlighted.In the first test, the only meta-set is the five cards $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$. The sets in it are the triples $$$(0000,\ 0001,\ 0002)$$$ and $$$(0000,\ 0010,\ 0020)$$$. Also, a set is the triple $$$(0100,\ 1000,\ 2200)$$$ which does not belong to any meta-set. In the second test, the following groups of five cards are meta-sets: $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$, $$$(0000,\ 0001,\ 0002,\ 0100,\ 0200)$$$, $$$(0000,\ 0010,\ 0020,\ 0100,\ 0200)$$$. In there third test, there are $$$54$$$ meta-sets.
Code:
n,k = map(int,input().split())
ns = set()
for _ in range(n):
s = tuple(int(v) for v in input().split())
ns.add(s)
arr = [[tuple((6-v1[i]-v2[i])%3 for i in range(k)) in ns for v1 in ns] for v2 in ns]
ans = 0
for i in range(n):
# TODO: Your code here
print(ans)
|
n,k = map(int,input().split())
ns = set()
for _ in range(n):
s = tuple(int(v) for v in input().split())
ns.add(s)
arr = [[tuple((6-v1[i]-v2[i])%3 for i in range(k)) in ns for v1 in ns] for v2 in ns]
ans = 0
for i in range(n):
{{completion}}
print(ans)
|
s = sum(arr[i])-2
ans += s*s//8
|
[{"input": "8 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n1 0 0 0\n2 2 0 0", "output": ["1"]}, {"input": "7 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n0 2 0 0", "output": ["3"]}, {"input": "9 2\n0 0\n0 1\n0 2\n1 0\n1 1\n1 2\n2 0\n2 1\n2 2", "output": ["54"]}, {"input": "20 4\n0 2 0 0\n0 2 2 2\n0 2 2 1\n0 2 0 1\n1 2 2 0\n1 2 1 0\n1 2 2 1\n1 2 0 1\n1 1 2 2\n1 1 0 2\n1 1 2 1\n1 1 1 1\n2 1 2 0\n2 1 1 2\n2 1 2 1\n2 1 1 1\n0 1 1 2\n0 0 1 0\n2 2 0 0\n2 0 0 2", "output": ["0"]}]
|
block_completion_005313
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You like the card board game "Set". Each card contains $$$k$$$ features, each of which is equal to a value from the set $$$\{0, 1, 2\}$$$. The deck contains all possible variants of cards, that is, there are $$$3^k$$$ different cards in total.A feature for three cards is called good if it is the same for these cards or pairwise distinct. Three cards are called a set if all $$$k$$$ features are good for them.For example, the cards $$$(0, 0, 0)$$$, $$$(0, 2, 1)$$$, and $$$(0, 1, 2)$$$ form a set, but the cards $$$(0, 2, 2)$$$, $$$(2, 1, 2)$$$, and $$$(1, 2, 0)$$$ do not, as, for example, the last feature is not good.A group of five cards is called a meta-set, if there is strictly more than one set among them. How many meta-sets there are among given $$$n$$$ distinct cards?
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^3$$$, $$$1 \le k \le 20$$$) β the number of cards on a table and the number of card features. The description of the cards follows in the next $$$n$$$ lines. Each line describing a card contains $$$k$$$ integers $$$c_{i, 1}, c_{i, 2}, \ldots, c_{i, k}$$$ ($$$0 \le c_{i, j} \le 2$$$)Β β card features. It is guaranteed that all cards are distinct.
Output Specification: Output one integer β the number of meta-sets.
Notes: NoteLet's draw the cards indicating the first four features. The first feature will indicate the number of objects on a card: $$$1$$$, $$$2$$$, $$$3$$$. The second one is the color: red, green, purple. The third is the shape: oval, diamond, squiggle. The fourth is filling: open, striped, solid.You can see the first three tests below. For the first two tests, the meta-sets are highlighted.In the first test, the only meta-set is the five cards $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$. The sets in it are the triples $$$(0000,\ 0001,\ 0002)$$$ and $$$(0000,\ 0010,\ 0020)$$$. Also, a set is the triple $$$(0100,\ 1000,\ 2200)$$$ which does not belong to any meta-set. In the second test, the following groups of five cards are meta-sets: $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$, $$$(0000,\ 0001,\ 0002,\ 0100,\ 0200)$$$, $$$(0000,\ 0010,\ 0020,\ 0100,\ 0200)$$$. In there third test, there are $$$54$$$ meta-sets.
Code:
from sys import stdin
def missing(c1, c2):
c3 = []
for i in range(len(c1)):
if c1[i] == c2[i]:
c3.append(c1[i])
else:
c3.append(next(iter({"0", "1", "2"}.difference({c1[i], c2[i]}))))
return "".join(c3)
def solve():
n, k = map(int, stdin.readline().split())
cards = [stdin.readline().strip().replace(" ", "") for i in range(n)]
off1 = {c:0 for c in cards}
for i in range(n):
for j in range(i+1, n):
m = missing(cards[i], cards[j])
if m in off1:
# TODO: Your code here
print(sum(i*(i-1)//2 for i in off1.values()))
solve()
|
from sys import stdin
def missing(c1, c2):
c3 = []
for i in range(len(c1)):
if c1[i] == c2[i]:
c3.append(c1[i])
else:
c3.append(next(iter({"0", "1", "2"}.difference({c1[i], c2[i]}))))
return "".join(c3)
def solve():
n, k = map(int, stdin.readline().split())
cards = [stdin.readline().strip().replace(" ", "") for i in range(n)]
off1 = {c:0 for c in cards}
for i in range(n):
for j in range(i+1, n):
m = missing(cards[i], cards[j])
if m in off1:
{{completion}}
print(sum(i*(i-1)//2 for i in off1.values()))
solve()
|
off1[m] += 1
|
[{"input": "8 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n1 0 0 0\n2 2 0 0", "output": ["1"]}, {"input": "7 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n0 2 0 0", "output": ["3"]}, {"input": "9 2\n0 0\n0 1\n0 2\n1 0\n1 1\n1 2\n2 0\n2 1\n2 2", "output": ["54"]}, {"input": "20 4\n0 2 0 0\n0 2 2 2\n0 2 2 1\n0 2 0 1\n1 2 2 0\n1 2 1 0\n1 2 2 1\n1 2 0 1\n1 1 2 2\n1 1 0 2\n1 1 2 1\n1 1 1 1\n2 1 2 0\n2 1 1 2\n2 1 2 1\n2 1 1 1\n0 1 1 2\n0 0 1 0\n2 2 0 0\n2 0 0 2", "output": ["0"]}]
|
block_completion_005314
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You like the card board game "Set". Each card contains $$$k$$$ features, each of which is equal to a value from the set $$$\{0, 1, 2\}$$$. The deck contains all possible variants of cards, that is, there are $$$3^k$$$ different cards in total.A feature for three cards is called good if it is the same for these cards or pairwise distinct. Three cards are called a set if all $$$k$$$ features are good for them.For example, the cards $$$(0, 0, 0)$$$, $$$(0, 2, 1)$$$, and $$$(0, 1, 2)$$$ form a set, but the cards $$$(0, 2, 2)$$$, $$$(2, 1, 2)$$$, and $$$(1, 2, 0)$$$ do not, as, for example, the last feature is not good.A group of five cards is called a meta-set, if there is strictly more than one set among them. How many meta-sets there are among given $$$n$$$ distinct cards?
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^3$$$, $$$1 \le k \le 20$$$) β the number of cards on a table and the number of card features. The description of the cards follows in the next $$$n$$$ lines. Each line describing a card contains $$$k$$$ integers $$$c_{i, 1}, c_{i, 2}, \ldots, c_{i, k}$$$ ($$$0 \le c_{i, j} \le 2$$$)Β β card features. It is guaranteed that all cards are distinct.
Output Specification: Output one integer β the number of meta-sets.
Notes: NoteLet's draw the cards indicating the first four features. The first feature will indicate the number of objects on a card: $$$1$$$, $$$2$$$, $$$3$$$. The second one is the color: red, green, purple. The third is the shape: oval, diamond, squiggle. The fourth is filling: open, striped, solid.You can see the first three tests below. For the first two tests, the meta-sets are highlighted.In the first test, the only meta-set is the five cards $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$. The sets in it are the triples $$$(0000,\ 0001,\ 0002)$$$ and $$$(0000,\ 0010,\ 0020)$$$. Also, a set is the triple $$$(0100,\ 1000,\ 2200)$$$ which does not belong to any meta-set. In the second test, the following groups of five cards are meta-sets: $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$, $$$(0000,\ 0001,\ 0002,\ 0100,\ 0200)$$$, $$$(0000,\ 0010,\ 0020,\ 0100,\ 0200)$$$. In there third test, there are $$$54$$$ meta-sets.
Code:
ndfeagbb, dfeagbbk = map(int, input().split())
cards = [tuple(map(int, input().split())) for _ in range(ndfeagbb)]
cards_lookup, counter = {card: i for i, card in enumerate(cards)}, [0] * (ndfeagbb + 1)
for i in range(len(cards) - 1):
for j in range(i + 1, len(cards)):
# TODO: Your code here
print(sum(x * (x - 1) // 2 for x in counter[:-1]))
|
ndfeagbb, dfeagbbk = map(int, input().split())
cards = [tuple(map(int, input().split())) for _ in range(ndfeagbb)]
cards_lookup, counter = {card: i for i, card in enumerate(cards)}, [0] * (ndfeagbb + 1)
for i in range(len(cards) - 1):
for j in range(i + 1, len(cards)):
{{completion}}
print(sum(x * (x - 1) // 2 for x in counter[:-1]))
|
counter[cards_lookup.get(tuple(x if x == y else ((x + 1) ^ (y + 1)) - 1 for x, y in zip(cards[i], cards[j])), -1)] += 1
|
[{"input": "8 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n1 0 0 0\n2 2 0 0", "output": ["1"]}, {"input": "7 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n0 2 0 0", "output": ["3"]}, {"input": "9 2\n0 0\n0 1\n0 2\n1 0\n1 1\n1 2\n2 0\n2 1\n2 2", "output": ["54"]}, {"input": "20 4\n0 2 0 0\n0 2 2 2\n0 2 2 1\n0 2 0 1\n1 2 2 0\n1 2 1 0\n1 2 2 1\n1 2 0 1\n1 1 2 2\n1 1 0 2\n1 1 2 1\n1 1 1 1\n2 1 2 0\n2 1 1 2\n2 1 2 1\n2 1 1 1\n0 1 1 2\n0 0 1 0\n2 2 0 0\n2 0 0 2", "output": ["0"]}]
|
block_completion_005315
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You like the card board game "Set". Each card contains $$$k$$$ features, each of which is equal to a value from the set $$$\{0, 1, 2\}$$$. The deck contains all possible variants of cards, that is, there are $$$3^k$$$ different cards in total.A feature for three cards is called good if it is the same for these cards or pairwise distinct. Three cards are called a set if all $$$k$$$ features are good for them.For example, the cards $$$(0, 0, 0)$$$, $$$(0, 2, 1)$$$, and $$$(0, 1, 2)$$$ form a set, but the cards $$$(0, 2, 2)$$$, $$$(2, 1, 2)$$$, and $$$(1, 2, 0)$$$ do not, as, for example, the last feature is not good.A group of five cards is called a meta-set, if there is strictly more than one set among them. How many meta-sets there are among given $$$n$$$ distinct cards?
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^3$$$, $$$1 \le k \le 20$$$) β the number of cards on a table and the number of card features. The description of the cards follows in the next $$$n$$$ lines. Each line describing a card contains $$$k$$$ integers $$$c_{i, 1}, c_{i, 2}, \ldots, c_{i, k}$$$ ($$$0 \le c_{i, j} \le 2$$$)Β β card features. It is guaranteed that all cards are distinct.
Output Specification: Output one integer β the number of meta-sets.
Notes: NoteLet's draw the cards indicating the first four features. The first feature will indicate the number of objects on a card: $$$1$$$, $$$2$$$, $$$3$$$. The second one is the color: red, green, purple. The third is the shape: oval, diamond, squiggle. The fourth is filling: open, striped, solid.You can see the first three tests below. For the first two tests, the meta-sets are highlighted.In the first test, the only meta-set is the five cards $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$. The sets in it are the triples $$$(0000,\ 0001,\ 0002)$$$ and $$$(0000,\ 0010,\ 0020)$$$. Also, a set is the triple $$$(0100,\ 1000,\ 2200)$$$ which does not belong to any meta-set. In the second test, the following groups of five cards are meta-sets: $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$, $$$(0000,\ 0001,\ 0002,\ 0100,\ 0200)$$$, $$$(0000,\ 0010,\ 0020,\ 0100,\ 0200)$$$. In there third test, there are $$$54$$$ meta-sets.
Code:
from sys import stdin, stdout
n, k = [int(x) for x in stdin.readline().split()]
cards = set()
for i in range(n):
cards.add(tuple([int(x) for x in stdin.readline().split()]))
answer = 0
for card in cards:
yes_v = 0
for v in cards:
w = []
for i in range(k):
# TODO: Your code here
if tuple(w) in cards:
yes_v += 1
yes_v = (yes_v-1)//2
answer += (yes_v * (yes_v-1))//2
stdout.write(str(answer)+'\n')
|
from sys import stdin, stdout
n, k = [int(x) for x in stdin.readline().split()]
cards = set()
for i in range(n):
cards.add(tuple([int(x) for x in stdin.readline().split()]))
answer = 0
for card in cards:
yes_v = 0
for v in cards:
w = []
for i in range(k):
{{completion}}
if tuple(w) in cards:
yes_v += 1
yes_v = (yes_v-1)//2
answer += (yes_v * (yes_v-1))//2
stdout.write(str(answer)+'\n')
|
w.append((3-card[i]-v[i])%3)
|
[{"input": "8 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n1 0 0 0\n2 2 0 0", "output": ["1"]}, {"input": "7 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n0 2 0 0", "output": ["3"]}, {"input": "9 2\n0 0\n0 1\n0 2\n1 0\n1 1\n1 2\n2 0\n2 1\n2 2", "output": ["54"]}, {"input": "20 4\n0 2 0 0\n0 2 2 2\n0 2 2 1\n0 2 0 1\n1 2 2 0\n1 2 1 0\n1 2 2 1\n1 2 0 1\n1 1 2 2\n1 1 0 2\n1 1 2 1\n1 1 1 1\n2 1 2 0\n2 1 1 2\n2 1 2 1\n2 1 1 1\n0 1 1 2\n0 0 1 0\n2 2 0 0\n2 0 0 2", "output": ["0"]}]
|
block_completion_005316
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You like the card board game "Set". Each card contains $$$k$$$ features, each of which is equal to a value from the set $$$\{0, 1, 2\}$$$. The deck contains all possible variants of cards, that is, there are $$$3^k$$$ different cards in total.A feature for three cards is called good if it is the same for these cards or pairwise distinct. Three cards are called a set if all $$$k$$$ features are good for them.For example, the cards $$$(0, 0, 0)$$$, $$$(0, 2, 1)$$$, and $$$(0, 1, 2)$$$ form a set, but the cards $$$(0, 2, 2)$$$, $$$(2, 1, 2)$$$, and $$$(1, 2, 0)$$$ do not, as, for example, the last feature is not good.A group of five cards is called a meta-set, if there is strictly more than one set among them. How many meta-sets there are among given $$$n$$$ distinct cards?
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^3$$$, $$$1 \le k \le 20$$$) β the number of cards on a table and the number of card features. The description of the cards follows in the next $$$n$$$ lines. Each line describing a card contains $$$k$$$ integers $$$c_{i, 1}, c_{i, 2}, \ldots, c_{i, k}$$$ ($$$0 \le c_{i, j} \le 2$$$)Β β card features. It is guaranteed that all cards are distinct.
Output Specification: Output one integer β the number of meta-sets.
Notes: NoteLet's draw the cards indicating the first four features. The first feature will indicate the number of objects on a card: $$$1$$$, $$$2$$$, $$$3$$$. The second one is the color: red, green, purple. The third is the shape: oval, diamond, squiggle. The fourth is filling: open, striped, solid.You can see the first three tests below. For the first two tests, the meta-sets are highlighted.In the first test, the only meta-set is the five cards $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$. The sets in it are the triples $$$(0000,\ 0001,\ 0002)$$$ and $$$(0000,\ 0010,\ 0020)$$$. Also, a set is the triple $$$(0100,\ 1000,\ 2200)$$$ which does not belong to any meta-set. In the second test, the following groups of five cards are meta-sets: $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$, $$$(0000,\ 0001,\ 0002,\ 0100,\ 0200)$$$, $$$(0000,\ 0010,\ 0020,\ 0100,\ 0200)$$$. In there third test, there are $$$54$$$ meta-sets.
Code:
from sys import stdin, stdout
n, k = [int(x) for x in stdin.readline().split()]
cards = set()
for i in range(n):
cards.add(tuple([int(x) for x in stdin.readline().split()]))
answer = 0
for card in cards:
yes_v = 0
for v in cards:
w = []
for i in range(k):
w.append((3-card[i]-v[i])%3)
if tuple(w) in cards:
# TODO: Your code here
yes_v = (yes_v-1)//2
answer += (yes_v * (yes_v-1))//2
stdout.write(str(answer)+'\n')
|
from sys import stdin, stdout
n, k = [int(x) for x in stdin.readline().split()]
cards = set()
for i in range(n):
cards.add(tuple([int(x) for x in stdin.readline().split()]))
answer = 0
for card in cards:
yes_v = 0
for v in cards:
w = []
for i in range(k):
w.append((3-card[i]-v[i])%3)
if tuple(w) in cards:
{{completion}}
yes_v = (yes_v-1)//2
answer += (yes_v * (yes_v-1))//2
stdout.write(str(answer)+'\n')
|
yes_v += 1
|
[{"input": "8 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n1 0 0 0\n2 2 0 0", "output": ["1"]}, {"input": "7 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n0 2 0 0", "output": ["3"]}, {"input": "9 2\n0 0\n0 1\n0 2\n1 0\n1 1\n1 2\n2 0\n2 1\n2 2", "output": ["54"]}, {"input": "20 4\n0 2 0 0\n0 2 2 2\n0 2 2 1\n0 2 0 1\n1 2 2 0\n1 2 1 0\n1 2 2 1\n1 2 0 1\n1 1 2 2\n1 1 0 2\n1 1 2 1\n1 1 1 1\n2 1 2 0\n2 1 1 2\n2 1 2 1\n2 1 1 1\n0 1 1 2\n0 0 1 0\n2 2 0 0\n2 0 0 2", "output": ["0"]}]
|
block_completion_005317
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You like the card board game "Set". Each card contains $$$k$$$ features, each of which is equal to a value from the set $$$\{0, 1, 2\}$$$. The deck contains all possible variants of cards, that is, there are $$$3^k$$$ different cards in total.A feature for three cards is called good if it is the same for these cards or pairwise distinct. Three cards are called a set if all $$$k$$$ features are good for them.For example, the cards $$$(0, 0, 0)$$$, $$$(0, 2, 1)$$$, and $$$(0, 1, 2)$$$ form a set, but the cards $$$(0, 2, 2)$$$, $$$(2, 1, 2)$$$, and $$$(1, 2, 0)$$$ do not, as, for example, the last feature is not good.A group of five cards is called a meta-set, if there is strictly more than one set among them. How many meta-sets there are among given $$$n$$$ distinct cards?
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^3$$$, $$$1 \le k \le 20$$$) β the number of cards on a table and the number of card features. The description of the cards follows in the next $$$n$$$ lines. Each line describing a card contains $$$k$$$ integers $$$c_{i, 1}, c_{i, 2}, \ldots, c_{i, k}$$$ ($$$0 \le c_{i, j} \le 2$$$)Β β card features. It is guaranteed that all cards are distinct.
Output Specification: Output one integer β the number of meta-sets.
Notes: NoteLet's draw the cards indicating the first four features. The first feature will indicate the number of objects on a card: $$$1$$$, $$$2$$$, $$$3$$$. The second one is the color: red, green, purple. The third is the shape: oval, diamond, squiggle. The fourth is filling: open, striped, solid.You can see the first three tests below. For the first two tests, the meta-sets are highlighted.In the first test, the only meta-set is the five cards $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$. The sets in it are the triples $$$(0000,\ 0001,\ 0002)$$$ and $$$(0000,\ 0010,\ 0020)$$$. Also, a set is the triple $$$(0100,\ 1000,\ 2200)$$$ which does not belong to any meta-set. In the second test, the following groups of five cards are meta-sets: $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$, $$$(0000,\ 0001,\ 0002,\ 0100,\ 0200)$$$, $$$(0000,\ 0010,\ 0020,\ 0100,\ 0200)$$$. In there third test, there are $$$54$$$ meta-sets.
Code:
import sys; R = sys.stdin.readline
n,k = map(int,R().split())
deck = [tuple(map(int,R().split())) for _ in range(n)]
dic = {}
for i in range(n): dic[deck[i]] = i
res = [0]*n
for p in range(n-2):
for q in range(p+1,n-1):
last = [0]*k
for j in range(k):
# TODO: Your code here
last = tuple(last)
if last in dic and dic[last]>q:
res[p] += 1; res[q] += 1; res[dic[last]] += 1
print(sum((s*(s-1))//2 for s in res))
|
import sys; R = sys.stdin.readline
n,k = map(int,R().split())
deck = [tuple(map(int,R().split())) for _ in range(n)]
dic = {}
for i in range(n): dic[deck[i]] = i
res = [0]*n
for p in range(n-2):
for q in range(p+1,n-1):
last = [0]*k
for j in range(k):
{{completion}}
last = tuple(last)
if last in dic and dic[last]>q:
res[p] += 1; res[q] += 1; res[dic[last]] += 1
print(sum((s*(s-1))//2 for s in res))
|
last[j] = deck[p][j] if deck[p][j]==deck[q][j] else 3-deck[p][j]-deck[q][j]
|
[{"input": "8 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n1 0 0 0\n2 2 0 0", "output": ["1"]}, {"input": "7 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n0 2 0 0", "output": ["3"]}, {"input": "9 2\n0 0\n0 1\n0 2\n1 0\n1 1\n1 2\n2 0\n2 1\n2 2", "output": ["54"]}, {"input": "20 4\n0 2 0 0\n0 2 2 2\n0 2 2 1\n0 2 0 1\n1 2 2 0\n1 2 1 0\n1 2 2 1\n1 2 0 1\n1 1 2 2\n1 1 0 2\n1 1 2 1\n1 1 1 1\n2 1 2 0\n2 1 1 2\n2 1 2 1\n2 1 1 1\n0 1 1 2\n0 0 1 0\n2 2 0 0\n2 0 0 2", "output": ["0"]}]
|
block_completion_005318
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You like the card board game "Set". Each card contains $$$k$$$ features, each of which is equal to a value from the set $$$\{0, 1, 2\}$$$. The deck contains all possible variants of cards, that is, there are $$$3^k$$$ different cards in total.A feature for three cards is called good if it is the same for these cards or pairwise distinct. Three cards are called a set if all $$$k$$$ features are good for them.For example, the cards $$$(0, 0, 0)$$$, $$$(0, 2, 1)$$$, and $$$(0, 1, 2)$$$ form a set, but the cards $$$(0, 2, 2)$$$, $$$(2, 1, 2)$$$, and $$$(1, 2, 0)$$$ do not, as, for example, the last feature is not good.A group of five cards is called a meta-set, if there is strictly more than one set among them. How many meta-sets there are among given $$$n$$$ distinct cards?
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^3$$$, $$$1 \le k \le 20$$$) β the number of cards on a table and the number of card features. The description of the cards follows in the next $$$n$$$ lines. Each line describing a card contains $$$k$$$ integers $$$c_{i, 1}, c_{i, 2}, \ldots, c_{i, k}$$$ ($$$0 \le c_{i, j} \le 2$$$)Β β card features. It is guaranteed that all cards are distinct.
Output Specification: Output one integer β the number of meta-sets.
Notes: NoteLet's draw the cards indicating the first four features. The first feature will indicate the number of objects on a card: $$$1$$$, $$$2$$$, $$$3$$$. The second one is the color: red, green, purple. The third is the shape: oval, diamond, squiggle. The fourth is filling: open, striped, solid.You can see the first three tests below. For the first two tests, the meta-sets are highlighted.In the first test, the only meta-set is the five cards $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$. The sets in it are the triples $$$(0000,\ 0001,\ 0002)$$$ and $$$(0000,\ 0010,\ 0020)$$$. Also, a set is the triple $$$(0100,\ 1000,\ 2200)$$$ which does not belong to any meta-set. In the second test, the following groups of five cards are meta-sets: $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$, $$$(0000,\ 0001,\ 0002,\ 0100,\ 0200)$$$, $$$(0000,\ 0010,\ 0020,\ 0100,\ 0200)$$$. In there third test, there are $$$54$$$ meta-sets.
Code:
import sys; R = sys.stdin.readline
n,k = map(int,R().split())
deck = [tuple(map(int,R().split())) for _ in range(n)]
dic = {}
for i in range(n): dic[deck[i]] = i
res = [0]*n
for p in range(n-2):
for q in range(p+1,n-1):
last = [0]*k
for j in range(k):
last[j] = deck[p][j] if deck[p][j]==deck[q][j] else 3-deck[p][j]-deck[q][j]
last = tuple(last)
if last in dic and dic[last]>q:
# TODO: Your code here
print(sum((s*(s-1))//2 for s in res))
|
import sys; R = sys.stdin.readline
n,k = map(int,R().split())
deck = [tuple(map(int,R().split())) for _ in range(n)]
dic = {}
for i in range(n): dic[deck[i]] = i
res = [0]*n
for p in range(n-2):
for q in range(p+1,n-1):
last = [0]*k
for j in range(k):
last[j] = deck[p][j] if deck[p][j]==deck[q][j] else 3-deck[p][j]-deck[q][j]
last = tuple(last)
if last in dic and dic[last]>q:
{{completion}}
print(sum((s*(s-1))//2 for s in res))
|
res[p] += 1; res[q] += 1; res[dic[last]] += 1
|
[{"input": "8 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n1 0 0 0\n2 2 0 0", "output": ["1"]}, {"input": "7 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n0 2 0 0", "output": ["3"]}, {"input": "9 2\n0 0\n0 1\n0 2\n1 0\n1 1\n1 2\n2 0\n2 1\n2 2", "output": ["54"]}, {"input": "20 4\n0 2 0 0\n0 2 2 2\n0 2 2 1\n0 2 0 1\n1 2 2 0\n1 2 1 0\n1 2 2 1\n1 2 0 1\n1 1 2 2\n1 1 0 2\n1 1 2 1\n1 1 1 1\n2 1 2 0\n2 1 1 2\n2 1 2 1\n2 1 1 1\n0 1 1 2\n0 0 1 0\n2 2 0 0\n2 0 0 2", "output": ["0"]}]
|
block_completion_005319
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You like the card board game "Set". Each card contains $$$k$$$ features, each of which is equal to a value from the set $$$\{0, 1, 2\}$$$. The deck contains all possible variants of cards, that is, there are $$$3^k$$$ different cards in total.A feature for three cards is called good if it is the same for these cards or pairwise distinct. Three cards are called a set if all $$$k$$$ features are good for them.For example, the cards $$$(0, 0, 0)$$$, $$$(0, 2, 1)$$$, and $$$(0, 1, 2)$$$ form a set, but the cards $$$(0, 2, 2)$$$, $$$(2, 1, 2)$$$, and $$$(1, 2, 0)$$$ do not, as, for example, the last feature is not good.A group of five cards is called a meta-set, if there is strictly more than one set among them. How many meta-sets there are among given $$$n$$$ distinct cards?
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^3$$$, $$$1 \le k \le 20$$$) β the number of cards on a table and the number of card features. The description of the cards follows in the next $$$n$$$ lines. Each line describing a card contains $$$k$$$ integers $$$c_{i, 1}, c_{i, 2}, \ldots, c_{i, k}$$$ ($$$0 \le c_{i, j} \le 2$$$)Β β card features. It is guaranteed that all cards are distinct.
Output Specification: Output one integer β the number of meta-sets.
Notes: NoteLet's draw the cards indicating the first four features. The first feature will indicate the number of objects on a card: $$$1$$$, $$$2$$$, $$$3$$$. The second one is the color: red, green, purple. The third is the shape: oval, diamond, squiggle. The fourth is filling: open, striped, solid.You can see the first three tests below. For the first two tests, the meta-sets are highlighted.In the first test, the only meta-set is the five cards $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$. The sets in it are the triples $$$(0000,\ 0001,\ 0002)$$$ and $$$(0000,\ 0010,\ 0020)$$$. Also, a set is the triple $$$(0100,\ 1000,\ 2200)$$$ which does not belong to any meta-set. In the second test, the following groups of five cards are meta-sets: $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$, $$$(0000,\ 0001,\ 0002,\ 0100,\ 0200)$$$, $$$(0000,\ 0010,\ 0020,\ 0100,\ 0200)$$$. In there third test, there are $$$54$$$ meta-sets.
Code:
n,k=map(int,input().split())
a=[]
d={}
for i in range(n):
a+=[''.join(input().split())]
d[a[-1]]=0
def cal(s,t):
res=""
for i in range(k):
res+=str((9-int(s[i])-int(t[i]))%3)
return res
for i in range(n):
for j in range(i):
try:
d[cal(a[i],a[j])]+=1
except:
# TODO: Your code here
ans=0
for y in d.values():
ans+=(y*(y-1))//2
print(ans)
|
n,k=map(int,input().split())
a=[]
d={}
for i in range(n):
a+=[''.join(input().split())]
d[a[-1]]=0
def cal(s,t):
res=""
for i in range(k):
res+=str((9-int(s[i])-int(t[i]))%3)
return res
for i in range(n):
for j in range(i):
try:
d[cal(a[i],a[j])]+=1
except:
{{completion}}
ans=0
for y in d.values():
ans+=(y*(y-1))//2
print(ans)
|
pass
|
[{"input": "8 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n1 0 0 0\n2 2 0 0", "output": ["1"]}, {"input": "7 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n0 2 0 0", "output": ["3"]}, {"input": "9 2\n0 0\n0 1\n0 2\n1 0\n1 1\n1 2\n2 0\n2 1\n2 2", "output": ["54"]}, {"input": "20 4\n0 2 0 0\n0 2 2 2\n0 2 2 1\n0 2 0 1\n1 2 2 0\n1 2 1 0\n1 2 2 1\n1 2 0 1\n1 1 2 2\n1 1 0 2\n1 1 2 1\n1 1 1 1\n2 1 2 0\n2 1 1 2\n2 1 2 1\n2 1 1 1\n0 1 1 2\n0 0 1 0\n2 2 0 0\n2 0 0 2", "output": ["0"]}]
|
block_completion_005320
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You like the card board game "Set". Each card contains $$$k$$$ features, each of which is equal to a value from the set $$$\{0, 1, 2\}$$$. The deck contains all possible variants of cards, that is, there are $$$3^k$$$ different cards in total.A feature for three cards is called good if it is the same for these cards or pairwise distinct. Three cards are called a set if all $$$k$$$ features are good for them.For example, the cards $$$(0, 0, 0)$$$, $$$(0, 2, 1)$$$, and $$$(0, 1, 2)$$$ form a set, but the cards $$$(0, 2, 2)$$$, $$$(2, 1, 2)$$$, and $$$(1, 2, 0)$$$ do not, as, for example, the last feature is not good.A group of five cards is called a meta-set, if there is strictly more than one set among them. How many meta-sets there are among given $$$n$$$ distinct cards?
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^3$$$, $$$1 \le k \le 20$$$) β the number of cards on a table and the number of card features. The description of the cards follows in the next $$$n$$$ lines. Each line describing a card contains $$$k$$$ integers $$$c_{i, 1}, c_{i, 2}, \ldots, c_{i, k}$$$ ($$$0 \le c_{i, j} \le 2$$$)Β β card features. It is guaranteed that all cards are distinct.
Output Specification: Output one integer β the number of meta-sets.
Notes: NoteLet's draw the cards indicating the first four features. The first feature will indicate the number of objects on a card: $$$1$$$, $$$2$$$, $$$3$$$. The second one is the color: red, green, purple. The third is the shape: oval, diamond, squiggle. The fourth is filling: open, striped, solid.You can see the first three tests below. For the first two tests, the meta-sets are highlighted.In the first test, the only meta-set is the five cards $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$. The sets in it are the triples $$$(0000,\ 0001,\ 0002)$$$ and $$$(0000,\ 0010,\ 0020)$$$. Also, a set is the triple $$$(0100,\ 1000,\ 2200)$$$ which does not belong to any meta-set. In the second test, the following groups of five cards are meta-sets: $$$(0000,\ 0001,\ 0002,\ 0010,\ 0020)$$$, $$$(0000,\ 0001,\ 0002,\ 0100,\ 0200)$$$, $$$(0000,\ 0010,\ 0020,\ 0100,\ 0200)$$$. In there third test, there are $$$54$$$ meta-sets.
Code:
n, k = [int(i) for i in input().split()]
a = []
for _ in range(n):
a.append(tuple([int(i) for i in input().split()]))
a = tuple(a)
sus = set(a)
cs = [0 for i in range(n)]
for i in range(n):
p = a[i]
for j in set(range(n)) - set(tuple([i])):
q = a[j]
r = []
for o in range(k):
if p[o] == q[o]:
r.append(p[o])
else:
# TODO: Your code here
if tuple(r) in sus:
cs[i] += 1
cs[j] += 1
cs = [i//4 for i in cs]
cs = [(i*(i-1))//2 for i in cs]
print(sum(cs))
|
n, k = [int(i) for i in input().split()]
a = []
for _ in range(n):
a.append(tuple([int(i) for i in input().split()]))
a = tuple(a)
sus = set(a)
cs = [0 for i in range(n)]
for i in range(n):
p = a[i]
for j in set(range(n)) - set(tuple([i])):
q = a[j]
r = []
for o in range(k):
if p[o] == q[o]:
r.append(p[o])
else:
{{completion}}
if tuple(r) in sus:
cs[i] += 1
cs[j] += 1
cs = [i//4 for i in cs]
cs = [(i*(i-1))//2 for i in cs]
print(sum(cs))
|
r.append(3-p[o]-q[o])
|
[{"input": "8 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n1 0 0 0\n2 2 0 0", "output": ["1"]}, {"input": "7 4\n0 0 0 0\n0 0 0 1\n0 0 0 2\n0 0 1 0\n0 0 2 0\n0 1 0 0\n0 2 0 0", "output": ["3"]}, {"input": "9 2\n0 0\n0 1\n0 2\n1 0\n1 1\n1 2\n2 0\n2 1\n2 2", "output": ["54"]}, {"input": "20 4\n0 2 0 0\n0 2 2 2\n0 2 2 1\n0 2 0 1\n1 2 2 0\n1 2 1 0\n1 2 2 1\n1 2 0 1\n1 1 2 2\n1 1 0 2\n1 1 2 1\n1 1 1 1\n2 1 2 0\n2 1 1 2\n2 1 2 1\n2 1 1 1\n0 1 1 2\n0 0 1 0\n2 2 0 0\n2 0 0 2", "output": ["0"]}]
|
block_completion_005321
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array $$$a$$$ that contains $$$n$$$ integers. You can choose any proper subsegment $$$a_l, a_{l + 1}, \ldots, a_r$$$ of this array, meaning you can choose any two integers $$$1 \le l \le r \le n$$$, where $$$r - l + 1 < n$$$. We define the beauty of a given subsegment as the value of the following expression:$$$$$$\max(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) - \min(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) + \max(a_{l}, \ldots, a_{r}) - \min(a_{l}, \ldots, a_{r}).$$$$$$Please find the maximum beauty among all proper subsegments.
Input Specification: The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) β the number of test cases. Then follow the descriptions of each test case. The first line of each test case contains a single integer $$$n$$$ $$$(4 \leq n \leq 10^5)$$$ β the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_{i} \leq 10^9$$$) β the elements of the given array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each testcase print a single integer β the maximum beauty of a proper subsegment.
Notes: NoteIn the first test case, the optimal segment is $$$l = 7$$$, $$$r = 8$$$. The beauty of this segment equals to $$$(6 - 1) + (5 - 1) = 9$$$.In the second test case, the optimal segment is $$$l = 2$$$, $$$r = 4$$$. The beauty of this segment equals $$$(100 - 2) + (200 - 1) = 297$$$.
Code:
for _ in range(int(input())):
# TODO: Your code here
|
for _ in range(int(input())):
{{completion}}
|
n = input()
a = sorted(map(int, input().split()))
print(a[-1] + a[-2] - a[0] - a[1])
|
[{"input": "4\n8\n1 2 2 3 1 5 6 1\n5\n1 2 3 100 200\n4\n3 3 3 3\n6\n7 8 3 1 1 8", "output": ["9\n297\n0\n14"]}]
|
block_completion_005384
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array $$$a$$$ that contains $$$n$$$ integers. You can choose any proper subsegment $$$a_l, a_{l + 1}, \ldots, a_r$$$ of this array, meaning you can choose any two integers $$$1 \le l \le r \le n$$$, where $$$r - l + 1 < n$$$. We define the beauty of a given subsegment as the value of the following expression:$$$$$$\max(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) - \min(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) + \max(a_{l}, \ldots, a_{r}) - \min(a_{l}, \ldots, a_{r}).$$$$$$Please find the maximum beauty among all proper subsegments.
Input Specification: The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) β the number of test cases. Then follow the descriptions of each test case. The first line of each test case contains a single integer $$$n$$$ $$$(4 \leq n \leq 10^5)$$$ β the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_{i} \leq 10^9$$$) β the elements of the given array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each testcase print a single integer β the maximum beauty of a proper subsegment.
Notes: NoteIn the first test case, the optimal segment is $$$l = 7$$$, $$$r = 8$$$. The beauty of this segment equals to $$$(6 - 1) + (5 - 1) = 9$$$.In the second test case, the optimal segment is $$$l = 2$$$, $$$r = 4$$$. The beauty of this segment equals $$$(100 - 2) + (200 - 1) = 297$$$.
Code:
for s in[*open(0)][2::2]:# TODO: Your code here
|
for s in[*open(0)][2::2]:{{completion}}
|
a,b,*_,c,d=sorted(map(int,s.split()));print(c+d-a-b)
|
[{"input": "4\n8\n1 2 2 3 1 5 6 1\n5\n1 2 3 100 200\n4\n3 3 3 3\n6\n7 8 3 1 1 8", "output": ["9\n297\n0\n14"]}]
|
block_completion_005385
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array $$$a$$$ that contains $$$n$$$ integers. You can choose any proper subsegment $$$a_l, a_{l + 1}, \ldots, a_r$$$ of this array, meaning you can choose any two integers $$$1 \le l \le r \le n$$$, where $$$r - l + 1 < n$$$. We define the beauty of a given subsegment as the value of the following expression:$$$$$$\max(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) - \min(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) + \max(a_{l}, \ldots, a_{r}) - \min(a_{l}, \ldots, a_{r}).$$$$$$Please find the maximum beauty among all proper subsegments.
Input Specification: The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) β the number of test cases. Then follow the descriptions of each test case. The first line of each test case contains a single integer $$$n$$$ $$$(4 \leq n \leq 10^5)$$$ β the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_{i} \leq 10^9$$$) β the elements of the given array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each testcase print a single integer β the maximum beauty of a proper subsegment.
Notes: NoteIn the first test case, the optimal segment is $$$l = 7$$$, $$$r = 8$$$. The beauty of this segment equals to $$$(6 - 1) + (5 - 1) = 9$$$.In the second test case, the optimal segment is $$$l = 2$$$, $$$r = 4$$$. The beauty of this segment equals $$$(100 - 2) + (200 - 1) = 297$$$.
Code:
for t in range(int(input())):# TODO: Your code here
|
for t in range(int(input())):{{completion}}
|
input();a,b,*_,c,d=sorted(map(int,input().split()));print(c+d-a-b)
|
[{"input": "4\n8\n1 2 2 3 1 5 6 1\n5\n1 2 3 100 200\n4\n3 3 3 3\n6\n7 8 3 1 1 8", "output": ["9\n297\n0\n14"]}]
|
block_completion_005386
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array $$$a$$$ that contains $$$n$$$ integers. You can choose any proper subsegment $$$a_l, a_{l + 1}, \ldots, a_r$$$ of this array, meaning you can choose any two integers $$$1 \le l \le r \le n$$$, where $$$r - l + 1 < n$$$. We define the beauty of a given subsegment as the value of the following expression:$$$$$$\max(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) - \min(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) + \max(a_{l}, \ldots, a_{r}) - \min(a_{l}, \ldots, a_{r}).$$$$$$Please find the maximum beauty among all proper subsegments.
Input Specification: The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) β the number of test cases. Then follow the descriptions of each test case. The first line of each test case contains a single integer $$$n$$$ $$$(4 \leq n \leq 10^5)$$$ β the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_{i} \leq 10^9$$$) β the elements of the given array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each testcase print a single integer β the maximum beauty of a proper subsegment.
Notes: NoteIn the first test case, the optimal segment is $$$l = 7$$$, $$$r = 8$$$. The beauty of this segment equals to $$$(6 - 1) + (5 - 1) = 9$$$.In the second test case, the optimal segment is $$$l = 2$$$, $$$r = 4$$$. The beauty of this segment equals $$$(100 - 2) + (200 - 1) = 297$$$.
Code:
for sdr in[*open(0)][2::2]:# TODO: Your code here
|
for sdr in[*open(0)][2::2]:{{completion}}
|
p,q,*_,r,s=sorted(map(int,sdr.split()));print(r+s-p-q)
|
[{"input": "4\n8\n1 2 2 3 1 5 6 1\n5\n1 2 3 100 200\n4\n3 3 3 3\n6\n7 8 3 1 1 8", "output": ["9\n297\n0\n14"]}]
|
block_completion_005387
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array $$$a$$$ that contains $$$n$$$ integers. You can choose any proper subsegment $$$a_l, a_{l + 1}, \ldots, a_r$$$ of this array, meaning you can choose any two integers $$$1 \le l \le r \le n$$$, where $$$r - l + 1 < n$$$. We define the beauty of a given subsegment as the value of the following expression:$$$$$$\max(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) - \min(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) + \max(a_{l}, \ldots, a_{r}) - \min(a_{l}, \ldots, a_{r}).$$$$$$Please find the maximum beauty among all proper subsegments.
Input Specification: The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) β the number of test cases. Then follow the descriptions of each test case. The first line of each test case contains a single integer $$$n$$$ $$$(4 \leq n \leq 10^5)$$$ β the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_{i} \leq 10^9$$$) β the elements of the given array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each testcase print a single integer β the maximum beauty of a proper subsegment.
Notes: NoteIn the first test case, the optimal segment is $$$l = 7$$$, $$$r = 8$$$. The beauty of this segment equals to $$$(6 - 1) + (5 - 1) = 9$$$.In the second test case, the optimal segment is $$$l = 2$$$, $$$r = 4$$$. The beauty of this segment equals $$$(100 - 2) + (200 - 1) = 297$$$.
Code:
for _ in range(int(input())):
# TODO: Your code here
|
for _ in range(int(input())):
{{completion}}
|
input()
a, b, *_, c, d = sorted(map(int, input().split()))
print(c+d-a-b)
|
[{"input": "4\n8\n1 2 2 3 1 5 6 1\n5\n1 2 3 100 200\n4\n3 3 3 3\n6\n7 8 3 1 1 8", "output": ["9\n297\n0\n14"]}]
|
block_completion_005388
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You are given an array $$$a$$$ that contains $$$n$$$ integers. You can choose any proper subsegment $$$a_l, a_{l + 1}, \ldots, a_r$$$ of this array, meaning you can choose any two integers $$$1 \le l \le r \le n$$$, where $$$r - l + 1 < n$$$. We define the beauty of a given subsegment as the value of the following expression:$$$$$$\max(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) - \min(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) + \max(a_{l}, \ldots, a_{r}) - \min(a_{l}, \ldots, a_{r}).$$$$$$Please find the maximum beauty among all proper subsegments.
Input Specification: The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) β the number of test cases. Then follow the descriptions of each test case. The first line of each test case contains a single integer $$$n$$$ $$$(4 \leq n \leq 10^5)$$$ β the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_{i} \leq 10^9$$$) β the elements of the given array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
Output Specification: For each testcase print a single integer β the maximum beauty of a proper subsegment.
Notes: NoteIn the first test case, the optimal segment is $$$l = 7$$$, $$$r = 8$$$. The beauty of this segment equals to $$$(6 - 1) + (5 - 1) = 9$$$.In the second test case, the optimal segment is $$$l = 2$$$, $$$r = 4$$$. The beauty of this segment equals $$$(100 - 2) + (200 - 1) = 297$$$.
Code:
for _ in range(int(input())):
# TODO: Your code here
|
for _ in range(int(input())):
{{completion}}
|
input()
a = sorted(map(int, input().split()))
print(a[-1] + a[-2] - a[0] - a[1])
|
[{"input": "4\n8\n1 2 2 3 1 5 6 1\n5\n1 2 3 100 200\n4\n3 3 3 3\n6\n7 8 3 1 1 8", "output": ["9\n297\n0\n14"]}]
|
block_completion_005389
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Monocarp is going to host a party for his friends. He prepared $$$n$$$ dishes and is about to serve them. First, he has to add some powdered pepper to each of themΒ β otherwise, the dishes will be pretty tasteless.The $$$i$$$-th dish has two values $$$a_i$$$ and $$$b_i$$$Β β its tastiness with red pepper added or black pepper added, respectively. Monocarp won't add both peppers to any dish, won't add any pepper multiple times, and won't leave any dish without the pepper added.Before adding the pepper, Monocarp should first purchase the said pepper in some shop. There are $$$m$$$ shops in his local area. The $$$j$$$-th of them has packages of red pepper sufficient for $$$x_j$$$ servings and packages of black pepper sufficient for $$$y_j$$$ servings.Monocarp goes to exactly one shop, purchases multiple (possibly, zero) packages of each pepper in such a way that each dish will get the pepper added once, and no pepper is left. More formally, if he purchases $$$x$$$ red pepper packages and $$$y$$$ black pepper packages, then $$$x$$$ and $$$y$$$ should be non-negative and $$$x \cdot x_j + y \cdot y_j$$$ should be equal to $$$n$$$.For each shop, determine the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages in the said way, print -1.
Input Specification: The first line contains a single integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$)Β β the number of dishes. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 10^9$$$)Β β the tastiness of the $$$i$$$-th dish with red pepper added or black pepper added, respectively. The next line contains a single integer $$$m$$$ ($$$1 \le m \le 3 \cdot 10^5$$$)Β β the number of shops. The $$$j$$$-th of the next $$$m$$$ lines contains two integers $$$x_j$$$ and $$$y_j$$$ ($$$1 \le x_j, y_j \le n$$$)Β β the number of servings the red and the black pepper packages are sufficient for in the $$$j$$$-th shop, respectively.
Output Specification: Print $$$m$$$ integers. For each shop, print the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages so that each dish will get the pepper added once and no pepper is left, print -1.
Notes: NoteConsider the first example.In the first shop, Monocarp can only buy $$$0$$$ red pepper packages and $$$1$$$ black pepper package. Black pepper added to all dishes will sum up to $$$10 + 50 + 2 = 62$$$.In the second shop, Monocarp can buy any number of red and black pepper packages: $$$0$$$ and $$$3$$$, $$$1$$$ and $$$2$$$, $$$2$$$ and $$$1$$$ or $$$3$$$ and $$$0$$$. The optimal choice turns out to be either $$$1$$$ and $$$2$$$ or $$$2$$$ and $$$1$$$. Monocarp can add black pepper to the first dish, red pepper to the second dish and any pepper to the third dish, the total is $$$10 + 100 + 2 = 112$$$.In the third shop, Monocarp can only buy $$$1$$$ red pepper package and $$$0$$$ black pepper packages. Red pepper added to all dishes will sum up to $$$5 + 100 + 2 = 107$$$.In the fourth shop, Monocarp can only buy an even total number of packages. Since $$$n$$$ is odd, it's impossible to get exactly $$$n$$$ packages. Thus, the answer is $$$-1$$$.
Code:
import sys
import math
import heapq
import itertools
import bisect
import random
from decimal import *
from collections import deque
input=sys.stdin.readline
def extended_gcd(a,b):
x0,x1,y0,y1=1,0,0,1
while b!=0:
n,a,b=a//b,b,a%b
x0,x1=x1,x0-n*x1
y0,y1=y1,y0-n*y1
return x0,y0
n=int(input())
arr=[]
ans=0
for i in range(n):
a,b=map(int,input().split())
ans+=a
arr.append(b-a)
arr.sort(reverse=True)
s=[0]
for i in range(n):
s.append(s[-1]+arr[i])
mp=s.index(max(s))
m=int(input())
for _ in range(m):
a,b=map(int,input().split())
k=math.gcd(a,b)
if n%(math.gcd(a,b))==0:
a1,b1=a//k,b//k
x,y=extended_gcd(a1,b1)
x,y=x*(n//k),y*(n//k)
mod=math.lcm(a,b)
p=(y*b)%mod
if p>n:
print(-1)
else:
p1=(mp//mod)*mod+p
line=[p1,p1-mod,p1+mod]
ma=-10**18
for i in line:
if 0<=i<=n:
# TODO: Your code here
print(ma+ans)
else:
print(-1)
|
import sys
import math
import heapq
import itertools
import bisect
import random
from decimal import *
from collections import deque
input=sys.stdin.readline
def extended_gcd(a,b):
x0,x1,y0,y1=1,0,0,1
while b!=0:
n,a,b=a//b,b,a%b
x0,x1=x1,x0-n*x1
y0,y1=y1,y0-n*y1
return x0,y0
n=int(input())
arr=[]
ans=0
for i in range(n):
a,b=map(int,input().split())
ans+=a
arr.append(b-a)
arr.sort(reverse=True)
s=[0]
for i in range(n):
s.append(s[-1]+arr[i])
mp=s.index(max(s))
m=int(input())
for _ in range(m):
a,b=map(int,input().split())
k=math.gcd(a,b)
if n%(math.gcd(a,b))==0:
a1,b1=a//k,b//k
x,y=extended_gcd(a1,b1)
x,y=x*(n//k),y*(n//k)
mod=math.lcm(a,b)
p=(y*b)%mod
if p>n:
print(-1)
else:
p1=(mp//mod)*mod+p
line=[p1,p1-mod,p1+mod]
ma=-10**18
for i in line:
if 0<=i<=n:
{{completion}}
print(ma+ans)
else:
print(-1)
|
ma=max(ma,s[i])
|
[{"input": "3\n5 10\n100 50\n2 2\n4\n2 3\n1 1\n3 2\n2 2", "output": ["62\n112\n107\n-1"]}, {"input": "10\n3 1\n2 3\n1 1\n2 1\n6 3\n1 4\n4 3\n1 3\n5 3\n5 4\n10\n8 10\n9 3\n1 4\n2 5\n8 3\n3 5\n1 6\n7 2\n6 7\n3 1", "output": ["26\n-1\n36\n30\n-1\n26\n34\n26\n-1\n36"]}]
|
block_completion_005534
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Monocarp is going to host a party for his friends. He prepared $$$n$$$ dishes and is about to serve them. First, he has to add some powdered pepper to each of themΒ β otherwise, the dishes will be pretty tasteless.The $$$i$$$-th dish has two values $$$a_i$$$ and $$$b_i$$$Β β its tastiness with red pepper added or black pepper added, respectively. Monocarp won't add both peppers to any dish, won't add any pepper multiple times, and won't leave any dish without the pepper added.Before adding the pepper, Monocarp should first purchase the said pepper in some shop. There are $$$m$$$ shops in his local area. The $$$j$$$-th of them has packages of red pepper sufficient for $$$x_j$$$ servings and packages of black pepper sufficient for $$$y_j$$$ servings.Monocarp goes to exactly one shop, purchases multiple (possibly, zero) packages of each pepper in such a way that each dish will get the pepper added once, and no pepper is left. More formally, if he purchases $$$x$$$ red pepper packages and $$$y$$$ black pepper packages, then $$$x$$$ and $$$y$$$ should be non-negative and $$$x \cdot x_j + y \cdot y_j$$$ should be equal to $$$n$$$.For each shop, determine the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages in the said way, print -1.
Input Specification: The first line contains a single integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$)Β β the number of dishes. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 10^9$$$)Β β the tastiness of the $$$i$$$-th dish with red pepper added or black pepper added, respectively. The next line contains a single integer $$$m$$$ ($$$1 \le m \le 3 \cdot 10^5$$$)Β β the number of shops. The $$$j$$$-th of the next $$$m$$$ lines contains two integers $$$x_j$$$ and $$$y_j$$$ ($$$1 \le x_j, y_j \le n$$$)Β β the number of servings the red and the black pepper packages are sufficient for in the $$$j$$$-th shop, respectively.
Output Specification: Print $$$m$$$ integers. For each shop, print the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages so that each dish will get the pepper added once and no pepper is left, print -1.
Notes: NoteConsider the first example.In the first shop, Monocarp can only buy $$$0$$$ red pepper packages and $$$1$$$ black pepper package. Black pepper added to all dishes will sum up to $$$10 + 50 + 2 = 62$$$.In the second shop, Monocarp can buy any number of red and black pepper packages: $$$0$$$ and $$$3$$$, $$$1$$$ and $$$2$$$, $$$2$$$ and $$$1$$$ or $$$3$$$ and $$$0$$$. The optimal choice turns out to be either $$$1$$$ and $$$2$$$ or $$$2$$$ and $$$1$$$. Monocarp can add black pepper to the first dish, red pepper to the second dish and any pepper to the third dish, the total is $$$10 + 100 + 2 = 112$$$.In the third shop, Monocarp can only buy $$$1$$$ red pepper package and $$$0$$$ black pepper packages. Red pepper added to all dishes will sum up to $$$5 + 100 + 2 = 107$$$.In the fourth shop, Monocarp can only buy an even total number of packages. Since $$$n$$$ is odd, it's impossible to get exactly $$$n$$$ packages. Thus, the answer is $$$-1$$$.
Code:
from collections import *
from itertools import *
from functools import *
import math,sys
input = sys.stdin.buffer.readline
n = int(input())
AB = [tuple(map(int,input().split())) for _ in range(n)]
M = int(input())
XY = [tuple(map(int,input().split())) for _ in range(M)]
ans = []
from math import gcd
def modinv(a, b):
p = b
x, y, u, v = 1, 0, 0, 1
while b:
k = a // b
x -= k * u
y -= k * v
x, u = u, x
y, v = v, y
a, b = b, a % b
x %= p
if x < 0:
x += p
return x
def slc(A, B, mod):
#solve Ax=B mod
a = A
b = B
m = mod
d = gcd(a,gcd(b,m))
while d>1:
a //= d
b //= d
m //= d
d = gcd(a,gcd(b,m))
if gcd(a,m) != 1:
return -1
return (modinv(a,m)*b)%m
D = [a-b for a,b in AB]
S = sum(b for a,b in AB)
D.sort(reverse=True)
SD = list(accumulate([0]+D))
L = 0
for i in range(n-1,-1,-1):
if D[i]>0:
L = i+1
break
for x,y in XY:
d = gcd(x,y)
if n%d != 0:
print(-1)
continue
x0 = slc(x,n,y)
tb = y//d
ok = 0
ng = -10**10
while ok-ng>1:
mid = (ok+ng)//2
if x0+mid*tb >=0:
ok = mid
else:
# TODO: Your code here
x0 += tb*ok
if x0*x>n:
print(-1)
continue
def is_ok(k):
return ((n-x*(x0 + k*tb)) >= 0)&(x0 + k*tb >= 0)
k0 = (L-x*x0)//(tb*x)
ans = -1
flg = False
if is_ok(k0):
tmp = S + SD[x*(x0 + k0*tb)]
ans = max(ans,tmp)
if is_ok(k0+1):
tmp = S + SD[x*(x0 + (k0+1)*tb)]
ans = max(ans,tmp)
flg = True
if flg:
print(ans)
continue
ok = 0
ng = k0 + 1
while ng-ok>1:
mid = (ok+ng)//2
if is_ok(mid):
ok = mid
else:
ng = mid
ans = max(ans,S + SD[x*(x0 + ok*tb)])
print(ans)
|
from collections import *
from itertools import *
from functools import *
import math,sys
input = sys.stdin.buffer.readline
n = int(input())
AB = [tuple(map(int,input().split())) for _ in range(n)]
M = int(input())
XY = [tuple(map(int,input().split())) for _ in range(M)]
ans = []
from math import gcd
def modinv(a, b):
p = b
x, y, u, v = 1, 0, 0, 1
while b:
k = a // b
x -= k * u
y -= k * v
x, u = u, x
y, v = v, y
a, b = b, a % b
x %= p
if x < 0:
x += p
return x
def slc(A, B, mod):
#solve Ax=B mod
a = A
b = B
m = mod
d = gcd(a,gcd(b,m))
while d>1:
a //= d
b //= d
m //= d
d = gcd(a,gcd(b,m))
if gcd(a,m) != 1:
return -1
return (modinv(a,m)*b)%m
D = [a-b for a,b in AB]
S = sum(b for a,b in AB)
D.sort(reverse=True)
SD = list(accumulate([0]+D))
L = 0
for i in range(n-1,-1,-1):
if D[i]>0:
L = i+1
break
for x,y in XY:
d = gcd(x,y)
if n%d != 0:
print(-1)
continue
x0 = slc(x,n,y)
tb = y//d
ok = 0
ng = -10**10
while ok-ng>1:
mid = (ok+ng)//2
if x0+mid*tb >=0:
ok = mid
else:
{{completion}}
x0 += tb*ok
if x0*x>n:
print(-1)
continue
def is_ok(k):
return ((n-x*(x0 + k*tb)) >= 0)&(x0 + k*tb >= 0)
k0 = (L-x*x0)//(tb*x)
ans = -1
flg = False
if is_ok(k0):
tmp = S + SD[x*(x0 + k0*tb)]
ans = max(ans,tmp)
if is_ok(k0+1):
tmp = S + SD[x*(x0 + (k0+1)*tb)]
ans = max(ans,tmp)
flg = True
if flg:
print(ans)
continue
ok = 0
ng = k0 + 1
while ng-ok>1:
mid = (ok+ng)//2
if is_ok(mid):
ok = mid
else:
ng = mid
ans = max(ans,S + SD[x*(x0 + ok*tb)])
print(ans)
|
ng = mid
|
[{"input": "3\n5 10\n100 50\n2 2\n4\n2 3\n1 1\n3 2\n2 2", "output": ["62\n112\n107\n-1"]}, {"input": "10\n3 1\n2 3\n1 1\n2 1\n6 3\n1 4\n4 3\n1 3\n5 3\n5 4\n10\n8 10\n9 3\n1 4\n2 5\n8 3\n3 5\n1 6\n7 2\n6 7\n3 1", "output": ["26\n-1\n36\n30\n-1\n26\n34\n26\n-1\n36"]}]
|
block_completion_005535
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Monocarp is going to host a party for his friends. He prepared $$$n$$$ dishes and is about to serve them. First, he has to add some powdered pepper to each of themΒ β otherwise, the dishes will be pretty tasteless.The $$$i$$$-th dish has two values $$$a_i$$$ and $$$b_i$$$Β β its tastiness with red pepper added or black pepper added, respectively. Monocarp won't add both peppers to any dish, won't add any pepper multiple times, and won't leave any dish without the pepper added.Before adding the pepper, Monocarp should first purchase the said pepper in some shop. There are $$$m$$$ shops in his local area. The $$$j$$$-th of them has packages of red pepper sufficient for $$$x_j$$$ servings and packages of black pepper sufficient for $$$y_j$$$ servings.Monocarp goes to exactly one shop, purchases multiple (possibly, zero) packages of each pepper in such a way that each dish will get the pepper added once, and no pepper is left. More formally, if he purchases $$$x$$$ red pepper packages and $$$y$$$ black pepper packages, then $$$x$$$ and $$$y$$$ should be non-negative and $$$x \cdot x_j + y \cdot y_j$$$ should be equal to $$$n$$$.For each shop, determine the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages in the said way, print -1.
Input Specification: The first line contains a single integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$)Β β the number of dishes. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 10^9$$$)Β β the tastiness of the $$$i$$$-th dish with red pepper added or black pepper added, respectively. The next line contains a single integer $$$m$$$ ($$$1 \le m \le 3 \cdot 10^5$$$)Β β the number of shops. The $$$j$$$-th of the next $$$m$$$ lines contains two integers $$$x_j$$$ and $$$y_j$$$ ($$$1 \le x_j, y_j \le n$$$)Β β the number of servings the red and the black pepper packages are sufficient for in the $$$j$$$-th shop, respectively.
Output Specification: Print $$$m$$$ integers. For each shop, print the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages so that each dish will get the pepper added once and no pepper is left, print -1.
Notes: NoteConsider the first example.In the first shop, Monocarp can only buy $$$0$$$ red pepper packages and $$$1$$$ black pepper package. Black pepper added to all dishes will sum up to $$$10 + 50 + 2 = 62$$$.In the second shop, Monocarp can buy any number of red and black pepper packages: $$$0$$$ and $$$3$$$, $$$1$$$ and $$$2$$$, $$$2$$$ and $$$1$$$ or $$$3$$$ and $$$0$$$. The optimal choice turns out to be either $$$1$$$ and $$$2$$$ or $$$2$$$ and $$$1$$$. Monocarp can add black pepper to the first dish, red pepper to the second dish and any pepper to the third dish, the total is $$$10 + 100 + 2 = 112$$$.In the third shop, Monocarp can only buy $$$1$$$ red pepper package and $$$0$$$ black pepper packages. Red pepper added to all dishes will sum up to $$$5 + 100 + 2 = 107$$$.In the fourth shop, Monocarp can only buy an even total number of packages. Since $$$n$$$ is odd, it's impossible to get exactly $$$n$$$ packages. Thus, the answer is $$$-1$$$.
Code:
from collections import *
from itertools import *
from functools import *
import math,sys
input = sys.stdin.buffer.readline
n = int(input())
AB = [tuple(map(int,input().split())) for _ in range(n)]
M = int(input())
XY = [tuple(map(int,input().split())) for _ in range(M)]
ans = []
from math import gcd
def modinv(a, b):
p = b
x, y, u, v = 1, 0, 0, 1
while b:
k = a // b
x -= k * u
y -= k * v
x, u = u, x
y, v = v, y
a, b = b, a % b
x %= p
if x < 0:
x += p
return x
def slc(A, B, mod):
#solve Ax=B mod
a = A
b = B
m = mod
d = gcd(a,gcd(b,m))
while d>1:
a //= d
b //= d
m //= d
d = gcd(a,gcd(b,m))
if gcd(a,m) != 1:
return -1
return (modinv(a,m)*b)%m
D = [a-b for a,b in AB]
S = sum(b for a,b in AB)
D.sort(reverse=True)
SD = list(accumulate([0]+D))
L = 0
for i in range(n-1,-1,-1):
if D[i]>0:
L = i+1
break
for x,y in XY:
d = gcd(x,y)
if n%d != 0:
print(-1)
continue
x0 = slc(x,n,y)
tb = y//d
ok = 0
ng = -10**10
while ok-ng>1:
mid = (ok+ng)//2
if x0+mid*tb >=0:
ok = mid
else:
ng = mid
x0 += tb*ok
if x0*x>n:
print(-1)
continue
def is_ok(k):
return ((n-x*(x0 + k*tb)) >= 0)&(x0 + k*tb >= 0)
k0 = (L-x*x0)//(tb*x)
ans = -1
flg = False
if is_ok(k0):
tmp = S + SD[x*(x0 + k0*tb)]
ans = max(ans,tmp)
if is_ok(k0+1):
tmp = S + SD[x*(x0 + (k0+1)*tb)]
ans = max(ans,tmp)
flg = True
if flg:
print(ans)
continue
ok = 0
ng = k0 + 1
while ng-ok>1:
mid = (ok+ng)//2
if is_ok(mid):
ok = mid
else:
# TODO: Your code here
ans = max(ans,S + SD[x*(x0 + ok*tb)])
print(ans)
|
from collections import *
from itertools import *
from functools import *
import math,sys
input = sys.stdin.buffer.readline
n = int(input())
AB = [tuple(map(int,input().split())) for _ in range(n)]
M = int(input())
XY = [tuple(map(int,input().split())) for _ in range(M)]
ans = []
from math import gcd
def modinv(a, b):
p = b
x, y, u, v = 1, 0, 0, 1
while b:
k = a // b
x -= k * u
y -= k * v
x, u = u, x
y, v = v, y
a, b = b, a % b
x %= p
if x < 0:
x += p
return x
def slc(A, B, mod):
#solve Ax=B mod
a = A
b = B
m = mod
d = gcd(a,gcd(b,m))
while d>1:
a //= d
b //= d
m //= d
d = gcd(a,gcd(b,m))
if gcd(a,m) != 1:
return -1
return (modinv(a,m)*b)%m
D = [a-b for a,b in AB]
S = sum(b for a,b in AB)
D.sort(reverse=True)
SD = list(accumulate([0]+D))
L = 0
for i in range(n-1,-1,-1):
if D[i]>0:
L = i+1
break
for x,y in XY:
d = gcd(x,y)
if n%d != 0:
print(-1)
continue
x0 = slc(x,n,y)
tb = y//d
ok = 0
ng = -10**10
while ok-ng>1:
mid = (ok+ng)//2
if x0+mid*tb >=0:
ok = mid
else:
ng = mid
x0 += tb*ok
if x0*x>n:
print(-1)
continue
def is_ok(k):
return ((n-x*(x0 + k*tb)) >= 0)&(x0 + k*tb >= 0)
k0 = (L-x*x0)//(tb*x)
ans = -1
flg = False
if is_ok(k0):
tmp = S + SD[x*(x0 + k0*tb)]
ans = max(ans,tmp)
if is_ok(k0+1):
tmp = S + SD[x*(x0 + (k0+1)*tb)]
ans = max(ans,tmp)
flg = True
if flg:
print(ans)
continue
ok = 0
ng = k0 + 1
while ng-ok>1:
mid = (ok+ng)//2
if is_ok(mid):
ok = mid
else:
{{completion}}
ans = max(ans,S + SD[x*(x0 + ok*tb)])
print(ans)
|
ng = mid
|
[{"input": "3\n5 10\n100 50\n2 2\n4\n2 3\n1 1\n3 2\n2 2", "output": ["62\n112\n107\n-1"]}, {"input": "10\n3 1\n2 3\n1 1\n2 1\n6 3\n1 4\n4 3\n1 3\n5 3\n5 4\n10\n8 10\n9 3\n1 4\n2 5\n8 3\n3 5\n1 6\n7 2\n6 7\n3 1", "output": ["26\n-1\n36\n30\n-1\n26\n34\n26\n-1\n36"]}]
|
block_completion_005536
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Monocarp is going to host a party for his friends. He prepared $$$n$$$ dishes and is about to serve them. First, he has to add some powdered pepper to each of themΒ β otherwise, the dishes will be pretty tasteless.The $$$i$$$-th dish has two values $$$a_i$$$ and $$$b_i$$$Β β its tastiness with red pepper added or black pepper added, respectively. Monocarp won't add both peppers to any dish, won't add any pepper multiple times, and won't leave any dish without the pepper added.Before adding the pepper, Monocarp should first purchase the said pepper in some shop. There are $$$m$$$ shops in his local area. The $$$j$$$-th of them has packages of red pepper sufficient for $$$x_j$$$ servings and packages of black pepper sufficient for $$$y_j$$$ servings.Monocarp goes to exactly one shop, purchases multiple (possibly, zero) packages of each pepper in such a way that each dish will get the pepper added once, and no pepper is left. More formally, if he purchases $$$x$$$ red pepper packages and $$$y$$$ black pepper packages, then $$$x$$$ and $$$y$$$ should be non-negative and $$$x \cdot x_j + y \cdot y_j$$$ should be equal to $$$n$$$.For each shop, determine the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages in the said way, print -1.
Input Specification: The first line contains a single integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$)Β β the number of dishes. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 10^9$$$)Β β the tastiness of the $$$i$$$-th dish with red pepper added or black pepper added, respectively. The next line contains a single integer $$$m$$$ ($$$1 \le m \le 3 \cdot 10^5$$$)Β β the number of shops. The $$$j$$$-th of the next $$$m$$$ lines contains two integers $$$x_j$$$ and $$$y_j$$$ ($$$1 \le x_j, y_j \le n$$$)Β β the number of servings the red and the black pepper packages are sufficient for in the $$$j$$$-th shop, respectively.
Output Specification: Print $$$m$$$ integers. For each shop, print the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages so that each dish will get the pepper added once and no pepper is left, print -1.
Notes: NoteConsider the first example.In the first shop, Monocarp can only buy $$$0$$$ red pepper packages and $$$1$$$ black pepper package. Black pepper added to all dishes will sum up to $$$10 + 50 + 2 = 62$$$.In the second shop, Monocarp can buy any number of red and black pepper packages: $$$0$$$ and $$$3$$$, $$$1$$$ and $$$2$$$, $$$2$$$ and $$$1$$$ or $$$3$$$ and $$$0$$$. The optimal choice turns out to be either $$$1$$$ and $$$2$$$ or $$$2$$$ and $$$1$$$. Monocarp can add black pepper to the first dish, red pepper to the second dish and any pepper to the third dish, the total is $$$10 + 100 + 2 = 112$$$.In the third shop, Monocarp can only buy $$$1$$$ red pepper package and $$$0$$$ black pepper packages. Red pepper added to all dishes will sum up to $$$5 + 100 + 2 = 107$$$.In the fourth shop, Monocarp can only buy an even total number of packages. Since $$$n$$$ is odd, it's impossible to get exactly $$$n$$$ packages. Thus, the answer is $$$-1$$$.
Code:
import math
import sys
input = sys.stdin.readline
class Dish:
def __init__(self):
self.a=0
self.b=0
def exgcd(a,b):
if b:
x,y=exgcd(b,a%b)
return y,x-a//b*y
return 1,0
n=int(input())
dish=[Dish() for i in range(n)]
val=[0 for i in range(n+5)]
for i in range(n):
dish[i].a,dish[i].b=map(int,input().split(' '))
val[0]+=dish[i].b
dish.sort(key=lambda x: x.b-x.a)
valMax=val[0]
maxW=0
for i in range(n):
val[i+1]=val[i]-dish[i].b+dish[i].a
if valMax<val[i+1]:
maxW=i+1
valMax=val[i+1]
#print(val)
for o in range(int(input())):
a,b=map(int,input().split(' '))
gcdAB=math.gcd(a,b)
a//=gcdAB
b//=gcdAB
if n%gcdAB:
print("-1")
continue
c=n//gcdAB
x0,y0=exgcd(a,b)
x1=x0*c
y1=y0*c
kmax=math.floor(y1/a)
kmin=math.ceil(-x1/b)
if kmin>kmax:
print(-1)
continue
if a*gcdAB*(x1+kmax*b)<maxW:
print(val[a*gcdAB*(x1+kmax*b)])
elif a*gcdAB*(x1+kmin*b)>maxW:
# TODO: Your code here
else:
k=(maxW/a/gcdAB-x1)/b
print(max(val[a*gcdAB*(x1+math.ceil(k)*b)],val[a*gcdAB*(x1+math.floor(k)*b)]))
#print(x1,y1)
#print(kmin,kmax)
#print("----")
|
import math
import sys
input = sys.stdin.readline
class Dish:
def __init__(self):
self.a=0
self.b=0
def exgcd(a,b):
if b:
x,y=exgcd(b,a%b)
return y,x-a//b*y
return 1,0
n=int(input())
dish=[Dish() for i in range(n)]
val=[0 for i in range(n+5)]
for i in range(n):
dish[i].a,dish[i].b=map(int,input().split(' '))
val[0]+=dish[i].b
dish.sort(key=lambda x: x.b-x.a)
valMax=val[0]
maxW=0
for i in range(n):
val[i+1]=val[i]-dish[i].b+dish[i].a
if valMax<val[i+1]:
maxW=i+1
valMax=val[i+1]
#print(val)
for o in range(int(input())):
a,b=map(int,input().split(' '))
gcdAB=math.gcd(a,b)
a//=gcdAB
b//=gcdAB
if n%gcdAB:
print("-1")
continue
c=n//gcdAB
x0,y0=exgcd(a,b)
x1=x0*c
y1=y0*c
kmax=math.floor(y1/a)
kmin=math.ceil(-x1/b)
if kmin>kmax:
print(-1)
continue
if a*gcdAB*(x1+kmax*b)<maxW:
print(val[a*gcdAB*(x1+kmax*b)])
elif a*gcdAB*(x1+kmin*b)>maxW:
{{completion}}
else:
k=(maxW/a/gcdAB-x1)/b
print(max(val[a*gcdAB*(x1+math.ceil(k)*b)],val[a*gcdAB*(x1+math.floor(k)*b)]))
#print(x1,y1)
#print(kmin,kmax)
#print("----")
|
print(val[a*gcdAB*(x1+kmin*b)])
|
[{"input": "3\n5 10\n100 50\n2 2\n4\n2 3\n1 1\n3 2\n2 2", "output": ["62\n112\n107\n-1"]}, {"input": "10\n3 1\n2 3\n1 1\n2 1\n6 3\n1 4\n4 3\n1 3\n5 3\n5 4\n10\n8 10\n9 3\n1 4\n2 5\n8 3\n3 5\n1 6\n7 2\n6 7\n3 1", "output": ["26\n-1\n36\n30\n-1\n26\n34\n26\n-1\n36"]}]
|
block_completion_005537
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Monocarp is going to host a party for his friends. He prepared $$$n$$$ dishes and is about to serve them. First, he has to add some powdered pepper to each of themΒ β otherwise, the dishes will be pretty tasteless.The $$$i$$$-th dish has two values $$$a_i$$$ and $$$b_i$$$Β β its tastiness with red pepper added or black pepper added, respectively. Monocarp won't add both peppers to any dish, won't add any pepper multiple times, and won't leave any dish without the pepper added.Before adding the pepper, Monocarp should first purchase the said pepper in some shop. There are $$$m$$$ shops in his local area. The $$$j$$$-th of them has packages of red pepper sufficient for $$$x_j$$$ servings and packages of black pepper sufficient for $$$y_j$$$ servings.Monocarp goes to exactly one shop, purchases multiple (possibly, zero) packages of each pepper in such a way that each dish will get the pepper added once, and no pepper is left. More formally, if he purchases $$$x$$$ red pepper packages and $$$y$$$ black pepper packages, then $$$x$$$ and $$$y$$$ should be non-negative and $$$x \cdot x_j + y \cdot y_j$$$ should be equal to $$$n$$$.For each shop, determine the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages in the said way, print -1.
Input Specification: The first line contains a single integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$)Β β the number of dishes. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 10^9$$$)Β β the tastiness of the $$$i$$$-th dish with red pepper added or black pepper added, respectively. The next line contains a single integer $$$m$$$ ($$$1 \le m \le 3 \cdot 10^5$$$)Β β the number of shops. The $$$j$$$-th of the next $$$m$$$ lines contains two integers $$$x_j$$$ and $$$y_j$$$ ($$$1 \le x_j, y_j \le n$$$)Β β the number of servings the red and the black pepper packages are sufficient for in the $$$j$$$-th shop, respectively.
Output Specification: Print $$$m$$$ integers. For each shop, print the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages so that each dish will get the pepper added once and no pepper is left, print -1.
Notes: NoteConsider the first example.In the first shop, Monocarp can only buy $$$0$$$ red pepper packages and $$$1$$$ black pepper package. Black pepper added to all dishes will sum up to $$$10 + 50 + 2 = 62$$$.In the second shop, Monocarp can buy any number of red and black pepper packages: $$$0$$$ and $$$3$$$, $$$1$$$ and $$$2$$$, $$$2$$$ and $$$1$$$ or $$$3$$$ and $$$0$$$. The optimal choice turns out to be either $$$1$$$ and $$$2$$$ or $$$2$$$ and $$$1$$$. Monocarp can add black pepper to the first dish, red pepper to the second dish and any pepper to the third dish, the total is $$$10 + 100 + 2 = 112$$$.In the third shop, Monocarp can only buy $$$1$$$ red pepper package and $$$0$$$ black pepper packages. Red pepper added to all dishes will sum up to $$$5 + 100 + 2 = 107$$$.In the fourth shop, Monocarp can only buy an even total number of packages. Since $$$n$$$ is odd, it's impossible to get exactly $$$n$$$ packages. Thus, the answer is $$$-1$$$.
Code:
import math
import sys
input = sys.stdin.readline
class Dish:
def __init__(self):
self.a=0
self.b=0
def exgcd(a,b):
if b:
x,y=exgcd(b,a%b)
return y,x-a//b*y
return 1,0
n=int(input())
dish=[Dish() for i in range(n)]
val=[0 for i in range(n+5)]
for i in range(n):
dish[i].a,dish[i].b=map(int,input().split(' '))
val[0]+=dish[i].b
dish.sort(key=lambda x: x.b-x.a)
valMax=val[0]
maxW=0
for i in range(n):
val[i+1]=val[i]-dish[i].b+dish[i].a
if valMax<val[i+1]:
maxW=i+1
valMax=val[i+1]
#print(val)
for o in range(int(input())):
a,b=map(int,input().split(' '))
gcdAB=math.gcd(a,b)
a//=gcdAB
b//=gcdAB
if n%gcdAB:
print("-1")
continue
c=n//gcdAB
x0,y0=exgcd(a,b)
x1=x0*c
y1=y0*c
kmax=math.floor(y1/a)
kmin=math.ceil(-x1/b)
if kmin>kmax:
print(-1)
continue
if a*gcdAB*(x1+kmax*b)<maxW:
print(val[a*gcdAB*(x1+kmax*b)])
elif a*gcdAB*(x1+kmin*b)>maxW:
print(val[a*gcdAB*(x1+kmin*b)])
else:
# TODO: Your code here
#print(x1,y1)
#print(kmin,kmax)
#print("----")
|
import math
import sys
input = sys.stdin.readline
class Dish:
def __init__(self):
self.a=0
self.b=0
def exgcd(a,b):
if b:
x,y=exgcd(b,a%b)
return y,x-a//b*y
return 1,0
n=int(input())
dish=[Dish() for i in range(n)]
val=[0 for i in range(n+5)]
for i in range(n):
dish[i].a,dish[i].b=map(int,input().split(' '))
val[0]+=dish[i].b
dish.sort(key=lambda x: x.b-x.a)
valMax=val[0]
maxW=0
for i in range(n):
val[i+1]=val[i]-dish[i].b+dish[i].a
if valMax<val[i+1]:
maxW=i+1
valMax=val[i+1]
#print(val)
for o in range(int(input())):
a,b=map(int,input().split(' '))
gcdAB=math.gcd(a,b)
a//=gcdAB
b//=gcdAB
if n%gcdAB:
print("-1")
continue
c=n//gcdAB
x0,y0=exgcd(a,b)
x1=x0*c
y1=y0*c
kmax=math.floor(y1/a)
kmin=math.ceil(-x1/b)
if kmin>kmax:
print(-1)
continue
if a*gcdAB*(x1+kmax*b)<maxW:
print(val[a*gcdAB*(x1+kmax*b)])
elif a*gcdAB*(x1+kmin*b)>maxW:
print(val[a*gcdAB*(x1+kmin*b)])
else:
{{completion}}
#print(x1,y1)
#print(kmin,kmax)
#print("----")
|
k=(maxW/a/gcdAB-x1)/b
print(max(val[a*gcdAB*(x1+math.ceil(k)*b)],val[a*gcdAB*(x1+math.floor(k)*b)]))
|
[{"input": "3\n5 10\n100 50\n2 2\n4\n2 3\n1 1\n3 2\n2 2", "output": ["62\n112\n107\n-1"]}, {"input": "10\n3 1\n2 3\n1 1\n2 1\n6 3\n1 4\n4 3\n1 3\n5 3\n5 4\n10\n8 10\n9 3\n1 4\n2 5\n8 3\n3 5\n1 6\n7 2\n6 7\n3 1", "output": ["26\n-1\n36\n30\n-1\n26\n34\n26\n-1\n36"]}]
|
block_completion_005538
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Consider a segment $$$[0, d]$$$ of the coordinate line. There are $$$n$$$ lanterns and $$$m$$$ points of interest in this segment.For each lantern, you can choose its power β an integer between $$$0$$$ and $$$d$$$ (inclusive). A lantern with coordinate $$$x$$$ illuminates the point of interest with coordinate $$$y$$$ if $$$|x - y|$$$ is less than or equal to the power of the lantern.A way to choose the power values for all lanterns is considered valid if every point of interest is illuminated by at least one lantern.You have to process $$$q$$$ queries. Each query is represented by one integer $$$f_i$$$. To answer the $$$i$$$-th query, you have to: add a lantern on coordinate $$$f_i$$$; calculate the number of valid ways to assign power values to all lanterns, and print it modulo $$$998244353$$$; remove the lantern you just added.
Input Specification: The first line contains three integers $$$d$$$, $$$n$$$ and $$$m$$$ ($$$4 \le d \le 3 \cdot 10^5$$$; $$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le m \le 16$$$) β the size of the segment, the number of lanterns and the number of points of interest, respectively. The second line contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$1 \le l_i \le d - 1$$$), where $$$l_i$$$ is the coordinate of the $$$i$$$-th lantern. The third line contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le d - 1$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th point of interest. The fourth line contains one integer $$$q$$$ ($$$1 \le q \le 5 \cdot 10^5$$$) β the number of queries. The fifth line contains $$$q$$$ integers $$$f_1, f_2, \dots, f_q$$$ ($$$1 \le f_i \le d - 1$$$), where $$$f_i$$$ is the integer representing the $$$i$$$-th query. Additional constraint on the input: during the processing of each query, no coordinate contains more than one object (i.βe. there cannot be two or more lanterns with the same coordinate, two or more points of interest with the same coordinate, or a lantern and a point of interest with the same coordinate).
Output Specification: For each query, print one integer β the answer to it, taken modulo $$$998244353$$$.
Code:
input = __import__('sys').stdin.readline
MOD = 998244353
d, n, m = map(int, input().split())
lamps = list(sorted(map(int, input().split()))) # n
points = list(sorted(map(int, input().split()))) # m
# 1. O(m^2) to find all interesting points (sould be around m^2 points)
positions = [x for x in points]
positions.append(0)
positions.append(d)
for i in range(m):
for j in range(i+1, m):
mid = (points[i] + points[j]) // 2
positions.append(mid)
positions.append(mid+1)
positions = list(sorted(set(positions)))
posmap = {x: i for i, x in enumerate(positions)}
# print('points', points)
# print('positions', positions)
# 2. O(nm) to precompute QueryL and QueryR
i = 0
queryL = []
for p in points:
queries = [0] * len(positions)
while positions[i] < p:
i += 1
j = i
q = 1
for x in lamps:
if x <= p:
continue
while x > positions[j]:
queries[j] = q
j += 1
q = q * (x - p) % MOD
while j < len(positions):
queries[j] = q
j += 1
queryL.append(queries)
# print('L p:', p, queries)
i = len(positions)-1
queryR = []
for p in points[::-1]:
queries = [0] * len(positions)
while positions[i] > p:
i -= 1
j = i
q = 1
for x in lamps[::-1]:
if x > p:
continue
while x < positions[j]:
queries[j] = q
j -= 1
q = q * (p - x) % MOD
while j >= 0:
queries[j] = q
j -= 1
queryR.append(queries)
# print('R p:', p, queries)
queryR = queryR[::-1]
# print('queryL', queryL)
# print('queryR', queryR)
# 3. O(m*2^m) to convert all mask to product of QueryL & QueryR and calculate the inclusion-exclusion & accumulate its SumQueryL[L..R] SumQueryR[L..R] values
querySums = [[[0]*len(positions) for _ in range(len(points))] for _ in range(2)]
current_ans = 0
for mask in range(1, 1 << m):
keys = []
prev_idx = -1
popcnt = 0
q = 1
for i in range(m):
if (mask >> i) & 1:
p = points[i]
if prev_idx == -1:
keys.append((1, i, 0))
q = q * queryR[i][0] % MOD
else:
# TODO: Your code here
prev_idx = i
popcnt += 1
keys.append((0, prev_idx, len(positions)-1))
q = q * queryL[prev_idx][-1] % MOD
if popcnt & 1:
current_ans = (current_ans - q) % MOD
for i, j, k in keys:
querySums[i][j][k] = (querySums[i][j][k] - q) % MOD
else:
current_ans = (current_ans + q) % MOD
for i, j, k in keys:
querySums[i][j][k] = (querySums[i][j][k] + q) % MOD
# print('mask', ('{:0' + str(m) + 'b}').format(mask), q, keys)
for j in range(m):
for k in range(len(positions) -2, -1, -1):
querySums[0][j][k] = (querySums[0][j][k] + querySums[0][j][k+1]) % MOD
for k in range(1, len(positions)):
querySums[1][j][k] = (querySums[1][j][k] + querySums[1][j][k-1]) % MOD
# 4. for each query, update the total ans by affected SumQueryL and SumQueryR (those with L <= x <= R)
current_ans += pow(d+1, n+1, MOD)
current_ans %= MOD
_ = int(input())
for x in map(int, input().split()):
ans = current_ans
for i in range(len(positions)):
if positions[i] >= x:
pos = i
break
for j in range(m):
if points[j] < x:
total = querySums[0][j][pos]
ans -= total
ans += total * (x - points[j]) % MOD
ans %= MOD
for i in range(len(positions)-1, -1, -1):
if positions[i] <= x:
pos = i
break
for j in range(m):
if x <= points[j]:
total = querySums[1][j][pos]
ans -= total
ans += total * (points[j] - x) % MOD
ans %= MOD
print(ans)
|
input = __import__('sys').stdin.readline
MOD = 998244353
d, n, m = map(int, input().split())
lamps = list(sorted(map(int, input().split()))) # n
points = list(sorted(map(int, input().split()))) # m
# 1. O(m^2) to find all interesting points (sould be around m^2 points)
positions = [x for x in points]
positions.append(0)
positions.append(d)
for i in range(m):
for j in range(i+1, m):
mid = (points[i] + points[j]) // 2
positions.append(mid)
positions.append(mid+1)
positions = list(sorted(set(positions)))
posmap = {x: i for i, x in enumerate(positions)}
# print('points', points)
# print('positions', positions)
# 2. O(nm) to precompute QueryL and QueryR
i = 0
queryL = []
for p in points:
queries = [0] * len(positions)
while positions[i] < p:
i += 1
j = i
q = 1
for x in lamps:
if x <= p:
continue
while x > positions[j]:
queries[j] = q
j += 1
q = q * (x - p) % MOD
while j < len(positions):
queries[j] = q
j += 1
queryL.append(queries)
# print('L p:', p, queries)
i = len(positions)-1
queryR = []
for p in points[::-1]:
queries = [0] * len(positions)
while positions[i] > p:
i -= 1
j = i
q = 1
for x in lamps[::-1]:
if x > p:
continue
while x < positions[j]:
queries[j] = q
j -= 1
q = q * (p - x) % MOD
while j >= 0:
queries[j] = q
j -= 1
queryR.append(queries)
# print('R p:', p, queries)
queryR = queryR[::-1]
# print('queryL', queryL)
# print('queryR', queryR)
# 3. O(m*2^m) to convert all mask to product of QueryL & QueryR and calculate the inclusion-exclusion & accumulate its SumQueryL[L..R] SumQueryR[L..R] values
querySums = [[[0]*len(positions) for _ in range(len(points))] for _ in range(2)]
current_ans = 0
for mask in range(1, 1 << m):
keys = []
prev_idx = -1
popcnt = 0
q = 1
for i in range(m):
if (mask >> i) & 1:
p = points[i]
if prev_idx == -1:
keys.append((1, i, 0))
q = q * queryR[i][0] % MOD
else:
{{completion}}
prev_idx = i
popcnt += 1
keys.append((0, prev_idx, len(positions)-1))
q = q * queryL[prev_idx][-1] % MOD
if popcnt & 1:
current_ans = (current_ans - q) % MOD
for i, j, k in keys:
querySums[i][j][k] = (querySums[i][j][k] - q) % MOD
else:
current_ans = (current_ans + q) % MOD
for i, j, k in keys:
querySums[i][j][k] = (querySums[i][j][k] + q) % MOD
# print('mask', ('{:0' + str(m) + 'b}').format(mask), q, keys)
for j in range(m):
for k in range(len(positions) -2, -1, -1):
querySums[0][j][k] = (querySums[0][j][k] + querySums[0][j][k+1]) % MOD
for k in range(1, len(positions)):
querySums[1][j][k] = (querySums[1][j][k] + querySums[1][j][k-1]) % MOD
# 4. for each query, update the total ans by affected SumQueryL and SumQueryR (those with L <= x <= R)
current_ans += pow(d+1, n+1, MOD)
current_ans %= MOD
_ = int(input())
for x in map(int, input().split()):
ans = current_ans
for i in range(len(positions)):
if positions[i] >= x:
pos = i
break
for j in range(m):
if points[j] < x:
total = querySums[0][j][pos]
ans -= total
ans += total * (x - points[j]) % MOD
ans %= MOD
for i in range(len(positions)-1, -1, -1):
if positions[i] <= x:
pos = i
break
for j in range(m):
if x <= points[j]:
total = querySums[1][j][pos]
ans -= total
ans += total * (points[j] - x) % MOD
ans %= MOD
print(ans)
|
prev_p = points[prev_idx]
mid = (prev_p + p) // 2
keys.append((0, prev_idx, posmap[mid]))
q = q * queryL[prev_idx][posmap[mid]] % MOD
keys.append((1, i, posmap[mid+1]))
q = q * queryR[i][posmap[mid+1]] % MOD
|
[{"input": "6 1 1\n4\n3\n3\n2 1 5", "output": ["48\n47\n47"]}, {"input": "6 1 2\n4\n2 5\n2\n1 3", "output": ["44\n46"]}, {"input": "20 1 2\n11\n15 7\n1\n8", "output": ["413"]}, {"input": "20 3 5\n5 7 18\n1 6 3 10 19\n5\n4 17 15 8 9", "output": ["190431\n187503\n188085\n189903\n189708"]}]
|
block_completion_005549
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Consider a segment $$$[0, d]$$$ of the coordinate line. There are $$$n$$$ lanterns and $$$m$$$ points of interest in this segment.For each lantern, you can choose its power β an integer between $$$0$$$ and $$$d$$$ (inclusive). A lantern with coordinate $$$x$$$ illuminates the point of interest with coordinate $$$y$$$ if $$$|x - y|$$$ is less than or equal to the power of the lantern.A way to choose the power values for all lanterns is considered valid if every point of interest is illuminated by at least one lantern.You have to process $$$q$$$ queries. Each query is represented by one integer $$$f_i$$$. To answer the $$$i$$$-th query, you have to: add a lantern on coordinate $$$f_i$$$; calculate the number of valid ways to assign power values to all lanterns, and print it modulo $$$998244353$$$; remove the lantern you just added.
Input Specification: The first line contains three integers $$$d$$$, $$$n$$$ and $$$m$$$ ($$$4 \le d \le 3 \cdot 10^5$$$; $$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le m \le 16$$$) β the size of the segment, the number of lanterns and the number of points of interest, respectively. The second line contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$1 \le l_i \le d - 1$$$), where $$$l_i$$$ is the coordinate of the $$$i$$$-th lantern. The third line contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le d - 1$$$), where $$$p_i$$$ is the coordinate of the $$$i$$$-th point of interest. The fourth line contains one integer $$$q$$$ ($$$1 \le q \le 5 \cdot 10^5$$$) β the number of queries. The fifth line contains $$$q$$$ integers $$$f_1, f_2, \dots, f_q$$$ ($$$1 \le f_i \le d - 1$$$), where $$$f_i$$$ is the integer representing the $$$i$$$-th query. Additional constraint on the input: during the processing of each query, no coordinate contains more than one object (i.βe. there cannot be two or more lanterns with the same coordinate, two or more points of interest with the same coordinate, or a lantern and a point of interest with the same coordinate).
Output Specification: For each query, print one integer β the answer to it, taken modulo $$$998244353$$$.
Code:
input = __import__('sys').stdin.readline
MOD = 998244353
d, n, m = map(int, input().split())
lamps = list(sorted(map(int, input().split()))) # n
points = list(sorted(map(int, input().split()))) # m
# 1. O(m^2) to find all interesting points (sould be around m^2 points)
positions = [x for x in points]
positions.append(0)
positions.append(d)
for i in range(m):
for j in range(i+1, m):
mid = (points[i] + points[j]) // 2
positions.append(mid)
positions.append(mid+1)
positions = list(sorted(set(positions)))
posmap = {x: i for i, x in enumerate(positions)}
# print('points', points)
# print('positions', positions)
# 2. O(nm) to precompute QueryL and QueryR
i = 0
queryL = []
for p in points:
queries = [0] * len(positions)
while positions[i] < p:
i += 1
j = i
q = 1
for x in lamps:
if x <= p:
continue
while x > positions[j]:
queries[j] = q
j += 1
q = q * (x - p) % MOD
while j < len(positions):
queries[j] = q
j += 1
queryL.append(queries)
# print('L p:', p, queries)
i = len(positions)-1
queryR = []
for p in points[::-1]:
queries = [0] * len(positions)
while positions[i] > p:
i -= 1
j = i
q = 1
for x in lamps[::-1]:
if x > p:
continue
while x < positions[j]:
queries[j] = q
j -= 1
q = q * (p - x) % MOD
while j >= 0:
queries[j] = q
j -= 1
queryR.append(queries)
# print('R p:', p, queries)
queryR = queryR[::-1]
# print('queryL', queryL)
# print('queryR', queryR)
# 3. O(m*2^m) to convert all mask to product of QueryL & QueryR and calculate the inclusion-exclusion & accumulate its SumQueryL[L..R] SumQueryR[L..R] values
querySums = [[[0]*len(positions) for _ in range(len(points))] for _ in range(2)]
current_ans = 0
for mask in range(1, 1 << m):
keys = []
prev_idx = -1
popcnt = 0
q = 1
for i in range(m):
if (mask >> i) & 1:
p = points[i]
if prev_idx == -1:
# TODO: Your code here
else:
prev_p = points[prev_idx]
mid = (prev_p + p) // 2
keys.append((0, prev_idx, posmap[mid]))
q = q * queryL[prev_idx][posmap[mid]] % MOD
keys.append((1, i, posmap[mid+1]))
q = q * queryR[i][posmap[mid+1]] % MOD
prev_idx = i
popcnt += 1
keys.append((0, prev_idx, len(positions)-1))
q = q * queryL[prev_idx][-1] % MOD
if popcnt & 1:
current_ans = (current_ans - q) % MOD
for i, j, k in keys:
querySums[i][j][k] = (querySums[i][j][k] - q) % MOD
else:
current_ans = (current_ans + q) % MOD
for i, j, k in keys:
querySums[i][j][k] = (querySums[i][j][k] + q) % MOD
# print('mask', ('{:0' + str(m) + 'b}').format(mask), q, keys)
for j in range(m):
for k in range(len(positions) -2, -1, -1):
querySums[0][j][k] = (querySums[0][j][k] + querySums[0][j][k+1]) % MOD
for k in range(1, len(positions)):
querySums[1][j][k] = (querySums[1][j][k] + querySums[1][j][k-1]) % MOD
# 4. for each query, update the total ans by affected SumQueryL and SumQueryR (those with L <= x <= R)
current_ans += pow(d+1, n+1, MOD)
current_ans %= MOD
_ = int(input())
for x in map(int, input().split()):
ans = current_ans
for i in range(len(positions)):
if positions[i] >= x:
pos = i
break
for j in range(m):
if points[j] < x:
total = querySums[0][j][pos]
ans -= total
ans += total * (x - points[j]) % MOD
ans %= MOD
for i in range(len(positions)-1, -1, -1):
if positions[i] <= x:
pos = i
break
for j in range(m):
if x <= points[j]:
total = querySums[1][j][pos]
ans -= total
ans += total * (points[j] - x) % MOD
ans %= MOD
print(ans)
|
input = __import__('sys').stdin.readline
MOD = 998244353
d, n, m = map(int, input().split())
lamps = list(sorted(map(int, input().split()))) # n
points = list(sorted(map(int, input().split()))) # m
# 1. O(m^2) to find all interesting points (sould be around m^2 points)
positions = [x for x in points]
positions.append(0)
positions.append(d)
for i in range(m):
for j in range(i+1, m):
mid = (points[i] + points[j]) // 2
positions.append(mid)
positions.append(mid+1)
positions = list(sorted(set(positions)))
posmap = {x: i for i, x in enumerate(positions)}
# print('points', points)
# print('positions', positions)
# 2. O(nm) to precompute QueryL and QueryR
i = 0
queryL = []
for p in points:
queries = [0] * len(positions)
while positions[i] < p:
i += 1
j = i
q = 1
for x in lamps:
if x <= p:
continue
while x > positions[j]:
queries[j] = q
j += 1
q = q * (x - p) % MOD
while j < len(positions):
queries[j] = q
j += 1
queryL.append(queries)
# print('L p:', p, queries)
i = len(positions)-1
queryR = []
for p in points[::-1]:
queries = [0] * len(positions)
while positions[i] > p:
i -= 1
j = i
q = 1
for x in lamps[::-1]:
if x > p:
continue
while x < positions[j]:
queries[j] = q
j -= 1
q = q * (p - x) % MOD
while j >= 0:
queries[j] = q
j -= 1
queryR.append(queries)
# print('R p:', p, queries)
queryR = queryR[::-1]
# print('queryL', queryL)
# print('queryR', queryR)
# 3. O(m*2^m) to convert all mask to product of QueryL & QueryR and calculate the inclusion-exclusion & accumulate its SumQueryL[L..R] SumQueryR[L..R] values
querySums = [[[0]*len(positions) for _ in range(len(points))] for _ in range(2)]
current_ans = 0
for mask in range(1, 1 << m):
keys = []
prev_idx = -1
popcnt = 0
q = 1
for i in range(m):
if (mask >> i) & 1:
p = points[i]
if prev_idx == -1:
{{completion}}
else:
prev_p = points[prev_idx]
mid = (prev_p + p) // 2
keys.append((0, prev_idx, posmap[mid]))
q = q * queryL[prev_idx][posmap[mid]] % MOD
keys.append((1, i, posmap[mid+1]))
q = q * queryR[i][posmap[mid+1]] % MOD
prev_idx = i
popcnt += 1
keys.append((0, prev_idx, len(positions)-1))
q = q * queryL[prev_idx][-1] % MOD
if popcnt & 1:
current_ans = (current_ans - q) % MOD
for i, j, k in keys:
querySums[i][j][k] = (querySums[i][j][k] - q) % MOD
else:
current_ans = (current_ans + q) % MOD
for i, j, k in keys:
querySums[i][j][k] = (querySums[i][j][k] + q) % MOD
# print('mask', ('{:0' + str(m) + 'b}').format(mask), q, keys)
for j in range(m):
for k in range(len(positions) -2, -1, -1):
querySums[0][j][k] = (querySums[0][j][k] + querySums[0][j][k+1]) % MOD
for k in range(1, len(positions)):
querySums[1][j][k] = (querySums[1][j][k] + querySums[1][j][k-1]) % MOD
# 4. for each query, update the total ans by affected SumQueryL and SumQueryR (those with L <= x <= R)
current_ans += pow(d+1, n+1, MOD)
current_ans %= MOD
_ = int(input())
for x in map(int, input().split()):
ans = current_ans
for i in range(len(positions)):
if positions[i] >= x:
pos = i
break
for j in range(m):
if points[j] < x:
total = querySums[0][j][pos]
ans -= total
ans += total * (x - points[j]) % MOD
ans %= MOD
for i in range(len(positions)-1, -1, -1):
if positions[i] <= x:
pos = i
break
for j in range(m):
if x <= points[j]:
total = querySums[1][j][pos]
ans -= total
ans += total * (points[j] - x) % MOD
ans %= MOD
print(ans)
|
keys.append((1, i, 0))
q = q * queryR[i][0] % MOD
|
[{"input": "6 1 1\n4\n3\n3\n2 1 5", "output": ["48\n47\n47"]}, {"input": "6 1 2\n4\n2 5\n2\n1 3", "output": ["44\n46"]}, {"input": "20 1 2\n11\n15 7\n1\n8", "output": ["413"]}, {"input": "20 3 5\n5 7 18\n1 6 3 10 19\n5\n4 17 15 8 9", "output": ["190431\n187503\n188085\n189903\n189708"]}]
|
block_completion_005550
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You have a square chessboard of size $$$n \times n$$$. Rows are numbered from top to bottom with numbers from $$$1$$$ to $$$n$$$, and columnsΒ β from left to right with numbers from $$$1$$$ to $$$n$$$. So, each cell is denoted with pair of integers $$$(x, y)$$$ ($$$1 \le x, y \le n$$$), where $$$x$$$ is a row number and $$$y$$$ is a column number.You have to perform $$$q$$$ queries of three types: Put a new rook in cell $$$(x, y)$$$. Remove a rook from cell $$$(x, y)$$$. It's guaranteed that the rook was put in this cell before. Check if each cell of subrectangle $$$(x_1, y_1) - (x_2, y_2)$$$ of the board is attacked by at least one rook. Subrectangle is a set of cells $$$(x, y)$$$ such that for each cell two conditions are satisfied: $$$x_1 \le x \le x_2$$$ and $$$y_1 \le y \le y_2$$$.Recall that cell $$$(a, b)$$$ is attacked by a rook placed in cell $$$(c, d)$$$ if either $$$a = c$$$ or $$$b = d$$$. In particular, the cell containing a rook is attacked by this rook.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le q \le 2 \cdot 10^5$$$)Β β the size of the chessboard and the number of queries, respectively. Each of the following $$$q$$$ lines contains description of a query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2, 3\}$$$) which denotes type of a query: If $$$t = 1$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinated of the cell where the new rook should be put in. It's guaranteed that there is no rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 2$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinates of the cell to remove a rook from. It's guaranteed that there is a rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 3$$$, four integers $$$x_1, y_1, x_2$$$ and $$$y_2$$$ follows ($$$1 \le x_1 \le x_2 \le n$$$, $$$1 \le y_1 \le y_2 \le n$$$)Β β subrectangle to check if each cell of it is attacked by at least one rook. It's guaranteed that among $$$q$$$ queries there is at least one query of the third type.
Output Specification: Print the answer for each query of the third type in a separate line. Print "Yes" (without quotes) if each cell of the subrectangle is attacked by at least one rook. Otherwise print "No" (without quotes).
Notes: NoteConsider example. After the first two queries the board will look like the following picture (the letter $$$R$$$ denotes cells in which rooks are located, the subrectangle of the query of the third type is highlighted in green): Chessboard after performing the third and the fourth queries: Chessboard after performing the fifth and the sixth queries: Chessboard after performing the seventh and the eighth queries: Chessboard after performing the last two queries:
Code:
import sys
input=sys.stdin.readline
R=lambda:map(int,input().split())
n,m=R();r,c,tr,tc=[0]*(n+1),[0]*(n+1),[0]*(n+1),[0]*(n+1)
def A(t,i,v):
while i<=n:t[i]+=v;i+=i&(-i)
def Q(t,i):
s=0
while i:s+=t[i];i-=i&(-i)
return s
for _ in range(m):
v=[*R()];op,x,y=v[:3]
if op==1:
r[x]+=1;c[y]+=1
if r[x]==1:A(tr,x,1)
if c[y]==1:A(tc,y,1)
elif op==2:
r[x]-=1;c[y]-=1
if r[x]==0:# TODO: Your code here
if c[y]==0:A(tc,y,-1)
else:
x1,y1=v[3:]
print('Yes' if Q(tr,x1)-Q(tr,x-1)==x1-x+1 or Q(tc,y1)-Q(tc,y-1)==y1-y+1 else 'No')
|
import sys
input=sys.stdin.readline
R=lambda:map(int,input().split())
n,m=R();r,c,tr,tc=[0]*(n+1),[0]*(n+1),[0]*(n+1),[0]*(n+1)
def A(t,i,v):
while i<=n:t[i]+=v;i+=i&(-i)
def Q(t,i):
s=0
while i:s+=t[i];i-=i&(-i)
return s
for _ in range(m):
v=[*R()];op,x,y=v[:3]
if op==1:
r[x]+=1;c[y]+=1
if r[x]==1:A(tr,x,1)
if c[y]==1:A(tc,y,1)
elif op==2:
r[x]-=1;c[y]-=1
if r[x]==0:{{completion}}
if c[y]==0:A(tc,y,-1)
else:
x1,y1=v[3:]
print('Yes' if Q(tr,x1)-Q(tr,x-1)==x1-x+1 or Q(tc,y1)-Q(tc,y-1)==y1-y+1 else 'No')
|
A(tr,x,-1)
|
[{"input": "8 10\n1 2 4\n3 6 2 7 2\n1 3 2\n3 6 2 7 2\n1 4 3\n3 2 6 4 8\n2 4 3\n3 2 6 4 8\n1 4 8\n3 2 6 4 8", "output": ["No\nYes\nYes\nNo\nYes"]}]
|
block_completion_005571
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You have a square chessboard of size $$$n \times n$$$. Rows are numbered from top to bottom with numbers from $$$1$$$ to $$$n$$$, and columnsΒ β from left to right with numbers from $$$1$$$ to $$$n$$$. So, each cell is denoted with pair of integers $$$(x, y)$$$ ($$$1 \le x, y \le n$$$), where $$$x$$$ is a row number and $$$y$$$ is a column number.You have to perform $$$q$$$ queries of three types: Put a new rook in cell $$$(x, y)$$$. Remove a rook from cell $$$(x, y)$$$. It's guaranteed that the rook was put in this cell before. Check if each cell of subrectangle $$$(x_1, y_1) - (x_2, y_2)$$$ of the board is attacked by at least one rook. Subrectangle is a set of cells $$$(x, y)$$$ such that for each cell two conditions are satisfied: $$$x_1 \le x \le x_2$$$ and $$$y_1 \le y \le y_2$$$.Recall that cell $$$(a, b)$$$ is attacked by a rook placed in cell $$$(c, d)$$$ if either $$$a = c$$$ or $$$b = d$$$. In particular, the cell containing a rook is attacked by this rook.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le q \le 2 \cdot 10^5$$$)Β β the size of the chessboard and the number of queries, respectively. Each of the following $$$q$$$ lines contains description of a query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2, 3\}$$$) which denotes type of a query: If $$$t = 1$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinated of the cell where the new rook should be put in. It's guaranteed that there is no rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 2$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinates of the cell to remove a rook from. It's guaranteed that there is a rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 3$$$, four integers $$$x_1, y_1, x_2$$$ and $$$y_2$$$ follows ($$$1 \le x_1 \le x_2 \le n$$$, $$$1 \le y_1 \le y_2 \le n$$$)Β β subrectangle to check if each cell of it is attacked by at least one rook. It's guaranteed that among $$$q$$$ queries there is at least one query of the third type.
Output Specification: Print the answer for each query of the third type in a separate line. Print "Yes" (without quotes) if each cell of the subrectangle is attacked by at least one rook. Otherwise print "No" (without quotes).
Notes: NoteConsider example. After the first two queries the board will look like the following picture (the letter $$$R$$$ denotes cells in which rooks are located, the subrectangle of the query of the third type is highlighted in green): Chessboard after performing the third and the fourth queries: Chessboard after performing the fifth and the sixth queries: Chessboard after performing the seventh and the eighth queries: Chessboard after performing the last two queries:
Code:
import sys
input=sys.stdin.readline
R=lambda:map(int,input().split())
n,m=R();r,c,tr,tc=[0]*(n+1),[0]*(n+1),[0]*(n+1),[0]*(n+1)
def A(t,i,v):
while i<=n:t[i]+=v;i+=i&(-i)
def Q(t,i):
s=0
while i:s+=t[i];i-=i&(-i)
return s
for _ in range(m):
v=[*R()];op,x,y=v[:3]
if op==1:
r[x]+=1;c[y]+=1
if r[x]==1:A(tr,x,1)
if c[y]==1:A(tc,y,1)
elif op==2:
r[x]-=1;c[y]-=1
if r[x]==0:A(tr,x,-1)
if c[y]==0:# TODO: Your code here
else:
x1,y1=v[3:]
print('Yes' if Q(tr,x1)-Q(tr,x-1)==x1-x+1 or Q(tc,y1)-Q(tc,y-1)==y1-y+1 else 'No')
|
import sys
input=sys.stdin.readline
R=lambda:map(int,input().split())
n,m=R();r,c,tr,tc=[0]*(n+1),[0]*(n+1),[0]*(n+1),[0]*(n+1)
def A(t,i,v):
while i<=n:t[i]+=v;i+=i&(-i)
def Q(t,i):
s=0
while i:s+=t[i];i-=i&(-i)
return s
for _ in range(m):
v=[*R()];op,x,y=v[:3]
if op==1:
r[x]+=1;c[y]+=1
if r[x]==1:A(tr,x,1)
if c[y]==1:A(tc,y,1)
elif op==2:
r[x]-=1;c[y]-=1
if r[x]==0:A(tr,x,-1)
if c[y]==0:{{completion}}
else:
x1,y1=v[3:]
print('Yes' if Q(tr,x1)-Q(tr,x-1)==x1-x+1 or Q(tc,y1)-Q(tc,y-1)==y1-y+1 else 'No')
|
A(tc,y,-1)
|
[{"input": "8 10\n1 2 4\n3 6 2 7 2\n1 3 2\n3 6 2 7 2\n1 4 3\n3 2 6 4 8\n2 4 3\n3 2 6 4 8\n1 4 8\n3 2 6 4 8", "output": ["No\nYes\nYes\nNo\nYes"]}]
|
block_completion_005572
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You have a square chessboard of size $$$n \times n$$$. Rows are numbered from top to bottom with numbers from $$$1$$$ to $$$n$$$, and columnsΒ β from left to right with numbers from $$$1$$$ to $$$n$$$. So, each cell is denoted with pair of integers $$$(x, y)$$$ ($$$1 \le x, y \le n$$$), where $$$x$$$ is a row number and $$$y$$$ is a column number.You have to perform $$$q$$$ queries of three types: Put a new rook in cell $$$(x, y)$$$. Remove a rook from cell $$$(x, y)$$$. It's guaranteed that the rook was put in this cell before. Check if each cell of subrectangle $$$(x_1, y_1) - (x_2, y_2)$$$ of the board is attacked by at least one rook. Subrectangle is a set of cells $$$(x, y)$$$ such that for each cell two conditions are satisfied: $$$x_1 \le x \le x_2$$$ and $$$y_1 \le y \le y_2$$$.Recall that cell $$$(a, b)$$$ is attacked by a rook placed in cell $$$(c, d)$$$ if either $$$a = c$$$ or $$$b = d$$$. In particular, the cell containing a rook is attacked by this rook.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le q \le 2 \cdot 10^5$$$)Β β the size of the chessboard and the number of queries, respectively. Each of the following $$$q$$$ lines contains description of a query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2, 3\}$$$) which denotes type of a query: If $$$t = 1$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinated of the cell where the new rook should be put in. It's guaranteed that there is no rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 2$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinates of the cell to remove a rook from. It's guaranteed that there is a rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 3$$$, four integers $$$x_1, y_1, x_2$$$ and $$$y_2$$$ follows ($$$1 \le x_1 \le x_2 \le n$$$, $$$1 \le y_1 \le y_2 \le n$$$)Β β subrectangle to check if each cell of it is attacked by at least one rook. It's guaranteed that among $$$q$$$ queries there is at least one query of the third type.
Output Specification: Print the answer for each query of the third type in a separate line. Print "Yes" (without quotes) if each cell of the subrectangle is attacked by at least one rook. Otherwise print "No" (without quotes).
Notes: NoteConsider example. After the first two queries the board will look like the following picture (the letter $$$R$$$ denotes cells in which rooks are located, the subrectangle of the query of the third type is highlighted in green): Chessboard after performing the third and the fourth queries: Chessboard after performing the fifth and the sixth queries: Chessboard after performing the seventh and the eighth queries: Chessboard after performing the last two queries:
Code:
class BIT:
def __init__(self, n, element):
self.num = n
self.ele = element
self.data = [self.ele] * (self.num + 1)
def calc(self, x, y):
return x + y
def update(self, idx, x):
while idx <= self.num:
self.data[idx] = self.calc(self.data[idx], x)
idx += idx & -idx
def sum(self, idx):
res = self.ele
while idx > 0:
res = self.calc(res, self.data[idx])
idx -= idx & -idx
return res
def prod(self, l, r):
return self.sum(r) - self.sum(l-1)
import sys
input = sys.stdin.readline
n, q = map(int, input().split())
cntb, cntv = [0] * n, [0] * n
bitb = BIT(n, 0)
bitv = BIT(n, 0)
for _ in range(q):
query = list(map(int, input().split()))
if query[0] == 1:
x, y = query[1], query[2]
if cntb[x-1] == 0:
bitb.update(x, 1)
cntb[x-1] += 1
if cntv[y-1] == 0:
bitv.update(y, 1)
cntv[y-1] += 1
elif query[0] == 2:
x, y = query[1], query[2]
cntb[x-1] -= 1
cntv[y-1] -= 1
if cntb[x-1] == 0:
# TODO: Your code here
if cntv[y-1] == 0:
bitv.update(y, -1)
else:
flg = bitb.prod(query[1], query[3]) == query[3] - query[1] + 1 or bitv.prod(query[2], query[4]) == query[4] - query[2] + 1
print("Yes" if flg else "No")
|
class BIT:
def __init__(self, n, element):
self.num = n
self.ele = element
self.data = [self.ele] * (self.num + 1)
def calc(self, x, y):
return x + y
def update(self, idx, x):
while idx <= self.num:
self.data[idx] = self.calc(self.data[idx], x)
idx += idx & -idx
def sum(self, idx):
res = self.ele
while idx > 0:
res = self.calc(res, self.data[idx])
idx -= idx & -idx
return res
def prod(self, l, r):
return self.sum(r) - self.sum(l-1)
import sys
input = sys.stdin.readline
n, q = map(int, input().split())
cntb, cntv = [0] * n, [0] * n
bitb = BIT(n, 0)
bitv = BIT(n, 0)
for _ in range(q):
query = list(map(int, input().split()))
if query[0] == 1:
x, y = query[1], query[2]
if cntb[x-1] == 0:
bitb.update(x, 1)
cntb[x-1] += 1
if cntv[y-1] == 0:
bitv.update(y, 1)
cntv[y-1] += 1
elif query[0] == 2:
x, y = query[1], query[2]
cntb[x-1] -= 1
cntv[y-1] -= 1
if cntb[x-1] == 0:
{{completion}}
if cntv[y-1] == 0:
bitv.update(y, -1)
else:
flg = bitb.prod(query[1], query[3]) == query[3] - query[1] + 1 or bitv.prod(query[2], query[4]) == query[4] - query[2] + 1
print("Yes" if flg else "No")
|
bitb.update(x, -1)
|
[{"input": "8 10\n1 2 4\n3 6 2 7 2\n1 3 2\n3 6 2 7 2\n1 4 3\n3 2 6 4 8\n2 4 3\n3 2 6 4 8\n1 4 8\n3 2 6 4 8", "output": ["No\nYes\nYes\nNo\nYes"]}]
|
block_completion_005573
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You have a square chessboard of size $$$n \times n$$$. Rows are numbered from top to bottom with numbers from $$$1$$$ to $$$n$$$, and columnsΒ β from left to right with numbers from $$$1$$$ to $$$n$$$. So, each cell is denoted with pair of integers $$$(x, y)$$$ ($$$1 \le x, y \le n$$$), where $$$x$$$ is a row number and $$$y$$$ is a column number.You have to perform $$$q$$$ queries of three types: Put a new rook in cell $$$(x, y)$$$. Remove a rook from cell $$$(x, y)$$$. It's guaranteed that the rook was put in this cell before. Check if each cell of subrectangle $$$(x_1, y_1) - (x_2, y_2)$$$ of the board is attacked by at least one rook. Subrectangle is a set of cells $$$(x, y)$$$ such that for each cell two conditions are satisfied: $$$x_1 \le x \le x_2$$$ and $$$y_1 \le y \le y_2$$$.Recall that cell $$$(a, b)$$$ is attacked by a rook placed in cell $$$(c, d)$$$ if either $$$a = c$$$ or $$$b = d$$$. In particular, the cell containing a rook is attacked by this rook.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le q \le 2 \cdot 10^5$$$)Β β the size of the chessboard and the number of queries, respectively. Each of the following $$$q$$$ lines contains description of a query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2, 3\}$$$) which denotes type of a query: If $$$t = 1$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinated of the cell where the new rook should be put in. It's guaranteed that there is no rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 2$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinates of the cell to remove a rook from. It's guaranteed that there is a rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 3$$$, four integers $$$x_1, y_1, x_2$$$ and $$$y_2$$$ follows ($$$1 \le x_1 \le x_2 \le n$$$, $$$1 \le y_1 \le y_2 \le n$$$)Β β subrectangle to check if each cell of it is attacked by at least one rook. It's guaranteed that among $$$q$$$ queries there is at least one query of the third type.
Output Specification: Print the answer for each query of the third type in a separate line. Print "Yes" (without quotes) if each cell of the subrectangle is attacked by at least one rook. Otherwise print "No" (without quotes).
Notes: NoteConsider example. After the first two queries the board will look like the following picture (the letter $$$R$$$ denotes cells in which rooks are located, the subrectangle of the query of the third type is highlighted in green): Chessboard after performing the third and the fourth queries: Chessboard after performing the fifth and the sixth queries: Chessboard after performing the seventh and the eighth queries: Chessboard after performing the last two queries:
Code:
class BIT:
def __init__(self, n, element):
self.num = n
self.ele = element
self.data = [self.ele] * (self.num + 1)
def calc(self, x, y):
return x + y
def update(self, idx, x):
while idx <= self.num:
self.data[idx] = self.calc(self.data[idx], x)
idx += idx & -idx
def sum(self, idx):
res = self.ele
while idx > 0:
res = self.calc(res, self.data[idx])
idx -= idx & -idx
return res
def prod(self, l, r):
return self.sum(r) - self.sum(l-1)
import sys
input = sys.stdin.readline
n, q = map(int, input().split())
cntb, cntv = [0] * n, [0] * n
bitb = BIT(n, 0)
bitv = BIT(n, 0)
for _ in range(q):
query = list(map(int, input().split()))
if query[0] == 1:
x, y = query[1], query[2]
if cntb[x-1] == 0:
bitb.update(x, 1)
cntb[x-1] += 1
if cntv[y-1] == 0:
bitv.update(y, 1)
cntv[y-1] += 1
elif query[0] == 2:
x, y = query[1], query[2]
cntb[x-1] -= 1
cntv[y-1] -= 1
if cntb[x-1] == 0:
bitb.update(x, -1)
if cntv[y-1] == 0:
# TODO: Your code here
else:
flg = bitb.prod(query[1], query[3]) == query[3] - query[1] + 1 or bitv.prod(query[2], query[4]) == query[4] - query[2] + 1
print("Yes" if flg else "No")
|
class BIT:
def __init__(self, n, element):
self.num = n
self.ele = element
self.data = [self.ele] * (self.num + 1)
def calc(self, x, y):
return x + y
def update(self, idx, x):
while idx <= self.num:
self.data[idx] = self.calc(self.data[idx], x)
idx += idx & -idx
def sum(self, idx):
res = self.ele
while idx > 0:
res = self.calc(res, self.data[idx])
idx -= idx & -idx
return res
def prod(self, l, r):
return self.sum(r) - self.sum(l-1)
import sys
input = sys.stdin.readline
n, q = map(int, input().split())
cntb, cntv = [0] * n, [0] * n
bitb = BIT(n, 0)
bitv = BIT(n, 0)
for _ in range(q):
query = list(map(int, input().split()))
if query[0] == 1:
x, y = query[1], query[2]
if cntb[x-1] == 0:
bitb.update(x, 1)
cntb[x-1] += 1
if cntv[y-1] == 0:
bitv.update(y, 1)
cntv[y-1] += 1
elif query[0] == 2:
x, y = query[1], query[2]
cntb[x-1] -= 1
cntv[y-1] -= 1
if cntb[x-1] == 0:
bitb.update(x, -1)
if cntv[y-1] == 0:
{{completion}}
else:
flg = bitb.prod(query[1], query[3]) == query[3] - query[1] + 1 or bitv.prod(query[2], query[4]) == query[4] - query[2] + 1
print("Yes" if flg else "No")
|
bitv.update(y, -1)
|
[{"input": "8 10\n1 2 4\n3 6 2 7 2\n1 3 2\n3 6 2 7 2\n1 4 3\n3 2 6 4 8\n2 4 3\n3 2 6 4 8\n1 4 8\n3 2 6 4 8", "output": ["No\nYes\nYes\nNo\nYes"]}]
|
block_completion_005574
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You have a square chessboard of size $$$n \times n$$$. Rows are numbered from top to bottom with numbers from $$$1$$$ to $$$n$$$, and columnsΒ β from left to right with numbers from $$$1$$$ to $$$n$$$. So, each cell is denoted with pair of integers $$$(x, y)$$$ ($$$1 \le x, y \le n$$$), where $$$x$$$ is a row number and $$$y$$$ is a column number.You have to perform $$$q$$$ queries of three types: Put a new rook in cell $$$(x, y)$$$. Remove a rook from cell $$$(x, y)$$$. It's guaranteed that the rook was put in this cell before. Check if each cell of subrectangle $$$(x_1, y_1) - (x_2, y_2)$$$ of the board is attacked by at least one rook. Subrectangle is a set of cells $$$(x, y)$$$ such that for each cell two conditions are satisfied: $$$x_1 \le x \le x_2$$$ and $$$y_1 \le y \le y_2$$$.Recall that cell $$$(a, b)$$$ is attacked by a rook placed in cell $$$(c, d)$$$ if either $$$a = c$$$ or $$$b = d$$$. In particular, the cell containing a rook is attacked by this rook.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le q \le 2 \cdot 10^5$$$)Β β the size of the chessboard and the number of queries, respectively. Each of the following $$$q$$$ lines contains description of a query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2, 3\}$$$) which denotes type of a query: If $$$t = 1$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinated of the cell where the new rook should be put in. It's guaranteed that there is no rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 2$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinates of the cell to remove a rook from. It's guaranteed that there is a rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 3$$$, four integers $$$x_1, y_1, x_2$$$ and $$$y_2$$$ follows ($$$1 \le x_1 \le x_2 \le n$$$, $$$1 \le y_1 \le y_2 \le n$$$)Β β subrectangle to check if each cell of it is attacked by at least one rook. It's guaranteed that among $$$q$$$ queries there is at least one query of the third type.
Output Specification: Print the answer for each query of the third type in a separate line. Print "Yes" (without quotes) if each cell of the subrectangle is attacked by at least one rook. Otherwise print "No" (without quotes).
Notes: NoteConsider example. After the first two queries the board will look like the following picture (the letter $$$R$$$ denotes cells in which rooks are located, the subrectangle of the query of the third type is highlighted in green): Chessboard after performing the third and the fourth queries: Chessboard after performing the fifth and the sixth queries: Chessboard after performing the seventh and the eighth queries: Chessboard after performing the last two queries:
Code:
import sys
def solve():
inp = sys.stdin.readline
n, q = map(int, inp().split())
r = [0] * n
c = [0] * n
rc = [0] * n
cc = [0] * n
for i in range(q):
ii = iter(map(int, inp().split()))
t = next(ii)
if t <= 2:
x, y = ii
vv = 1 if t == 1 else -1
x -= 1
w = int(rc[x] > 0)
rc[x] += vv
v = int(rc[x] > 0) - w
while x < n:
r[x] += v
x = (x | (x + 1))
x = y - 1
w = int(cc[x] > 0)
cc[x] += vv
v = int(cc[x] > 0) - w
while x < n:
c[x] += v
x = (x | (x + 1))
else:
x1, y1, x2, y2 = ii
v = 0
x = x2 - 1
while x >= 0:
v += r[x]
x = (x & (x + 1)) - 1
x = x1 - 2
while x >= 0:
v -= r[x]
x = (x & (x + 1)) - 1
if v == x2 - x1 + 1:
print('Yes')
continue
v = 0
x = y2 - 1
while x >= 0:
v += c[x]
x = (x & (x + 1)) - 1
x = y1 - 2
while x >= 0:
v -= c[x]
x = (x & (x + 1)) - 1
if v == y2 - y1 + 1:
print('Yes')
else:
# TODO: Your code here
def main():
solve()
if __name__ == '__main__':
main()
|
import sys
def solve():
inp = sys.stdin.readline
n, q = map(int, inp().split())
r = [0] * n
c = [0] * n
rc = [0] * n
cc = [0] * n
for i in range(q):
ii = iter(map(int, inp().split()))
t = next(ii)
if t <= 2:
x, y = ii
vv = 1 if t == 1 else -1
x -= 1
w = int(rc[x] > 0)
rc[x] += vv
v = int(rc[x] > 0) - w
while x < n:
r[x] += v
x = (x | (x + 1))
x = y - 1
w = int(cc[x] > 0)
cc[x] += vv
v = int(cc[x] > 0) - w
while x < n:
c[x] += v
x = (x | (x + 1))
else:
x1, y1, x2, y2 = ii
v = 0
x = x2 - 1
while x >= 0:
v += r[x]
x = (x & (x + 1)) - 1
x = x1 - 2
while x >= 0:
v -= r[x]
x = (x & (x + 1)) - 1
if v == x2 - x1 + 1:
print('Yes')
continue
v = 0
x = y2 - 1
while x >= 0:
v += c[x]
x = (x & (x + 1)) - 1
x = y1 - 2
while x >= 0:
v -= c[x]
x = (x & (x + 1)) - 1
if v == y2 - y1 + 1:
print('Yes')
else:
{{completion}}
def main():
solve()
if __name__ == '__main__':
main()
|
print('No')
|
[{"input": "8 10\n1 2 4\n3 6 2 7 2\n1 3 2\n3 6 2 7 2\n1 4 3\n3 2 6 4 8\n2 4 3\n3 2 6 4 8\n1 4 8\n3 2 6 4 8", "output": ["No\nYes\nYes\nNo\nYes"]}]
|
block_completion_005575
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You have a square chessboard of size $$$n \times n$$$. Rows are numbered from top to bottom with numbers from $$$1$$$ to $$$n$$$, and columnsΒ β from left to right with numbers from $$$1$$$ to $$$n$$$. So, each cell is denoted with pair of integers $$$(x, y)$$$ ($$$1 \le x, y \le n$$$), where $$$x$$$ is a row number and $$$y$$$ is a column number.You have to perform $$$q$$$ queries of three types: Put a new rook in cell $$$(x, y)$$$. Remove a rook from cell $$$(x, y)$$$. It's guaranteed that the rook was put in this cell before. Check if each cell of subrectangle $$$(x_1, y_1) - (x_2, y_2)$$$ of the board is attacked by at least one rook. Subrectangle is a set of cells $$$(x, y)$$$ such that for each cell two conditions are satisfied: $$$x_1 \le x \le x_2$$$ and $$$y_1 \le y \le y_2$$$.Recall that cell $$$(a, b)$$$ is attacked by a rook placed in cell $$$(c, d)$$$ if either $$$a = c$$$ or $$$b = d$$$. In particular, the cell containing a rook is attacked by this rook.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le q \le 2 \cdot 10^5$$$)Β β the size of the chessboard and the number of queries, respectively. Each of the following $$$q$$$ lines contains description of a query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2, 3\}$$$) which denotes type of a query: If $$$t = 1$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinated of the cell where the new rook should be put in. It's guaranteed that there is no rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 2$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinates of the cell to remove a rook from. It's guaranteed that there is a rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 3$$$, four integers $$$x_1, y_1, x_2$$$ and $$$y_2$$$ follows ($$$1 \le x_1 \le x_2 \le n$$$, $$$1 \le y_1 \le y_2 \le n$$$)Β β subrectangle to check if each cell of it is attacked by at least one rook. It's guaranteed that among $$$q$$$ queries there is at least one query of the third type.
Output Specification: Print the answer for each query of the third type in a separate line. Print "Yes" (without quotes) if each cell of the subrectangle is attacked by at least one rook. Otherwise print "No" (without quotes).
Notes: NoteConsider example. After the first two queries the board will look like the following picture (the letter $$$R$$$ denotes cells in which rooks are located, the subrectangle of the query of the third type is highlighted in green): Chessboard after performing the third and the fourth queries: Chessboard after performing the fifth and the sixth queries: Chessboard after performing the seventh and the eighth queries: Chessboard after performing the last two queries:
Code:
import sys
def solve():
inp = sys.stdin.readline
n, q = map(int, inp().split())
r = [0] * n
c = [0] * n
rc = [0] * n
cc = [0] * n
for i in range(q):
ii = iter(map(int, inp().split()))
t = next(ii)
if t <= 2:
x, y = ii
vv = 1 if t == 1 else -1
x -= 1
w = int(rc[x] > 0)
rc[x] += vv
v = int(rc[x] > 0) - w
while x < n:
r[x] += v
x = (x | (x + 1))
x = y - 1
w = int(cc[x] > 0)
cc[x] += vv
v = int(cc[x] > 0) - w
while x < n:
c[x] += v
x = (x | (x + 1))
else:
x1, y1, x2, y2 = ii
v = 0
x = x2 - 1
while x >= 0:
# TODO: Your code here
x = x1 - 2
while x >= 0:
v -= r[x]
x = (x & (x + 1)) - 1
if v == x2 - x1 + 1:
print('Yes')
continue
v = 0
x = y2 - 1
while x >= 0:
v += c[x]
x = (x & (x + 1)) - 1
x = y1 - 2
while x >= 0:
v -= c[x]
x = (x & (x + 1)) - 1
if v == y2 - y1 + 1:
print('Yes')
else:
print('No')
def main():
solve()
if __name__ == '__main__':
main()
|
import sys
def solve():
inp = sys.stdin.readline
n, q = map(int, inp().split())
r = [0] * n
c = [0] * n
rc = [0] * n
cc = [0] * n
for i in range(q):
ii = iter(map(int, inp().split()))
t = next(ii)
if t <= 2:
x, y = ii
vv = 1 if t == 1 else -1
x -= 1
w = int(rc[x] > 0)
rc[x] += vv
v = int(rc[x] > 0) - w
while x < n:
r[x] += v
x = (x | (x + 1))
x = y - 1
w = int(cc[x] > 0)
cc[x] += vv
v = int(cc[x] > 0) - w
while x < n:
c[x] += v
x = (x | (x + 1))
else:
x1, y1, x2, y2 = ii
v = 0
x = x2 - 1
while x >= 0:
{{completion}}
x = x1 - 2
while x >= 0:
v -= r[x]
x = (x & (x + 1)) - 1
if v == x2 - x1 + 1:
print('Yes')
continue
v = 0
x = y2 - 1
while x >= 0:
v += c[x]
x = (x & (x + 1)) - 1
x = y1 - 2
while x >= 0:
v -= c[x]
x = (x & (x + 1)) - 1
if v == y2 - y1 + 1:
print('Yes')
else:
print('No')
def main():
solve()
if __name__ == '__main__':
main()
|
v += r[x]
x = (x & (x + 1)) - 1
|
[{"input": "8 10\n1 2 4\n3 6 2 7 2\n1 3 2\n3 6 2 7 2\n1 4 3\n3 2 6 4 8\n2 4 3\n3 2 6 4 8\n1 4 8\n3 2 6 4 8", "output": ["No\nYes\nYes\nNo\nYes"]}]
|
block_completion_005576
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You have a square chessboard of size $$$n \times n$$$. Rows are numbered from top to bottom with numbers from $$$1$$$ to $$$n$$$, and columnsΒ β from left to right with numbers from $$$1$$$ to $$$n$$$. So, each cell is denoted with pair of integers $$$(x, y)$$$ ($$$1 \le x, y \le n$$$), where $$$x$$$ is a row number and $$$y$$$ is a column number.You have to perform $$$q$$$ queries of three types: Put a new rook in cell $$$(x, y)$$$. Remove a rook from cell $$$(x, y)$$$. It's guaranteed that the rook was put in this cell before. Check if each cell of subrectangle $$$(x_1, y_1) - (x_2, y_2)$$$ of the board is attacked by at least one rook. Subrectangle is a set of cells $$$(x, y)$$$ such that for each cell two conditions are satisfied: $$$x_1 \le x \le x_2$$$ and $$$y_1 \le y \le y_2$$$.Recall that cell $$$(a, b)$$$ is attacked by a rook placed in cell $$$(c, d)$$$ if either $$$a = c$$$ or $$$b = d$$$. In particular, the cell containing a rook is attacked by this rook.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le q \le 2 \cdot 10^5$$$)Β β the size of the chessboard and the number of queries, respectively. Each of the following $$$q$$$ lines contains description of a query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2, 3\}$$$) which denotes type of a query: If $$$t = 1$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinated of the cell where the new rook should be put in. It's guaranteed that there is no rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 2$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinates of the cell to remove a rook from. It's guaranteed that there is a rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 3$$$, four integers $$$x_1, y_1, x_2$$$ and $$$y_2$$$ follows ($$$1 \le x_1 \le x_2 \le n$$$, $$$1 \le y_1 \le y_2 \le n$$$)Β β subrectangle to check if each cell of it is attacked by at least one rook. It's guaranteed that among $$$q$$$ queries there is at least one query of the third type.
Output Specification: Print the answer for each query of the third type in a separate line. Print "Yes" (without quotes) if each cell of the subrectangle is attacked by at least one rook. Otherwise print "No" (without quotes).
Notes: NoteConsider example. After the first two queries the board will look like the following picture (the letter $$$R$$$ denotes cells in which rooks are located, the subrectangle of the query of the third type is highlighted in green): Chessboard after performing the third and the fourth queries: Chessboard after performing the fifth and the sixth queries: Chessboard after performing the seventh and the eighth queries: Chessboard after performing the last two queries:
Code:
import math
from collections import defaultdict, deque, Counter
from sys import stdin
inf = int(1e18)
input = stdin.readline
#fenwick Tree
#D V ARAVIND
def add(ft, i, v):
while i < len(ft):
ft[i] += v
i += i&(-i)
def get(ft, i):
s = 0
while (i > 0):
s = s + ft[i]
i = i - (i &(-i))
return(s)
for _ in range (1):
n,q = map(int, input().split())
ftr = [0 for i in range (n+1)]
ftc = [0 for i in range (n+1)]
visr = [0 for i in range (n+1)]
visc = [0 for i in range (n+1)]
for _ in range (q):
a = [int(i) for i in input().split()]
if a[0] == 1:
if visr[a[1]] == 0:
add(ftr, a[1], 1)
visr[a[1]] += 1
if visc[a[2]] == 0:
add(ftc, a[2], 1)
visc[a[2]] += 1
elif a[0] == 2:
if visr[a[1]] == 1:
add(ftr, a[1], -1)
visr[a[1]] -= 1
if visc[a[2]] == 1:
add(ftc, a[2], -1)
visc[a[2]] -= 1
else:
sr = get(ftr, a[3]) - get(ftr, a[1]-1)
sc = get(ftc, a[4]) - get(ftc, a[2]-1)
if (sr == a[3] - a[1] + 1) or (sc == a[4]-a[2]+1):
print("YES")
else:
# TODO: Your code here
|
import math
from collections import defaultdict, deque, Counter
from sys import stdin
inf = int(1e18)
input = stdin.readline
#fenwick Tree
#D V ARAVIND
def add(ft, i, v):
while i < len(ft):
ft[i] += v
i += i&(-i)
def get(ft, i):
s = 0
while (i > 0):
s = s + ft[i]
i = i - (i &(-i))
return(s)
for _ in range (1):
n,q = map(int, input().split())
ftr = [0 for i in range (n+1)]
ftc = [0 for i in range (n+1)]
visr = [0 for i in range (n+1)]
visc = [0 for i in range (n+1)]
for _ in range (q):
a = [int(i) for i in input().split()]
if a[0] == 1:
if visr[a[1]] == 0:
add(ftr, a[1], 1)
visr[a[1]] += 1
if visc[a[2]] == 0:
add(ftc, a[2], 1)
visc[a[2]] += 1
elif a[0] == 2:
if visr[a[1]] == 1:
add(ftr, a[1], -1)
visr[a[1]] -= 1
if visc[a[2]] == 1:
add(ftc, a[2], -1)
visc[a[2]] -= 1
else:
sr = get(ftr, a[3]) - get(ftr, a[1]-1)
sc = get(ftc, a[4]) - get(ftc, a[2]-1)
if (sr == a[3] - a[1] + 1) or (sc == a[4]-a[2]+1):
print("YES")
else:
{{completion}}
|
print("NO")
|
[{"input": "8 10\n1 2 4\n3 6 2 7 2\n1 3 2\n3 6 2 7 2\n1 4 3\n3 2 6 4 8\n2 4 3\n3 2 6 4 8\n1 4 8\n3 2 6 4 8", "output": ["No\nYes\nYes\nNo\nYes"]}]
|
block_completion_005577
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You have a square chessboard of size $$$n \times n$$$. Rows are numbered from top to bottom with numbers from $$$1$$$ to $$$n$$$, and columnsΒ β from left to right with numbers from $$$1$$$ to $$$n$$$. So, each cell is denoted with pair of integers $$$(x, y)$$$ ($$$1 \le x, y \le n$$$), where $$$x$$$ is a row number and $$$y$$$ is a column number.You have to perform $$$q$$$ queries of three types: Put a new rook in cell $$$(x, y)$$$. Remove a rook from cell $$$(x, y)$$$. It's guaranteed that the rook was put in this cell before. Check if each cell of subrectangle $$$(x_1, y_1) - (x_2, y_2)$$$ of the board is attacked by at least one rook. Subrectangle is a set of cells $$$(x, y)$$$ such that for each cell two conditions are satisfied: $$$x_1 \le x \le x_2$$$ and $$$y_1 \le y \le y_2$$$.Recall that cell $$$(a, b)$$$ is attacked by a rook placed in cell $$$(c, d)$$$ if either $$$a = c$$$ or $$$b = d$$$. In particular, the cell containing a rook is attacked by this rook.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le q \le 2 \cdot 10^5$$$)Β β the size of the chessboard and the number of queries, respectively. Each of the following $$$q$$$ lines contains description of a query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2, 3\}$$$) which denotes type of a query: If $$$t = 1$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinated of the cell where the new rook should be put in. It's guaranteed that there is no rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 2$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinates of the cell to remove a rook from. It's guaranteed that there is a rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 3$$$, four integers $$$x_1, y_1, x_2$$$ and $$$y_2$$$ follows ($$$1 \le x_1 \le x_2 \le n$$$, $$$1 \le y_1 \le y_2 \le n$$$)Β β subrectangle to check if each cell of it is attacked by at least one rook. It's guaranteed that among $$$q$$$ queries there is at least one query of the third type.
Output Specification: Print the answer for each query of the third type in a separate line. Print "Yes" (without quotes) if each cell of the subrectangle is attacked by at least one rook. Otherwise print "No" (without quotes).
Notes: NoteConsider example. After the first two queries the board will look like the following picture (the letter $$$R$$$ denotes cells in which rooks are located, the subrectangle of the query of the third type is highlighted in green): Chessboard after performing the third and the fourth queries: Chessboard after performing the fifth and the sixth queries: Chessboard after performing the seventh and the eighth queries: Chessboard after performing the last two queries:
Code:
import sys
def update(ind, val, tree, n):
while ind <= n:
tree[ind] += val
ind += (ind & -ind)
def read(ind, tree):
ans = 0
while(ind > 0):
ans += tree[ind]
ind -= (ind & -ind)
return ans
def query(l, r, tree):
return read(r, tree) - read(l-1, tree)
n, q = map(int, sys.stdin.readline().split())
row = [0] * (n+1)
col = [0] * (n+1)
rtree = [0] * (n+1)
ctree = [0] * (n+1)
for i in range(q):
inp = list(map(int, sys.stdin.readline().split()))
t = inp[0]
if t == 1:
x = inp[1]
y = inp[2]
row[x] += 1
col[y] += 1
if row[x] == 1:
update(x, 1, rtree, n)
if col[y] == 1:
update(y, 1, ctree, n)
elif t == 2:
x = inp[1]
y = inp[2]
row[x] -= 1
col[y] -= 1
if row[x] == 0:
update(x, -1, rtree, n)
if col[y] == 0:
update(y, -1, ctree, n)
else:
x1 = inp[1]
y1 = inp[2]
x2 = inp[3]
y2 = inp[4]
flag1 = True
flag2 = True;
if query(x1, x2, rtree) < x2 - x1 + 1:
flag1 = False
if query(y1, y2, ctree) < y2 - y1 + 1:
flag2 = False
if flag1 or flag2:
sys.stdout.write("Yes\n")
else:
# TODO: Your code here
|
import sys
def update(ind, val, tree, n):
while ind <= n:
tree[ind] += val
ind += (ind & -ind)
def read(ind, tree):
ans = 0
while(ind > 0):
ans += tree[ind]
ind -= (ind & -ind)
return ans
def query(l, r, tree):
return read(r, tree) - read(l-1, tree)
n, q = map(int, sys.stdin.readline().split())
row = [0] * (n+1)
col = [0] * (n+1)
rtree = [0] * (n+1)
ctree = [0] * (n+1)
for i in range(q):
inp = list(map(int, sys.stdin.readline().split()))
t = inp[0]
if t == 1:
x = inp[1]
y = inp[2]
row[x] += 1
col[y] += 1
if row[x] == 1:
update(x, 1, rtree, n)
if col[y] == 1:
update(y, 1, ctree, n)
elif t == 2:
x = inp[1]
y = inp[2]
row[x] -= 1
col[y] -= 1
if row[x] == 0:
update(x, -1, rtree, n)
if col[y] == 0:
update(y, -1, ctree, n)
else:
x1 = inp[1]
y1 = inp[2]
x2 = inp[3]
y2 = inp[4]
flag1 = True
flag2 = True;
if query(x1, x2, rtree) < x2 - x1 + 1:
flag1 = False
if query(y1, y2, ctree) < y2 - y1 + 1:
flag2 = False
if flag1 or flag2:
sys.stdout.write("Yes\n")
else:
{{completion}}
|
sys.stdout.write("No\n")
|
[{"input": "8 10\n1 2 4\n3 6 2 7 2\n1 3 2\n3 6 2 7 2\n1 4 3\n3 2 6 4 8\n2 4 3\n3 2 6 4 8\n1 4 8\n3 2 6 4 8", "output": ["No\nYes\nYes\nNo\nYes"]}]
|
block_completion_005578
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You have a square chessboard of size $$$n \times n$$$. Rows are numbered from top to bottom with numbers from $$$1$$$ to $$$n$$$, and columnsΒ β from left to right with numbers from $$$1$$$ to $$$n$$$. So, each cell is denoted with pair of integers $$$(x, y)$$$ ($$$1 \le x, y \le n$$$), where $$$x$$$ is a row number and $$$y$$$ is a column number.You have to perform $$$q$$$ queries of three types: Put a new rook in cell $$$(x, y)$$$. Remove a rook from cell $$$(x, y)$$$. It's guaranteed that the rook was put in this cell before. Check if each cell of subrectangle $$$(x_1, y_1) - (x_2, y_2)$$$ of the board is attacked by at least one rook. Subrectangle is a set of cells $$$(x, y)$$$ such that for each cell two conditions are satisfied: $$$x_1 \le x \le x_2$$$ and $$$y_1 \le y \le y_2$$$.Recall that cell $$$(a, b)$$$ is attacked by a rook placed in cell $$$(c, d)$$$ if either $$$a = c$$$ or $$$b = d$$$. In particular, the cell containing a rook is attacked by this rook.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le q \le 2 \cdot 10^5$$$)Β β the size of the chessboard and the number of queries, respectively. Each of the following $$$q$$$ lines contains description of a query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2, 3\}$$$) which denotes type of a query: If $$$t = 1$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinated of the cell where the new rook should be put in. It's guaranteed that there is no rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 2$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinates of the cell to remove a rook from. It's guaranteed that there is a rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 3$$$, four integers $$$x_1, y_1, x_2$$$ and $$$y_2$$$ follows ($$$1 \le x_1 \le x_2 \le n$$$, $$$1 \le y_1 \le y_2 \le n$$$)Β β subrectangle to check if each cell of it is attacked by at least one rook. It's guaranteed that among $$$q$$$ queries there is at least one query of the third type.
Output Specification: Print the answer for each query of the third type in a separate line. Print "Yes" (without quotes) if each cell of the subrectangle is attacked by at least one rook. Otherwise print "No" (without quotes).
Notes: NoteConsider example. After the first two queries the board will look like the following picture (the letter $$$R$$$ denotes cells in which rooks are located, the subrectangle of the query of the third type is highlighted in green): Chessboard after performing the third and the fourth queries: Chessboard after performing the fifth and the sixth queries: Chessboard after performing the seventh and the eighth queries: Chessboard after performing the last two queries:
Code:
import sys
def update(ind, val, tree, n):
while ind <= n:
tree[ind] += val
ind += (ind & -ind)
def read(ind, tree):
ans = 0
while(ind > 0):
ans += tree[ind]
ind -= (ind & -ind)
return ans
def query(l, r, tree):
return read(r, tree) - read(l-1, tree)
n, q = map(int, sys.stdin.readline().split())
row = [0] * (n+1)
col = [0] * (n+1)
rtree = [0] * (n+1)
ctree = [0] * (n+1)
for i in range(q):
inp = list(map(int, sys.stdin.readline().split()))
t = inp[0]
if t == 1:
x = inp[1]
y = inp[2]
row[x] += 1
col[y] += 1
if row[x] == 1:
update(x, 1, rtree, n)
if col[y] == 1:
update(y, 1, ctree, n)
elif t == 2:
x = inp[1]
y = inp[2]
row[x] -= 1
col[y] -= 1
if row[x] == 0:
# TODO: Your code here
if col[y] == 0:
update(y, -1, ctree, n)
else:
x1 = inp[1]
y1 = inp[2]
x2 = inp[3]
y2 = inp[4]
flag1 = True
flag2 = True;
if query(x1, x2, rtree) < x2 - x1 + 1:
flag1 = False
if query(y1, y2, ctree) < y2 - y1 + 1:
flag2 = False
if flag1 or flag2:
sys.stdout.write("Yes\n")
else:
sys.stdout.write("No\n")
|
import sys
def update(ind, val, tree, n):
while ind <= n:
tree[ind] += val
ind += (ind & -ind)
def read(ind, tree):
ans = 0
while(ind > 0):
ans += tree[ind]
ind -= (ind & -ind)
return ans
def query(l, r, tree):
return read(r, tree) - read(l-1, tree)
n, q = map(int, sys.stdin.readline().split())
row = [0] * (n+1)
col = [0] * (n+1)
rtree = [0] * (n+1)
ctree = [0] * (n+1)
for i in range(q):
inp = list(map(int, sys.stdin.readline().split()))
t = inp[0]
if t == 1:
x = inp[1]
y = inp[2]
row[x] += 1
col[y] += 1
if row[x] == 1:
update(x, 1, rtree, n)
if col[y] == 1:
update(y, 1, ctree, n)
elif t == 2:
x = inp[1]
y = inp[2]
row[x] -= 1
col[y] -= 1
if row[x] == 0:
{{completion}}
if col[y] == 0:
update(y, -1, ctree, n)
else:
x1 = inp[1]
y1 = inp[2]
x2 = inp[3]
y2 = inp[4]
flag1 = True
flag2 = True;
if query(x1, x2, rtree) < x2 - x1 + 1:
flag1 = False
if query(y1, y2, ctree) < y2 - y1 + 1:
flag2 = False
if flag1 or flag2:
sys.stdout.write("Yes\n")
else:
sys.stdout.write("No\n")
|
update(x, -1, rtree, n)
|
[{"input": "8 10\n1 2 4\n3 6 2 7 2\n1 3 2\n3 6 2 7 2\n1 4 3\n3 2 6 4 8\n2 4 3\n3 2 6 4 8\n1 4 8\n3 2 6 4 8", "output": ["No\nYes\nYes\nNo\nYes"]}]
|
block_completion_005579
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You have a square chessboard of size $$$n \times n$$$. Rows are numbered from top to bottom with numbers from $$$1$$$ to $$$n$$$, and columnsΒ β from left to right with numbers from $$$1$$$ to $$$n$$$. So, each cell is denoted with pair of integers $$$(x, y)$$$ ($$$1 \le x, y \le n$$$), where $$$x$$$ is a row number and $$$y$$$ is a column number.You have to perform $$$q$$$ queries of three types: Put a new rook in cell $$$(x, y)$$$. Remove a rook from cell $$$(x, y)$$$. It's guaranteed that the rook was put in this cell before. Check if each cell of subrectangle $$$(x_1, y_1) - (x_2, y_2)$$$ of the board is attacked by at least one rook. Subrectangle is a set of cells $$$(x, y)$$$ such that for each cell two conditions are satisfied: $$$x_1 \le x \le x_2$$$ and $$$y_1 \le y \le y_2$$$.Recall that cell $$$(a, b)$$$ is attacked by a rook placed in cell $$$(c, d)$$$ if either $$$a = c$$$ or $$$b = d$$$. In particular, the cell containing a rook is attacked by this rook.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le q \le 2 \cdot 10^5$$$)Β β the size of the chessboard and the number of queries, respectively. Each of the following $$$q$$$ lines contains description of a query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2, 3\}$$$) which denotes type of a query: If $$$t = 1$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinated of the cell where the new rook should be put in. It's guaranteed that there is no rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 2$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinates of the cell to remove a rook from. It's guaranteed that there is a rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 3$$$, four integers $$$x_1, y_1, x_2$$$ and $$$y_2$$$ follows ($$$1 \le x_1 \le x_2 \le n$$$, $$$1 \le y_1 \le y_2 \le n$$$)Β β subrectangle to check if each cell of it is attacked by at least one rook. It's guaranteed that among $$$q$$$ queries there is at least one query of the third type.
Output Specification: Print the answer for each query of the third type in a separate line. Print "Yes" (without quotes) if each cell of the subrectangle is attacked by at least one rook. Otherwise print "No" (without quotes).
Notes: NoteConsider example. After the first two queries the board will look like the following picture (the letter $$$R$$$ denotes cells in which rooks are located, the subrectangle of the query of the third type is highlighted in green): Chessboard after performing the third and the fourth queries: Chessboard after performing the fifth and the sixth queries: Chessboard after performing the seventh and the eighth queries: Chessboard after performing the last two queries:
Code:
import sys
input = lambda: sys.stdin.readline().rstrip()
class SegTree:
def __init__(self, n):
self.size = n
self.tree = [0]*(n*2)
def update(self,p,v):
self.tree[p+self.size] = v
p+=self.size
i = p
while i>1:
self.tree[i>>1] = self.tree[i] + self.tree[i^1]
i>>=1
def query(self,l,r):
ans = 0
l += self.size
r += self.size
while l<r:
if 1&l:
# TODO: Your code here
if r&1:
r-=1
ans += self.tree[r]
l>>=1
r>>=1
return ans
N,Q = map(int, input().split())
sr,sc = SegTree(N),SegTree(N)
R,C = [0]*N,[0]*N
for _ in range(Q):
t = list(map(int, input().split()))
if t[0]==1:
if R[t[1]-1]==0:
sr.update(t[1]-1, 1)
R[t[1]-1] += 1
if C[t[2]-1]==0:
sc.update(t[2]-1, 1)
C[t[2]-1] += 1
elif t[0]==2:
if R[t[1]-1]==1:
sr.update(t[1]-1, 0)
R[t[1]-1] -= 1
if C[t[2]-1]==1:
sc.update(t[2]-1, 0)
C[t[2]-1] -= 1
else:
x1,y1,x2,y2 = t[1]-1,t[2]-1,t[3]-1,t[4]-1
cnt = sr.query(x1,x2+1)
#print(x1,x2,cnt)
if cnt==x2-x1+1:
print('Yes')
continue
cnt = sc.query(y1,y2+1)
if cnt==y2-y1+1:
print('Yes')
else:
print('No')
|
import sys
input = lambda: sys.stdin.readline().rstrip()
class SegTree:
def __init__(self, n):
self.size = n
self.tree = [0]*(n*2)
def update(self,p,v):
self.tree[p+self.size] = v
p+=self.size
i = p
while i>1:
self.tree[i>>1] = self.tree[i] + self.tree[i^1]
i>>=1
def query(self,l,r):
ans = 0
l += self.size
r += self.size
while l<r:
if 1&l:
{{completion}}
if r&1:
r-=1
ans += self.tree[r]
l>>=1
r>>=1
return ans
N,Q = map(int, input().split())
sr,sc = SegTree(N),SegTree(N)
R,C = [0]*N,[0]*N
for _ in range(Q):
t = list(map(int, input().split()))
if t[0]==1:
if R[t[1]-1]==0:
sr.update(t[1]-1, 1)
R[t[1]-1] += 1
if C[t[2]-1]==0:
sc.update(t[2]-1, 1)
C[t[2]-1] += 1
elif t[0]==2:
if R[t[1]-1]==1:
sr.update(t[1]-1, 0)
R[t[1]-1] -= 1
if C[t[2]-1]==1:
sc.update(t[2]-1, 0)
C[t[2]-1] -= 1
else:
x1,y1,x2,y2 = t[1]-1,t[2]-1,t[3]-1,t[4]-1
cnt = sr.query(x1,x2+1)
#print(x1,x2,cnt)
if cnt==x2-x1+1:
print('Yes')
continue
cnt = sc.query(y1,y2+1)
if cnt==y2-y1+1:
print('Yes')
else:
print('No')
|
ans += self.tree[l]
l+=1
|
[{"input": "8 10\n1 2 4\n3 6 2 7 2\n1 3 2\n3 6 2 7 2\n1 4 3\n3 2 6 4 8\n2 4 3\n3 2 6 4 8\n1 4 8\n3 2 6 4 8", "output": ["No\nYes\nYes\nNo\nYes"]}]
|
block_completion_005580
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You have a square chessboard of size $$$n \times n$$$. Rows are numbered from top to bottom with numbers from $$$1$$$ to $$$n$$$, and columnsΒ β from left to right with numbers from $$$1$$$ to $$$n$$$. So, each cell is denoted with pair of integers $$$(x, y)$$$ ($$$1 \le x, y \le n$$$), where $$$x$$$ is a row number and $$$y$$$ is a column number.You have to perform $$$q$$$ queries of three types: Put a new rook in cell $$$(x, y)$$$. Remove a rook from cell $$$(x, y)$$$. It's guaranteed that the rook was put in this cell before. Check if each cell of subrectangle $$$(x_1, y_1) - (x_2, y_2)$$$ of the board is attacked by at least one rook. Subrectangle is a set of cells $$$(x, y)$$$ such that for each cell two conditions are satisfied: $$$x_1 \le x \le x_2$$$ and $$$y_1 \le y \le y_2$$$.Recall that cell $$$(a, b)$$$ is attacked by a rook placed in cell $$$(c, d)$$$ if either $$$a = c$$$ or $$$b = d$$$. In particular, the cell containing a rook is attacked by this rook.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le q \le 2 \cdot 10^5$$$)Β β the size of the chessboard and the number of queries, respectively. Each of the following $$$q$$$ lines contains description of a query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2, 3\}$$$) which denotes type of a query: If $$$t = 1$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinated of the cell where the new rook should be put in. It's guaranteed that there is no rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 2$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinates of the cell to remove a rook from. It's guaranteed that there is a rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 3$$$, four integers $$$x_1, y_1, x_2$$$ and $$$y_2$$$ follows ($$$1 \le x_1 \le x_2 \le n$$$, $$$1 \le y_1 \le y_2 \le n$$$)Β β subrectangle to check if each cell of it is attacked by at least one rook. It's guaranteed that among $$$q$$$ queries there is at least one query of the third type.
Output Specification: Print the answer for each query of the third type in a separate line. Print "Yes" (without quotes) if each cell of the subrectangle is attacked by at least one rook. Otherwise print "No" (without quotes).
Notes: NoteConsider example. After the first two queries the board will look like the following picture (the letter $$$R$$$ denotes cells in which rooks are located, the subrectangle of the query of the third type is highlighted in green): Chessboard after performing the third and the fourth queries: Chessboard after performing the fifth and the sixth queries: Chessboard after performing the seventh and the eighth queries: Chessboard after performing the last two queries:
Code:
import sys
input = lambda: sys.stdin.readline().rstrip()
class SegTree:
def __init__(self, n):
self.size = n
self.tree = [0]*(n*2)
def update(self,p,v):
self.tree[p+self.size] = v
p+=self.size
i = p
while i>1:
self.tree[i>>1] = self.tree[i] + self.tree[i^1]
i>>=1
def query(self,l,r):
ans = 0
l += self.size
r += self.size
while l<r:
if 1&l:
ans += self.tree[l]
l+=1
if r&1:
# TODO: Your code here
l>>=1
r>>=1
return ans
N,Q = map(int, input().split())
sr,sc = SegTree(N),SegTree(N)
R,C = [0]*N,[0]*N
for _ in range(Q):
t = list(map(int, input().split()))
if t[0]==1:
if R[t[1]-1]==0:
sr.update(t[1]-1, 1)
R[t[1]-1] += 1
if C[t[2]-1]==0:
sc.update(t[2]-1, 1)
C[t[2]-1] += 1
elif t[0]==2:
if R[t[1]-1]==1:
sr.update(t[1]-1, 0)
R[t[1]-1] -= 1
if C[t[2]-1]==1:
sc.update(t[2]-1, 0)
C[t[2]-1] -= 1
else:
x1,y1,x2,y2 = t[1]-1,t[2]-1,t[3]-1,t[4]-1
cnt = sr.query(x1,x2+1)
#print(x1,x2,cnt)
if cnt==x2-x1+1:
print('Yes')
continue
cnt = sc.query(y1,y2+1)
if cnt==y2-y1+1:
print('Yes')
else:
print('No')
|
import sys
input = lambda: sys.stdin.readline().rstrip()
class SegTree:
def __init__(self, n):
self.size = n
self.tree = [0]*(n*2)
def update(self,p,v):
self.tree[p+self.size] = v
p+=self.size
i = p
while i>1:
self.tree[i>>1] = self.tree[i] + self.tree[i^1]
i>>=1
def query(self,l,r):
ans = 0
l += self.size
r += self.size
while l<r:
if 1&l:
ans += self.tree[l]
l+=1
if r&1:
{{completion}}
l>>=1
r>>=1
return ans
N,Q = map(int, input().split())
sr,sc = SegTree(N),SegTree(N)
R,C = [0]*N,[0]*N
for _ in range(Q):
t = list(map(int, input().split()))
if t[0]==1:
if R[t[1]-1]==0:
sr.update(t[1]-1, 1)
R[t[1]-1] += 1
if C[t[2]-1]==0:
sc.update(t[2]-1, 1)
C[t[2]-1] += 1
elif t[0]==2:
if R[t[1]-1]==1:
sr.update(t[1]-1, 0)
R[t[1]-1] -= 1
if C[t[2]-1]==1:
sc.update(t[2]-1, 0)
C[t[2]-1] -= 1
else:
x1,y1,x2,y2 = t[1]-1,t[2]-1,t[3]-1,t[4]-1
cnt = sr.query(x1,x2+1)
#print(x1,x2,cnt)
if cnt==x2-x1+1:
print('Yes')
continue
cnt = sc.query(y1,y2+1)
if cnt==y2-y1+1:
print('Yes')
else:
print('No')
|
r-=1
ans += self.tree[r]
|
[{"input": "8 10\n1 2 4\n3 6 2 7 2\n1 3 2\n3 6 2 7 2\n1 4 3\n3 2 6 4 8\n2 4 3\n3 2 6 4 8\n1 4 8\n3 2 6 4 8", "output": ["No\nYes\nYes\nNo\nYes"]}]
|
block_completion_005581
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You have a square chessboard of size $$$n \times n$$$. Rows are numbered from top to bottom with numbers from $$$1$$$ to $$$n$$$, and columnsΒ β from left to right with numbers from $$$1$$$ to $$$n$$$. So, each cell is denoted with pair of integers $$$(x, y)$$$ ($$$1 \le x, y \le n$$$), where $$$x$$$ is a row number and $$$y$$$ is a column number.You have to perform $$$q$$$ queries of three types: Put a new rook in cell $$$(x, y)$$$. Remove a rook from cell $$$(x, y)$$$. It's guaranteed that the rook was put in this cell before. Check if each cell of subrectangle $$$(x_1, y_1) - (x_2, y_2)$$$ of the board is attacked by at least one rook. Subrectangle is a set of cells $$$(x, y)$$$ such that for each cell two conditions are satisfied: $$$x_1 \le x \le x_2$$$ and $$$y_1 \le y \le y_2$$$.Recall that cell $$$(a, b)$$$ is attacked by a rook placed in cell $$$(c, d)$$$ if either $$$a = c$$$ or $$$b = d$$$. In particular, the cell containing a rook is attacked by this rook.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le q \le 2 \cdot 10^5$$$)Β β the size of the chessboard and the number of queries, respectively. Each of the following $$$q$$$ lines contains description of a query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2, 3\}$$$) which denotes type of a query: If $$$t = 1$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinated of the cell where the new rook should be put in. It's guaranteed that there is no rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 2$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinates of the cell to remove a rook from. It's guaranteed that there is a rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 3$$$, four integers $$$x_1, y_1, x_2$$$ and $$$y_2$$$ follows ($$$1 \le x_1 \le x_2 \le n$$$, $$$1 \le y_1 \le y_2 \le n$$$)Β β subrectangle to check if each cell of it is attacked by at least one rook. It's guaranteed that among $$$q$$$ queries there is at least one query of the third type.
Output Specification: Print the answer for each query of the third type in a separate line. Print "Yes" (without quotes) if each cell of the subrectangle is attacked by at least one rook. Otherwise print "No" (without quotes).
Notes: NoteConsider example. After the first two queries the board will look like the following picture (the letter $$$R$$$ denotes cells in which rooks are located, the subrectangle of the query of the third type is highlighted in green): Chessboard after performing the third and the fourth queries: Chessboard after performing the fifth and the sixth queries: Chessboard after performing the seventh and the eighth queries: Chessboard after performing the last two queries:
Code:
import bisect
import collections
import heapq
import io
import math
import os
import sys
LO = 'abcdefghijklmnopqrstuvwxyz'
Mod = 1000000007
def gcd(x, y):
while y:
x, y = y, x % y
return x
# _input = lambda: io.BytesIO(os.read(0, os.fstat(0).st_size)).readline().decode()
_input = lambda: sys.stdin.buffer.readline().strip().decode()
# for _ in range(int(_input())):
for _ in range(1):
n, q = map(int, _input().split())
a = [0] * (n + 1)
b = [0] * (n + 1)
x = [0] * (n + 1)
y = [0] * (n + 1)
for _ in range(q):
o = list(map(int, _input().split()))
if o[0] == 1:
_, u, v = o
a[u] += 1
if a[u] == 1:
while u <= n:
x[u] += 1
u += u & -u
b[v] += 1
if b[v] == 1:
while v <= n:
y[v] += 1
v += v & -v
elif o[0] == 2:
_, u, v = o
a[u] -= 1
if a[u] == 0:
while u <= n:
# TODO: Your code here
b[v] -= 1
if b[v] == 0:
while v <= n:
y[v] -= 1
v += v & -v
else:
_, u1, v1, u2, v2 = o
c = 0
u = u2
while u > 0:
c += x[u]
u -= u & -u
u = u1 - 1
while u > 0:
c -= x[u]
u -= u & -u
d = 0
v = v2
while v > 0:
d += y[v]
v -= v & -v
v = v1 - 1
while v > 0:
d -= y[v]
v -= v & -v
print('Yes' if c >= u2 - u1 + 1 or d >= v2 - v1 + 1 else 'No')
|
import bisect
import collections
import heapq
import io
import math
import os
import sys
LO = 'abcdefghijklmnopqrstuvwxyz'
Mod = 1000000007
def gcd(x, y):
while y:
x, y = y, x % y
return x
# _input = lambda: io.BytesIO(os.read(0, os.fstat(0).st_size)).readline().decode()
_input = lambda: sys.stdin.buffer.readline().strip().decode()
# for _ in range(int(_input())):
for _ in range(1):
n, q = map(int, _input().split())
a = [0] * (n + 1)
b = [0] * (n + 1)
x = [0] * (n + 1)
y = [0] * (n + 1)
for _ in range(q):
o = list(map(int, _input().split()))
if o[0] == 1:
_, u, v = o
a[u] += 1
if a[u] == 1:
while u <= n:
x[u] += 1
u += u & -u
b[v] += 1
if b[v] == 1:
while v <= n:
y[v] += 1
v += v & -v
elif o[0] == 2:
_, u, v = o
a[u] -= 1
if a[u] == 0:
while u <= n:
{{completion}}
b[v] -= 1
if b[v] == 0:
while v <= n:
y[v] -= 1
v += v & -v
else:
_, u1, v1, u2, v2 = o
c = 0
u = u2
while u > 0:
c += x[u]
u -= u & -u
u = u1 - 1
while u > 0:
c -= x[u]
u -= u & -u
d = 0
v = v2
while v > 0:
d += y[v]
v -= v & -v
v = v1 - 1
while v > 0:
d -= y[v]
v -= v & -v
print('Yes' if c >= u2 - u1 + 1 or d >= v2 - v1 + 1 else 'No')
|
x[u] -= 1
u += u & -u
|
[{"input": "8 10\n1 2 4\n3 6 2 7 2\n1 3 2\n3 6 2 7 2\n1 4 3\n3 2 6 4 8\n2 4 3\n3 2 6 4 8\n1 4 8\n3 2 6 4 8", "output": ["No\nYes\nYes\nNo\nYes"]}]
|
block_completion_005582
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: You have a square chessboard of size $$$n \times n$$$. Rows are numbered from top to bottom with numbers from $$$1$$$ to $$$n$$$, and columnsΒ β from left to right with numbers from $$$1$$$ to $$$n$$$. So, each cell is denoted with pair of integers $$$(x, y)$$$ ($$$1 \le x, y \le n$$$), where $$$x$$$ is a row number and $$$y$$$ is a column number.You have to perform $$$q$$$ queries of three types: Put a new rook in cell $$$(x, y)$$$. Remove a rook from cell $$$(x, y)$$$. It's guaranteed that the rook was put in this cell before. Check if each cell of subrectangle $$$(x_1, y_1) - (x_2, y_2)$$$ of the board is attacked by at least one rook. Subrectangle is a set of cells $$$(x, y)$$$ such that for each cell two conditions are satisfied: $$$x_1 \le x \le x_2$$$ and $$$y_1 \le y \le y_2$$$.Recall that cell $$$(a, b)$$$ is attacked by a rook placed in cell $$$(c, d)$$$ if either $$$a = c$$$ or $$$b = d$$$. In particular, the cell containing a rook is attacked by this rook.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le q \le 2 \cdot 10^5$$$)Β β the size of the chessboard and the number of queries, respectively. Each of the following $$$q$$$ lines contains description of a query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2, 3\}$$$) which denotes type of a query: If $$$t = 1$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinated of the cell where the new rook should be put in. It's guaranteed that there is no rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 2$$$, two integers $$$x$$$ and $$$y$$$ follows ($$$1 \le x, y \le n$$$)Β β coordinates of the cell to remove a rook from. It's guaranteed that there is a rook in the cell $$$(x, y)$$$ at the moment of the given query. If $$$t = 3$$$, four integers $$$x_1, y_1, x_2$$$ and $$$y_2$$$ follows ($$$1 \le x_1 \le x_2 \le n$$$, $$$1 \le y_1 \le y_2 \le n$$$)Β β subrectangle to check if each cell of it is attacked by at least one rook. It's guaranteed that among $$$q$$$ queries there is at least one query of the third type.
Output Specification: Print the answer for each query of the third type in a separate line. Print "Yes" (without quotes) if each cell of the subrectangle is attacked by at least one rook. Otherwise print "No" (without quotes).
Notes: NoteConsider example. After the first two queries the board will look like the following picture (the letter $$$R$$$ denotes cells in which rooks are located, the subrectangle of the query of the third type is highlighted in green): Chessboard after performing the third and the fourth queries: Chessboard after performing the fifth and the sixth queries: Chessboard after performing the seventh and the eighth queries: Chessboard after performing the last two queries:
Code:
import bisect
import collections
import heapq
import io
import math
import os
import sys
LO = 'abcdefghijklmnopqrstuvwxyz'
Mod = 1000000007
def gcd(x, y):
while y:
x, y = y, x % y
return x
# _input = lambda: io.BytesIO(os.read(0, os.fstat(0).st_size)).readline().decode()
_input = lambda: sys.stdin.buffer.readline().strip().decode()
# for _ in range(int(_input())):
for _ in range(1):
n, q = map(int, _input().split())
a = [0] * (n + 1)
b = [0] * (n + 1)
x = [0] * (n + 1)
y = [0] * (n + 1)
for _ in range(q):
o = list(map(int, _input().split()))
if o[0] == 1:
_, u, v = o
a[u] += 1
if a[u] == 1:
while u <= n:
x[u] += 1
u += u & -u
b[v] += 1
if b[v] == 1:
while v <= n:
y[v] += 1
v += v & -v
elif o[0] == 2:
_, u, v = o
a[u] -= 1
if a[u] == 0:
while u <= n:
x[u] -= 1
u += u & -u
b[v] -= 1
if b[v] == 0:
while v <= n:
# TODO: Your code here
else:
_, u1, v1, u2, v2 = o
c = 0
u = u2
while u > 0:
c += x[u]
u -= u & -u
u = u1 - 1
while u > 0:
c -= x[u]
u -= u & -u
d = 0
v = v2
while v > 0:
d += y[v]
v -= v & -v
v = v1 - 1
while v > 0:
d -= y[v]
v -= v & -v
print('Yes' if c >= u2 - u1 + 1 or d >= v2 - v1 + 1 else 'No')
|
import bisect
import collections
import heapq
import io
import math
import os
import sys
LO = 'abcdefghijklmnopqrstuvwxyz'
Mod = 1000000007
def gcd(x, y):
while y:
x, y = y, x % y
return x
# _input = lambda: io.BytesIO(os.read(0, os.fstat(0).st_size)).readline().decode()
_input = lambda: sys.stdin.buffer.readline().strip().decode()
# for _ in range(int(_input())):
for _ in range(1):
n, q = map(int, _input().split())
a = [0] * (n + 1)
b = [0] * (n + 1)
x = [0] * (n + 1)
y = [0] * (n + 1)
for _ in range(q):
o = list(map(int, _input().split()))
if o[0] == 1:
_, u, v = o
a[u] += 1
if a[u] == 1:
while u <= n:
x[u] += 1
u += u & -u
b[v] += 1
if b[v] == 1:
while v <= n:
y[v] += 1
v += v & -v
elif o[0] == 2:
_, u, v = o
a[u] -= 1
if a[u] == 0:
while u <= n:
x[u] -= 1
u += u & -u
b[v] -= 1
if b[v] == 0:
while v <= n:
{{completion}}
else:
_, u1, v1, u2, v2 = o
c = 0
u = u2
while u > 0:
c += x[u]
u -= u & -u
u = u1 - 1
while u > 0:
c -= x[u]
u -= u & -u
d = 0
v = v2
while v > 0:
d += y[v]
v -= v & -v
v = v1 - 1
while v > 0:
d -= y[v]
v -= v & -v
print('Yes' if c >= u2 - u1 + 1 or d >= v2 - v1 + 1 else 'No')
|
y[v] -= 1
v += v & -v
|
[{"input": "8 10\n1 2 4\n3 6 2 7 2\n1 3 2\n3 6 2 7 2\n1 4 3\n3 2 6 4 8\n2 4 3\n3 2 6 4 8\n1 4 8\n3 2 6 4 8", "output": ["No\nYes\nYes\nNo\nYes"]}]
|
block_completion_005583
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Once upon a time Mike and Mike decided to come up with an outstanding problem for some stage of ROI (rare olympiad in informatics). One of them came up with a problem prototype but another stole the idea and proposed that problem for another stage of the same olympiad. Since then the first Mike has been waiting for an opportunity to propose the original idea for some other contest... Mike waited until this moment!You are given an array $$$a$$$ of $$$n$$$ integers. You are also given $$$q$$$ queries of two types: Replace $$$i$$$-th element in the array with integer $$$x$$$. Replace each element in the array with integer $$$x$$$. After performing each query you have to calculate the sum of all elements in the array.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$)Β β the number of elements in the array and the number of queries, respectively. The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array $$$a$$$. Each of the following $$$q$$$ lines contains a description of the corresponding query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2\}$$$) which denotes a type of the query: If $$$t = 1$$$, then two integers $$$i$$$ and $$$x$$$ are following ($$$1 \le i \le n$$$, $$$1 \le x \le 10^9$$$)Β β position of replaced element and it's new value. If $$$t = 2$$$, then integer $$$x$$$ is following ($$$1 \le x \le 10^9$$$)Β β new value of each element in the array.
Output Specification: Print $$$q$$$ integers, each on a separate line. In the $$$i$$$-th line print the sum of all elements in the array after performing the first $$$i$$$ queries.
Notes: NoteConsider array from the example and the result of performing each query: Initial array is $$$[1, 2, 3, 4, 5]$$$. After performing the first query, array equals to $$$[5, 2, 3, 4, 5]$$$. The sum of all elements is $$$19$$$. After performing the second query, array equals to $$$[10, 10, 10, 10, 10]$$$. The sum of all elements is $$$50$$$. After performing the third query, array equals to $$$[10, 10, 10, 10, 11$$$]. The sum of all elements is $$$51$$$. After performing the fourth query, array equals to $$$[10, 10, 10, 1, 11]$$$. The sum of all elements is $$$42$$$. After performing the fifth query, array equals to $$$[1, 1, 1, 1, 1]$$$. The sum of all elements is $$$5$$$.
Code:
f = open(0)
def R(): return map(int, next(f).split())
n, q = R()
d = {}
i = v = r = 0
for x in R():
r += x
i += 1
d[i] = x
while q:
q -= 1
t, *x = R()
if t & 1:
i, x = x
r += x - d.get(i, v)
d[i] = x
else:
# TODO: Your code here
print(r)
|
f = open(0)
def R(): return map(int, next(f).split())
n, q = R()
d = {}
i = v = r = 0
for x in R():
r += x
i += 1
d[i] = x
while q:
q -= 1
t, *x = R()
if t & 1:
i, x = x
r += x - d.get(i, v)
d[i] = x
else:
{{completion}}
print(r)
|
d = {}
v, = x
r = v * n
|
[{"input": "5 5\n1 2 3 4 5\n1 1 5\n2 10\n1 5 11\n1 4 1\n2 1", "output": ["19\n50\n51\n42\n5"]}]
|
block_completion_005606
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Once upon a time Mike and Mike decided to come up with an outstanding problem for some stage of ROI (rare olympiad in informatics). One of them came up with a problem prototype but another stole the idea and proposed that problem for another stage of the same olympiad. Since then the first Mike has been waiting for an opportunity to propose the original idea for some other contest... Mike waited until this moment!You are given an array $$$a$$$ of $$$n$$$ integers. You are also given $$$q$$$ queries of two types: Replace $$$i$$$-th element in the array with integer $$$x$$$. Replace each element in the array with integer $$$x$$$. After performing each query you have to calculate the sum of all elements in the array.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$)Β β the number of elements in the array and the number of queries, respectively. The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array $$$a$$$. Each of the following $$$q$$$ lines contains a description of the corresponding query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2\}$$$) which denotes a type of the query: If $$$t = 1$$$, then two integers $$$i$$$ and $$$x$$$ are following ($$$1 \le i \le n$$$, $$$1 \le x \le 10^9$$$)Β β position of replaced element and it's new value. If $$$t = 2$$$, then integer $$$x$$$ is following ($$$1 \le x \le 10^9$$$)Β β new value of each element in the array.
Output Specification: Print $$$q$$$ integers, each on a separate line. In the $$$i$$$-th line print the sum of all elements in the array after performing the first $$$i$$$ queries.
Notes: NoteConsider array from the example and the result of performing each query: Initial array is $$$[1, 2, 3, 4, 5]$$$. After performing the first query, array equals to $$$[5, 2, 3, 4, 5]$$$. The sum of all elements is $$$19$$$. After performing the second query, array equals to $$$[10, 10, 10, 10, 10]$$$. The sum of all elements is $$$50$$$. After performing the third query, array equals to $$$[10, 10, 10, 10, 11$$$]. The sum of all elements is $$$51$$$. After performing the fourth query, array equals to $$$[10, 10, 10, 1, 11]$$$. The sum of all elements is $$$42$$$. After performing the fifth query, array equals to $$$[1, 1, 1, 1, 1]$$$. The sum of all elements is $$$5$$$.
Code:
inp = [list(map(int, l.split())) for l in open(0).read().splitlines()]
n, q = inp[0]
a = inp[1]
last = 0
step = [-1] * n
laststep = -2
tot = sum(a)
for i, b in enumerate(inp[2:]):
if b[0] == 1:
if step[b[1]-1] > laststep:
tot += b[2] - a[b[1]-1]
a[b[1]-1] = b[2]
else:
# TODO: Your code here
step[b[1]-1] = i
print(tot)
else:
tot = b[1] * n
last = b[1]
laststep = i
print(tot)
|
inp = [list(map(int, l.split())) for l in open(0).read().splitlines()]
n, q = inp[0]
a = inp[1]
last = 0
step = [-1] * n
laststep = -2
tot = sum(a)
for i, b in enumerate(inp[2:]):
if b[0] == 1:
if step[b[1]-1] > laststep:
tot += b[2] - a[b[1]-1]
a[b[1]-1] = b[2]
else:
{{completion}}
step[b[1]-1] = i
print(tot)
else:
tot = b[1] * n
last = b[1]
laststep = i
print(tot)
|
tot += b[2] - last
a[b[1]-1] = b[2]
|
[{"input": "5 5\n1 2 3 4 5\n1 1 5\n2 10\n1 5 11\n1 4 1\n2 1", "output": ["19\n50\n51\n42\n5"]}]
|
block_completion_005607
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Once upon a time Mike and Mike decided to come up with an outstanding problem for some stage of ROI (rare olympiad in informatics). One of them came up with a problem prototype but another stole the idea and proposed that problem for another stage of the same olympiad. Since then the first Mike has been waiting for an opportunity to propose the original idea for some other contest... Mike waited until this moment!You are given an array $$$a$$$ of $$$n$$$ integers. You are also given $$$q$$$ queries of two types: Replace $$$i$$$-th element in the array with integer $$$x$$$. Replace each element in the array with integer $$$x$$$. After performing each query you have to calculate the sum of all elements in the array.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$)Β β the number of elements in the array and the number of queries, respectively. The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array $$$a$$$. Each of the following $$$q$$$ lines contains a description of the corresponding query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2\}$$$) which denotes a type of the query: If $$$t = 1$$$, then two integers $$$i$$$ and $$$x$$$ are following ($$$1 \le i \le n$$$, $$$1 \le x \le 10^9$$$)Β β position of replaced element and it's new value. If $$$t = 2$$$, then integer $$$x$$$ is following ($$$1 \le x \le 10^9$$$)Β β new value of each element in the array.
Output Specification: Print $$$q$$$ integers, each on a separate line. In the $$$i$$$-th line print the sum of all elements in the array after performing the first $$$i$$$ queries.
Notes: NoteConsider array from the example and the result of performing each query: Initial array is $$$[1, 2, 3, 4, 5]$$$. After performing the first query, array equals to $$$[5, 2, 3, 4, 5]$$$. The sum of all elements is $$$19$$$. After performing the second query, array equals to $$$[10, 10, 10, 10, 10]$$$. The sum of all elements is $$$50$$$. After performing the third query, array equals to $$$[10, 10, 10, 10, 11$$$]. The sum of all elements is $$$51$$$. After performing the fourth query, array equals to $$$[10, 10, 10, 1, 11]$$$. The sum of all elements is $$$42$$$. After performing the fifth query, array equals to $$$[1, 1, 1, 1, 1]$$$. The sum of all elements is $$$5$$$.
Code:
def inpList():
return [int(i) for i in input().split()]
def solve():
n, q = inpList()
a = inpList()
t1 = {}
t2 = 0
sm = sum(a)
for qi in range(q):
inp = inpList()
if len(inp) == 3:
_, i, x = inp
if t1.get(i):
sm += x - t1[i]
else:
# TODO: Your code here
t1[i] = x
else:
_, x = inp
t2 = x
sm = t2*n
t1 = {}
print(sm)
solve()
|
def inpList():
return [int(i) for i in input().split()]
def solve():
n, q = inpList()
a = inpList()
t1 = {}
t2 = 0
sm = sum(a)
for qi in range(q):
inp = inpList()
if len(inp) == 3:
_, i, x = inp
if t1.get(i):
sm += x - t1[i]
else:
{{completion}}
t1[i] = x
else:
_, x = inp
t2 = x
sm = t2*n
t1 = {}
print(sm)
solve()
|
sm += x - (t2 or a[i-1])
|
[{"input": "5 5\n1 2 3 4 5\n1 1 5\n2 10\n1 5 11\n1 4 1\n2 1", "output": ["19\n50\n51\n42\n5"]}]
|
block_completion_005608
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Once upon a time Mike and Mike decided to come up with an outstanding problem for some stage of ROI (rare olympiad in informatics). One of them came up with a problem prototype but another stole the idea and proposed that problem for another stage of the same olympiad. Since then the first Mike has been waiting for an opportunity to propose the original idea for some other contest... Mike waited until this moment!You are given an array $$$a$$$ of $$$n$$$ integers. You are also given $$$q$$$ queries of two types: Replace $$$i$$$-th element in the array with integer $$$x$$$. Replace each element in the array with integer $$$x$$$. After performing each query you have to calculate the sum of all elements in the array.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$)Β β the number of elements in the array and the number of queries, respectively. The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array $$$a$$$. Each of the following $$$q$$$ lines contains a description of the corresponding query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2\}$$$) which denotes a type of the query: If $$$t = 1$$$, then two integers $$$i$$$ and $$$x$$$ are following ($$$1 \le i \le n$$$, $$$1 \le x \le 10^9$$$)Β β position of replaced element and it's new value. If $$$t = 2$$$, then integer $$$x$$$ is following ($$$1 \le x \le 10^9$$$)Β β new value of each element in the array.
Output Specification: Print $$$q$$$ integers, each on a separate line. In the $$$i$$$-th line print the sum of all elements in the array after performing the first $$$i$$$ queries.
Notes: NoteConsider array from the example and the result of performing each query: Initial array is $$$[1, 2, 3, 4, 5]$$$. After performing the first query, array equals to $$$[5, 2, 3, 4, 5]$$$. The sum of all elements is $$$19$$$. After performing the second query, array equals to $$$[10, 10, 10, 10, 10]$$$. The sum of all elements is $$$50$$$. After performing the third query, array equals to $$$[10, 10, 10, 10, 11$$$]. The sum of all elements is $$$51$$$. After performing the fourth query, array equals to $$$[10, 10, 10, 1, 11]$$$. The sum of all elements is $$$42$$$. After performing the fifth query, array equals to $$$[1, 1, 1, 1, 1]$$$. The sum of all elements is $$$5$$$.
Code:
from collections import defaultdict
import sys
input = sys.stdin.readline
n, q = map(int, input().split())
t = dict(enumerate(map(int, input().split())))
ans = sum(t.values())
for i in range(q):
p = list(map(int, input().split()))
if p[0] == 2:
k = p[1]
ans = n*p[1]
t = defaultdict(lambda:k)
else :
# TODO: Your code here
print(ans)
|
from collections import defaultdict
import sys
input = sys.stdin.readline
n, q = map(int, input().split())
t = dict(enumerate(map(int, input().split())))
ans = sum(t.values())
for i in range(q):
p = list(map(int, input().split()))
if p[0] == 2:
k = p[1]
ans = n*p[1]
t = defaultdict(lambda:k)
else :
{{completion}}
print(ans)
|
ans += p[2] - t[p[1] - 1]
t[p[1] - 1] = p[2]
|
[{"input": "5 5\n1 2 3 4 5\n1 1 5\n2 10\n1 5 11\n1 4 1\n2 1", "output": ["19\n50\n51\n42\n5"]}]
|
block_completion_005609
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Once upon a time Mike and Mike decided to come up with an outstanding problem for some stage of ROI (rare olympiad in informatics). One of them came up with a problem prototype but another stole the idea and proposed that problem for another stage of the same olympiad. Since then the first Mike has been waiting for an opportunity to propose the original idea for some other contest... Mike waited until this moment!You are given an array $$$a$$$ of $$$n$$$ integers. You are also given $$$q$$$ queries of two types: Replace $$$i$$$-th element in the array with integer $$$x$$$. Replace each element in the array with integer $$$x$$$. After performing each query you have to calculate the sum of all elements in the array.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$)Β β the number of elements in the array and the number of queries, respectively. The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array $$$a$$$. Each of the following $$$q$$$ lines contains a description of the corresponding query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2\}$$$) which denotes a type of the query: If $$$t = 1$$$, then two integers $$$i$$$ and $$$x$$$ are following ($$$1 \le i \le n$$$, $$$1 \le x \le 10^9$$$)Β β position of replaced element and it's new value. If $$$t = 2$$$, then integer $$$x$$$ is following ($$$1 \le x \le 10^9$$$)Β β new value of each element in the array.
Output Specification: Print $$$q$$$ integers, each on a separate line. In the $$$i$$$-th line print the sum of all elements in the array after performing the first $$$i$$$ queries.
Notes: NoteConsider array from the example and the result of performing each query: Initial array is $$$[1, 2, 3, 4, 5]$$$. After performing the first query, array equals to $$$[5, 2, 3, 4, 5]$$$. The sum of all elements is $$$19$$$. After performing the second query, array equals to $$$[10, 10, 10, 10, 10]$$$. The sum of all elements is $$$50$$$. After performing the third query, array equals to $$$[10, 10, 10, 10, 11$$$]. The sum of all elements is $$$51$$$. After performing the fourth query, array equals to $$$[10, 10, 10, 1, 11]$$$. The sum of all elements is $$$42$$$. After performing the fifth query, array equals to $$$[1, 1, 1, 1, 1]$$$. The sum of all elements is $$$5$$$.
Code:
n,q = map(int, input().split(' '))
array = list(map(int, input().split(' ')))
d = {i:item for i,item in enumerate(array, start=1)}
tot = sum(array)
default = None
for _ in range(q):
t, *a = map(int, input().split(' '))
if t==1:
i, x = a
tot += (x-d.get(i, default))
d[i] = x
elif t==2:
# TODO: Your code here
print(tot)
|
n,q = map(int, input().split(' '))
array = list(map(int, input().split(' ')))
d = {i:item for i,item in enumerate(array, start=1)}
tot = sum(array)
default = None
for _ in range(q):
t, *a = map(int, input().split(' '))
if t==1:
i, x = a
tot += (x-d.get(i, default))
d[i] = x
elif t==2:
{{completion}}
print(tot)
|
default, = a
tot = default*n
d = {}
|
[{"input": "5 5\n1 2 3 4 5\n1 1 5\n2 10\n1 5 11\n1 4 1\n2 1", "output": ["19\n50\n51\n42\n5"]}]
|
block_completion_005610
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Once upon a time Mike and Mike decided to come up with an outstanding problem for some stage of ROI (rare olympiad in informatics). One of them came up with a problem prototype but another stole the idea and proposed that problem for another stage of the same olympiad. Since then the first Mike has been waiting for an opportunity to propose the original idea for some other contest... Mike waited until this moment!You are given an array $$$a$$$ of $$$n$$$ integers. You are also given $$$q$$$ queries of two types: Replace $$$i$$$-th element in the array with integer $$$x$$$. Replace each element in the array with integer $$$x$$$. After performing each query you have to calculate the sum of all elements in the array.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$)Β β the number of elements in the array and the number of queries, respectively. The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array $$$a$$$. Each of the following $$$q$$$ lines contains a description of the corresponding query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2\}$$$) which denotes a type of the query: If $$$t = 1$$$, then two integers $$$i$$$ and $$$x$$$ are following ($$$1 \le i \le n$$$, $$$1 \le x \le 10^9$$$)Β β position of replaced element and it's new value. If $$$t = 2$$$, then integer $$$x$$$ is following ($$$1 \le x \le 10^9$$$)Β β new value of each element in the array.
Output Specification: Print $$$q$$$ integers, each on a separate line. In the $$$i$$$-th line print the sum of all elements in the array after performing the first $$$i$$$ queries.
Notes: NoteConsider array from the example and the result of performing each query: Initial array is $$$[1, 2, 3, 4, 5]$$$. After performing the first query, array equals to $$$[5, 2, 3, 4, 5]$$$. The sum of all elements is $$$19$$$. After performing the second query, array equals to $$$[10, 10, 10, 10, 10]$$$. The sum of all elements is $$$50$$$. After performing the third query, array equals to $$$[10, 10, 10, 10, 11$$$]. The sum of all elements is $$$51$$$. After performing the fourth query, array equals to $$$[10, 10, 10, 1, 11]$$$. The sum of all elements is $$$42$$$. After performing the fifth query, array equals to $$$[1, 1, 1, 1, 1]$$$. The sum of all elements is $$$5$$$.
Code:
f=open(0)
s=lambda:map(int,next(f).split())
n,tst=s()
arr={}
i=g=ans=0
for x in s():ans+=x;i+=1;arr[i]=x
while tst:
tst-=1;t,*x=s()
if t&1:i,x=x;ans+=x-arr.get(i,g);arr[i]=x
else:# TODO: Your code here
print(ans)
|
f=open(0)
s=lambda:map(int,next(f).split())
n,tst=s()
arr={}
i=g=ans=0
for x in s():ans+=x;i+=1;arr[i]=x
while tst:
tst-=1;t,*x=s()
if t&1:i,x=x;ans+=x-arr.get(i,g);arr[i]=x
else:{{completion}}
print(ans)
|
arr={};g,=x;ans=g*n
|
[{"input": "5 5\n1 2 3 4 5\n1 1 5\n2 10\n1 5 11\n1 4 1\n2 1", "output": ["19\n50\n51\n42\n5"]}]
|
block_completion_005611
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Once upon a time Mike and Mike decided to come up with an outstanding problem for some stage of ROI (rare olympiad in informatics). One of them came up with a problem prototype but another stole the idea and proposed that problem for another stage of the same olympiad. Since then the first Mike has been waiting for an opportunity to propose the original idea for some other contest... Mike waited until this moment!You are given an array $$$a$$$ of $$$n$$$ integers. You are also given $$$q$$$ queries of two types: Replace $$$i$$$-th element in the array with integer $$$x$$$. Replace each element in the array with integer $$$x$$$. After performing each query you have to calculate the sum of all elements in the array.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$)Β β the number of elements in the array and the number of queries, respectively. The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array $$$a$$$. Each of the following $$$q$$$ lines contains a description of the corresponding query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2\}$$$) which denotes a type of the query: If $$$t = 1$$$, then two integers $$$i$$$ and $$$x$$$ are following ($$$1 \le i \le n$$$, $$$1 \le x \le 10^9$$$)Β β position of replaced element and it's new value. If $$$t = 2$$$, then integer $$$x$$$ is following ($$$1 \le x \le 10^9$$$)Β β new value of each element in the array.
Output Specification: Print $$$q$$$ integers, each on a separate line. In the $$$i$$$-th line print the sum of all elements in the array after performing the first $$$i$$$ queries.
Notes: NoteConsider array from the example and the result of performing each query: Initial array is $$$[1, 2, 3, 4, 5]$$$. After performing the first query, array equals to $$$[5, 2, 3, 4, 5]$$$. The sum of all elements is $$$19$$$. After performing the second query, array equals to $$$[10, 10, 10, 10, 10]$$$. The sum of all elements is $$$50$$$. After performing the third query, array equals to $$$[10, 10, 10, 10, 11$$$]. The sum of all elements is $$$51$$$. After performing the fourth query, array equals to $$$[10, 10, 10, 1, 11]$$$. The sum of all elements is $$$42$$$. After performing the fifth query, array equals to $$$[1, 1, 1, 1, 1]$$$. The sum of all elements is $$$5$$$.
Code:
n, q = list(map(int, input().split()))
a = list(map(int, input().split()))
x, c, s, b = 0, 0, sum(a), [1]*(n)
for i in range(q):
k = list(map(int, input().split()))
if k[0]==1:
j = k[1]-1
if b[j]>c:
s = s-a[j]+k[2]
else:
# TODO: Your code here
a[j] = k[2]
print(s)
else:
c = c+1
x = k[1]
s = n*x
print(s)
|
n, q = list(map(int, input().split()))
a = list(map(int, input().split()))
x, c, s, b = 0, 0, sum(a), [1]*(n)
for i in range(q):
k = list(map(int, input().split()))
if k[0]==1:
j = k[1]-1
if b[j]>c:
s = s-a[j]+k[2]
else:
{{completion}}
a[j] = k[2]
print(s)
else:
c = c+1
x = k[1]
s = n*x
print(s)
|
s = s-x+k[2]
b[j] = c+1
|
[{"input": "5 5\n1 2 3 4 5\n1 1 5\n2 10\n1 5 11\n1 4 1\n2 1", "output": ["19\n50\n51\n42\n5"]}]
|
block_completion_005612
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Once upon a time Mike and Mike decided to come up with an outstanding problem for some stage of ROI (rare olympiad in informatics). One of them came up with a problem prototype but another stole the idea and proposed that problem for another stage of the same olympiad. Since then the first Mike has been waiting for an opportunity to propose the original idea for some other contest... Mike waited until this moment!You are given an array $$$a$$$ of $$$n$$$ integers. You are also given $$$q$$$ queries of two types: Replace $$$i$$$-th element in the array with integer $$$x$$$. Replace each element in the array with integer $$$x$$$. After performing each query you have to calculate the sum of all elements in the array.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$)Β β the number of elements in the array and the number of queries, respectively. The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array $$$a$$$. Each of the following $$$q$$$ lines contains a description of the corresponding query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2\}$$$) which denotes a type of the query: If $$$t = 1$$$, then two integers $$$i$$$ and $$$x$$$ are following ($$$1 \le i \le n$$$, $$$1 \le x \le 10^9$$$)Β β position of replaced element and it's new value. If $$$t = 2$$$, then integer $$$x$$$ is following ($$$1 \le x \le 10^9$$$)Β β new value of each element in the array.
Output Specification: Print $$$q$$$ integers, each on a separate line. In the $$$i$$$-th line print the sum of all elements in the array after performing the first $$$i$$$ queries.
Notes: NoteConsider array from the example and the result of performing each query: Initial array is $$$[1, 2, 3, 4, 5]$$$. After performing the first query, array equals to $$$[5, 2, 3, 4, 5]$$$. The sum of all elements is $$$19$$$. After performing the second query, array equals to $$$[10, 10, 10, 10, 10]$$$. The sum of all elements is $$$50$$$. After performing the third query, array equals to $$$[10, 10, 10, 10, 11$$$]. The sum of all elements is $$$51$$$. After performing the fourth query, array equals to $$$[10, 10, 10, 1, 11]$$$. The sum of all elements is $$$42$$$. After performing the fifth query, array equals to $$$[1, 1, 1, 1, 1]$$$. The sum of all elements is $$$5$$$.
Code:
f=open(0)
n,q=map(int,next(f).split())
a = list(map(int,next(f).split()))
c = [-1]*n
X = 0
S = sum(a)
lst=-2
for idx in range(q):
req = list(map(int,next(f).split()))
if (req[0] == 1):
i = req[1]-1
x = req[2]
current = X if c[i]<lst else a[i]
S += x - current
a[i] = x
c[i] = idx
else:
# TODO: Your code here
print(S)
|
f=open(0)
n,q=map(int,next(f).split())
a = list(map(int,next(f).split()))
c = [-1]*n
X = 0
S = sum(a)
lst=-2
for idx in range(q):
req = list(map(int,next(f).split()))
if (req[0] == 1):
i = req[1]-1
x = req[2]
current = X if c[i]<lst else a[i]
S += x - current
a[i] = x
c[i] = idx
else:
{{completion}}
print(S)
|
X = req[1]
S = X * n
lst = idx
|
[{"input": "5 5\n1 2 3 4 5\n1 1 5\n2 10\n1 5 11\n1 4 1\n2 1", "output": ["19\n50\n51\n42\n5"]}]
|
block_completion_005613
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Once upon a time Mike and Mike decided to come up with an outstanding problem for some stage of ROI (rare olympiad in informatics). One of them came up with a problem prototype but another stole the idea and proposed that problem for another stage of the same olympiad. Since then the first Mike has been waiting for an opportunity to propose the original idea for some other contest... Mike waited until this moment!You are given an array $$$a$$$ of $$$n$$$ integers. You are also given $$$q$$$ queries of two types: Replace $$$i$$$-th element in the array with integer $$$x$$$. Replace each element in the array with integer $$$x$$$. After performing each query you have to calculate the sum of all elements in the array.
Input Specification: The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$)Β β the number of elements in the array and the number of queries, respectively. The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)Β β elements of the array $$$a$$$. Each of the following $$$q$$$ lines contains a description of the corresponding query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2\}$$$) which denotes a type of the query: If $$$t = 1$$$, then two integers $$$i$$$ and $$$x$$$ are following ($$$1 \le i \le n$$$, $$$1 \le x \le 10^9$$$)Β β position of replaced element and it's new value. If $$$t = 2$$$, then integer $$$x$$$ is following ($$$1 \le x \le 10^9$$$)Β β new value of each element in the array.
Output Specification: Print $$$q$$$ integers, each on a separate line. In the $$$i$$$-th line print the sum of all elements in the array after performing the first $$$i$$$ queries.
Notes: NoteConsider array from the example and the result of performing each query: Initial array is $$$[1, 2, 3, 4, 5]$$$. After performing the first query, array equals to $$$[5, 2, 3, 4, 5]$$$. The sum of all elements is $$$19$$$. After performing the second query, array equals to $$$[10, 10, 10, 10, 10]$$$. The sum of all elements is $$$50$$$. After performing the third query, array equals to $$$[10, 10, 10, 10, 11$$$]. The sum of all elements is $$$51$$$. After performing the fourth query, array equals to $$$[10, 10, 10, 1, 11]$$$. The sum of all elements is $$$42$$$. After performing the fifth query, array equals to $$$[1, 1, 1, 1, 1]$$$. The sum of all elements is $$$5$$$.
Code:
import sys, math
input = sys.stdin.readline
n, q = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
d = {}
for i in range(n):
d[i + 1] = a[i]
type2 = 0
for i in range(q):
t = [int(x) for x in input().split()]
if t[0] == 1:
d[t[1]] = t[2]
else:
# TODO: Your code here
print(type2*(n - len(d)) + sum(d.values()))
|
import sys, math
input = sys.stdin.readline
n, q = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
d = {}
for i in range(n):
d[i + 1] = a[i]
type2 = 0
for i in range(q):
t = [int(x) for x in input().split()]
if t[0] == 1:
d[t[1]] = t[2]
else:
{{completion}}
print(type2*(n - len(d)) + sum(d.values()))
|
d.clear()
type2 = t[1]
|
[{"input": "5 5\n1 2 3 4 5\n1 1 5\n2 10\n1 5 11\n1 4 1\n2 1", "output": ["19\n50\n51\n42\n5"]}]
|
block_completion_005614
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: One day Masha was walking in the park and found a graph under a tree... Surprised? Did you think that this problem would have some logical and reasoned story? No way! So, the problem...Masha has an oriented graph which $$$i$$$-th vertex contains some positive integer $$$a_i$$$. Initially Masha can put a coin at some vertex. In one operation she can move a coin placed in some vertex $$$u$$$ to any other vertex $$$v$$$ such that there is an oriented edge $$$u \to v$$$ in the graph. Each time when the coin is placed in some vertex $$$i$$$, Masha write down an integer $$$a_i$$$ in her notebook (in particular, when Masha initially puts a coin at some vertex, she writes an integer written at this vertex in her notebook). Masha wants to make exactly $$$k - 1$$$ operations in such way that the maximum number written in her notebook is as small as possible.
Input Specification: The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le 2 \cdot 10^5$$$, $$$1 \le k \le 10^{18}$$$)Β β the number of vertices and edges in the graph, and the number of operation that Masha should make. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β the numbers written in graph vertices. Each of the following $$$m$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u \ne v \le n$$$)Β β it means that there is an edge $$$u \to v$$$ in the graph. It's guaranteed that graph doesn't contain loops and multi-edges.
Output Specification: Print one integerΒ β the minimum value of the maximum number that Masha wrote in her notebook during optimal coin movements. If Masha won't be able to perform $$$k - 1$$$ operations, print $$$-1$$$.
Notes: NoteGraph described in the first and the second examples is illustrated below. In the first example Masha can initially put a coin at vertex $$$1$$$. After that she can perform three operations: $$$1 \to 3$$$, $$$3 \to 4$$$ and $$$4 \to 5$$$. Integers $$$1, 2, 3$$$ and $$$4$$$ will be written in the notepad.In the second example Masha can initially put a coin at vertex $$$2$$$. After that she can perform $$$99$$$ operations: $$$2 \to 5$$$, $$$5 \to 6$$$, $$$6 \to 2$$$, $$$2 \to 5$$$, and so on. Integers $$$10, 4, 5, 10, 4, 5, \ldots, 10, 4, 5, 10$$$ will be written in the notepad.In the third example Masha won't be able to perform $$$4$$$ operations.
Code:
import sys
input = sys.stdin.readline
def solve():
n, m, k = map(int, input().split())
arr = list(map(int, input().split()))
graph = [[] for _ in range(n)]
for i in range(m):
u, v = map(int, input().split())
graph[u-1].append(v-1)
lo, hi = min(arr), max(arr)+1
while lo < hi:
mid = lo + (hi-lo)//2
dp = [0]*n
degree = [0]*n
cnt = 0
for i in range(n):
if arr[i] > mid:
continue
cnt += 1
for nei in graph[i]:
if arr[nei] > mid:
# TODO: Your code here
degree[nei] += 1
stack = []
nums = 0
for i in range(n):
if degree[i] == 0 and arr[i] <= mid:
stack.append(i)
nums += 1
while stack:
curr = stack.pop()
for nei in graph[curr]:
if arr[nei] > mid:
continue
degree[nei] -= 1
if degree[nei] == 0:
stack.append(nei)
dp[nei] = max(dp[nei], dp[curr] + 1)
nums += 1
if nums != cnt or max(dp) >= k-1:
hi = mid
else:
lo = mid + 1
if lo == max(arr) + 1:
return -1
else:
return lo
print(solve())
|
import sys
input = sys.stdin.readline
def solve():
n, m, k = map(int, input().split())
arr = list(map(int, input().split()))
graph = [[] for _ in range(n)]
for i in range(m):
u, v = map(int, input().split())
graph[u-1].append(v-1)
lo, hi = min(arr), max(arr)+1
while lo < hi:
mid = lo + (hi-lo)//2
dp = [0]*n
degree = [0]*n
cnt = 0
for i in range(n):
if arr[i] > mid:
continue
cnt += 1
for nei in graph[i]:
if arr[nei] > mid:
{{completion}}
degree[nei] += 1
stack = []
nums = 0
for i in range(n):
if degree[i] == 0 and arr[i] <= mid:
stack.append(i)
nums += 1
while stack:
curr = stack.pop()
for nei in graph[curr]:
if arr[nei] > mid:
continue
degree[nei] -= 1
if degree[nei] == 0:
stack.append(nei)
dp[nei] = max(dp[nei], dp[curr] + 1)
nums += 1
if nums != cnt or max(dp) >= k-1:
hi = mid
else:
lo = mid + 1
if lo == max(arr) + 1:
return -1
else:
return lo
print(solve())
|
continue
|
[{"input": "6 7 4\n1 10 2 3 4 5\n1 2\n1 3\n3 4\n4 5\n5 6\n6 2\n2 5", "output": ["4"]}, {"input": "6 7 100\n1 10 2 3 4 5\n1 2\n1 3\n3 4\n4 5\n5 6\n6 2\n2 5", "output": ["10"]}, {"input": "2 1 5\n1 1\n1 2", "output": ["-1"]}, {"input": "1 0 1\n1000000000", "output": ["1000000000"]}]
|
block_completion_005667
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: One day Masha was walking in the park and found a graph under a tree... Surprised? Did you think that this problem would have some logical and reasoned story? No way! So, the problem...Masha has an oriented graph which $$$i$$$-th vertex contains some positive integer $$$a_i$$$. Initially Masha can put a coin at some vertex. In one operation she can move a coin placed in some vertex $$$u$$$ to any other vertex $$$v$$$ such that there is an oriented edge $$$u \to v$$$ in the graph. Each time when the coin is placed in some vertex $$$i$$$, Masha write down an integer $$$a_i$$$ in her notebook (in particular, when Masha initially puts a coin at some vertex, she writes an integer written at this vertex in her notebook). Masha wants to make exactly $$$k - 1$$$ operations in such way that the maximum number written in her notebook is as small as possible.
Input Specification: The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le 2 \cdot 10^5$$$, $$$1 \le k \le 10^{18}$$$)Β β the number of vertices and edges in the graph, and the number of operation that Masha should make. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β the numbers written in graph vertices. Each of the following $$$m$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u \ne v \le n$$$)Β β it means that there is an edge $$$u \to v$$$ in the graph. It's guaranteed that graph doesn't contain loops and multi-edges.
Output Specification: Print one integerΒ β the minimum value of the maximum number that Masha wrote in her notebook during optimal coin movements. If Masha won't be able to perform $$$k - 1$$$ operations, print $$$-1$$$.
Notes: NoteGraph described in the first and the second examples is illustrated below. In the first example Masha can initially put a coin at vertex $$$1$$$. After that she can perform three operations: $$$1 \to 3$$$, $$$3 \to 4$$$ and $$$4 \to 5$$$. Integers $$$1, 2, 3$$$ and $$$4$$$ will be written in the notepad.In the second example Masha can initially put a coin at vertex $$$2$$$. After that she can perform $$$99$$$ operations: $$$2 \to 5$$$, $$$5 \to 6$$$, $$$6 \to 2$$$, $$$2 \to 5$$$, and so on. Integers $$$10, 4, 5, 10, 4, 5, \ldots, 10, 4, 5, 10$$$ will be written in the notepad.In the third example Masha won't be able to perform $$$4$$$ operations.
Code:
import sys
input = sys.stdin.readline
def solve():
n, m, k = map(int, input().split())
arr = list(map(int, input().split()))
graph = [[] for _ in range(n)]
for i in range(m):
u, v = map(int, input().split())
graph[u-1].append(v-1)
lo, hi = min(arr), max(arr)+1
while lo < hi:
mid = lo + (hi-lo)//2
dp = [0]*n
degree = [0]*n
cnt = 0
for i in range(n):
if arr[i] > mid:
continue
cnt += 1
for nei in graph[i]:
if arr[nei] > mid:
continue
degree[nei] += 1
stack = []
nums = 0
for i in range(n):
if degree[i] == 0 and arr[i] <= mid:
stack.append(i)
nums += 1
while stack:
curr = stack.pop()
for nei in graph[curr]:
if arr[nei] > mid:
# TODO: Your code here
degree[nei] -= 1
if degree[nei] == 0:
stack.append(nei)
dp[nei] = max(dp[nei], dp[curr] + 1)
nums += 1
if nums != cnt or max(dp) >= k-1:
hi = mid
else:
lo = mid + 1
if lo == max(arr) + 1:
return -1
else:
return lo
print(solve())
|
import sys
input = sys.stdin.readline
def solve():
n, m, k = map(int, input().split())
arr = list(map(int, input().split()))
graph = [[] for _ in range(n)]
for i in range(m):
u, v = map(int, input().split())
graph[u-1].append(v-1)
lo, hi = min(arr), max(arr)+1
while lo < hi:
mid = lo + (hi-lo)//2
dp = [0]*n
degree = [0]*n
cnt = 0
for i in range(n):
if arr[i] > mid:
continue
cnt += 1
for nei in graph[i]:
if arr[nei] > mid:
continue
degree[nei] += 1
stack = []
nums = 0
for i in range(n):
if degree[i] == 0 and arr[i] <= mid:
stack.append(i)
nums += 1
while stack:
curr = stack.pop()
for nei in graph[curr]:
if arr[nei] > mid:
{{completion}}
degree[nei] -= 1
if degree[nei] == 0:
stack.append(nei)
dp[nei] = max(dp[nei], dp[curr] + 1)
nums += 1
if nums != cnt or max(dp) >= k-1:
hi = mid
else:
lo = mid + 1
if lo == max(arr) + 1:
return -1
else:
return lo
print(solve())
|
continue
|
[{"input": "6 7 4\n1 10 2 3 4 5\n1 2\n1 3\n3 4\n4 5\n5 6\n6 2\n2 5", "output": ["4"]}, {"input": "6 7 100\n1 10 2 3 4 5\n1 2\n1 3\n3 4\n4 5\n5 6\n6 2\n2 5", "output": ["10"]}, {"input": "2 1 5\n1 1\n1 2", "output": ["-1"]}, {"input": "1 0 1\n1000000000", "output": ["1000000000"]}]
|
block_completion_005668
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: One day Masha was walking in the park and found a graph under a tree... Surprised? Did you think that this problem would have some logical and reasoned story? No way! So, the problem...Masha has an oriented graph which $$$i$$$-th vertex contains some positive integer $$$a_i$$$. Initially Masha can put a coin at some vertex. In one operation she can move a coin placed in some vertex $$$u$$$ to any other vertex $$$v$$$ such that there is an oriented edge $$$u \to v$$$ in the graph. Each time when the coin is placed in some vertex $$$i$$$, Masha write down an integer $$$a_i$$$ in her notebook (in particular, when Masha initially puts a coin at some vertex, she writes an integer written at this vertex in her notebook). Masha wants to make exactly $$$k - 1$$$ operations in such way that the maximum number written in her notebook is as small as possible.
Input Specification: The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le 2 \cdot 10^5$$$, $$$1 \le k \le 10^{18}$$$)Β β the number of vertices and edges in the graph, and the number of operation that Masha should make. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β the numbers written in graph vertices. Each of the following $$$m$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u \ne v \le n$$$)Β β it means that there is an edge $$$u \to v$$$ in the graph. It's guaranteed that graph doesn't contain loops and multi-edges.
Output Specification: Print one integerΒ β the minimum value of the maximum number that Masha wrote in her notebook during optimal coin movements. If Masha won't be able to perform $$$k - 1$$$ operations, print $$$-1$$$.
Notes: NoteGraph described in the first and the second examples is illustrated below. In the first example Masha can initially put a coin at vertex $$$1$$$. After that she can perform three operations: $$$1 \to 3$$$, $$$3 \to 4$$$ and $$$4 \to 5$$$. Integers $$$1, 2, 3$$$ and $$$4$$$ will be written in the notepad.In the second example Masha can initially put a coin at vertex $$$2$$$. After that she can perform $$$99$$$ operations: $$$2 \to 5$$$, $$$5 \to 6$$$, $$$6 \to 2$$$, $$$2 \to 5$$$, and so on. Integers $$$10, 4, 5, 10, 4, 5, \ldots, 10, 4, 5, 10$$$ will be written in the notepad.In the third example Masha won't be able to perform $$$4$$$ operations.
Code:
import sys
from array import array
from collections import deque
input = lambda: sys.stdin.buffer.readline().decode().strip()
inp = lambda dtype: [dtype(x) for x in input().split()]
inp_2d = lambda dtype, n: [dtype(input()) for _ in range(n)]
inp_2ds = lambda dtype, n: [inp(dtype) for _ in range(n)]
ceil1 = lambda a, b: (a + b - 1) // b
debug = lambda *x: print(*x, file=sys.stderr)
out = array('i')
class graph:
def __init__(self, n):
self.n = n
self.gdict = [array('i') for _ in range(n + 1)]
self.deg = array('i', [0] * (n + 1))
def add_uniedge(self, node1, node2):
self.gdict[node1].append(node2)
self.deg[node2] += 1
def kahn(self):
# enqueue all node with 0 in degree
que, cnt = deque([(i, 0) for i in range(1, self.n + 1) if not self.deg[i]]), 0
ret = 0
while que:
s, lev = que.popleft()
ret = max(ret, lev)
for i in self.gdict[s]:
self.deg[i] -= 1
if a[i] <= md and not self.deg[i]:
# TODO: Your code here
cnt += 1
return cnt != valids or ret >= k - 1
n, m, k = inp(int)
a = array('i', [0] + inp(int))
g = graph(n)
for i in range(m):
u, v = inp(int)
g.add_uniedge(u, v)
be, en, ans = min(a[1:]), 10 ** 9, -1
orgdeg = g.deg[:]
while be <= en:
md, valids = (be + en) >> 1, n
for i in range(1, n + 1):
if a[i] > md:
valids -= 1
g.deg[i] = 10 ** 6
for j in g.gdict[i]:
g.deg[j] -= 1
if g.kahn():
en, ans = md - 1, md
else:
be = md + 1
g.deg = orgdeg[:]
print(ans)
|
import sys
from array import array
from collections import deque
input = lambda: sys.stdin.buffer.readline().decode().strip()
inp = lambda dtype: [dtype(x) for x in input().split()]
inp_2d = lambda dtype, n: [dtype(input()) for _ in range(n)]
inp_2ds = lambda dtype, n: [inp(dtype) for _ in range(n)]
ceil1 = lambda a, b: (a + b - 1) // b
debug = lambda *x: print(*x, file=sys.stderr)
out = array('i')
class graph:
def __init__(self, n):
self.n = n
self.gdict = [array('i') for _ in range(n + 1)]
self.deg = array('i', [0] * (n + 1))
def add_uniedge(self, node1, node2):
self.gdict[node1].append(node2)
self.deg[node2] += 1
def kahn(self):
# enqueue all node with 0 in degree
que, cnt = deque([(i, 0) for i in range(1, self.n + 1) if not self.deg[i]]), 0
ret = 0
while que:
s, lev = que.popleft()
ret = max(ret, lev)
for i in self.gdict[s]:
self.deg[i] -= 1
if a[i] <= md and not self.deg[i]:
{{completion}}
cnt += 1
return cnt != valids or ret >= k - 1
n, m, k = inp(int)
a = array('i', [0] + inp(int))
g = graph(n)
for i in range(m):
u, v = inp(int)
g.add_uniedge(u, v)
be, en, ans = min(a[1:]), 10 ** 9, -1
orgdeg = g.deg[:]
while be <= en:
md, valids = (be + en) >> 1, n
for i in range(1, n + 1):
if a[i] > md:
valids -= 1
g.deg[i] = 10 ** 6
for j in g.gdict[i]:
g.deg[j] -= 1
if g.kahn():
en, ans = md - 1, md
else:
be = md + 1
g.deg = orgdeg[:]
print(ans)
|
que.append((i, lev + 1))
|
[{"input": "6 7 4\n1 10 2 3 4 5\n1 2\n1 3\n3 4\n4 5\n5 6\n6 2\n2 5", "output": ["4"]}, {"input": "6 7 100\n1 10 2 3 4 5\n1 2\n1 3\n3 4\n4 5\n5 6\n6 2\n2 5", "output": ["10"]}, {"input": "2 1 5\n1 1\n1 2", "output": ["-1"]}, {"input": "1 0 1\n1000000000", "output": ["1000000000"]}]
|
block_completion_005669
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: One day Masha was walking in the park and found a graph under a tree... Surprised? Did you think that this problem would have some logical and reasoned story? No way! So, the problem...Masha has an oriented graph which $$$i$$$-th vertex contains some positive integer $$$a_i$$$. Initially Masha can put a coin at some vertex. In one operation she can move a coin placed in some vertex $$$u$$$ to any other vertex $$$v$$$ such that there is an oriented edge $$$u \to v$$$ in the graph. Each time when the coin is placed in some vertex $$$i$$$, Masha write down an integer $$$a_i$$$ in her notebook (in particular, when Masha initially puts a coin at some vertex, she writes an integer written at this vertex in her notebook). Masha wants to make exactly $$$k - 1$$$ operations in such way that the maximum number written in her notebook is as small as possible.
Input Specification: The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le 2 \cdot 10^5$$$, $$$1 \le k \le 10^{18}$$$)Β β the number of vertices and edges in the graph, and the number of operation that Masha should make. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β the numbers written in graph vertices. Each of the following $$$m$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u \ne v \le n$$$)Β β it means that there is an edge $$$u \to v$$$ in the graph. It's guaranteed that graph doesn't contain loops and multi-edges.
Output Specification: Print one integerΒ β the minimum value of the maximum number that Masha wrote in her notebook during optimal coin movements. If Masha won't be able to perform $$$k - 1$$$ operations, print $$$-1$$$.
Notes: NoteGraph described in the first and the second examples is illustrated below. In the first example Masha can initially put a coin at vertex $$$1$$$. After that she can perform three operations: $$$1 \to 3$$$, $$$3 \to 4$$$ and $$$4 \to 5$$$. Integers $$$1, 2, 3$$$ and $$$4$$$ will be written in the notepad.In the second example Masha can initially put a coin at vertex $$$2$$$. After that she can perform $$$99$$$ operations: $$$2 \to 5$$$, $$$5 \to 6$$$, $$$6 \to 2$$$, $$$2 \to 5$$$, and so on. Integers $$$10, 4, 5, 10, 4, 5, \ldots, 10, 4, 5, 10$$$ will be written in the notepad.In the third example Masha won't be able to perform $$$4$$$ operations.
Code:
from sys import stdin, stdout
n, m, k = [int(x) for x in stdin.readline().split()]
a = [int(x) for x in stdin.readline().split()]
edges = {i:[] for i in range(n)}
for bar in range(m):
u, v = [int(x)-1 for x in stdin.readline().split()]
edges[u].append(v)
a_copy = list(set(a))
a_copy.sort()
def check(bound):
heights = [0]*n
expanded = [0]*n
parents = [-1]*n
for root in range(n):
if a[root] <= bound and heights[root] == 0:
stack = [root]
while len(stack) > 0:
if heights[stack[-1]] > 0:
v = stack.pop()
expanded[v] = 2
if parents[v] != -1:
heights[parents[v]] = max(heights[parents[v]], 1 + heights[v])
if heights[parents[v]] >= k:
return True
else:
v = stack[-1]
heights[v] = 1
if heights[v] >= k:
return True
expanded[v] = 1
for w in edges[v]:
if a[w] <= bound:
if expanded[w] == 1:
return True
if heights[w] > 0:
heights[v] = max(heights[v], 1 + heights[w])
if heights[v] >= k:
# TODO: Your code here
else:
parents[w] = v
stack.append(w)
return False
if not check(a_copy[-1]):
stdout.write('-1\n')
else:
upper = len(a_copy)-1
lower = -1
while upper - lower > 1:
candidate = (upper+lower)//2
if check(a_copy[candidate]):
upper = candidate
else:
lower = candidate
stdout.write(str(a_copy[upper])+'\n')
|
from sys import stdin, stdout
n, m, k = [int(x) for x in stdin.readline().split()]
a = [int(x) for x in stdin.readline().split()]
edges = {i:[] for i in range(n)}
for bar in range(m):
u, v = [int(x)-1 for x in stdin.readline().split()]
edges[u].append(v)
a_copy = list(set(a))
a_copy.sort()
def check(bound):
heights = [0]*n
expanded = [0]*n
parents = [-1]*n
for root in range(n):
if a[root] <= bound and heights[root] == 0:
stack = [root]
while len(stack) > 0:
if heights[stack[-1]] > 0:
v = stack.pop()
expanded[v] = 2
if parents[v] != -1:
heights[parents[v]] = max(heights[parents[v]], 1 + heights[v])
if heights[parents[v]] >= k:
return True
else:
v = stack[-1]
heights[v] = 1
if heights[v] >= k:
return True
expanded[v] = 1
for w in edges[v]:
if a[w] <= bound:
if expanded[w] == 1:
return True
if heights[w] > 0:
heights[v] = max(heights[v], 1 + heights[w])
if heights[v] >= k:
{{completion}}
else:
parents[w] = v
stack.append(w)
return False
if not check(a_copy[-1]):
stdout.write('-1\n')
else:
upper = len(a_copy)-1
lower = -1
while upper - lower > 1:
candidate = (upper+lower)//2
if check(a_copy[candidate]):
upper = candidate
else:
lower = candidate
stdout.write(str(a_copy[upper])+'\n')
|
return True
|
[{"input": "6 7 4\n1 10 2 3 4 5\n1 2\n1 3\n3 4\n4 5\n5 6\n6 2\n2 5", "output": ["4"]}, {"input": "6 7 100\n1 10 2 3 4 5\n1 2\n1 3\n3 4\n4 5\n5 6\n6 2\n2 5", "output": ["10"]}, {"input": "2 1 5\n1 1\n1 2", "output": ["-1"]}, {"input": "1 0 1\n1000000000", "output": ["1000000000"]}]
|
block_completion_005670
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: One day Masha was walking in the park and found a graph under a tree... Surprised? Did you think that this problem would have some logical and reasoned story? No way! So, the problem...Masha has an oriented graph which $$$i$$$-th vertex contains some positive integer $$$a_i$$$. Initially Masha can put a coin at some vertex. In one operation she can move a coin placed in some vertex $$$u$$$ to any other vertex $$$v$$$ such that there is an oriented edge $$$u \to v$$$ in the graph. Each time when the coin is placed in some vertex $$$i$$$, Masha write down an integer $$$a_i$$$ in her notebook (in particular, when Masha initially puts a coin at some vertex, she writes an integer written at this vertex in her notebook). Masha wants to make exactly $$$k - 1$$$ operations in such way that the maximum number written in her notebook is as small as possible.
Input Specification: The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le 2 \cdot 10^5$$$, $$$1 \le k \le 10^{18}$$$)Β β the number of vertices and edges in the graph, and the number of operation that Masha should make. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β the numbers written in graph vertices. Each of the following $$$m$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u \ne v \le n$$$)Β β it means that there is an edge $$$u \to v$$$ in the graph. It's guaranteed that graph doesn't contain loops and multi-edges.
Output Specification: Print one integerΒ β the minimum value of the maximum number that Masha wrote in her notebook during optimal coin movements. If Masha won't be able to perform $$$k - 1$$$ operations, print $$$-1$$$.
Notes: NoteGraph described in the first and the second examples is illustrated below. In the first example Masha can initially put a coin at vertex $$$1$$$. After that she can perform three operations: $$$1 \to 3$$$, $$$3 \to 4$$$ and $$$4 \to 5$$$. Integers $$$1, 2, 3$$$ and $$$4$$$ will be written in the notepad.In the second example Masha can initially put a coin at vertex $$$2$$$. After that she can perform $$$99$$$ operations: $$$2 \to 5$$$, $$$5 \to 6$$$, $$$6 \to 2$$$, $$$2 \to 5$$$, and so on. Integers $$$10, 4, 5, 10, 4, 5, \ldots, 10, 4, 5, 10$$$ will be written in the notepad.In the third example Masha won't be able to perform $$$4$$$ operations.
Code:
import sys
input = sys.stdin.readline
n, m, k = list(map(int,input().split()))
arr = list(map(int,input().split()))
adj = [list() for _ in range(n)]
for i in range(m):
u, v = list(map(int,input().split()))
adj[u-1].append(v-1)
def dfs(u, vis, val, dist, group):
vis[u] = True
group[u] = 1
for v in adj[u]:
if arr[v] <= val :
if group[v]:
dist[u] = 10**18
return True
if not vis[v]:
dfs(v, vis, val, dist, group)
group[v] = 0
dist[u] = max(dist[u], dist[v] + 1)
if dist[u] >= k :
return True
def ok(val):
if k == 1:return True
vis = [False] * n
dist = [1] * n
group = [0] * n
for i in range(n):
if arr[i] <= val and not vis[i]:
stk = [i]
while stk:
u = stk.pop()
if vis[u]:
for v in adj[u]:
if arr[v] <= val :
dist[u] = max(dist[u], dist[v] + 1)
if dist[u] >= k :
# TODO: Your code here
group[v] = 0
group[u] = 0
continue
stk.append(u)
group[u] = 1
vis[u] = True
for v in adj[u]:
if group[v]:
return True
if arr[v] <= val :
if not vis[v]:
stk.append(v)
group[i] = 0
return False
sor = sorted(arr)
l = 0
r = n - 1
while l <= r :
mid = (l + r) // 2
if ok(sor[mid]):
r = mid - 1
else:
l = mid + 1
if l == n:
print(-1)
else:
print(sor[l])
|
import sys
input = sys.stdin.readline
n, m, k = list(map(int,input().split()))
arr = list(map(int,input().split()))
adj = [list() for _ in range(n)]
for i in range(m):
u, v = list(map(int,input().split()))
adj[u-1].append(v-1)
def dfs(u, vis, val, dist, group):
vis[u] = True
group[u] = 1
for v in adj[u]:
if arr[v] <= val :
if group[v]:
dist[u] = 10**18
return True
if not vis[v]:
dfs(v, vis, val, dist, group)
group[v] = 0
dist[u] = max(dist[u], dist[v] + 1)
if dist[u] >= k :
return True
def ok(val):
if k == 1:return True
vis = [False] * n
dist = [1] * n
group = [0] * n
for i in range(n):
if arr[i] <= val and not vis[i]:
stk = [i]
while stk:
u = stk.pop()
if vis[u]:
for v in adj[u]:
if arr[v] <= val :
dist[u] = max(dist[u], dist[v] + 1)
if dist[u] >= k :
{{completion}}
group[v] = 0
group[u] = 0
continue
stk.append(u)
group[u] = 1
vis[u] = True
for v in adj[u]:
if group[v]:
return True
if arr[v] <= val :
if not vis[v]:
stk.append(v)
group[i] = 0
return False
sor = sorted(arr)
l = 0
r = n - 1
while l <= r :
mid = (l + r) // 2
if ok(sor[mid]):
r = mid - 1
else:
l = mid + 1
if l == n:
print(-1)
else:
print(sor[l])
|
return True
|
[{"input": "6 7 4\n1 10 2 3 4 5\n1 2\n1 3\n3 4\n4 5\n5 6\n6 2\n2 5", "output": ["4"]}, {"input": "6 7 100\n1 10 2 3 4 5\n1 2\n1 3\n3 4\n4 5\n5 6\n6 2\n2 5", "output": ["10"]}, {"input": "2 1 5\n1 1\n1 2", "output": ["-1"]}, {"input": "1 0 1\n1000000000", "output": ["1000000000"]}]
|
block_completion_005671
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: One day Masha was walking in the park and found a graph under a tree... Surprised? Did you think that this problem would have some logical and reasoned story? No way! So, the problem...Masha has an oriented graph which $$$i$$$-th vertex contains some positive integer $$$a_i$$$. Initially Masha can put a coin at some vertex. In one operation she can move a coin placed in some vertex $$$u$$$ to any other vertex $$$v$$$ such that there is an oriented edge $$$u \to v$$$ in the graph. Each time when the coin is placed in some vertex $$$i$$$, Masha write down an integer $$$a_i$$$ in her notebook (in particular, when Masha initially puts a coin at some vertex, she writes an integer written at this vertex in her notebook). Masha wants to make exactly $$$k - 1$$$ operations in such way that the maximum number written in her notebook is as small as possible.
Input Specification: The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le 2 \cdot 10^5$$$, $$$1 \le k \le 10^{18}$$$)Β β the number of vertices and edges in the graph, and the number of operation that Masha should make. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$)Β β the numbers written in graph vertices. Each of the following $$$m$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u \ne v \le n$$$)Β β it means that there is an edge $$$u \to v$$$ in the graph. It's guaranteed that graph doesn't contain loops and multi-edges.
Output Specification: Print one integerΒ β the minimum value of the maximum number that Masha wrote in her notebook during optimal coin movements. If Masha won't be able to perform $$$k - 1$$$ operations, print $$$-1$$$.
Notes: NoteGraph described in the first and the second examples is illustrated below. In the first example Masha can initially put a coin at vertex $$$1$$$. After that she can perform three operations: $$$1 \to 3$$$, $$$3 \to 4$$$ and $$$4 \to 5$$$. Integers $$$1, 2, 3$$$ and $$$4$$$ will be written in the notepad.In the second example Masha can initially put a coin at vertex $$$2$$$. After that she can perform $$$99$$$ operations: $$$2 \to 5$$$, $$$5 \to 6$$$, $$$6 \to 2$$$, $$$2 \to 5$$$, and so on. Integers $$$10, 4, 5, 10, 4, 5, \ldots, 10, 4, 5, 10$$$ will be written in the notepad.In the third example Masha won't be able to perform $$$4$$$ operations.
Code:
import sys
input = sys.stdin.readline
n, m, k = list(map(int,input().split()))
arr = list(map(int,input().split()))
adj = [list() for _ in range(n)]
for i in range(m):
u, v = list(map(int,input().split()))
adj[u-1].append(v-1)
def dfs(u, vis, val, dist, group):
vis[u] = True
group[u] = 1
for v in adj[u]:
if arr[v] <= val :
if group[v]:
dist[u] = 10**18
return True
if not vis[v]:
dfs(v, vis, val, dist, group)
group[v] = 0
dist[u] = max(dist[u], dist[v] + 1)
if dist[u] >= k :
return True
def ok(val):
if k == 1:return True
vis = [False] * n
dist = [1] * n
group = [0] * n
for i in range(n):
if arr[i] <= val and not vis[i]:
stk = [i]
while stk:
u = stk.pop()
if vis[u]:
for v in adj[u]:
if arr[v] <= val :
dist[u] = max(dist[u], dist[v] + 1)
if dist[u] >= k :
return True
group[v] = 0
group[u] = 0
continue
stk.append(u)
group[u] = 1
vis[u] = True
for v in adj[u]:
if group[v]:
return True
if arr[v] <= val :
if not vis[v]:
# TODO: Your code here
group[i] = 0
return False
sor = sorted(arr)
l = 0
r = n - 1
while l <= r :
mid = (l + r) // 2
if ok(sor[mid]):
r = mid - 1
else:
l = mid + 1
if l == n:
print(-1)
else:
print(sor[l])
|
import sys
input = sys.stdin.readline
n, m, k = list(map(int,input().split()))
arr = list(map(int,input().split()))
adj = [list() for _ in range(n)]
for i in range(m):
u, v = list(map(int,input().split()))
adj[u-1].append(v-1)
def dfs(u, vis, val, dist, group):
vis[u] = True
group[u] = 1
for v in adj[u]:
if arr[v] <= val :
if group[v]:
dist[u] = 10**18
return True
if not vis[v]:
dfs(v, vis, val, dist, group)
group[v] = 0
dist[u] = max(dist[u], dist[v] + 1)
if dist[u] >= k :
return True
def ok(val):
if k == 1:return True
vis = [False] * n
dist = [1] * n
group = [0] * n
for i in range(n):
if arr[i] <= val and not vis[i]:
stk = [i]
while stk:
u = stk.pop()
if vis[u]:
for v in adj[u]:
if arr[v] <= val :
dist[u] = max(dist[u], dist[v] + 1)
if dist[u] >= k :
return True
group[v] = 0
group[u] = 0
continue
stk.append(u)
group[u] = 1
vis[u] = True
for v in adj[u]:
if group[v]:
return True
if arr[v] <= val :
if not vis[v]:
{{completion}}
group[i] = 0
return False
sor = sorted(arr)
l = 0
r = n - 1
while l <= r :
mid = (l + r) // 2
if ok(sor[mid]):
r = mid - 1
else:
l = mid + 1
if l == n:
print(-1)
else:
print(sor[l])
|
stk.append(v)
|
[{"input": "6 7 4\n1 10 2 3 4 5\n1 2\n1 3\n3 4\n4 5\n5 6\n6 2\n2 5", "output": ["4"]}, {"input": "6 7 100\n1 10 2 3 4 5\n1 2\n1 3\n3 4\n4 5\n5 6\n6 2\n2 5", "output": ["10"]}, {"input": "2 1 5\n1 1\n1 2", "output": ["-1"]}, {"input": "1 0 1\n1000000000", "output": ["1000000000"]}]
|
block_completion_005672
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: On an $$$8 \times 8$$$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last. The red stripe was painted after the blue one, so the answer is R.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 4000$$$)Β β the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either 'R', 'B', or '.', denoting a red square, a blue square, and an unpainted square, respectively. It is guaranteed that the given field is obtained from a colorless one by drawing horizontal red rows and vertical blue columns. At least one stripe is painted.
Output Specification: For each test case, output 'R' if a red stripe was painted last, and 'B' if a blue stripe was painted last (without quotes).
Notes: NoteThe first test case is pictured in the statement.In the second test case, the first blue column is painted first, then the first and last red rows, and finally the last blue column. Since a blue stripe is painted last, the answer is B.
Code:
test = int(input())
for i in range(test):
ans = "B"
cnt =0
while cnt < 8 :
t = input()
if t.strip() != '':
cnt +=1
if t == "RRRRRRRR":
# TODO: Your code here
print(ans)
|
test = int(input())
for i in range(test):
ans = "B"
cnt =0
while cnt < 8 :
t = input()
if t.strip() != '':
cnt +=1
if t == "RRRRRRRR":
{{completion}}
print(ans)
|
ans = "R"
|
[{"input": "4\n\n\n\n\n....B...\n\n....B...\n\n....B...\n\nRRRRRRRR\n\n....B...\n\n....B...\n\n....B...\n\n....B...\n\n\n\n\nRRRRRRRB\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nRRRRRRRB\n\n\n\n\nRRRRRRBB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\n\n\n\n........\n\n........\n\n........\n\nRRRRRRRR\n\n........\n\n........\n\n........\n\n........", "output": ["R\nB\nB\nR"]}]
|
block_completion_005800
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: On an $$$8 \times 8$$$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last. The red stripe was painted after the blue one, so the answer is R.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 4000$$$)Β β the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either 'R', 'B', or '.', denoting a red square, a blue square, and an unpainted square, respectively. It is guaranteed that the given field is obtained from a colorless one by drawing horizontal red rows and vertical blue columns. At least one stripe is painted.
Output Specification: For each test case, output 'R' if a red stripe was painted last, and 'B' if a blue stripe was painted last (without quotes).
Notes: NoteThe first test case is pictured in the statement.In the second test case, the first blue column is painted first, then the first and last red rows, and finally the last blue column. Since a blue stripe is painted last, the answer is B.
Code:
t=int(input())
for p in range(t):
l=[]
c=0
a=['R','R','R','R','R','R','R','R']
while(len(l)<8):
s=input()
if len(s)==8:
# TODO: Your code here
for i in range(8):
if l[i]==a:
c=1
break
print("B" if c!=1 else "R")
|
t=int(input())
for p in range(t):
l=[]
c=0
a=['R','R','R','R','R','R','R','R']
while(len(l)<8):
s=input()
if len(s)==8:
{{completion}}
for i in range(8):
if l[i]==a:
c=1
break
print("B" if c!=1 else "R")
|
l.append([*s])
|
[{"input": "4\n\n\n\n\n....B...\n\n....B...\n\n....B...\n\nRRRRRRRR\n\n....B...\n\n....B...\n\n....B...\n\n....B...\n\n\n\n\nRRRRRRRB\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nRRRRRRRB\n\n\n\n\nRRRRRRBB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\n\n\n\n........\n\n........\n\n........\n\nRRRRRRRR\n\n........\n\n........\n\n........\n\n........", "output": ["R\nB\nB\nR"]}]
|
block_completion_005801
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: On an $$$8 \times 8$$$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last. The red stripe was painted after the blue one, so the answer is R.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 4000$$$)Β β the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either 'R', 'B', or '.', denoting a red square, a blue square, and an unpainted square, respectively. It is guaranteed that the given field is obtained from a colorless one by drawing horizontal red rows and vertical blue columns. At least one stripe is painted.
Output Specification: For each test case, output 'R' if a red stripe was painted last, and 'B' if a blue stripe was painted last (without quotes).
Notes: NoteThe first test case is pictured in the statement.In the second test case, the first blue column is painted first, then the first and last red rows, and finally the last blue column. Since a blue stripe is painted last, the answer is B.
Code:
t=int(input())
for p in range(t):
l=[]
c=0
a=['R','R','R','R','R','R','R','R']
while(len(l)<8):
s=input()
if len(s)==8:
l.append([*s])
for i in range(8):
if l[i]==a:
# TODO: Your code here
print("B" if c!=1 else "R")
|
t=int(input())
for p in range(t):
l=[]
c=0
a=['R','R','R','R','R','R','R','R']
while(len(l)<8):
s=input()
if len(s)==8:
l.append([*s])
for i in range(8):
if l[i]==a:
{{completion}}
print("B" if c!=1 else "R")
|
c=1
break
|
[{"input": "4\n\n\n\n\n....B...\n\n....B...\n\n....B...\n\nRRRRRRRR\n\n....B...\n\n....B...\n\n....B...\n\n....B...\n\n\n\n\nRRRRRRRB\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nRRRRRRRB\n\n\n\n\nRRRRRRBB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\n\n\n\n........\n\n........\n\n........\n\nRRRRRRRR\n\n........\n\n........\n\n........\n\n........", "output": ["R\nB\nB\nR"]}]
|
block_completion_005802
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: On an $$$8 \times 8$$$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last. The red stripe was painted after the blue one, so the answer is R.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 4000$$$)Β β the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either 'R', 'B', or '.', denoting a red square, a blue square, and an unpainted square, respectively. It is guaranteed that the given field is obtained from a colorless one by drawing horizontal red rows and vertical blue columns. At least one stripe is painted.
Output Specification: For each test case, output 'R' if a red stripe was painted last, and 'B' if a blue stripe was painted last (without quotes).
Notes: NoteThe first test case is pictured in the statement.In the second test case, the first blue column is painted first, then the first and last red rows, and finally the last blue column. Since a blue stripe is painted last, the answer is B.
Code:
for _ in range(int(input())):
l=[]
ans="B"
while len(l)!=8:
l.append(input())
if len(l[-1])<8:
# TODO: Your code here
for row in l:
if row.count('R')==8:
ans='R'
break
print(ans)
|
for _ in range(int(input())):
l=[]
ans="B"
while len(l)!=8:
l.append(input())
if len(l[-1])<8:
{{completion}}
for row in l:
if row.count('R')==8:
ans='R'
break
print(ans)
|
l.pop()
|
[{"input": "4\n\n\n\n\n....B...\n\n....B...\n\n....B...\n\nRRRRRRRR\n\n....B...\n\n....B...\n\n....B...\n\n....B...\n\n\n\n\nRRRRRRRB\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nRRRRRRRB\n\n\n\n\nRRRRRRBB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\n\n\n\n........\n\n........\n\n........\n\nRRRRRRRR\n\n........\n\n........\n\n........\n\n........", "output": ["R\nB\nB\nR"]}]
|
block_completion_005803
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: On an $$$8 \times 8$$$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last. The red stripe was painted after the blue one, so the answer is R.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 4000$$$)Β β the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either 'R', 'B', or '.', denoting a red square, a blue square, and an unpainted square, respectively. It is guaranteed that the given field is obtained from a colorless one by drawing horizontal red rows and vertical blue columns. At least one stripe is painted.
Output Specification: For each test case, output 'R' if a red stripe was painted last, and 'B' if a blue stripe was painted last (without quotes).
Notes: NoteThe first test case is pictured in the statement.In the second test case, the first blue column is painted first, then the first and last red rows, and finally the last blue column. Since a blue stripe is painted last, the answer is B.
Code:
for _ in range(int(input())):
l=[]
ans="B"
while len(l)!=8:
l.append(input())
if len(l[-1])<8:
l.pop()
for row in l:
if row.count('R')==8:
# TODO: Your code here
print(ans)
|
for _ in range(int(input())):
l=[]
ans="B"
while len(l)!=8:
l.append(input())
if len(l[-1])<8:
l.pop()
for row in l:
if row.count('R')==8:
{{completion}}
print(ans)
|
ans='R'
break
|
[{"input": "4\n\n\n\n\n....B...\n\n....B...\n\n....B...\n\nRRRRRRRR\n\n....B...\n\n....B...\n\n....B...\n\n....B...\n\n\n\n\nRRRRRRRB\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nRRRRRRRB\n\n\n\n\nRRRRRRBB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\n\n\n\n........\n\n........\n\n........\n\nRRRRRRRR\n\n........\n\n........\n\n........\n\n........", "output": ["R\nB\nB\nR"]}]
|
block_completion_005804
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: On an $$$8 \times 8$$$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last. The red stripe was painted after the blue one, so the answer is R.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 4000$$$)Β β the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either 'R', 'B', or '.', denoting a red square, a blue square, and an unpainted square, respectively. It is guaranteed that the given field is obtained from a colorless one by drawing horizontal red rows and vertical blue columns. At least one stripe is painted.
Output Specification: For each test case, output 'R' if a red stripe was painted last, and 'B' if a blue stripe was painted last (without quotes).
Notes: NoteThe first test case is pictured in the statement.In the second test case, the first blue column is painted first, then the first and last red rows, and finally the last blue column. Since a blue stripe is painted last, the answer is B.
Code:
from sys import stdin
n = int(input())
lines = stdin.read().split()
a = 0
for ele in range(n):
for i in range(8):
if lines[i+a].count('R') == 8:
# TODO: Your code here
else:
print('B')
a+=8
|
from sys import stdin
n = int(input())
lines = stdin.read().split()
a = 0
for ele in range(n):
for i in range(8):
if lines[i+a].count('R') == 8:
{{completion}}
else:
print('B')
a+=8
|
print('R')
break
|
[{"input": "4\n\n\n\n\n....B...\n\n....B...\n\n....B...\n\nRRRRRRRR\n\n....B...\n\n....B...\n\n....B...\n\n....B...\n\n\n\n\nRRRRRRRB\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nRRRRRRRB\n\n\n\n\nRRRRRRBB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\n\n\n\n........\n\n........\n\n........\n\nRRRRRRRR\n\n........\n\n........\n\n........\n\n........", "output": ["R\nB\nB\nR"]}]
|
block_completion_005805
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: On an $$$8 \times 8$$$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last. The red stripe was painted after the blue one, so the answer is R.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 4000$$$)Β β the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either 'R', 'B', or '.', denoting a red square, a blue square, and an unpainted square, respectively. It is guaranteed that the given field is obtained from a colorless one by drawing horizontal red rows and vertical blue columns. At least one stripe is painted.
Output Specification: For each test case, output 'R' if a red stripe was painted last, and 'B' if a blue stripe was painted last (without quotes).
Notes: NoteThe first test case is pictured in the statement.In the second test case, the first blue column is painted first, then the first and last red rows, and finally the last blue column. Since a blue stripe is painted last, the answer is B.
Code:
for _ in range(int(input())):
met = []
res = []
judge = True
i = 0
while i < 8:
tmp = input()
met.append(tmp)
if tmp != '':
# TODO: Your code here
if tmp == "R" * 8 and judge:
print("R")
judge = False
if judge:
print("B")
# for i in met:
# print(i)
|
for _ in range(int(input())):
met = []
res = []
judge = True
i = 0
while i < 8:
tmp = input()
met.append(tmp)
if tmp != '':
{{completion}}
if tmp == "R" * 8 and judge:
print("R")
judge = False
if judge:
print("B")
# for i in met:
# print(i)
|
i += 1
|
[{"input": "4\n\n\n\n\n....B...\n\n....B...\n\n....B...\n\nRRRRRRRR\n\n....B...\n\n....B...\n\n....B...\n\n....B...\n\n\n\n\nRRRRRRRB\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nRRRRRRRB\n\n\n\n\nRRRRRRBB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\n\n\n\n........\n\n........\n\n........\n\nRRRRRRRR\n\n........\n\n........\n\n........\n\n........", "output": ["R\nB\nB\nR"]}]
|
block_completion_005806
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: On an $$$8 \times 8$$$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last. The red stripe was painted after the blue one, so the answer is R.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 4000$$$)Β β the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either 'R', 'B', or '.', denoting a red square, a blue square, and an unpainted square, respectively. It is guaranteed that the given field is obtained from a colorless one by drawing horizontal red rows and vertical blue columns. At least one stripe is painted.
Output Specification: For each test case, output 'R' if a red stripe was painted last, and 'B' if a blue stripe was painted last (without quotes).
Notes: NoteThe first test case is pictured in the statement.In the second test case, the first blue column is painted first, then the first and last red rows, and finally the last blue column. Since a blue stripe is painted last, the answer is B.
Code:
for _ in range(int(input())):
met = []
res = []
judge = True
i = 0
while i < 8:
tmp = input()
met.append(tmp)
if tmp != '':
i += 1
if tmp == "R" * 8 and judge:
# TODO: Your code here
if judge:
print("B")
# for i in met:
# print(i)
|
for _ in range(int(input())):
met = []
res = []
judge = True
i = 0
while i < 8:
tmp = input()
met.append(tmp)
if tmp != '':
i += 1
if tmp == "R" * 8 and judge:
{{completion}}
if judge:
print("B")
# for i in met:
# print(i)
|
print("R")
judge = False
|
[{"input": "4\n\n\n\n\n....B...\n\n....B...\n\n....B...\n\nRRRRRRRR\n\n....B...\n\n....B...\n\n....B...\n\n....B...\n\n\n\n\nRRRRRRRB\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nRRRRRRRB\n\n\n\n\nRRRRRRBB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\n\n\n\n........\n\n........\n\n........\n\nRRRRRRRR\n\n........\n\n........\n\n........\n\n........", "output": ["R\nB\nB\nR"]}]
|
block_completion_005807
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: On an $$$8 \times 8$$$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last. The red stripe was painted after the blue one, so the answer is R.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 4000$$$)Β β the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either 'R', 'B', or '.', denoting a red square, a blue square, and an unpainted square, respectively. It is guaranteed that the given field is obtained from a colorless one by drawing horizontal red rows and vertical blue columns. At least one stripe is painted.
Output Specification: For each test case, output 'R' if a red stripe was painted last, and 'B' if a blue stripe was painted last (without quotes).
Notes: NoteThe first test case is pictured in the statement.In the second test case, the first blue column is painted first, then the first and last red rows, and finally the last blue column. Since a blue stripe is painted last, the answer is B.
Code:
n = int(input())
for i in range(n) :
b = []
j = 0
while(j<8) :
a = input()
if(a != '') :
b.append(a)
j += 1
key = 0
for j in range(8) :
ok = True
for k in range(8) :
if(b[j][k] != 'R') :
# TODO: Your code here
if(ok) :
key = 1
print("R")
break
if(not key) :
print("B")
|
n = int(input())
for i in range(n) :
b = []
j = 0
while(j<8) :
a = input()
if(a != '') :
b.append(a)
j += 1
key = 0
for j in range(8) :
ok = True
for k in range(8) :
if(b[j][k] != 'R') :
{{completion}}
if(ok) :
key = 1
print("R")
break
if(not key) :
print("B")
|
ok = False
|
[{"input": "4\n\n\n\n\n....B...\n\n....B...\n\n....B...\n\nRRRRRRRR\n\n....B...\n\n....B...\n\n....B...\n\n....B...\n\n\n\n\nRRRRRRRB\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nRRRRRRRB\n\n\n\n\nRRRRRRBB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\n\n\n\n........\n\n........\n\n........\n\nRRRRRRRR\n\n........\n\n........\n\n........\n\n........", "output": ["R\nB\nB\nR"]}]
|
block_completion_005808
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: On an $$$8 \times 8$$$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last. The red stripe was painted after the blue one, so the answer is R.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 4000$$$)Β β the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either 'R', 'B', or '.', denoting a red square, a blue square, and an unpainted square, respectively. It is guaranteed that the given field is obtained from a colorless one by drawing horizontal red rows and vertical blue columns. At least one stripe is painted.
Output Specification: For each test case, output 'R' if a red stripe was painted last, and 'B' if a blue stripe was painted last (without quotes).
Notes: NoteThe first test case is pictured in the statement.In the second test case, the first blue column is painted first, then the first and last red rows, and finally the last blue column. Since a blue stripe is painted last, the answer is B.
Code:
from sys import stdin
t = int(input())
lines = stdin.read().split()
j = 0
for num in range(t):
for i in range(8):
if lines[i + j].count('R') == 8:
# TODO: Your code here
else:
print('B')
j += 8
|
from sys import stdin
t = int(input())
lines = stdin.read().split()
j = 0
for num in range(t):
for i in range(8):
if lines[i + j].count('R') == 8:
{{completion}}
else:
print('B')
j += 8
|
print('R')
break
|
[{"input": "4\n\n\n\n\n....B...\n\n....B...\n\n....B...\n\nRRRRRRRR\n\n....B...\n\n....B...\n\n....B...\n\n....B...\n\n\n\n\nRRRRRRRB\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nRRRRRRRB\n\n\n\n\nRRRRRRBB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\n\n\n\n........\n\n........\n\n........\n\nRRRRRRRR\n\n........\n\n........\n\n........\n\n........", "output": ["R\nB\nB\nR"]}]
|
block_completion_005809
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: On an $$$8 \times 8$$$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last. The red stripe was painted after the blue one, so the answer is R.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 4000$$$)Β β the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either 'R', 'B', or '.', denoting a red square, a blue square, and an unpainted square, respectively. It is guaranteed that the given field is obtained from a colorless one by drawing horizontal red rows and vertical blue columns. At least one stripe is painted.
Output Specification: For each test case, output 'R' if a red stripe was painted last, and 'B' if a blue stripe was painted last (without quotes).
Notes: NoteThe first test case is pictured in the statement.In the second test case, the first blue column is painted first, then the first and last red rows, and finally the last blue column. Since a blue stripe is painted last, the answer is B.
Code:
t = int(input())
for _ in range(t):
count = 0
grid = []
while count < 8:
n = input()
if len(n) != 0:
count+=1
grid.append(n)
ans = False
for i in range(8):
x = False
for j in range(8):
if grid[i][j]!='R':
# TODO: Your code here
if not x:
print('R')
ans = True
break
if not ans:
print('B')
|
t = int(input())
for _ in range(t):
count = 0
grid = []
while count < 8:
n = input()
if len(n) != 0:
count+=1
grid.append(n)
ans = False
for i in range(8):
x = False
for j in range(8):
if grid[i][j]!='R':
{{completion}}
if not x:
print('R')
ans = True
break
if not ans:
print('B')
|
x = True
|
[{"input": "4\n\n\n\n\n....B...\n\n....B...\n\n....B...\n\nRRRRRRRR\n\n....B...\n\n....B...\n\n....B...\n\n....B...\n\n\n\n\nRRRRRRRB\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nRRRRRRRB\n\n\n\n\nRRRRRRBB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\n\n\n\n........\n\n........\n\n........\n\nRRRRRRRR\n\n........\n\n........\n\n........\n\n........", "output": ["R\nB\nB\nR"]}]
|
block_completion_005810
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: On an $$$8 \times 8$$$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last. The red stripe was painted after the blue one, so the answer is R.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 4000$$$)Β β the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either 'R', 'B', or '.', denoting a red square, a blue square, and an unpainted square, respectively. It is guaranteed that the given field is obtained from a colorless one by drawing horizontal red rows and vertical blue columns. At least one stripe is painted.
Output Specification: For each test case, output 'R' if a red stripe was painted last, and 'B' if a blue stripe was painted last (without quotes).
Notes: NoteThe first test case is pictured in the statement.In the second test case, the first blue column is painted first, then the first and last red rows, and finally the last blue column. Since a blue stripe is painted last, the answer is B.
Code:
n = int(input())
for i in range(n) :
b = []
j = 0
key = '.'
while(j<8) :
a = input()
if(a != '') :
# TODO: Your code here
for j in range(8) :
if(len(set(b[j])) == 1 and b[j][0] == 'R') :
key = 'R'
break
if(key!= 'R') :
key = 'B'
print(key)
|
n = int(input())
for i in range(n) :
b = []
j = 0
key = '.'
while(j<8) :
a = input()
if(a != '') :
{{completion}}
for j in range(8) :
if(len(set(b[j])) == 1 and b[j][0] == 'R') :
key = 'R'
break
if(key!= 'R') :
key = 'B'
print(key)
|
b.append(a)
j += 1
|
[{"input": "4\n\n\n\n\n....B...\n\n....B...\n\n....B...\n\nRRRRRRRR\n\n....B...\n\n....B...\n\n....B...\n\n....B...\n\n\n\n\nRRRRRRRB\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nRRRRRRRB\n\n\n\n\nRRRRRRBB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\n\n\n\n........\n\n........\n\n........\n\nRRRRRRRR\n\n........\n\n........\n\n........\n\n........", "output": ["R\nB\nB\nR"]}]
|
block_completion_005811
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: On an $$$8 \times 8$$$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last. The red stripe was painted after the blue one, so the answer is R.
Input Specification: The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 4000$$$)Β β the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either 'R', 'B', or '.', denoting a red square, a blue square, and an unpainted square, respectively. It is guaranteed that the given field is obtained from a colorless one by drawing horizontal red rows and vertical blue columns. At least one stripe is painted.
Output Specification: For each test case, output 'R' if a red stripe was painted last, and 'B' if a blue stripe was painted last (without quotes).
Notes: NoteThe first test case is pictured in the statement.In the second test case, the first blue column is painted first, then the first and last red rows, and finally the last blue column. Since a blue stripe is painted last, the answer is B.
Code:
n = int(input())
for i in range(n) :
b = []
j = 0
key = '.'
while(j<8) :
a = input()
if(a != '') :
b.append(a)
j += 1
for j in range(8) :
if(len(set(b[j])) == 1 and b[j][0] == 'R') :
# TODO: Your code here
if(key!= 'R') :
key = 'B'
print(key)
|
n = int(input())
for i in range(n) :
b = []
j = 0
key = '.'
while(j<8) :
a = input()
if(a != '') :
b.append(a)
j += 1
for j in range(8) :
if(len(set(b[j])) == 1 and b[j][0] == 'R') :
{{completion}}
if(key!= 'R') :
key = 'B'
print(key)
|
key = 'R'
break
|
[{"input": "4\n\n\n\n\n....B...\n\n....B...\n\n....B...\n\nRRRRRRRR\n\n....B...\n\n....B...\n\n....B...\n\n....B...\n\n\n\n\nRRRRRRRB\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nB......B\n\nRRRRRRRB\n\n\n\n\nRRRRRRBB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\nRRRRRRBB\n\n.B.B..BB\n\n.B.B..BB\n\n\n\n\n........\n\n........\n\n........\n\nRRRRRRRR\n\n........\n\n........\n\n........\n\n........", "output": ["R\nB\nB\nR"]}]
|
block_completion_005812
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Mark has just purchased a rack of $$$n$$$ lightbulbs. The state of the lightbulbs can be described with binary string $$$s = s_1s_2\dots s_n$$$, where $$$s_i=\texttt{1}$$$ means that the $$$i$$$-th lightbulb is turned on, while $$$s_i=\texttt{0}$$$ means that the $$$i$$$-th lightbulb is turned off.Unfortunately, the lightbulbs are broken, and the only operation he can perform to change the state of the lightbulbs is the following: Select an index $$$i$$$ from $$$2,3,\dots,n-1$$$ such that $$$s_{i-1}\ne s_{i+1}$$$. Toggle $$$s_i$$$. Namely, if $$$s_i$$$ is $$$\texttt{0}$$$, set $$$s_i$$$ to $$$\texttt{1}$$$ or vice versa. Mark wants the state of the lightbulbs to be another binary string $$$t$$$. Help Mark determine the minimum number of operations to do so.
Input Specification: The first line of the input contains a single integer $$$q$$$ ($$$1\leq q\leq 10^4$$$) β the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$3\leq n\leq 2\cdot 10^5$$$) β the number of lightbulbs. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$ β the initial state of the lightbulbs. The third line of each test case contains a binary string $$$t$$$ of length $$$n$$$ β the final state of the lightbulbs. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$2\cdot 10^5$$$.
Output Specification: For each test case, print a line containing the minimum number of operations Mark needs to perform to transform $$$s$$$ to $$$t$$$. If there is no such sequence of operations, print $$$-1$$$.
Notes: NoteIn the first test case, one sequence of operations that achieves the minimum number of operations is the following. Select $$$i=3$$$, changing $$$\texttt{01}\color{red}{\texttt{0}}\texttt{0}$$$ to $$$\texttt{01}\color{red}{\texttt{1}}\texttt{0}$$$. Select $$$i=2$$$, changing $$$\texttt{0}\color{red}{\texttt{1}}\texttt{10}$$$ to $$$\texttt{0}\color{red}{\texttt{0}}\texttt{10}$$$. In the second test case, there is no sequence of operations because one cannot change the first digit or the last digit of $$$s$$$.In the third test case, even though the first digits of $$$s$$$ and $$$t$$$ are the same and the last digits of $$$s$$$ and $$$t$$$ are the same, it can be shown that there is no sequence of operations that satisfies the condition.In the fourth test case, one sequence that achieves the minimum number of operations is the following: Select $$$i=3$$$, changing $$$\texttt{00}\color{red}{\texttt{0}}\texttt{101}$$$ to $$$\texttt{00}\color{red}{\texttt{1}}\texttt{101}$$$. Select $$$i=2$$$, changing $$$\texttt{0}\color{red}{\texttt{0}}\texttt{1101}$$$ to $$$\texttt{0}\color{red}{\texttt{1}}\texttt{1101}$$$. Select $$$i=4$$$, changing $$$\texttt{011}\color{red}{\texttt{1}}\texttt{01}$$$ to $$$\texttt{011}\color{red}{\texttt{0}}\texttt{01}$$$. Select $$$i=5$$$, changing $$$\texttt{0110}\color{red}{\texttt{0}}\texttt{1}$$$ to $$$\texttt{0110}\color{red}{\texttt{1}}\texttt{1}$$$. Select $$$i=3$$$, changing $$$\texttt{01}\color{red}{\texttt{1}}\texttt{011}$$$ to $$$\texttt{01}\color{red}{\texttt{0}}\texttt{011}$$$.
Code:
import sys
inp = sys.stdin.read().split()[::-1]
out = []
def compress(s):
lst = None
ret = []
for c in s:
if lst != c:
# TODO: Your code here
ret[-1] += 1
return ret
def transform(lns):
st = []
s = 0
for l in lns:
st.append(s)
s += l
return st
def tc(n, txt, patt):
if txt == patt:
out.append(0)
return
if txt[0] != patt[0] or txt[-1] != patt[-1]:
out.append(-1)
return
A = compress(txt)
B = compress(patt)
if len(A) != len(B):
out.append(-1)
return
A = transform(A)
B = transform(B)
ans = 0
for a, b in zip(A, B):
ans += abs(a - b)
out.append(ans)
for _ in range(int(inp.pop())):
n = int(inp.pop())
txt = inp.pop()
patt = inp.pop()
tc(n, txt, patt)
print('\n'.join(map(str, out)))
|
import sys
inp = sys.stdin.read().split()[::-1]
out = []
def compress(s):
lst = None
ret = []
for c in s:
if lst != c:
{{completion}}
ret[-1] += 1
return ret
def transform(lns):
st = []
s = 0
for l in lns:
st.append(s)
s += l
return st
def tc(n, txt, patt):
if txt == patt:
out.append(0)
return
if txt[0] != patt[0] or txt[-1] != patt[-1]:
out.append(-1)
return
A = compress(txt)
B = compress(patt)
if len(A) != len(B):
out.append(-1)
return
A = transform(A)
B = transform(B)
ans = 0
for a, b in zip(A, B):
ans += abs(a - b)
out.append(ans)
for _ in range(int(inp.pop())):
n = int(inp.pop())
txt = inp.pop()
patt = inp.pop()
tc(n, txt, patt)
print('\n'.join(map(str, out)))
|
ret.append(0)
lst = c
|
[{"input": "4\n\n4\n\n0100\n\n0010\n\n4\n\n1010\n\n0100\n\n5\n\n01001\n\n00011\n\n6\n\n000101\n\n010011", "output": ["2\n-1\n-1\n5"]}]
|
block_completion_005866
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: After watching a certain anime before going to sleep, Mark dreams of standing in an old classroom with a blackboard that has a sequence of $$$n$$$ positive integers $$$a_1, a_2,\dots,a_n$$$ on it.Then, professor Koro comes in. He can perform the following operation: select an integer $$$x$$$ that appears at least $$$2$$$ times on the board, erase those $$$2$$$ appearances, and write $$$x+1$$$ on the board. Professor Koro then asks Mark the question, "what is the maximum possible number that could appear on the board after some operations?"Mark quickly solves this question, but he is still slower than professor Koro. Thus, professor Koro decides to give Mark additional challenges. He will update the initial sequence of integers $$$q$$$ times. Each time, he will choose positive integers $$$k$$$ and $$$l$$$, then change $$$a_k$$$ to $$$l$$$. After each update, he will ask Mark the same question again.Help Mark answer these questions faster than Professor Koro!Note that the updates are persistent. Changes made to the sequence $$$a$$$ will apply when processing future updates.
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$2\leq n\leq 2\cdot 10^5$$$, $$$1\leq q\leq 2\cdot 10^5$$$) β the length of the sequence $$$a$$$ and the number of updates, respectively. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$1\leq a_i\leq 2\cdot 10^5$$$) Then, $$$q$$$ lines follow, each consisting of two integers $$$k$$$ and $$$l$$$ ($$$1\leq k\leq n$$$, $$$1\leq l\leq 2\cdot 10^5$$$), telling to update $$$a_k$$$ to $$$l$$$.
Output Specification: Print $$$q$$$ lines. The $$$i$$$-th line should consist of a single integer β the answer after the $$$i$$$-th update.
Notes: NoteIn the first example test, the program must proceed through $$$4$$$ updates.The sequence after the first update is $$$[2,3,2,4,5]$$$. One sequence of operations that achieves the number $$$6$$$ the following. Initially, the blackboard has numbers $$$[2,3,2,4,5]$$$. Erase two copies of $$$2$$$ and write $$$3$$$, yielding $$$[3,4,5,\color{red}{3}]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[4,5,\color{red}{4}]$$$. Erase two copies of $$$4$$$ and write $$$5$$$, yielding $$$[5,\color{red}{5}]$$$. Erase two copies of $$$5$$$ and write $$$6$$$, yielding $$$[\color{red}{6}]$$$. Then, in the second update, the array is changed to $$$[2,3,2,4,3]$$$. This time, Mark cannot achieve $$$6$$$. However, one sequence that Mark can use to achieve $$$5$$$ is shown below. Initially, the blackboard has $$$[2,3,2,4,3]$$$. Erase two copies of $$$2$$$ and write $$$3$$$, yielding $$$[3,4,3,\color{red}{3}]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[3,4,\color{red}{4}]$$$. Erase two copies of $$$4$$$ and write $$$5$$$, yielding $$$[3,\color{red}{5}]$$$. In the third update, the array is changed to $$$[2,3,2,1,3]$$$. One way to achieve $$$4$$$ is shown below. Initially, the blackboard has $$$[2,3,2,1,3]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[2,2,1,\color{red}{4}]$$$.
Code:
import sys
import os
from io import BytesIO, IOBase
# 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")
if sys.version_info[0] < 3:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
file = sys.stdin
if os.environ.get('USER') == "loic":
file = open("data.in")
line = lambda: file.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
class BitSet:
ADDRESS_BITS_PER_WORD = 6
BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD
WORD_MASK = -1
def __init__(self, sz):
self.sz = sz
self.words = [0] * (self._wordIndex(sz - 1) + 1)
def _wordIndex(self, bitIndex):
if bitIndex >= self.sz:
raise ValueError("out of bound index", bitIndex)
return bitIndex >> BitSet.ADDRESS_BITS_PER_WORD
def flip(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
self.words[wordIndex] ^= 1 << (bitIndex % BitSet.BITS_PER_WORD)
def flip_range(self, l, r):
startWordIndex = self._wordIndex(l)
endWordIndex = self._wordIndex(r)
firstWordMask = BitSet.WORD_MASK << (l % BitSet.BITS_PER_WORD)
rem = (r+1) % BitSet.BITS_PER_WORD
lastWordMask = BitSet.WORD_MASK if rem == 0 else ~(BitSet.WORD_MASK << rem)
if startWordIndex == endWordIndex:
self.words[startWordIndex] ^= (firstWordMask & lastWordMask)
else:
self.words[startWordIndex] ^= firstWordMask
for i in range(startWordIndex + 1, endWordIndex):
self.words[i] ^= BitSet.WORD_MASK
self.words[endWordIndex] ^= lastWordMask
def __setitem__(self, bitIndex, value):
wordIndex = self._wordIndex(bitIndex)
if value:
self.words[wordIndex] |= 1 << (bitIndex % BitSet.BITS_PER_WORD)
else:
self.words[wordIndex] &= ~(1 << (bitIndex % BitSet.BITS_PER_WORD))
def __getitem__(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
return self.words[wordIndex] & (1 << (bitIndex % BitSet.BITS_PER_WORD)) != 0
def nextSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & (BitSet.WORD_MASK << (fromIndex % BitSet.BITS_PER_WORD))
while True:
if word != 0:
return wordIndex * BitSet.BITS_PER_WORD + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return -1
word = self.words[wordIndex]
def nextClearBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = ~self.words[wordIndex] & (BitSet.WORD_MASK << (fromIndex % BitSet.BITS_PER_WORD))
while True:
if word != 0:
index = wordIndex * BitSet.BITS_PER_WORD + (word & -word).bit_length() - 1
return index if index < self.sz else - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return -1
word = ~self.words[wordIndex]
def lastSetBit(self):
wordIndex = len(self.words) - 1
word = self.words[wordIndex]
while wordIndex >= 0:
if word != 0:
return wordIndex * BitSet.BITS_PER_WORD + (word.bit_length() - 1 if word > 0 else BitSet.BITS_PER_WORD - 1)
wordIndex -= 1
word = self.words[wordIndex]
return -1
def __str__(self):
res = []
st = 0
while True:
i = self.nextSetBit(st)
if i != -1:
res += [0] * (i - st)
j = self.nextClearBit(i)
if j != -1:
res += [1] * (j-i)
st = j
else:
# TODO: Your code here
else:
res += [0] * (self.sz - st)
break
return "".join(str(v) for v in res)
def __repr__(self):
return "Bitset(%s)" % str(self)
def __iter__(self):
for i in self[:]:
yield i
def __len__(self):
return self.sz
def add(bs,val):
bs.flip_range(val, bs.nextClearBit(val))
def rem(bs,val):
bs.flip_range(val, bs.nextSetBit(val))
def solve():
res = []
bs = BitSet(Z)
for val in A:
add(bs,val)
for _ in range(Q):
idx, val = ti()
idx -= 1
rem(bs,A[idx])
A[idx] = val
add(bs,val)
res.append(bs.lastSetBit())
return "\n".join(str(v) for v in res)
Z = 200030
for test in range(1,1+1):
N,Q = ti()
A = li()
print(solve())
file.close()
|
import sys
import os
from io import BytesIO, IOBase
# 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")
if sys.version_info[0] < 3:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
file = sys.stdin
if os.environ.get('USER') == "loic":
file = open("data.in")
line = lambda: file.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
class BitSet:
ADDRESS_BITS_PER_WORD = 6
BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD
WORD_MASK = -1
def __init__(self, sz):
self.sz = sz
self.words = [0] * (self._wordIndex(sz - 1) + 1)
def _wordIndex(self, bitIndex):
if bitIndex >= self.sz:
raise ValueError("out of bound index", bitIndex)
return bitIndex >> BitSet.ADDRESS_BITS_PER_WORD
def flip(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
self.words[wordIndex] ^= 1 << (bitIndex % BitSet.BITS_PER_WORD)
def flip_range(self, l, r):
startWordIndex = self._wordIndex(l)
endWordIndex = self._wordIndex(r)
firstWordMask = BitSet.WORD_MASK << (l % BitSet.BITS_PER_WORD)
rem = (r+1) % BitSet.BITS_PER_WORD
lastWordMask = BitSet.WORD_MASK if rem == 0 else ~(BitSet.WORD_MASK << rem)
if startWordIndex == endWordIndex:
self.words[startWordIndex] ^= (firstWordMask & lastWordMask)
else:
self.words[startWordIndex] ^= firstWordMask
for i in range(startWordIndex + 1, endWordIndex):
self.words[i] ^= BitSet.WORD_MASK
self.words[endWordIndex] ^= lastWordMask
def __setitem__(self, bitIndex, value):
wordIndex = self._wordIndex(bitIndex)
if value:
self.words[wordIndex] |= 1 << (bitIndex % BitSet.BITS_PER_WORD)
else:
self.words[wordIndex] &= ~(1 << (bitIndex % BitSet.BITS_PER_WORD))
def __getitem__(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
return self.words[wordIndex] & (1 << (bitIndex % BitSet.BITS_PER_WORD)) != 0
def nextSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & (BitSet.WORD_MASK << (fromIndex % BitSet.BITS_PER_WORD))
while True:
if word != 0:
return wordIndex * BitSet.BITS_PER_WORD + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return -1
word = self.words[wordIndex]
def nextClearBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = ~self.words[wordIndex] & (BitSet.WORD_MASK << (fromIndex % BitSet.BITS_PER_WORD))
while True:
if word != 0:
index = wordIndex * BitSet.BITS_PER_WORD + (word & -word).bit_length() - 1
return index if index < self.sz else - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return -1
word = ~self.words[wordIndex]
def lastSetBit(self):
wordIndex = len(self.words) - 1
word = self.words[wordIndex]
while wordIndex >= 0:
if word != 0:
return wordIndex * BitSet.BITS_PER_WORD + (word.bit_length() - 1 if word > 0 else BitSet.BITS_PER_WORD - 1)
wordIndex -= 1
word = self.words[wordIndex]
return -1
def __str__(self):
res = []
st = 0
while True:
i = self.nextSetBit(st)
if i != -1:
res += [0] * (i - st)
j = self.nextClearBit(i)
if j != -1:
res += [1] * (j-i)
st = j
else:
{{completion}}
else:
res += [0] * (self.sz - st)
break
return "".join(str(v) for v in res)
def __repr__(self):
return "Bitset(%s)" % str(self)
def __iter__(self):
for i in self[:]:
yield i
def __len__(self):
return self.sz
def add(bs,val):
bs.flip_range(val, bs.nextClearBit(val))
def rem(bs,val):
bs.flip_range(val, bs.nextSetBit(val))
def solve():
res = []
bs = BitSet(Z)
for val in A:
add(bs,val)
for _ in range(Q):
idx, val = ti()
idx -= 1
rem(bs,A[idx])
A[idx] = val
add(bs,val)
res.append(bs.lastSetBit())
return "\n".join(str(v) for v in res)
Z = 200030
for test in range(1,1+1):
N,Q = ti()
A = li()
print(solve())
file.close()
|
res += [1] * (self.sz - i)
break
|
[{"input": "5 4\n2 2 2 4 5\n2 3\n5 3\n4 1\n1 4", "output": ["6\n5\n4\n5"]}, {"input": "2 1\n200000 1\n2 200000", "output": ["200001"]}]
|
block_completion_005931
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: After watching a certain anime before going to sleep, Mark dreams of standing in an old classroom with a blackboard that has a sequence of $$$n$$$ positive integers $$$a_1, a_2,\dots,a_n$$$ on it.Then, professor Koro comes in. He can perform the following operation: select an integer $$$x$$$ that appears at least $$$2$$$ times on the board, erase those $$$2$$$ appearances, and write $$$x+1$$$ on the board. Professor Koro then asks Mark the question, "what is the maximum possible number that could appear on the board after some operations?"Mark quickly solves this question, but he is still slower than professor Koro. Thus, professor Koro decides to give Mark additional challenges. He will update the initial sequence of integers $$$q$$$ times. Each time, he will choose positive integers $$$k$$$ and $$$l$$$, then change $$$a_k$$$ to $$$l$$$. After each update, he will ask Mark the same question again.Help Mark answer these questions faster than Professor Koro!Note that the updates are persistent. Changes made to the sequence $$$a$$$ will apply when processing future updates.
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$2\leq n\leq 2\cdot 10^5$$$, $$$1\leq q\leq 2\cdot 10^5$$$) β the length of the sequence $$$a$$$ and the number of updates, respectively. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$1\leq a_i\leq 2\cdot 10^5$$$) Then, $$$q$$$ lines follow, each consisting of two integers $$$k$$$ and $$$l$$$ ($$$1\leq k\leq n$$$, $$$1\leq l\leq 2\cdot 10^5$$$), telling to update $$$a_k$$$ to $$$l$$$.
Output Specification: Print $$$q$$$ lines. The $$$i$$$-th line should consist of a single integer β the answer after the $$$i$$$-th update.
Notes: NoteIn the first example test, the program must proceed through $$$4$$$ updates.The sequence after the first update is $$$[2,3,2,4,5]$$$. One sequence of operations that achieves the number $$$6$$$ the following. Initially, the blackboard has numbers $$$[2,3,2,4,5]$$$. Erase two copies of $$$2$$$ and write $$$3$$$, yielding $$$[3,4,5,\color{red}{3}]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[4,5,\color{red}{4}]$$$. Erase two copies of $$$4$$$ and write $$$5$$$, yielding $$$[5,\color{red}{5}]$$$. Erase two copies of $$$5$$$ and write $$$6$$$, yielding $$$[\color{red}{6}]$$$. Then, in the second update, the array is changed to $$$[2,3,2,4,3]$$$. This time, Mark cannot achieve $$$6$$$. However, one sequence that Mark can use to achieve $$$5$$$ is shown below. Initially, the blackboard has $$$[2,3,2,4,3]$$$. Erase two copies of $$$2$$$ and write $$$3$$$, yielding $$$[3,4,3,\color{red}{3}]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[3,4,\color{red}{4}]$$$. Erase two copies of $$$4$$$ and write $$$5$$$, yielding $$$[3,\color{red}{5}]$$$. In the third update, the array is changed to $$$[2,3,2,1,3]$$$. One way to achieve $$$4$$$ is shown below. Initially, the blackboard has $$$[2,3,2,1,3]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[2,2,1,\color{red}{4}]$$$.
Code:
import sys
import os
from io import BytesIO, IOBase
# 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")
if sys.version_info[0] < 3:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
file = sys.stdin
if os.environ.get('USER') == "loic":
file = open("data.in")
line = lambda: file.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
class BitSet:
ADDRESS_BITS_PER_WORD = 6
BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD
WORD_MASK = -1
def __init__(self, sz):
self.sz = sz
self.words = [0] * (self._wordIndex(sz - 1) + 1)
def _wordIndex(self, bitIndex):
if bitIndex >= self.sz:
raise ValueError("out of bound index", bitIndex)
return bitIndex >> BitSet.ADDRESS_BITS_PER_WORD
def flip(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
self.words[wordIndex] ^= 1 << (bitIndex % BitSet.BITS_PER_WORD)
def flip_range(self, l, r):
startWordIndex = self._wordIndex(l)
endWordIndex = self._wordIndex(r)
firstWordMask = BitSet.WORD_MASK << (l % BitSet.BITS_PER_WORD)
rem = (r+1) % BitSet.BITS_PER_WORD
lastWordMask = BitSet.WORD_MASK if rem == 0 else ~(BitSet.WORD_MASK << rem)
if startWordIndex == endWordIndex:
self.words[startWordIndex] ^= (firstWordMask & lastWordMask)
else:
self.words[startWordIndex] ^= firstWordMask
for i in range(startWordIndex + 1, endWordIndex):
self.words[i] ^= BitSet.WORD_MASK
self.words[endWordIndex] ^= lastWordMask
def __setitem__(self, bitIndex, value):
wordIndex = self._wordIndex(bitIndex)
if value:
self.words[wordIndex] |= 1 << (bitIndex % BitSet.BITS_PER_WORD)
else:
self.words[wordIndex] &= ~(1 << (bitIndex % BitSet.BITS_PER_WORD))
def __getitem__(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
return self.words[wordIndex] & (1 << (bitIndex % BitSet.BITS_PER_WORD)) != 0
def nextSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & (BitSet.WORD_MASK << (fromIndex % BitSet.BITS_PER_WORD))
while True:
if word != 0:
return wordIndex * BitSet.BITS_PER_WORD + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return -1
word = self.words[wordIndex]
def nextClearBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = ~self.words[wordIndex] & (BitSet.WORD_MASK << (fromIndex % BitSet.BITS_PER_WORD))
while True:
if word != 0:
index = wordIndex * BitSet.BITS_PER_WORD + (word & -word).bit_length() - 1
return index if index < self.sz else - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return -1
word = ~self.words[wordIndex]
def lastSetBit(self):
wordIndex = len(self.words) - 1
word = self.words[wordIndex]
while wordIndex >= 0:
if word != 0:
return wordIndex * BitSet.BITS_PER_WORD + (word.bit_length() - 1 if word > 0 else BitSet.BITS_PER_WORD - 1)
wordIndex -= 1
word = self.words[wordIndex]
return -1
def __str__(self):
res = []
st = 0
while True:
i = self.nextSetBit(st)
if i != -1:
res += [0] * (i - st)
j = self.nextClearBit(i)
if j != -1:
# TODO: Your code here
else:
res += [1] * (self.sz - i)
break
else:
res += [0] * (self.sz - st)
break
return "".join(str(v) for v in res)
def __repr__(self):
return "Bitset(%s)" % str(self)
def __iter__(self):
for i in self[:]:
yield i
def __len__(self):
return self.sz
def add(bs,val):
bs.flip_range(val, bs.nextClearBit(val))
def rem(bs,val):
bs.flip_range(val, bs.nextSetBit(val))
def solve():
res = []
bs = BitSet(Z)
for val in A:
add(bs,val)
for _ in range(Q):
idx, val = ti()
idx -= 1
rem(bs,A[idx])
A[idx] = val
add(bs,val)
res.append(bs.lastSetBit())
return "\n".join(str(v) for v in res)
Z = 200030
for test in range(1,1+1):
N,Q = ti()
A = li()
print(solve())
file.close()
|
import sys
import os
from io import BytesIO, IOBase
# 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")
if sys.version_info[0] < 3:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
file = sys.stdin
if os.environ.get('USER') == "loic":
file = open("data.in")
line = lambda: file.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
class BitSet:
ADDRESS_BITS_PER_WORD = 6
BITS_PER_WORD = 1 << ADDRESS_BITS_PER_WORD
WORD_MASK = -1
def __init__(self, sz):
self.sz = sz
self.words = [0] * (self._wordIndex(sz - 1) + 1)
def _wordIndex(self, bitIndex):
if bitIndex >= self.sz:
raise ValueError("out of bound index", bitIndex)
return bitIndex >> BitSet.ADDRESS_BITS_PER_WORD
def flip(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
self.words[wordIndex] ^= 1 << (bitIndex % BitSet.BITS_PER_WORD)
def flip_range(self, l, r):
startWordIndex = self._wordIndex(l)
endWordIndex = self._wordIndex(r)
firstWordMask = BitSet.WORD_MASK << (l % BitSet.BITS_PER_WORD)
rem = (r+1) % BitSet.BITS_PER_WORD
lastWordMask = BitSet.WORD_MASK if rem == 0 else ~(BitSet.WORD_MASK << rem)
if startWordIndex == endWordIndex:
self.words[startWordIndex] ^= (firstWordMask & lastWordMask)
else:
self.words[startWordIndex] ^= firstWordMask
for i in range(startWordIndex + 1, endWordIndex):
self.words[i] ^= BitSet.WORD_MASK
self.words[endWordIndex] ^= lastWordMask
def __setitem__(self, bitIndex, value):
wordIndex = self._wordIndex(bitIndex)
if value:
self.words[wordIndex] |= 1 << (bitIndex % BitSet.BITS_PER_WORD)
else:
self.words[wordIndex] &= ~(1 << (bitIndex % BitSet.BITS_PER_WORD))
def __getitem__(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
return self.words[wordIndex] & (1 << (bitIndex % BitSet.BITS_PER_WORD)) != 0
def nextSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & (BitSet.WORD_MASK << (fromIndex % BitSet.BITS_PER_WORD))
while True:
if word != 0:
return wordIndex * BitSet.BITS_PER_WORD + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return -1
word = self.words[wordIndex]
def nextClearBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = ~self.words[wordIndex] & (BitSet.WORD_MASK << (fromIndex % BitSet.BITS_PER_WORD))
while True:
if word != 0:
index = wordIndex * BitSet.BITS_PER_WORD + (word & -word).bit_length() - 1
return index if index < self.sz else - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return -1
word = ~self.words[wordIndex]
def lastSetBit(self):
wordIndex = len(self.words) - 1
word = self.words[wordIndex]
while wordIndex >= 0:
if word != 0:
return wordIndex * BitSet.BITS_PER_WORD + (word.bit_length() - 1 if word > 0 else BitSet.BITS_PER_WORD - 1)
wordIndex -= 1
word = self.words[wordIndex]
return -1
def __str__(self):
res = []
st = 0
while True:
i = self.nextSetBit(st)
if i != -1:
res += [0] * (i - st)
j = self.nextClearBit(i)
if j != -1:
{{completion}}
else:
res += [1] * (self.sz - i)
break
else:
res += [0] * (self.sz - st)
break
return "".join(str(v) for v in res)
def __repr__(self):
return "Bitset(%s)" % str(self)
def __iter__(self):
for i in self[:]:
yield i
def __len__(self):
return self.sz
def add(bs,val):
bs.flip_range(val, bs.nextClearBit(val))
def rem(bs,val):
bs.flip_range(val, bs.nextSetBit(val))
def solve():
res = []
bs = BitSet(Z)
for val in A:
add(bs,val)
for _ in range(Q):
idx, val = ti()
idx -= 1
rem(bs,A[idx])
A[idx] = val
add(bs,val)
res.append(bs.lastSetBit())
return "\n".join(str(v) for v in res)
Z = 200030
for test in range(1,1+1):
N,Q = ti()
A = li()
print(solve())
file.close()
|
res += [1] * (j-i)
st = j
|
[{"input": "5 4\n2 2 2 4 5\n2 3\n5 3\n4 1\n1 4", "output": ["6\n5\n4\n5"]}, {"input": "2 1\n200000 1\n2 200000", "output": ["200001"]}]
|
block_completion_005932
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: After watching a certain anime before going to sleep, Mark dreams of standing in an old classroom with a blackboard that has a sequence of $$$n$$$ positive integers $$$a_1, a_2,\dots,a_n$$$ on it.Then, professor Koro comes in. He can perform the following operation: select an integer $$$x$$$ that appears at least $$$2$$$ times on the board, erase those $$$2$$$ appearances, and write $$$x+1$$$ on the board. Professor Koro then asks Mark the question, "what is the maximum possible number that could appear on the board after some operations?"Mark quickly solves this question, but he is still slower than professor Koro. Thus, professor Koro decides to give Mark additional challenges. He will update the initial sequence of integers $$$q$$$ times. Each time, he will choose positive integers $$$k$$$ and $$$l$$$, then change $$$a_k$$$ to $$$l$$$. After each update, he will ask Mark the same question again.Help Mark answer these questions faster than Professor Koro!Note that the updates are persistent. Changes made to the sequence $$$a$$$ will apply when processing future updates.
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$2\leq n\leq 2\cdot 10^5$$$, $$$1\leq q\leq 2\cdot 10^5$$$) β the length of the sequence $$$a$$$ and the number of updates, respectively. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$1\leq a_i\leq 2\cdot 10^5$$$) Then, $$$q$$$ lines follow, each consisting of two integers $$$k$$$ and $$$l$$$ ($$$1\leq k\leq n$$$, $$$1\leq l\leq 2\cdot 10^5$$$), telling to update $$$a_k$$$ to $$$l$$$.
Output Specification: Print $$$q$$$ lines. The $$$i$$$-th line should consist of a single integer β the answer after the $$$i$$$-th update.
Notes: NoteIn the first example test, the program must proceed through $$$4$$$ updates.The sequence after the first update is $$$[2,3,2,4,5]$$$. One sequence of operations that achieves the number $$$6$$$ the following. Initially, the blackboard has numbers $$$[2,3,2,4,5]$$$. Erase two copies of $$$2$$$ and write $$$3$$$, yielding $$$[3,4,5,\color{red}{3}]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[4,5,\color{red}{4}]$$$. Erase two copies of $$$4$$$ and write $$$5$$$, yielding $$$[5,\color{red}{5}]$$$. Erase two copies of $$$5$$$ and write $$$6$$$, yielding $$$[\color{red}{6}]$$$. Then, in the second update, the array is changed to $$$[2,3,2,4,3]$$$. This time, Mark cannot achieve $$$6$$$. However, one sequence that Mark can use to achieve $$$5$$$ is shown below. Initially, the blackboard has $$$[2,3,2,4,3]$$$. Erase two copies of $$$2$$$ and write $$$3$$$, yielding $$$[3,4,3,\color{red}{3}]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[3,4,\color{red}{4}]$$$. Erase two copies of $$$4$$$ and write $$$5$$$, yielding $$$[3,\color{red}{5}]$$$. In the third update, the array is changed to $$$[2,3,2,1,3]$$$. One way to achieve $$$4$$$ is shown below. Initially, the blackboard has $$$[2,3,2,1,3]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[2,2,1,\color{red}{4}]$$$.
Code:
import sys
import os
from io import BytesIO, IOBase
# 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")
if sys.version_info[0] < 3:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
file = sys.stdin
if os.environ.get('USER') == "loic":
file = open("data.in")
line = lambda: file.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
class BitSet:
ADDRESS_BITS_PER_WORD = 6
WORD_SZ = 1 << ADDRESS_BITS_PER_WORD
MASK = -0x1
MASK_MAX = 0x7fffffffffffffff
MASK_MIN = ~MASK_MAX
def __init__(self, sz):
self.sz = sz
self.words = [0] * (self._wordIndex(sz - 1) + 1)
self.last = -1
def _wordIndex(self, bitIndex):
if bitIndex >= self.sz:
raise ValueError("out of bound index", bitIndex)
return bitIndex >> BitSet.ADDRESS_BITS_PER_WORD
def _shift_one_left(self, shift):
if shift == BitSet.WORD_SZ - 1:
return BitSet.MASK_MIN
return 1 << (shift % BitSet.WORD_SZ)
def _shift_mask_right(self, shift):
if shift == 0:
return BitSet.MASK
return BitSet.MASK_MAX >> (shift - 1)
def _shift_mask_left(self, shift):
if shift == 0:
return BitSet.MASK
return ~(BitSet.MASK_MAX >> (BitSet.WORD_SZ - shift - 1))
def flip(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
self.words[wordIndex] ^= self._shift_one_left(bitIndex % BitSet.WORD_SZ)
def flip_range(self, l, r, pos):
startWordIndex = self._wordIndex(l)
endWordIndex = self._wordIndex(r)
firstWordMask = self._shift_mask_left(l % BitSet.WORD_SZ)
lastWordMask = self._shift_mask_right(BitSet.WORD_SZ - 1 - r % BitSet.WORD_SZ)
if startWordIndex == endWordIndex:
self.words[startWordIndex] ^= (firstWordMask & lastWordMask)
else:
self.words[startWordIndex] ^= firstWordMask
for i in range(startWordIndex + 1, endWordIndex):
self.words[i] ^= BitSet.MASK
self.words[endWordIndex] ^= lastWordMask
if pos:
self.last = max(self.last, r)
elif r == self.last:
self.last = self.previousSetBit(r-1)
def __setitem__(self, bitIndex, value):
wordIndex = self._wordIndex(bitIndex)
if value:
self.words[wordIndex] |= self._shift_one_left(bitIndex % BitSet.WORD_SZ)
else:
self.words[wordIndex] &= ~self._shift_one_left(bitIndex % BitSet.WORD_SZ)
def __getitem__(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
return (self.words[wordIndex] >> (bitIndex % BitSet.WORD_SZ)) & 1
''' return len(bitset) if there is no "1" after fromIndex '''
def nextSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = self.words[wordIndex]
''' return len(bitset) if there is no "0" after fromIndex '''
def nextClearBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = ~self.words[wordIndex] & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = ~self.words[wordIndex]
''' return -1 if there is no "1" before fromIndex '''
def previousSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
rem = fromIndex % BitSet.WORD_SZ
word = self.words[wordIndex] & self._shift_mask_right(BitSet.WORD_SZ - 1 - rem)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ - 1 + (word.bit_length() if word > 0 else BitSet.WORD_SZ)
wordIndex -= 1
if wordIndex < 0:
return -1
word = self.words[wordIndex]
''' return -1 if there is no "0" before fromIndex '''
def previousClearBit(self,fromIndex):
wordIndex = self._wordIndex(fromIndex)
rem = fromIndex % BitSet.WORD_SZ
word = ~self.words[wordIndex] & self._shift_mask_right(BitSet.WORD_SZ - 1 - rem)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ - 1 + (word.bit_length() if word > 0 else BitSet.WORD_SZ)
wordIndex -= 1
if wordIndex < 0:
return -1
word = ~self.words[wordIndex]
def __str__(self):
res = []
st = 0
while True:
i = self.nextSetBit(st)
if i != self.sz:
res += [0] * (i - st)
j = self.nextClearBit(i)
if j != self.sz:
res += [1] * (j-i)
st = j
else:
# TODO: Your code here
else:
res += [0] * (self.sz - st)
break
return "".join(str(v) for v in res)
def __repr__(self):
return "Bitset(%s)" % str(self)
def __iter__(self):
for i in self[:]:
yield i
def __len__(self):
return self.sz
def add(bs,val):
bs.flip_range(val, bs.nextClearBit(val), 1)
def rem(bs,val):
bs.flip_range(val, bs.nextSetBit(val), 0)
def solve():
res = []
bs = BitSet(Z)
for val in A:
add(bs,val)
for _ in range(Q):
idx, val = ti()
idx -= 1
rem(bs,A[idx])
A[idx] = val
add(bs,val)
res.append(bs.last)
return "\n".join(str(v) for v in res)
Z = 200030
for test in range(1,1+1):
N,Q = ti()
A = li()
print(solve())
file.close()
|
import sys
import os
from io import BytesIO, IOBase
# 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")
if sys.version_info[0] < 3:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
file = sys.stdin
if os.environ.get('USER') == "loic":
file = open("data.in")
line = lambda: file.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
class BitSet:
ADDRESS_BITS_PER_WORD = 6
WORD_SZ = 1 << ADDRESS_BITS_PER_WORD
MASK = -0x1
MASK_MAX = 0x7fffffffffffffff
MASK_MIN = ~MASK_MAX
def __init__(self, sz):
self.sz = sz
self.words = [0] * (self._wordIndex(sz - 1) + 1)
self.last = -1
def _wordIndex(self, bitIndex):
if bitIndex >= self.sz:
raise ValueError("out of bound index", bitIndex)
return bitIndex >> BitSet.ADDRESS_BITS_PER_WORD
def _shift_one_left(self, shift):
if shift == BitSet.WORD_SZ - 1:
return BitSet.MASK_MIN
return 1 << (shift % BitSet.WORD_SZ)
def _shift_mask_right(self, shift):
if shift == 0:
return BitSet.MASK
return BitSet.MASK_MAX >> (shift - 1)
def _shift_mask_left(self, shift):
if shift == 0:
return BitSet.MASK
return ~(BitSet.MASK_MAX >> (BitSet.WORD_SZ - shift - 1))
def flip(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
self.words[wordIndex] ^= self._shift_one_left(bitIndex % BitSet.WORD_SZ)
def flip_range(self, l, r, pos):
startWordIndex = self._wordIndex(l)
endWordIndex = self._wordIndex(r)
firstWordMask = self._shift_mask_left(l % BitSet.WORD_SZ)
lastWordMask = self._shift_mask_right(BitSet.WORD_SZ - 1 - r % BitSet.WORD_SZ)
if startWordIndex == endWordIndex:
self.words[startWordIndex] ^= (firstWordMask & lastWordMask)
else:
self.words[startWordIndex] ^= firstWordMask
for i in range(startWordIndex + 1, endWordIndex):
self.words[i] ^= BitSet.MASK
self.words[endWordIndex] ^= lastWordMask
if pos:
self.last = max(self.last, r)
elif r == self.last:
self.last = self.previousSetBit(r-1)
def __setitem__(self, bitIndex, value):
wordIndex = self._wordIndex(bitIndex)
if value:
self.words[wordIndex] |= self._shift_one_left(bitIndex % BitSet.WORD_SZ)
else:
self.words[wordIndex] &= ~self._shift_one_left(bitIndex % BitSet.WORD_SZ)
def __getitem__(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
return (self.words[wordIndex] >> (bitIndex % BitSet.WORD_SZ)) & 1
''' return len(bitset) if there is no "1" after fromIndex '''
def nextSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = self.words[wordIndex]
''' return len(bitset) if there is no "0" after fromIndex '''
def nextClearBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = ~self.words[wordIndex] & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = ~self.words[wordIndex]
''' return -1 if there is no "1" before fromIndex '''
def previousSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
rem = fromIndex % BitSet.WORD_SZ
word = self.words[wordIndex] & self._shift_mask_right(BitSet.WORD_SZ - 1 - rem)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ - 1 + (word.bit_length() if word > 0 else BitSet.WORD_SZ)
wordIndex -= 1
if wordIndex < 0:
return -1
word = self.words[wordIndex]
''' return -1 if there is no "0" before fromIndex '''
def previousClearBit(self,fromIndex):
wordIndex = self._wordIndex(fromIndex)
rem = fromIndex % BitSet.WORD_SZ
word = ~self.words[wordIndex] & self._shift_mask_right(BitSet.WORD_SZ - 1 - rem)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ - 1 + (word.bit_length() if word > 0 else BitSet.WORD_SZ)
wordIndex -= 1
if wordIndex < 0:
return -1
word = ~self.words[wordIndex]
def __str__(self):
res = []
st = 0
while True:
i = self.nextSetBit(st)
if i != self.sz:
res += [0] * (i - st)
j = self.nextClearBit(i)
if j != self.sz:
res += [1] * (j-i)
st = j
else:
{{completion}}
else:
res += [0] * (self.sz - st)
break
return "".join(str(v) for v in res)
def __repr__(self):
return "Bitset(%s)" % str(self)
def __iter__(self):
for i in self[:]:
yield i
def __len__(self):
return self.sz
def add(bs,val):
bs.flip_range(val, bs.nextClearBit(val), 1)
def rem(bs,val):
bs.flip_range(val, bs.nextSetBit(val), 0)
def solve():
res = []
bs = BitSet(Z)
for val in A:
add(bs,val)
for _ in range(Q):
idx, val = ti()
idx -= 1
rem(bs,A[idx])
A[idx] = val
add(bs,val)
res.append(bs.last)
return "\n".join(str(v) for v in res)
Z = 200030
for test in range(1,1+1):
N,Q = ti()
A = li()
print(solve())
file.close()
|
res += [1] * (self.sz - i)
break
|
[{"input": "5 4\n2 2 2 4 5\n2 3\n5 3\n4 1\n1 4", "output": ["6\n5\n4\n5"]}, {"input": "2 1\n200000 1\n2 200000", "output": ["200001"]}]
|
block_completion_005933
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: After watching a certain anime before going to sleep, Mark dreams of standing in an old classroom with a blackboard that has a sequence of $$$n$$$ positive integers $$$a_1, a_2,\dots,a_n$$$ on it.Then, professor Koro comes in. He can perform the following operation: select an integer $$$x$$$ that appears at least $$$2$$$ times on the board, erase those $$$2$$$ appearances, and write $$$x+1$$$ on the board. Professor Koro then asks Mark the question, "what is the maximum possible number that could appear on the board after some operations?"Mark quickly solves this question, but he is still slower than professor Koro. Thus, professor Koro decides to give Mark additional challenges. He will update the initial sequence of integers $$$q$$$ times. Each time, he will choose positive integers $$$k$$$ and $$$l$$$, then change $$$a_k$$$ to $$$l$$$. After each update, he will ask Mark the same question again.Help Mark answer these questions faster than Professor Koro!Note that the updates are persistent. Changes made to the sequence $$$a$$$ will apply when processing future updates.
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$2\leq n\leq 2\cdot 10^5$$$, $$$1\leq q\leq 2\cdot 10^5$$$) β the length of the sequence $$$a$$$ and the number of updates, respectively. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$1\leq a_i\leq 2\cdot 10^5$$$) Then, $$$q$$$ lines follow, each consisting of two integers $$$k$$$ and $$$l$$$ ($$$1\leq k\leq n$$$, $$$1\leq l\leq 2\cdot 10^5$$$), telling to update $$$a_k$$$ to $$$l$$$.
Output Specification: Print $$$q$$$ lines. The $$$i$$$-th line should consist of a single integer β the answer after the $$$i$$$-th update.
Notes: NoteIn the first example test, the program must proceed through $$$4$$$ updates.The sequence after the first update is $$$[2,3,2,4,5]$$$. One sequence of operations that achieves the number $$$6$$$ the following. Initially, the blackboard has numbers $$$[2,3,2,4,5]$$$. Erase two copies of $$$2$$$ and write $$$3$$$, yielding $$$[3,4,5,\color{red}{3}]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[4,5,\color{red}{4}]$$$. Erase two copies of $$$4$$$ and write $$$5$$$, yielding $$$[5,\color{red}{5}]$$$. Erase two copies of $$$5$$$ and write $$$6$$$, yielding $$$[\color{red}{6}]$$$. Then, in the second update, the array is changed to $$$[2,3,2,4,3]$$$. This time, Mark cannot achieve $$$6$$$. However, one sequence that Mark can use to achieve $$$5$$$ is shown below. Initially, the blackboard has $$$[2,3,2,4,3]$$$. Erase two copies of $$$2$$$ and write $$$3$$$, yielding $$$[3,4,3,\color{red}{3}]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[3,4,\color{red}{4}]$$$. Erase two copies of $$$4$$$ and write $$$5$$$, yielding $$$[3,\color{red}{5}]$$$. In the third update, the array is changed to $$$[2,3,2,1,3]$$$. One way to achieve $$$4$$$ is shown below. Initially, the blackboard has $$$[2,3,2,1,3]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[2,2,1,\color{red}{4}]$$$.
Code:
import sys
import os
from io import BytesIO, IOBase
# 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")
if sys.version_info[0] < 3:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
file = sys.stdin
if os.environ.get('USER') == "loic":
file = open("data.in")
line = lambda: file.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
class BitSet:
ADDRESS_BITS_PER_WORD = 6
WORD_SZ = 1 << ADDRESS_BITS_PER_WORD
MASK = -0x1
MASK_MAX = 0x7fffffffffffffff
MASK_MIN = ~MASK_MAX
def __init__(self, sz):
self.sz = sz
self.words = [0] * (self._wordIndex(sz - 1) + 1)
self.last = -1
def _wordIndex(self, bitIndex):
if bitIndex >= self.sz:
raise ValueError("out of bound index", bitIndex)
return bitIndex >> BitSet.ADDRESS_BITS_PER_WORD
def _shift_one_left(self, shift):
if shift == BitSet.WORD_SZ - 1:
return BitSet.MASK_MIN
return 1 << (shift % BitSet.WORD_SZ)
def _shift_mask_right(self, shift):
if shift == 0:
return BitSet.MASK
return BitSet.MASK_MAX >> (shift - 1)
def _shift_mask_left(self, shift):
if shift == 0:
return BitSet.MASK
return ~(BitSet.MASK_MAX >> (BitSet.WORD_SZ - shift - 1))
def flip(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
self.words[wordIndex] ^= self._shift_one_left(bitIndex % BitSet.WORD_SZ)
def flip_range(self, l, r, pos):
startWordIndex = self._wordIndex(l)
endWordIndex = self._wordIndex(r)
firstWordMask = self._shift_mask_left(l % BitSet.WORD_SZ)
lastWordMask = self._shift_mask_right(BitSet.WORD_SZ - 1 - r % BitSet.WORD_SZ)
if startWordIndex == endWordIndex:
self.words[startWordIndex] ^= (firstWordMask & lastWordMask)
else:
self.words[startWordIndex] ^= firstWordMask
for i in range(startWordIndex + 1, endWordIndex):
self.words[i] ^= BitSet.MASK
self.words[endWordIndex] ^= lastWordMask
if pos:
self.last = max(self.last, r)
elif r == self.last:
self.last = self.previousSetBit(r-1)
def __setitem__(self, bitIndex, value):
wordIndex = self._wordIndex(bitIndex)
if value:
self.words[wordIndex] |= self._shift_one_left(bitIndex % BitSet.WORD_SZ)
else:
self.words[wordIndex] &= ~self._shift_one_left(bitIndex % BitSet.WORD_SZ)
def __getitem__(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
return (self.words[wordIndex] >> (bitIndex % BitSet.WORD_SZ)) & 1
''' return len(bitset) if there is no "1" after fromIndex '''
def nextSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = self.words[wordIndex]
''' return len(bitset) if there is no "0" after fromIndex '''
def nextClearBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = ~self.words[wordIndex] & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = ~self.words[wordIndex]
''' return -1 if there is no "1" before fromIndex '''
def previousSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
rem = fromIndex % BitSet.WORD_SZ
word = self.words[wordIndex] & self._shift_mask_right(BitSet.WORD_SZ - 1 - rem)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ - 1 + (word.bit_length() if word > 0 else BitSet.WORD_SZ)
wordIndex -= 1
if wordIndex < 0:
return -1
word = self.words[wordIndex]
''' return -1 if there is no "0" before fromIndex '''
def previousClearBit(self,fromIndex):
wordIndex = self._wordIndex(fromIndex)
rem = fromIndex % BitSet.WORD_SZ
word = ~self.words[wordIndex] & self._shift_mask_right(BitSet.WORD_SZ - 1 - rem)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ - 1 + (word.bit_length() if word > 0 else BitSet.WORD_SZ)
wordIndex -= 1
if wordIndex < 0:
return -1
word = ~self.words[wordIndex]
def __str__(self):
res = []
st = 0
while True:
i = self.nextSetBit(st)
if i != self.sz:
res += [0] * (i - st)
j = self.nextClearBit(i)
if j != self.sz:
# TODO: Your code here
else:
res += [1] * (self.sz - i)
break
else:
res += [0] * (self.sz - st)
break
return "".join(str(v) for v in res)
def __repr__(self):
return "Bitset(%s)" % str(self)
def __iter__(self):
for i in self[:]:
yield i
def __len__(self):
return self.sz
def add(bs,val):
bs.flip_range(val, bs.nextClearBit(val), 1)
def rem(bs,val):
bs.flip_range(val, bs.nextSetBit(val), 0)
def solve():
res = []
bs = BitSet(Z)
for val in A:
add(bs,val)
for _ in range(Q):
idx, val = ti()
idx -= 1
rem(bs,A[idx])
A[idx] = val
add(bs,val)
res.append(bs.last)
return "\n".join(str(v) for v in res)
Z = 200030
for test in range(1,1+1):
N,Q = ti()
A = li()
print(solve())
file.close()
|
import sys
import os
from io import BytesIO, IOBase
# 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")
if sys.version_info[0] < 3:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
file = sys.stdin
if os.environ.get('USER') == "loic":
file = open("data.in")
line = lambda: file.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
class BitSet:
ADDRESS_BITS_PER_WORD = 6
WORD_SZ = 1 << ADDRESS_BITS_PER_WORD
MASK = -0x1
MASK_MAX = 0x7fffffffffffffff
MASK_MIN = ~MASK_MAX
def __init__(self, sz):
self.sz = sz
self.words = [0] * (self._wordIndex(sz - 1) + 1)
self.last = -1
def _wordIndex(self, bitIndex):
if bitIndex >= self.sz:
raise ValueError("out of bound index", bitIndex)
return bitIndex >> BitSet.ADDRESS_BITS_PER_WORD
def _shift_one_left(self, shift):
if shift == BitSet.WORD_SZ - 1:
return BitSet.MASK_MIN
return 1 << (shift % BitSet.WORD_SZ)
def _shift_mask_right(self, shift):
if shift == 0:
return BitSet.MASK
return BitSet.MASK_MAX >> (shift - 1)
def _shift_mask_left(self, shift):
if shift == 0:
return BitSet.MASK
return ~(BitSet.MASK_MAX >> (BitSet.WORD_SZ - shift - 1))
def flip(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
self.words[wordIndex] ^= self._shift_one_left(bitIndex % BitSet.WORD_SZ)
def flip_range(self, l, r, pos):
startWordIndex = self._wordIndex(l)
endWordIndex = self._wordIndex(r)
firstWordMask = self._shift_mask_left(l % BitSet.WORD_SZ)
lastWordMask = self._shift_mask_right(BitSet.WORD_SZ - 1 - r % BitSet.WORD_SZ)
if startWordIndex == endWordIndex:
self.words[startWordIndex] ^= (firstWordMask & lastWordMask)
else:
self.words[startWordIndex] ^= firstWordMask
for i in range(startWordIndex + 1, endWordIndex):
self.words[i] ^= BitSet.MASK
self.words[endWordIndex] ^= lastWordMask
if pos:
self.last = max(self.last, r)
elif r == self.last:
self.last = self.previousSetBit(r-1)
def __setitem__(self, bitIndex, value):
wordIndex = self._wordIndex(bitIndex)
if value:
self.words[wordIndex] |= self._shift_one_left(bitIndex % BitSet.WORD_SZ)
else:
self.words[wordIndex] &= ~self._shift_one_left(bitIndex % BitSet.WORD_SZ)
def __getitem__(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
return (self.words[wordIndex] >> (bitIndex % BitSet.WORD_SZ)) & 1
''' return len(bitset) if there is no "1" after fromIndex '''
def nextSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = self.words[wordIndex]
''' return len(bitset) if there is no "0" after fromIndex '''
def nextClearBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = ~self.words[wordIndex] & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = ~self.words[wordIndex]
''' return -1 if there is no "1" before fromIndex '''
def previousSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
rem = fromIndex % BitSet.WORD_SZ
word = self.words[wordIndex] & self._shift_mask_right(BitSet.WORD_SZ - 1 - rem)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ - 1 + (word.bit_length() if word > 0 else BitSet.WORD_SZ)
wordIndex -= 1
if wordIndex < 0:
return -1
word = self.words[wordIndex]
''' return -1 if there is no "0" before fromIndex '''
def previousClearBit(self,fromIndex):
wordIndex = self._wordIndex(fromIndex)
rem = fromIndex % BitSet.WORD_SZ
word = ~self.words[wordIndex] & self._shift_mask_right(BitSet.WORD_SZ - 1 - rem)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ - 1 + (word.bit_length() if word > 0 else BitSet.WORD_SZ)
wordIndex -= 1
if wordIndex < 0:
return -1
word = ~self.words[wordIndex]
def __str__(self):
res = []
st = 0
while True:
i = self.nextSetBit(st)
if i != self.sz:
res += [0] * (i - st)
j = self.nextClearBit(i)
if j != self.sz:
{{completion}}
else:
res += [1] * (self.sz - i)
break
else:
res += [0] * (self.sz - st)
break
return "".join(str(v) for v in res)
def __repr__(self):
return "Bitset(%s)" % str(self)
def __iter__(self):
for i in self[:]:
yield i
def __len__(self):
return self.sz
def add(bs,val):
bs.flip_range(val, bs.nextClearBit(val), 1)
def rem(bs,val):
bs.flip_range(val, bs.nextSetBit(val), 0)
def solve():
res = []
bs = BitSet(Z)
for val in A:
add(bs,val)
for _ in range(Q):
idx, val = ti()
idx -= 1
rem(bs,A[idx])
A[idx] = val
add(bs,val)
res.append(bs.last)
return "\n".join(str(v) for v in res)
Z = 200030
for test in range(1,1+1):
N,Q = ti()
A = li()
print(solve())
file.close()
|
res += [1] * (j-i)
st = j
|
[{"input": "5 4\n2 2 2 4 5\n2 3\n5 3\n4 1\n1 4", "output": ["6\n5\n4\n5"]}, {"input": "2 1\n200000 1\n2 200000", "output": ["200001"]}]
|
block_completion_005934
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: After watching a certain anime before going to sleep, Mark dreams of standing in an old classroom with a blackboard that has a sequence of $$$n$$$ positive integers $$$a_1, a_2,\dots,a_n$$$ on it.Then, professor Koro comes in. He can perform the following operation: select an integer $$$x$$$ that appears at least $$$2$$$ times on the board, erase those $$$2$$$ appearances, and write $$$x+1$$$ on the board. Professor Koro then asks Mark the question, "what is the maximum possible number that could appear on the board after some operations?"Mark quickly solves this question, but he is still slower than professor Koro. Thus, professor Koro decides to give Mark additional challenges. He will update the initial sequence of integers $$$q$$$ times. Each time, he will choose positive integers $$$k$$$ and $$$l$$$, then change $$$a_k$$$ to $$$l$$$. After each update, he will ask Mark the same question again.Help Mark answer these questions faster than Professor Koro!Note that the updates are persistent. Changes made to the sequence $$$a$$$ will apply when processing future updates.
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$2\leq n\leq 2\cdot 10^5$$$, $$$1\leq q\leq 2\cdot 10^5$$$) β the length of the sequence $$$a$$$ and the number of updates, respectively. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$1\leq a_i\leq 2\cdot 10^5$$$) Then, $$$q$$$ lines follow, each consisting of two integers $$$k$$$ and $$$l$$$ ($$$1\leq k\leq n$$$, $$$1\leq l\leq 2\cdot 10^5$$$), telling to update $$$a_k$$$ to $$$l$$$.
Output Specification: Print $$$q$$$ lines. The $$$i$$$-th line should consist of a single integer β the answer after the $$$i$$$-th update.
Notes: NoteIn the first example test, the program must proceed through $$$4$$$ updates.The sequence after the first update is $$$[2,3,2,4,5]$$$. One sequence of operations that achieves the number $$$6$$$ the following. Initially, the blackboard has numbers $$$[2,3,2,4,5]$$$. Erase two copies of $$$2$$$ and write $$$3$$$, yielding $$$[3,4,5,\color{red}{3}]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[4,5,\color{red}{4}]$$$. Erase two copies of $$$4$$$ and write $$$5$$$, yielding $$$[5,\color{red}{5}]$$$. Erase two copies of $$$5$$$ and write $$$6$$$, yielding $$$[\color{red}{6}]$$$. Then, in the second update, the array is changed to $$$[2,3,2,4,3]$$$. This time, Mark cannot achieve $$$6$$$. However, one sequence that Mark can use to achieve $$$5$$$ is shown below. Initially, the blackboard has $$$[2,3,2,4,3]$$$. Erase two copies of $$$2$$$ and write $$$3$$$, yielding $$$[3,4,3,\color{red}{3}]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[3,4,\color{red}{4}]$$$. Erase two copies of $$$4$$$ and write $$$5$$$, yielding $$$[3,\color{red}{5}]$$$. In the third update, the array is changed to $$$[2,3,2,1,3]$$$. One way to achieve $$$4$$$ is shown below. Initially, the blackboard has $$$[2,3,2,1,3]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[2,2,1,\color{red}{4}]$$$.
Code:
import sys
import os
from io import BytesIO, IOBase
# 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")
if sys.version_info[0] < 3:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
file = sys.stdin
if os.environ.get('USER') == "loic":
file = open("data.in")
line = lambda: file.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
class BitSet:
ADDRESS_BITS_PER_WORD = 6
WORD_SZ = 60#1 << ADDRESS_BITS_PER_WORD
MASK = 0xfffffffffffffff
def __init__(self, sz):
self.sz = sz
self.words = [0] * (self._wordIndex(sz - 1) + 1)
self.last = -1
def _wordIndex(self, bitIndex):
if bitIndex >= self.sz:
raise ValueError("out of bound index", bitIndex)
return bitIndex // BitSet.WORD_SZ #>> BitSet.ADDRESS_BITS_PER_WORD
def _shift_mask_right(self, shift):
return BitSet.MASK >> shift
def _shift_mask_left(self, shift):
return (BitSet.MASK >> shift) << shift
def flip(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
self.words[wordIndex] ^= 1 << (bitIndex % BitSet.WORD_SZ)
def flip_range(self, l, r, pos):
startWordIndex = self._wordIndex(l)
endWordIndex = self._wordIndex(r)
firstWordMask = self._shift_mask_left(l % BitSet.WORD_SZ)
lastWordMask = self._shift_mask_right(BitSet.WORD_SZ - 1 - r % BitSet.WORD_SZ)
if startWordIndex == endWordIndex:
self.words[startWordIndex] ^= (firstWordMask & lastWordMask)
else:
self.words[startWordIndex] ^= firstWordMask
for i in range(startWordIndex + 1, endWordIndex):
self.words[i] ^= BitSet.MASK
self.words[endWordIndex] ^= lastWordMask
if pos:
self.last = max(self.last, r)
elif r == self.last:
self.last = self.previousSetBit(r-1)
def __setitem__(self, bitIndex, value):
wordIndex = self._wordIndex(bitIndex)
if value:
self.words[wordIndex] |= 1 << (bitIndex % BitSet.WORD_SZ)
else:
self.words[wordIndex] &= ~(1 << (bitIndex % BitSet.WORD_SZ))
def __getitem__(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
return (self.words[wordIndex] >> (bitIndex % BitSet.WORD_SZ)) & 1
''' return len(bitset) if there is no "1" after fromIndex '''
def nextSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = self.words[wordIndex]
''' return len(bitset) if there is no "0" after fromIndex '''
def nextClearBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = (~self.words[wordIndex] & BitSet.MASK) & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = ~self.words[wordIndex] & BitSet.MASK
''' return -1 if there is no "1" before fromIndex '''
def previousSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & self._shift_mask_right(BitSet.WORD_SZ - 1 - fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + word.bit_length() - 1
wordIndex -= 1
if wordIndex < 0:
return -1
word = self.words[wordIndex]
''' return -1 if there is no "0" before fromIndex '''
def previousClearBit(self,fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = (~self.words[wordIndex] & BitSet.MASK) & self._shift_mask_right(BitSet.WORD_SZ - 1 - fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + word.bit_length() - 1
wordIndex -= 1
if wordIndex < 0:
return -1
word = ~self.words[wordIndex] & BitSet.MASK
def __str__(self):
res = []
st = 0
while True:
i = self.nextSetBit(st)
if i != self.sz:
res += [0] * (i - st)
j = self.nextClearBit(i)
if j != self.sz:
res += [1] * (j-i)
st = j
else:
# TODO: Your code here
else:
res += [0] * (self.sz - st)
break
return "".join(str(v) for v in res)
def __repr__(self):
return "Bitset(%s)" % str(self)
def __iter__(self):
for i in self[:]:
yield i
def __len__(self):
return self.sz
def add(bs,val):
bs.flip_range(val, bs.nextClearBit(val), 1)
def rem(bs,val):
bs.flip_range(val, bs.nextSetBit(val), 0)
def solve():
res = []
bs = BitSet(Z)
for val in A:
add(bs,val)
for _ in range(Q):
idx, val = ti()
idx -= 1
rem(bs,A[idx])
A[idx] = val
add(bs,val)
res.append(bs.last)
return "\n".join(str(v) for v in res)
Z = 200030
for test in range(1,1+1):
N,Q = ti()
A = li()
print(solve())
file.close()
|
import sys
import os
from io import BytesIO, IOBase
# 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")
if sys.version_info[0] < 3:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
file = sys.stdin
if os.environ.get('USER') == "loic":
file = open("data.in")
line = lambda: file.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
class BitSet:
ADDRESS_BITS_PER_WORD = 6
WORD_SZ = 60#1 << ADDRESS_BITS_PER_WORD
MASK = 0xfffffffffffffff
def __init__(self, sz):
self.sz = sz
self.words = [0] * (self._wordIndex(sz - 1) + 1)
self.last = -1
def _wordIndex(self, bitIndex):
if bitIndex >= self.sz:
raise ValueError("out of bound index", bitIndex)
return bitIndex // BitSet.WORD_SZ #>> BitSet.ADDRESS_BITS_PER_WORD
def _shift_mask_right(self, shift):
return BitSet.MASK >> shift
def _shift_mask_left(self, shift):
return (BitSet.MASK >> shift) << shift
def flip(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
self.words[wordIndex] ^= 1 << (bitIndex % BitSet.WORD_SZ)
def flip_range(self, l, r, pos):
startWordIndex = self._wordIndex(l)
endWordIndex = self._wordIndex(r)
firstWordMask = self._shift_mask_left(l % BitSet.WORD_SZ)
lastWordMask = self._shift_mask_right(BitSet.WORD_SZ - 1 - r % BitSet.WORD_SZ)
if startWordIndex == endWordIndex:
self.words[startWordIndex] ^= (firstWordMask & lastWordMask)
else:
self.words[startWordIndex] ^= firstWordMask
for i in range(startWordIndex + 1, endWordIndex):
self.words[i] ^= BitSet.MASK
self.words[endWordIndex] ^= lastWordMask
if pos:
self.last = max(self.last, r)
elif r == self.last:
self.last = self.previousSetBit(r-1)
def __setitem__(self, bitIndex, value):
wordIndex = self._wordIndex(bitIndex)
if value:
self.words[wordIndex] |= 1 << (bitIndex % BitSet.WORD_SZ)
else:
self.words[wordIndex] &= ~(1 << (bitIndex % BitSet.WORD_SZ))
def __getitem__(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
return (self.words[wordIndex] >> (bitIndex % BitSet.WORD_SZ)) & 1
''' return len(bitset) if there is no "1" after fromIndex '''
def nextSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = self.words[wordIndex]
''' return len(bitset) if there is no "0" after fromIndex '''
def nextClearBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = (~self.words[wordIndex] & BitSet.MASK) & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = ~self.words[wordIndex] & BitSet.MASK
''' return -1 if there is no "1" before fromIndex '''
def previousSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & self._shift_mask_right(BitSet.WORD_SZ - 1 - fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + word.bit_length() - 1
wordIndex -= 1
if wordIndex < 0:
return -1
word = self.words[wordIndex]
''' return -1 if there is no "0" before fromIndex '''
def previousClearBit(self,fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = (~self.words[wordIndex] & BitSet.MASK) & self._shift_mask_right(BitSet.WORD_SZ - 1 - fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + word.bit_length() - 1
wordIndex -= 1
if wordIndex < 0:
return -1
word = ~self.words[wordIndex] & BitSet.MASK
def __str__(self):
res = []
st = 0
while True:
i = self.nextSetBit(st)
if i != self.sz:
res += [0] * (i - st)
j = self.nextClearBit(i)
if j != self.sz:
res += [1] * (j-i)
st = j
else:
{{completion}}
else:
res += [0] * (self.sz - st)
break
return "".join(str(v) for v in res)
def __repr__(self):
return "Bitset(%s)" % str(self)
def __iter__(self):
for i in self[:]:
yield i
def __len__(self):
return self.sz
def add(bs,val):
bs.flip_range(val, bs.nextClearBit(val), 1)
def rem(bs,val):
bs.flip_range(val, bs.nextSetBit(val), 0)
def solve():
res = []
bs = BitSet(Z)
for val in A:
add(bs,val)
for _ in range(Q):
idx, val = ti()
idx -= 1
rem(bs,A[idx])
A[idx] = val
add(bs,val)
res.append(bs.last)
return "\n".join(str(v) for v in res)
Z = 200030
for test in range(1,1+1):
N,Q = ti()
A = li()
print(solve())
file.close()
|
res += [1] * (self.sz - i)
break
|
[{"input": "5 4\n2 2 2 4 5\n2 3\n5 3\n4 1\n1 4", "output": ["6\n5\n4\n5"]}, {"input": "2 1\n200000 1\n2 200000", "output": ["200001"]}]
|
block_completion_005935
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: After watching a certain anime before going to sleep, Mark dreams of standing in an old classroom with a blackboard that has a sequence of $$$n$$$ positive integers $$$a_1, a_2,\dots,a_n$$$ on it.Then, professor Koro comes in. He can perform the following operation: select an integer $$$x$$$ that appears at least $$$2$$$ times on the board, erase those $$$2$$$ appearances, and write $$$x+1$$$ on the board. Professor Koro then asks Mark the question, "what is the maximum possible number that could appear on the board after some operations?"Mark quickly solves this question, but he is still slower than professor Koro. Thus, professor Koro decides to give Mark additional challenges. He will update the initial sequence of integers $$$q$$$ times. Each time, he will choose positive integers $$$k$$$ and $$$l$$$, then change $$$a_k$$$ to $$$l$$$. After each update, he will ask Mark the same question again.Help Mark answer these questions faster than Professor Koro!Note that the updates are persistent. Changes made to the sequence $$$a$$$ will apply when processing future updates.
Input Specification: The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$2\leq n\leq 2\cdot 10^5$$$, $$$1\leq q\leq 2\cdot 10^5$$$) β the length of the sequence $$$a$$$ and the number of updates, respectively. The second line contains $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$ ($$$1\leq a_i\leq 2\cdot 10^5$$$) Then, $$$q$$$ lines follow, each consisting of two integers $$$k$$$ and $$$l$$$ ($$$1\leq k\leq n$$$, $$$1\leq l\leq 2\cdot 10^5$$$), telling to update $$$a_k$$$ to $$$l$$$.
Output Specification: Print $$$q$$$ lines. The $$$i$$$-th line should consist of a single integer β the answer after the $$$i$$$-th update.
Notes: NoteIn the first example test, the program must proceed through $$$4$$$ updates.The sequence after the first update is $$$[2,3,2,4,5]$$$. One sequence of operations that achieves the number $$$6$$$ the following. Initially, the blackboard has numbers $$$[2,3,2,4,5]$$$. Erase two copies of $$$2$$$ and write $$$3$$$, yielding $$$[3,4,5,\color{red}{3}]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[4,5,\color{red}{4}]$$$. Erase two copies of $$$4$$$ and write $$$5$$$, yielding $$$[5,\color{red}{5}]$$$. Erase two copies of $$$5$$$ and write $$$6$$$, yielding $$$[\color{red}{6}]$$$. Then, in the second update, the array is changed to $$$[2,3,2,4,3]$$$. This time, Mark cannot achieve $$$6$$$. However, one sequence that Mark can use to achieve $$$5$$$ is shown below. Initially, the blackboard has $$$[2,3,2,4,3]$$$. Erase two copies of $$$2$$$ and write $$$3$$$, yielding $$$[3,4,3,\color{red}{3}]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[3,4,\color{red}{4}]$$$. Erase two copies of $$$4$$$ and write $$$5$$$, yielding $$$[3,\color{red}{5}]$$$. In the third update, the array is changed to $$$[2,3,2,1,3]$$$. One way to achieve $$$4$$$ is shown below. Initially, the blackboard has $$$[2,3,2,1,3]$$$. Erase two copies of $$$3$$$ and write $$$4$$$, yielding $$$[2,2,1,\color{red}{4}]$$$.
Code:
import sys
import os
from io import BytesIO, IOBase
# 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")
if sys.version_info[0] < 3:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
file = sys.stdin
if os.environ.get('USER') == "loic":
file = open("data.in")
line = lambda: file.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
class BitSet:
ADDRESS_BITS_PER_WORD = 6
WORD_SZ = 60#1 << ADDRESS_BITS_PER_WORD
MASK = 0xfffffffffffffff
def __init__(self, sz):
self.sz = sz
self.words = [0] * (self._wordIndex(sz - 1) + 1)
self.last = -1
def _wordIndex(self, bitIndex):
if bitIndex >= self.sz:
raise ValueError("out of bound index", bitIndex)
return bitIndex // BitSet.WORD_SZ #>> BitSet.ADDRESS_BITS_PER_WORD
def _shift_mask_right(self, shift):
return BitSet.MASK >> shift
def _shift_mask_left(self, shift):
return (BitSet.MASK >> shift) << shift
def flip(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
self.words[wordIndex] ^= 1 << (bitIndex % BitSet.WORD_SZ)
def flip_range(self, l, r, pos):
startWordIndex = self._wordIndex(l)
endWordIndex = self._wordIndex(r)
firstWordMask = self._shift_mask_left(l % BitSet.WORD_SZ)
lastWordMask = self._shift_mask_right(BitSet.WORD_SZ - 1 - r % BitSet.WORD_SZ)
if startWordIndex == endWordIndex:
self.words[startWordIndex] ^= (firstWordMask & lastWordMask)
else:
self.words[startWordIndex] ^= firstWordMask
for i in range(startWordIndex + 1, endWordIndex):
self.words[i] ^= BitSet.MASK
self.words[endWordIndex] ^= lastWordMask
if pos:
self.last = max(self.last, r)
elif r == self.last:
self.last = self.previousSetBit(r-1)
def __setitem__(self, bitIndex, value):
wordIndex = self._wordIndex(bitIndex)
if value:
self.words[wordIndex] |= 1 << (bitIndex % BitSet.WORD_SZ)
else:
self.words[wordIndex] &= ~(1 << (bitIndex % BitSet.WORD_SZ))
def __getitem__(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
return (self.words[wordIndex] >> (bitIndex % BitSet.WORD_SZ)) & 1
''' return len(bitset) if there is no "1" after fromIndex '''
def nextSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = self.words[wordIndex]
''' return len(bitset) if there is no "0" after fromIndex '''
def nextClearBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = (~self.words[wordIndex] & BitSet.MASK) & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = ~self.words[wordIndex] & BitSet.MASK
''' return -1 if there is no "1" before fromIndex '''
def previousSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & self._shift_mask_right(BitSet.WORD_SZ - 1 - fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + word.bit_length() - 1
wordIndex -= 1
if wordIndex < 0:
return -1
word = self.words[wordIndex]
''' return -1 if there is no "0" before fromIndex '''
def previousClearBit(self,fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = (~self.words[wordIndex] & BitSet.MASK) & self._shift_mask_right(BitSet.WORD_SZ - 1 - fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + word.bit_length() - 1
wordIndex -= 1
if wordIndex < 0:
return -1
word = ~self.words[wordIndex] & BitSet.MASK
def __str__(self):
res = []
st = 0
while True:
i = self.nextSetBit(st)
if i != self.sz:
res += [0] * (i - st)
j = self.nextClearBit(i)
if j != self.sz:
# TODO: Your code here
else:
res += [1] * (self.sz - i)
break
else:
res += [0] * (self.sz - st)
break
return "".join(str(v) for v in res)
def __repr__(self):
return "Bitset(%s)" % str(self)
def __iter__(self):
for i in self[:]:
yield i
def __len__(self):
return self.sz
def add(bs,val):
bs.flip_range(val, bs.nextClearBit(val), 1)
def rem(bs,val):
bs.flip_range(val, bs.nextSetBit(val), 0)
def solve():
res = []
bs = BitSet(Z)
for val in A:
add(bs,val)
for _ in range(Q):
idx, val = ti()
idx -= 1
rem(bs,A[idx])
A[idx] = val
add(bs,val)
res.append(bs.last)
return "\n".join(str(v) for v in res)
Z = 200030
for test in range(1,1+1):
N,Q = ti()
A = li()
print(solve())
file.close()
|
import sys
import os
from io import BytesIO, IOBase
# 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")
if sys.version_info[0] < 3:
sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
file = sys.stdin
if os.environ.get('USER') == "loic":
file = open("data.in")
line = lambda: file.readline().split()
ui = lambda: int(line()[0])
ti = lambda: map(int,line())
li = lambda: list(ti())
#######################################################################
class BitSet:
ADDRESS_BITS_PER_WORD = 6
WORD_SZ = 60#1 << ADDRESS_BITS_PER_WORD
MASK = 0xfffffffffffffff
def __init__(self, sz):
self.sz = sz
self.words = [0] * (self._wordIndex(sz - 1) + 1)
self.last = -1
def _wordIndex(self, bitIndex):
if bitIndex >= self.sz:
raise ValueError("out of bound index", bitIndex)
return bitIndex // BitSet.WORD_SZ #>> BitSet.ADDRESS_BITS_PER_WORD
def _shift_mask_right(self, shift):
return BitSet.MASK >> shift
def _shift_mask_left(self, shift):
return (BitSet.MASK >> shift) << shift
def flip(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
self.words[wordIndex] ^= 1 << (bitIndex % BitSet.WORD_SZ)
def flip_range(self, l, r, pos):
startWordIndex = self._wordIndex(l)
endWordIndex = self._wordIndex(r)
firstWordMask = self._shift_mask_left(l % BitSet.WORD_SZ)
lastWordMask = self._shift_mask_right(BitSet.WORD_SZ - 1 - r % BitSet.WORD_SZ)
if startWordIndex == endWordIndex:
self.words[startWordIndex] ^= (firstWordMask & lastWordMask)
else:
self.words[startWordIndex] ^= firstWordMask
for i in range(startWordIndex + 1, endWordIndex):
self.words[i] ^= BitSet.MASK
self.words[endWordIndex] ^= lastWordMask
if pos:
self.last = max(self.last, r)
elif r == self.last:
self.last = self.previousSetBit(r-1)
def __setitem__(self, bitIndex, value):
wordIndex = self._wordIndex(bitIndex)
if value:
self.words[wordIndex] |= 1 << (bitIndex % BitSet.WORD_SZ)
else:
self.words[wordIndex] &= ~(1 << (bitIndex % BitSet.WORD_SZ))
def __getitem__(self, bitIndex):
wordIndex = self._wordIndex(bitIndex)
return (self.words[wordIndex] >> (bitIndex % BitSet.WORD_SZ)) & 1
''' return len(bitset) if there is no "1" after fromIndex '''
def nextSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = self.words[wordIndex]
''' return len(bitset) if there is no "0" after fromIndex '''
def nextClearBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = (~self.words[wordIndex] & BitSet.MASK) & self._shift_mask_left(fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + (word & -word).bit_length() - 1
wordIndex += 1
if wordIndex > len(self.words) - 1:
return self.sz
word = ~self.words[wordIndex] & BitSet.MASK
''' return -1 if there is no "1" before fromIndex '''
def previousSetBit(self, fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = self.words[wordIndex] & self._shift_mask_right(BitSet.WORD_SZ - 1 - fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + word.bit_length() - 1
wordIndex -= 1
if wordIndex < 0:
return -1
word = self.words[wordIndex]
''' return -1 if there is no "0" before fromIndex '''
def previousClearBit(self,fromIndex):
wordIndex = self._wordIndex(fromIndex)
word = (~self.words[wordIndex] & BitSet.MASK) & self._shift_mask_right(BitSet.WORD_SZ - 1 - fromIndex % BitSet.WORD_SZ)
while True:
if word != 0:
return wordIndex * BitSet.WORD_SZ + word.bit_length() - 1
wordIndex -= 1
if wordIndex < 0:
return -1
word = ~self.words[wordIndex] & BitSet.MASK
def __str__(self):
res = []
st = 0
while True:
i = self.nextSetBit(st)
if i != self.sz:
res += [0] * (i - st)
j = self.nextClearBit(i)
if j != self.sz:
{{completion}}
else:
res += [1] * (self.sz - i)
break
else:
res += [0] * (self.sz - st)
break
return "".join(str(v) for v in res)
def __repr__(self):
return "Bitset(%s)" % str(self)
def __iter__(self):
for i in self[:]:
yield i
def __len__(self):
return self.sz
def add(bs,val):
bs.flip_range(val, bs.nextClearBit(val), 1)
def rem(bs,val):
bs.flip_range(val, bs.nextSetBit(val), 0)
def solve():
res = []
bs = BitSet(Z)
for val in A:
add(bs,val)
for _ in range(Q):
idx, val = ti()
idx -= 1
rem(bs,A[idx])
A[idx] = val
add(bs,val)
res.append(bs.last)
return "\n".join(str(v) for v in res)
Z = 200030
for test in range(1,1+1):
N,Q = ti()
A = li()
print(solve())
file.close()
|
res += [1] * (j-i)
st = j
|
[{"input": "5 4\n2 2 2 4 5\n2 3\n5 3\n4 1\n1 4", "output": ["6\n5\n4\n5"]}, {"input": "2 1\n200000 1\n2 200000", "output": ["200001"]}]
|
block_completion_005936
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Sehr Sus is an infinite hexagonal grid as pictured below, controlled by MennaFadali, ZerooCool and Hosssam.They love equilateral triangles and want to create $$$n$$$ equilateral triangles on the grid by adding some straight lines. The triangles must all be empty from the inside (in other words, no straight line or hexagon edge should pass through any of the triangles).You are allowed to add straight lines parallel to the edges of the hexagons. Given $$$n$$$, what is the minimum number of lines you need to add to create at least $$$n$$$ equilateral triangles as described? Adding two red lines results in two new yellow equilateral triangles.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β the number of test cases. Then $$$t$$$ test cases follow. Each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^{9}$$$) β the required number of equilateral triangles.
Output Specification: For each test case, print the minimum number of lines needed to have $$$n$$$ or more equilateral triangles.
Notes: NoteIn the first and second test cases only 2 lines are needed. After adding the first line, no equilateral triangles will be created no matter where it is added. But after adding the second line, two more triangles will be created at once. In the third test case, the minimum needed is 3 lines as shown below.
Code:
import sys
ctr = [0, 0, 0]
cnt = [0]
while cnt[-1] < 10**9:
i = ctr.index(min(ctr))
cnt.append(cnt[-1] + 2*(sum(ctr) - ctr[i]))
ctr[i] += 1
def solve(sn):
t = int(sn)
s, e = 0, len(cnt) - 1
while s < e:
m = (s + e) >> 1
if cnt[m] >= t:
e = m
else:
# TODO: Your code here
return str(s)
inp = sys.stdin.read().split()
inp.pop(0)
print('\n'.join(map(solve, inp)))
|
import sys
ctr = [0, 0, 0]
cnt = [0]
while cnt[-1] < 10**9:
i = ctr.index(min(ctr))
cnt.append(cnt[-1] + 2*(sum(ctr) - ctr[i]))
ctr[i] += 1
def solve(sn):
t = int(sn)
s, e = 0, len(cnt) - 1
while s < e:
m = (s + e) >> 1
if cnt[m] >= t:
e = m
else:
{{completion}}
return str(s)
inp = sys.stdin.read().split()
inp.pop(0)
print('\n'.join(map(solve, inp)))
|
s = m + 1
|
[{"input": "4\n\n1\n\n2\n\n3\n\n4567", "output": ["2\n2\n3\n83"]}]
|
block_completion_005986
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: Sehr Sus is an infinite hexagonal grid as pictured below, controlled by MennaFadali, ZerooCool and Hosssam.They love equilateral triangles and want to create $$$n$$$ equilateral triangles on the grid by adding some straight lines. The triangles must all be empty from the inside (in other words, no straight line or hexagon edge should pass through any of the triangles).You are allowed to add straight lines parallel to the edges of the hexagons. Given $$$n$$$, what is the minimum number of lines you need to add to create at least $$$n$$$ equilateral triangles as described? Adding two red lines results in two new yellow equilateral triangles.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β the number of test cases. Then $$$t$$$ test cases follow. Each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^{9}$$$) β the required number of equilateral triangles.
Output Specification: For each test case, print the minimum number of lines needed to have $$$n$$$ or more equilateral triangles.
Notes: NoteIn the first and second test cases only 2 lines are needed. After adding the first line, no equilateral triangles will be created no matter where it is added. But after adding the second line, two more triangles will be created at once. In the third test case, the minimum needed is 3 lines as shown below.
Code:
import sys
ctr = [0, 0, 0]
cnt = [0]
i = 0
tot = 0
s = 0
while tot < 10**9:
tot += 2*(s - ctr[i])
cnt.append(tot)
ctr[i] += 1
s += 1
i += 1
if i == 3: i = 0
def solve(sn):
t = int(sn)
s, e = 0, len(cnt) - 1
while s < e:
m = (s + e) >> 1
if cnt[m] >= t:
e = m
else:
# TODO: Your code here
return str(s)
inp = sys.stdin.read().split()
inp.pop(0)
print('\n'.join(map(solve, inp)))
|
import sys
ctr = [0, 0, 0]
cnt = [0]
i = 0
tot = 0
s = 0
while tot < 10**9:
tot += 2*(s - ctr[i])
cnt.append(tot)
ctr[i] += 1
s += 1
i += 1
if i == 3: i = 0
def solve(sn):
t = int(sn)
s, e = 0, len(cnt) - 1
while s < e:
m = (s + e) >> 1
if cnt[m] >= t:
e = m
else:
{{completion}}
return str(s)
inp = sys.stdin.read().split()
inp.pop(0)
print('\n'.join(map(solve, inp)))
|
s = m + 1
|
[{"input": "4\n\n1\n\n2\n\n3\n\n4567", "output": ["2\n2\n3\n83"]}]
|
block_completion_005987
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: While searching for the pizza, baby Hosssam came across two permutations $$$a$$$ and $$$b$$$ of length $$$n$$$.Recall that a permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).Baby Hosssam forgot about the pizza and started playing around with the two permutations. While he was playing with them, some elements of the first permutation got mixed up with some elements of the second permutation, and to his surprise those elements also formed a permutation of size $$$n$$$.Specifically, he mixed up the permutations to form a new array $$$c$$$ in the following way. For each $$$i$$$ ($$$1\le i\le n$$$), he either made $$$c_i=a_i$$$ or $$$c_i=b_i$$$. The array $$$c$$$ is a permutation. You know permutations $$$a$$$, $$$b$$$, and values at some positions in $$$c$$$. Please count the number different permutations $$$c$$$ that are consistent with the described process and the given values. Since the answer can be large, print it modulo $$$10^9+7$$$.It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements.
Input Specification: The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$) β the length of the permutations. The next line contains $$$n$$$ distinct integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le n$$$) β the first permutation. The next line contains $$$n$$$ distinct integers $$$b_1,b_2,\ldots,b_n$$$ ($$$1\le b_i\le n$$$) β the second permutation. The next line contains $$$n$$$ distinct integers $$$d_1,d_2,\ldots,d_n$$$ ($$$d_i$$$ is either $$$0$$$, $$$a_i$$$, or $$$b_i$$$) β the description of the known values of $$$c$$$. If $$$d_i=0$$$, then there are no requirements on the value of $$$c_i$$$. Otherwise, it is required that $$$c_i=d_i$$$. It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$.
Output Specification: For each test case, print the number of possible permutations $$$c$$$, modulo $$$10^9+7$$$.
Notes: NoteIn the first test case, there are $$$4$$$ distinct permutation that can be made using the process: $$$[2,3,1,4,5,6,7]$$$, $$$[2,3,1,7,6,5,4]$$$, $$$[2,3,1,4,6,5,7]$$$, $$$[2,3,1,7,5,6,4]$$$.In the second test case, there is only one distinct permutation that can be made using the process: $$$[1]$$$.In the third test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[6,5,2,1,4,3]$$$, $$$[6,5,3,1,4,2]$$$.In the fourth test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[1,2,8,7,4,3,6,5]$$$, $$$[1,6,4,7,2,3,8,5]$$$.In the fifth test case, there is only one distinct permutation that can be made using the process: $$$[1,9,2,3,4,10,8,6,7,5]$$$.
Code:
"""
in each circle, there's two options
"""
import sys;input=sys.stdin.readline
I=lambda:int(input())
A=lambda:[*map(int,input().split())]
mod=10**9+7
for _ in range(I()):
n=I()
a,b,c=A(),A(),A()
g={a[i]:[b[i],c[i]] for i in range(n)}
cycles,visi=0,[False]*(n+1)
for u in range(1,n+1):
need=True;cycle_size=0
while not visi[g[u][0]]:
if g[u][1]!=0:# TODO: Your code here
#mark visited and move to next vertex
visi[g[u][0]],u=True,g[u][0]
cycle_size+=1
if need and cycle_size>1:cycles+=1
print(pow(2,cycles,mod))
|
"""
in each circle, there's two options
"""
import sys;input=sys.stdin.readline
I=lambda:int(input())
A=lambda:[*map(int,input().split())]
mod=10**9+7
for _ in range(I()):
n=I()
a,b,c=A(),A(),A()
g={a[i]:[b[i],c[i]] for i in range(n)}
cycles,visi=0,[False]*(n+1)
for u in range(1,n+1):
need=True;cycle_size=0
while not visi[g[u][0]]:
if g[u][1]!=0:{{completion}}
#mark visited and move to next vertex
visi[g[u][0]],u=True,g[u][0]
cycle_size+=1
if need and cycle_size>1:cycles+=1
print(pow(2,cycles,mod))
|
need=False
|
[{"input": "9\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n2 0 1 0 0 0 0\n1\n1\n1\n0\n6\n1 5 2 4 6 3\n6 5 3 1 4 2\n6 0 0 0 0 0\n8\n1 6 4 7 2 3 8 5\n3 2 8 1 4 5 6 7\n1 0 0 7 0 3 0 5\n10\n1 8 6 2 4 7 9 3 10 5\n1 9 2 3 4 10 8 6 7 5\n1 9 2 3 4 10 8 6 7 5\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n0 0 0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 4 5\n0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 5 4\n0 0 0 0 0\n3\n1 2 3\n3 1 2\n0 0 0", "output": ["4\n1\n2\n2\n1\n8\n1\n2\n2"]}]
|
block_completion_006024
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: While searching for the pizza, baby Hosssam came across two permutations $$$a$$$ and $$$b$$$ of length $$$n$$$.Recall that a permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).Baby Hosssam forgot about the pizza and started playing around with the two permutations. While he was playing with them, some elements of the first permutation got mixed up with some elements of the second permutation, and to his surprise those elements also formed a permutation of size $$$n$$$.Specifically, he mixed up the permutations to form a new array $$$c$$$ in the following way. For each $$$i$$$ ($$$1\le i\le n$$$), he either made $$$c_i=a_i$$$ or $$$c_i=b_i$$$. The array $$$c$$$ is a permutation. You know permutations $$$a$$$, $$$b$$$, and values at some positions in $$$c$$$. Please count the number different permutations $$$c$$$ that are consistent with the described process and the given values. Since the answer can be large, print it modulo $$$10^9+7$$$.It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements.
Input Specification: The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$) β the length of the permutations. The next line contains $$$n$$$ distinct integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le n$$$) β the first permutation. The next line contains $$$n$$$ distinct integers $$$b_1,b_2,\ldots,b_n$$$ ($$$1\le b_i\le n$$$) β the second permutation. The next line contains $$$n$$$ distinct integers $$$d_1,d_2,\ldots,d_n$$$ ($$$d_i$$$ is either $$$0$$$, $$$a_i$$$, or $$$b_i$$$) β the description of the known values of $$$c$$$. If $$$d_i=0$$$, then there are no requirements on the value of $$$c_i$$$. Otherwise, it is required that $$$c_i=d_i$$$. It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$.
Output Specification: For each test case, print the number of possible permutations $$$c$$$, modulo $$$10^9+7$$$.
Notes: NoteIn the first test case, there are $$$4$$$ distinct permutation that can be made using the process: $$$[2,3,1,4,5,6,7]$$$, $$$[2,3,1,7,6,5,4]$$$, $$$[2,3,1,4,6,5,7]$$$, $$$[2,3,1,7,5,6,4]$$$.In the second test case, there is only one distinct permutation that can be made using the process: $$$[1]$$$.In the third test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[6,5,2,1,4,3]$$$, $$$[6,5,3,1,4,2]$$$.In the fourth test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[1,2,8,7,4,3,6,5]$$$, $$$[1,6,4,7,2,3,8,5]$$$.In the fifth test case, there is only one distinct permutation that can be made using the process: $$$[1,9,2,3,4,10,8,6,7,5]$$$.
Code:
# read interger t from input.txt and then read t lines
import sys
DEBUG = False
def check(a, b, c):
a = [0] + a
b = [0] + b
c = [0] + c
m_ = [0] * len(a)
m = [0] * len(a)
for i in range(1, len(b)):
m_[b[i]] = i
for i in range(1, len(a)):
m[i] = m_[a[i]]
# print(">>>", a)
# print(">>>", b)
# print(">>>", m)
# find cicles in permutations
total_num = 1
used = [False] * len(m)
# print(a, b, c)
for i in range(1, len(m)):
if not used[i]:
j = i
c_zeros = True
while not used[j]:
if c[j] != 0:
# TODO: Your code here
used[j] = True
j = m[j]
used[i] = True
# print(i, m[i], a[i], b[i], c[i])
if c_zeros and m[i] != i:
# print(">>", i)
total_num = (total_num) * 2 % 1000000007
print(total_num)
def main(f):
t = int(f.readline())
for i in range(t):
n = int(f.readline())
a = list(map(int, f.readline().split()))
b = list(map(int, f.readline().split()))
c = list(map(int, f.readline().split()))
check(a, b, c)
if DEBUG:
f = open('input.txt', 'r')
else:
f = sys.stdin
main(f)
f.close()
|
# read interger t from input.txt and then read t lines
import sys
DEBUG = False
def check(a, b, c):
a = [0] + a
b = [0] + b
c = [0] + c
m_ = [0] * len(a)
m = [0] * len(a)
for i in range(1, len(b)):
m_[b[i]] = i
for i in range(1, len(a)):
m[i] = m_[a[i]]
# print(">>>", a)
# print(">>>", b)
# print(">>>", m)
# find cicles in permutations
total_num = 1
used = [False] * len(m)
# print(a, b, c)
for i in range(1, len(m)):
if not used[i]:
j = i
c_zeros = True
while not used[j]:
if c[j] != 0:
{{completion}}
used[j] = True
j = m[j]
used[i] = True
# print(i, m[i], a[i], b[i], c[i])
if c_zeros and m[i] != i:
# print(">>", i)
total_num = (total_num) * 2 % 1000000007
print(total_num)
def main(f):
t = int(f.readline())
for i in range(t):
n = int(f.readline())
a = list(map(int, f.readline().split()))
b = list(map(int, f.readline().split()))
c = list(map(int, f.readline().split()))
check(a, b, c)
if DEBUG:
f = open('input.txt', 'r')
else:
f = sys.stdin
main(f)
f.close()
|
c_zeros = False
|
[{"input": "9\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n2 0 1 0 0 0 0\n1\n1\n1\n0\n6\n1 5 2 4 6 3\n6 5 3 1 4 2\n6 0 0 0 0 0\n8\n1 6 4 7 2 3 8 5\n3 2 8 1 4 5 6 7\n1 0 0 7 0 3 0 5\n10\n1 8 6 2 4 7 9 3 10 5\n1 9 2 3 4 10 8 6 7 5\n1 9 2 3 4 10 8 6 7 5\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n0 0 0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 4 5\n0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 5 4\n0 0 0 0 0\n3\n1 2 3\n3 1 2\n0 0 0", "output": ["4\n1\n2\n2\n1\n8\n1\n2\n2"]}]
|
block_completion_006025
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: While searching for the pizza, baby Hosssam came across two permutations $$$a$$$ and $$$b$$$ of length $$$n$$$.Recall that a permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).Baby Hosssam forgot about the pizza and started playing around with the two permutations. While he was playing with them, some elements of the first permutation got mixed up with some elements of the second permutation, and to his surprise those elements also formed a permutation of size $$$n$$$.Specifically, he mixed up the permutations to form a new array $$$c$$$ in the following way. For each $$$i$$$ ($$$1\le i\le n$$$), he either made $$$c_i=a_i$$$ or $$$c_i=b_i$$$. The array $$$c$$$ is a permutation. You know permutations $$$a$$$, $$$b$$$, and values at some positions in $$$c$$$. Please count the number different permutations $$$c$$$ that are consistent with the described process and the given values. Since the answer can be large, print it modulo $$$10^9+7$$$.It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements.
Input Specification: The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$) β the length of the permutations. The next line contains $$$n$$$ distinct integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le n$$$) β the first permutation. The next line contains $$$n$$$ distinct integers $$$b_1,b_2,\ldots,b_n$$$ ($$$1\le b_i\le n$$$) β the second permutation. The next line contains $$$n$$$ distinct integers $$$d_1,d_2,\ldots,d_n$$$ ($$$d_i$$$ is either $$$0$$$, $$$a_i$$$, or $$$b_i$$$) β the description of the known values of $$$c$$$. If $$$d_i=0$$$, then there are no requirements on the value of $$$c_i$$$. Otherwise, it is required that $$$c_i=d_i$$$. It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$.
Output Specification: For each test case, print the number of possible permutations $$$c$$$, modulo $$$10^9+7$$$.
Notes: NoteIn the first test case, there are $$$4$$$ distinct permutation that can be made using the process: $$$[2,3,1,4,5,6,7]$$$, $$$[2,3,1,7,6,5,4]$$$, $$$[2,3,1,4,6,5,7]$$$, $$$[2,3,1,7,5,6,4]$$$.In the second test case, there is only one distinct permutation that can be made using the process: $$$[1]$$$.In the third test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[6,5,2,1,4,3]$$$, $$$[6,5,3,1,4,2]$$$.In the fourth test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[1,2,8,7,4,3,6,5]$$$, $$$[1,6,4,7,2,3,8,5]$$$.In the fifth test case, there is only one distinct permutation that can be made using the process: $$$[1,9,2,3,4,10,8,6,7,5]$$$.
Code:
import sys
t = int(sys.stdin.readline())
for _ in range(t):
n = int(sys.stdin.readline())
a = list(map(int,sys.stdin.readline().split()))
b = list(map(int,sys.stdin.readline().split()))
c = list(map(int,sys.stdin.readline().split()))
count = 0
L = [0] * (n+1)
for i in range(0,n):
L[a[i]] = b[i]
status = 1
for i in range(n):
if c[i] != 0:
L[a[i]] = 0
L[b[i]] = 0
for i in range(1,n+1):
key = i
xstatus = 1
status = 1
xcount= 0
while status == 1:
if L[key] == 0:
status = 0
if L[key] == i:
if xcount >= 1:
# TODO: Your code here
status = 0
xcount += 1
x = L[key]
L[key] = 0
key = x
print((2 **count) % (10 ** 9 + 7))
|
import sys
t = int(sys.stdin.readline())
for _ in range(t):
n = int(sys.stdin.readline())
a = list(map(int,sys.stdin.readline().split()))
b = list(map(int,sys.stdin.readline().split()))
c = list(map(int,sys.stdin.readline().split()))
count = 0
L = [0] * (n+1)
for i in range(0,n):
L[a[i]] = b[i]
status = 1
for i in range(n):
if c[i] != 0:
L[a[i]] = 0
L[b[i]] = 0
for i in range(1,n+1):
key = i
xstatus = 1
status = 1
xcount= 0
while status == 1:
if L[key] == 0:
status = 0
if L[key] == i:
if xcount >= 1:
{{completion}}
status = 0
xcount += 1
x = L[key]
L[key] = 0
key = x
print((2 **count) % (10 ** 9 + 7))
|
count += 1
|
[{"input": "9\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n2 0 1 0 0 0 0\n1\n1\n1\n0\n6\n1 5 2 4 6 3\n6 5 3 1 4 2\n6 0 0 0 0 0\n8\n1 6 4 7 2 3 8 5\n3 2 8 1 4 5 6 7\n1 0 0 7 0 3 0 5\n10\n1 8 6 2 4 7 9 3 10 5\n1 9 2 3 4 10 8 6 7 5\n1 9 2 3 4 10 8 6 7 5\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n0 0 0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 4 5\n0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 5 4\n0 0 0 0 0\n3\n1 2 3\n3 1 2\n0 0 0", "output": ["4\n1\n2\n2\n1\n8\n1\n2\n2"]}]
|
block_completion_006026
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: While searching for the pizza, baby Hosssam came across two permutations $$$a$$$ and $$$b$$$ of length $$$n$$$.Recall that a permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).Baby Hosssam forgot about the pizza and started playing around with the two permutations. While he was playing with them, some elements of the first permutation got mixed up with some elements of the second permutation, and to his surprise those elements also formed a permutation of size $$$n$$$.Specifically, he mixed up the permutations to form a new array $$$c$$$ in the following way. For each $$$i$$$ ($$$1\le i\le n$$$), he either made $$$c_i=a_i$$$ or $$$c_i=b_i$$$. The array $$$c$$$ is a permutation. You know permutations $$$a$$$, $$$b$$$, and values at some positions in $$$c$$$. Please count the number different permutations $$$c$$$ that are consistent with the described process and the given values. Since the answer can be large, print it modulo $$$10^9+7$$$.It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements.
Input Specification: The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$) β the length of the permutations. The next line contains $$$n$$$ distinct integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le n$$$) β the first permutation. The next line contains $$$n$$$ distinct integers $$$b_1,b_2,\ldots,b_n$$$ ($$$1\le b_i\le n$$$) β the second permutation. The next line contains $$$n$$$ distinct integers $$$d_1,d_2,\ldots,d_n$$$ ($$$d_i$$$ is either $$$0$$$, $$$a_i$$$, or $$$b_i$$$) β the description of the known values of $$$c$$$. If $$$d_i=0$$$, then there are no requirements on the value of $$$c_i$$$. Otherwise, it is required that $$$c_i=d_i$$$. It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$.
Output Specification: For each test case, print the number of possible permutations $$$c$$$, modulo $$$10^9+7$$$.
Notes: NoteIn the first test case, there are $$$4$$$ distinct permutation that can be made using the process: $$$[2,3,1,4,5,6,7]$$$, $$$[2,3,1,7,6,5,4]$$$, $$$[2,3,1,4,6,5,7]$$$, $$$[2,3,1,7,5,6,4]$$$.In the second test case, there is only one distinct permutation that can be made using the process: $$$[1]$$$.In the third test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[6,5,2,1,4,3]$$$, $$$[6,5,3,1,4,2]$$$.In the fourth test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[1,2,8,7,4,3,6,5]$$$, $$$[1,6,4,7,2,3,8,5]$$$.In the fifth test case, there is only one distinct permutation that can be made using the process: $$$[1,9,2,3,4,10,8,6,7,5]$$$.
Code:
import sys
input = sys.stdin.readline
class Solver1670C:
def __init__(self):
self.n = int(input())
self.a = list(map(int, input().split(' ')))
self.b = list(map(int, input().split(' ')))
self.d = list(map(int, input().split(' ')))
self.pos_a = [0 for _ in range(self.n+1)]
self.pos_b = [0 for _ in range(self.n+1)]
self.been = [0 for _ in range(self.n+1)]
self.mod = (10**9)+7
def solve(self):
for i in range(0, self.n):
self.pos_a[self.a[i]] = i
self.pos_b[self.b[i]] = i
for i in range(0, self.n):
if self.d[i] and self.been[i] == 0:
if self.d[i] == self.a[i]:
j = i
while self.been[j] == 0:
self.been[j] = 1
j = self.pos_a[self.b[j]]
else:
j = i
while self.been[j] == 0:
# TODO: Your code here
outp = 1
for i in range(0, self.n):
if self.been[i] == 0:
cnt = 0
j = i
while self.been[j] == 0:
self.been[j] = 1
j = self.pos_a[self.b[j]]
cnt += 1
if cnt >= 2:
outp = outp * 2 % self.mod
return outp
t = int(input())
while t:
t -= 1
cur = Solver1670C()
print(cur.solve())
|
import sys
input = sys.stdin.readline
class Solver1670C:
def __init__(self):
self.n = int(input())
self.a = list(map(int, input().split(' ')))
self.b = list(map(int, input().split(' ')))
self.d = list(map(int, input().split(' ')))
self.pos_a = [0 for _ in range(self.n+1)]
self.pos_b = [0 for _ in range(self.n+1)]
self.been = [0 for _ in range(self.n+1)]
self.mod = (10**9)+7
def solve(self):
for i in range(0, self.n):
self.pos_a[self.a[i]] = i
self.pos_b[self.b[i]] = i
for i in range(0, self.n):
if self.d[i] and self.been[i] == 0:
if self.d[i] == self.a[i]:
j = i
while self.been[j] == 0:
self.been[j] = 1
j = self.pos_a[self.b[j]]
else:
j = i
while self.been[j] == 0:
{{completion}}
outp = 1
for i in range(0, self.n):
if self.been[i] == 0:
cnt = 0
j = i
while self.been[j] == 0:
self.been[j] = 1
j = self.pos_a[self.b[j]]
cnt += 1
if cnt >= 2:
outp = outp * 2 % self.mod
return outp
t = int(input())
while t:
t -= 1
cur = Solver1670C()
print(cur.solve())
|
self.been[j] = 1
j = self.pos_b[self.a[j]]
|
[{"input": "9\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n2 0 1 0 0 0 0\n1\n1\n1\n0\n6\n1 5 2 4 6 3\n6 5 3 1 4 2\n6 0 0 0 0 0\n8\n1 6 4 7 2 3 8 5\n3 2 8 1 4 5 6 7\n1 0 0 7 0 3 0 5\n10\n1 8 6 2 4 7 9 3 10 5\n1 9 2 3 4 10 8 6 7 5\n1 9 2 3 4 10 8 6 7 5\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n0 0 0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 4 5\n0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 5 4\n0 0 0 0 0\n3\n1 2 3\n3 1 2\n0 0 0", "output": ["4\n1\n2\n2\n1\n8\n1\n2\n2"]}]
|
block_completion_006027
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: While searching for the pizza, baby Hosssam came across two permutations $$$a$$$ and $$$b$$$ of length $$$n$$$.Recall that a permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).Baby Hosssam forgot about the pizza and started playing around with the two permutations. While he was playing with them, some elements of the first permutation got mixed up with some elements of the second permutation, and to his surprise those elements also formed a permutation of size $$$n$$$.Specifically, he mixed up the permutations to form a new array $$$c$$$ in the following way. For each $$$i$$$ ($$$1\le i\le n$$$), he either made $$$c_i=a_i$$$ or $$$c_i=b_i$$$. The array $$$c$$$ is a permutation. You know permutations $$$a$$$, $$$b$$$, and values at some positions in $$$c$$$. Please count the number different permutations $$$c$$$ that are consistent with the described process and the given values. Since the answer can be large, print it modulo $$$10^9+7$$$.It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements.
Input Specification: The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$) β the length of the permutations. The next line contains $$$n$$$ distinct integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le n$$$) β the first permutation. The next line contains $$$n$$$ distinct integers $$$b_1,b_2,\ldots,b_n$$$ ($$$1\le b_i\le n$$$) β the second permutation. The next line contains $$$n$$$ distinct integers $$$d_1,d_2,\ldots,d_n$$$ ($$$d_i$$$ is either $$$0$$$, $$$a_i$$$, or $$$b_i$$$) β the description of the known values of $$$c$$$. If $$$d_i=0$$$, then there are no requirements on the value of $$$c_i$$$. Otherwise, it is required that $$$c_i=d_i$$$. It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$.
Output Specification: For each test case, print the number of possible permutations $$$c$$$, modulo $$$10^9+7$$$.
Notes: NoteIn the first test case, there are $$$4$$$ distinct permutation that can be made using the process: $$$[2,3,1,4,5,6,7]$$$, $$$[2,3,1,7,6,5,4]$$$, $$$[2,3,1,4,6,5,7]$$$, $$$[2,3,1,7,5,6,4]$$$.In the second test case, there is only one distinct permutation that can be made using the process: $$$[1]$$$.In the third test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[6,5,2,1,4,3]$$$, $$$[6,5,3,1,4,2]$$$.In the fourth test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[1,2,8,7,4,3,6,5]$$$, $$$[1,6,4,7,2,3,8,5]$$$.In the fifth test case, there is only one distinct permutation that can be made using the process: $$$[1,9,2,3,4,10,8,6,7,5]$$$.
Code:
m = 10**9+7
for _ in range(int(input())):
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
c = list(map(int,input().split()))
d={i:0 for i in range(1,n+1)}
for i in range(n):
d[c[i]]=1
dd={}
for i in range(n):
dd[a[i]]=i
ans = 1
for i in range(n):
if(c[i] != 0 or a[i]==b[i] or d[a[i]] == 1 or d[b[i]]==1):continue
j=dd[b[i]]; f=2
while(j!=i):
if(c[j]!=0):# TODO: Your code here
c[j]=1
j=dd[b[j]]
ans=(ans*f)%m
k=1
print(ans)
|
m = 10**9+7
for _ in range(int(input())):
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
c = list(map(int,input().split()))
d={i:0 for i in range(1,n+1)}
for i in range(n):
d[c[i]]=1
dd={}
for i in range(n):
dd[a[i]]=i
ans = 1
for i in range(n):
if(c[i] != 0 or a[i]==b[i] or d[a[i]] == 1 or d[b[i]]==1):continue
j=dd[b[i]]; f=2
while(j!=i):
if(c[j]!=0):{{completion}}
c[j]=1
j=dd[b[j]]
ans=(ans*f)%m
k=1
print(ans)
|
f=1
|
[{"input": "9\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n2 0 1 0 0 0 0\n1\n1\n1\n0\n6\n1 5 2 4 6 3\n6 5 3 1 4 2\n6 0 0 0 0 0\n8\n1 6 4 7 2 3 8 5\n3 2 8 1 4 5 6 7\n1 0 0 7 0 3 0 5\n10\n1 8 6 2 4 7 9 3 10 5\n1 9 2 3 4 10 8 6 7 5\n1 9 2 3 4 10 8 6 7 5\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n0 0 0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 4 5\n0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 5 4\n0 0 0 0 0\n3\n1 2 3\n3 1 2\n0 0 0", "output": ["4\n1\n2\n2\n1\n8\n1\n2\n2"]}]
|
block_completion_006028
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: While searching for the pizza, baby Hosssam came across two permutations $$$a$$$ and $$$b$$$ of length $$$n$$$.Recall that a permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).Baby Hosssam forgot about the pizza and started playing around with the two permutations. While he was playing with them, some elements of the first permutation got mixed up with some elements of the second permutation, and to his surprise those elements also formed a permutation of size $$$n$$$.Specifically, he mixed up the permutations to form a new array $$$c$$$ in the following way. For each $$$i$$$ ($$$1\le i\le n$$$), he either made $$$c_i=a_i$$$ or $$$c_i=b_i$$$. The array $$$c$$$ is a permutation. You know permutations $$$a$$$, $$$b$$$, and values at some positions in $$$c$$$. Please count the number different permutations $$$c$$$ that are consistent with the described process and the given values. Since the answer can be large, print it modulo $$$10^9+7$$$.It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements.
Input Specification: The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$) β the length of the permutations. The next line contains $$$n$$$ distinct integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le n$$$) β the first permutation. The next line contains $$$n$$$ distinct integers $$$b_1,b_2,\ldots,b_n$$$ ($$$1\le b_i\le n$$$) β the second permutation. The next line contains $$$n$$$ distinct integers $$$d_1,d_2,\ldots,d_n$$$ ($$$d_i$$$ is either $$$0$$$, $$$a_i$$$, or $$$b_i$$$) β the description of the known values of $$$c$$$. If $$$d_i=0$$$, then there are no requirements on the value of $$$c_i$$$. Otherwise, it is required that $$$c_i=d_i$$$. It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$.
Output Specification: For each test case, print the number of possible permutations $$$c$$$, modulo $$$10^9+7$$$.
Notes: NoteIn the first test case, there are $$$4$$$ distinct permutation that can be made using the process: $$$[2,3,1,4,5,6,7]$$$, $$$[2,3,1,7,6,5,4]$$$, $$$[2,3,1,4,6,5,7]$$$, $$$[2,3,1,7,5,6,4]$$$.In the second test case, there is only one distinct permutation that can be made using the process: $$$[1]$$$.In the third test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[6,5,2,1,4,3]$$$, $$$[6,5,3,1,4,2]$$$.In the fourth test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[1,2,8,7,4,3,6,5]$$$, $$$[1,6,4,7,2,3,8,5]$$$.In the fifth test case, there is only one distinct permutation that can be made using the process: $$$[1,9,2,3,4,10,8,6,7,5]$$$.
Code:
from sys import stdin, stdout
from functools import reduce
M = int(10**9 + 7)
def solve(a, b, c, n):
vis = [False]*n
ans = []
g = {a[i]:(b[i], c[i]) for i in range(n)}
for i in range(n):
t, ass, j = 0, False, i
while not vis[j]:
vis[j] = True
if g[j + 1][1] != 0: # TODO: Your code here
j = g[j + 1][0] - 1
t += 1
#print(t, ass, j)
if not ass and t > 1: ans.append(2)
else: ans.append(1)
#print(ans)
if not ans: return 0
#print(reduce(lambda x, y: (x*y)%M, ans, 1) % M)
return reduce(lambda x, y: (x*y)%M, ans, 1) % M
for i in range(int(stdin.readline().strip())):
n = int(stdin.readline().strip())
a = list(map(int, stdin.readline().strip().split()))
b = list(map(int, stdin.readline().strip().split()))
c = list(map(int, stdin.readline().strip().split()))
out_ = solve(a, b, c, n)
stdout.write(f"{out_}\n")
|
from sys import stdin, stdout
from functools import reduce
M = int(10**9 + 7)
def solve(a, b, c, n):
vis = [False]*n
ans = []
g = {a[i]:(b[i], c[i]) for i in range(n)}
for i in range(n):
t, ass, j = 0, False, i
while not vis[j]:
vis[j] = True
if g[j + 1][1] != 0: {{completion}}
j = g[j + 1][0] - 1
t += 1
#print(t, ass, j)
if not ass and t > 1: ans.append(2)
else: ans.append(1)
#print(ans)
if not ans: return 0
#print(reduce(lambda x, y: (x*y)%M, ans, 1) % M)
return reduce(lambda x, y: (x*y)%M, ans, 1) % M
for i in range(int(stdin.readline().strip())):
n = int(stdin.readline().strip())
a = list(map(int, stdin.readline().strip().split()))
b = list(map(int, stdin.readline().strip().split()))
c = list(map(int, stdin.readline().strip().split()))
out_ = solve(a, b, c, n)
stdout.write(f"{out_}\n")
|
ass = True
|
[{"input": "9\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n2 0 1 0 0 0 0\n1\n1\n1\n0\n6\n1 5 2 4 6 3\n6 5 3 1 4 2\n6 0 0 0 0 0\n8\n1 6 4 7 2 3 8 5\n3 2 8 1 4 5 6 7\n1 0 0 7 0 3 0 5\n10\n1 8 6 2 4 7 9 3 10 5\n1 9 2 3 4 10 8 6 7 5\n1 9 2 3 4 10 8 6 7 5\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n0 0 0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 4 5\n0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 5 4\n0 0 0 0 0\n3\n1 2 3\n3 1 2\n0 0 0", "output": ["4\n1\n2\n2\n1\n8\n1\n2\n2"]}]
|
block_completion_006029
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: While searching for the pizza, baby Hosssam came across two permutations $$$a$$$ and $$$b$$$ of length $$$n$$$.Recall that a permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).Baby Hosssam forgot about the pizza and started playing around with the two permutations. While he was playing with them, some elements of the first permutation got mixed up with some elements of the second permutation, and to his surprise those elements also formed a permutation of size $$$n$$$.Specifically, he mixed up the permutations to form a new array $$$c$$$ in the following way. For each $$$i$$$ ($$$1\le i\le n$$$), he either made $$$c_i=a_i$$$ or $$$c_i=b_i$$$. The array $$$c$$$ is a permutation. You know permutations $$$a$$$, $$$b$$$, and values at some positions in $$$c$$$. Please count the number different permutations $$$c$$$ that are consistent with the described process and the given values. Since the answer can be large, print it modulo $$$10^9+7$$$.It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements.
Input Specification: The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$) β the length of the permutations. The next line contains $$$n$$$ distinct integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le n$$$) β the first permutation. The next line contains $$$n$$$ distinct integers $$$b_1,b_2,\ldots,b_n$$$ ($$$1\le b_i\le n$$$) β the second permutation. The next line contains $$$n$$$ distinct integers $$$d_1,d_2,\ldots,d_n$$$ ($$$d_i$$$ is either $$$0$$$, $$$a_i$$$, or $$$b_i$$$) β the description of the known values of $$$c$$$. If $$$d_i=0$$$, then there are no requirements on the value of $$$c_i$$$. Otherwise, it is required that $$$c_i=d_i$$$. It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$.
Output Specification: For each test case, print the number of possible permutations $$$c$$$, modulo $$$10^9+7$$$.
Notes: NoteIn the first test case, there are $$$4$$$ distinct permutation that can be made using the process: $$$[2,3,1,4,5,6,7]$$$, $$$[2,3,1,7,6,5,4]$$$, $$$[2,3,1,4,6,5,7]$$$, $$$[2,3,1,7,5,6,4]$$$.In the second test case, there is only one distinct permutation that can be made using the process: $$$[1]$$$.In the third test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[6,5,2,1,4,3]$$$, $$$[6,5,3,1,4,2]$$$.In the fourth test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[1,2,8,7,4,3,6,5]$$$, $$$[1,6,4,7,2,3,8,5]$$$.In the fifth test case, there is only one distinct permutation that can be made using the process: $$$[1,9,2,3,4,10,8,6,7,5]$$$.
Code:
from sys import stdin, setrecursionlimit
input = stdin.readline
from bisect import bisect_left, bisect_right
from collections import deque
from functools import lru_cache, reduce
from heapq import heappush, heappop
from math import sqrt, ceil, floor, log2
T = int(input())
def rl(t = int):
return list(map(t, input().split()))
MOD = 10**9 + 7
for t in range(1, T + 1):
n = int(input())
a = rl()
b = rl()
d = rl()
m = {v:i for i,v in enumerate(a)}
for i in range(n):
if a[i] == b[i]:
d[i] = a[i]
ret = 1
seen = set()
for i,cur in enumerate(a):
if cur in seen:
continue
mul = 2
while cur not in seen:
if d[i] != 0:
# TODO: Your code here
seen.add(cur)
#print(i, cur)
cur = b[i]
i = m[cur]
#print(seen, mul)
ret = (ret * mul) % MOD
print(ret)
|
from sys import stdin, setrecursionlimit
input = stdin.readline
from bisect import bisect_left, bisect_right
from collections import deque
from functools import lru_cache, reduce
from heapq import heappush, heappop
from math import sqrt, ceil, floor, log2
T = int(input())
def rl(t = int):
return list(map(t, input().split()))
MOD = 10**9 + 7
for t in range(1, T + 1):
n = int(input())
a = rl()
b = rl()
d = rl()
m = {v:i for i,v in enumerate(a)}
for i in range(n):
if a[i] == b[i]:
d[i] = a[i]
ret = 1
seen = set()
for i,cur in enumerate(a):
if cur in seen:
continue
mul = 2
while cur not in seen:
if d[i] != 0:
{{completion}}
seen.add(cur)
#print(i, cur)
cur = b[i]
i = m[cur]
#print(seen, mul)
ret = (ret * mul) % MOD
print(ret)
|
mul = 1
|
[{"input": "9\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n2 0 1 0 0 0 0\n1\n1\n1\n0\n6\n1 5 2 4 6 3\n6 5 3 1 4 2\n6 0 0 0 0 0\n8\n1 6 4 7 2 3 8 5\n3 2 8 1 4 5 6 7\n1 0 0 7 0 3 0 5\n10\n1 8 6 2 4 7 9 3 10 5\n1 9 2 3 4 10 8 6 7 5\n1 9 2 3 4 10 8 6 7 5\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n0 0 0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 4 5\n0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 5 4\n0 0 0 0 0\n3\n1 2 3\n3 1 2\n0 0 0", "output": ["4\n1\n2\n2\n1\n8\n1\n2\n2"]}]
|
block_completion_006030
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: While searching for the pizza, baby Hosssam came across two permutations $$$a$$$ and $$$b$$$ of length $$$n$$$.Recall that a permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).Baby Hosssam forgot about the pizza and started playing around with the two permutations. While he was playing with them, some elements of the first permutation got mixed up with some elements of the second permutation, and to his surprise those elements also formed a permutation of size $$$n$$$.Specifically, he mixed up the permutations to form a new array $$$c$$$ in the following way. For each $$$i$$$ ($$$1\le i\le n$$$), he either made $$$c_i=a_i$$$ or $$$c_i=b_i$$$. The array $$$c$$$ is a permutation. You know permutations $$$a$$$, $$$b$$$, and values at some positions in $$$c$$$. Please count the number different permutations $$$c$$$ that are consistent with the described process and the given values. Since the answer can be large, print it modulo $$$10^9+7$$$.It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements.
Input Specification: The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$) β the length of the permutations. The next line contains $$$n$$$ distinct integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le n$$$) β the first permutation. The next line contains $$$n$$$ distinct integers $$$b_1,b_2,\ldots,b_n$$$ ($$$1\le b_i\le n$$$) β the second permutation. The next line contains $$$n$$$ distinct integers $$$d_1,d_2,\ldots,d_n$$$ ($$$d_i$$$ is either $$$0$$$, $$$a_i$$$, or $$$b_i$$$) β the description of the known values of $$$c$$$. If $$$d_i=0$$$, then there are no requirements on the value of $$$c_i$$$. Otherwise, it is required that $$$c_i=d_i$$$. It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$.
Output Specification: For each test case, print the number of possible permutations $$$c$$$, modulo $$$10^9+7$$$.
Notes: NoteIn the first test case, there are $$$4$$$ distinct permutation that can be made using the process: $$$[2,3,1,4,5,6,7]$$$, $$$[2,3,1,7,6,5,4]$$$, $$$[2,3,1,4,6,5,7]$$$, $$$[2,3,1,7,5,6,4]$$$.In the second test case, there is only one distinct permutation that can be made using the process: $$$[1]$$$.In the third test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[6,5,2,1,4,3]$$$, $$$[6,5,3,1,4,2]$$$.In the fourth test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[1,2,8,7,4,3,6,5]$$$, $$$[1,6,4,7,2,3,8,5]$$$.In the fifth test case, there is only one distinct permutation that can be made using the process: $$$[1,9,2,3,4,10,8,6,7,5]$$$.
Code:
import math,sys;input=sys.stdin.readline;S=lambda:input().rstrip();I=lambda:int(S());M=lambda:map(int,S().split());L=lambda:list(M());mod1=1000000007;mod2=998244353
for _ in range(I()):
n=I();a=L();b=L();d=L();l=[]
for i in range(n):l.append([a[i],b[i],d[i]])
l.sort(key=lambda x:x[0]);s=set();ans=1
for i in range(n):
if i not in s:
d={};cur=i;f=0
while True:
d[l[cur][0]]=d.get(l[cur][0],0)+1
d[l[cur][1]]=d.get(l[cur][1],0)+1
s.add(cur)
if l[cur][2]!=0 or l[cur][1]==l[cur][0]:# TODO: Your code here
if d[l[cur][1]]==2:break
cur=l[cur][1]-1
if f!=1:ans=(ans*2)%mod1
print(ans)
|
import math,sys;input=sys.stdin.readline;S=lambda:input().rstrip();I=lambda:int(S());M=lambda:map(int,S().split());L=lambda:list(M());mod1=1000000007;mod2=998244353
for _ in range(I()):
n=I();a=L();b=L();d=L();l=[]
for i in range(n):l.append([a[i],b[i],d[i]])
l.sort(key=lambda x:x[0]);s=set();ans=1
for i in range(n):
if i not in s:
d={};cur=i;f=0
while True:
d[l[cur][0]]=d.get(l[cur][0],0)+1
d[l[cur][1]]=d.get(l[cur][1],0)+1
s.add(cur)
if l[cur][2]!=0 or l[cur][1]==l[cur][0]:{{completion}}
if d[l[cur][1]]==2:break
cur=l[cur][1]-1
if f!=1:ans=(ans*2)%mod1
print(ans)
|
f=1
|
[{"input": "9\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n2 0 1 0 0 0 0\n1\n1\n1\n0\n6\n1 5 2 4 6 3\n6 5 3 1 4 2\n6 0 0 0 0 0\n8\n1 6 4 7 2 3 8 5\n3 2 8 1 4 5 6 7\n1 0 0 7 0 3 0 5\n10\n1 8 6 2 4 7 9 3 10 5\n1 9 2 3 4 10 8 6 7 5\n1 9 2 3 4 10 8 6 7 5\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n0 0 0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 4 5\n0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 5 4\n0 0 0 0 0\n3\n1 2 3\n3 1 2\n0 0 0", "output": ["4\n1\n2\n2\n1\n8\n1\n2\n2"]}]
|
block_completion_006031
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: While searching for the pizza, baby Hosssam came across two permutations $$$a$$$ and $$$b$$$ of length $$$n$$$.Recall that a permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).Baby Hosssam forgot about the pizza and started playing around with the two permutations. While he was playing with them, some elements of the first permutation got mixed up with some elements of the second permutation, and to his surprise those elements also formed a permutation of size $$$n$$$.Specifically, he mixed up the permutations to form a new array $$$c$$$ in the following way. For each $$$i$$$ ($$$1\le i\le n$$$), he either made $$$c_i=a_i$$$ or $$$c_i=b_i$$$. The array $$$c$$$ is a permutation. You know permutations $$$a$$$, $$$b$$$, and values at some positions in $$$c$$$. Please count the number different permutations $$$c$$$ that are consistent with the described process and the given values. Since the answer can be large, print it modulo $$$10^9+7$$$.It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements.
Input Specification: The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^5$$$) β the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^5$$$) β the length of the permutations. The next line contains $$$n$$$ distinct integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le n$$$) β the first permutation. The next line contains $$$n$$$ distinct integers $$$b_1,b_2,\ldots,b_n$$$ ($$$1\le b_i\le n$$$) β the second permutation. The next line contains $$$n$$$ distinct integers $$$d_1,d_2,\ldots,d_n$$$ ($$$d_i$$$ is either $$$0$$$, $$$a_i$$$, or $$$b_i$$$) β the description of the known values of $$$c$$$. If $$$d_i=0$$$, then there are no requirements on the value of $$$c_i$$$. Otherwise, it is required that $$$c_i=d_i$$$. It is guaranteed that there exists at least one permutation $$$c$$$ that satisfies all the requirements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$.
Output Specification: For each test case, print the number of possible permutations $$$c$$$, modulo $$$10^9+7$$$.
Notes: NoteIn the first test case, there are $$$4$$$ distinct permutation that can be made using the process: $$$[2,3,1,4,5,6,7]$$$, $$$[2,3,1,7,6,5,4]$$$, $$$[2,3,1,4,6,5,7]$$$, $$$[2,3,1,7,5,6,4]$$$.In the second test case, there is only one distinct permutation that can be made using the process: $$$[1]$$$.In the third test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[6,5,2,1,4,3]$$$, $$$[6,5,3,1,4,2]$$$.In the fourth test case, there are $$$2$$$ distinct permutation that can be made using the process: $$$[1,2,8,7,4,3,6,5]$$$, $$$[1,6,4,7,2,3,8,5]$$$.In the fifth test case, there is only one distinct permutation that can be made using the process: $$$[1,9,2,3,4,10,8,6,7,5]$$$.
Code:
import math,sys;input=sys.stdin.readline;S=lambda:input().rstrip();I=lambda:int(S());M=lambda:map(int,S().split());L=lambda:list(M());mod1=1000000007;mod2=998244353
for _ in range(I()):
n=I();a=L();b=L();d=L();l=[]
for i in range(n):l.append([a[i],b[i],d[i]])
l.sort(key=lambda x:x[0]);s=set();ans=1
for i in range(n):
if i not in s:
d={};cur=i;f=0
while True:
d[l[cur][0]]=d.get(l[cur][0],0)+1
d[l[cur][1]]=d.get(l[cur][1],0)+1
s.add(cur)
if l[cur][2]!=0 or l[cur][1]==l[cur][0]:f=1
if d[l[cur][1]]==2:# TODO: Your code here
cur=l[cur][1]-1
if f!=1:ans=(ans*2)%mod1
print(ans)
|
import math,sys;input=sys.stdin.readline;S=lambda:input().rstrip();I=lambda:int(S());M=lambda:map(int,S().split());L=lambda:list(M());mod1=1000000007;mod2=998244353
for _ in range(I()):
n=I();a=L();b=L();d=L();l=[]
for i in range(n):l.append([a[i],b[i],d[i]])
l.sort(key=lambda x:x[0]);s=set();ans=1
for i in range(n):
if i not in s:
d={};cur=i;f=0
while True:
d[l[cur][0]]=d.get(l[cur][0],0)+1
d[l[cur][1]]=d.get(l[cur][1],0)+1
s.add(cur)
if l[cur][2]!=0 or l[cur][1]==l[cur][0]:f=1
if d[l[cur][1]]==2:{{completion}}
cur=l[cur][1]-1
if f!=1:ans=(ans*2)%mod1
print(ans)
|
break
|
[{"input": "9\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n2 0 1 0 0 0 0\n1\n1\n1\n0\n6\n1 5 2 4 6 3\n6 5 3 1 4 2\n6 0 0 0 0 0\n8\n1 6 4 7 2 3 8 5\n3 2 8 1 4 5 6 7\n1 0 0 7 0 3 0 5\n10\n1 8 6 2 4 7 9 3 10 5\n1 9 2 3 4 10 8 6 7 5\n1 9 2 3 4 10 8 6 7 5\n7\n1 2 3 4 5 6 7\n2 3 1 7 6 5 4\n0 0 0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 4 5\n0 0 0 0 0\n5\n1 2 3 4 5\n1 2 3 5 4\n0 0 0 0 0\n3\n1 2 3\n3 1 2\n0 0 0", "output": ["4\n1\n2\n2\n1\n8\n1\n2\n2"]}]
|
block_completion_006032
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: One day Prof. Slim decided to leave the kingdom of the GUC to join the kingdom of the GIU. He was given an easy online assessment to solve before joining the GIU. Citizens of the GUC were happy sad to see the prof leaving, so they decided to hack into the system and change the online assessment into a harder one so that he stays at the GUC. After a long argument, they decided to change it into the following problem.Given an array of $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$, where $$$a_{i} \neq 0$$$, check if you can make this array sorted by using the following operation any number of times (possibly zero). An array is sorted if its elements are arranged in a non-decreasing order. select two indices $$$i$$$ and $$$j$$$ ($$$1 \le i,j \le n$$$) such that $$$a_i$$$ and $$$a_j$$$ have different signs. In other words, one must be positive and one must be negative. swap the signs of $$$a_{i}$$$ and $$$a_{j}$$$. For example if you select $$$a_i=3$$$ and $$$a_j=-2$$$, then they will change to $$$a_i=-3$$$ and $$$a_j=2$$$. Prof. Slim saw that the problem is still too easy and isn't worth his time, so he decided to give it to you to solve.
Input Specification: The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) β the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) β the length of the array $$$a$$$. The next line contain $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_{i} \le 10^9$$$, $$$a_{i} \neq 0$$$) separated by spaces describing elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.
Output Specification: For each test case, print "YES" if the array can be sorted in the non-decreasing order, otherwise print "NO". You can print each letter in any case (upper or lower).
Notes: NoteIn the first test case, there is no way to make the array sorted using the operation any number of times.In the second test case, the array is already sorted.In the third test case, we can swap the sign of the $$$1$$$-st element with the sign of the $$$5$$$-th element, and the sign of the $$$3$$$-rd element with the sign of the $$$6$$$-th element, this way the array will be sorted.In the fourth test case, there is no way to make the array sorted using the operation any number of times.
Code:
import sys
ls = []
for l in sys.stdin:
lst = l.rstrip('\n')
if len(lst) > 0:
ls.append(lst)
for l in ls:
sys.stderr.write(l + ('\n'))
sys.stderr.write("-- output --\n")
def solve(n, a):
k = sum([0 if ai > 0 else 1 for ai in a])
b = [abs(a[i]) if i >= k else -abs(a[i]) for i in range(n)]
for i in range(n-1):
if b[i] > b[i+1]:
# TODO: Your code here
return "YES"
for i in range(1, len(ls)-1, 2):
n = int(ls[i])
a = [int(x) for x in ls[i+1].split(' ')]
print(solve(n, a))
|
import sys
ls = []
for l in sys.stdin:
lst = l.rstrip('\n')
if len(lst) > 0:
ls.append(lst)
for l in ls:
sys.stderr.write(l + ('\n'))
sys.stderr.write("-- output --\n")
def solve(n, a):
k = sum([0 if ai > 0 else 1 for ai in a])
b = [abs(a[i]) if i >= k else -abs(a[i]) for i in range(n)]
for i in range(n-1):
if b[i] > b[i+1]:
{{completion}}
return "YES"
for i in range(1, len(ls)-1, 2):
n = int(ls[i])
a = [int(x) for x in ls[i+1].split(' ')]
print(solve(n, a))
|
return "NO"
|
[{"input": "4\n\n7\n\n7 3 2 -11 -13 -17 -23\n\n6\n\n4 10 25 47 71 96\n\n6\n\n71 -35 7 -4 -11 -25\n\n6\n\n-45 9 -48 -67 -55 7", "output": ["NO\nYES\nYES\nNO"]}]
|
block_completion_006045
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: During their training for the ICPC competitions, team "Jee You See" stumbled upon a very basic counting problem. After many "Wrong answer" verdicts, they finally decided to give up and destroy turn-off the PC. Now they want your help in up-solving the problem.You are given 4 integers $$$n$$$, $$$l$$$, $$$r$$$, and $$$z$$$. Count the number of arrays $$$a$$$ of length $$$n$$$ containing non-negative integers such that: $$$l\le a_1+a_2+\ldots+a_n\le r$$$, and $$$a_1\oplus a_2 \oplus \ldots\oplus a_n=z$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Since the answer can be large, print it modulo $$$10^9+7$$$.
Input Specification: The only line contains four integers $$$n$$$, $$$l$$$, $$$r$$$, $$$z$$$ ($$$1 \le n \le 1000$$$, $$$1\le l\le r\le 10^{18}$$$, $$$1\le z\le 10^{18}$$$).
Output Specification: Print the number of arrays $$$a$$$ satisfying all requirements modulo $$$10^9+7$$$.
Notes: NoteThe following arrays satisfy the conditions for the first sample: $$$[1, 0, 0]$$$; $$$[0, 1, 0]$$$; $$$[3, 2, 0]$$$; $$$[2, 3, 0]$$$; $$$[0, 0, 1]$$$; $$$[1, 1, 1]$$$; $$$[2, 2, 1]$$$; $$$[3, 0, 2]$$$; $$$[2, 1, 2]$$$; $$$[1, 2, 2]$$$; $$$[0, 3, 2]$$$; $$$[2, 0, 3]$$$; $$$[0, 2, 3]$$$. The following arrays satisfy the conditions for the second sample: $$$[2, 0, 0, 0]$$$; $$$[0, 2, 0, 0]$$$; $$$[0, 0, 2, 0]$$$; $$$[0, 0, 0, 2]$$$.
Code:
n,l,r,z=map(int,input().split())
mod=10**9+7
#############################
#############
cnb_max=10**5
#############
kai=[1]*(cnb_max+1)
rkai=[1]*(cnb_max+1)
for i in range(cnb_max):
kai[i+1]=kai[i]*(i+1)%mod
rkai[cnb_max]=pow(kai[cnb_max],mod-2,mod)
for i in range(cnb_max):
rkai[cnb_max-1-i]=rkai[cnb_max-i]*(cnb_max-i)%mod
def cnb(x,y):
if y>x:
return 0
if x<0:return 0
if y<0:return 0
return (kai[x]*rkai[y]%mod)*rkai[x-y]%mod
def inv(n):
return kai[n-1]*rkai[n]%mod
##################################
def f(r,z):
dp=[0]*(2*n+10)
dp[0]=1
for i in range(65):
newdp=[0]*(2*n+10)
for j in range(2*n+5):
dp[j]%=mod
if dp[j]==0:continue
for cnt in range(z&1,n+1,2):
if j+cnt>r:# TODO: Your code here
d=0
if (r&1)==0 and (j+cnt)%2==1:d=1
newdp[(j+cnt)//2+d]+=dp[j]*cnb(n,cnt)%mod
z//=2
r//=2
dp=newdp[:]
return dp[0]%mod
print((f(r,z)-f(l-1,z))%mod)
|
n,l,r,z=map(int,input().split())
mod=10**9+7
#############################
#############
cnb_max=10**5
#############
kai=[1]*(cnb_max+1)
rkai=[1]*(cnb_max+1)
for i in range(cnb_max):
kai[i+1]=kai[i]*(i+1)%mod
rkai[cnb_max]=pow(kai[cnb_max],mod-2,mod)
for i in range(cnb_max):
rkai[cnb_max-1-i]=rkai[cnb_max-i]*(cnb_max-i)%mod
def cnb(x,y):
if y>x:
return 0
if x<0:return 0
if y<0:return 0
return (kai[x]*rkai[y]%mod)*rkai[x-y]%mod
def inv(n):
return kai[n-1]*rkai[n]%mod
##################################
def f(r,z):
dp=[0]*(2*n+10)
dp[0]=1
for i in range(65):
newdp=[0]*(2*n+10)
for j in range(2*n+5):
dp[j]%=mod
if dp[j]==0:continue
for cnt in range(z&1,n+1,2):
if j+cnt>r:{{completion}}
d=0
if (r&1)==0 and (j+cnt)%2==1:d=1
newdp[(j+cnt)//2+d]+=dp[j]*cnb(n,cnt)%mod
z//=2
r//=2
dp=newdp[:]
return dp[0]%mod
print((f(r,z)-f(l-1,z))%mod)
|
break
|
[{"input": "3 1 5 1", "output": ["13"]}, {"input": "4 1 3 2", "output": ["4"]}, {"input": "2 1 100000 15629", "output": ["49152"]}, {"input": "100 56 89 66", "output": ["981727503"]}]
|
block_completion_006063
|
block
|
python
|
Complete the code in python to solve this programming problem:
Description: During their training for the ICPC competitions, team "Jee You See" stumbled upon a very basic counting problem. After many "Wrong answer" verdicts, they finally decided to give up and destroy turn-off the PC. Now they want your help in up-solving the problem.You are given 4 integers $$$n$$$, $$$l$$$, $$$r$$$, and $$$z$$$. Count the number of arrays $$$a$$$ of length $$$n$$$ containing non-negative integers such that: $$$l\le a_1+a_2+\ldots+a_n\le r$$$, and $$$a_1\oplus a_2 \oplus \ldots\oplus a_n=z$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. Since the answer can be large, print it modulo $$$10^9+7$$$.
Input Specification: The only line contains four integers $$$n$$$, $$$l$$$, $$$r$$$, $$$z$$$ ($$$1 \le n \le 1000$$$, $$$1\le l\le r\le 10^{18}$$$, $$$1\le z\le 10^{18}$$$).
Output Specification: Print the number of arrays $$$a$$$ satisfying all requirements modulo $$$10^9+7$$$.
Notes: NoteThe following arrays satisfy the conditions for the first sample: $$$[1, 0, 0]$$$; $$$[0, 1, 0]$$$; $$$[3, 2, 0]$$$; $$$[2, 3, 0]$$$; $$$[0, 0, 1]$$$; $$$[1, 1, 1]$$$; $$$[2, 2, 1]$$$; $$$[3, 0, 2]$$$; $$$[2, 1, 2]$$$; $$$[1, 2, 2]$$$; $$$[0, 3, 2]$$$; $$$[2, 0, 3]$$$; $$$[0, 2, 3]$$$. The following arrays satisfy the conditions for the second sample: $$$[2, 0, 0, 0]$$$; $$$[0, 2, 0, 0]$$$; $$$[0, 0, 2, 0]$$$; $$$[0, 0, 0, 2]$$$.
Code:
n,l,r,z=map(int,input().split())
mod=10**9+7
#############################
#############
cnb_max=10**5
#############
kai=[1]*(cnb_max+1)
rkai=[1]*(cnb_max+1)
for i in range(cnb_max):
kai[i+1]=kai[i]*(i+1)%mod
rkai[cnb_max]=pow(kai[cnb_max],mod-2,mod)
for i in range(cnb_max):
rkai[cnb_max-1-i]=rkai[cnb_max-i]*(cnb_max-i)%mod
def cnb(x,y):
if y>x:
return 0
if x<0:return 0
if y<0:return 0
return (kai[x]*rkai[y]%mod)*rkai[x-y]%mod
def inv(n):
return kai[n-1]*rkai[n]%mod
##################################
def f(r,z):
dp=[0]*(2*n+10)
dp[0]=1
for i in range(65):
newdp=[0]*(2*n+10)
for j in range(2*n+5):
dp[j]%=mod
if dp[j]==0:continue
for cnt in range(z&1,n+1,2):
if j+cnt>r:break
d=0
if (r&1)==0 and (j+cnt)%2==1:# TODO: Your code here
newdp[(j+cnt)//2+d]+=dp[j]*cnb(n,cnt)%mod
z//=2
r//=2
dp=newdp[:]
return dp[0]%mod
print((f(r,z)-f(l-1,z))%mod)
|
n,l,r,z=map(int,input().split())
mod=10**9+7
#############################
#############
cnb_max=10**5
#############
kai=[1]*(cnb_max+1)
rkai=[1]*(cnb_max+1)
for i in range(cnb_max):
kai[i+1]=kai[i]*(i+1)%mod
rkai[cnb_max]=pow(kai[cnb_max],mod-2,mod)
for i in range(cnb_max):
rkai[cnb_max-1-i]=rkai[cnb_max-i]*(cnb_max-i)%mod
def cnb(x,y):
if y>x:
return 0
if x<0:return 0
if y<0:return 0
return (kai[x]*rkai[y]%mod)*rkai[x-y]%mod
def inv(n):
return kai[n-1]*rkai[n]%mod
##################################
def f(r,z):
dp=[0]*(2*n+10)
dp[0]=1
for i in range(65):
newdp=[0]*(2*n+10)
for j in range(2*n+5):
dp[j]%=mod
if dp[j]==0:continue
for cnt in range(z&1,n+1,2):
if j+cnt>r:break
d=0
if (r&1)==0 and (j+cnt)%2==1:{{completion}}
newdp[(j+cnt)//2+d]+=dp[j]*cnb(n,cnt)%mod
z//=2
r//=2
dp=newdp[:]
return dp[0]%mod
print((f(r,z)-f(l-1,z))%mod)
|
d=1
|
[{"input": "3 1 5 1", "output": ["13"]}, {"input": "4 1 3 2", "output": ["4"]}, {"input": "2 1 100000 15629", "output": ["49152"]}, {"input": "100 56 89 66", "output": ["981727503"]}]
|
block_completion_006064
|
block
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.