message stringlengths 2 433k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 113 108k | cluster float64 12 12 | __index_level_0__ int64 226 217k |
|---|---|---|---|---|---|
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 | instruction | 0 | 10,299 | 12 | 20,598 |
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])
``` | output | 1 | 10,299 | 12 | 20,599 |
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 | instruction | 0 | 10,300 | 12 | 20,600 |
Tags: data structures, trees
Correct Solution:
```
from operator import or_, xor
import sys
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])
``` | output | 1 | 10,300 | 12 | 20,601 |
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 | instruction | 0 | 10,301 | 12 | 20,602 |
Tags: data structures, trees
Correct Solution:
```
import sys,os,io
from sys import stdin
if(os.path.exists('input.txt')):
sys.stdin = open("input.txt","r") ; sys.stdout = open("output.txt","w")
else:
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def powerof2(n):
while n>1:
if n%2:
return False
n//=2
return True
class SegmentTree:
def __init__(self, data, default=0, func=lambda a,b:a+b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
orl = False
for i in range(self._size-1,0,-1):
if powerof2(i+1):
orl = orl ^ True
# print(orl,i,self.data[i + i] , self.data[i + i + 1])
if orl:
self.data[i] = (self.data[i + i] | self.data[i + i + 1])
else:
self.data[i] = (self.data[i + i] ^ self.data[i + i + 1])
# print(self.data)
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
orl = True
# print(self.data)
while idx:
if orl:
self.data[idx] = (self.data[2 * idx] | self.data[2 * idx + 1])
else:
self.data[idx] = (self.data[2 * idx] ^ self.data[2 * idx + 1])
idx >>= 1
orl^= True
# print(self.data)
def __len__(self):
return self._len
def query(self, start, stop):
"""Returns the result of function over the range (inclusive)! [start,stop]"""
start += self._size
stop += self._size+1
res_left = res_right = self._default
orl = True
while start < stop:
if start & 1:
if orl:
res_left = (res_left | self.data[start])
else:
res_left = (res_left ^ self.data[start])
start += 1
if stop & 1:
stop -= 1
if orl:
res_right = (self.data[stop] | res_right)
else:
res_right = (self.data[stop] ^ res_right)
start >>= 1
stop >>= 1
orl ^= True
return self._func(res_left, res_right)
def __repr__(self):
return "SegmentTree({0})".format(self.data)
n,m = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
seg = SegmentTree(a)
for i in range(m):
p,b = [int(x) for x in input().split()]
seg.__setitem__(p-1,b)
print(seg.data[1])
``` | output | 1 | 10,301 | 12 | 20,603 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
from math import log
import sys
def buildTree(arr):
n = len(arr)
tree = [0]*n + arr
for i in range(n-1, 0, -1):
z = int(log(i, 2)) # determines what level of the tree you're at
if N%2 == 0:
if z % 2 == 0:
tree[i] = tree[2*i]^tree[2*i+1]
else:
tree[i] = tree[2*i]|tree[2*i+1]
else:
if z % 2 == 0:
tree[i] = tree[2*i]|tree[2*i+1]
else:
tree[i] = tree[2*i]^tree[2*i+1]
return tree
def updateTree(tree, ind, value, n):
ind += n
tree[ind] = value
while ind > 1:
ind //= 2
z = int(log(ind, 2))
if N%2 == 0:
if z % 2 == 0:
tree[ind] = tree[2*ind]^tree[2*ind+1]
else:
tree[ind] = tree[2*ind]|tree[2*ind+1]
else:
if z % 2 == 0:
tree[ind] = tree[2*ind]|tree[2*ind+1]
else:
tree[ind] = tree[2*ind]^tree[2*ind+1]
return tree
N, m = map(int, sys.stdin.readline().strip().split())
arr = list(map(int, sys.stdin.readline().strip().split()))
tree = buildTree(arr)
for i in range(m):
ind, val = map(int,sys.stdin.readline().strip().split())
tree = updateTree(tree, ind-1, val, len(arr))
print(tree[1])
``` | instruction | 0 | 10,302 | 12 | 20,604 |
Yes | output | 1 | 10,302 | 12 | 20,605 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
A = list(map(int, input().split()))
Query = [list(map(int, input().split())) for _ in range(M)]
L = 2**N
seg = [0]*(2*L-1)
# initialize
for i in range(L):
seg[i+L-1] = A[i]
k = L-1
c = 0
while k > 0:
if c%2 == 0:
for i in range((k-1)//2, k):
seg[i] = seg[2*i+1] | seg[2*i+2]
else:
for i in range((k-1)//2, k):
seg[i] = seg[2*i+1] ^ seg[2*i+2]
c += 1
k = (k-1)//2
# update and return v
def update(k, a):
k += L-1
seg[k] = a
c = 0
while k > 0:
k = (k-1)//2
if c % 2 == 0:
seg[k] = seg[2*k+1] | seg[2*k+2]
else:
seg[k] = seg[2*k+1] ^ seg[2*k+2]
c += 1
return seg[0]
for p, b in Query:
ans = update(p-1, b)
print(ans)
``` | instruction | 0 | 10,303 | 12 | 20,606 |
Yes | output | 1 | 10,303 | 12 | 20,607 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
import math,sys,bisect,heapq
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
from functools import lru_cache
#sys.setrecursionlimit(200000000)
int1 = lambda x: int(x) - 1
#def input(): return sys.stdin.readline().strip()m
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
aj = lambda: list(map(int, input().split()))
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
#MOD = 1000000000 + 7
def Y(c): print(["NO","YES"][c])
def y(c): print(["no","yes"][c])
def Yy(c): print(["No","Yes"][c])
n,m = aj()
size = 2*(2**n) - 1
A = [-1]*size
B = aj()
start = size
for i in range(len(B)-1,-1,-1):
A[-(i+1)] = B[-(i+1)]
start -= 1
last = size - len(B) - 1
for i in range(n):
l = 2**(n-1-i)
for j in range(l):
if i%2 == 0:
A[last]=A[2*last+1]|A[2*last+2]
else:
A[last]=A[2*last+1]^A[2*last+2]
last-=1
def update(a,b):
pos = start + a - 1
step = 0
A[pos] = b
while True:
pos = (pos-1)//2
if step % 2 == 0:
A[pos]=A[2*pos+1]|A[2*pos+2]
else:
A[pos]=A[2*pos+1]^A[2*pos+2]
if pos == 0:
break
step ^= 1
print(A[0])
#print(A)
#print(start)
#print(*A)
for i in range(m):
a,b = aj()
update(a,b)
``` | instruction | 0 | 10,304 | 12 | 20,608 |
Yes | output | 1 | 10,304 | 12 | 20,609 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
import sys
from math import sqrt
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
n,m = map(int,input().split())
a = list(map(int,input().split()))
size = 2 * 2**n # 8
segmentTree = [-1]*size # 1~7
levels = [-1]*size
idx = 0
#initialize
for i in range(int(size/2),size):
segmentTree[i] = a[idx]
levels[i] = 1
idx+=1
#build segment tree
for i in range(2**n-1,0,-1): # 3,2,1
left = 2*i; right = 2*i+1
levels[i] = levels[2*i]+1
if levels[i] % 2 == 0:
segmentTree[i] = segmentTree[left] | segmentTree[right]
else:
segmentTree[i] = segmentTree[left] ^ segmentTree[right]
#update segment tree
for t in range(m):
p,b = map(int,input().split())
segmentTree[2**n+p-1] = b
i = 2**n+p-1
while i != 1:
parent = int(i/2)
left = parent*2; right = parent*2+1
if levels[parent] % 2 == 0:
segmentTree[parent] = segmentTree[left] | segmentTree[right]
else:
segmentTree[parent] = segmentTree[left] ^ segmentTree[right]
i = parent
print(segmentTree[1])
``` | instruction | 0 | 10,305 | 12 | 20,610 |
Yes | output | 1 | 10,305 | 12 | 20,611 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
import math,sys
## from itertools import permutations, combinations;import heapq,random;
from collections import defaultdict,deque
import bisect as bi
def yes():print('YES')
def no():print('NO')
#sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
def I():return (int(sys.stdin.readline()))
def In():return(map(int,sys.stdin.readline().split()))
def Sn():return sys.stdin.readline().strip()
#sys.setrecursionlimit(1500)
def dict(a):
d={}
for x in a:
if d.get(x,-1)!=-1:
d[x]+=1
else:
d[x]=1
return d
def find_gt(a, x):
'Find leftmost value greater than x'
i = bi.bisect_left(a, x)
if i != len(a):
return i
else:
return -1
class Segmenttreemx():
st,n=[],0
def __init__(self,n,l):
self.st=[-P]*(2*n)
self.n=n
for i in range(n):
self.st[i+n]=l[i]
for i in range(n-1,0,-1):
z=(int(math.log(i,2))+1)
if z&1:
self.st[i]=(self.st[i<<1]^self.st[i<<1 | 1])
else:
self.st[i]=(self.st[i<<1]|self.st[i<<1 | 1])
def update(self,p,val):
self.st[p+self.n]=val
p+=self.n
while p>1:
z=(int(math.log(p>>1,2))+1)
if z&1:
self.st[p>>1]=( self.st[p]^self.st[p^1])
else:
self.st[p>>1]=( self.st[p]|self.st[p^1])
p>>=1
def query(self,l,r):
l,r=l+self.n,r+self.n
res=-P
while l<r:
if l&1:
res=max(res,self.st[l])
l+=1
if r&1:
r-=1
res=max(res,self.st[r])
l>>=1
r>>=1
return res
def main():
try:
n,nQ=In()
l=list(In())
N=2**n
Sg=Segmenttreemx(N,l)
for x in range(nQ):
a,b=In()
Sg.update(a-1,b)
print(Sg.st[1])
except:
pass
M = 998244353
P = 1000000007
if __name__ == '__main__':
# for _ in range(I()):main()
for _ in range(1):main()
#End#
# ******************* All The Best ******************* #
``` | instruction | 0 | 10,306 | 12 | 20,612 |
No | output | 1 | 10,306 | 12 | 20,613 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
__author__ = 'ratnesh.mishra'
def create_tree(node, start, last):
if start == last:
tree[node] = arr[start]
create_tree.turn = 1
return tree[node]
l = node << 1
mid = (start+last) >> 1
left = create_tree(l, start, mid)
right = create_tree(l+1, mid+1, last)
if create_tree.turn:
tree[node] = left | right
else:
tree[node] = left ^ right
create_tree.turn ^= 1
return tree[node]
def update_tree(node, start, end, idx):
if start == end and start == idx:
tree[node] = arr[start]
update_tree.turn = 1
return tree[node]
mid = (start + end) >> 1
l = node << 1
left, right = -1, -1
if mid >= idx >= start:
left = update_tree(l, start, mid, idx)
elif end >= idx >= mid+1:
right = update_tree(l+1, mid+1, end, idx)
if left != -1:
if update_tree.turn:
tree[node] = left | tree[l+1]
else:
tree[node] = left ^ tree[l+1]
elif right != -1:
if update_tree.turn:
tree[node] = tree[l] | right
else:
tree[node] = tree[l] ^ right
update_tree.turn ^= 1
return tree[node]
if __name__ == '__main__':
try:
n, m = map(int, input().split())
arr = [0]
arr.extend(list(map(int, input().split())))
tree = [0]*(2*len(arr) + 1)
turn = 0
create_tree(1, 1, (2*n))
for _ in range(m):
i, val = map(int, input().split())
arr[i] = val
print(update_tree(1, 1, (2*n), i))
except Exception as e:
print(str(e))
``` | instruction | 0 | 10,307 | 12 | 20,614 |
No | output | 1 | 10,307 | 12 | 20,615 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
n, m = list(map(int, input().split(' ')))
arr = list(map(int, input().split(' ')))
# Align with 1-based indexing
arr.insert(0, None)
# Full and complete binary tree
class Tree(object):
def __init__(self, interval, depth = 0, parent = None):
self.interval = interval
self.parent = parent
self.depth = depth
# If this isn't a leaf, make two children so we have a full tree
if interval[1] - interval[0] > 0:
num_elements = interval[1] - interval[0] + 1
# Complete with weight on left
left_upper = interval[0] + num_elements // 2 - 1
right_lower = left_upper + 1
self.left = Tree((interval[0], left_upper), depth + 1, self)
self.right = Tree((right_lower, interval[1]), depth + 1, self)
else:
self.left = None
self.right = None
self.updateNode()
# print(self.interval, self.gcd)
# if not self.isLeaf():
# print("Left child:\t", self.left.interval)
# print("Right child:\t", self.right.interval)
def isLeaf(self):
return self.left is None and self.right is None
# Update this node's gcd
def updateNode(self):
if self.isLeaf():
self.value = arr[self.interval[0]]
elif self.depth & 1:
# odd is xor
self.value = self.left.value ^ self.right.value
else:
# even is or
self.value = self.left.value | self.right.value
# Iterator of the path to the leaf containing the specified index
def leafSearch(self, index):
currentNode = self
while(not currentNode.isLeaf()):
yield(currentNode)
if index <= currentNode.left.interval[1]:
currentNode = currentNode.left
else:
currentNode = currentNode.right
yield(currentNode)
# Search to the changed leaf, then update the gcds from the bottom up
def updateValue(self, index):
for node in [*self.leafSearch(index)][::-1]:
node.updateNode()
def containsInterval(self, interval):
return self.interval[0] <= interval[0] and self.interval[1] >= interval[1]
# Build the tree from the bottom up
root = Tree((1, len(arr) - 1), 1) # Why the minus? Isn't this 1-based?
result = list()
for i in range(0, m):
index, value = list(map(int, input().split(' ')))
# Update the array and tree
arr[index] = value
root.updateValue(index)
# Record the result
print(root.value)
``` | instruction | 0 | 10,308 | 12 | 20,616 |
No | output | 1 | 10,308 | 12 | 20,617 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
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
Submitted Solution:
```
import sys
input=sys.stdin.readline
import math
sys.setrecursionlimit(10**9)
def construct(array,cur_pos,tree,start,end):
if(start==end):
tree[cur_pos]=array[start]
else:
mid=(start+end)//2
w=int(math.log(int(n-2**math.log(cur_pos+1))))
# print(w)
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=int(math.log(int(n-2**math.log(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]*(4*n)
construct(l1,0,tree,0,n-1)
for i in range(l[1]):
l2=list(map(int,input().split()))
update(0,0,n-1,l2[0]-1,l2[1])
# print(tree,"ppp")
print(tree[0])
``` | instruction | 0 | 10,309 | 12 | 20,618 |
No | output | 1 | 10,309 | 12 | 20,619 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136 | instruction | 0 | 10,566 | 12 | 21,132 |
"Correct Solution:
```
import heapq
from collections import defaultdict
N = int(input())
P = list(map(int,input().split()))
d_r = defaultdict(lambda:N+1)
h_r = []
d_r2 = defaultdict(lambda:N+1)
h_r2 = []
for i in range(N):
p = P[i]
while h_r2:
q = heapq.heappop(h_r2)
if q < p:
d_r2[q] = p
else:
heapq.heappush(h_r2,q)
break
while h_r:
q = heapq.heappop(h_r)
if q < p:
d_r[q] = p
heapq.heappush(h_r2,q)
else:
heapq.heappush(h_r,q)
break
heapq.heappush(h_r,p)
d_l = defaultdict(lambda:0)
h_l = []
d_l2 = defaultdict(lambda:0)
h_l2 = []
for i in range(N-1,-1,-1):
p = P[i]
while h_l2:
q = heapq.heappop(h_l2)
if q < p:
d_l2[q] = p
else:
heapq.heappush(h_l2,q)
break
while h_l:
q = heapq.heappop(h_l)
if q < p:
d_l[q] = p
heapq.heappush(h_l2,q)
else:
heapq.heappush(h_l,q)
break
heapq.heappush(h_l,p)
d = {}
for i in range(N):
d[P[i]] = i
d[N+1] = N
d[0] = -1
ans = 0
for i in range(N):
x = d[d_l2[P[i]]]
y = d[d_l[P[i]]]
z = d[d_r[P[i]]]
w = d[d_r2[P[i]]]
ans += P[i]*((y-x)*(z-i)+(w-z)*(i-y))
print(ans)
``` | output | 1 | 10,566 | 12 | 21,133 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136 | instruction | 0 | 10,567 | 12 | 21,134 |
"Correct Solution:
```
def argsort(a):
return list(map(lambda z: z[1], sorted(zip(a, range(len(a))))))
N = int(input())
P = list(map(int, input().split()))
a = argsort(P)
left = [i for i in range(N)]
right = [i for i in range(N)]
result = 0
for i in range(1, N):
k = a[i - 1]
extend_left = k - 1 >= 0 and P[k - 1] < i
extend_right = k + 1 < N and P[k + 1] < i
if extend_left and extend_right:
L = left[k - 1]
R = right[k + 1]
elif extend_left:
L = left[k - 1]
R = k
elif extend_right:
R = right[k + 1]
L = k
else:
L = k
R = k
right[L] = R
left[R] = L
if L - 1 >= 0:
if L - 2 >= 0 and P[L - 2] < i:
LL = left[L - 2]
else:
LL = L - 1
result += ((L - 1) - LL + 1) * (R - k + 1) * i;
if R + 1 < N:
if R + 2 < N and P[R + 2] < i:
RR = right[R + 2]
else:
RR = R + 1
result += (RR - (R + 1) + 1) * (k - L + 1) * i;
print(result)
``` | output | 1 | 10,567 | 12 | 21,135 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136 | instruction | 0 | 10,568 | 12 | 21,136 |
"Correct Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from operator import itemgetter
n = int(readline())
ppp = list(map(int,readline().split()))
def BIT_add(i,x):
while i <= n:
tree[i] += x
i += i&(-i)
def BIT_sum(i):
s = 0
while i:
s += tree[i]
i -= i&(-i)
return s
def BIT_search(x):
# 二分探索。和がx以上となる最小のインデックス(>= 1)を返す
i = 0
s = 0
step = 1<<(n.bit_length()-1)
while step:
if i+step <= n and s + tree[i+step] < x:
i += step
s += tree[i]
step >>= 1
return i+1
q = sorted(enumerate(ppp,1),key=itemgetter(1),reverse=True)
tree = [0]*(n+1)
ans = 0
for i, p in q:
L = BIT_sum(i) # 左にある既に書き込んだ数の個数
BIT_add(i,1)
R = n-p-L # 右にある既に書き込んだ数の個数
LL = BIT_search(L-1) if L >= 2 else 0
LR = BIT_search(L) if L >= 1 else 0
RL = BIT_search(L+2) if R >= 1 else n+1
RR = BIT_search(L+3) if R >= 2 else n+1
ans += p*((LR-LL)*(RL-i)+(RR-RL)*(i-LR))
print(ans)
``` | output | 1 | 10,568 | 12 | 21,137 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136 | instruction | 0 | 10,570 | 12 | 21,140 |
"Correct Solution:
```
def solve():
N = int(input())
Ps = list(map(int, input().split()))
def makeBIT(numEle):
numPow2 = 2 ** (numEle-1).bit_length()
data = [0] * (numPow2+1)
return data, numPow2
def addValue(iA, A):
iB = iA + 1
while iB <= numPow2:
data[iB] += A
iB += iB & -iB
def getSum(iA):
iB = iA + 1
ans = 0
while iB > 0:
ans += data[iB]
iB -= iB & -iB
return ans
data, numPow2 = makeBIT(N)
iPs = list(range(N))
iPs.sort(key=lambda iP: Ps[iP])
ans = 0
for iP in reversed(iPs):
v = getSum(iP)
Bs = []
for x in range(v-1, v+3):
if x <= 0:
L = -1
elif getSum(numPow2-1) < x:
L = N
else:
maxD = numPow2.bit_length()-1
L = 0
S = 0
for d in reversed(range(maxD)):
if S+data[L+(1<<d)] < x:
S += data[L+(1<<d)]
L += 1<<d
Bs.append(L)
num = (Bs[1]-Bs[0])*(Bs[2]-iP) + (iP-Bs[1])*(Bs[3]-Bs[2])
ans += Ps[iP] * num
addValue(iP, 1)
print(ans)
solve()
``` | output | 1 | 10,570 | 12 | 21,141 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136 | instruction | 0 | 10,571 | 12 | 21,142 |
"Correct Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from operator import itemgetter
n = int(readline())
ppp = list(map(int,readline().split()))
class Bit:
def __init__(self, n):
self.size = n
self.tree = [0] * (n + 1)
self.depth = n.bit_length()
def sum(self, i):
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def add(self, i, x):
while i <= self.size:
self.tree[i] += x
i += i & -i
def lower_bound(self, x):
""" 累積和がx以上になる最小のindexと、その直前までの累積和 """
sum_ = 0
pos = 0
for i in range(self.depth, -1, -1):
k = pos + (1 << i)
if k <= self.size and sum_ + self.tree[k] < x:
sum_ += self.tree[k]
pos += 1 << i
return pos + 1
q = sorted(enumerate(ppp,1),key=itemgetter(1),reverse=True)
bit = Bit(n+4)
bit.add(1,1)
bit.add(2,1)
bit.add(n+3,1)
bit.add(n+4,1)
ans = 0
for i, p in q:
f = bit.sum(i+2)
LL = max(2,bit.lower_bound(f-1))
LR = bit.lower_bound(f)
RL = bit.lower_bound(f+1)
RR = min(n+3,bit.lower_bound(f+2))
ans += p*((i+2-LR)*(RR-RL)+(LR-LL)*(RL-i-2))
bit.add(i+2,1)
print(ans)
``` | output | 1 | 10,571 | 12 | 21,143 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136 | instruction | 0 | 10,572 | 12 | 21,144 |
"Correct Solution:
```
class SparseTable:
def __init__(self, a, func=max, one=-10**18):
self.table = [a[:]]
self.n = len(a)
self.logn = self.n.bit_length()
self.func = func
self.one = one
for i in map(lambda x: 1 << x, range(self.logn - 1)):
self.table.append([])
for j in range(self.n - i * 2 + 1):
self.table[-1].append(self.func(self.table[-2][j],
self.table[-2][j + i]))
def get_section(self, i, j):
length = j - i
log = length.bit_length() - 1
if length <= 0:
return self.one
a = self.func(self.table[log][i], self.table[log][j - (1<<log)])
return a
def low(m, x):
mi = 0
ma = m - 1
if ma < 0 or sp.get_section(0, m) <= x:
return - 1
while mi != ma:
mm = (mi + ma) // 2 + 1
if sp.get_section(mm, m) > x:
mi = mm
else:
ma = mm - 1
return mi
def high(m, x):
mi = m
ma = n - 1
if m >= n or sp.get_section(m, n) <= x:
return n
while mi != ma:
mm = (mi + ma) // 2
if sp.get_section(m, mm+1) > x:
ma = mm
else:
mi = mm + 1
return mi
n = int(input())
p = [int(i) for i in input().split()]
sp = SparseTable(p)
ans = 0
for i in range(n):
j = low(i, p[i])
k = low(j, p[i])
l = high(i, p[i])
m = high(l+1, p[i])
ans += p[i] * ((i-j) * (m-l) + (j-k) * (l-i))
print(ans)
``` | output | 1 | 10,572 | 12 | 21,145 |
Provide a correct Python 3 solution for this coding contest problem.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136 | instruction | 0 | 10,573 | 12 | 21,146 |
"Correct Solution:
```
class BinaryIndexedTree:
def __init__(self, size):
self.data = [0] * (size+1)
self.msb = 1 << (size.bit_length()-1)
def add(self, i, w):
i += 1
while i < len(self.data):
self.data[i] += w
i += i & -i
def get_sum(self, i):
res = 0
while i > 0:
res += self.data[i]
i -= i & -i
return res
def __getitem__(self, i):
"""
[0,i)
"""
if isinstance(i, slice):
return self.get_sum(i.stop) if i.start is None else self.get_sum(i.stop) - self.get_sum(i.start)
else:
return 0 # fake value
__setitem__ = add
def bisect_left(self, v):
"""
return smallest i s.t v <= sum[:i]
"""
i = 0
k = self.msb
while k > 0:
i += k
if i < len(self.data) and self.data[i] < v:
v -= self.data[i]
else:
i -= k
k >>= 1
return i
def bisect_right(self, v):
"""
return smallest i s.t v < sum[:i]
"""
i = 0
k = self.msb
while k > 0:
i += k
if i < len(self.data) and self.data[i] <= v:
v -= self.data[i]
else:
i -= k
k >>= 1
return i
bisect = bisect_right
def naive(P):
def it():
for i in range(len(P)-1):
for j in range(i+1,len(P)):
yield sorted(P[i:j+1])[-2]
return sum(it())
def solve(P):
def it():
bit = BinaryIndexedTree(len(P))
for cnt, (v,i) in enumerate(sorted(((v,i) for i,v in enumerate(P)), reverse=True)):
bit[i] += 1
c = bit.get_sum(i)
low1 = -1 if c <= 0 else bit.bisect_left(c)
low2 = -1 if c <= 1 else bit.bisect_left(c-1)
up1 = len(P) if c > cnt-1 else bit.bisect_left(c+2)
up2 = len(P) if c > cnt-2 else bit.bisect_left(c+3)
yield v*((up1-i)*(low1-low2)+(i-low1)*(up2-up1))
return sum(it())
if __name__ == '__main__':
N = int(input())
P = list(map(int,input().split()))
print(solve(P))
``` | output | 1 | 10,573 | 12 | 21,147 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given is a permutation P of \\{1, 2, \ldots, N\\}.
For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.
Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Constraints
* 2 \le N \le 10^5
* 1 \le P_i \le N
* P_i \neq P_j (i \neq j)
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1 P_2 \ldots P_N
Output
Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.
Examples
Input
3
2 3 1
Output
5
Input
5
1 2 3 4 5
Output
30
Input
8
8 2 7 3 4 5 6 1
Output
136
Submitted Solution:
```
from bisect import bisect_left
import array
n = int(input())
p = []
for i, x in enumerate(map(int, input().split())):
p.append([x, i])
p.sort(reverse=True)
s = array.array('i', [-1, -1, p[0][1], n, n])
#print(p)
ans = 0
i = 2
for a, x in p[1:]:
t = bisect_left(s, x)
ans += a * ((x - s[t-1]) * (s[t+1] - s[t]) + (s[t] - x) * (s[t-1] - s[t-2]))
#print(t, s)
s.insert(t, x)
i += 1
print(ans)
``` | instruction | 0 | 10,576 | 12 | 21,152 |
Yes | output | 1 | 10,576 | 12 | 21,153 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is actually possible to sort the sequence using this operation.
Constraints
* 1 \leq N \leq 2\times 10^5
* (P_1,P_2,...,P_N) is a permutation of (1,2,...,N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1
:
P_N
Output
Print the minimum number of operations required.
Examples
Input
4
1
3
2
4
Output
2
Input
6
3
2
5
1
4
6
Output
4
Input
8
6
3
1
2
7
4
8
5
Output
5 | instruction | 0 | 10,608 | 12 | 21,216 |
"Correct Solution:
```
N = int(input())
P = [int(input()) for _ in range(N)]
K = [0]*(N+1)
for p in P:
K[p] = K[p-1] + 1
print(N - max(K))
``` | output | 1 | 10,608 | 12 | 21,217 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is actually possible to sort the sequence using this operation.
Constraints
* 1 \leq N \leq 2\times 10^5
* (P_1,P_2,...,P_N) is a permutation of (1,2,...,N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1
:
P_N
Output
Print the minimum number of operations required.
Examples
Input
4
1
3
2
4
Output
2
Input
6
3
2
5
1
4
6
Output
4
Input
8
6
3
1
2
7
4
8
5
Output
5 | instruction | 0 | 10,609 | 12 | 21,218 |
"Correct Solution:
```
n = int(input())
P = [int(input()) for _ in range(n)]
Q = [0]*(n+1)
for i, j in enumerate(P):
Q[j-1] = i+1
count = 0
m = 0
for i in range(n):
count += 1
if Q[i] > Q[i+1]:
m = max(m, count)
count = 0
print(n-m)
``` | output | 1 | 10,609 | 12 | 21,219 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is actually possible to sort the sequence using this operation.
Constraints
* 1 \leq N \leq 2\times 10^5
* (P_1,P_2,...,P_N) is a permutation of (1,2,...,N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1
:
P_N
Output
Print the minimum number of operations required.
Examples
Input
4
1
3
2
4
Output
2
Input
6
3
2
5
1
4
6
Output
4
Input
8
6
3
1
2
7
4
8
5
Output
5 | instruction | 0 | 10,610 | 12 | 21,220 |
"Correct Solution:
```
n=int(input())
l=[0]*n
for i in range(n):
l[int(input())-1]=i
pre=-1
now=0
ans=n
for i in l:
if pre<i:
now+=1
else:
ans=min(ans,n-now)
now=1
pre=i
print(min(ans,n-now))
``` | output | 1 | 10,610 | 12 | 21,221 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is actually possible to sort the sequence using this operation.
Constraints
* 1 \leq N \leq 2\times 10^5
* (P_1,P_2,...,P_N) is a permutation of (1,2,...,N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1
:
P_N
Output
Print the minimum number of operations required.
Examples
Input
4
1
3
2
4
Output
2
Input
6
3
2
5
1
4
6
Output
4
Input
8
6
3
1
2
7
4
8
5
Output
5 | instruction | 0 | 10,611 | 12 | 21,222 |
"Correct Solution:
```
N = int(input())
P = [int(input()) for _ in range(N)]
dp = [0 for _ in range(N+1)]
for p in P:
dp[p] = dp[p-1]+1
print(N-max(dp))
``` | output | 1 | 10,611 | 12 | 21,223 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is actually possible to sort the sequence using this operation.
Constraints
* 1 \leq N \leq 2\times 10^5
* (P_1,P_2,...,P_N) is a permutation of (1,2,...,N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1
:
P_N
Output
Print the minimum number of operations required.
Examples
Input
4
1
3
2
4
Output
2
Input
6
3
2
5
1
4
6
Output
4
Input
8
6
3
1
2
7
4
8
5
Output
5 | instruction | 0 | 10,612 | 12 | 21,224 |
"Correct Solution:
```
import bisect
n = int(input())
p = [int(input()) for _ in range(n)]
idx = dict()
for i in range(n):
idx[p[i]] = i
c = 0
cnt = 1
for i in range(1, n):
if idx[i + 1] > idx[i]:
cnt += 1
else:
c = max(c, cnt)
cnt = 1
c = max(c, cnt)
print(n - c)
``` | output | 1 | 10,612 | 12 | 21,225 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is actually possible to sort the sequence using this operation.
Constraints
* 1 \leq N \leq 2\times 10^5
* (P_1,P_2,...,P_N) is a permutation of (1,2,...,N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1
:
P_N
Output
Print the minimum number of operations required.
Examples
Input
4
1
3
2
4
Output
2
Input
6
3
2
5
1
4
6
Output
4
Input
8
6
3
1
2
7
4
8
5
Output
5 | instruction | 0 | 10,613 | 12 | 21,226 |
"Correct Solution:
```
n,*p=map(int,open(0))
s=[0]*-~n
for i in p:s[i]=s[i-1]+1
print(n-max(s))
``` | output | 1 | 10,613 | 12 | 21,227 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is actually possible to sort the sequence using this operation.
Constraints
* 1 \leq N \leq 2\times 10^5
* (P_1,P_2,...,P_N) is a permutation of (1,2,...,N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1
:
P_N
Output
Print the minimum number of operations required.
Examples
Input
4
1
3
2
4
Output
2
Input
6
3
2
5
1
4
6
Output
4
Input
8
6
3
1
2
7
4
8
5
Output
5 | instruction | 0 | 10,614 | 12 | 21,228 |
"Correct Solution:
```
N=int(input())
P=[int(input())-1 for i in range(N)]
Q=[0 for i in range(N)]
for i in range(N):
Q[P[i]]=i
L=[1]
k=0
for i in range(1,N):
if Q[i-1]<Q[i]:
L[k]+=1
else:
L.append(0)
k+=1
L[k]+=1
print(N-max(L))
``` | output | 1 | 10,614 | 12 | 21,229 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is actually possible to sort the sequence using this operation.
Constraints
* 1 \leq N \leq 2\times 10^5
* (P_1,P_2,...,P_N) is a permutation of (1,2,...,N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1
:
P_N
Output
Print the minimum number of operations required.
Examples
Input
4
1
3
2
4
Output
2
Input
6
3
2
5
1
4
6
Output
4
Input
8
6
3
1
2
7
4
8
5
Output
5 | instruction | 0 | 10,615 | 12 | 21,230 |
"Correct Solution:
```
N = int(input())
P = []
for i in range(N):
P.append(int(input()))
#print(P)
S = [0 for _ in range(N+1)]
for i in range(N):
S[P[i]] = S[P[i]-1] + 1
print(N-max(S))
``` | output | 1 | 10,615 | 12 | 21,231 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is actually possible to sort the sequence using this operation.
Constraints
* 1 \leq N \leq 2\times 10^5
* (P_1,P_2,...,P_N) is a permutation of (1,2,...,N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1
:
P_N
Output
Print the minimum number of operations required.
Examples
Input
4
1
3
2
4
Output
2
Input
6
3
2
5
1
4
6
Output
4
Input
8
6
3
1
2
7
4
8
5
Output
5
Submitted Solution:
```
N=int(input())
P=[int(input()) for i in range(N)]
pos=[-1]*N
for i,p in enumerate(P):
pos[p-1]=i
x,mx=0,0
for i in range(N-1):
if pos[i]<pos[i+1]:
x+=1
mx=max(mx,x)
else:
x=0
print(N-mx-1)
``` | instruction | 0 | 10,616 | 12 | 21,232 |
Yes | output | 1 | 10,616 | 12 | 21,233 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is actually possible to sort the sequence using this operation.
Constraints
* 1 \leq N \leq 2\times 10^5
* (P_1,P_2,...,P_N) is a permutation of (1,2,...,N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1
:
P_N
Output
Print the minimum number of operations required.
Examples
Input
4
1
3
2
4
Output
2
Input
6
3
2
5
1
4
6
Output
4
Input
8
6
3
1
2
7
4
8
5
Output
5
Submitted Solution:
```
import bisect
N=int(input())
A=[int(input())for i in range(N)]
#print(A)
L=[0 for i in range(N+1)]
for i in range(N):
if L[A[i]-1]>0:
L[A[i]]=(L[A[i]-1]+1)
else:
L[A[i]]=1
print(N-max(L))
``` | instruction | 0 | 10,617 | 12 | 21,234 |
Yes | output | 1 | 10,617 | 12 | 21,235 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is actually possible to sort the sequence using this operation.
Constraints
* 1 \leq N \leq 2\times 10^5
* (P_1,P_2,...,P_N) is a permutation of (1,2,...,N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1
:
P_N
Output
Print the minimum number of operations required.
Examples
Input
4
1
3
2
4
Output
2
Input
6
3
2
5
1
4
6
Output
4
Input
8
6
3
1
2
7
4
8
5
Output
5
Submitted Solution:
```
from collections import defaultdict
n = int(input())
p = [int(input()) for i in range(n)]
d = defaultdict(int)
for i in p:
d[i] = d[i - 1] + 1
print(n - max(d.values()))
``` | instruction | 0 | 10,618 | 12 | 21,236 |
Yes | output | 1 | 10,618 | 12 | 21,237 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is actually possible to sort the sequence using this operation.
Constraints
* 1 \leq N \leq 2\times 10^5
* (P_1,P_2,...,P_N) is a permutation of (1,2,...,N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1
:
P_N
Output
Print the minimum number of operations required.
Examples
Input
4
1
3
2
4
Output
2
Input
6
3
2
5
1
4
6
Output
4
Input
8
6
3
1
2
7
4
8
5
Output
5
Submitted Solution:
```
n=int(input())
p=[int(input())-1for _ in[0]*n]
q=[0]*n
for i in range(n):q[p[i]]=i
r,c=0,1
for i in range(n-1):
c=c+1if q[i]<q[i+1]else 1
if r<c:r=c
if r<c:r=c
print(n-r)
``` | instruction | 0 | 10,619 | 12 | 21,238 |
Yes | output | 1 | 10,619 | 12 | 21,239 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is actually possible to sort the sequence using this operation.
Constraints
* 1 \leq N \leq 2\times 10^5
* (P_1,P_2,...,P_N) is a permutation of (1,2,...,N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1
:
P_N
Output
Print the minimum number of operations required.
Examples
Input
4
1
3
2
4
Output
2
Input
6
3
2
5
1
4
6
Output
4
Input
8
6
3
1
2
7
4
8
5
Output
5
Submitted Solution:
```
N = int(input())
list = {0:0}
for i in range(1,N):
list[int(input())] = i
x = 0
for j in range(2,N-1):
if list[j-1] > list[j] :
x = x + 1
print(x)
``` | instruction | 0 | 10,620 | 12 | 21,240 |
No | output | 1 | 10,620 | 12 | 21,241 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is actually possible to sort the sequence using this operation.
Constraints
* 1 \leq N \leq 2\times 10^5
* (P_1,P_2,...,P_N) is a permutation of (1,2,...,N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1
:
P_N
Output
Print the minimum number of operations required.
Examples
Input
4
1
3
2
4
Output
2
Input
6
3
2
5
1
4
6
Output
4
Input
8
6
3
1
2
7
4
8
5
Output
5
Submitted Solution:
```
n = int(input())
p = []
for i in range(n):
p.append(int(input()))
dic = {p[0]:1}
for i in range(1,n):
print(dic)
check = 0
for k in list(dic):
#print(k, dic[k])
if p[i] == k + dic[k]:
dic[k] += 1
check = 1
break
elif p[i] == k - 1:
dic[p[i]] = 1
if dic[k] < max(dic.values()) or dic[k] == 1:
dic.pop(k)
else:
dic[p[i]] = 1
print(n - max(dic.values()))
``` | instruction | 0 | 10,621 | 12 | 21,242 |
No | output | 1 | 10,621 | 12 | 21,243 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is actually possible to sort the sequence using this operation.
Constraints
* 1 \leq N \leq 2\times 10^5
* (P_1,P_2,...,P_N) is a permutation of (1,2,...,N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1
:
P_N
Output
Print the minimum number of operations required.
Examples
Input
4
1
3
2
4
Output
2
Input
6
3
2
5
1
4
6
Output
4
Input
8
6
3
1
2
7
4
8
5
Output
5
Submitted Solution:
```
n=int(input())
f,s=n//2,n//2+1
p=[int(input()) for _ in range(n)]
fi=p.index(f)
si=p.index(s)
ans=0
if fi>si:
ans+=1
for i in range(fi-1,-1,-1):
if p[i]==f-1: f-=1
for i in range(si+1,n):
if p[i]==s+1: s+=1
ans+=f-1+n-s
print(f-1+n-s)
``` | instruction | 0 | 10,622 | 12 | 21,244 |
No | output | 1 | 10,622 | 12 | 21,245 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation:
* Choose an element in the sequence and move it to the beginning or the end of the sequence.
Find the minimum number of operations required. It can be proved that it is actually possible to sort the sequence using this operation.
Constraints
* 1 \leq N \leq 2\times 10^5
* (P_1,P_2,...,P_N) is a permutation of (1,2,...,N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
P_1
:
P_N
Output
Print the minimum number of operations required.
Examples
Input
4
1
3
2
4
Output
2
Input
6
3
2
5
1
4
6
Output
4
Input
8
6
3
1
2
7
4
8
5
Output
5
Submitted Solution:
```
import sys
input = sys.stdin.readline
def main():
N = int(input())
A = [int(input()) for i in range(N)]
dp = [0] * N
for i in range(N):
if A[i] > 1 or i == 0:
dp[A[i]-1] = dp[A[i]-2] + 1
print(N - max(dp))
if __name__ == "__main__":
main()
``` | instruction | 0 | 10,623 | 12 | 21,246 |
No | output | 1 | 10,623 | 12 | 21,247 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Suppose you are given a sequence S of k pairs of integers (a_1, b_1), (a_2, b_2), ..., (a_k, b_k).
You can perform the following operations on it:
1. Choose some position i and increase a_i by 1. That can be performed only if there exists at least one such position j that i ≠ j and a_i = a_j. The cost of this operation is b_i;
2. Choose some position i and decrease a_i by 1. That can be performed only if there exists at least one such position j that a_i = a_j + 1. The cost of this operation is -b_i.
Each operation can be performed arbitrary number of times (possibly zero).
Let f(S) be minimum possible x such that there exists a sequence of operations with total cost x, after which all a_i from S are pairwise distinct.
Now for the task itself ...
You are given a sequence P consisting of n pairs of integers (a_1, b_1), (a_2, b_2), ..., (a_n, b_n). All b_i are pairwise distinct. Let P_i be the sequence consisting of the first i pairs of P. Your task is to calculate the values of f(P_1), f(P_2), ..., f(P_n).
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of pairs in sequence P.
Next n lines contain the elements of P: i-th of the next n lines contains two integers a_i and b_i (1 ≤ a_i ≤ 2 ⋅ 10^5, 1 ≤ b_i ≤ n). It is guaranteed that all values of b_i are pairwise distinct.
Output
Print n integers — the i-th number should be equal to f(P_i).
Examples
Input
5
1 1
3 3
5 5
4 2
2 4
Output
0
0
0
-5
-16
Input
4
2 4
2 3
2 2
1 1
Output
0
3
7
1
Submitted Solution:
```
print("""0
0
0
-5
-16""")
``` | instruction | 0 | 10,814 | 12 | 21,628 |
No | output | 1 | 10,814 | 12 | 21,629 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n.
Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries.
A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it.
A cyclic shift of a permutation (p_1, p_2, …, p_n) is a permutation (p_i, p_{i + 1}, …, p_{n}, p_1, p_2, …, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1).
A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, …, a_{i_k} for some i_1, i_2, …, i_k such that l ≤ i_1 < i_2 < … < i_k ≤ r.
Input
The first line contains three integers n, m, q (1 ≤ n, m, q ≤ 2 ⋅ 10^5) — the length of the permutation p, the length of the array a and the number of queries.
The next line contains n integers from 1 to n, where the i-th of them is the i-th element of the permutation. Each integer from 1 to n appears exactly once.
The next line contains m integers from 1 to n, the i-th of them is the i-th element of the array a.
The next q lines describe queries. The i-th of these lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m), meaning that the i-th query is about the subsegment of the array from the l_i-th to the r_i-th positions, inclusive.
Output
Print a single string of length q, consisting of 0 and 1, the digit on the i-th positions should be 1, if the subsegment of array a from the l_i-th to the r_i-th positions, inclusive, contains a subsequence that is a cyclic shift of p, and 0 otherwise.
Examples
Input
3 6 3
2 1 3
1 2 3 1 2 3
1 5
2 6
3 5
Output
110
Input
2 4 3
2 1
1 1 2 2
1 2
2 3
3 4
Output
010
Note
In the first example the segment from the 1-st to the 5-th positions is 1, 2, 3, 1, 2. There is a subsequence 1, 3, 2 that is a cyclic shift of the permutation. The subsegment from the 2-nd to the 6-th positions also contains a subsequence 2, 1, 3 that is equal to the permutation. The subsegment from the 3-rd to the 5-th positions is 3, 1, 2, there is only one subsequence of length 3 (3, 1, 2), but it is not a cyclic shift of the permutation.
In the second example the possible cyclic shifts are 1, 2 and 2, 1. The subsegment from the 1-st to the 2-nd positions is 1, 1, its subsequences are not cyclic shifts of the permutation. The subsegment from the 2-nd to the 3-rd positions is 1, 2, it coincides with the permutation. The subsegment from the 3 to the 4 positions is 2, 2, its subsequences are not cyclic shifts of the permutation. | instruction | 0 | 10,863 | 12 | 21,726 |
Tags: data structures, dfs and similar, dp, math, trees
Correct Solution:
```
# 注意array cache順序 QQ
from math import log, floor
import sys
"""
class RMQ:
'''
maximum version rmq
query: max([l, r])
'''
def __init__(self, nums):
size = floor(log(len(nums)) // log(2)) + 1
self.nums = [nums]
for i in range(1, size):
last = self.nums[-1]
delta = 1 << (i-1)
self.nums.append([max(last[j], last[j + delta])
for j in range(len(nums) - 2 * delta + 1)])
def query(self, l, r):
delta = floor(log(r - l + 1) // log(2))
return max(self.nums[delta][l], self.nums[delta][r-2**delta+1])
"""
n, m, q = map(int, sys.stdin.readline().split())
perms = list(map(int, sys.stdin.readline().split()))
nums = list(map(int, sys.stdin.readline().split()))
logit = floor(log(n) // log(2)) + 1
current_max_index = [-1]*(n+1)
prevs = [[-1]*m for i in range(logit)]
prev_map = [-2]*(n+1)
for i, j in zip(perms[1:]+[perms[0]], perms):
prev_map[i] = j
# Update the one step case
for idx, ele in enumerate(nums):
prevs[0][idx] = current_max_index[prev_map[ele]]
current_max_index[ele] = idx
# Update the n_step table
for i in range(1, logit):
for idx, ele in enumerate(nums):
if prevs[i-1][idx] != -1:
prevs[i][idx] = prevs[i-1][prevs[i-1][idx]]
prev_n = []
# Create the update sequence
use = [i for i in range(n.bit_length()) if 1 & (n - 1) >> i]
max_pre = -1
ran = [-1] * (m+2)
for i in range(m):
t = i
for dim in use:
t = prevs[dim][t]
if t == -1:
break
max_pre = max(t, max_pre)
ran[i] = max_pre
"""
for i in range(m):
remain = n - 1
idx = i
while remain and idx != -1:
ma = floor(log(remain) // log(2))
idx = prevs[ma][idx]
remain -= 2**ma
prev_n.append(idx)
"""
#rmq = RMQ(prev_n)
ans = [None]*q
for i in range(q):
l, r = map(int, sys.stdin.readline().split())
ans[i] = str(int(l - 1 <= ran[r-1]))
print("".join(ans))
``` | output | 1 | 10,863 | 12 | 21,727 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n.
Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries.
A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it.
A cyclic shift of a permutation (p_1, p_2, …, p_n) is a permutation (p_i, p_{i + 1}, …, p_{n}, p_1, p_2, …, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1).
A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, …, a_{i_k} for some i_1, i_2, …, i_k such that l ≤ i_1 < i_2 < … < i_k ≤ r.
Input
The first line contains three integers n, m, q (1 ≤ n, m, q ≤ 2 ⋅ 10^5) — the length of the permutation p, the length of the array a and the number of queries.
The next line contains n integers from 1 to n, where the i-th of them is the i-th element of the permutation. Each integer from 1 to n appears exactly once.
The next line contains m integers from 1 to n, the i-th of them is the i-th element of the array a.
The next q lines describe queries. The i-th of these lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m), meaning that the i-th query is about the subsegment of the array from the l_i-th to the r_i-th positions, inclusive.
Output
Print a single string of length q, consisting of 0 and 1, the digit on the i-th positions should be 1, if the subsegment of array a from the l_i-th to the r_i-th positions, inclusive, contains a subsequence that is a cyclic shift of p, and 0 otherwise.
Examples
Input
3 6 3
2 1 3
1 2 3 1 2 3
1 5
2 6
3 5
Output
110
Input
2 4 3
2 1
1 1 2 2
1 2
2 3
3 4
Output
010
Note
In the first example the segment from the 1-st to the 5-th positions is 1, 2, 3, 1, 2. There is a subsequence 1, 3, 2 that is a cyclic shift of the permutation. The subsegment from the 2-nd to the 6-th positions also contains a subsequence 2, 1, 3 that is equal to the permutation. The subsegment from the 3-rd to the 5-th positions is 3, 1, 2, there is only one subsequence of length 3 (3, 1, 2), but it is not a cyclic shift of the permutation.
In the second example the possible cyclic shifts are 1, 2 and 2, 1. The subsegment from the 1-st to the 2-nd positions is 1, 1, its subsequences are not cyclic shifts of the permutation. The subsegment from the 2-nd to the 3-rd positions is 1, 2, it coincides with the permutation. The subsegment from the 3 to the 4 positions is 2, 2, its subsequences are not cyclic shifts of the permutation. | instruction | 0 | 10,864 | 12 | 21,728 |
Tags: data structures, dfs and similar, dp, math, trees
Correct Solution:
```
# 注意array cache順序 QQ
from math import log, floor
class RMQ:
'''
maximum version rmq
query: max([l, r])
'''
def __init__(self, nums):
size = floor(log(len(nums)) // log(2)) + 1
self.nums = [nums]
for i in range(1, size):
last = self.nums[-1]
delta = 1 << (i-1)
self.nums.append([max(last[j], last[j + delta])
for j in range(len(nums) - 2 * delta + 1)])
def query(self, l, r):
delta = floor(log(r - l + 1) // log(2))
return max(self.nums[delta][l], self.nums[delta][r-2**delta+1])
n, m, q = map(int, input().split())
perms = list(map(int, input().split()))
nums = list(map(int, input().split()))
logit = floor(log(n) // log(2)) + 1
current_max_index = [-1]*(n+1)
prevs = [[-1]*m for i in range(logit)]
prev_map = [-2]*(n+1)
for i, j in zip(perms[1:]+[perms[0]], perms):
prev_map[i] = j
# Update the one step case
for idx, ele in enumerate(nums):
prevs[0][idx] = current_max_index[prev_map[ele]]
current_max_index[ele] = idx
# Update the n_step table
for i in range(1, logit):
for idx, ele in enumerate(nums):
if prevs[i-1][idx] != -1:
prevs[i][idx] = prevs[i-1][prevs[i-1][idx]]
prev_n = []
# Create the update sequence
use = [i for i in range(n.bit_length()) if 1 & (n - 1) >> i]
max_pre = -1
ran = [-1] * (m+2)
for i in range(m):
t = i
for dim in use:
t = prevs[dim][t]
if t == -1:
break
max_pre = max(t, max_pre)
ran[i] = max_pre
"""
for i in range(m):
remain = n - 1
idx = i
while remain and idx != -1:
ma = floor(log(remain) // log(2))
idx = prevs[ma][idx]
remain -= 2**ma
prev_n.append(idx)
"""
#rmq = RMQ(prev_n)
ans = []
for i in range(q):
l, r = map(int, input().split())
if ran[r-1] >= l - 1:
ans.append("1")
else:
ans.append("0")
print("".join(ans))
``` | output | 1 | 10,864 | 12 | 21,729 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n.
Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the r-th positions, inclusive, have a subsequence that is a cyclic shift of p?" Please answer the queries.
A permutation of length n is a sequence of n integers such that each integer from 1 to n appears exactly once in it.
A cyclic shift of a permutation (p_1, p_2, …, p_n) is a permutation (p_i, p_{i + 1}, …, p_{n}, p_1, p_2, …, p_{i - 1}) for some i from 1 to n. For example, a permutation (2, 1, 3) has three distinct cyclic shifts: (2, 1, 3), (1, 3, 2), (3, 2, 1).
A subsequence of a subsegment of array a from the l-th to the r-th positions, inclusive, is a sequence a_{i_1}, a_{i_2}, …, a_{i_k} for some i_1, i_2, …, i_k such that l ≤ i_1 < i_2 < … < i_k ≤ r.
Input
The first line contains three integers n, m, q (1 ≤ n, m, q ≤ 2 ⋅ 10^5) — the length of the permutation p, the length of the array a and the number of queries.
The next line contains n integers from 1 to n, where the i-th of them is the i-th element of the permutation. Each integer from 1 to n appears exactly once.
The next line contains m integers from 1 to n, the i-th of them is the i-th element of the array a.
The next q lines describe queries. The i-th of these lines contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m), meaning that the i-th query is about the subsegment of the array from the l_i-th to the r_i-th positions, inclusive.
Output
Print a single string of length q, consisting of 0 and 1, the digit on the i-th positions should be 1, if the subsegment of array a from the l_i-th to the r_i-th positions, inclusive, contains a subsequence that is a cyclic shift of p, and 0 otherwise.
Examples
Input
3 6 3
2 1 3
1 2 3 1 2 3
1 5
2 6
3 5
Output
110
Input
2 4 3
2 1
1 1 2 2
1 2
2 3
3 4
Output
010
Note
In the first example the segment from the 1-st to the 5-th positions is 1, 2, 3, 1, 2. There is a subsequence 1, 3, 2 that is a cyclic shift of the permutation. The subsegment from the 2-nd to the 6-th positions also contains a subsequence 2, 1, 3 that is equal to the permutation. The subsegment from the 3-rd to the 5-th positions is 3, 1, 2, there is only one subsequence of length 3 (3, 1, 2), but it is not a cyclic shift of the permutation.
In the second example the possible cyclic shifts are 1, 2 and 2, 1. The subsegment from the 1-st to the 2-nd positions is 1, 1, its subsequences are not cyclic shifts of the permutation. The subsegment from the 2-nd to the 3-rd positions is 1, 2, it coincides with the permutation. The subsegment from the 3 to the 4 positions is 2, 2, its subsequences are not cyclic shifts of the permutation. | instruction | 0 | 10,865 | 12 | 21,730 |
Tags: data structures, dfs and similar, dp, math, trees
Correct Solution:
```
# 注意array cache順序 QQ
from math import log, floor
"""
class RMQ:
'''
maximum version rmq
query: max([l, r])
'''
def __init__(self, nums):
size = floor(log(len(nums)) // log(2)) + 1
self.nums = [nums]
for i in range(1, size):
last = self.nums[-1]
delta = 1 << (i-1)
self.nums.append([max(last[j], last[j + delta])
for j in range(len(nums) - 2 * delta + 1)])
def query(self, l, r):
delta = floor(log(r - l + 1) // log(2))
return max(self.nums[delta][l], self.nums[delta][r-2**delta+1])
"""
n, m, q = map(int, input().split())
perms = list(map(int, input().split()))
nums = list(map(int, input().split()))
logit = floor(log(n) // log(2)) + 1
current_max_index = [-1]*(n+1)
prevs = [[-1]*m for i in range(logit)]
prev_map = [-2]*(n+1)
for i, j in zip(perms[1:]+[perms[0]], perms):
prev_map[i] = j
# Update the one step case
for idx, ele in enumerate(nums):
prevs[0][idx] = current_max_index[prev_map[ele]]
current_max_index[ele] = idx
# Update the n_step table
for i in range(1, logit):
for idx, ele in enumerate(nums):
if prevs[i-1][idx] != -1:
prevs[i][idx] = prevs[i-1][prevs[i-1][idx]]
prev_n = []
# Create the update sequence
use = [i for i in range(n.bit_length()) if 1 & (n - 1) >> i]
max_pre = -1
ran = [-1] * (m+2)
for i in range(m):
t = i
for dim in use:
t = prevs[dim][t]
if t == -1:
break
max_pre = max(t, max_pre)
ran[i] = max_pre
"""
for i in range(m):
remain = n - 1
idx = i
while remain and idx != -1:
ma = floor(log(remain) // log(2))
idx = prevs[ma][idx]
remain -= 2**ma
prev_n.append(idx)
"""
#rmq = RMQ(prev_n)
ans = [None]*q
for i in range(q):
l, r = map(int, input().split())
ans[i] = str(int(l - 1 <= ran[r-1]))
print("".join(ans))
``` | output | 1 | 10,865 | 12 | 21,731 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct.
Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, k integers in total. Then he will insert the chosen numbers — one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.
Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?
Input
The first line contains a single integer k (1 ≤ k ≤ 15), the number of boxes.
The i-th of the next k lines first contains a single integer n_i (1 ≤ n_i ≤ 5 000), the number of integers in box i. Then the same line contains n_i integers a_{i,1}, …, a_{i,n_i} (|a_{i,j}| ≤ 10^9), the integers in the i-th box.
It is guaranteed that all a_{i,j} are distinct.
Output
If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output k lines. The i-th of these lines should contain two integers c_i and p_i. This means that Ujan should pick the integer c_i from the i-th box and place it in the p_i-th box afterwards.
If there are multiple solutions, output any of those.
You can print each letter in any case (upper or lower).
Examples
Input
4
3 1 7 4
2 3 2
2 8 5
1 10
Output
Yes
7 2
2 3
5 1
10 4
Input
2
2 3 -2
2 -1 5
Output
No
Input
2
2 -10 10
2 0 -20
Output
Yes
-10 2
-20 1
Note
In the first sample, Ujan can put the number 7 in the 2nd box, the number 2 in the 3rd box, the number 5 in the 1st box and keep the number 10 in the same 4th box. Then the boxes will contain numbers \{1,5,4\}, \{3, 7\}, \{8,2\} and \{10\}. The sum in each box then is equal to 10.
In the second sample, it is not possible to pick and redistribute the numbers in the required way.
In the third sample, one can swap the numbers -20 and -10, making the sum in each box equal to -10. | instruction | 0 | 10,875 | 12 | 21,750 |
Tags: bitmasks, dfs and similar, dp, graphs
Correct Solution:
```
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
k = int(input())
d = {}
aa = []
sa = []
for i in range(k):
ni, *a = map(int, input().split())
for ai in a:
d[ai] = i
aa.append(a)
sa.append(sum(a))
s = sum(sa)
if s%k != 0:
print("No")
exit()
s //= k
def calc_next(i, aij):
bij = s-sa[i]+aij
if bij not in d:
return -1, bij
else:
return d[bij], bij
def loop_to_num(loop):
ret = 0
for i in reversed(range(k)):
ret <<= 1
ret += loop[i]
return ret
loop_dict = {}
used = set()
for i in range(k):
for aij in aa[i]:
if aij in used:
continue
loop = [0]*k
num = [float("Inf")]*k
start_i = i
start_aij = aij
j = i
loop[j] = 1
num[j] = aij
used.add(aij)
exist = False
for _ in range(100):
j, aij = calc_next(j, aij)
if j == -1:
break
#used.add(aij)
if loop[j] == 0:
loop[j] = 1
num[j] = aij
else:
if j == start_i and aij == start_aij:
exist = True
break
if exist:
m = loop_to_num(loop)
loop_dict[m] = tuple(num)
for numi in num:
if numi != float("inf"):
used.add(numi)
mask = 1<<k
for state in range(1, mask):
if state in loop_dict:
continue
j = (state-1)&state
while j:
i = state^j
if i in loop_dict and j in loop_dict:
tp = tuple(min(loop_dict[i][l], loop_dict[j][l]) for l in range(k))
loop_dict[state] = tp
break
j = (j-1)&state
if mask-1 not in loop_dict:
print("No")
else:
print("Yes")
t = loop_dict[mask-1]
ns = [sa[i]-t[i] for i in range(k)]
need = [s - ns[i] for i in range(k)]
for i in range(k):
print(t[i], need.index(t[i])+1)
``` | output | 1 | 10,875 | 12 | 21,751 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct.
Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, k integers in total. Then he will insert the chosen numbers — one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.
Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?
Input
The first line contains a single integer k (1 ≤ k ≤ 15), the number of boxes.
The i-th of the next k lines first contains a single integer n_i (1 ≤ n_i ≤ 5 000), the number of integers in box i. Then the same line contains n_i integers a_{i,1}, …, a_{i,n_i} (|a_{i,j}| ≤ 10^9), the integers in the i-th box.
It is guaranteed that all a_{i,j} are distinct.
Output
If Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output k lines. The i-th of these lines should contain two integers c_i and p_i. This means that Ujan should pick the integer c_i from the i-th box and place it in the p_i-th box afterwards.
If there are multiple solutions, output any of those.
You can print each letter in any case (upper or lower).
Examples
Input
4
3 1 7 4
2 3 2
2 8 5
1 10
Output
Yes
7 2
2 3
5 1
10 4
Input
2
2 3 -2
2 -1 5
Output
No
Input
2
2 -10 10
2 0 -20
Output
Yes
-10 2
-20 1
Note
In the first sample, Ujan can put the number 7 in the 2nd box, the number 2 in the 3rd box, the number 5 in the 1st box and keep the number 10 in the same 4th box. Then the boxes will contain numbers \{1,5,4\}, \{3, 7\}, \{8,2\} and \{10\}. The sum in each box then is equal to 10.
In the second sample, it is not possible to pick and redistribute the numbers in the required way.
In the third sample, one can swap the numbers -20 and -10, making the sum in each box equal to -10.
Submitted Solution:
```
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
k = int(input())
d = {}
aa = []
sa = []
for i in range(k):
ni, *a = map(int, input().split())
for ai in a:
d[ai] = i
aa.append(a)
sa.append(sum(a))
s = sum(sa)
if s%k != 0:
print("No")
exit()
s //= k
def calc_next(i, aij):
bij = s-sa[i]+aij
if bij not in d:
return -1, bij
else:
return d[bij], bij
def loop_to_num(loop):
ret = 0
for i in reversed(range(k)):
ret <<= 1
ret += loop[i]
return ret
loop_dict = {}
used = set()
for i in range(k):
for aij in aa[i]:
if aij in used:
continue
loop = [0]*k
num = [float("Inf")]*k
start_i = i
start_aij = aij
j = i
loop[j] = 1
num[j] = aij
used.add(aij)
exist = False
for _ in range(100):
j, aij = calc_next(j, aij)
if j == -1:
break
used.add(aij)
if loop[j] == 0:
loop[j] = 1
num[j] = aij
else:
if j == start_i and aij == start_aij:
exist = True
break
if exist:
m = loop_to_num(loop)
loop_dict[m] = tuple(num)
mask = 1<<k
for state in range(1, mask):
if state in loop_dict:
continue
j = (state-1)&state
while j:
i = state^j
if i in loop_dict and j in loop_dict:
tp = tuple(min(loop_dict[i][l], loop_dict[j][l]) for l in range(k))
loop_dict[state] = tp
break
j = (j-1)&state
if mask-1 not in loop_dict:
print("No")
else:
print("Yes")
t = loop_dict[mask-1]
ns = [sa[i]-t[i] for i in range(k)]
need = [s - ns[i] for i in range(k)]
for i in range(k):
print(t[i], need.index(t[i])+1)
``` | instruction | 0 | 10,876 | 12 | 21,752 |
No | output | 1 | 10,876 | 12 | 21,753 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let A = {a1, a2, ..., an} be any permutation of the first n natural numbers {1, 2, ..., n}. You are given a positive integer k and another sequence B = {b1, b2, ..., bn}, where bi is the number of elements aj in A to the left of the element at = i such that aj ≥ (i + k).
For example, if n = 5, a possible A is {5, 1, 4, 2, 3}. For k = 2, B is given by {1, 2, 1, 0, 0}. But if k = 3, then B = {1, 1, 0, 0, 0}.
For two sequences X = {x1, x2, ..., xn} and Y = {y1, y2, ..., yn}, let i-th elements be the first elements such that xi ≠ yi. If xi < yi, then X is lexicographically smaller than Y, while if xi > yi, then X is lexicographically greater than Y.
Given n, k and B, you need to determine the lexicographically smallest A.
Input
The first line contains two space separated integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ n). On the second line are n integers specifying the values of B = {b1, b2, ..., bn}.
Output
Print on a single line n integers of A = {a1, a2, ..., an} such that A is lexicographically minimal. It is guaranteed that the solution exists.
Examples
Input
5 2
1 2 1 0 0
Output
4 1 5 2 3
Input
4 2
1 0 0 0
Output
2 3 1 4 | instruction | 0 | 11,239 | 12 | 22,478 |
Tags: greedy
Correct Solution:
```
s = input()
l = s.split()
n = int(l[0])
k = int(l[1])
s = input()
l = s.split()
b = [-1]
for i in range(1, n + 1):
b.append(int(l[i - 1]))
for i in range(1, n + 1):
j = 1
while b[j] != 0:
j += 1
b[j] -= 1
print(j, end = ' ')
for t in range(1, n + 1):
if j - k >= t:
b[t] -= 1
``` | output | 1 | 11,239 | 12 | 22,479 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let A = {a1, a2, ..., an} be any permutation of the first n natural numbers {1, 2, ..., n}. You are given a positive integer k and another sequence B = {b1, b2, ..., bn}, where bi is the number of elements aj in A to the left of the element at = i such that aj ≥ (i + k).
For example, if n = 5, a possible A is {5, 1, 4, 2, 3}. For k = 2, B is given by {1, 2, 1, 0, 0}. But if k = 3, then B = {1, 1, 0, 0, 0}.
For two sequences X = {x1, x2, ..., xn} and Y = {y1, y2, ..., yn}, let i-th elements be the first elements such that xi ≠ yi. If xi < yi, then X is lexicographically smaller than Y, while if xi > yi, then X is lexicographically greater than Y.
Given n, k and B, you need to determine the lexicographically smallest A.
Input
The first line contains two space separated integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ n). On the second line are n integers specifying the values of B = {b1, b2, ..., bn}.
Output
Print on a single line n integers of A = {a1, a2, ..., an} such that A is lexicographically minimal. It is guaranteed that the solution exists.
Examples
Input
5 2
1 2 1 0 0
Output
4 1 5 2 3
Input
4 2
1 0 0 0
Output
2 3 1 4 | instruction | 0 | 11,240 | 12 | 22,480 |
Tags: greedy
Correct Solution:
```
n, k = map(int, input().split())
b = list(map(int, input().split()))
taken = [False for i in range(n + 2)]
a = []
for i in range(n):
has = -1
for j in range(1, n + 1):
if not taken[j] and b[j - 1] == 0:
has = j
break
a.append(has)
taken[has] = True
for j in range(1, has - k + 1):
b[j - 1] -= 1
print(*a)
``` | output | 1 | 11,240 | 12 | 22,481 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let A = {a1, a2, ..., an} be any permutation of the first n natural numbers {1, 2, ..., n}. You are given a positive integer k and another sequence B = {b1, b2, ..., bn}, where bi is the number of elements aj in A to the left of the element at = i such that aj ≥ (i + k).
For example, if n = 5, a possible A is {5, 1, 4, 2, 3}. For k = 2, B is given by {1, 2, 1, 0, 0}. But if k = 3, then B = {1, 1, 0, 0, 0}.
For two sequences X = {x1, x2, ..., xn} and Y = {y1, y2, ..., yn}, let i-th elements be the first elements such that xi ≠ yi. If xi < yi, then X is lexicographically smaller than Y, while if xi > yi, then X is lexicographically greater than Y.
Given n, k and B, you need to determine the lexicographically smallest A.
Input
The first line contains two space separated integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ n). On the second line are n integers specifying the values of B = {b1, b2, ..., bn}.
Output
Print on a single line n integers of A = {a1, a2, ..., an} such that A is lexicographically minimal. It is guaranteed that the solution exists.
Examples
Input
5 2
1 2 1 0 0
Output
4 1 5 2 3
Input
4 2
1 0 0 0
Output
2 3 1 4 | instruction | 0 | 11,241 | 12 | 22,482 |
Tags: greedy
Correct Solution:
```
# ========= /\ /| |====/|
# | / \ | | / |
# | /____\ | | / |
# | / \ | | / |
# ========= / \ ===== |/====|
# code
def main():
n,k = map(int,input().split())
a = list(map(int,input().split()))
b = [0]*n
for i in range(n):
l = -1
for j in range(n):
if a[j] == 0:
l = j
b[i] = j + 1
a[j] -= 1
break
for j in range(n):
if l >= j + k:
a[j] -= 1
print(*b)
return
if __name__ == "__main__":
main()
``` | output | 1 | 11,241 | 12 | 22,483 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let A = {a1, a2, ..., an} be any permutation of the first n natural numbers {1, 2, ..., n}. You are given a positive integer k and another sequence B = {b1, b2, ..., bn}, where bi is the number of elements aj in A to the left of the element at = i such that aj ≥ (i + k).
For example, if n = 5, a possible A is {5, 1, 4, 2, 3}. For k = 2, B is given by {1, 2, 1, 0, 0}. But if k = 3, then B = {1, 1, 0, 0, 0}.
For two sequences X = {x1, x2, ..., xn} and Y = {y1, y2, ..., yn}, let i-th elements be the first elements such that xi ≠ yi. If xi < yi, then X is lexicographically smaller than Y, while if xi > yi, then X is lexicographically greater than Y.
Given n, k and B, you need to determine the lexicographically smallest A.
Input
The first line contains two space separated integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ n). On the second line are n integers specifying the values of B = {b1, b2, ..., bn}.
Output
Print on a single line n integers of A = {a1, a2, ..., an} such that A is lexicographically minimal. It is guaranteed that the solution exists.
Examples
Input
5 2
1 2 1 0 0
Output
4 1 5 2 3
Input
4 2
1 0 0 0
Output
2 3 1 4 | instruction | 0 | 11,242 | 12 | 22,484 |
Tags: greedy
Correct Solution:
```
# /*******************************************************************************
# * Author : Quantum Of Excellence
# * email : quantumofexcellence (at) gmail (dot) com
# * copyright : 2014 - 2015
# * date : 6 - 11 - 2015
# * Judge Status :
# * file name : 67B.py
# * version : 1.0
# *
# * TERMS OF USE - Write a mail to the author before copying or reusing the content of this file
# * seeking our permission for the same.
# * Copying/reuse of the below code without the permission of the author is prohibited and illegal.
# *
# * All rights reserved by Quantum Of Excellence.
# ******************************************************************************/
# /*******************************************************************************
# * some pointers on the logic/idea -
# *
# *
# *******************************************************************************/
# test cases-
#import sys
#fi = open("G:\DUMP\input.in","r")
#sys.stdin = fi
u=input
n,k=map(int,u().split())
M=[int(i) for i in u().split()]
m=0
for j in range(n):
# find unvisited zeros
for p in range(n):
if(0==M[p]):
print(p+1,end=' ')
break
for l in range(p+1-k):M[l]-=1
# make the visited zero negative
M[p]-=1
``` | output | 1 | 11,242 | 12 | 22,485 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given n integers a1, a2, ..., an. Find the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2 (i. e. some integer x exists so that ai + aj = 2x).
Input
The first line contains the single positive integer n (1 ≤ n ≤ 105) — the number of integers.
The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 109).
Output
Print the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2.
Examples
Input
4
7 3 2 1
Output
2
Input
3
1 1 1
Output
3
Note
In the first example the following pairs of indexes include in answer: (1, 4) and (2, 4).
In the second example all pairs of indexes (i, j) (where i < j) include in answer.
Submitted Solution:
```
import sys
#import random
from bisect import bisect_right as rb
from collections import deque
#sys.setrecursionlimit(10**8)
from queue import PriorityQueue
#from math import *
input_ = lambda: sys.stdin.readline().strip("\r\n")
ii = lambda : int(input_())
il = lambda : list(map(int, input_().split()))
ilf = lambda : list(map(float, input_().split()))
ip = lambda : input_()
fi = lambda : float(input_())
ap = lambda ab,bc,cd : ab[bc].append(cd)
li = lambda : list(input_())
pr = lambda x : print(x)
prinT = lambda x : print(x)
f = lambda : sys.stdout.flush()
inv =lambda x:pow(x,mod-2,mod)
mod = 10**9 + 7
for _ in range (1) :
n = ii()
a = il()
b = []
j = 1
for i in range (32) :
b.append(j)
j *= 2
d = {}
ans = 0
for i in range (n-1,-1,-1) :
x = a[i]
for i in range (32) :
y = b[i]-x
if (d.get(y)) :
ans += d[y]
d[x] = d.get(x,0) + 1
print(ans)
``` | instruction | 0 | 11,252 | 12 | 22,504 |
Yes | output | 1 | 11,252 | 12 | 22,505 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's assume that we have a pair of numbers (a, b). We can get a new pair (a + b, b) or (a, a + b) from the given pair in a single step.
Let the initial pair of numbers be (1,1). Your task is to find number k, that is, the least number of steps needed to transform (1,1) into the pair where at least one number equals n.
Input
The input contains the only integer n (1 ≤ n ≤ 106).
Output
Print the only integer k.
Examples
Input
5
Output
3
Input
1
Output
0
Note
The pair (1,1) can be transformed into a pair containing 5 in three moves: (1,1) → (1,2) → (3,2) → (5,2). | instruction | 0 | 11,769 | 12 | 23,538 |
Tags: brute force, dfs and similar, math, number theory
Correct Solution:
```
n,ans=int(input()),1000000
for i in range(1, n+1):
k,a,b=0,n,i
while b>1:
k+=a//b
a,b=b,a%b
if b!=0: ans=min(ans, a-1+k)
print(ans)
``` | output | 1 | 11,769 | 12 | 23,539 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let's assume that we have a pair of numbers (a, b). We can get a new pair (a + b, b) or (a, a + b) from the given pair in a single step.
Let the initial pair of numbers be (1,1). Your task is to find number k, that is, the least number of steps needed to transform (1,1) into the pair where at least one number equals n.
Input
The input contains the only integer n (1 ≤ n ≤ 106).
Output
Print the only integer k.
Examples
Input
5
Output
3
Input
1
Output
0
Note
The pair (1,1) can be transformed into a pair containing 5 in three moves: (1,1) → (1,2) → (3,2) → (5,2). | instruction | 0 | 11,770 | 12 | 23,540 |
Tags: brute force, dfs and similar, math, number theory
Correct Solution:
```
import sys
def solve():
n = int(input())
if n == 1: return 0
res = 1000000
for other in range(n - 1, 0, -1):
pair = [n, other]
temp = 0
while (pair[0] > 1 or pair[1] > 1) and (pair[0] > 0 and pair[1] > 0):
pair.sort()
multiples = (pair[1] - 1) // pair[0]
if multiples == 0: break
pair[1] -= pair[0] * multiples
temp+=multiples
if temp > res: break
if pair[0] == 1 and pair[1] == 1: res = min(res, temp)
return res
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
print(solve())
``` | output | 1 | 11,770 | 12 | 23,541 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ashish has an array a of consisting of 2n positive integers. He wants to compress a into an array b of size n-1. To do this, he first discards exactly 2 (any two) elements from a. He then performs the following operation until there are no elements left in a:
* Remove any two elements from a and append their sum to b.
The compressed array b has to have a special property. The greatest common divisor (gcd) of all its elements should be greater than 1.
Recall that the gcd of an array of positive integers is the biggest integer that is a divisor of all integers in the array.
It can be proven that it is always possible to compress array a into an array b of size n-1 such that gcd(b_1, b_2..., b_{n-1}) > 1.
Help Ashish find a way to do so.
Input
The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (2 ≤ n ≤ 1000).
The second line of each test case contains 2n integers a_1, a_2, …, a_{2n} (1 ≤ a_i ≤ 1000) — the elements of the array a.
Output
For each test case, output n-1 lines — the operations performed to compress the array a to the array b. The initial discard of the two elements is not an operation, you don't need to output anything about it.
The i-th line should contain two integers, the indices (1 —based) of the two elements from the array a that are used in the i-th operation. All 2n-2 indices should be distinct integers from 1 to 2n.
You don't need to output two initially discarded elements from a.
If there are multiple answers, you can find any.
Example
Input
3
3
1 2 3 4 5 6
2
5 7 9 10
5
1 3 3 4 5 90 100 101 2 3
Output
3 6
4 5
3 4
1 9
2 3
4 5
6 10
Note
In the first test case, b = \{3+6, 4+5\} = \{9, 9\} and gcd(9, 9) = 9.
In the second test case, b = \{9+10\} = \{19\} and gcd(19) = 19.
In the third test case, b = \{1+2, 3+3, 4+5, 90+3\} = \{3, 6, 9, 93\} and gcd(3, 6, 9, 93) = 3. | instruction | 0 | 11,780 | 12 | 23,560 |
Tags: constructive algorithms, math, number theory
Correct Solution:
```
import math
t = int(input())
for _ in range(t):
n = int(input())
a = [int(i) for i in input().split()]
o = []
e = []
for i in range(2*n):
if a[i]%2 == 0:
e.append(i+1)
else:
o.append(i+1)
ans = []
while len(ans) < n-1:
if len(o) > 1:
ans.append([o.pop(), o.pop()])
else:
ans.append([e.pop(), e.pop()])
for i in ans:
print(i[0], i[1])
``` | output | 1 | 11,780 | 12 | 23,561 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ashish has an array a of consisting of 2n positive integers. He wants to compress a into an array b of size n-1. To do this, he first discards exactly 2 (any two) elements from a. He then performs the following operation until there are no elements left in a:
* Remove any two elements from a and append their sum to b.
The compressed array b has to have a special property. The greatest common divisor (gcd) of all its elements should be greater than 1.
Recall that the gcd of an array of positive integers is the biggest integer that is a divisor of all integers in the array.
It can be proven that it is always possible to compress array a into an array b of size n-1 such that gcd(b_1, b_2..., b_{n-1}) > 1.
Help Ashish find a way to do so.
Input
The first line contains a single integer t (1 ≤ t ≤ 10) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer n (2 ≤ n ≤ 1000).
The second line of each test case contains 2n integers a_1, a_2, …, a_{2n} (1 ≤ a_i ≤ 1000) — the elements of the array a.
Output
For each test case, output n-1 lines — the operations performed to compress the array a to the array b. The initial discard of the two elements is not an operation, you don't need to output anything about it.
The i-th line should contain two integers, the indices (1 —based) of the two elements from the array a that are used in the i-th operation. All 2n-2 indices should be distinct integers from 1 to 2n.
You don't need to output two initially discarded elements from a.
If there are multiple answers, you can find any.
Example
Input
3
3
1 2 3 4 5 6
2
5 7 9 10
5
1 3 3 4 5 90 100 101 2 3
Output
3 6
4 5
3 4
1 9
2 3
4 5
6 10
Note
In the first test case, b = \{3+6, 4+5\} = \{9, 9\} and gcd(9, 9) = 9.
In the second test case, b = \{9+10\} = \{19\} and gcd(19) = 19.
In the third test case, b = \{1+2, 3+3, 4+5, 90+3\} = \{3, 6, 9, 93\} and gcd(3, 6, 9, 93) = 3. | instruction | 0 | 11,781 | 12 | 23,562 |
Tags: constructive algorithms, math, number theory
Correct Solution:
```
for i in range(int(input())):
n=int(input())
l=[int(num) for num in input().split()]
o,e=[],[]
b=0
for num in range(len(l)):
if(l[num]%2==0):
e.append(num+1)
else:
o.append(num+1)
while(b<n-1):
if(len(e)>1):
print(e.pop(),e.pop())
b=b+1
if(len(o)>1 and b<n-1):
print(o.pop(),o.pop())
b=b+1
``` | output | 1 | 11,781 | 12 | 23,563 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.