text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has 26 tasks. Each task is designated by a capital letter of the Latin alphabet.
The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot return to the previous task.
Polycarp can only solve one task during the day. Every day he wrote down what task he solved. Now the teacher wants to know if Polycarp followed his advice.
For example, if Polycarp solved tasks in the following order: "DDBBCCCBBEZ", then the teacher will see that on the third day Polycarp began to solve the task 'B', then on the fifth day he got distracted and began to solve the task 'C', on the eighth day Polycarp returned to the task 'B'. Other examples of when the teacher is suspicious: "BAB", "AABBCCDDEEBZZ" and "AAAAZAAAAA".
If Polycarp solved the tasks as follows: "FFGZZZY", then the teacher cannot have any suspicions. Please note that Polycarp is not obligated to solve all tasks. Other examples of when the teacher doesn't have any suspicious: "BA", "AFFFCC" and "YYYYY".
Help Polycarp find out if his teacher might be suspicious.
Input
The first line contains an integer t (1 ≤ t ≤ 1000). Then t test cases follow.
The first line of each test case contains one integer n (1 ≤ n ≤ 50) — the number of days during which Polycarp solved tasks.
The second line contains a string of length n, consisting of uppercase Latin letters, which is the order in which Polycarp solved the tasks.
Output
For each test case output:
* "YES", if the teacher cannot be suspicious;
* "NO", otherwise.
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
3
ABA
11
DDBBCCCBBEZ
7
FFGZZZY
1
Z
2
AB
Output
NO
NO
YES
YES
YES
Submitted Solution:
```
for i in range(int(input())):
n = int(input())
s = input()
for i in range(len(s)):
if i <= len(s) - 2 and s[i] != s[i+1]:
if s[i] in s[i+1:]:
print("NO")
break
else:
print("YES")
```
Yes
| 10,200 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has 26 tasks. Each task is designated by a capital letter of the Latin alphabet.
The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot return to the previous task.
Polycarp can only solve one task during the day. Every day he wrote down what task he solved. Now the teacher wants to know if Polycarp followed his advice.
For example, if Polycarp solved tasks in the following order: "DDBBCCCBBEZ", then the teacher will see that on the third day Polycarp began to solve the task 'B', then on the fifth day he got distracted and began to solve the task 'C', on the eighth day Polycarp returned to the task 'B'. Other examples of when the teacher is suspicious: "BAB", "AABBCCDDEEBZZ" and "AAAAZAAAAA".
If Polycarp solved the tasks as follows: "FFGZZZY", then the teacher cannot have any suspicions. Please note that Polycarp is not obligated to solve all tasks. Other examples of when the teacher doesn't have any suspicious: "BA", "AFFFCC" and "YYYYY".
Help Polycarp find out if his teacher might be suspicious.
Input
The first line contains an integer t (1 ≤ t ≤ 1000). Then t test cases follow.
The first line of each test case contains one integer n (1 ≤ n ≤ 50) — the number of days during which Polycarp solved tasks.
The second line contains a string of length n, consisting of uppercase Latin letters, which is the order in which Polycarp solved the tasks.
Output
For each test case output:
* "YES", if the teacher cannot be suspicious;
* "NO", otherwise.
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
3
ABA
11
DDBBCCCBBEZ
7
FFGZZZY
1
Z
2
AB
Output
NO
NO
YES
YES
YES
Submitted Solution:
```
def main():
t = int(input())
for _ in range(1, t+1):
n = int(input())
s = input()
unique = set()
temp = ''
not_suspicious = True
for c in s:
if c == temp:
pass
else:
if ord(c) in unique:
not_suspicious = False
break
else:
temp = c
unique.add(ord(c))
if not_suspicious:
print('YES')
else:
print('NO')
if __name__ == '__main__': main()
```
Yes
| 10,201 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has 26 tasks. Each task is designated by a capital letter of the Latin alphabet.
The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot return to the previous task.
Polycarp can only solve one task during the day. Every day he wrote down what task he solved. Now the teacher wants to know if Polycarp followed his advice.
For example, if Polycarp solved tasks in the following order: "DDBBCCCBBEZ", then the teacher will see that on the third day Polycarp began to solve the task 'B', then on the fifth day he got distracted and began to solve the task 'C', on the eighth day Polycarp returned to the task 'B'. Other examples of when the teacher is suspicious: "BAB", "AABBCCDDEEBZZ" and "AAAAZAAAAA".
If Polycarp solved the tasks as follows: "FFGZZZY", then the teacher cannot have any suspicions. Please note that Polycarp is not obligated to solve all tasks. Other examples of when the teacher doesn't have any suspicious: "BA", "AFFFCC" and "YYYYY".
Help Polycarp find out if his teacher might be suspicious.
Input
The first line contains an integer t (1 ≤ t ≤ 1000). Then t test cases follow.
The first line of each test case contains one integer n (1 ≤ n ≤ 50) — the number of days during which Polycarp solved tasks.
The second line contains a string of length n, consisting of uppercase Latin letters, which is the order in which Polycarp solved the tasks.
Output
For each test case output:
* "YES", if the teacher cannot be suspicious;
* "NO", otherwise.
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
3
ABA
11
DDBBCCCBBEZ
7
FFGZZZY
1
Z
2
AB
Output
NO
NO
YES
YES
YES
Submitted Solution:
```
import sys
input = sys.stdin.readline
def mp():return map(int,input().split())
def lmp():return list(map(int,input().split()))
def mps(A):return [tuple(map(int, input().split())) for _ in range(A)]
import math
import bisect
from copy import deepcopy as dc
from itertools import accumulate
from collections import Counter, defaultdict, deque
def ceil(U,V):return (U+V-1)//V
def modf1(N,MOD):return (N-1)%MOD+1
inf = int(1e20)
mod = int(1e9+7)
def rle(lst):
ans = []
cnt = 1
ini = lst[0]
for i in range(1, len(lst)):
if ini == lst[i]:cnt += 1
else:
ans.append((ini, cnt))
cnt = 1
ini = lst[i]
ans.append((ini, cnt))
return ans
t = int(input())
for _ in range(t):
n = int(input())
s = list(input()[:-1])
s = rle(s)
#print(s)
used = [0]*26
f = True
for i,j in s:
if used[ord(i)-ord("A")] == 0:
used[ord(i)-ord("A")] += 1
else:
f = False
break
if f:
print("YES")
else:
print("NO")
```
Yes
| 10,202 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has 26 tasks. Each task is designated by a capital letter of the Latin alphabet.
The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot return to the previous task.
Polycarp can only solve one task during the day. Every day he wrote down what task he solved. Now the teacher wants to know if Polycarp followed his advice.
For example, if Polycarp solved tasks in the following order: "DDBBCCCBBEZ", then the teacher will see that on the third day Polycarp began to solve the task 'B', then on the fifth day he got distracted and began to solve the task 'C', on the eighth day Polycarp returned to the task 'B'. Other examples of when the teacher is suspicious: "BAB", "AABBCCDDEEBZZ" and "AAAAZAAAAA".
If Polycarp solved the tasks as follows: "FFGZZZY", then the teacher cannot have any suspicions. Please note that Polycarp is not obligated to solve all tasks. Other examples of when the teacher doesn't have any suspicious: "BA", "AFFFCC" and "YYYYY".
Help Polycarp find out if his teacher might be suspicious.
Input
The first line contains an integer t (1 ≤ t ≤ 1000). Then t test cases follow.
The first line of each test case contains one integer n (1 ≤ n ≤ 50) — the number of days during which Polycarp solved tasks.
The second line contains a string of length n, consisting of uppercase Latin letters, which is the order in which Polycarp solved the tasks.
Output
For each test case output:
* "YES", if the teacher cannot be suspicious;
* "NO", otherwise.
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
3
ABA
11
DDBBCCCBBEZ
7
FFGZZZY
1
Z
2
AB
Output
NO
NO
YES
YES
YES
Submitted Solution:
```
t = int(input())
p = False
z = []
pr = 10
for i in range(t):
n = int(input())
s = input()
for i in range(len(s)):
if s[i] not in z and n == pr or pr == 10:
z.append(s[i])
else:
p = True
pr = n
if not p:
print("YES")
else:
print("NO")
```
No
| 10,203 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has 26 tasks. Each task is designated by a capital letter of the Latin alphabet.
The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot return to the previous task.
Polycarp can only solve one task during the day. Every day he wrote down what task he solved. Now the teacher wants to know if Polycarp followed his advice.
For example, if Polycarp solved tasks in the following order: "DDBBCCCBBEZ", then the teacher will see that on the third day Polycarp began to solve the task 'B', then on the fifth day he got distracted and began to solve the task 'C', on the eighth day Polycarp returned to the task 'B'. Other examples of when the teacher is suspicious: "BAB", "AABBCCDDEEBZZ" and "AAAAZAAAAA".
If Polycarp solved the tasks as follows: "FFGZZZY", then the teacher cannot have any suspicions. Please note that Polycarp is not obligated to solve all tasks. Other examples of when the teacher doesn't have any suspicious: "BA", "AFFFCC" and "YYYYY".
Help Polycarp find out if his teacher might be suspicious.
Input
The first line contains an integer t (1 ≤ t ≤ 1000). Then t test cases follow.
The first line of each test case contains one integer n (1 ≤ n ≤ 50) — the number of days during which Polycarp solved tasks.
The second line contains a string of length n, consisting of uppercase Latin letters, which is the order in which Polycarp solved the tasks.
Output
For each test case output:
* "YES", if the teacher cannot be suspicious;
* "NO", otherwise.
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
3
ABA
11
DDBBCCCBBEZ
7
FFGZZZY
1
Z
2
AB
Output
NO
NO
YES
YES
YES
Submitted Solution:
```
import math
for _ in range(int(input())):
n = int(input())
s = input()
tmp=[]
ans=0
if n==1:
print("YES")
continue
for i in range(n-1):
if s[i]==s[i+1]:
continue
else:
tmp.append(s[i])
if s[i+1] in tmp:
ans =1
break
print(*tmp)
if ans==1:
print("NO")
else:
print("YES")
```
No
| 10,204 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has 26 tasks. Each task is designated by a capital letter of the Latin alphabet.
The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot return to the previous task.
Polycarp can only solve one task during the day. Every day he wrote down what task he solved. Now the teacher wants to know if Polycarp followed his advice.
For example, if Polycarp solved tasks in the following order: "DDBBCCCBBEZ", then the teacher will see that on the third day Polycarp began to solve the task 'B', then on the fifth day he got distracted and began to solve the task 'C', on the eighth day Polycarp returned to the task 'B'. Other examples of when the teacher is suspicious: "BAB", "AABBCCDDEEBZZ" and "AAAAZAAAAA".
If Polycarp solved the tasks as follows: "FFGZZZY", then the teacher cannot have any suspicions. Please note that Polycarp is not obligated to solve all tasks. Other examples of when the teacher doesn't have any suspicious: "BA", "AFFFCC" and "YYYYY".
Help Polycarp find out if his teacher might be suspicious.
Input
The first line contains an integer t (1 ≤ t ≤ 1000). Then t test cases follow.
The first line of each test case contains one integer n (1 ≤ n ≤ 50) — the number of days during which Polycarp solved tasks.
The second line contains a string of length n, consisting of uppercase Latin letters, which is the order in which Polycarp solved the tasks.
Output
For each test case output:
* "YES", if the teacher cannot be suspicious;
* "NO", otherwise.
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
3
ABA
11
DDBBCCCBBEZ
7
FFGZZZY
1
Z
2
AB
Output
NO
NO
YES
YES
YES
Submitted Solution:
```
# cook your dish here
t=int(input())
for i in range(t):
n=int(input())
s=input()
c=1
for i in range(len(s)):
if s[i] in s[i+1:len(s):1]:
c=0
break
else:
c=1
if c==1:
print('YES')
else:
print('NO')
```
No
| 10,205 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp has 26 tasks. Each task is designated by a capital letter of the Latin alphabet.
The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot return to the previous task.
Polycarp can only solve one task during the day. Every day he wrote down what task he solved. Now the teacher wants to know if Polycarp followed his advice.
For example, if Polycarp solved tasks in the following order: "DDBBCCCBBEZ", then the teacher will see that on the third day Polycarp began to solve the task 'B', then on the fifth day he got distracted and began to solve the task 'C', on the eighth day Polycarp returned to the task 'B'. Other examples of when the teacher is suspicious: "BAB", "AABBCCDDEEBZZ" and "AAAAZAAAAA".
If Polycarp solved the tasks as follows: "FFGZZZY", then the teacher cannot have any suspicions. Please note that Polycarp is not obligated to solve all tasks. Other examples of when the teacher doesn't have any suspicious: "BA", "AFFFCC" and "YYYYY".
Help Polycarp find out if his teacher might be suspicious.
Input
The first line contains an integer t (1 ≤ t ≤ 1000). Then t test cases follow.
The first line of each test case contains one integer n (1 ≤ n ≤ 50) — the number of days during which Polycarp solved tasks.
The second line contains a string of length n, consisting of uppercase Latin letters, which is the order in which Polycarp solved the tasks.
Output
For each test case output:
* "YES", if the teacher cannot be suspicious;
* "NO", otherwise.
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
3
ABA
11
DDBBCCCBBEZ
7
FFGZZZY
1
Z
2
AB
Output
NO
NO
YES
YES
YES
Submitted Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Wed May 5 20:43:22 2021
@author: babai
"""
tc=int(input())
for i in range(tc):
l=int(input())
st=input()
chk=list(st)
ch=[]
count=0
for j in range(len(chk)):
if(j==0):
ch.append(chk[j])
elif(ch[j-1]==chk[j]):
ch.append("re")
else:
ch.append(chk[j])
ch = [i for i in ch if i != "re"]
if(len(ch)!=len(set(ch))):
print("NO")
else:
print("YES")
```
No
| 10,206 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array of positive integers a = [a_0, a_1, ..., a_{n - 1}] (n ≥ 2).
In one step, the array a is replaced with another array of length n, in which each element is the [greatest common divisor (GCD)](http://tiny.cc/tuy9uz) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the (n - 1)-th element is the 0-th element).
Formally speaking, a new array b = [b_0, b_1, ..., b_{n - 1}] is being built from array a = [a_0, a_1, ..., a_{n - 1}] such that b_i = \gcd(a_i, a_{(i + 1) mod n}), where \gcd(x, y) is the greatest common divisor of x and y, and x mod y is the remainder of x dividing by y. In one step the array b is built and then the array a is replaced with b (that is, the assignment a := b is taking place).
For example, if a = [16, 24, 10, 5] then b = [\gcd(16, 24), \gcd(24, 10), \gcd(10, 5), \gcd(5, 16)] = [8, 2, 5, 1]. Thus, after one step the array a = [16, 24, 10, 5] will be equal to [8, 2, 5, 1].
For a given array a, find the minimum number of steps after which all values a_i become equal (that is, a_0 = a_1 = ... = a_{n - 1}). If the original array a consists of identical elements then consider the number of steps is equal to 0.
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
Each test case contains two lines. The first line contains an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — length of the sequence a. The second line contains n integers a_0, a_1, ..., a_{n - 1} (1 ≤ a_i ≤ 10^6).
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
Print t numbers — answers for each test case.
Example
Input
5
4
16 24 10 5
4
42 42 42 42
3
4 6 4
5
1 2 3 4 5
6
9 9 27 9 9 63
Output
3
0
2
1
1
Tags: binary search, brute force, data structures, divide and conquer, number theory, two pointers
Correct Solution:
```
from collections import defaultdict, deque, Counter
from heapq import heapify, heappop, heappush
import math
from copy import deepcopy
from itertools import combinations, permutations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
import sys
def input():
return sys.stdin.readline().rstrip()
def getN():
return int(input())
def getNM():
return map(int, input().split())
def getList():
return list(map(int, input().split()))
def getListGraph():
return list(map(lambda x:int(x) - 1, input().split()))
def getArray(intn):
return [int(input()) for i in range(intn)]
mod = 10 ** 9 + 7
MOD = 998244353
inf = float('inf')
eps = 10 ** (-10)
dy = [0, 1, 0, -1]
dx = [1, 0, -1, 0]
#############
# Main Code #
#############
# ここの設定を変えて使う
#####segfunc#####
def segfunc(x, y):
return math.gcd(x, y)
#################
#####ide_ele#####
ide_ele = 0
#################
class SegTree:
def __init__(self, init_val, segfunc, ide_ele):
n = len(init_val)
self.segfunc = segfunc
self.ide_ele = ide_ele
self.num = 1 << (n - 1).bit_length()
self.tree = [ide_ele] * 2 * self.num
# 配列の値を葉にセット
for i in range(n):
self.tree[self.num + i] = init_val[i]
# 構築していく
for i in range(self.num - 1, 0, -1):
self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])
def update(self, k, x):
k += self.num
self.tree[k] = x
while k > 1:
self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
k >>= 1
def query(self, l, r):
res = self.ide_ele
l += self.num
r += self.num
while l < r:
if l & 1:
res = self.segfunc(res, self.tree[l])
l += 1
if r & 1:
res = self.segfunc(res, self.tree[r - 1])
l >>= 1
r >>= 1
return res
# gcdする
# gcd(a1, a2), gcd(a2, a3)... 輪っかになっている
# だんだんgcdが1とかにならされて行くのでは?
# 操作回数の最小を求める
# 連続部分列Kについていずれの列でもgcdが等しくなる
# gcdはモノイドだぞ セグ木使えば
T = getN()
for _ in range(T):
N = getN()
A = getList()
A += A
def f(x):
seg = SegTree(A, segfunc, ide_ele) # セグ木立てる
res = [seg.query(i, i + x) for i in range(N)]
return all([res[i] == res[0] for i in range(N)])
ok = N + 1
ng = 0
while abs(ok - ng) > 1:
mid = (ok + ng) // 2
if f(mid):
ok = mid
else:
ng = mid
print(ok - 1)
```
| 10,207 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array of positive integers a = [a_0, a_1, ..., a_{n - 1}] (n ≥ 2).
In one step, the array a is replaced with another array of length n, in which each element is the [greatest common divisor (GCD)](http://tiny.cc/tuy9uz) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the (n - 1)-th element is the 0-th element).
Formally speaking, a new array b = [b_0, b_1, ..., b_{n - 1}] is being built from array a = [a_0, a_1, ..., a_{n - 1}] such that b_i = \gcd(a_i, a_{(i + 1) mod n}), where \gcd(x, y) is the greatest common divisor of x and y, and x mod y is the remainder of x dividing by y. In one step the array b is built and then the array a is replaced with b (that is, the assignment a := b is taking place).
For example, if a = [16, 24, 10, 5] then b = [\gcd(16, 24), \gcd(24, 10), \gcd(10, 5), \gcd(5, 16)] = [8, 2, 5, 1]. Thus, after one step the array a = [16, 24, 10, 5] will be equal to [8, 2, 5, 1].
For a given array a, find the minimum number of steps after which all values a_i become equal (that is, a_0 = a_1 = ... = a_{n - 1}). If the original array a consists of identical elements then consider the number of steps is equal to 0.
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
Each test case contains two lines. The first line contains an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — length of the sequence a. The second line contains n integers a_0, a_1, ..., a_{n - 1} (1 ≤ a_i ≤ 10^6).
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
Print t numbers — answers for each test case.
Example
Input
5
4
16 24 10 5
4
42 42 42 42
3
4 6 4
5
1 2 3 4 5
6
9 9 27 9 9 63
Output
3
0
2
1
1
Tags: binary search, brute force, data structures, divide and conquer, number theory, two pointers
Correct Solution:
```
import math
import sys
input = sys.stdin.readline
def make_tree(n):
i = 2
while True:
if i >= n * 2:
tree = [0] * i
break
else:
i *= 2
return tree
def initialization(a):
l = len(tree) // 2
for i in range(l, l + len(a)):
tree[i] = a[i - l]
for i in range(l - 1, 0, -1):
tree[i] = math.gcd(tree[2 * i], tree[2 * i + 1])
return
def update(i, x):
i += len(tree) // 2
tree[i] = x
i //= 2
while True:
if i == 0:
break
tree[i] = math.gcd(tree[2 * i], tree[2 * i + 1])
i //= 2
return
def get_gcd(s, t):
s += len(tree) // 2
t += len(tree) // 2
ans = tree[s]
while True:
if s > t:
break
if s % 2 == 0:
s //= 2
else:
ans = math.gcd(ans, tree[s])
s = (s + 1) // 2
if t % 2 == 1:
t //= 2
else:
ans = math.gcd(ans, tree[t])
t = (t - 1) // 2
return ans
def binary_search(c1, c2):
m = (c1 + c2 + 1) // 2
if abs(c1 - c2) <= 1:
return m
else:
if ok(m):
c2 = m
else:
c1 = m
return binary_search(c1, c2)
def ok(m):
g = get_gcd(0, m)
for i in range(1, n):
if get_gcd(i, m + i) ^ g:
return False
return True
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
tree = make_tree(2 * n + 1)
initialization(a + a)
ans = binary_search(-1, n)
print(ans)
```
| 10,208 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array of positive integers a = [a_0, a_1, ..., a_{n - 1}] (n ≥ 2).
In one step, the array a is replaced with another array of length n, in which each element is the [greatest common divisor (GCD)](http://tiny.cc/tuy9uz) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the (n - 1)-th element is the 0-th element).
Formally speaking, a new array b = [b_0, b_1, ..., b_{n - 1}] is being built from array a = [a_0, a_1, ..., a_{n - 1}] such that b_i = \gcd(a_i, a_{(i + 1) mod n}), where \gcd(x, y) is the greatest common divisor of x and y, and x mod y is the remainder of x dividing by y. In one step the array b is built and then the array a is replaced with b (that is, the assignment a := b is taking place).
For example, if a = [16, 24, 10, 5] then b = [\gcd(16, 24), \gcd(24, 10), \gcd(10, 5), \gcd(5, 16)] = [8, 2, 5, 1]. Thus, after one step the array a = [16, 24, 10, 5] will be equal to [8, 2, 5, 1].
For a given array a, find the minimum number of steps after which all values a_i become equal (that is, a_0 = a_1 = ... = a_{n - 1}). If the original array a consists of identical elements then consider the number of steps is equal to 0.
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
Each test case contains two lines. The first line contains an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — length of the sequence a. The second line contains n integers a_0, a_1, ..., a_{n - 1} (1 ≤ a_i ≤ 10^6).
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
Print t numbers — answers for each test case.
Example
Input
5
4
16 24 10 5
4
42 42 42 42
3
4 6 4
5
1 2 3 4 5
6
9 9 27 9 9 63
Output
3
0
2
1
1
Tags: binary search, brute force, data structures, divide and conquer, number theory, two pointers
Correct Solution:
```
import sys
from functools import reduce
from math import gcd
#comment these out later
#sys.stdin = open("in.in", "r")
#sys.stdout = open("out.out", "w")
def main():
class RangeQuery:
def __init__(self, data, func=min):
self.func = func
self._data = _data = [list(data)]
i, n = 1, len(_data[0])
while 2 * i <= n:
prev = _data[-1]
_data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])
i <<= 1
def query(self, start, stop):
"""func of data[start, stop)"""
depth = (stop - start).bit_length() - 1
return self.func(self._data[depth][start], self._data[depth][stop - (1 << depth)])
def __getitem__(self, idx):
return self._data[0][idx]
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
t = inp[ii]; ii += 1
for _ in range(t):
n = inp[ii]; ii += 1
ar = inp[ii:ii+n]; ii += n
ar = ar+ar
spt = RangeQuery(ar, gcd)
target = spt.query(0, n)
ans = 0
for i in range(n):
for l in range(ans+1, n+1):
g = spt.query(i, i+l)
if g == target:
ans = max(ans, l-1)
break
print(ans)
main()
```
| 10,209 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array of positive integers a = [a_0, a_1, ..., a_{n - 1}] (n ≥ 2).
In one step, the array a is replaced with another array of length n, in which each element is the [greatest common divisor (GCD)](http://tiny.cc/tuy9uz) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the (n - 1)-th element is the 0-th element).
Formally speaking, a new array b = [b_0, b_1, ..., b_{n - 1}] is being built from array a = [a_0, a_1, ..., a_{n - 1}] such that b_i = \gcd(a_i, a_{(i + 1) mod n}), where \gcd(x, y) is the greatest common divisor of x and y, and x mod y is the remainder of x dividing by y. In one step the array b is built and then the array a is replaced with b (that is, the assignment a := b is taking place).
For example, if a = [16, 24, 10, 5] then b = [\gcd(16, 24), \gcd(24, 10), \gcd(10, 5), \gcd(5, 16)] = [8, 2, 5, 1]. Thus, after one step the array a = [16, 24, 10, 5] will be equal to [8, 2, 5, 1].
For a given array a, find the minimum number of steps after which all values a_i become equal (that is, a_0 = a_1 = ... = a_{n - 1}). If the original array a consists of identical elements then consider the number of steps is equal to 0.
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
Each test case contains two lines. The first line contains an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — length of the sequence a. The second line contains n integers a_0, a_1, ..., a_{n - 1} (1 ≤ a_i ≤ 10^6).
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
Print t numbers — answers for each test case.
Example
Input
5
4
16 24 10 5
4
42 42 42 42
3
4 6 4
5
1 2 3 4 5
6
9 9 27 9 9 63
Output
3
0
2
1
1
Tags: binary search, brute force, data structures, divide and conquer, number theory, two pointers
Correct Solution:
```
import sys,os,io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from math import gcd
class RangeQuery:
def __init__(self, data, func=gcd):
self.func = func
self._data = _data = [list(data)]
i, n = 1, len(_data[0])
while 2 * i <= n:
prev = _data[-1]
_data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])
i <<= 1
def query(self, start, stop):
"""func of data[start, stop)"""
depth = (stop - start).bit_length() - 1
return self.func(self._data[depth][start], self._data[depth][stop - (1 << depth)])
def __getitem__(self, idx):
return self._data[0][idx]
for _ in range (int(input())):
n = int(input())
a = [int(i) for i in input().split()]
a += a[:]
g = a[0]
for i in a:
g = gcd(i,g)
rmq = RangeQuery(a)
l = 1
h = n
ans = -1
while(l<=h):
mid = (l+h)//2
flag = 0
for i in range (n):
curr = rmq.query(i, i+mid)
if curr != g:
flag = 1
if flag:
l = mid+1
else:
ans = mid-1
h = mid-1
print(ans)
```
| 10,210 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array of positive integers a = [a_0, a_1, ..., a_{n - 1}] (n ≥ 2).
In one step, the array a is replaced with another array of length n, in which each element is the [greatest common divisor (GCD)](http://tiny.cc/tuy9uz) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the (n - 1)-th element is the 0-th element).
Formally speaking, a new array b = [b_0, b_1, ..., b_{n - 1}] is being built from array a = [a_0, a_1, ..., a_{n - 1}] such that b_i = \gcd(a_i, a_{(i + 1) mod n}), where \gcd(x, y) is the greatest common divisor of x and y, and x mod y is the remainder of x dividing by y. In one step the array b is built and then the array a is replaced with b (that is, the assignment a := b is taking place).
For example, if a = [16, 24, 10, 5] then b = [\gcd(16, 24), \gcd(24, 10), \gcd(10, 5), \gcd(5, 16)] = [8, 2, 5, 1]. Thus, after one step the array a = [16, 24, 10, 5] will be equal to [8, 2, 5, 1].
For a given array a, find the minimum number of steps after which all values a_i become equal (that is, a_0 = a_1 = ... = a_{n - 1}). If the original array a consists of identical elements then consider the number of steps is equal to 0.
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
Each test case contains two lines. The first line contains an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — length of the sequence a. The second line contains n integers a_0, a_1, ..., a_{n - 1} (1 ≤ a_i ≤ 10^6).
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
Print t numbers — answers for each test case.
Example
Input
5
4
16 24 10 5
4
42 42 42 42
3
4 6 4
5
1 2 3 4 5
6
9 9 27 9 9 63
Output
3
0
2
1
1
Tags: binary search, brute force, data structures, divide and conquer, number theory, two pointers
Correct Solution:
```
import sys
from math import gcd
t = int(sys.stdin.readline())
while(t>0):
n = int(input())
a = list(map(int,sys.stdin.readline().split()))
a = a+a
m = 0
for i in range(n):
x = a[i]
y = a[i+1]
c = 0
j = i+1
while x!=y:
x = gcd(x,a[j])
y = gcd(y,a[j+1])
j += 1
c += 1
m = max(m,c)
print(m)
t-=1
```
| 10,211 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array of positive integers a = [a_0, a_1, ..., a_{n - 1}] (n ≥ 2).
In one step, the array a is replaced with another array of length n, in which each element is the [greatest common divisor (GCD)](http://tiny.cc/tuy9uz) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the (n - 1)-th element is the 0-th element).
Formally speaking, a new array b = [b_0, b_1, ..., b_{n - 1}] is being built from array a = [a_0, a_1, ..., a_{n - 1}] such that b_i = \gcd(a_i, a_{(i + 1) mod n}), where \gcd(x, y) is the greatest common divisor of x and y, and x mod y is the remainder of x dividing by y. In one step the array b is built and then the array a is replaced with b (that is, the assignment a := b is taking place).
For example, if a = [16, 24, 10, 5] then b = [\gcd(16, 24), \gcd(24, 10), \gcd(10, 5), \gcd(5, 16)] = [8, 2, 5, 1]. Thus, after one step the array a = [16, 24, 10, 5] will be equal to [8, 2, 5, 1].
For a given array a, find the minimum number of steps after which all values a_i become equal (that is, a_0 = a_1 = ... = a_{n - 1}). If the original array a consists of identical elements then consider the number of steps is equal to 0.
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
Each test case contains two lines. The first line contains an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — length of the sequence a. The second line contains n integers a_0, a_1, ..., a_{n - 1} (1 ≤ a_i ≤ 10^6).
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
Print t numbers — answers for each test case.
Example
Input
5
4
16 24 10 5
4
42 42 42 42
3
4 6 4
5
1 2 3 4 5
6
9 9 27 9 9 63
Output
3
0
2
1
1
Tags: binary search, brute force, data structures, divide and conquer, number theory, two pointers
Correct Solution:
```
def read_ints():
return list(map(int, input().split()))
def gcd(x, y):
if x == 0 or y == 0:
return x + y
if x > y:
return gcd(x % y, y)
else:
return gcd(x, y % x)
def remove_gcd(a):
g = gcd(a[0], a[1])
for i in range(2, len(a)):
g = gcd(g, a[i])
return [x // g for x in a]
def make_cycled(a):
a.extend(a[:-1])
return a
def create_dp(a):
n = len(a)
k = 0
while n > 0:
k += 1
n //= 2
dp = [[0 for _ in range(len(a))] for _ in range(k)]
dp[0] = a
step = 1
for i in range(1, k):
step *= 2
for j in range(len(a)):
if j + step <= len(a):
dp[i][j] = gcd(dp[i - 1][j], dp[i - 1][j + step // 2])
return dp
def get_seq_gcd(dp, l, r):
step = 1
k = -1
while r - l >= step:
step *= 2
k += 1
step //= 2
#print(k, l, r, step)
return gcd(dp[k][l], dp[k][r - step])
def get_answer(dp):
answer = 0
l, r = 0, 1
while l < len(dp[0]):
cur = get_seq_gcd(dp, l, r)
while r < len(dp[0]) and cur > 1:
cur = gcd(cur, dp[0][r])
r += 1
#print(l, r, cur)
answer = max(answer, r - l - 1)
l += 1
if l == r:
r += 1
return answer
t = int(input())
for _ in range(t):
n = int(input())
a = read_ints()
a = remove_gcd(a)
a = make_cycled(a)
dp = create_dp(a)
answer = get_answer(dp)
print(answer)
```
| 10,212 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array of positive integers a = [a_0, a_1, ..., a_{n - 1}] (n ≥ 2).
In one step, the array a is replaced with another array of length n, in which each element is the [greatest common divisor (GCD)](http://tiny.cc/tuy9uz) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the (n - 1)-th element is the 0-th element).
Formally speaking, a new array b = [b_0, b_1, ..., b_{n - 1}] is being built from array a = [a_0, a_1, ..., a_{n - 1}] such that b_i = \gcd(a_i, a_{(i + 1) mod n}), where \gcd(x, y) is the greatest common divisor of x and y, and x mod y is the remainder of x dividing by y. In one step the array b is built and then the array a is replaced with b (that is, the assignment a := b is taking place).
For example, if a = [16, 24, 10, 5] then b = [\gcd(16, 24), \gcd(24, 10), \gcd(10, 5), \gcd(5, 16)] = [8, 2, 5, 1]. Thus, after one step the array a = [16, 24, 10, 5] will be equal to [8, 2, 5, 1].
For a given array a, find the minimum number of steps after which all values a_i become equal (that is, a_0 = a_1 = ... = a_{n - 1}). If the original array a consists of identical elements then consider the number of steps is equal to 0.
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
Each test case contains two lines. The first line contains an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — length of the sequence a. The second line contains n integers a_0, a_1, ..., a_{n - 1} (1 ≤ a_i ≤ 10^6).
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
Print t numbers — answers for each test case.
Example
Input
5
4
16 24 10 5
4
42 42 42 42
3
4 6 4
5
1 2 3 4 5
6
9 9 27 9 9 63
Output
3
0
2
1
1
Tags: binary search, brute force, data structures, divide and conquer, number theory, two pointers
Correct Solution:
```
from __future__ import division, print_function
import os,sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
from bisect import bisect_left as lower_bound, bisect_right as upper_bound
def so(): return int(input())
def st(): return input()
def mj(): return map(int,input().strip().split(" "))
def msj(): return map(str,input().strip().split(" "))
def le(): return list(map(int,input().split()))
def lebe():return list(map(int, input()))
def dmain():
sys.setrecursionlimit(1000000)
threading.stack_size(1024000)
thread = threading.Thread(target=main)
thread.start()
def joro(L):
return(''.join(map(str, L)))
def cheems(c,d):
a=1
while(d!=0):
if(d%2==1):
a*=c
c=c*c
d=d//2
return a
def decimalToBinary(n): return bin(n).replace("0b","")
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def npr(n, r):
return factorial(n) // factorial(n - r) if n >= r else 0
def ncr(n, r):
return factorial(n) // (factorial(r) * factorial(n - r)) if n >= r else 0
def lower_bound(li, num):
answer = -1
start = 0
end = len(li) - 1
while (start <= end):
middle = (end + start) // 2
if li[middle] >= num:
answer = middle
end = middle - 1
else:
start = middle + 1
return answer # min index where x is not less than num
def upper_bound(li, num):
answer = -1
start = 0
end = len(li) - 1
while (start <= end):
middle = (end + start) // 2
if li[middle] <= num:
answer = middle
start = middle + 1
else:
end = middle - 1
return answer # max index where x is not greater than num
def tir(a,b,c):
if(0==c):
return 1
if(len(a)<=b):
return 0
if(c!=-1):
return (tir(a,1+b,c+a[b]) or tir(a,b+1,c-a[b]) or tir(a,1+b,c))
else:
return (tir(a,1+b,a[b]) or tir(a,b+1,-a[b]) or tir(a,1+b,-1))
def abs(x):
return x if x >= 0 else -x
def binary_search(li, val, lb, ub):
# print(lb, ub, li)
ans = -1
while (lb <= ub):
mid = (lb + ub) // 2
# print('mid is',mid, li[mid])
if li[mid] > val:
ub = mid - 1
elif val > li[mid]:
lb = mid + 1
else:
ans = mid # return index
break
return ans
def kadane(x): # maximum sum contiguous subarray
sum_so_far = 0
current_sum = 0
for i in x:
current_sum += i
if current_sum < 0:
current_sum = 0
else:
sum_so_far = max(sum_so_far, current_sum)
return sum_so_far
def wubu(m):
import math as my
d=0
while(not m%2):
m=m//2
d=1+d
for i in range(3,int(my.sqrt(m))+1,2):
while(not m%i):
m=m//i
d=1+d
return int(m>1)+d
def pref(li):
pref_sum = [0]
for i in li:
pref_sum.append(pref_sum[-1] + i)
return pref_sum
def SieveOfEratosthenes(n):
prime = [True for i in range(n + 1)]
p = 2
li = []
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n + 1, p):
prime[i] = False
p += 1
for p in range(2, len(prime)):
if prime[p]:
li.append(p)
return li
def primefactors(n):
factors = []
while (n % 2 == 0):
factors.append(2)
n //= 2
for i in range(3, int(sqrt(n)) + 1, 2): # only odd factors left
while n % i == 0:
factors.append(i)
n //= i
if n > 2: # incase of prime
factors.append(n)
return factors
def read():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
def tr(n):
return n*(n+1)//2
def bro(q,r,c):
bec,pot,h=0,0,0
ds=[]
bs=[]
es=[]
for i in range(c):
while(h<len(r) and r[h]<=q[i][0]):
pot=0
ds.clear()
bs.clear()
h=1+h
for i in range(c):
ds.append(q[i][1])
es.append(q[i][1])
ds=list(set(ds))
for i in ds:
bs.append(es.count(i))
print(bs)
for i in range(c):
if(q[i][0]>r[h-1]):
bec=bec+pot-bs[i]
pot=1+pot
return bec
def iu():
import sys
input = sys.stdin.readline
import math as my
import bisect as op
c=0
m=so()
L=le()
L=2*L
for i in range(m):
p,q,r,s=L[i],L[1+i],0,1+i
while(q!=p):
p,q,r,s=my.gcd(L[s],p),my.gcd(L[1+s],q),1+r,1+s
c=max(r,c)
print(c)
def main():
for i in range(so()):
iu()
# region fastio
# template taken from https://github.com/cheran-senthil/PyRival/blob/master/templates/template.py
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
#read()
main()
#dmain()
# Comment Read()
```
| 10,213 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array of positive integers a = [a_0, a_1, ..., a_{n - 1}] (n ≥ 2).
In one step, the array a is replaced with another array of length n, in which each element is the [greatest common divisor (GCD)](http://tiny.cc/tuy9uz) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the (n - 1)-th element is the 0-th element).
Formally speaking, a new array b = [b_0, b_1, ..., b_{n - 1}] is being built from array a = [a_0, a_1, ..., a_{n - 1}] such that b_i = \gcd(a_i, a_{(i + 1) mod n}), where \gcd(x, y) is the greatest common divisor of x and y, and x mod y is the remainder of x dividing by y. In one step the array b is built and then the array a is replaced with b (that is, the assignment a := b is taking place).
For example, if a = [16, 24, 10, 5] then b = [\gcd(16, 24), \gcd(24, 10), \gcd(10, 5), \gcd(5, 16)] = [8, 2, 5, 1]. Thus, after one step the array a = [16, 24, 10, 5] will be equal to [8, 2, 5, 1].
For a given array a, find the minimum number of steps after which all values a_i become equal (that is, a_0 = a_1 = ... = a_{n - 1}). If the original array a consists of identical elements then consider the number of steps is equal to 0.
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
Each test case contains two lines. The first line contains an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — length of the sequence a. The second line contains n integers a_0, a_1, ..., a_{n - 1} (1 ≤ a_i ≤ 10^6).
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
Print t numbers — answers for each test case.
Example
Input
5
4
16 24 10 5
4
42 42 42 42
3
4 6 4
5
1 2 3 4 5
6
9 9 27 9 9 63
Output
3
0
2
1
1
Tags: binary search, brute force, data structures, divide and conquer, number theory, two pointers
Correct Solution:
```
import sys
import math
input = sys.stdin.readline
def sieve(n):
prime = [-1]*(n+1)
for i in range(2,n+1):
if prime[i]==-1:
for j in range(i,n+1,i):
if prime[j]==-1:
prime[j] = i
return prime
def PrimeFactors(num):
ans = {}
while num != 1:
p = prime[num]
ans[p] = 1
while num%p==0:
num = num//p
return ans
def solve(ind, p):
ans = 0
for i in range(ind, ind+n):
if p not in pf[i%n]:
return ans
else:
if i not in done:
done[i] = {p:0}
else:
done[i][p] = 0
ans += 1
return ans
prime = sieve(1000010)
for nt in range(int(input())):
n = int(input())
a = list(map(int,input().split()))
hcf = a[0]
for i in a:
hcf = math.gcd(hcf, i)
for i in range(n):
a[i] = a[i]//hcf
pf = []
for i in a:
pf.append(PrimeFactors(i))
ans = 0
done = {}
for i in range(n):
for j in pf[i]:
if i not in done:
done[i] = {}
if j not in done[i]:
ans = max(ans, solve(i, j))
print (ans)
```
| 10,214 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array of positive integers a = [a_0, a_1, ..., a_{n - 1}] (n ≥ 2).
In one step, the array a is replaced with another array of length n, in which each element is the [greatest common divisor (GCD)](http://tiny.cc/tuy9uz) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the (n - 1)-th element is the 0-th element).
Formally speaking, a new array b = [b_0, b_1, ..., b_{n - 1}] is being built from array a = [a_0, a_1, ..., a_{n - 1}] such that b_i = \gcd(a_i, a_{(i + 1) mod n}), where \gcd(x, y) is the greatest common divisor of x and y, and x mod y is the remainder of x dividing by y. In one step the array b is built and then the array a is replaced with b (that is, the assignment a := b is taking place).
For example, if a = [16, 24, 10, 5] then b = [\gcd(16, 24), \gcd(24, 10), \gcd(10, 5), \gcd(5, 16)] = [8, 2, 5, 1]. Thus, after one step the array a = [16, 24, 10, 5] will be equal to [8, 2, 5, 1].
For a given array a, find the minimum number of steps after which all values a_i become equal (that is, a_0 = a_1 = ... = a_{n - 1}). If the original array a consists of identical elements then consider the number of steps is equal to 0.
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
Each test case contains two lines. The first line contains an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — length of the sequence a. The second line contains n integers a_0, a_1, ..., a_{n - 1} (1 ≤ a_i ≤ 10^6).
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
Print t numbers — answers for each test case.
Example
Input
5
4
16 24 10 5
4
42 42 42 42
3
4 6 4
5
1 2 3 4 5
6
9 9 27 9 9 63
Output
3
0
2
1
1
Submitted Solution:
```
from collections import defaultdict, Counter
from math import sqrt, log10, log2, log, gcd, floor, factorial
from bisect import bisect_left, bisect_right
from itertools import permutations
import sys, io, os
input = sys.stdin.readline
input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# print=sys.stdout.write
# sys.setrecursionlimit(10000)
inf = float('inf');
mod = 10 ** 9 + 7
def get_list(): return [int(i) for i in input().split()]
yn = lambda a: print("YES" if a else "NO")
ceil = lambda a, b: (a + b - 1) // b
class LazySegmentTree:
def __init__(self, data, default=0, func=max):
"""initialize the lazy segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self._lazy = [0] * (2 * _size)
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __len__(self):
return self._len
def _push(self, idx):
"""push query on idx to its children"""
# Let the children know of the queries
q, self._lazy[idx] = self._lazy[idx], 0
self._lazy[2 * idx] += q
self._lazy[2 * idx + 1] += q
self.data[2 * idx] += q
self.data[2 * idx + 1] += q
def _update(self, idx):
"""updates the node idx to know of all queries applied to it via its ancestors"""
for i in reversed(range(1, idx.bit_length())):
self._push(idx >> i)
def _build(self, idx):
"""make the changes to idx be known to its ancestors"""
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) + self._lazy[idx]
idx >>= 1
def add(self, start, stop, value):
"""lazily add value to [start, stop)"""
start = start_copy = start + self._size
stop = stop_copy = stop + self._size
while start < stop:
if start & 1:
self._lazy[start] += value
self.data[start] += value
start += 1
if stop & 1:
stop -= 1
self._lazy[stop] += value
self.data[stop] += value
start >>= 1
stop >>= 1
# Tell all nodes above of the updated area of the updates
self._build(start_copy)
self._build(stop_copy - 1)
def query(self, start, stop, default=0):
"""func of data[start, stop)"""
start += self._size
stop += self._size
# Apply all the lazily stored queries
self._update(start)
self._update(stop - 1)
res = default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "LazySegmentTree({0})".format(self.data)
t=int(input())
for i in range(t):
n=int(input())
l=get_list()
gcda=l[0]
for i in l:
gcda=gcd(i,gcda)
l+=l
s=LazySegmentTree(l,0,gcd)
maxa=0
for i in range(n):
answer=0
low=i;high=i+n
while low<high:
mid=(low+high)//2
if s.query(i,mid+1)==gcda:
high=mid
answer=mid-i
else:
low=mid+1
maxa=max(answer,maxa)
print(maxa)
```
Yes
| 10,215 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array of positive integers a = [a_0, a_1, ..., a_{n - 1}] (n ≥ 2).
In one step, the array a is replaced with another array of length n, in which each element is the [greatest common divisor (GCD)](http://tiny.cc/tuy9uz) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the (n - 1)-th element is the 0-th element).
Formally speaking, a new array b = [b_0, b_1, ..., b_{n - 1}] is being built from array a = [a_0, a_1, ..., a_{n - 1}] such that b_i = \gcd(a_i, a_{(i + 1) mod n}), where \gcd(x, y) is the greatest common divisor of x and y, and x mod y is the remainder of x dividing by y. In one step the array b is built and then the array a is replaced with b (that is, the assignment a := b is taking place).
For example, if a = [16, 24, 10, 5] then b = [\gcd(16, 24), \gcd(24, 10), \gcd(10, 5), \gcd(5, 16)] = [8, 2, 5, 1]. Thus, after one step the array a = [16, 24, 10, 5] will be equal to [8, 2, 5, 1].
For a given array a, find the minimum number of steps after which all values a_i become equal (that is, a_0 = a_1 = ... = a_{n - 1}). If the original array a consists of identical elements then consider the number of steps is equal to 0.
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
Each test case contains two lines. The first line contains an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — length of the sequence a. The second line contains n integers a_0, a_1, ..., a_{n - 1} (1 ≤ a_i ≤ 10^6).
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
Print t numbers — answers for each test case.
Example
Input
5
4
16 24 10 5
4
42 42 42 42
3
4 6 4
5
1 2 3 4 5
6
9 9 27 9 9 63
Output
3
0
2
1
1
Submitted Solution:
```
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
ans = []
for _ in range(int(input())):
n = int(input())
u = list(map(int, input().split()))
u += u[:]
m = 0
for i in range(n):
k1 = u[i]
k2 = u[i + 1]
c = 0
j = i + 1
while k1 != k2:
k1 = gcd(k1, u[j])
k2 = gcd(k2, u[j + 1])
j += 1
c += 1
m = max(m, c)
ans.append(m)
print('\n'.join(map(str, ans)))
```
Yes
| 10,216 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array of positive integers a = [a_0, a_1, ..., a_{n - 1}] (n ≥ 2).
In one step, the array a is replaced with another array of length n, in which each element is the [greatest common divisor (GCD)](http://tiny.cc/tuy9uz) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the (n - 1)-th element is the 0-th element).
Formally speaking, a new array b = [b_0, b_1, ..., b_{n - 1}] is being built from array a = [a_0, a_1, ..., a_{n - 1}] such that b_i = \gcd(a_i, a_{(i + 1) mod n}), where \gcd(x, y) is the greatest common divisor of x and y, and x mod y is the remainder of x dividing by y. In one step the array b is built and then the array a is replaced with b (that is, the assignment a := b is taking place).
For example, if a = [16, 24, 10, 5] then b = [\gcd(16, 24), \gcd(24, 10), \gcd(10, 5), \gcd(5, 16)] = [8, 2, 5, 1]. Thus, after one step the array a = [16, 24, 10, 5] will be equal to [8, 2, 5, 1].
For a given array a, find the minimum number of steps after which all values a_i become equal (that is, a_0 = a_1 = ... = a_{n - 1}). If the original array a consists of identical elements then consider the number of steps is equal to 0.
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
Each test case contains two lines. The first line contains an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — length of the sequence a. The second line contains n integers a_0, a_1, ..., a_{n - 1} (1 ≤ a_i ≤ 10^6).
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
Print t numbers — answers for each test case.
Example
Input
5
4
16 24 10 5
4
42 42 42 42
3
4 6 4
5
1 2 3 4 5
6
9 9 27 9 9 63
Output
3
0
2
1
1
Submitted Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
from collections import Counter
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: max(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SegmentTree1:
def __init__(self, data, default=0, func=lambda a, b: math.gcd(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
MOD=10**9+7
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(10001)]
prime[0]=prime[1]=False
#pp=[0]*10000
def SieveOfEratosthenes(n=10000):
p = 2
c=0
while (p <= n):
if (prime[p] == True):
c+=1
for i in range(p, n+1, p):
#pp[i]=1
prime[i] = False
p += 1
#-----------------------------------DSU--------------------------------------------------
class DSU:
def __init__(self, R, C):
#R * C is the source, and isn't a grid square
self.par = range(R*C + 1)
self.rnk = [0] * (R*C + 1)
self.sz = [1] * (R*C + 1)
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
xr, yr = self.find(x), self.find(y)
if xr == yr: return
if self.rnk[xr] < self.rnk[yr]:
xr, yr = yr, xr
if self.rnk[xr] == self.rnk[yr]:
self.rnk[xr] += 1
self.par[yr] = xr
self.sz[xr] += self.sz[yr]
def size(self, x):
return self.sz[self.find(x)]
def top(self):
# Size of component at ephemeral "source" node at index R*C,
# minus 1 to not count the source itself in the size
return self.size(len(self.sz) - 1) - 1
#---------------------------------Lazy Segment Tree--------------------------------------
# https://github.com/atcoder/ac-library/blob/master/atcoder/lazysegtree.hpp
class LazySegTree:
def __init__(self, _op, _e, _mapping, _composition, _id, v):
def set(p, x):
assert 0 <= p < _n
p += _size
for i in range(_log, 0, -1):
_push(p >> i)
_d[p] = x
for i in range(1, _log + 1):
_update(p >> i)
def get(p):
assert 0 <= p < _n
p += _size
for i in range(_log, 0, -1):
_push(p >> i)
return _d[p]
def prod(l, r):
assert 0 <= l <= r <= _n
if l == r:
return _e
l += _size
r += _size
for i in range(_log, 0, -1):
if ((l >> i) << i) != l:
_push(l >> i)
if ((r >> i) << i) != r:
_push(r >> i)
sml = _e
smr = _e
while l < r:
if l & 1:
sml = _op(sml, _d[l])
l += 1
if r & 1:
r -= 1
smr = _op(_d[r], smr)
l >>= 1
r >>= 1
return _op(sml, smr)
def apply(l, r, f):
assert 0 <= l <= r <= _n
if l == r:
return
l += _size
r += _size
for i in range(_log, 0, -1):
if ((l >> i) << i) != l:
_push(l >> i)
if ((r >> i) << i) != r:
_push((r - 1) >> i)
l2 = l
r2 = r
while l < r:
if l & 1:
_all_apply(l, f)
l += 1
if r & 1:
r -= 1
_all_apply(r, f)
l >>= 1
r >>= 1
l = l2
r = r2
for i in range(1, _log + 1):
if ((l >> i) << i) != l:
_update(l >> i)
if ((r >> i) << i) != r:
_update((r - 1) >> i)
def _update(k):
_d[k] = _op(_d[2 * k], _d[2 * k + 1])
def _all_apply(k, f):
_d[k] = _mapping(f, _d[k])
if k < _size:
_lz[k] = _composition(f, _lz[k])
def _push(k):
_all_apply(2 * k, _lz[k])
_all_apply(2 * k + 1, _lz[k])
_lz[k] = _id
_n = len(v)
_log = _n.bit_length()
_size = 1 << _log
_d = [_e] * (2 * _size)
_lz = [_id] * _size
for i in range(_n):
_d[_size + i] = v[i]
for i in range(_size - 1, 0, -1):
_update(i)
self.set = set
self.get = get
self.prod = prod
self.apply = apply
MIL = 1 << 20
def makeNode(total, count):
# Pack a pair into a float
return (total * MIL) + count
def getTotal(node):
return math.floor(node / MIL)
def getCount(node):
return node - getTotal(node) * MIL
nodeIdentity = makeNode(0.0, 0.0)
def nodeOp(node1, node2):
return node1 + node2
# Equivalent to the following:
return makeNode(
getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2)
)
identityMapping = -1
def mapping(tag, node):
if tag == identityMapping:
return node
# If assigned, new total is the number assigned times count
count = getCount(node)
return makeNode(tag * count, count)
def composition(mapping1, mapping2):
# If assigned multiple times, take first non-identity assignment
return mapping1 if mapping1 != identityMapping else mapping2
#---------------------------------Pollard rho--------------------------------------------
def memodict(f):
"""memoization decorator for a function taking a single argument"""
class memodict(dict):
def __missing__(self, key):
ret = self[key] = f(key)
return ret
return memodict().__getitem__
def pollard_rho(n):
"""returns a random factor of n"""
if n & 1 == 0:
return 2
if n % 3 == 0:
return 3
s = ((n - 1) & (1 - n)).bit_length() - 1
d = n >> s
for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
p = pow(a, d, n)
if p == 1 or p == n - 1 or a % n == 0:
continue
for _ in range(s):
prev = p
p = (p * p) % n
if p == 1:
return math.gcd(prev - 1, n)
if p == n - 1:
break
else:
for i in range(2, n):
x, y = i, (i * i + 1) % n
f = math.gcd(abs(x - y), n)
while f == 1:
x, y = (x * x + 1) % n, (y * y + 1) % n
y = (y * y + 1) % n
f = math.gcd(abs(x - y), n)
if f != n:
return f
return n
@memodict
def prime_factors(n):
"""returns a Counter of the prime factorization of n"""
if n <= 1:
return Counter()
f = pollard_rho(n)
return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)
def distinct_factors(n):
"""returns a list of all distinct factors of n"""
factors = [1]
for p, exp in prime_factors(n).items():
factors += [p**i * factor for factor in factors for i in range(1, exp + 1)]
return factors
def all_factors(n):
"""returns a sorted list of all distinct factors of n"""
small, large = [], []
for i in range(1, int(n**0.5) + 1, 2 if n & 1 else 1):
if not n % i:
small.append(i)
large.append(n // i)
if small[-1] == large[-1]:
large.pop()
large.reverse()
small.extend(large)
return small
#---------------------------------Binary Search------------------------------------------
def binarySearch(arr, n, key):
left = 0
right = n-1
mid = 0
res=arr[n-1]
while (left <= right):
mid = (right + left)//2
if (arr[mid] >= key):
res=arr[mid]
right = mid-1
else:
left = mid + 1
return res
def binarySearch1(arr, n, key):
left = 0
right = n-1
mid = 0
res=-1
while (left <= right):
mid = (right + left)//2
if (arr[mid][0] >= key):
right = mid-1
else:
res=mid
left = mid + 1
return res
#---------------------------------running code------------------------------------------
t=1
t=int(input())
for _ in range (t):
n=int(input())
#n,k=map(int,input().split())
a=list(map(int,input().split()))
#tp=list(map(int,input().split()))
#s=input()
a=a+a
s=SegmentTree1(a)
m=0
g=s.query(0, n-1)
j=0
#print(g)
for i in range (n):
j=max(j,i)
#print(i,j)
if j==i:
c=a[i]
else:
c=s.query(i, j)
while c!=g:
#print(c)
j+=1
c=math.gcd(c,a[j])
m=max(m,j-i)
#print(j-i)
print(m)
```
Yes
| 10,217 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array of positive integers a = [a_0, a_1, ..., a_{n - 1}] (n ≥ 2).
In one step, the array a is replaced with another array of length n, in which each element is the [greatest common divisor (GCD)](http://tiny.cc/tuy9uz) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the (n - 1)-th element is the 0-th element).
Formally speaking, a new array b = [b_0, b_1, ..., b_{n - 1}] is being built from array a = [a_0, a_1, ..., a_{n - 1}] such that b_i = \gcd(a_i, a_{(i + 1) mod n}), where \gcd(x, y) is the greatest common divisor of x and y, and x mod y is the remainder of x dividing by y. In one step the array b is built and then the array a is replaced with b (that is, the assignment a := b is taking place).
For example, if a = [16, 24, 10, 5] then b = [\gcd(16, 24), \gcd(24, 10), \gcd(10, 5), \gcd(5, 16)] = [8, 2, 5, 1]. Thus, after one step the array a = [16, 24, 10, 5] will be equal to [8, 2, 5, 1].
For a given array a, find the minimum number of steps after which all values a_i become equal (that is, a_0 = a_1 = ... = a_{n - 1}). If the original array a consists of identical elements then consider the number of steps is equal to 0.
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
Each test case contains two lines. The first line contains an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — length of the sequence a. The second line contains n integers a_0, a_1, ..., a_{n - 1} (1 ≤ a_i ≤ 10^6).
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
Print t numbers — answers for each test case.
Example
Input
5
4
16 24 10 5
4
42 42 42 42
3
4 6 4
5
1 2 3 4 5
6
9 9 27 9 9 63
Output
3
0
2
1
1
Submitted Solution:
```
from math import *
from collections import *
t = int(input())
def getVal(l, sp, d):
ans = 0
while d:
di = int(log2(d))
ans = gcd(ans, sp[di][l])
di = 2**di
l += di
d -= di
return ans
def isPos(sp, mid, n):
prev = getVal(0, sp, mid)
for i in range(1, n):
if prev != getVal(i, sp, mid):
return 0
return 1
def sparsiTable(a, n):
d = int(log2(n))
sp = []
sp.append([])
# [gcd(a[i], a[i+1]) for i in range(n+n-1)]
for i in range(n+n-1):
sp[-1].append(gcd(a[i], a[i+1]))
for i in range(1, d+1):
di = 2**(i-1)
lst = []
for i in range(n+n):
if i+di < len(sp[-1]):lst.append(gcd(sp[-1][i], sp[-1][i+di]))
sp.append(lst)
return sp
for _ in range(t):
n = int(input())
a = [int(v) for v in input().split()]
f = Counter(a)
if f[a[0]] == n:print(0);continue
for i in range(n):
a.append(a[i])
sp = sparsiTable(a, n)
left, right = 1, n-1
ans = 0
while left <= right:
mid = (left+right)//2
if isPos(sp, mid, n) == 0:
left = mid + 1
else:
right = mid - 1
ans = mid
print(ans)
```
Yes
| 10,218 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array of positive integers a = [a_0, a_1, ..., a_{n - 1}] (n ≥ 2).
In one step, the array a is replaced with another array of length n, in which each element is the [greatest common divisor (GCD)](http://tiny.cc/tuy9uz) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the (n - 1)-th element is the 0-th element).
Formally speaking, a new array b = [b_0, b_1, ..., b_{n - 1}] is being built from array a = [a_0, a_1, ..., a_{n - 1}] such that b_i = \gcd(a_i, a_{(i + 1) mod n}), where \gcd(x, y) is the greatest common divisor of x and y, and x mod y is the remainder of x dividing by y. In one step the array b is built and then the array a is replaced with b (that is, the assignment a := b is taking place).
For example, if a = [16, 24, 10, 5] then b = [\gcd(16, 24), \gcd(24, 10), \gcd(10, 5), \gcd(5, 16)] = [8, 2, 5, 1]. Thus, after one step the array a = [16, 24, 10, 5] will be equal to [8, 2, 5, 1].
For a given array a, find the minimum number of steps after which all values a_i become equal (that is, a_0 = a_1 = ... = a_{n - 1}). If the original array a consists of identical elements then consider the number of steps is equal to 0.
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
Each test case contains two lines. The first line contains an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — length of the sequence a. The second line contains n integers a_0, a_1, ..., a_{n - 1} (1 ≤ a_i ≤ 10^6).
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
Print t numbers — answers for each test case.
Example
Input
5
4
16 24 10 5
4
42 42 42 42
3
4 6 4
5
1 2 3 4 5
6
9 9 27 9 9 63
Output
3
0
2
1
1
Submitted Solution:
```
import math
class RMQ:
def __init__(self, arr, min_max):
self.cache = [arr]
self.func = min_max
self.precompute(arr, self.func)
def precompute(self, arr, min_max):
max_log = int(math.log2(len(arr)))
for i in range(1, max_log + 1):
new_row = []
for j in range(0, len(arr) - 2 ** i + 1):
new_row.append(min_max(self.cache[i - 1][j],
self.cache[i - 1][j + 2 ** (i - 1)]))
self.cache.append(new_row)
# should be equal to min(arr[l:r]) care l == r, plus minus 1 error
def query(self, l, r):
if l == r:
return self.cache[0][l]
if l > r:
return self.func(self.query(l,n), self.query(0,r))
log_val = int(math.log2(r - l))
return self.func(self.cache[log_val][l],
self.cache[log_val][r - 2 ** log_val])
def solve(n,seq):
rmq = RMQ(seq, math.gcd)
min_all = rmq.query(0,n)
max_op = 0
cur = 0
while cur < n:
if seq[cur] == min_all:
cur+=1
continue
for i in range(1,n+1):
if (cur+i)%n+1 == cur:
res1 = min_all
else:
res1= rmq.query(cur, (cur+i)%n+1)
if res1 == min_all:
if i > max_op:
max_op=i
break
cur = cur+i
return max_op
import os
import io
# import time
# a=time.time()
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input().decode().strip())
for t in range(T):
n = int(input().decode().strip())
seq=[int(x) for x in input().decode().strip().split(" ")]
res = solve(n,seq)
print(res)
```
No
| 10,219 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array of positive integers a = [a_0, a_1, ..., a_{n - 1}] (n ≥ 2).
In one step, the array a is replaced with another array of length n, in which each element is the [greatest common divisor (GCD)](http://tiny.cc/tuy9uz) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the (n - 1)-th element is the 0-th element).
Formally speaking, a new array b = [b_0, b_1, ..., b_{n - 1}] is being built from array a = [a_0, a_1, ..., a_{n - 1}] such that b_i = \gcd(a_i, a_{(i + 1) mod n}), where \gcd(x, y) is the greatest common divisor of x and y, and x mod y is the remainder of x dividing by y. In one step the array b is built and then the array a is replaced with b (that is, the assignment a := b is taking place).
For example, if a = [16, 24, 10, 5] then b = [\gcd(16, 24), \gcd(24, 10), \gcd(10, 5), \gcd(5, 16)] = [8, 2, 5, 1]. Thus, after one step the array a = [16, 24, 10, 5] will be equal to [8, 2, 5, 1].
For a given array a, find the minimum number of steps after which all values a_i become equal (that is, a_0 = a_1 = ... = a_{n - 1}). If the original array a consists of identical elements then consider the number of steps is equal to 0.
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
Each test case contains two lines. The first line contains an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — length of the sequence a. The second line contains n integers a_0, a_1, ..., a_{n - 1} (1 ≤ a_i ≤ 10^6).
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
Print t numbers — answers for each test case.
Example
Input
5
4
16 24 10 5
4
42 42 42 42
3
4 6 4
5
1 2 3 4 5
6
9 9 27 9 9 63
Output
3
0
2
1
1
Submitted Solution:
```
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")
#######################################
from math import gcd
for t in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
l.append(l[0])
g=0
for i in l:
g=gcd(g,i)
ans=0
i=0
while i<=n:
a=l[i]
c=0
while a!=g:
i+=1
c+=1
if i>n:
break
a=gcd(a,l[i])
i+=1
ans=max(ans,c)
print(ans)
```
No
| 10,220 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array of positive integers a = [a_0, a_1, ..., a_{n - 1}] (n ≥ 2).
In one step, the array a is replaced with another array of length n, in which each element is the [greatest common divisor (GCD)](http://tiny.cc/tuy9uz) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the (n - 1)-th element is the 0-th element).
Formally speaking, a new array b = [b_0, b_1, ..., b_{n - 1}] is being built from array a = [a_0, a_1, ..., a_{n - 1}] such that b_i = \gcd(a_i, a_{(i + 1) mod n}), where \gcd(x, y) is the greatest common divisor of x and y, and x mod y is the remainder of x dividing by y. In one step the array b is built and then the array a is replaced with b (that is, the assignment a := b is taking place).
For example, if a = [16, 24, 10, 5] then b = [\gcd(16, 24), \gcd(24, 10), \gcd(10, 5), \gcd(5, 16)] = [8, 2, 5, 1]. Thus, after one step the array a = [16, 24, 10, 5] will be equal to [8, 2, 5, 1].
For a given array a, find the minimum number of steps after which all values a_i become equal (that is, a_0 = a_1 = ... = a_{n - 1}). If the original array a consists of identical elements then consider the number of steps is equal to 0.
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
Each test case contains two lines. The first line contains an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — length of the sequence a. The second line contains n integers a_0, a_1, ..., a_{n - 1} (1 ≤ a_i ≤ 10^6).
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
Print t numbers — answers for each test case.
Example
Input
5
4
16 24 10 5
4
42 42 42 42
3
4 6 4
5
1 2 3 4 5
6
9 9 27 9 9 63
Output
3
0
2
1
1
Submitted Solution:
```
import math
t = int(input())
for i in range(t):
n = int(input())
a = list(map(int, input().split()))
suc, ans = 0, 0
for j in range(n):
if a[j] != a[0]:
break
if j == n-1:
print(0)
continue
while 1:
ans = ans + 1
b, suc = [], 1
for j in range(n):
if j == 0:
bj = math.gcd(a[0],a[1])
b.append(bj)
u = bj
elif j != n-1:
bj = math.gcd(a[j],a[j+1])
b.append(bj)
if bj != u:
suc = 0
else:
bj = math.gcd(a[n-1],a[0])
b.append(bj)
if bj != u:
suc = 0
if suc:
print(ans)
break
a = b[0:n]
```
No
| 10,221 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array of positive integers a = [a_0, a_1, ..., a_{n - 1}] (n ≥ 2).
In one step, the array a is replaced with another array of length n, in which each element is the [greatest common divisor (GCD)](http://tiny.cc/tuy9uz) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the (n - 1)-th element is the 0-th element).
Formally speaking, a new array b = [b_0, b_1, ..., b_{n - 1}] is being built from array a = [a_0, a_1, ..., a_{n - 1}] such that b_i = \gcd(a_i, a_{(i + 1) mod n}), where \gcd(x, y) is the greatest common divisor of x and y, and x mod y is the remainder of x dividing by y. In one step the array b is built and then the array a is replaced with b (that is, the assignment a := b is taking place).
For example, if a = [16, 24, 10, 5] then b = [\gcd(16, 24), \gcd(24, 10), \gcd(10, 5), \gcd(5, 16)] = [8, 2, 5, 1]. Thus, after one step the array a = [16, 24, 10, 5] will be equal to [8, 2, 5, 1].
For a given array a, find the minimum number of steps after which all values a_i become equal (that is, a_0 = a_1 = ... = a_{n - 1}). If the original array a consists of identical elements then consider the number of steps is equal to 0.
Input
The first line contains an integer t (1 ≤ t ≤ 10^4). Then t test cases follow.
Each test case contains two lines. The first line contains an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — length of the sequence a. The second line contains n integers a_0, a_1, ..., a_{n - 1} (1 ≤ a_i ≤ 10^6).
It is guaranteed that the sum of n over all test cases doesn't exceed 2 ⋅ 10^5.
Output
Print t numbers — answers for each test case.
Example
Input
5
4
16 24 10 5
4
42 42 42 42
3
4 6 4
5
1 2 3 4 5
6
9 9 27 9 9 63
Output
3
0
2
1
1
Submitted Solution:
```
import sys,os,io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# input = sys.stdin.readline
from math import gcd
def fun(a):
na = [a[0]]
cnt = 0
f = 0
for i in range (1,len(a)):
if na[-1]!=a[i]:
cnt = 0
na.append(a[i])
else:
if a[i]!=g:
cnt += 1
f = max(f,cnt)
return [na,f]
t = int(input())
for _ in range (t):
n = int(input())
a = [int(i) for i in input().split()]
n = len(a)
g = a[0]
for i in a:
g = gcd(i,g)
flag = 0
for i in a:
if i!=g:
flag = 1
break
a,ans = fun(a)
while(flag):
ans+=1
flag = 0
na = [0]*len(a)
for i in range (len(a)):
i1 = (i+1)%len(a)
na[i] = gcd(a[i], a[i1])
if na[i]!=g:
flag = 1
a = na[:]
print(ans)
```
No
| 10,222 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya plays the Geometry Horse.
The game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value.
There are n types of geometric figures. The number of figures of type ki and figure cost ci is known for each figure type. A player gets ci·f points for destroying one figure of type i, where f is the current factor. The factor value can be an integer number from 1 to t + 1, inclusive. At the beginning of the game the factor value is equal to 1. The factor is set to i + 1 after destruction of pi (1 ≤ i ≤ t) figures, so the (pi + 1)-th figure to be destroyed is considered with factor equal to i + 1.
Your task is to determine the maximum number of points Vasya can get after he destroys all figures. Take into account that Vasya is so tough that he can destroy figures in any order chosen by him.
Input
The first line contains the only integer number n (1 ≤ n ≤ 100) — the number of figure types.
Each of the following n lines contains two integer numbers ki and ci (1 ≤ ki ≤ 109, 0 ≤ ci ≤ 1000), separated with space — the number of figures of the i-th type and the cost of one i-type figure, correspondingly.
The next line contains the only integer number t (1 ≤ t ≤ 100) — the number that describe the factor's changes.
The next line contains t integer numbers pi (1 ≤ p1 < p2 < ... < pt ≤ 1012), separated with spaces.
Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.
Output
Print the only number — the maximum number of points Vasya can get.
Examples
Input
1
5 10
2
3 6
Output
70
Input
2
3 8
5 10
1
20
Output
74
Note
In the first example Vasya destroys three figures first and gets 3·1·10 = 30 points. Then the factor will become equal to 2 and after destroying the last two figures Vasya will get 2·2·10 = 40 points. As a result Vasya will get 70 points.
In the second example all 8 figures will be destroyed with factor 1, so Vasya will get (3·8 + 5·10)·1 = 74 points.
Tags: greedy, implementation, sortings, two pointers
Correct Solution:
```
import sys
def solve():
n, = rv()
figures = list()
before = 0
for i in range(n):
number, cost, = rv()
figures.append([cost, number, before, before + number])
figures.sort()
for i in range(n):
number = figures[i][1]
figures[i][2] = before
figures[i][3] = before + number
before += number
t, = rv()
p = [0] + list(map(int, input().split())) + [before]
res = 0
for i in range(1, len(p)):
for f in range(len(figures)):
left = max(figures[f][2], p[i - 1])
right = min(figures[f][3], p[i])
num = max(0, right - left)
res += num * i * figures[f][0]
# print(left, right, num, i , f, figures[f][0])
print(res)
def prt(l): return print(''.join(l))
def rv(): return map(int, input().split())
def rl(n): return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve()
# Made By Mostafa_Khaled
```
| 10,223 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya plays the Geometry Horse.
The game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value.
There are n types of geometric figures. The number of figures of type ki and figure cost ci is known for each figure type. A player gets ci·f points for destroying one figure of type i, where f is the current factor. The factor value can be an integer number from 1 to t + 1, inclusive. At the beginning of the game the factor value is equal to 1. The factor is set to i + 1 after destruction of pi (1 ≤ i ≤ t) figures, so the (pi + 1)-th figure to be destroyed is considered with factor equal to i + 1.
Your task is to determine the maximum number of points Vasya can get after he destroys all figures. Take into account that Vasya is so tough that he can destroy figures in any order chosen by him.
Input
The first line contains the only integer number n (1 ≤ n ≤ 100) — the number of figure types.
Each of the following n lines contains two integer numbers ki and ci (1 ≤ ki ≤ 109, 0 ≤ ci ≤ 1000), separated with space — the number of figures of the i-th type and the cost of one i-type figure, correspondingly.
The next line contains the only integer number t (1 ≤ t ≤ 100) — the number that describe the factor's changes.
The next line contains t integer numbers pi (1 ≤ p1 < p2 < ... < pt ≤ 1012), separated with spaces.
Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.
Output
Print the only number — the maximum number of points Vasya can get.
Examples
Input
1
5 10
2
3 6
Output
70
Input
2
3 8
5 10
1
20
Output
74
Note
In the first example Vasya destroys three figures first and gets 3·1·10 = 30 points. Then the factor will become equal to 2 and after destroying the last two figures Vasya will get 2·2·10 = 40 points. As a result Vasya will get 70 points.
In the second example all 8 figures will be destroyed with factor 1, so Vasya will get (3·8 + 5·10)·1 = 74 points.
Tags: greedy, implementation, sortings, two pointers
Correct Solution:
```
n=int(input())
a=[list(map(int,input().split()))[::-1] for i in range(n)]
t=int(input())
p=list(map(int,input().split()))
b=0
i=0
a.sort()
c=0
for j in range(n):
while i<t and p[i]-b<=a[j][1]:
c+=(p[i]-b)*(i+1)*a[j][0]
a[j][1]-=p[i]-b
b=p[i]
i+=1
c+=a[j][1]*(i+1)*a[j][0]
b+=a[j][1]
print(c)
```
| 10,224 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya plays the Geometry Horse.
The game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value.
There are n types of geometric figures. The number of figures of type ki and figure cost ci is known for each figure type. A player gets ci·f points for destroying one figure of type i, where f is the current factor. The factor value can be an integer number from 1 to t + 1, inclusive. At the beginning of the game the factor value is equal to 1. The factor is set to i + 1 after destruction of pi (1 ≤ i ≤ t) figures, so the (pi + 1)-th figure to be destroyed is considered with factor equal to i + 1.
Your task is to determine the maximum number of points Vasya can get after he destroys all figures. Take into account that Vasya is so tough that he can destroy figures in any order chosen by him.
Input
The first line contains the only integer number n (1 ≤ n ≤ 100) — the number of figure types.
Each of the following n lines contains two integer numbers ki and ci (1 ≤ ki ≤ 109, 0 ≤ ci ≤ 1000), separated with space — the number of figures of the i-th type and the cost of one i-type figure, correspondingly.
The next line contains the only integer number t (1 ≤ t ≤ 100) — the number that describe the factor's changes.
The next line contains t integer numbers pi (1 ≤ p1 < p2 < ... < pt ≤ 1012), separated with spaces.
Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.
Output
Print the only number — the maximum number of points Vasya can get.
Examples
Input
1
5 10
2
3 6
Output
70
Input
2
3 8
5 10
1
20
Output
74
Note
In the first example Vasya destroys three figures first and gets 3·1·10 = 30 points. Then the factor will become equal to 2 and after destroying the last two figures Vasya will get 2·2·10 = 40 points. As a result Vasya will get 70 points.
In the second example all 8 figures will be destroyed with factor 1, so Vasya will get (3·8 + 5·10)·1 = 74 points.
Tags: greedy, implementation, sortings, two pointers
Correct Solution:
```
import sys
def solve():
n, = rv()
figures = list()
before = 0
for i in range(n):
number, cost, = rv()
figures.append([cost, number, before, before + number])
figures.sort()
for i in range(n):
number = figures[i][1]
figures[i][2] = before
figures[i][3] = before + number
before += number
t, = rv()
p = [0] + list(map(int, input().split())) + [before]
res = 0
for i in range(1, len(p)):
for f in range(len(figures)):
left = max(figures[f][2], p[i - 1])
right = min(figures[f][3], p[i])
num = max(0, right - left)
res += num * i * figures[f][0]
# print(left, right, num, i , f, figures[f][0])
print(res)
def prt(l): return print(''.join(l))
def rv(): return map(int, input().split())
def rl(n): return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve()
```
| 10,225 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya plays the Geometry Horse.
The game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value.
There are n types of geometric figures. The number of figures of type ki and figure cost ci is known for each figure type. A player gets ci·f points for destroying one figure of type i, where f is the current factor. The factor value can be an integer number from 1 to t + 1, inclusive. At the beginning of the game the factor value is equal to 1. The factor is set to i + 1 after destruction of pi (1 ≤ i ≤ t) figures, so the (pi + 1)-th figure to be destroyed is considered with factor equal to i + 1.
Your task is to determine the maximum number of points Vasya can get after he destroys all figures. Take into account that Vasya is so tough that he can destroy figures in any order chosen by him.
Input
The first line contains the only integer number n (1 ≤ n ≤ 100) — the number of figure types.
Each of the following n lines contains two integer numbers ki and ci (1 ≤ ki ≤ 109, 0 ≤ ci ≤ 1000), separated with space — the number of figures of the i-th type and the cost of one i-type figure, correspondingly.
The next line contains the only integer number t (1 ≤ t ≤ 100) — the number that describe the factor's changes.
The next line contains t integer numbers pi (1 ≤ p1 < p2 < ... < pt ≤ 1012), separated with spaces.
Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.
Output
Print the only number — the maximum number of points Vasya can get.
Examples
Input
1
5 10
2
3 6
Output
70
Input
2
3 8
5 10
1
20
Output
74
Note
In the first example Vasya destroys three figures first and gets 3·1·10 = 30 points. Then the factor will become equal to 2 and after destroying the last two figures Vasya will get 2·2·10 = 40 points. As a result Vasya will get 70 points.
In the second example all 8 figures will be destroyed with factor 1, so Vasya will get (3·8 + 5·10)·1 = 74 points.
Tags: greedy, implementation, sortings, two pointers
Correct Solution:
```
if __name__ == '__main__':
n = int(input())
pieces = [input() for _ in range(n)]
pieces = [_.split() for _ in pieces]
pieces = [tuple(_) for _ in pieces]
pieces = [[int(k), int(c)] for k, c in pieces]
t = int(input())
p = input().split()
p = [int(_) for _ in p]
pieces = sorted(pieces, key=lambda x: x[1])
values = []
count = 0
i = 0
j = 0
while i < n and j < t:
if count + pieces[i][0] < p[j]:
values.append((pieces[i][0], pieces[i][1], j + 1))
count += pieces[i][0]
i += 1
elif count + pieces[i][0] == p[j]:
values.append((pieces[i][0], pieces[i][1], j + 1))
count += pieces[i][0]
i += 1
j += 1
else:
diff = p[j] - count
values.append((diff, pieces[i][1], j + 1))
count = p[j]
j += 1
pieces[i][0] -= diff
while i < n:
values.append((pieces[i][0], pieces[i][1], j + 1))
i += 1
score = 0
for a, b, c in values:
score += a * b * c
print(score)
```
| 10,226 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya plays the Geometry Horse.
The game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value.
There are n types of geometric figures. The number of figures of type ki and figure cost ci is known for each figure type. A player gets ci·f points for destroying one figure of type i, where f is the current factor. The factor value can be an integer number from 1 to t + 1, inclusive. At the beginning of the game the factor value is equal to 1. The factor is set to i + 1 after destruction of pi (1 ≤ i ≤ t) figures, so the (pi + 1)-th figure to be destroyed is considered with factor equal to i + 1.
Your task is to determine the maximum number of points Vasya can get after he destroys all figures. Take into account that Vasya is so tough that he can destroy figures in any order chosen by him.
Input
The first line contains the only integer number n (1 ≤ n ≤ 100) — the number of figure types.
Each of the following n lines contains two integer numbers ki and ci (1 ≤ ki ≤ 109, 0 ≤ ci ≤ 1000), separated with space — the number of figures of the i-th type and the cost of one i-type figure, correspondingly.
The next line contains the only integer number t (1 ≤ t ≤ 100) — the number that describe the factor's changes.
The next line contains t integer numbers pi (1 ≤ p1 < p2 < ... < pt ≤ 1012), separated with spaces.
Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.
Output
Print the only number — the maximum number of points Vasya can get.
Examples
Input
1
5 10
2
3 6
Output
70
Input
2
3 8
5 10
1
20
Output
74
Note
In the first example Vasya destroys three figures first and gets 3·1·10 = 30 points. Then the factor will become equal to 2 and after destroying the last two figures Vasya will get 2·2·10 = 40 points. As a result Vasya will get 70 points.
In the second example all 8 figures will be destroyed with factor 1, so Vasya will get (3·8 + 5·10)·1 = 74 points.
Tags: greedy, implementation, sortings, two pointers
Correct Solution:
```
n = int(input())
figures = []
for _ in range(n):
amount, cost = map(int, input().split())
figures += [(cost, amount)]
figures.sort()
t = int(input())
T = list(map(int, input().split()))
result = 0
destructed = 0
i, j = 0, 0
while i < len(figures):
if j < len(T) and destructed + figures[i][1] >= T[j]:
take = T[j] - destructed
destructed += take
figures[i] = (figures[i][0], figures[i][1] - take)
result += take * (j + 1) * figures[i][0]
j += 1
else:
take = figures[i][1]
destructed += take
result += take * (j + 1) * figures[i][0]
i += 1
print(result)
```
| 10,227 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya plays the Geometry Horse.
The game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value.
There are n types of geometric figures. The number of figures of type ki and figure cost ci is known for each figure type. A player gets ci·f points for destroying one figure of type i, where f is the current factor. The factor value can be an integer number from 1 to t + 1, inclusive. At the beginning of the game the factor value is equal to 1. The factor is set to i + 1 after destruction of pi (1 ≤ i ≤ t) figures, so the (pi + 1)-th figure to be destroyed is considered with factor equal to i + 1.
Your task is to determine the maximum number of points Vasya can get after he destroys all figures. Take into account that Vasya is so tough that he can destroy figures in any order chosen by him.
Input
The first line contains the only integer number n (1 ≤ n ≤ 100) — the number of figure types.
Each of the following n lines contains two integer numbers ki and ci (1 ≤ ki ≤ 109, 0 ≤ ci ≤ 1000), separated with space — the number of figures of the i-th type and the cost of one i-type figure, correspondingly.
The next line contains the only integer number t (1 ≤ t ≤ 100) — the number that describe the factor's changes.
The next line contains t integer numbers pi (1 ≤ p1 < p2 < ... < pt ≤ 1012), separated with spaces.
Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.
Output
Print the only number — the maximum number of points Vasya can get.
Examples
Input
1
5 10
2
3 6
Output
70
Input
2
3 8
5 10
1
20
Output
74
Note
In the first example Vasya destroys three figures first and gets 3·1·10 = 30 points. Then the factor will become equal to 2 and after destroying the last two figures Vasya will get 2·2·10 = 40 points. As a result Vasya will get 70 points.
In the second example all 8 figures will be destroyed with factor 1, so Vasya will get (3·8 + 5·10)·1 = 74 points.
Tags: greedy, implementation, sortings, two pointers
Correct Solution:
```
n = int(input())
fig = [tuple(map(int, input().split()))[::-1] for _ in range(n)]
fig.sort()
t = int(input())
a = list(map(int, input().split()))
res, curr = 0, 0
i, j = 0, 0
while i < n:
if j < t and curr + fig[i][1] >= a[j]:
take = a[j] - curr
curr += take
fig[i] = (fig[i][0], fig[i][1] - take)
res += take * (j + 1) * fig[i][0]
j += 1
else:
take = fig[i][1]
curr += take
res += take * (j + 1) * fig[i][0]
i += 1
print(res)
```
| 10,228 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya plays the Geometry Horse.
The game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value.
There are n types of geometric figures. The number of figures of type ki and figure cost ci is known for each figure type. A player gets ci·f points for destroying one figure of type i, where f is the current factor. The factor value can be an integer number from 1 to t + 1, inclusive. At the beginning of the game the factor value is equal to 1. The factor is set to i + 1 after destruction of pi (1 ≤ i ≤ t) figures, so the (pi + 1)-th figure to be destroyed is considered with factor equal to i + 1.
Your task is to determine the maximum number of points Vasya can get after he destroys all figures. Take into account that Vasya is so tough that he can destroy figures in any order chosen by him.
Input
The first line contains the only integer number n (1 ≤ n ≤ 100) — the number of figure types.
Each of the following n lines contains two integer numbers ki and ci (1 ≤ ki ≤ 109, 0 ≤ ci ≤ 1000), separated with space — the number of figures of the i-th type and the cost of one i-type figure, correspondingly.
The next line contains the only integer number t (1 ≤ t ≤ 100) — the number that describe the factor's changes.
The next line contains t integer numbers pi (1 ≤ p1 < p2 < ... < pt ≤ 1012), separated with spaces.
Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.
Output
Print the only number — the maximum number of points Vasya can get.
Examples
Input
1
5 10
2
3 6
Output
70
Input
2
3 8
5 10
1
20
Output
74
Note
In the first example Vasya destroys three figures first and gets 3·1·10 = 30 points. Then the factor will become equal to 2 and after destroying the last two figures Vasya will get 2·2·10 = 40 points. As a result Vasya will get 70 points.
In the second example all 8 figures will be destroyed with factor 1, so Vasya will get (3·8 + 5·10)·1 = 74 points.
Submitted Solution:
```
import sys
def solve():
n, = rv()
figures = list()
before = 0
for i in range(n):
number, cost, = rv()
figures.append([cost, number, before + 1, before + number])
figures.sort()
for i in range(n):
number = figures[i][1]
figures[i][2] = before + 1
figures[i][3] = before + number
before += number
t, = rv()
p = [0] + list(map(int, input().split()))
res = 0
for i in range(1, t + 1):
for f in range(n):
left = max(figures[f][2], p[i - 1] + 1)
right = min(figures[f][3], p[i])
num = max(0, right - left + 1)
res += num * i * figures[f][0]
# print(left, right, num, i , f, figures[f][0])
print(res)
def prt(l): return print(''.join(l))
def rv(): return map(int, input().split())
def rl(n): return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve()
```
No
| 10,229 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya plays the Geometry Horse.
The game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value.
There are n types of geometric figures. The number of figures of type ki and figure cost ci is known for each figure type. A player gets ci·f points for destroying one figure of type i, where f is the current factor. The factor value can be an integer number from 1 to t + 1, inclusive. At the beginning of the game the factor value is equal to 1. The factor is set to i + 1 after destruction of pi (1 ≤ i ≤ t) figures, so the (pi + 1)-th figure to be destroyed is considered with factor equal to i + 1.
Your task is to determine the maximum number of points Vasya can get after he destroys all figures. Take into account that Vasya is so tough that he can destroy figures in any order chosen by him.
Input
The first line contains the only integer number n (1 ≤ n ≤ 100) — the number of figure types.
Each of the following n lines contains two integer numbers ki and ci (1 ≤ ki ≤ 109, 0 ≤ ci ≤ 1000), separated with space — the number of figures of the i-th type and the cost of one i-type figure, correspondingly.
The next line contains the only integer number t (1 ≤ t ≤ 100) — the number that describe the factor's changes.
The next line contains t integer numbers pi (1 ≤ p1 < p2 < ... < pt ≤ 1012), separated with spaces.
Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.
Output
Print the only number — the maximum number of points Vasya can get.
Examples
Input
1
5 10
2
3 6
Output
70
Input
2
3 8
5 10
1
20
Output
74
Note
In the first example Vasya destroys three figures first and gets 3·1·10 = 30 points. Then the factor will become equal to 2 and after destroying the last two figures Vasya will get 2·2·10 = 40 points. As a result Vasya will get 70 points.
In the second example all 8 figures will be destroyed with factor 1, so Vasya will get (3·8 + 5·10)·1 = 74 points.
Submitted Solution:
```
n = int(input())
figures = []
for _ in range(n):
amount, cost = map(int, input().split())
figures += [(cost, amount)]
figures.sort()
t = int(input())
T = list(map(int, input().split()))
result = 0
destructed = 0
i, j = 0, 0
while i < len(figures):
if destructed + figures[i][1] >= T[j]:
take = T[j] - destructed
figures[i] = (figures[i][0], figures[i][1] - take)
result += take * (j + 1) * figures[i][0]
j += 1
else:
take = figures[i][1]
result += take * (j + 1) * figures[i][0]
i += 1
print(result)
```
No
| 10,230 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya plays the Geometry Horse.
The game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value.
There are n types of geometric figures. The number of figures of type ki and figure cost ci is known for each figure type. A player gets ci·f points for destroying one figure of type i, where f is the current factor. The factor value can be an integer number from 1 to t + 1, inclusive. At the beginning of the game the factor value is equal to 1. The factor is set to i + 1 after destruction of pi (1 ≤ i ≤ t) figures, so the (pi + 1)-th figure to be destroyed is considered with factor equal to i + 1.
Your task is to determine the maximum number of points Vasya can get after he destroys all figures. Take into account that Vasya is so tough that he can destroy figures in any order chosen by him.
Input
The first line contains the only integer number n (1 ≤ n ≤ 100) — the number of figure types.
Each of the following n lines contains two integer numbers ki and ci (1 ≤ ki ≤ 109, 0 ≤ ci ≤ 1000), separated with space — the number of figures of the i-th type and the cost of one i-type figure, correspondingly.
The next line contains the only integer number t (1 ≤ t ≤ 100) — the number that describe the factor's changes.
The next line contains t integer numbers pi (1 ≤ p1 < p2 < ... < pt ≤ 1012), separated with spaces.
Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.
Output
Print the only number — the maximum number of points Vasya can get.
Examples
Input
1
5 10
2
3 6
Output
70
Input
2
3 8
5 10
1
20
Output
74
Note
In the first example Vasya destroys three figures first and gets 3·1·10 = 30 points. Then the factor will become equal to 2 and after destroying the last two figures Vasya will get 2·2·10 = 40 points. As a result Vasya will get 70 points.
In the second example all 8 figures will be destroyed with factor 1, so Vasya will get (3·8 + 5·10)·1 = 74 points.
Submitted Solution:
```
import sys
import math
from heapq import *;
input = sys.stdin.readline
from functools import cmp_to_key;
def pi():
return(int(input()))
def pl():
return(int(input(), 16))
def ti():
return(list(map(int,input().split())))
def ts():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
mod = 1000000007;
f = [];
def fact(n,m):
global f;
f = [1 for i in range(n+1)];
f[0] = 1;
for i in range(1,n+1):
f[i] = (f[i-1]*i)%m;
def fast_mod_exp(a,b,m):
res = 1;
while b > 0:
if b & 1:
res = (res*a)%m;
a = (a*a)%m;
b = b >> 1;
return res;
def inverseMod(n,m):
return fast_mod_exp(n,m-2,m);
def ncr(n,r,m):
if n < 0 or r < 0 or r > n: return 0;
if r == 0: return 1;
return ((f[n]*inverseMod(f[n-r],m))%m*inverseMod(f[r],m))%m;
def main():
C();
def cmp(a,b):
if a[1] > b[1]: return 1;
if a[1] < b[1]: return -1;
return 0;
def C():
n = pi();
k,c = [],[];
for i in range(n):
[x,y] = ti();
k.append(x);
c.append(y);
t,p = pi(),ti();
kc = [[] for i in range(n)];
for i in range(n):
kc[i] = [k[i],c[i]];
kc.sort(key=cmp_to_key(cmp));
i,j = 0,0;
d = p[0];
ans = 0;
while j < n:
if kc[j][0] < d:
ans += kc[j][0]*(i+1)*kc[j][1];
d -= kc[j][0];
j += 1;
else:
ans += d*(i+1)*kc[j][1];
kc[j][0] -= d;
i += 1;
if i < t:
d = p[i]-p[i-1];
print(ans);
main();
```
No
| 10,231 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya plays the Geometry Horse.
The game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value.
There are n types of geometric figures. The number of figures of type ki and figure cost ci is known for each figure type. A player gets ci·f points for destroying one figure of type i, where f is the current factor. The factor value can be an integer number from 1 to t + 1, inclusive. At the beginning of the game the factor value is equal to 1. The factor is set to i + 1 after destruction of pi (1 ≤ i ≤ t) figures, so the (pi + 1)-th figure to be destroyed is considered with factor equal to i + 1.
Your task is to determine the maximum number of points Vasya can get after he destroys all figures. Take into account that Vasya is so tough that he can destroy figures in any order chosen by him.
Input
The first line contains the only integer number n (1 ≤ n ≤ 100) — the number of figure types.
Each of the following n lines contains two integer numbers ki and ci (1 ≤ ki ≤ 109, 0 ≤ ci ≤ 1000), separated with space — the number of figures of the i-th type and the cost of one i-type figure, correspondingly.
The next line contains the only integer number t (1 ≤ t ≤ 100) — the number that describe the factor's changes.
The next line contains t integer numbers pi (1 ≤ p1 < p2 < ... < pt ≤ 1012), separated with spaces.
Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.
Output
Print the only number — the maximum number of points Vasya can get.
Examples
Input
1
5 10
2
3 6
Output
70
Input
2
3 8
5 10
1
20
Output
74
Note
In the first example Vasya destroys three figures first and gets 3·1·10 = 30 points. Then the factor will become equal to 2 and after destroying the last two figures Vasya will get 2·2·10 = 40 points. As a result Vasya will get 70 points.
In the second example all 8 figures will be destroyed with factor 1, so Vasya will get (3·8 + 5·10)·1 = 74 points.
Submitted Solution:
```
import sys
def solve():
n, = rv()
figures = list()
before = 0
for i in range(n):
number, cost, = rv()
figures.append((cost, number, before + 1, before + number))
before += number
figures.sort()
t, = rv()
p = [0] + list(map(int, input().split()))
res = 0
for i in range(1, t + 1):
for f in range(n):
left = max(figures[f][2], p[i - 1] + 1)
right = min(figures[f][3], p[i])
num = right - left + 1
res += num * i * figures[f][0]
# print(left, right, num, i * figures[f][0])
print(res)
def prt(l): return print(''.join(l))
def rv(): return map(int, input().split())
def rl(n): return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
solve()
```
No
| 10,232 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.
Let's consider a set of functions of the following form:
<image> Let's define a sum of n functions y1(x), ..., yn(x) of the given type as function s(x) = y1(x) + ... + yn(x) for any x. It's easy to show that in this case the graph s(x) is a polyline. You are given n functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph s(x), that is the sum of the given functions.
Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of functions. Each of the following n lines contains two space-separated integer numbers ki, bi ( - 109 ≤ ki, bi ≤ 109) that determine the i-th function.
Output
Print a single number — the number of angles that do not equal 180 degrees in the graph of the polyline that equals the sum of the given functions.
Examples
Input
1
1 0
Output
1
Input
3
1 0
0 2
-1 1
Output
2
Input
3
-2 -4
1 7
-5 1
Output
3
Tags: geometry, math, sortings
Correct Solution:
```
def GCD(a, b):
return GCD(b,a%b) if b>0 else a
def main():
n=int(input())
S=set()
for i in range (n):
k,b=map(int,input().split())
if k:
G=GCD(abs(k),abs(b))
k//=G
b//=G
if k<0:
k=-k
b=-b
S.add((b,k))
print(len(S))
if __name__ == "__main__":
main()
```
| 10,233 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.
Let's consider a set of functions of the following form:
<image> Let's define a sum of n functions y1(x), ..., yn(x) of the given type as function s(x) = y1(x) + ... + yn(x) for any x. It's easy to show that in this case the graph s(x) is a polyline. You are given n functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph s(x), that is the sum of the given functions.
Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of functions. Each of the following n lines contains two space-separated integer numbers ki, bi ( - 109 ≤ ki, bi ≤ 109) that determine the i-th function.
Output
Print a single number — the number of angles that do not equal 180 degrees in the graph of the polyline that equals the sum of the given functions.
Examples
Input
1
1 0
Output
1
Input
3
1 0
0 2
-1 1
Output
2
Input
3
-2 -4
1 7
-5 1
Output
3
Tags: geometry, math, sortings
Correct Solution:
```
from decimal import *
n = int(input())
a = set()
for i in range(n):
k, b = map(int, input().split())
if k != 0:
a.add(Decimal(b) / Decimal(k))
print(len(a))
```
| 10,234 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.
Let's consider a set of functions of the following form:
<image> Let's define a sum of n functions y1(x), ..., yn(x) of the given type as function s(x) = y1(x) + ... + yn(x) for any x. It's easy to show that in this case the graph s(x) is a polyline. You are given n functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph s(x), that is the sum of the given functions.
Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of functions. Each of the following n lines contains two space-separated integer numbers ki, bi ( - 109 ≤ ki, bi ≤ 109) that determine the i-th function.
Output
Print a single number — the number of angles that do not equal 180 degrees in the graph of the polyline that equals the sum of the given functions.
Examples
Input
1
1 0
Output
1
Input
3
1 0
0 2
-1 1
Output
2
Input
3
-2 -4
1 7
-5 1
Output
3
Tags: geometry, math, sortings
Correct Solution:
```
from decimal import *
getcontext().prec = 35
index=0
t=int(input())
slo=list([])
while(t!=0):
k,b=map(int, input().split())
if(k!=0):
slo.append(Decimal(-b)/Decimal(k))
index+=1
t-=1
slo.sort()
res=0
i=0
slo.append(0)
slo.append(0)
while(i<index):
while(slo[i]==slo[i+1] and i<index):
i+=1
res+=1
i+=1
print(res)
```
| 10,235 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.
Let's consider a set of functions of the following form:
<image> Let's define a sum of n functions y1(x), ..., yn(x) of the given type as function s(x) = y1(x) + ... + yn(x) for any x. It's easy to show that in this case the graph s(x) is a polyline. You are given n functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph s(x), that is the sum of the given functions.
Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of functions. Each of the following n lines contains two space-separated integer numbers ki, bi ( - 109 ≤ ki, bi ≤ 109) that determine the i-th function.
Output
Print a single number — the number of angles that do not equal 180 degrees in the graph of the polyline that equals the sum of the given functions.
Examples
Input
1
1 0
Output
1
Input
3
1 0
0 2
-1 1
Output
2
Input
3
-2 -4
1 7
-5 1
Output
3
Tags: geometry, math, sortings
Correct Solution:
```
from sys import stdin
from math import gcd
n = int(stdin.readline())
iset = set()
for _ in range(n):
k,b = map(int,stdin.readline().split())
if k!=0:
if b==0:
iset.add((0,1))
else:
x = gcd(k,b)
if k*b>0:
iset.add((abs(b//x),abs(k//x)))
else:
iset.add((-abs(b//x),abs(k//x)))
print(len(iset))
```
| 10,236 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.
Let's consider a set of functions of the following form:
<image> Let's define a sum of n functions y1(x), ..., yn(x) of the given type as function s(x) = y1(x) + ... + yn(x) for any x. It's easy to show that in this case the graph s(x) is a polyline. You are given n functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph s(x), that is the sum of the given functions.
Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of functions. Each of the following n lines contains two space-separated integer numbers ki, bi ( - 109 ≤ ki, bi ≤ 109) that determine the i-th function.
Output
Print a single number — the number of angles that do not equal 180 degrees in the graph of the polyline that equals the sum of the given functions.
Examples
Input
1
1 0
Output
1
Input
3
1 0
0 2
-1 1
Output
2
Input
3
-2 -4
1 7
-5 1
Output
3
Tags: geometry, math, sortings
Correct Solution:
```
from sys import stdin, stdout
from decimal import Decimal
n = int(stdin.readline())
visit = []
for i in range(n):
k, b = map(Decimal, stdin.readline().split())
if not k:
continue
visit.append(-b/k)
visit.sort()
if len(visit):
ans = 1
else:
ans = 0
e = Decimal(10) ** Decimal(-10)
for i in range(1, len(visit)):
if visit[i] != visit[i - 1]:
ans += 1
stdout.write(str(ans))
```
| 10,237 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.
Let's consider a set of functions of the following form:
<image> Let's define a sum of n functions y1(x), ..., yn(x) of the given type as function s(x) = y1(x) + ... + yn(x) for any x. It's easy to show that in this case the graph s(x) is a polyline. You are given n functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph s(x), that is the sum of the given functions.
Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of functions. Each of the following n lines contains two space-separated integer numbers ki, bi ( - 109 ≤ ki, bi ≤ 109) that determine the i-th function.
Output
Print a single number — the number of angles that do not equal 180 degrees in the graph of the polyline that equals the sum of the given functions.
Examples
Input
1
1 0
Output
1
Input
3
1 0
0 2
-1 1
Output
2
Input
3
-2 -4
1 7
-5 1
Output
3
Tags: geometry, math, sortings
Correct Solution:
```
from fractions import gcd
s = set()
for _ in range(int(input())):
k, b = map(int, input().split())
if b and k:
g = gcd(k, b)
s.add((k // g, b // g))
elif k:
s.add((0, 0))
print(len(s))
```
| 10,238 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.
Let's consider a set of functions of the following form:
<image> Let's define a sum of n functions y1(x), ..., yn(x) of the given type as function s(x) = y1(x) + ... + yn(x) for any x. It's easy to show that in this case the graph s(x) is a polyline. You are given n functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph s(x), that is the sum of the given functions.
Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of functions. Each of the following n lines contains two space-separated integer numbers ki, bi ( - 109 ≤ ki, bi ≤ 109) that determine the i-th function.
Output
Print a single number — the number of angles that do not equal 180 degrees in the graph of the polyline that equals the sum of the given functions.
Examples
Input
1
1 0
Output
1
Input
3
1 0
0 2
-1 1
Output
2
Input
3
-2 -4
1 7
-5 1
Output
3
Submitted Solution:
```
from sys import stdin
from math import gcd
n = int(stdin.readline())
iset = set()
for _ in range(n):
k,b = map(int,stdin.readline().split())
if k!=0:
if b==0:
iset.add((0,1))
else:
x = gcd(k,b)
iset.add((-b//x,k//x))
print(len(iset))
```
No
| 10,239 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.
Let's consider a set of functions of the following form:
<image> Let's define a sum of n functions y1(x), ..., yn(x) of the given type as function s(x) = y1(x) + ... + yn(x) for any x. It's easy to show that in this case the graph s(x) is a polyline. You are given n functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph s(x), that is the sum of the given functions.
Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of functions. Each of the following n lines contains two space-separated integer numbers ki, bi ( - 109 ≤ ki, bi ≤ 109) that determine the i-th function.
Output
Print a single number — the number of angles that do not equal 180 degrees in the graph of the polyline that equals the sum of the given functions.
Examples
Input
1
1 0
Output
1
Input
3
1 0
0 2
-1 1
Output
2
Input
3
-2 -4
1 7
-5 1
Output
3
Submitted Solution:
```
def GCD(a, b):
return GCD(b,a%b) if b>0 else a
def main():
n=int(input())
S=set()
for i in range (n):
k,b=map(int,input().split())
if k:
G=GCD(k,b)
k/=G
b/=G
if k<0:
k=-k
b=-b
S.add((k,b))
print(len(S))
if __name__ == "__main__":
main()
```
No
| 10,240 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.
Let's consider a set of functions of the following form:
<image> Let's define a sum of n functions y1(x), ..., yn(x) of the given type as function s(x) = y1(x) + ... + yn(x) for any x. It's easy to show that in this case the graph s(x) is a polyline. You are given n functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph s(x), that is the sum of the given functions.
Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of functions. Each of the following n lines contains two space-separated integer numbers ki, bi ( - 109 ≤ ki, bi ≤ 109) that determine the i-th function.
Output
Print a single number — the number of angles that do not equal 180 degrees in the graph of the polyline that equals the sum of the given functions.
Examples
Input
1
1 0
Output
1
Input
3
1 0
0 2
-1 1
Output
2
Input
3
-2 -4
1 7
-5 1
Output
3
Submitted Solution:
```
from sys import stdin, stdout
n = int(stdin.readline())
visit = []
e1 = 10 ** (-3)
e2 = 10 ** (-2)
for i in range(n):
k, b = map(int, stdin.readline().split())
if 10 ** 10 * k + b > 0:
r = 10 ** 10
l = - 10 ** 10
else:
r = - 10 ** 10
l = 10 ** 10
while (max(l, r) - min(l, r) > e1):
m = (r + l) / 2
if k * m + b >= 0:
r = m
else:
l = m
visit.append((r, k, b))
visit.sort()
ans = 1
for i in range(1, n):
if abs(visit[i][0] - visit[i - 1][0]) > e2 and abs(visit[i][0] * visit[i][1] + visit[i][2]) < e2:
ans += 1
stdout.write(str(ans))
```
No
| 10,241 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.
Let's consider a set of functions of the following form:
<image> Let's define a sum of n functions y1(x), ..., yn(x) of the given type as function s(x) = y1(x) + ... + yn(x) for any x. It's easy to show that in this case the graph s(x) is a polyline. You are given n functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph s(x), that is the sum of the given functions.
Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of functions. Each of the following n lines contains two space-separated integer numbers ki, bi ( - 109 ≤ ki, bi ≤ 109) that determine the i-th function.
Output
Print a single number — the number of angles that do not equal 180 degrees in the graph of the polyline that equals the sum of the given functions.
Examples
Input
1
1 0
Output
1
Input
3
1 0
0 2
-1 1
Output
2
Input
3
-2 -4
1 7
-5 1
Output
3
Submitted Solution:
```
from sys import stdin, stdout
from decimal import Decimal
n = int(stdin.readline())
visit = []
for i in range(n):
k, b = map(Decimal, stdin.readline().split())
if not k:
continue
visit.append(-b/k)
visit.sort()
ans = 1
e = Decimal(10) ** Decimal(-10)
for i in range(1, len(visit)):
if abs(visit[i] - visit[i - 1]) > e:
ans += 1
stdout.write(str(ans))
```
No
| 10,242 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.
The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.
Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.
Input
The first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.
Output
In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.
Examples
Input
3
2 1
2 3
Output
0
2
Input
4
1 4
2 4
3 4
Output
2
1 2 3
Tags: dfs and similar, dp, graphs, trees
Correct Solution:
```
#More es mi pastor nada me faltara
import sys
from collections import defaultdict
from typing import NamedTuple
class EdgeNode(NamedTuple):
vertex: int
weight: int
#vertex1: int
class Graph:
def __init__(self, n):
self.graph = d = {i: [] for i in range(n + 1)}
self.distance = [0] * (n + 1)
self.distance[0] = sys.maxsize
self.min_dist = sys.maxsize
self.summation = (n * (n + 1)) / 2
def dfs(self, root, visited=defaultdict(bool)):
stack, path = [root], []
rev = 0
visited[root] = True
while stack:
s = stack.pop()
visited[s] = True
for v in self.graph[s]:
if v[0] not in visited:
dist = self.distance[s] + v[1]
if dist < self.min_dist:
self.min_dist = dist
self.distance[v[0]] = dist
self.summation -= v[0]
if v[1] == -1:
rev += 1
path.append(s)
stack.append(v[0])
return rev
def get_min_distance(self):
return min(self.distance)
def main():
n = int(input())
g = Graph(n)
for i in range(n - 1):
x, y = map(int, input().split())
g.graph[x].append([y, 1])
g.graph[y].append([x, -1])
total_rev = g.dfs(1)
min_distance = 0 if (g.summation > 0 and g.min_dist > 0) else g.min_dist
print(total_rev + min_distance)
join = ' '.join(map(str, [i for i in range(n + 1) if g.distance[i] == min_distance]))
print(join)
main()
```
| 10,243 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.
The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.
Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.
Input
The first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.
Output
In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.
Examples
Input
3
2 1
2 3
Output
0
2
Input
4
1 4
2 4
3 4
Output
2
1 2 3
Tags: dfs and similar, dp, graphs, trees
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
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")
sys.setrecursionlimit(2*10**5)
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
@bootstrap
def dfs(u,p):
for j in adj[u]:
if j!=p:
yield dfs(j, u)
val[u]+=(val[j]+d[u,j])
yield
@bootstrap
def dfs2(u,p,v):
ans[u]=val[u]+v
for j in adj[u]:
if j != p:
yield dfs2(j,u,val[u]-val[j]-d[u,j]+v+d[j,u])
yield
n=int(input())
adj=[[] for i in range(n+1)]
d=dict()
for j in range(n-1):
u,v=map(int,input().split())
adj[u].append(v)
adj[v].append(u)
d[u,v]=0
d[v,u]=1
val=[0]*(n+1)
dfs(1,0)
ans=[0]*(n+1)
d[1,0]=0
dfs2(1,0,0)
m=min(ans[1:])
res=[]
for j in range(1,n+1):
if ans[j]==m:
res.append(j)
print(m)
print(*res)
```
| 10,244 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.
The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.
Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.
Input
The first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.
Output
In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.
Examples
Input
3
2 1
2 3
Output
0
2
Input
4
1 4
2 4
3 4
Output
2
1 2 3
Tags: dfs and similar, dp, graphs, trees
Correct Solution:
```
# Author : nitish420 --------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
from collections import deque
def main():
n=int(input())
tree=[[] for _ in range(n+1)]
path=[set() for _ in range(n+1)]
straight=[0]*(n+1)
reverse=[0]*(n+1)
for _ in range(n-1):
a,b=map(int,input().split())
tree[a].append(b)
tree[b].append(a)
path[a].add(b)
idx=[0]*(n+1)
root=[(1,0)]
totalrev=0
while root:
x,p=root[-1]
y=idx[x]
if y==len(tree[x]):
root.pop()
else:
z=tree[x][y]
if z!=p:
root.append((z,x))
if z not in path[x]:
reverse[z]=1+reverse[x]
straight[z]=straight[x]
totalrev+=1
else:
reverse[z]=reverse[x]
straight[z]=1+straight[x]
idx[x]+=1
ans=totalrev
arr=[1]
# print(totalrev)
# print(*reverse)
# print(*straight)
# now using parent go from each node to other
for i in range(2,n+1):
temp=totalrev-reverse[i]+straight[i]
if ans>temp:
ans=temp
arr=[i]
elif ans==temp:
arr.append(i)
print(ans)
print(*arr)
#----------------------------------------------------------------------------------------
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# endregion
if __name__ == '__main__':
main()
```
| 10,245 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.
The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.
Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.
Input
The first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.
Output
In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.
Examples
Input
3
2 1
2 3
Output
0
2
Input
4
1 4
2 4
3 4
Output
2
1 2 3
Tags: dfs and similar, dp, graphs, trees
Correct Solution:
```
import sys
from collections import defaultdict
from typing import NamedTuple
class EdgeNode(NamedTuple):
vertex: int
weight: int
class Graph:
def __init__(self, n):
self.graph = d = {i: [] for i in range(n + 1)}
self.distance = [0] * (n + 1)
self.distance[0] = sys.maxsize
self.min_dist = sys.maxsize
self.summation = (n * (n + 1)) / 2
def dfs(self, root, visited=defaultdict(bool)):
stack, path = [root], []
rev = 0
visited[root] = True
while stack:
s = stack.pop()
visited[s] = True
for v in self.graph[s]:
if v[0] not in visited:
dist = self.distance[s] + v[1]
if dist < self.min_dist:
self.min_dist = dist
self.distance[v[0]] = dist
self.summation -= v[0]
if v[1] == -1:
rev += 1
path.append(s)
stack.append(v[0])
return rev
def get_min_distance(self):
return min(self.distance)
def main():
n = int(input())
g = Graph(n)
for i in range(n - 1):
x, y = map(int, input().split())
g.graph[x].append([y, 1])
g.graph[y].append([x, -1])
total_rev = g.dfs(1)
min_distance = 0 if (g.summation > 0 and g.min_dist > 0) else g.min_dist
print(total_rev + min_distance)
join = ' '.join(map(str, [i for i in range(n + 1) if g.distance[i] == min_distance]))
print(join)
main()
```
| 10,246 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.
The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.
Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.
Input
The first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.
Output
In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.
Examples
Input
3
2 1
2 3
Output
0
2
Input
4
1 4
2 4
3 4
Output
2
1 2 3
Tags: dfs and similar, dp, graphs, trees
Correct Solution:
```
#More es mi pastor nada me faltara
import sys
from collections import defaultdict
from typing import NamedTuple
class EdgeNode(NamedTuple):
vertex: int
weight: int
class Graph:
def __init__(self, n):
self.graph = d = {i: [] for i in range(n + 1)}
self.distance = [0] * (n + 1)
self.distance[0] = sys.maxsize
self.min_dist = sys.maxsize
self.summation = (n * (n + 1)) / 2
def dfs(self, root, visited=defaultdict(bool)):
stack, path = [root], []
rev = 0
visited[root] = True
while stack:
s = stack.pop()
visited[s] = True
for v in self.graph[s]:
if v[0] not in visited:
dist = self.distance[s] + v[1]
if dist < self.min_dist:
self.min_dist = dist
self.distance[v[0]] = dist
self.summation -= v[0]
if v[1] == -1:
rev += 1
path.append(s)
stack.append(v[0])
return rev
def get_min_distance(self):
return min(self.distance)
def main():
n = int(input())
g = Graph(n)
for i in range(n - 1):
x, y = map(int, input().split())
g.graph[x].append([y, 1])
g.graph[y].append([x, -1])
total_rev = g.dfs(1)
min_distance = 0 if (g.summation > 0 and g.min_dist > 0) else g.min_dist
print(total_rev + min_distance)
join = ' '.join(map(str, [i for i in range(n + 1) if g.distance[i] == min_distance]))
print(join)
main()
```
| 10,247 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.
The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.
Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.
Input
The first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.
Output
In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.
Examples
Input
3
2 1
2 3
Output
0
2
Input
4
1 4
2 4
3 4
Output
2
1 2 3
Tags: dfs and similar, dp, graphs, trees
Correct Solution:
```
from math import sqrt,gcd,ceil,floor,log,factorial
from itertools import permutations,combinations
from collections import Counter, defaultdict
import collections,sys,threading
import collections,sys,threading
sys.setrecursionlimit(10**9)
threading.stack_size(10**8)
def solve():
def dfs_red(node,par,dire,undire,dist,path_red,red):
dist[node]=1+dist[par]
if par in dire[node]:
path_red[node]=1+path_red[par]
red.append(1)
else:
path_red[node]=path_red[par]
for i in undire[node]:
if i!=par:
dfs_red(i,node,dire,undire,dist,path_red,red)
def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().split())
def msi(): return map(str,input().split())
def li(): return list(mi())
n=ii()
dire=defaultdict(list)
undire=defaultdict(list)
dist,path_red={},{}
dist[0]=-1;path_red[0]=0
#totred=0
for _ in range(n-1):
u,v=mi()
dire[u].append(v)
undire[u].append(v)
undire[v].append(u)
#visited[i]=[0]*(n+1)
red=[]
dfs_red(1,0,dire,undire,dist,path_red,red)
totred=len(red)
ans=10**9
res=[0];fin=[]
for i in range(1,n+1):
res.append(totred-2*path_red[i]+dist[i])
ans=min(ans,totred-2*path_red[i]+dist[i])
for i in range(1,n+1):
if res[i]==ans:
fin.append(i)
print(ans)
print(*fin)
threading.Thread(target=solve).start()
```
| 10,248 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.
The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.
Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.
Input
The first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.
Output
In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.
Examples
Input
3
2 1
2 3
Output
0
2
Input
4
1 4
2 4
3 4
Output
2
1 2 3
Tags: dfs and similar, dp, graphs, trees
Correct Solution:
```
# -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 1/13/20
"""
import collections
import time
import os
import sys
import bisect
import heapq
from typing import List
def redOfTree(node, parent, g):
count = 0
for v, c in g[node]:
if v != parent:
count += c + redOfTree(v, node, g)
return count
def solve(N, A):
INF = N+100
flips = [INF for _ in range(N + 1)]
q = [(1, 0, 0)]
redCount = 0
flips[1] = 0
while q:
nq = []
for node, red, dist in q:
for v, c in A[node]:
if flips[v] == INF:
redCount += c
ndist, nred = dist + 1, red + c
flips[v] = ndist - 2 * nred
nq.append((v, nred, ndist))
q = nq
# def dfs(node, parent, red, dist):
# x = dist - 2 * red
# flips[node] = x
# ans = x
#
# for v, c in A[node]:
# if v != parent:
# ans = min(ans, dfs(v, node, red + c, dist + 1))
#
# return ans
#
# mf = dfs(1, -1, 0, 0)
mf = min(flips)
# redCount = redOfTree(1, -1, A)
vertex = [i for i, v in enumerate(flips) if v == mf]
# print(redCount)
# print(flips)
# print(vertex)
print(redCount + mf)
print(' '.join(map(str, vertex)))
N = int(input())
A = [[] for _ in range(N+1)]
for i in range(N - 1):
u, v = map(int, input().split())
A[u].append((v, 0))
A[v].append((u, 1))
solve(N, A)
```
| 10,249 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.
The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.
Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.
Input
The first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.
Output
In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.
Examples
Input
3
2 1
2 3
Output
0
2
Input
4
1 4
2 4
3 4
Output
2
1 2 3
Tags: dfs and similar, dp, graphs, trees
Correct Solution:
```
n=int(input())
t=[0]*(n+1)
u,v=[[]for i in range(n+1)],[[]for i in range(n+1)]
for i in range(n-1):
x,y=map(int,input().split())
t[y]=1
u[x].append(y)
v[y].append(x)
d, s = u[1] + v[1], len(v[1])
for i in u[1]:
t[i]=1
v[i].remove(1)
for i in v[1]:
t[i]=-1
u[i].remove(1)
while d:
b=d.pop()
for i in u[b]:
t[i]=t[b]+1
v[i].remove(b)
for i in v[b]:
t[i]=t[b]-1
u[i].remove(b)
d+=u[b]+v[b]
s+=len(v[b])
m=min(t)
print(s+m)
print(' '.join(map(str,[i for i in range(1,n+1) if t[i]==m])))
```
| 10,250 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.
The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.
Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.
Input
The first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.
Output
In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.
Examples
Input
3
2 1
2 3
Output
0
2
Input
4
1 4
2 4
3 4
Output
2
1 2 3
Submitted Solution:
```
# Author : nitish420 --------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
mod=10**9+7
from collections import defaultdict
def main():
n=int(input())
tree=[[] for _ in range(n+1)]
path=[set() for _ in range(n+1)]
for _ in range(n-1):
a,b=map(int,input().split())
tree[a].append(b)
tree[b].append(a)
path[a].add(b)
dist=[0]*(n+1)
d=defaultdict(int)
stack=[(1,0,0)]
# assuming root 1
idx=[0]*(n+1)
totalGreen=0
while stack:
x,p,g=stack[-1]
y=idx[x]
if y==len(tree[x]):
d[x]=g
stack.pop()
else:
z=tree[x][y]
if z!=p:
if z in path[x]:
g+=1
totalGreen+=1
stack.append((z,x,g))
dist[z]=1+dist[x]
idx[x]+=1
totalRed=n-1-totalGreen
res=[0]*(n+1)
ans=10**10
for i in range(1,n+1):
res[i]=(d[i]<<1)+totalRed-dist[i]
ans=min(ans,res[i])
print(ans)
for i in range(1,n+1):
if res[i]==ans:
print(i,end=" ")
print()
#----------------------------------------------------------------------------------------
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = 'x' in file.mode or 'r' not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b'\n') + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode('ascii'))
self.read = lambda: self.buffer.read().decode('ascii')
self.readline = lambda: self.buffer.readline().decode('ascii')
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip('\r\n')
# endregion
if __name__ == '__main__':
main()
```
Yes
| 10,251 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.
The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.
Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.
Input
The first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.
Output
In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.
Examples
Input
3
2 1
2 3
Output
0
2
Input
4
1 4
2 4
3 4
Output
2
1 2 3
Submitted Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
def in_arr():
return map(int,raw_input().split())
def pr_num(n):
stdout.write(str(n)+'\n')
def pr_arr(arr):
pr(' '.join(map(str,arr))+'\n')
#range = xrange # not for python 3.0+
# main code
n=int(raw_input())
d=[[] for i in range(n+1)]
for i in range(n-1):
u,v=in_arr()
d[u].append((v,0))
d[v].append((u,1))
totr=0
dp=[[0,0] for i in range(n+1)]
q=[1]
vis=[0]*(n+1)
vis[1]=1
q=[1]
pos=0
while pos<n:
x=q[pos]
pos+=1
for i,w in d[x]:
if not vis[i]:
vis[i]=1
q.append(i)
dp[i][0]=dp[x][0]+1
dp[i][1]=dp[x][1]
if w:
totr+=1
dp[i][1]+=1
#ans=defaultdict(list)
mn=10**18
for i in range(1,n+1):
temp=totr-(2*dp[i][1])+dp[i][0]
#ans[temp].append(i)
mn=min(mn,temp)
pr_num(mn)
for i in range(1,n+1):
temp=totr-(2*dp[i][1])+dp[i][0]
#ans[temp].append(i)
if temp==mn:
pr(str(i)+' ')
#pr_arr(ans[mn])
```
Yes
| 10,252 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.
The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.
Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.
Input
The first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.
Output
In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.
Examples
Input
3
2 1
2 3
Output
0
2
Input
4
1 4
2 4
3 4
Output
2
1 2 3
Submitted Solution:
```
#TESTING ANOTHER SOLUTION FOR TIME LIMIT
n = int(input())
t = [0] * (n + 1)
u, v = [[] for i in range(n + 1)], [[] for i in range(n + 1)]
for i in range(n - 1):
a, b = map(int, input().split())
t[b] = 1
u[a].append(b)
v[b].append(a)
d, s = u[1] + v[1], len(v[1])
for i in u[1]:
t[i] = 1
v[i].remove(1)
for i in v[1]:
t[i] = -1
u[i].remove(1)
while d:
b = d.pop()
x, y = t[b] + 1, t[b] - 1
for i in u[b]:
t[i] = x
v[i].remove(b)
for i in v[b]:
t[i] = y
u[i].remove(b)
d += u[b] + v[b]
s += len(v[b])
m = min(t)
print(s + m)
print(' '.join(map(str, [i for i in range(1, n + 1) if t[i] == m])))
```
Yes
| 10,253 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.
The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.
Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.
Input
The first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.
Output
In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.
Examples
Input
3
2 1
2 3
Output
0
2
Input
4
1 4
2 4
3 4
Output
2
1 2 3
Submitted Solution:
```
from sys import stdin, stdout
input = stdin.readline
n = int(input())
mn = n
e, down, up = {(1, 0)}, [0] * (n + 1), [0] * (n + 1)
g = {x: [] for x in range(1, n + 1)}
for i in range(n - 1):
a, b = map(int, input().split())
e.add((a, b))
g[a].append(b)
g[b].append(a)
q = [(0, 1)]
trav = [(0, 1)]
while q:
p, v = q.pop()
for ch in g[v]:
if ch != p:
q.append((v, ch))
trav.append((v, ch))
for p, v in trav[::-1]:
down[v] = sum(down[ch] + ((v, ch) not in e) for ch in g[v] if ch != p)
up[0] = down[1] + 1
q = [(0, 1)]
while q:
p, v = q.pop()
up[v] = down[p] + up[p] - down[v] + [1, -1][(v, p) in e]
if down[v] + up[v] < mn:
ans, mn = [v], down[v] + up[v]
elif down[v] + up[v] == mn:
ans.append(v)
for ch in g[v]:
if ch != p:
q.append((v, ch))
print(mn)
stdout.write(' '.join(str(i) for i in sorted(ans)))
```
Yes
| 10,254 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.
The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.
Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.
Input
The first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.
Output
In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.
Examples
Input
3
2 1
2 3
Output
0
2
Input
4
1 4
2 4
3 4
Output
2
1 2 3
Submitted Solution:
```
import sys
from collections import defaultdict
from typing import NamedTuple
class EdgeNode(NamedTuple):
vertex: int
weight: int
class Graph:
def __init__(self, n):
self.graph = defaultdict(list)
self.distance = (n + 1) * [0]
self.distance[0] = sys.maxsize
def add_edge(self, u, v, weight=0):
self.graph[u].append(EdgeNode(vertex=v, weight=weight))
def dfs(self, root, visited=defaultdict(bool)):
stack, path = [root], []
rev = 0
while stack:
s = stack.pop()
if s in path:
continue
path.append(s)
for v in self.graph[s]:
stack.append(v.vertex)
self.distance[v.vertex] = self.distance[s] + v.weight
if v.weight == -1:
rev = rev + 1
return rev
def get_min_distance(self):
return min(self.distance)
#sys.stdin = open('input.txt', 'r')
n = int(input())
g = Graph(n)
for i in range(n - 1):
x, y = map(int, input().split())
g.add_edge(x, y, 1)
g.add_edge(y, x, -1)
total_rev = g.dfs(1)
min_distance = g.get_min_distance()
print(total_rev + min_distance - 1)
print(' '.join(map(str, [i for i in range(n + 1) if g.distance[i] == min_distance])))
```
No
| 10,255 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.
The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.
Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.
Input
The first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.
Output
In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.
Examples
Input
3
2 1
2 3
Output
0
2
Input
4
1 4
2 4
3 4
Output
2
1 2 3
Submitted Solution:
```
import typing
#219D
totalRed = 0
t = 0
#adj(u)= <v,1> = v en sentido directo (u,v), <j,0> = j en
# sentido opuesto (j, u)
def dfs(u):
global t,totalRed
t += 1
d[u] = t
for p in adj[u]: #adj[]son <v, (0 v 1)> v el vert adj y el 2do valor si la arista es roja
v = p[0]
red = p[1] == 0;
if d[v] == 0:
dist[v] = dist[u] + 1
if red :#aumento actualizo total y rojas de raiz a v
totalRed += 1
redsUntil[v] = redsUntil[u] + 1
dfs(v)
t += 1
f[u] = t
def solve():
dfs(0)
min = 1e9
list = []
for i in range(0, n):
toChange = dist[i] + totalRed - 2*redsUntil[i]
if toChange < min:
min = toChange
list = [i]
elif toChange == min:
list.append(i)
return (min, list)
#read/////////////////////
n = input()
n = int(n)
t = 0
dist = [0 for x in range(0, n)]
f = [0 for x in range(0, n)]
d = [0 for x in range(0, n)]
redsUntil = [0 for x in range(0, n)]
adj = [[] for x in range(0, n)]
for i in range(0, n-1):
a, b = [x for x in input().split()]
a = int(a)
b = int(b)
a-=1
b-=1
adj[a].append((b, 1))
adj[b].append((a, 0))
#/////////////----////////
#Process
dfs(0)
min = 1e9
list = []
for i in range(0, n):
toChange = dist[i] + totalRed - 2*redsUntil[i]#Calculo aristas a cambiar para cada vert
if toChange < min:#nuevo min
min = toChange
list = [i]
elif toChange == min:
list.append(i)
#Out//////////////////////
print(min)
print(' '.join([str(a+1) for a in list]))
# out = []
# for i in range(0, len(list)):
# print(list[i] + 1)
```
No
| 10,256 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.
The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.
Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.
Input
The first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.
Output
In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.
Examples
Input
3
2 1
2 3
Output
0
2
Input
4
1 4
2 4
3 4
Output
2
1 2 3
Submitted Solution:
```
#TESTING @Emberald for time limit
# w, h = map(int, input().split())
# to_zero_based = lambda x: int(x) - 1
def main():
n = int(input())
cities = {i : {} for i in range(n)}
to_zero_based = lambda x: int(x) - 1
for _ in range(n - 1):
s, t = map(to_zero_based, input().split())
cities[s][t] = True
cities[t][s] = False
ipivot = 0
invs_if_capital = 0
stack = [ipivot]
visited = set()
path = []
while stack:
icity = stack.pop()
visited.add(icity)
path.append((icity, None))
for ineighbor, goto in cities[icity].items():
if ineighbor in visited:
continue
if not goto:
invs_if_capital += 1
stack.append(ineighbor)
path.append((ineighbor, goto))
invs_if_capitals = {ipivot : invs_if_capital}
icity = None
for index, goto in path:
if goto is None:
icity = index
else:
invs_if_capitals[index] = invs_if_capitals[icity] + (1 if goto else -1)
min_invs = min(invs_if_capitals.values())
mins = [str(i + 1) for i, invs in invs_if_capitals.items() if invs == min_invs]
print(min_invs)
print(' '.join(mins))
main()
```
No
| 10,257 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.
The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.
Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.
Input
The first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.
Output
In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.
Examples
Input
3
2 1
2 3
Output
0
2
Input
4
1 4
2 4
3 4
Output
2
1 2 3
Submitted Solution:
```
import sys
from collections import defaultdict
from typing import NamedTuple
class EdgeNode(NamedTuple):
vertex: int
weight: int
class Graph:
def __init__(self, n):
self.graph = d = {i: [] for i in range(n + 1)}
self.distance = [0] * (n + 1)
self.distance[0] = sys.maxsize
self.min_dist = sys.maxsize
self.summation = (n * (n + 1)) / 2
def add_edge(self, u, v, weight=0):
self.graph[u].append(EdgeNode(vertex=v, weight=weight))
def dfs(self, root, visited=defaultdict(bool)):
stack, path = [root], []
rev = 0
visited[root] = True
while stack:
s = stack.pop()
visited[s] = True
for v in self.graph[s]:
if v.vertex not in visited:
dist = self.distance[s] + v.weight
if dist < self.min_dist:
self.min_dist = dist
self.distance[v.vertex] = dist
self.summation -= v.vertex
if v.weight == -1:
rev += 1
path.append(s)
stack.append(v.vertex)
return rev
def get_min_distance(self):
return min(self.distance)
# sys.stdin = open('input.txt', 'r')
n = int(input())
g = Graph(n)
for i in range(n - 1):
x, y = map(int, input().split())
g.add_edge(x, y, 1)
g.add_edge(y, x, -1)
total_rev = g.dfs(1)
min_distance = 0 if g.summation > 0 else g.min_dist
print(total_rev + min_distance)
print(' '.join(map(str, [i for i in range(n + 1) if g.distance[i] == min_distance])))
```
No
| 10,258 |
Provide tags and a correct Python 2 solution for this coding contest problem.
Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an.
Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar.
Polycarpus took a piece of paper and wrote out the values of function f(l, r) for all l, r (l, r are integer, 1 ≤ l ≤ r ≤ n). Now he wants to know, how many distinct values he's got in the end.
Help Polycarpus, count the number of distinct values of function f(l, r) for the given sequence a.
Expression x | y means applying the operation of bitwise OR to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or".
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements of sequence a. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 106) — the elements of sequence a.
Output
Print a single integer — the number of distinct values of function f(l, r) for the given sequence a.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
3
1 2 0
Output
4
Input
10
1 2 3 4 5 6 1 2 9 10
Output
11
Note
In the first test case Polycarpus will have 6 numbers written on the paper: f(1, 1) = 1, f(1, 2) = 3, f(1, 3) = 3, f(2, 2) = 2, f(2, 3) = 2, f(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3.
Tags: bitmasks
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
def in_num():
return int(raw_input())
def in_arr():
return tuple(map(int,raw_input().split()))
def pr_num(n):
stdout.write(str(n)+'\n')
def pr_arr(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
n=input()
l=in_arr()
ans=set()
temp=set()
for i in l:
temp=set([i|j for j in temp])
temp.add(i)
ans.update(temp)
pr_num(len(ans))
```
| 10,259 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an.
Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar.
Polycarpus took a piece of paper and wrote out the values of function f(l, r) for all l, r (l, r are integer, 1 ≤ l ≤ r ≤ n). Now he wants to know, how many distinct values he's got in the end.
Help Polycarpus, count the number of distinct values of function f(l, r) for the given sequence a.
Expression x | y means applying the operation of bitwise OR to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or".
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements of sequence a. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 106) — the elements of sequence a.
Output
Print a single integer — the number of distinct values of function f(l, r) for the given sequence a.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
3
1 2 0
Output
4
Input
10
1 2 3 4 5 6 1 2 9 10
Output
11
Note
In the first test case Polycarpus will have 6 numbers written on the paper: f(1, 1) = 1, f(1, 2) = 3, f(1, 3) = 3, f(2, 2) = 2, f(2, 3) = 2, f(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3.
Tags: bitmasks
Correct Solution:
```
n, a, b = input(), set(), set()
for i in map(int, input().split()):
b = set(i | j for j in b)
b.add(i)
a.update(b)
print(len(a))
```
| 10,260 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an.
Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar.
Polycarpus took a piece of paper and wrote out the values of function f(l, r) for all l, r (l, r are integer, 1 ≤ l ≤ r ≤ n). Now he wants to know, how many distinct values he's got in the end.
Help Polycarpus, count the number of distinct values of function f(l, r) for the given sequence a.
Expression x | y means applying the operation of bitwise OR to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or".
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements of sequence a. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 106) — the elements of sequence a.
Output
Print a single integer — the number of distinct values of function f(l, r) for the given sequence a.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
3
1 2 0
Output
4
Input
10
1 2 3 4 5 6 1 2 9 10
Output
11
Note
In the first test case Polycarpus will have 6 numbers written on the paper: f(1, 1) = 1, f(1, 2) = 3, f(1, 3) = 3, f(2, 2) = 2, f(2, 3) = 2, f(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3.
Tags: bitmasks
Correct Solution:
```
import sys, math,os
from io import BytesIO, IOBase
#from bisect import bisect_left as bl, bisect_right as br, insort
#from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
#from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1e9)+7
def main():
n=int(data())
A=mdata()
s=set()
ans=set()
for i in A:
s=set(i|j for j in s)
s.add(i)
ans.update(s)
print(len(ans))
if __name__ == '__main__':
main()
```
| 10,261 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an.
Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar.
Polycarpus took a piece of paper and wrote out the values of function f(l, r) for all l, r (l, r are integer, 1 ≤ l ≤ r ≤ n). Now he wants to know, how many distinct values he's got in the end.
Help Polycarpus, count the number of distinct values of function f(l, r) for the given sequence a.
Expression x | y means applying the operation of bitwise OR to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or".
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements of sequence a. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 106) — the elements of sequence a.
Output
Print a single integer — the number of distinct values of function f(l, r) for the given sequence a.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
3
1 2 0
Output
4
Input
10
1 2 3 4 5 6 1 2 9 10
Output
11
Note
In the first test case Polycarpus will have 6 numbers written on the paper: f(1, 1) = 1, f(1, 2) = 3, f(1, 3) = 3, f(2, 2) = 2, f(2, 3) = 2, f(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3.
Tags: bitmasks
Correct Solution:
```
n, p, q = input(), set(), set()
for i in map(int, input().split()):
q = set(i | j for j in q)
q.add(i)
p.update(q)
print(len(p))
```
| 10,262 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an.
Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar.
Polycarpus took a piece of paper and wrote out the values of function f(l, r) for all l, r (l, r are integer, 1 ≤ l ≤ r ≤ n). Now he wants to know, how many distinct values he's got in the end.
Help Polycarpus, count the number of distinct values of function f(l, r) for the given sequence a.
Expression x | y means applying the operation of bitwise OR to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or".
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements of sequence a. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 106) — the elements of sequence a.
Output
Print a single integer — the number of distinct values of function f(l, r) for the given sequence a.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
3
1 2 0
Output
4
Input
10
1 2 3 4 5 6 1 2 9 10
Output
11
Note
In the first test case Polycarpus will have 6 numbers written on the paper: f(1, 1) = 1, f(1, 2) = 3, f(1, 3) = 3, f(2, 2) = 2, f(2, 3) = 2, f(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3.
Tags: bitmasks
Correct Solution:
```
#n=int(input())
from bisect import bisect_right
#d=sorted(d,key=lambda x:(len(d[x]),-x)) d=dictionary d={x:set() for x in arr}
#n=int(input())
#n,m,k= map(int, input().split())
import heapq
#for _ in range(int(input())):
#n,k=map(int, input().split())
#input=sys.stdin.buffer.readline
#for _ in range(int(input())):
n=int(input())
arr = list(map(int, input().split()))
ans=set()
s=set()
for i in range(n):
s={arr[i]|j for j in s}
s.add(arr[i])
ans.update(s)
#print(s)
print(len(ans))
```
| 10,263 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an.
Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar.
Polycarpus took a piece of paper and wrote out the values of function f(l, r) for all l, r (l, r are integer, 1 ≤ l ≤ r ≤ n). Now he wants to know, how many distinct values he's got in the end.
Help Polycarpus, count the number of distinct values of function f(l, r) for the given sequence a.
Expression x | y means applying the operation of bitwise OR to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or".
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements of sequence a. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 106) — the elements of sequence a.
Output
Print a single integer — the number of distinct values of function f(l, r) for the given sequence a.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
3
1 2 0
Output
4
Input
10
1 2 3 4 5 6 1 2 9 10
Output
11
Note
In the first test case Polycarpus will have 6 numbers written on the paper: f(1, 1) = 1, f(1, 2) = 3, f(1, 3) = 3, f(2, 2) = 2, f(2, 3) = 2, f(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3.
Tags: bitmasks
Correct Solution:
```
def R(): return map(int, input().split())
def I(): return int(input())
def S(): return str(input())
def L(): return list(R())
from collections import Counter
import math
import sys
from itertools import permutations
import bisect
n=I()
a=L()
s1=set()
s2=set()
for i in range(n):
s1={a[i]|j for j in s1}
s1.add(a[i])
s2.update(s1)
print(len(s2))
```
| 10,264 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an.
Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar.
Polycarpus took a piece of paper and wrote out the values of function f(l, r) for all l, r (l, r are integer, 1 ≤ l ≤ r ≤ n). Now he wants to know, how many distinct values he's got in the end.
Help Polycarpus, count the number of distinct values of function f(l, r) for the given sequence a.
Expression x | y means applying the operation of bitwise OR to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or".
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements of sequence a. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 106) — the elements of sequence a.
Output
Print a single integer — the number of distinct values of function f(l, r) for the given sequence a.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
3
1 2 0
Output
4
Input
10
1 2 3 4 5 6 1 2 9 10
Output
11
Note
In the first test case Polycarpus will have 6 numbers written on the paper: f(1, 1) = 1, f(1, 2) = 3, f(1, 3) = 3, f(2, 2) = 2, f(2, 3) = 2, f(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3.
Tags: bitmasks
Correct Solution:
```
import copy
n=int(input())
a=list(map(int,input().split()))
ans=set()
s=set()
s.add(a[0])
ans.add(a[0])
for i in range(1,len(a)):
pres=set()
for x in s:
pres.add(x|a[i])
pres.add(a[i])
for y in pres:
ans.add(y)
s=copy.deepcopy(pres)
print(len(ans))
```
| 10,265 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an.
Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar.
Polycarpus took a piece of paper and wrote out the values of function f(l, r) for all l, r (l, r are integer, 1 ≤ l ≤ r ≤ n). Now he wants to know, how many distinct values he's got in the end.
Help Polycarpus, count the number of distinct values of function f(l, r) for the given sequence a.
Expression x | y means applying the operation of bitwise OR to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or".
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements of sequence a. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 106) — the elements of sequence a.
Output
Print a single integer — the number of distinct values of function f(l, r) for the given sequence a.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
3
1 2 0
Output
4
Input
10
1 2 3 4 5 6 1 2 9 10
Output
11
Note
In the first test case Polycarpus will have 6 numbers written on the paper: f(1, 1) = 1, f(1, 2) = 3, f(1, 3) = 3, f(2, 2) = 2, f(2, 3) = 2, f(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3.
Tags: bitmasks
Correct Solution:
```
n=int(input())
a=list(map(int,input().split()))
b=set();c=set()
for i in a:
b=set(i|j for j in b)
b.add(i)
c.update(b)
print(len(c))
```
| 10,266 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an.
Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar.
Polycarpus took a piece of paper and wrote out the values of function f(l, r) for all l, r (l, r are integer, 1 ≤ l ≤ r ≤ n). Now he wants to know, how many distinct values he's got in the end.
Help Polycarpus, count the number of distinct values of function f(l, r) for the given sequence a.
Expression x | y means applying the operation of bitwise OR to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or".
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements of sequence a. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 106) — the elements of sequence a.
Output
Print a single integer — the number of distinct values of function f(l, r) for the given sequence a.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
3
1 2 0
Output
4
Input
10
1 2 3 4 5 6 1 2 9 10
Output
11
Note
In the first test case Polycarpus will have 6 numbers written on the paper: f(1, 1) = 1, f(1, 2) = 3, f(1, 3) = 3, f(2, 2) = 2, f(2, 3) = 2, f(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3.
Tags: bitmasks
Correct Solution:
```
import sys,os
from io import BytesIO,IOBase
# from functools import lru_cache
mod = 10**9+7; Mod = 998244353; INF = float('inf')
# input = lambda: sys.stdin.readline().rstrip("\r\n")
# inp = lambda: list(map(int,sys.stdin.readline().rstrip("\r\n").split()))
#______________________________________________________________________________________________________
# region fastio
# '''
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# endregion'''
#______________________________________________________________________________________________________
input = lambda: sys.stdin.readline().rstrip("\r\n")
inp = lambda: list(map(int,sys.stdin.readline().rstrip("\r\n").split()))
# ______________________________________________________________________________________________________
# import math
# from bisect import *
# from heapq import *
from collections import defaultdict as dd
# from collections import OrderedDict as odict
# from collections import Counter as cc
# from collections import deque
# from itertools import groupby
# from itertools import combinations
# sys.setrecursionlimit(100_100) #this is must for dfs
# ______________________________________________________________________________________________________
# segment tree for range minimum query and update 0 indexing
# init = float('inf')
# st = [init for i in range(4*len(a))]
# def build(a,ind,start,end):
# if start == end:
# st[ind] = a[start]
# else:
# mid = (start+end)//2
# build(a,2*ind+1,start,mid)
# build(a,2*ind+2,mid+1,end)
# st[ind] = min(st[2*ind+1],st[2*ind+2])
# build(a,0,0,n-1)
# def query(ind,l,r,start,end):
# if start>r or end<l:
# return init
# if l<=start<=end<=r:
# return st[ind]
# mid = (start+end)//2
# return min(query(2*ind+1,l,r,start,mid),query(2*ind+2,l,r,mid+1,end))
# def update(ind,val,stind,start,end):
# if start<=ind<=end:
# if start==end:
# st[stind] = a[start] = val
# else:
# mid = (start+end)//2
# update(ind,val,2*stind+1,start,mid)
# update(ind,val,2*stind+2,mid+1,end)
# st[stind] = min(st[left],st[right])
# ______________________________________________________________________________________________________
# Checking prime in O(root(N))
# def isprime(n):
# if (n % 2 == 0 and n > 2) or n == 1: return 0
# else:
# s = int(n**(0.5)) + 1
# for i in range(3, s, 2):
# if n % i == 0:
# return 0
# return 1
# def lcm(a,b):
# return (a*b)//gcd(a,b)
# returning factors in O(root(N))
# def factors(n):
# fact = []
# N = int(n**0.5)+1
# for i in range(1,N):
# if (n%i==0):
# fact.append(i)
# if (i!=n//i):
# fact.append(n//i)
# return fact
# ______________________________________________________________________________________________________
# Merge sort for inversion count
# def mergeSort(left,right,arr,temp):
# inv_cnt = 0
# if left<right:
# mid = (left+right)//2
# inv1 = mergeSort(left,mid,arr,temp)
# inv2 = mergeSort(mid+1,right,arr,temp)
# inv3 = merge(left,right,mid,arr,temp)
# inv_cnt = inv1+inv3+inv2
# return inv_cnt
# def merge(left,right,mid,arr,temp):
# i = left
# j = mid+1
# k = left
# inv = 0
# while(i<=mid and j<=right):
# if(arr[i]<=arr[j]):
# temp[k] = arr[i]
# i+=1
# else:
# temp[k] = arr[j]
# inv+=(mid+1-i)
# j+=1
# k+=1
# while(i<=mid):
# temp[k]=arr[i]
# i+=1
# k+=1
# while(j<=right):
# temp[k]=arr[j]
# j+=1
# k+=1
# for k in range(left,right+1):
# arr[k] = temp[k]
# return inv
# ______________________________________________________________________________________________________
# nCr under mod
# def C(n,r,mod = 10**9+7):
# if r>n: return 0
# if r>n-r: r = n-r
# num = den = 1
# for i in range(r):
# num = (num*(n-i))%mod
# den = (den*(i+1))%mod
# return (num*pow(den,mod-2,mod))%mod
# def C(n,r):
# if r>n:
# return 0
# if r>n-r:
# r = n-r
# ans = 1
# for i in range(r):
# ans = (ans*(n-i))//(i+1)
# return ans
# ______________________________________________________________________________________________________
# For smallest prime factor of a number
# M = 5*10**5+100
# spf = [i for i in range(M)]
# def spfs(M):
# for i in range(2,M):
# if spf[i]==i:
# for j in range(i*i,M,i):
# if spf[j]==j:
# spf[j] = i
# return
# spfs(M)
# p = [0]*M
# for i in range(2,M):
# p[i]+=(p[i-1]+(spf[i]==i))
# ______________________________________________________________________________________________________
# def gtc(p):
# print('Case #'+str(p)+': ',end='')
# ______________________________________________________________________________________________________
tc = 1
# tc = int(input())
for test in range(1,tc+1):
n = int(input())
a = inp()
s = [[n]*20 for i in range(n+1)]
for i in range(n-1,-1,-1):
for j in range(20):
s[i][j] = s[i+1][j]
if (a[i]&(1<<j)):
s[i][j] = i
ans = set()
for i in range(n):
num = a[i]
ans.add(num)
d = dd(list)
for j in range(20):
if s[i][j]<n and s[i][j]!=i:
d[s[i][j]].append(j)
for key in sorted(d.keys()):
for j in d[key]:
num+=(1<<j)
ans.add(num)
print(len(ans))
```
| 10,267 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an.
Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar.
Polycarpus took a piece of paper and wrote out the values of function f(l, r) for all l, r (l, r are integer, 1 ≤ l ≤ r ≤ n). Now he wants to know, how many distinct values he's got in the end.
Help Polycarpus, count the number of distinct values of function f(l, r) for the given sequence a.
Expression x | y means applying the operation of bitwise OR to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or".
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements of sequence a. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 106) — the elements of sequence a.
Output
Print a single integer — the number of distinct values of function f(l, r) for the given sequence a.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
3
1 2 0
Output
4
Input
10
1 2 3 4 5 6 1 2 9 10
Output
11
Note
In the first test case Polycarpus will have 6 numbers written on the paper: f(1, 1) = 1, f(1, 2) = 3, f(1, 3) = 3, f(2, 2) = 2, f(2, 3) = 2, f(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3.
Submitted Solution:
```
input();a,b=set(),set()
for i in map(int,input().split()):a={i|j for j in a}; a.add(i,);b.update(a)
print(len(b))
```
Yes
| 10,268 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an.
Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar.
Polycarpus took a piece of paper and wrote out the values of function f(l, r) for all l, r (l, r are integer, 1 ≤ l ≤ r ≤ n). Now he wants to know, how many distinct values he's got in the end.
Help Polycarpus, count the number of distinct values of function f(l, r) for the given sequence a.
Expression x | y means applying the operation of bitwise OR to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or".
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements of sequence a. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 106) — the elements of sequence a.
Output
Print a single integer — the number of distinct values of function f(l, r) for the given sequence a.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
3
1 2 0
Output
4
Input
10
1 2 3 4 5 6 1 2 9 10
Output
11
Note
In the first test case Polycarpus will have 6 numbers written on the paper: f(1, 1) = 1, f(1, 2) = 3, f(1, 3) = 3, f(2, 2) = 2, f(2, 3) = 2, f(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3.
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
s1, s2 = set(), set()
for each in a:
st = set()
st.add(each)
for i in s1:
st.add(each | i)
s1 = st
s2.update(s1)
print(len(s2))
```
Yes
| 10,269 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an.
Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar.
Polycarpus took a piece of paper and wrote out the values of function f(l, r) for all l, r (l, r are integer, 1 ≤ l ≤ r ≤ n). Now he wants to know, how many distinct values he's got in the end.
Help Polycarpus, count the number of distinct values of function f(l, r) for the given sequence a.
Expression x | y means applying the operation of bitwise OR to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or".
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements of sequence a. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 106) — the elements of sequence a.
Output
Print a single integer — the number of distinct values of function f(l, r) for the given sequence a.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
3
1 2 0
Output
4
Input
10
1 2 3 4 5 6 1 2 9 10
Output
11
Note
In the first test case Polycarpus will have 6 numbers written on the paper: f(1, 1) = 1, f(1, 2) = 3, f(1, 3) = 3, f(2, 2) = 2, f(2, 3) = 2, f(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3.
Submitted Solution:
```
n = input()
arr = list(map(int, input().split()))
res = set()
temp = set()
for i in arr:
temp = {i|j for j in temp}
temp.add(i)
res.update(temp)
print(len(res))
```
Yes
| 10,270 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an.
Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar.
Polycarpus took a piece of paper and wrote out the values of function f(l, r) for all l, r (l, r are integer, 1 ≤ l ≤ r ≤ n). Now he wants to know, how many distinct values he's got in the end.
Help Polycarpus, count the number of distinct values of function f(l, r) for the given sequence a.
Expression x | y means applying the operation of bitwise OR to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or".
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements of sequence a. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 106) — the elements of sequence a.
Output
Print a single integer — the number of distinct values of function f(l, r) for the given sequence a.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
3
1 2 0
Output
4
Input
10
1 2 3 4 5 6 1 2 9 10
Output
11
Note
In the first test case Polycarpus will have 6 numbers written on the paper: f(1, 1) = 1, f(1, 2) = 3, f(1, 3) = 3, f(2, 2) = 2, f(2, 3) = 2, f(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3.
Submitted Solution:
```
input()
a, b = set(), set()
for i in map(int, input().split()):
a = {i | j for j in a}
a.add(i)
b.update(a)
print(len(b))
```
Yes
| 10,271 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an.
Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar.
Polycarpus took a piece of paper and wrote out the values of function f(l, r) for all l, r (l, r are integer, 1 ≤ l ≤ r ≤ n). Now he wants to know, how many distinct values he's got in the end.
Help Polycarpus, count the number of distinct values of function f(l, r) for the given sequence a.
Expression x | y means applying the operation of bitwise OR to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or".
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements of sequence a. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 106) — the elements of sequence a.
Output
Print a single integer — the number of distinct values of function f(l, r) for the given sequence a.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
3
1 2 0
Output
4
Input
10
1 2 3 4 5 6 1 2 9 10
Output
11
Note
In the first test case Polycarpus will have 6 numbers written on the paper: f(1, 1) = 1, f(1, 2) = 3, f(1, 3) = 3, f(2, 2) = 2, f(2, 3) = 2, f(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
s1=set()
s2=set()
for i in a:
print(s1)
s1={i|j for j in s1}
s1.add(i)
s2.update(s1)
print(len(s2))
```
No
| 10,272 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an.
Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar.
Polycarpus took a piece of paper and wrote out the values of function f(l, r) for all l, r (l, r are integer, 1 ≤ l ≤ r ≤ n). Now he wants to know, how many distinct values he's got in the end.
Help Polycarpus, count the number of distinct values of function f(l, r) for the given sequence a.
Expression x | y means applying the operation of bitwise OR to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or".
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements of sequence a. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 106) — the elements of sequence a.
Output
Print a single integer — the number of distinct values of function f(l, r) for the given sequence a.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
3
1 2 0
Output
4
Input
10
1 2 3 4 5 6 1 2 9 10
Output
11
Note
In the first test case Polycarpus will have 6 numbers written on the paper: f(1, 1) = 1, f(1, 2) = 3, f(1, 3) = 3, f(2, 2) = 2, f(2, 3) = 2, f(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3.
Submitted Solution:
```
import itertools
a = [int(x) for x in input().split()]
s = set([])
for i, val in enumerate(a):
for j in range(i, len(a)):
tmp = a[i]
for k in range(i+1, j+1):
tmp |= a[k]
s.add(tmp)
print(len(s))
```
No
| 10,273 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an.
Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar.
Polycarpus took a piece of paper and wrote out the values of function f(l, r) for all l, r (l, r are integer, 1 ≤ l ≤ r ≤ n). Now he wants to know, how many distinct values he's got in the end.
Help Polycarpus, count the number of distinct values of function f(l, r) for the given sequence a.
Expression x | y means applying the operation of bitwise OR to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or".
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements of sequence a. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 106) — the elements of sequence a.
Output
Print a single integer — the number of distinct values of function f(l, r) for the given sequence a.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
3
1 2 0
Output
4
Input
10
1 2 3 4 5 6 1 2 9 10
Output
11
Note
In the first test case Polycarpus will have 6 numbers written on the paper: f(1, 1) = 1, f(1, 2) = 3, f(1, 3) = 3, f(2, 2) = 2, f(2, 3) = 2, f(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
s=set()
b=[]
for i in range(1,n+1):
for j in range(i,n+1):
b.append([a[i-1],a[j-1]])
s=set(list(map(lambda x: x[0]|x[1],b )))
print(len(s))
```
No
| 10,274 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an.
Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar.
Polycarpus took a piece of paper and wrote out the values of function f(l, r) for all l, r (l, r are integer, 1 ≤ l ≤ r ≤ n). Now he wants to know, how many distinct values he's got in the end.
Help Polycarpus, count the number of distinct values of function f(l, r) for the given sequence a.
Expression x | y means applying the operation of bitwise OR to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or".
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of elements of sequence a. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 106) — the elements of sequence a.
Output
Print a single integer — the number of distinct values of function f(l, r) for the given sequence a.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Examples
Input
3
1 2 0
Output
4
Input
10
1 2 3 4 5 6 1 2 9 10
Output
11
Note
In the first test case Polycarpus will have 6 numbers written on the paper: f(1, 1) = 1, f(1, 2) = 3, f(1, 3) = 3, f(2, 2) = 2, f(2, 3) = 2, f(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3.
Submitted Solution:
```
c = 0
n = int(input())
*a, = map(int, input().split())
s = set(a)
for i in a:
c = i
for j in a:
c |= j
s.add(c)
print(len(s))
```
No
| 10,275 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.
One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.
Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.
Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.
Input
The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise.
Consider the secretaries indexed from 1 to n in some way.
Output
Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.
Examples
Input
6
0 1 7 1 7 10
Output
2
Input
3
1 1 1
Output
-1
Input
1
0
Output
0
Note
In the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.
In the second test sample the described situation is impossible as conferences aren't allowed.
Tags: *special, implementation, sortings
Correct Solution:
```
n = int(input())
l = list(map(int,input().split()))
l.sort()
r = 0
bad = False
for i in range(n-1):
if l[i] == 0 :
continue
if l[i] == l[i+1]:
r += 1
if i < n-2 and l[i+2] == l[i]:
print(-1)
bad = True
break
if not bad :
print(r)
```
| 10,276 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.
One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.
Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.
Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.
Input
The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise.
Consider the secretaries indexed from 1 to n in some way.
Output
Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.
Examples
Input
6
0 1 7 1 7 10
Output
2
Input
3
1 1 1
Output
-1
Input
1
0
Output
0
Note
In the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.
In the second test sample the described situation is impossible as conferences aren't allowed.
Tags: *special, implementation, sortings
Correct Solution:
```
n = map(int, input().split())
a = list(map(int, input().split()))
b = set(a)-{0}
result = 0
for i in b:
if a.count(i)>2:
print(-1)
exit(0)
elif a.count(i)==2:
result+=1
print(result)
```
| 10,277 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.
One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.
Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.
Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.
Input
The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise.
Consider the secretaries indexed from 1 to n in some way.
Output
Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.
Examples
Input
6
0 1 7 1 7 10
Output
2
Input
3
1 1 1
Output
-1
Input
1
0
Output
0
Note
In the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.
In the second test sample the described situation is impossible as conferences aren't allowed.
Tags: *special, implementation, sortings
Correct Solution:
```
def shellSort(arr):
gap = n//2
while gap > 0:
for i in range(gap,n):
temp = arr[i]
j = i
while j >= gap and arr[j-gap] >temp:
arr[j] = arr[j-gap]
j -= gap
arr[j] = temp
gap //= 2
n = int(input())
arr = [int(x) for x in input().split()]
shellSort(arr)
ans = 0
if n == 1:
print(0)
quit()
else:
for i in range(n-2):
if arr[i] == 0: continue
if arr[i] == arr[i+1]:
if arr[i+1] == arr[i+2]:
ans = -1
break
else:
ans += 1
if ans == -1:
print(ans)
else:
print(ans if arr[n-2] != arr[n-1] or arr[n-2] == 0 else ans+1)
```
| 10,278 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.
One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.
Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.
Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.
Input
The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise.
Consider the secretaries indexed from 1 to n in some way.
Output
Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.
Examples
Input
6
0 1 7 1 7 10
Output
2
Input
3
1 1 1
Output
-1
Input
1
0
Output
0
Note
In the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.
In the second test sample the described situation is impossible as conferences aren't allowed.
Tags: *special, implementation, sortings
Correct Solution:
```
from collections import Counter
N, Answer = int(input()), 0
X = Counter(list(map(int, input().split())))
for key in X:
if key != 0:
if X[key] == 2:
Answer += 1
elif X[key] > 2:
print(-1)
exit()
print(Answer)
# Hope the best for Ravens
# Never give up
```
| 10,279 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.
One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.
Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.
Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.
Input
The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise.
Consider the secretaries indexed from 1 to n in some way.
Output
Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.
Examples
Input
6
0 1 7 1 7 10
Output
2
Input
3
1 1 1
Output
-1
Input
1
0
Output
0
Note
In the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.
In the second test sample the described situation is impossible as conferences aren't allowed.
Tags: *special, implementation, sortings
Correct Solution:
```
from collections import *
from sys import *
input=stdin.readline
n=int(input())
ll=list(map(int,input().split()))
l = [i for i in ll if i!=0]
c=Counter(l)
cc=0
d=list(c.values())
for i in d:
if(i==2):
cc=cc+1
elif(i>2):
cc=-1
break
print(cc)
```
| 10,280 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.
One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.
Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.
Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.
Input
The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise.
Consider the secretaries indexed from 1 to n in some way.
Output
Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.
Examples
Input
6
0 1 7 1 7 10
Output
2
Input
3
1 1 1
Output
-1
Input
1
0
Output
0
Note
In the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.
In the second test sample the described situation is impossible as conferences aren't allowed.
Tags: *special, implementation, sortings
Correct Solution:
```
def solve():
n = int(input())
id = list(map(int, input().split()))
duplicate_id = set()
unique_id = set()
score = 0
for i in range(len(id)):
if id[i] != 0 and id[i] not in duplicate_id:
if id[i] not in unique_id:
unique_id.add(id[i])
else:
duplicate_id.add(id[i])
score+=1
elif id[i] == 0:
pass
else:
return -1
return score
print(solve())
```
| 10,281 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.
One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.
Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.
Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.
Input
The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise.
Consider the secretaries indexed from 1 to n in some way.
Output
Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.
Examples
Input
6
0 1 7 1 7 10
Output
2
Input
3
1 1 1
Output
-1
Input
1
0
Output
0
Note
In the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.
In the second test sample the described situation is impossible as conferences aren't allowed.
Tags: *special, implementation, sortings
Correct Solution:
```
n = int(input())
id = sorted(list(map(int, input().split())))
prev = -1
count = 1
output = 0
for i in id[id.count(0):]:
if i == 0:
continue
if prev == i:
count += 1
else:
count = 1
if count == 2:
output += 1
elif count >= 3:
output = -1
break
prev = i
print(output)
```
| 10,282 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.
One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.
Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.
Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.
Input
The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise.
Consider the secretaries indexed from 1 to n in some way.
Output
Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.
Examples
Input
6
0 1 7 1 7 10
Output
2
Input
3
1 1 1
Output
-1
Input
1
0
Output
0
Note
In the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.
In the second test sample the described situation is impossible as conferences aren't allowed.
Tags: *special, implementation, sortings
Correct Solution:
```
def cycleSort(array):
writes = 0
for cycleStart in range(0, len(array) - 1):
item = array[cycleStart]
pos = cycleStart
for i in range(cycleStart + 1, len(array)):
if array[i] < item:
pos += 1
if pos == cycleStart:
continue
while item == array[pos]:
pos += 1
array[pos], item = item, array[pos]
writes += 1
while pos != cycleStart:
pos = cycleStart
for i in range(cycleStart + 1, len(array)):
if array[i] < item:
pos += 1
while item == array[pos]:
pos += 1
array[pos], item = item, array[pos]
writes += 1
return writes
n = int(input())
x = list(map(int, input().split()))
answer = 0
cycleSort(x)
for i in range(len(x) - 1):
if (i + 2) >= n:
if (x[i] == x[i + 1]) and (x[i] != 0):
answer = answer + 1
i = i + 1
else:
if x[i] == x[i + 1] and x[i] != 0 and x[i] != x[i + 2]:
answer = answer + 1
i = i + 1
elif x[i] == x[i + 1] and x[i] != 0 and x[i] != 0:
answer = -1
break
print(answer)
```
| 10,283 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.
One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.
Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.
Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.
Input
The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise.
Consider the secretaries indexed from 1 to n in some way.
Output
Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.
Examples
Input
6
0 1 7 1 7 10
Output
2
Input
3
1 1 1
Output
-1
Input
1
0
Output
0
Note
In the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.
In the second test sample the described situation is impossible as conferences aren't allowed.
Submitted Solution:
```
# import sys
# sys.stdin = open("test.in","r")
# sys.stdout = open("test.out.py","w")
n=int(input())
a=list(map(int,input().split()))
c=0
b=list(set(a))
for i in b:
d=a.count(i)
if i==0:
pass
elif d==2:
c+=1
elif d>=3:
print('-1')
exit()
print(c)
```
Yes
| 10,284 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.
One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.
Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.
Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.
Input
The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise.
Consider the secretaries indexed from 1 to n in some way.
Output
Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.
Examples
Input
6
0 1 7 1 7 10
Output
2
Input
3
1 1 1
Output
-1
Input
1
0
Output
0
Note
In the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.
In the second test sample the described situation is impossible as conferences aren't allowed.
Submitted Solution:
```
n=int(input())
l=list(map(int,input().split(' ')))
dict={}
cnt=0
for i in l:
if i==0 :
continue
if i in dict :
if dict[i]==2 :
cnt=-1
break
dict[i]+=1
cnt+=1
else:
dict[i]=1
print(cnt)
```
Yes
| 10,285 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.
One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.
Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.
Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.
Input
The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise.
Consider the secretaries indexed from 1 to n in some way.
Output
Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.
Examples
Input
6
0 1 7 1 7 10
Output
2
Input
3
1 1 1
Output
-1
Input
1
0
Output
0
Note
In the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.
In the second test sample the described situation is impossible as conferences aren't allowed.
Submitted Solution:
```
def cocktail_sort(a):
n = len(a)
swapped = True
start = 0
end = n-1
while (swapped == True):
swapped = False
for i in range (start, end):
if (a[i] > a[i + 1]) :
a[i], a[i + 1]= a[i + 1], a[i]
swapped = True
if (swapped == False):
break
swapped = False
end = end-1
for i in range(end-1, start-1, -1):
if (a[i] > a[i + 1]):
a[i], a[i + 1] = a[i + 1], a[i]
swapped = True
start = start + 1
n = int(input())
x = list(map(int, input().split()))
ans = 0
cocktail_sort(x)
for i in range(len(x) - 1):
if (i + 2) >= n:
if (x[i] == x[i + 1]) and (x[i] != 0):
ans = ans + 1
i = i + 1
else:
if x[i] == x[i + 1] and x[i] != 0 and x[i] != x[i + 2]:
ans = ans + 1
i = i + 1
elif x[i] == x[i + 1] and x[i] != 0 and x[i] != 0:
ans = -1
break
print(ans)
```
Yes
| 10,286 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.
One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.
Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.
Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.
Input
The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise.
Consider the secretaries indexed from 1 to n in some way.
Output
Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.
Examples
Input
6
0 1 7 1 7 10
Output
2
Input
3
1 1 1
Output
-1
Input
1
0
Output
0
Note
In the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.
In the second test sample the described situation is impossible as conferences aren't allowed.
Submitted Solution:
```
n=int(input())
s=(list(map(int,input().split())))
pair=0
freq={}
for item in s:
if item in freq:
freq[item]=freq[item] + 1
else:
freq[item] = 1
for key,value in freq.items():
#print ("% d : % d"%(key, value))
if key>0 and value==2:
pair = pair + (value//2)
elif key>0 and value>2:
pair = -1
break;
print(pair)
```
Yes
| 10,287 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.
One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.
Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.
Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.
Input
The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise.
Consider the secretaries indexed from 1 to n in some way.
Output
Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.
Examples
Input
6
0 1 7 1 7 10
Output
2
Input
3
1 1 1
Output
-1
Input
1
0
Output
0
Note
In the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.
In the second test sample the described situation is impossible as conferences aren't allowed.
Submitted Solution:
```
def shellSort(arr):
gap = n//2
while gap > 0:
for i in range(gap,n):
temp = arr[i]
j = i
while j >= gap and arr[j-gap] >temp:
arr[j] = arr[j-gap]
j -= gap
arr[j] = temp
gap //= 2
n = int(input())
arr = [int(x) for x in input().split()]
shellSort(arr)
ans = 0
if n == 1:
print(0)
quit()
else:
for i in range(n-2):
if arr[i] == arr[i+1]:
if arr[i+1] == arr[i+2]:
ans = -1
break
else:
ans += 1
if ans == -1:
print(ans)
else:
print(ans if arr[n-2] != arr[n-1] else ans+1)
```
No
| 10,288 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.
One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.
Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.
Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.
Input
The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise.
Consider the secretaries indexed from 1 to n in some way.
Output
Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.
Examples
Input
6
0 1 7 1 7 10
Output
2
Input
3
1 1 1
Output
-1
Input
1
0
Output
0
Note
In the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.
In the second test sample the described situation is impossible as conferences aren't allowed.
Submitted Solution:
```
input()
a,i,c=list(map(int,input().split())),0,0
a.sort()
while i<len(a):
j=a.count(a[i])
if j==2:
c+=1
elif j>2:
c=-1
break
i+=j
print(c)
```
No
| 10,289 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.
One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.
Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.
Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.
Input
The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise.
Consider the secretaries indexed from 1 to n in some way.
Output
Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.
Examples
Input
6
0 1 7 1 7 10
Output
2
Input
3
1 1 1
Output
-1
Input
1
0
Output
0
Note
In the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.
In the second test sample the described situation is impossible as conferences aren't allowed.
Submitted Solution:
```
n=int(input())
l=list(map(int,input().split(' ')))
dict={}
cnt=0
for i in l:
if i in dict :
if dict[i]==2 :
cnt=-1
break
dict[i]+=1
cnt+=1
else:
dict[i]=1
print(cnt)
```
No
| 10,290 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.
One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.
Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.
Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.
Input
The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise.
Consider the secretaries indexed from 1 to n in some way.
Output
Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.
Examples
Input
6
0 1 7 1 7 10
Output
2
Input
3
1 1 1
Output
-1
Input
1
0
Output
0
Note
In the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.
In the second test sample the described situation is impossible as conferences aren't allowed.
Submitted Solution:
```
n=int(input())
a=input().split()
k=0
for i in set(a):
if a.count(i)==2 and i!='0':k+=1
elif a.count(i)>2:print(-1);quit()
print(k)
```
No
| 10,291 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission).
<image> Figure 1. The initial position for n = 5.
After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped.
<image> Figure 2. The example of a throw.
In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.
Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise.
Input
The first line contains a single number n — the number of students in the line and the number of balls. The next line contains exactly n space-separated integers. Each number corresponds to a student in the line (the i-th number corresponds to the i-th from the left student in the line) and shows the number of throws he can participate in.
The input limits for scoring 30 points are (subproblem D1):
* 1 ≤ n ≤ 10.
The input limits for scoring 70 points are (subproblems D1+D2):
* 1 ≤ n ≤ 500.
The input limits for scoring 100 points are (subproblems D1+D2+D3):
* 1 ≤ n ≤ 1000000.
Output
The output should contain a single integer — the number of variants of ball orders after the warm up exercise is complete. As the number can be rather large, print it modulo 1000000007 (109 + 7).
Examples
Input
5
1 2 2 1 2
Output
120
Input
8
1 2 2 1 2 1 1 2
Output
16800
Tags: brute force, dp
Correct Solution:
```
m = 1000000007
n = int(input())
a = map(int, input().split())
t1, t2 = 0, 0
for i in a:
if i == 1:
t1 += 1
else:
t2 += 1
a = [1, 2]
for i in range(3, t1+1):
a = a[::-1]
a[1] = (a[0]+(i-1)*a[1])%m
if not t1 or t1 == 1:
a[1] = 1
for i in range(t1+1, n+1):
a[1] = a[1]*i%m
print(a[1])
```
| 10,292 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission).
<image> Figure 1. The initial position for n = 5.
After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped.
<image> Figure 2. The example of a throw.
In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.
Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise.
Input
The first line contains a single number n — the number of students in the line and the number of balls. The next line contains exactly n space-separated integers. Each number corresponds to a student in the line (the i-th number corresponds to the i-th from the left student in the line) and shows the number of throws he can participate in.
The input limits for scoring 30 points are (subproblem D1):
* 1 ≤ n ≤ 10.
The input limits for scoring 70 points are (subproblems D1+D2):
* 1 ≤ n ≤ 500.
The input limits for scoring 100 points are (subproblems D1+D2+D3):
* 1 ≤ n ≤ 1000000.
Output
The output should contain a single integer — the number of variants of ball orders after the warm up exercise is complete. As the number can be rather large, print it modulo 1000000007 (109 + 7).
Examples
Input
5
1 2 2 1 2
Output
120
Input
8
1 2 2 1 2 1 1 2
Output
16800
Submitted Solution:
```
m = 1000000007
n = int(input())
a = map(int, input().split())
t1, t2 = 0, 0
for i in a:
if i == 1:
t1 += 1
else:
t2 += 1
a = [1, 2]
for i in range(3, t1+1):
a = a[::-1]
a[1] = (a[0]+(i-1)*a[1])%m
for i in range(t1+1, n+1):
a[1] = a[1]*i%m
print(a[1])
```
No
| 10,293 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.
Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.
Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4) → (1 or 2 = 3, 3 or 4 = 7) → (3 xor 7 = 4). The result is v = 4.
You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
Input
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi < 230) — the i-th query.
Output
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
Examples
Input
2 4
1 6 3 5
1 4
3 4
1 2
1 2
Output
1
3
3
3
Note
For more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Tags: data structures, trees
Correct Solution:
```
from sys import stdin,stdout
n,m=map(int,input().split())
n=pow(2,n)
tarr=list(map(int,stdin.readline().split()))
arr=[0]*n
arr=arr+tarr
start=n
end=2*n
flag=0
while(start>1):
for i in range(start,end,2):
if(flag):
arr[i>>1]=arr[i]^arr[i+1]
else:
arr[i>>1]=arr[i]|arr[i+1]
flag=flag^1
end=start
start=start>>1
for i in range(m):
p,b=map(int,stdin.readline().split())
arr[n+p-1]=b
pos=n+p-1
flag=0
while(pos>1):
pos=pos>>1
if(flag):
arr[pos]=arr[pos<<1]^arr[(pos<<1)+1]
else:
arr[pos]=arr[pos<<1]|arr[(pos<<1)+1]
flag=flag^1
stdout.write(str(arr[1])+'\n')
```
| 10,294 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.
Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.
Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4) → (1 or 2 = 3, 3 or 4 = 7) → (3 xor 7 = 4). The result is v = 4.
You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
Input
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi < 230) — the i-th query.
Output
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
Examples
Input
2 4
1 6 3 5
1 4
3 4
1 2
1 2
Output
1
3
3
3
Note
For more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Tags: data structures, trees
Correct Solution:
```
'''
Code from : AKASH KUMAR BHAGAT(akay_99)
'''
#-------------------------------------------------------------------------------------
'''
from sys import stdin, stdout
def input():
return stdin.readline().rstrip()
'''
#--------------------------------------------------------------------------------------------------
'''
#For PYPY 2.7
#Dont forget to change the print statments
from sys import stdin, stdout
import sys
range = xrange
input = raw_input
def input():
return stdin.readline().rstrip()
'''
#-----------------------------------------------------------------------------------
#!/usr/bin/env python
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")
# endregion
#---------------------------------------------------------------------------------------------------
#CODE HERE
def assign():
for i in range(x,len(a)+x):
seg[i]=a[i-x]
def op(c,ind):
for i in range(ind,ind*2+1):
if(c%2):
seg[i]=seg[2*i+1]^seg[2*i+2]
else:
seg[i]=seg[2*i+1]| seg[2*i+2]
if(ind==0):
return
op(c+1,ind//2)
def update(p,val):
pos=x+p-1
seg[pos]=val
def cal(c,ind):
#print(ind,c)
i=ind
if(c%2):
seg[i]=seg[2*i+1]^seg[2*i+2]
else:
seg[i]=seg[2*i+1]| seg[2*i+2]
if(i==0):
return 1
cal(c+1,(ind-1)//2)
cal(0,(pos-1)//2)
def built():
assign()
op(0,(len(a)-1)//2)
n,m=[int(i) for i in input().split()]
a=[int(i) for i in input().split()]
seg=[-1]*(2**(n+1))
x=len(a)-1
built()
for _ in range(m):
p,b=[int(i) for i in input().split()]
update(p,b)
print(seg[0])
```
| 10,295 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.
Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.
Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4) → (1 or 2 = 3, 3 or 4 = 7) → (3 xor 7 = 4). The result is v = 4.
You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
Input
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi < 230) — the i-th query.
Output
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
Examples
Input
2 4
1 6 3 5
1 4
3 4
1 2
1 2
Output
1
3
3
3
Note
For more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Tags: data structures, trees
Correct Solution:
```
import sys, os, io
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math,datetime,functools,itertools,operator,bisect,fractions,statistics
from collections import deque,defaultdict,OrderedDict,Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout
from heapq import heappush, heappop, heapify ,_heapify_max,_heappop_max,nsmallest,nlargest
# sys.setrecursionlimit(111111)
INF=999999999999999999999999
alphabets="abcdefghijklmnopqrstuvwxyz"
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
class SegTree:
def __init__(self, n):
self.N = 1 << n.bit_length()
self.tree = [0] * (self.N<<1)
def update(self, i, j, v):
i += self.N
j += self.N
while i <= j:
if i%2==1: self.tree[i] += v
if j%2==0: self.tree[j] += v
i, j = (i+1) >> 1, (j-1) >> 1
def query(self, i):
v = 0
i += self.N
while i > 0:
v += self.tree[i]
i >>= 1
return v
def SieveOfEratosthenes(limit):
"""Returns all primes not greater than limit."""
isPrime = [True]*(limit+1)
isPrime[0] = isPrime[1] = False
primes = []
for i in range(2, limit+1):
if not isPrime[i]:continue
primes += [i]
for j in range(i*i, limit+1, i):
isPrime[j] = False
return primes
N = 1005
# array to store inverse of 1 to N
factorialNumInverse = [None] * (N + 1)
# array to precompute inverse of 1! to N!
naturalNumInverse = [None] * (N + 1)
# array to store factorial of
# first N numbers
fact = [None] * (N + 1)
# Function to precompute inverse of numbers
def InverseofNumber(p):
naturalNumInverse[0] = naturalNumInverse[1] = 1
for i in range(2, N + 1, 1):
naturalNumInverse[i] = (naturalNumInverse[p % i] *
(p - int(p / i)) % p)
# Function to precompute inverse
# of factorials
def InverseofFactorial(p):
factorialNumInverse[0] = factorialNumInverse[1] = 1
# precompute inverse of natural numbers
for i in range(2, N + 1, 1):
factorialNumInverse[i] = (naturalNumInverse[i] *
factorialNumInverse[i - 1]) % p
# Function to calculate factorial of 1 to N
def factorial(p):
fact[0] = 1
# precompute factorials
for i in range(1, N + 1):
fact[i] = (fact[i - 1] * i) % p
# Function to return nCr % p in O(1) time
def Binomial(N, R, p):
# n C r = n!*inverse(r!)*inverse((n-r)!)
ans = ((fact[N] * factorialNumInverse[R])% p *
factorialNumInverse[N - R])% p
return ans
def main():
mod=1000000007
InverseofNumber(mod)
InverseofFactorial(mod)
factorial(mod)
starttime=datetime.datetime.now()
if(os.path.exists('input.txt')):
sys.stdin = open("input.txt","r")
sys.stdout = open("output.txt","w")
###CODE
tc = 1
for _ in range(tc):
n,q=ria()
a=ria()
pow2sum={}
s=0
for i in range(n,-1,-1):
s+=2**i
pow2sum[s]=1
tree=a.copy()
i=0
t=0
la=2**n
while i+1<len(tree):
if t==0:
tree.append(tree[i]|tree[i+1])
else:
tree.append(tree[i]^tree[i+1])
if len(tree) in pow2sum:
t=1-t
i+=2
tree=tree[::-1]
# Note:
# if i even i's parent is (i-2)//2
# if i odd i's parent is (i-1)//2
# if i even i's brother is (i-1)
# if i odd i's brother is (i+1)
# Now lets go
for i in range(q):
posn,b=ria()
initialpos=len(tree)-posn
tree[initialpos]=b
t=0
while initialpos!=0:
if initialpos%2:
brotherpos=initialpos+1
parentpos=(initialpos-1)//2
else:
brotherpos=initialpos-1
parentpos=(initialpos-2)//2
if t==0:
tree[parentpos]=tree[initialpos]|tree[brotherpos]
else:
tree[parentpos]=tree[initialpos]^tree[brotherpos]
t=1-t
initialpos=parentpos
wi(tree[0])
#<--Solving Area Ends
endtime=datetime.datetime.now()
time=(endtime-starttime).total_seconds()*1000
if(os.path.exists('input.txt')):
print("Time:",time,"ms")
class FastReader(io.IOBase):
newlines = 0
def __init__(self, fd, chunk_size=1024 * 8):
self._fd = fd
self._chunk_size = chunk_size
self.buffer = io.BytesIO()
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
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, size=-1):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
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()
class FastWriter(io.IOBase):
def __init__(self, fd):
self._fd = fd
self.buffer = io.BytesIO()
self.write = self.buffer.write
def flush(self):
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class FastStdin(io.IOBase):
def __init__(self, fd=0):
self.buffer = FastReader(fd)
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
class FastStdout(io.IOBase):
def __init__(self, fd=1):
self.buffer = FastWriter(fd)
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.flush = self.buffer.flush
if __name__ == '__main__':
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()
```
| 10,296 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.
Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.
Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4) → (1 or 2 = 3, 3 or 4 = 7) → (3 xor 7 = 4). The result is v = 4.
You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
Input
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi < 230) — the i-th query.
Output
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
Examples
Input
2 4
1 6 3 5
1 4
3 4
1 2
1 2
Output
1
3
3
3
Note
For more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Tags: data structures, trees
Correct Solution:
```
import sys
input=sys.stdin.readline
import math
# sys.setrecursionlimit(10**9)
def construct(array,cur_pos,tree,start,end):
if(start==end):
# print(cur_pos,"pppp",array[start])
tree[cur_pos]=array[start]
else:
mid=(start+end)//2
w=(n1-int(math.log2(cur_pos+1)))
# print(w,n1,cur_pos+1)
if(w%2!=0):
# print(cur_pos,w)
tree[cur_pos]=(construct(array,2*cur_pos+1,tree,start,mid)|construct(array,2*cur_pos+2,tree,mid+1,end))
else:
# print(cur_pos,w)
tree[cur_pos]=(construct(array,2*cur_pos+1,tree,start,mid)^construct(array,2*cur_pos+2,tree,mid+1,end))
return tree[cur_pos]
def update(cur_pos,l,r,index,increment):
# print(tree)
if(l<=index<=r):
if(l==r):
tree[cur_pos]=increment
else:
mid=(l+r)//2
w=(n1-int(math.log2(cur_pos+1)))
if(w%2!=0):
update(2*cur_pos+1,l,mid,index,increment)
update(2*cur_pos+2,mid+1,r,index,increment)
tree[cur_pos]=tree[2*cur_pos+1]|tree[2*cur_pos+2]
else:
update(2*cur_pos+1,l,mid,index,increment)
update(2*cur_pos+2,mid+1,r,index,increment)
tree[cur_pos]=tree[2*cur_pos+1]^tree[2*cur_pos+2]
return tree[cur_pos]
return 0
l= list(map(int,input().split()))
l1=list(map(int,input().split()))
n=(2**(l[0]))
tree=[0]*(2**(l[0]+1)-1)
n1=int(math.log2(len(tree)))
# print(n1,n,"llll")
construct(l1,0,tree,0,n-1)
# print(tree)
for i in range(l[1]):
# print(tree)
l2=list(map(int,input().split()))
update(0,0,n-1,l2[0]-1,l2[1])
# print(tree,"ppp")
print(tree[0])
```
| 10,297 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.
Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.
Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4) → (1 or 2 = 3, 3 or 4 = 7) → (3 xor 7 = 4). The result is v = 4.
You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
Input
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi < 230) — the i-th query.
Output
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
Examples
Input
2 4
1 6 3 5
1 4
3 4
1 2
1 2
Output
1
3
3
3
Note
For more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Tags: data structures, trees
Correct Solution:
```
from operator import or_, xor
import sys
greg=1
#Stolen from tchr to test Xenia and Bit Operations speed.
n, m = map(int, input().split())
t = [list(map(int, input().split()))]
for i in range(n):
t += [[(or_, xor)[i & 1](*t[i][j: j + 2]) for j in range(0, len(t[i]), 2)]]
for s in sys.stdin:
p, b = s.split()
p = int(p) - 1
t[0][p] = int(b)
for j in range(n):
p >>= 1
t[j + 1][p] = (or_, xor)[j & 1](*t[j][p << 1: (p << 1) + 2])
print(t[-1][0])
```
| 10,298 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.
Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.
Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4) → (1 or 2 = 3, 3 or 4 = 7) → (3 xor 7 = 4). The result is v = 4.
You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.
Input
The first line contains two integers n and m (1 ≤ n ≤ 17, 1 ≤ m ≤ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≤ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≤ pi ≤ 2n, 0 ≤ bi < 230) — the i-th query.
Output
Print m integers — the i-th integer denotes value v for sequence a after the i-th query.
Examples
Input
2 4
1 6 3 5
1 4
3 4
1 2
1 2
Output
1
3
3
3
Note
For more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Tags: data structures, trees
Correct Solution:
```
# lista[0] 0 1 2 3 4 5 6 7
# lista[1] 0 1 2 3
# lista[2] 0 1
# lista[3] 0
from sys import stdin
def ler():
for line in stdin:
yield line.rstrip()
def criar(lista_inicial, altura):
arvore = [lista_inicial]
i = 0
t = 2**altura
operacao = True
while i<altura:
t = t // 2
lista = [0]*(t)
for j in range(t):
if operacao:
lista[j] = arvore[i][2*j] | arvore[i][2*j+1]
else:
lista[j] = arvore[i][2*j] ^ arvore[i][2*j+1]
operacao = not operacao
i += 1
arvore.append(lista)
return arvore
def atualizar(arvore, altura, pos, valor):
arvore[0][pos] = valor
operacao = True
for i in range(1, altura + 1):
pos = pos // 2
if operacao:
arvore[i][pos] = arvore[i-1][2*pos] | arvore[i-1][2*pos+1]
else:
arvore[i][pos] = arvore[i-1][2*pos] ^ arvore[i-1][2*pos+1]
operacao = not operacao
s = ler()
n, m = [int(x) for x in next(s).split()]
lista = [int(x) for x in next(s).split()]
arvore = criar(lista, n)
for i in range(m):
p, b = [int(x) for x in next(s).split()]
atualizar(arvore, n, p-1, b)
print(arvore[-1][0])
```
| 10,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.