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 a correct Python 3 solution for this coding contest problem.
We will define the median of a sequence b of length M, as follows:
* Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down.
For example, the median of (10, 30, 20) is 20; the median of (10, 30, 20, 40) is 30; the median of (10, 10, 10, 20, 30) is 10.
Snuke comes up with the following problem.
You are given a sequence a of length N. For each pair (l, r) (1 \leq l \leq r \leq N), let m_{l, r} be the median of the contiguous subsequence (a_l, a_{l + 1}, ..., a_r) of a. We will list m_{l, r} for all pairs (l, r) to create a new sequence m. Find the median of m.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the median of m.
Examples
Input
3
10 30 20
Output
30
Input
1
10
Output
10
Input
10
5 9 5 9 8 9 3 5 4 3
Output
8 | instruction | 0 | 80,673 | 12 | 161,346 |
"Correct Solution:
```
import sys
stdin = sys.stdin
sys.setrecursionlimit(10**5)
def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())
from itertools import accumulate
# 転倒数を求めるためのBIT
class BIT(object):
def __init__(self, size):
self.size = size+1
self.bitree = [0]*self.size
def addval(self, idx:int, val:int):
while idx < self.size:
self.bitree[idx] += val
idx += idx&(-idx)
def getsum(self, idx:int):
ret = 0
while idx > 0:
ret += self.bitree[idx]
idx -= idx&(-idx)
return ret
def reset(self):
self.bitree = [0]*self.size
# 二分探索のための関数
def findInv(arr:list, med:int):
arrbin = [-1 if ai < med else 1 for ai in arr]
arrcum = [0] + list(accumulate(arrbin))
arrcummin = abs(min(arrcum))
arrcumpos = [arrcum_i + arrcummin + 1 for arrcum_i in arrcum]
bitree = BIT(max(arrcumpos))
inv = 0
for i,ai in enumerate(arrcumpos):
inv += (i - bitree.getsum(ai))
bitree.addval(ai, 1)
return inv
# 二分探索
def binsearch(arr:list):
low = 0
high = max(arr) + 1
n = len(arr)
threshould = n*(n+1)//4
while high-low > 1:
mid = (high+low) // 2
if findInv(arr, mid) <= threshould:
low = mid
else:
high = mid
return low
n = ni()
a = list(li())
print(binsearch(a))
``` | output | 1 | 80,673 | 12 | 161,347 |
Provide a correct Python 3 solution for this coding contest problem.
We will define the median of a sequence b of length M, as follows:
* Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down.
For example, the median of (10, 30, 20) is 20; the median of (10, 30, 20, 40) is 30; the median of (10, 10, 10, 20, 30) is 10.
Snuke comes up with the following problem.
You are given a sequence a of length N. For each pair (l, r) (1 \leq l \leq r \leq N), let m_{l, r} be the median of the contiguous subsequence (a_l, a_{l + 1}, ..., a_r) of a. We will list m_{l, r} for all pairs (l, r) to create a new sequence m. Find the median of m.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the median of m.
Examples
Input
3
10 30 20
Output
30
Input
1
10
Output
10
Input
10
5 9 5 9 8 9 3 5 4 3
Output
8 | instruction | 0 | 80,674 | 12 | 161,348 |
"Correct Solution:
```
#!/usr/bin/env python3
import sys
try:
from typing import List
except ImportError:
pass
class BIT:
def __init__(self, n: int):
self.tr = [0] * (n + 1)
def add(self, n: int, v: int):
while n < len(self.tr):
self.tr[n] += v
n += n & -n
def cumsum(self, n: int):
ans = 0
while n > 0:
ans += self.tr[n]
n -= n & -n
return ans
def solve(N: int, a: "List[int]"):
def f(m):
s = [0] * (N + 1)
for i, ai in enumerate(a):
s[i + 1] = s[i] + (-1 if ai < m else 1)
ms = min(s)
b = BIT(max(s) - ms + 1)
t = 0
for si in s:
t += b.cumsum(si - ms + 1)
b.add(si - ms + 1, 1)
return t >= -(-(N * (N + 1) // 2) // 2)
lb = 0
rb = max(a) + 1
while lb + 1 < rb:
m = (lb + rb) // 2
if f(m):
lb = m
else:
rb = m
print(lb)
def main():
def iterate_tokens():
for line in sys.stdin:
for word in line.split():
yield word
tokens = iterate_tokens()
N = int(next(tokens)) # type: int
a = [int(next(tokens)) for _ in range(N)] # type: "List[int]"
solve(N, a)
if __name__ == '__main__':
main()
``` | output | 1 | 80,674 | 12 | 161,349 |
Provide a correct Python 3 solution for this coding contest problem.
We will define the median of a sequence b of length M, as follows:
* Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down.
For example, the median of (10, 30, 20) is 20; the median of (10, 30, 20, 40) is 30; the median of (10, 10, 10, 20, 30) is 10.
Snuke comes up with the following problem.
You are given a sequence a of length N. For each pair (l, r) (1 \leq l \leq r \leq N), let m_{l, r} be the median of the contiguous subsequence (a_l, a_{l + 1}, ..., a_r) of a. We will list m_{l, r} for all pairs (l, r) to create a new sequence m. Find the median of m.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the median of m.
Examples
Input
3
10 30 20
Output
30
Input
1
10
Output
10
Input
10
5 9 5 9 8 9 3 5 4 3
Output
8 | instruction | 0 | 80,675 | 12 | 161,350 |
"Correct Solution:
```
n = int(input())
A = list(map(int, input().split()))
# n = 4
# A = [i+1 for i in range(n)]
class Bit:
def __init__(self, n):
self.size = n
self.tree = [0] * (n + 1)
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
#print((n*(n+1))//(2*2))
le = -1
ri = max(A) + 1
mid = (le + ri) // 2
while ri - le > 1:
S = [0] * n
S[0] = -1 + 2 * int(A[0] >= mid)
for i in range(n-1):
S[i+1] = S[i] - 1 + 2 * int(A[i+1] >= mid)
bit = Bit(n+2)
ans = 0
for i in range(n):
if S[i] >= 0:
ans += 1
#print("S OK")
Smin = min(S)
S = [S[i] - Smin + 1 for i in range(n)]
#print("S OK2")
#print(S)
for i, p in enumerate(S):
bit.add(p, 1)
ans += bit.sum(p) - 1 # 「S[i] >= S[i]」をカウントしないように1を引く
#print(i,ans)
#print(le, ri, mid, ans)
if ans >= (n*(n+1))//(2*2):
le = mid
else:
ri = mid
mid = (le + ri) // 2
print(le)
``` | output | 1 | 80,675 | 12 | 161,351 |
Provide a correct Python 3 solution for this coding contest problem.
We will define the median of a sequence b of length M, as follows:
* Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down.
For example, the median of (10, 30, 20) is 20; the median of (10, 30, 20, 40) is 30; the median of (10, 10, 10, 20, 30) is 10.
Snuke comes up with the following problem.
You are given a sequence a of length N. For each pair (l, r) (1 \leq l \leq r \leq N), let m_{l, r} be the median of the contiguous subsequence (a_l, a_{l + 1}, ..., a_r) of a. We will list m_{l, r} for all pairs (l, r) to create a new sequence m. Find the median of m.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the median of m.
Examples
Input
3
10 30 20
Output
30
Input
1
10
Output
10
Input
10
5 9 5 9 8 9 3 5 4 3
Output
8 | instruction | 0 | 80,676 | 12 | 161,352 |
"Correct Solution:
```
def main():
from itertools import accumulate as ac
n = int(input())
a = list(map(int, input().split()))
class BIT():
def __init__(self, n):
self.n = n
self.bit = [0]*(n+1)
# 位置iに値vを足す
def add(self, i, v):
x = i+1
while x < self.n + 1:
self.bit[x] += v
x += x & (-x)
# 位置0からiまでの和(sum(bit[:i]))を計算する
def sum(self, i):
ret = 0
x = i
while x > 0:
ret += self.bit[x]
x -= x & (-x)
return ret
# 位置iからjまでの和(sum(bit[i:j]))を計算する
def sum_range(self, i, j):
return self.sum(j) - self.sum(i)
def value(v):
if n == 1:
if v <= a[0]:
return True
else:
return False
b = [0]+list(ac([(i >= v)*2-1 for i in a]))
bit = BIT(2*n+1)
ans = 0
bit.add(b[-1]+n, 1)
for i in range(n-1, -1, -1):
w = b[i]
ans += bit.sum_range(w+n, 2*n+1)
bit.add(w+n, 1)
if ans >= (n*(n+1)//2)//2:
return True
else:
return False
def b_search(ok, ng, value):
while abs(ok-ng) > 1:
mid = (ok+ng)//2
if value(mid):
ok = mid
else:
ng = mid
return ok
print(b_search(0, 10**9+1, value))
main()
``` | output | 1 | 80,676 | 12 | 161,353 |
Provide a correct Python 3 solution for this coding contest problem.
We will define the median of a sequence b of length M, as follows:
* Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down.
For example, the median of (10, 30, 20) is 20; the median of (10, 30, 20, 40) is 30; the median of (10, 10, 10, 20, 30) is 10.
Snuke comes up with the following problem.
You are given a sequence a of length N. For each pair (l, r) (1 \leq l \leq r \leq N), let m_{l, r} be the median of the contiguous subsequence (a_l, a_{l + 1}, ..., a_r) of a. We will list m_{l, r} for all pairs (l, r) to create a new sequence m. Find the median of m.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the median of m.
Examples
Input
3
10 30 20
Output
30
Input
1
10
Output
10
Input
10
5 9 5 9 8 9 3 5 4 3
Output
8 | instruction | 0 | 80,677 | 12 | 161,354 |
"Correct Solution:
```
n=int(input())
a=list(map(int,input().split()))
a2=sorted(set(a))
L=len(a2)
if n==1:print(a[0]);exit()
elif n==2:print(a[1]);exit()
ng=L
ok=0
while ng-ok>1:
check=a2[(ok+ng)//2]
cnt=0 #check以上の要素の数
idx=n
cl=[0]*(2*n+1)
cl[n]=1
Ru=0
for i in range(n):
if a[i]<check:
Ru-=cl[idx]-1
idx-=1
else:
idx+=1
Ru+=cl[idx]+1
cnt += Ru
cl[idx]+=1
if cnt >= ((n+1)*n//2)//2:
ok = (ok+ng)//2
else:
ng = (ok+ng)//2
print(a2[ok])
``` | output | 1 | 80,677 | 12 | 161,355 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We will define the median of a sequence b of length M, as follows:
* Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down.
For example, the median of (10, 30, 20) is 20; the median of (10, 30, 20, 40) is 30; the median of (10, 10, 10, 20, 30) is 10.
Snuke comes up with the following problem.
You are given a sequence a of length N. For each pair (l, r) (1 \leq l \leq r \leq N), let m_{l, r} be the median of the contiguous subsequence (a_l, a_{l + 1}, ..., a_r) of a. We will list m_{l, r} for all pairs (l, r) to create a new sequence m. Find the median of m.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the median of m.
Examples
Input
3
10 30 20
Output
30
Input
1
10
Output
10
Input
10
5 9 5 9 8 9 3 5 4 3
Output
8
Submitted Solution:
```
import sys
def bit_add(iii,x):
while iii<len(bit):
bit[iii]+=x
iii+=iii&(-iii)
def bit_sum(jjj):
s=0
while jjj>0:
s+=bit[jjj]
jjj-=jjj&(-jjj)
return s
n=int(input())
a=list(map(int,input().split()))
num=n*(n+1)//2
high=max(a)
low=min(a)
while high-low>1:
mid=(high+low)//2
ans=0
b=[]
for i in range(n):
if a[i]>=mid:
b.append(1)
else:
b.append(-1)
for i in range(1,n):
b[i]+=b[i-1]
for i in range(n):
b[i]+=n
bit=[0]*(2*n+3)
bit_add(n,1)
for i in range(n):
ans+=bit_sum(b[i])
bit_add(b[i],1)
if num%2==1:
if ans>=num//2+1:
low=mid
else:
high=mid
else:
if ans>=num//2:
low=mid
else:
high=mid
if not high in a:
print(low)
sys.exit()
else:
mid=high
ans=0
b=[]
for i in range(n):
if a[i]>=mid:
b.append(1)
else:
b.append(-1)
for i in range(1,n):
b[i]+=b[i-1]
for i in range(n):
b[i]+=n
bit=[0]*(2*n+3)
bit_add(n,1)
for i in range(n):
ans+=bit_sum(b[i])
bit_add(b[i],1)
if num%2==1:
if ans>=num//2+1:
print(high)
else:
print(low)
else:
if ans>=num//2:
print(high)
else:
print(low)
``` | instruction | 0 | 80,678 | 12 | 161,356 |
Yes | output | 1 | 80,678 | 12 | 161,357 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We will define the median of a sequence b of length M, as follows:
* Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down.
For example, the median of (10, 30, 20) is 20; the median of (10, 30, 20, 40) is 30; the median of (10, 10, 10, 20, 30) is 10.
Snuke comes up with the following problem.
You are given a sequence a of length N. For each pair (l, r) (1 \leq l \leq r \leq N), let m_{l, r} be the median of the contiguous subsequence (a_l, a_{l + 1}, ..., a_r) of a. We will list m_{l, r} for all pairs (l, r) to create a new sequence m. Find the median of m.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the median of m.
Examples
Input
3
10 30 20
Output
30
Input
1
10
Output
10
Input
10
5 9 5 9 8 9 3 5 4 3
Output
8
Submitted Solution:
```
N = int(input())
a_list = list(map(int, input().split()))
def search(c):
bar = N
r = 0
res_nega = 0
dp_arr = [0]*(2*N+1)
for i in range(N):
dp_arr[bar] += 1
if a_list[i] < c:
r += dp_arr[bar]
bar += 1
else:
r -= (dp_arr[bar-1])
bar -= 1
res_nega += r
return res_nega
# binary search
a_sorted = sorted(a_list)
left = 0
right = N
mid = N // 2
C = N*(N+1) // 2
while True:
if search(a_sorted[mid]) <= C // 2:
if mid == N-1:
break
elif search(a_sorted[mid+1]) > C // 2:
break
else:
left = mid
mid = (mid + right) // 2
else:
right = mid + 1
mid = (mid + left) // 2
print(a_sorted[mid])
``` | instruction | 0 | 80,679 | 12 | 161,358 |
Yes | output | 1 | 80,679 | 12 | 161,359 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We will define the median of a sequence b of length M, as follows:
* Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down.
For example, the median of (10, 30, 20) is 20; the median of (10, 30, 20, 40) is 30; the median of (10, 10, 10, 20, 30) is 10.
Snuke comes up with the following problem.
You are given a sequence a of length N. For each pair (l, r) (1 \leq l \leq r \leq N), let m_{l, r} be the median of the contiguous subsequence (a_l, a_{l + 1}, ..., a_r) of a. We will list m_{l, r} for all pairs (l, r) to create a new sequence m. Find the median of m.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the median of m.
Examples
Input
3
10 30 20
Output
30
Input
1
10
Output
10
Input
10
5 9 5 9 8 9 3 5 4 3
Output
8
Submitted Solution:
```
N = int(input())
A = [int(x) for x in input().split()]
total_medians = N*(N+1)//2
# n件のデータ
# (上側中央値 >= x) iff (a > x となる a が(n-1)//2以下)
def BIT_update(BIT,x,value):
# 番号xにvalueを加える
L = len(BIT)
while x < L:
BIT[x] += value
bottom_bit = x & (-x)
x += bottom_bit
return
def BIT_sum(BIT,x):
# 番号1~xの和を求める
result = 0
while x:
result += BIT[x]
bottom_bit = x & (-x)
x -= bottom_bit
return result
def test(x):
# 「答はx以下である」
# 「xより真に大きな区間中央値が(total_medians-1)//2個以下」
B = [0]
for a in A:
B.append(B[-1] + (1 if a>x else -1))
m = min(B)-1
B = [x-m for x in B]
BIT = [0]*(N+1)
cnt = 0
for R in range(1,N+1):
BIT_update(BIT,B[R-1],1)
cnt += BIT_sum(BIT,B[R]) # 右端がRとなる(L,R)対
return cnt <= (total_medians-1)//2
AA = sorted(A)
left = -1 # 答はAA[left]より大きい
right = len(AA)-1 # 答はAA[right]以下である
while right - left > 1:
mid = (left+right)//2
if test(AA[mid]):
right = mid
else:
left = mid
answer = AA[right]
print(answer)
``` | instruction | 0 | 80,680 | 12 | 161,360 |
Yes | output | 1 | 80,680 | 12 | 161,361 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We will define the median of a sequence b of length M, as follows:
* Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down.
For example, the median of (10, 30, 20) is 20; the median of (10, 30, 20, 40) is 30; the median of (10, 10, 10, 20, 30) is 10.
Snuke comes up with the following problem.
You are given a sequence a of length N. For each pair (l, r) (1 \leq l \leq r \leq N), let m_{l, r} be the median of the contiguous subsequence (a_l, a_{l + 1}, ..., a_r) of a. We will list m_{l, r} for all pairs (l, r) to create a new sequence m. Find the median of m.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the median of m.
Examples
Input
3
10 30 20
Output
30
Input
1
10
Output
10
Input
10
5 9 5 9 8 9 3 5 4 3
Output
8
Submitted Solution:
```
from itertools import accumulate
from math import ceil
N = int(input())
A = list(map(int, input().split()))
class BinaryIndexedTree:
def __init__(self, n):
self.size = n
self.bit = [0] * (n + 1)
def sum(self, i):
s = 0
while i > 0:
s += self.bit[i]
i -= (i & -i)
return s
def add(self, i, x):
while i <= self.size:
self.bit[i] += x
i += (i & -i)
def reset(self):
self.bit = [0] * (self.size + 1)
lo, hi = -1, 10 ** 9 + 1
BIT = BinaryIndexedTree(N + 1)
while hi - lo > 1:
X = (hi + lo) // 2
B = [(1 if a >= X else -1) for a in A]
B = [0] + list(accumulate(B))
B_sorted = {b: i for i, b in enumerate(sorted(B), start=1)}
tmp = 0
BIT.reset()
for j, b in enumerate(B):
tmp += BIT.sum(B_sorted[b])
BIT.add(B_sorted[b], 1)
if tmp >= ceil((N * (N + 1) / 2) / 2):
lo = X
else:
hi = X
print(lo)
``` | instruction | 0 | 80,681 | 12 | 161,362 |
Yes | output | 1 | 80,681 | 12 | 161,363 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We will define the median of a sequence b of length M, as follows:
* Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down.
For example, the median of (10, 30, 20) is 20; the median of (10, 30, 20, 40) is 30; the median of (10, 10, 10, 20, 30) is 10.
Snuke comes up with the following problem.
You are given a sequence a of length N. For each pair (l, r) (1 \leq l \leq r \leq N), let m_{l, r} be the median of the contiguous subsequence (a_l, a_{l + 1}, ..., a_r) of a. We will list m_{l, r} for all pairs (l, r) to create a new sequence m. Find the median of m.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the median of m.
Examples
Input
3
10 30 20
Output
30
Input
1
10
Output
10
Input
10
5 9 5 9 8 9 3 5 4 3
Output
8
Submitted Solution:
```
N=int(input())
A=list(map(int,input().split()))
def f(A):
A.sort()
return A[len(A)//2]
ml=[]
for l in range(N):
for r in range(l,N):
ml.append(f(A[l:r+1]))
print(f(ml))
``` | instruction | 0 | 80,682 | 12 | 161,364 |
No | output | 1 | 80,682 | 12 | 161,365 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We will define the median of a sequence b of length M, as follows:
* Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down.
For example, the median of (10, 30, 20) is 20; the median of (10, 30, 20, 40) is 30; the median of (10, 10, 10, 20, 30) is 10.
Snuke comes up with the following problem.
You are given a sequence a of length N. For each pair (l, r) (1 \leq l \leq r \leq N), let m_{l, r} be the median of the contiguous subsequence (a_l, a_{l + 1}, ..., a_r) of a. We will list m_{l, r} for all pairs (l, r) to create a new sequence m. Find the median of m.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the median of m.
Examples
Input
3
10 30 20
Output
30
Input
1
10
Output
10
Input
10
5 9 5 9 8 9 3 5 4 3
Output
8
Submitted Solution:
```
import itertools
from statistics import median as md
n=int(input())
lst=list(map(int,input().split()))
ans=[].append(lst)
for c in list(itertools.combinations(range(len(lst)),2)):
ans.append(md(lst[c[0]:c[1]]))
print(sorted(md(ans)))
``` | instruction | 0 | 80,683 | 12 | 161,366 |
No | output | 1 | 80,683 | 12 | 161,367 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We will define the median of a sequence b of length M, as follows:
* Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down.
For example, the median of (10, 30, 20) is 20; the median of (10, 30, 20, 40) is 30; the median of (10, 10, 10, 20, 30) is 10.
Snuke comes up with the following problem.
You are given a sequence a of length N. For each pair (l, r) (1 \leq l \leq r \leq N), let m_{l, r} be the median of the contiguous subsequence (a_l, a_{l + 1}, ..., a_r) of a. We will list m_{l, r} for all pairs (l, r) to create a new sequence m. Find the median of m.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the median of m.
Examples
Input
3
10 30 20
Output
30
Input
1
10
Output
10
Input
10
5 9 5 9 8 9 3 5 4 3
Output
8
Submitted Solution:
```
'''
☆長さnの数列Aの中央値がxであるとは
1.x以上の要素が (n + 1)// 2 個以上
2.そのようなxの中で最小
ということ。
'''
class BIT:
def __init__(self, n):
self.bit = [0] * (n+1)
def sum(self, i):
'''
:param i:
:return: bit[i]までの和
'''
s = 0
while i > 0:
s += self.bit[i]
i -= i & -i
return s
def add(self, i, x):
'''
:param i:
:param x:
:return: bit[i]にxを加える
'''
while i < len(self.bit):
self.bit[i] += x
i += i & -i
import numpy as np
def median(L):
n = len(L)
L.sort()
return L[n // 2]
N = int(input())
a = list(map(int, input().split()))
def ans_bigger(X):
'''
答えがX以上かどうかを判定
つまり、区間[l. r]のうち中央値がX以上であるものが ((N+1) * N /2 + 1 ) //2 個以上かを判定
[l, r]の中央値がX以上 =
'''
a_X = np.array([1 if a[i] >= X else -1 for i in range(N)]) #1, -1に変換
cum = np.hstack(([0], np.cumsum(a_X))) #累積和を取る
min_cum = min(cum)
cum -= min_cum - 1 #BITを使うために全部0以上に
b = BIT(max(cum) + 1)
ans = 0
for j in range(N + 1):
ans += b.sum(cum[j])
b.add(cum[j], 1)
if ans >= ((N+1) * N /2 + 1 ) //2:
return True
else:
return False
l = min(a)
r = max(a) + 1
#区間[l, r)を2分探索
while r > l + 1:
if ans_bigger((l + r) // 2):
l = (l + r) // 2
else:
r = (l + r) // 2
print(l)
``` | instruction | 0 | 80,684 | 12 | 161,368 |
No | output | 1 | 80,684 | 12 | 161,369 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We will define the median of a sequence b of length M, as follows:
* Let b' be the sequence obtained by sorting b in non-decreasing order. Then, the value of the (M / 2 + 1)-th element of b' is the median of b. Here, / is integer division, rounding down.
For example, the median of (10, 30, 20) is 20; the median of (10, 30, 20, 40) is 30; the median of (10, 10, 10, 20, 30) is 10.
Snuke comes up with the following problem.
You are given a sequence a of length N. For each pair (l, r) (1 \leq l \leq r \leq N), let m_{l, r} be the median of the contiguous subsequence (a_l, a_{l + 1}, ..., a_r) of a. We will list m_{l, r} for all pairs (l, r) to create a new sequence m. Find the median of m.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the median of m.
Examples
Input
3
10 30 20
Output
30
Input
1
10
Output
10
Input
10
5 9 5 9 8 9 3 5 4 3
Output
8
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
class Bit:
def __init__(self, n):
self.size = n
self.tree = [0] * (n + 1)
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 f(x): # 連続部分列の中央値がxなる場合の数
s = Bit(2)
S = Bit(2 * n + 1)
judge = 0
for p in a:
s.add((p >= x) + 1, 1)
b = n + s.tree[2] - 2 * s.tree[1]
S.add(b,1)
judge += S.sum(b)
if judge >= n_sub_half:
return 1
return 0
b = sorted(set(a))
l, r = 0, len(b)
n_sub_half = (n * (n + 1) // 2) // 2
while True:
m = (r + l) // 2
if f(b[m]): # ans >= x
if m == len(b) - 1:
break
elif not f(b[m + 1]):
break
else:
l = m + 1
else: # ans < x
if f(b[m - 1]):
m = m - 1
break
else:
r = m - 2
print(b[m])
``` | instruction | 0 | 80,685 | 12 | 161,370 |
No | output | 1 | 80,685 | 12 | 161,371 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We call two numbers x and y similar if they have the same parity (the same remainder when divided by 2), or if |x-y|=1. For example, in each of the pairs (2, 6), (4, 3), (11, 7), the numbers are similar to each other, and in the pairs (1, 4), (3, 12), they are not.
You are given an array a of n (n is even) positive integers. Check if there is such a partition of the array into pairs that each element of the array belongs to exactly one pair and the numbers in each pair are similar to each other.
For example, for the array a = [11, 14, 16, 12], there is a partition into pairs (11, 12) and (14, 16). The numbers in the first pair are similar because they differ by one, and in the second pair because they are both even.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow.
Each test case consists of two lines.
The first line contains an even positive integer n (2 ≤ n ≤ 50) — length of array a.
The second line contains n positive integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100).
Output
For each test case print:
* YES if the such a partition exists,
* NO otherwise.
The letters in the words YES and NO can be displayed in any case.
Example
Input
7
4
11 14 16 12
2
1 8
4
1 1 1 1
4
1 2 5 6
2
12 13
6
1 6 3 10 5 8
6
1 12 3 10 5 8
Output
YES
NO
YES
YES
YES
YES
NO
Note
The first test case was explained in the statement.
In the second test case, the two given numbers are not similar.
In the third test case, any partition is suitable.
Submitted Solution:
```
from collections import Counter,defaultdict,deque
#from heapq import *
#import itertools
#from operator import itemgetter
#from itertools import count, islice
#from functools import reduce
#alph = 'abcdefghijklmnopqrstuvwxyz'
#dirs = [[1,0],[0,1],[-1,0],[0,-1]]
#from math import factorial as fact
#a,b = [int(x) for x in input().split()]
#sarr = [x for x in input().strip().split()]
#import math
from math import *
import sys
input=sys.stdin.readline
#sys.setrecursionlimit(2**30)
def solve():
n = int(input())
arr = [int(x) for x in input().split()]
arr.sort()
d = 0
odd = 0
for i in range(n-1):
if arr[i]&1:
odd+=1
if arr[i+1]-arr[i]==1:
d = 1
if arr[-1]&1:
odd+=1
if odd&1:
if d:
print('YES')
else:
print('NO')
else:
print('YES')
tt = int(input())
for test in range(tt):
solve()
#
``` | instruction | 0 | 80,989 | 12 | 161,978 |
Yes | output | 1 | 80,989 | 12 | 161,979 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We call two numbers x and y similar if they have the same parity (the same remainder when divided by 2), or if |x-y|=1. For example, in each of the pairs (2, 6), (4, 3), (11, 7), the numbers are similar to each other, and in the pairs (1, 4), (3, 12), they are not.
You are given an array a of n (n is even) positive integers. Check if there is such a partition of the array into pairs that each element of the array belongs to exactly one pair and the numbers in each pair are similar to each other.
For example, for the array a = [11, 14, 16, 12], there is a partition into pairs (11, 12) and (14, 16). The numbers in the first pair are similar because they differ by one, and in the second pair because they are both even.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. Then t test cases follow.
Each test case consists of two lines.
The first line contains an even positive integer n (2 ≤ n ≤ 50) — length of array a.
The second line contains n positive integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 100).
Output
For each test case print:
* YES if the such a partition exists,
* NO otherwise.
The letters in the words YES and NO can be displayed in any case.
Example
Input
7
4
11 14 16 12
2
1 8
4
1 1 1 1
4
1 2 5 6
2
12 13
6
1 6 3 10 5 8
6
1 12 3 10 5 8
Output
YES
NO
YES
YES
YES
YES
NO
Note
The first test case was explained in the statement.
In the second test case, the two given numbers are not similar.
In the third test case, any partition is suitable.
Submitted Solution:
```
for _ in range(int(input())):
n=int(input())
arr=list(map(int,input().split()))
arr.sort()
even,odd=0,0
for i in arr:
if(i%2==0):
even+=1
else:
odd+=1
flag=False
if(even%2==0 and odd%2==0):
print("YES")
else:
for i in range(1,n):
if(abs(arr[i]-arr[i-1])==1):
flag=True
break
if(flag):
print("YES")
else:
print("NO")
``` | instruction | 0 | 80,992 | 12 | 161,984 |
Yes | output | 1 | 80,992 | 12 | 161,985 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a_1, a_2 ... a_n. Calculate the number of tuples (i, j, k, l) such that:
* 1 ≤ i < j < k < l ≤ n;
* a_i = a_k and a_j = a_l;
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases.
The first line of each test case contains a single integer n (4 ≤ n ≤ 3000) — the size of the array a.
The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the array a.
It's guaranteed that the sum of n in one test doesn't exceed 3000.
Output
For each test case, print the number of described tuples.
Example
Input
2
5
2 2 2 2 2
6
1 3 3 1 2 3
Output
5
2
Note
In the first test case, for any four indices i < j < k < l are valid, so the answer is the number of tuples.
In the second test case, there are 2 valid tuples:
* (1, 2, 4, 6): a_1 = a_4 and a_2 = a_6;
* (1, 3, 4, 6): a_1 = a_4 and a_3 = a_6. | instruction | 0 | 81,013 | 12 | 162,026 |
Tags: brute force, combinatorics, data structures, math, two pointers
Correct Solution:
```
#: Author - Soumya Saurav
import sys,io,os,time
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect,math,heapq
alphabet = "abcdefghijklmnopqrstuvwxyz"
input = sys.stdin.readline
########################################
for ii in range(int(input())):
n = int(input())
arr = list(map(int , input().split()))
lcount = [0]*(n+100)
ans = 0
for l in range(n):
rcount = [0]*(n+100)
for r in range(n-1,l,-1):
ans += lcount[arr[r]]*rcount[arr[l]]
rcount[arr[r]]+=1
lcount[arr[l]]+=1
print(ans)
``` | output | 1 | 81,013 | 12 | 162,027 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a_1, a_2 ... a_n. Calculate the number of tuples (i, j, k, l) such that:
* 1 ≤ i < j < k < l ≤ n;
* a_i = a_k and a_j = a_l;
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases.
The first line of each test case contains a single integer n (4 ≤ n ≤ 3000) — the size of the array a.
The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the array a.
It's guaranteed that the sum of n in one test doesn't exceed 3000.
Output
For each test case, print the number of described tuples.
Example
Input
2
5
2 2 2 2 2
6
1 3 3 1 2 3
Output
5
2
Note
In the first test case, for any four indices i < j < k < l are valid, so the answer is the number of tuples.
In the second test case, there are 2 valid tuples:
* (1, 2, 4, 6): a_1 = a_4 and a_2 = a_6;
* (1, 3, 4, 6): a_1 = a_4 and a_3 = a_6. | instruction | 0 | 81,014 | 12 | 162,028 |
Tags: brute force, combinatorics, data structures, math, two pointers
Correct Solution:
```
from sys import stdin, stdout
import heapq
import cProfile
from collections import Counter, defaultdict, deque
from functools import reduce
import math
def get_int():
return int(stdin.readline().strip())
def get_tuple():
return map(int, stdin.readline().split())
def get_list():
return list(map(int, stdin.readline().split()))
def solve():
n = get_int()
ls = get_list()
l = [0]*(n+1)
c = 0
for j in range(n):
r = [0]*(n+1)
for k in range(n-1,j,-1):
c += l[ls[k]]*r[ls[j]]
r[ls[k]] += 1
l[ls[j]] += 1
print(c)
def main():
solve()
TestCases = True
if TestCases:
for i in range(get_int()):
main()
else:
main()
``` | output | 1 | 81,014 | 12 | 162,029 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a_1, a_2 ... a_n. Calculate the number of tuples (i, j, k, l) such that:
* 1 ≤ i < j < k < l ≤ n;
* a_i = a_k and a_j = a_l;
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases.
The first line of each test case contains a single integer n (4 ≤ n ≤ 3000) — the size of the array a.
The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the array a.
It's guaranteed that the sum of n in one test doesn't exceed 3000.
Output
For each test case, print the number of described tuples.
Example
Input
2
5
2 2 2 2 2
6
1 3 3 1 2 3
Output
5
2
Note
In the first test case, for any four indices i < j < k < l are valid, so the answer is the number of tuples.
In the second test case, there are 2 valid tuples:
* (1, 2, 4, 6): a_1 = a_4 and a_2 = a_6;
* (1, 3, 4, 6): a_1 = a_4 and a_3 = a_6. | instruction | 0 | 81,015 | 12 | 162,030 |
Tags: brute force, combinatorics, data structures, math, two pointers
Correct Solution:
```
import sys
import math
from collections import defaultdict,Counter
# input=sys.stdin.readline
# def print(x):
# sys.stdout.write(str(x)+"\n")
# sys.stdout=open("CP1/output.txt",'w')
# sys.stdin=open("CP1/input.txt",'r')
# m=pow(10,9)+7
t=int(input())
for i in range(t):
n=int(input())
a=list(map(int,input().split()))
pre=defaultdict(int)
ans=0
for j in range(n-1):
suf=defaultdict(int)
for k in range(n-1,j,-1):
ans+=suf[a[j]]*pre[a[k]]
suf[a[k]]+=1
pre[a[j]]+=1
print(ans)
``` | output | 1 | 81,015 | 12 | 162,031 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a_1, a_2 ... a_n. Calculate the number of tuples (i, j, k, l) such that:
* 1 ≤ i < j < k < l ≤ n;
* a_i = a_k and a_j = a_l;
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases.
The first line of each test case contains a single integer n (4 ≤ n ≤ 3000) — the size of the array a.
The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the array a.
It's guaranteed that the sum of n in one test doesn't exceed 3000.
Output
For each test case, print the number of described tuples.
Example
Input
2
5
2 2 2 2 2
6
1 3 3 1 2 3
Output
5
2
Note
In the first test case, for any four indices i < j < k < l are valid, so the answer is the number of tuples.
In the second test case, there are 2 valid tuples:
* (1, 2, 4, 6): a_1 = a_4 and a_2 = a_6;
* (1, 3, 4, 6): a_1 = a_4 and a_3 = a_6. | instruction | 0 | 81,016 | 12 | 162,032 |
Tags: brute force, combinatorics, data structures, math, two pointers
Correct Solution:
```
import sys
import math,bisect
sys.setrecursionlimit(10 ** 5)
from collections import defaultdict
from itertools import groupby,accumulate
from heapq import heapify,heappop,heappush
from collections import deque,Counter,OrderedDict
def I(): return int(sys.stdin.readline())
def neo(): return map(int, sys.stdin.readline().split())
def Neo(): return list(map(int, sys.stdin.readline().split()))
for _ in range(int(input())):
n = I()
A = Neo()
Ans,cnt = 0,[0]*(n+1)
for i,a in enumerate(A):
cur=0
for a2 in A[i+1:]:
if a2==a:
Ans+=cur
cur+=cnt[a2]
cnt[a]+=1
print(Ans)
``` | output | 1 | 81,016 | 12 | 162,033 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a_1, a_2 ... a_n. Calculate the number of tuples (i, j, k, l) such that:
* 1 ≤ i < j < k < l ≤ n;
* a_i = a_k and a_j = a_l;
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases.
The first line of each test case contains a single integer n (4 ≤ n ≤ 3000) — the size of the array a.
The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the array a.
It's guaranteed that the sum of n in one test doesn't exceed 3000.
Output
For each test case, print the number of described tuples.
Example
Input
2
5
2 2 2 2 2
6
1 3 3 1 2 3
Output
5
2
Note
In the first test case, for any four indices i < j < k < l are valid, so the answer is the number of tuples.
In the second test case, there are 2 valid tuples:
* (1, 2, 4, 6): a_1 = a_4 and a_2 = a_6;
* (1, 3, 4, 6): a_1 = a_4 and a_3 = a_6. | instruction | 0 | 81,017 | 12 | 162,034 |
Tags: brute force, combinatorics, data structures, math, two pointers
Correct Solution:
```
for _ in range(int(input())):
n=int(input())
arr=list(map(int,input().split()))
left=[0 for i in range(n+1)]
right=[0 for i in range(n+1)]
state=[0 for i in range(n)]
k=n-1
while k>=0:
state[k]=right[:]
#print(right)
right[arr[k]]+=1
k-=1
#print(state)
ans=0
k=0
for j in range(0,n-2):
k=n-1
while k>j:
ans+=left[arr[k]]*state[k][arr[j]]
k-=1
left[arr[j]]+=1
print(ans)
``` | output | 1 | 81,017 | 12 | 162,035 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a_1, a_2 ... a_n. Calculate the number of tuples (i, j, k, l) such that:
* 1 ≤ i < j < k < l ≤ n;
* a_i = a_k and a_j = a_l;
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases.
The first line of each test case contains a single integer n (4 ≤ n ≤ 3000) — the size of the array a.
The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the array a.
It's guaranteed that the sum of n in one test doesn't exceed 3000.
Output
For each test case, print the number of described tuples.
Example
Input
2
5
2 2 2 2 2
6
1 3 3 1 2 3
Output
5
2
Note
In the first test case, for any four indices i < j < k < l are valid, so the answer is the number of tuples.
In the second test case, there are 2 valid tuples:
* (1, 2, 4, 6): a_1 = a_4 and a_2 = a_6;
* (1, 3, 4, 6): a_1 = a_4 and a_3 = a_6. | instruction | 0 | 81,018 | 12 | 162,036 |
Tags: brute force, combinatorics, data structures, math, two pointers
Correct Solution:
```
from collections import Counter
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
h1 = Counter(a)
h2 = Counter()
res = 0
for i in range(n):
h1[a[i]] -= 1
s = 0
for j in range(i + 1, n):
s -= h1[a[j]] * h2[a[j]]
h1[a[j]] -= 1
if j > i + 1:
if a[j] != a[j - 1]:
s -= h1[a[j - 1]] * h2[a[j - 1]]
h2[a[j - 1]] += 1
if a[j] != a[j - 1]:
s += h1[a[j - 1]] * h2[a[j - 1]]
s += h1[a[j]] * h2[a[j]]
# print(f'i={i}, j={j}, s={s}, h1={h1}, h2={h2}, {a[i]==a[j]}')
if a[i] == a[j]:
res += s
h2[a[n - 1]] += 1
h1, h2 = h2, h1
print(res)
``` | output | 1 | 81,018 | 12 | 162,037 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a_1, a_2 ... a_n. Calculate the number of tuples (i, j, k, l) such that:
* 1 ≤ i < j < k < l ≤ n;
* a_i = a_k and a_j = a_l;
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases.
The first line of each test case contains a single integer n (4 ≤ n ≤ 3000) — the size of the array a.
The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the array a.
It's guaranteed that the sum of n in one test doesn't exceed 3000.
Output
For each test case, print the number of described tuples.
Example
Input
2
5
2 2 2 2 2
6
1 3 3 1 2 3
Output
5
2
Note
In the first test case, for any four indices i < j < k < l are valid, so the answer is the number of tuples.
In the second test case, there are 2 valid tuples:
* (1, 2, 4, 6): a_1 = a_4 and a_2 = a_6;
* (1, 3, 4, 6): a_1 = a_4 and a_3 = a_6. | instruction | 0 | 81,019 | 12 | 162,038 |
Tags: brute force, combinatorics, data structures, math, two pointers
Correct Solution:
```
def process(A):
d = {}
n = len(A)
for i in range(n):
x = A[i]
if x not in d:
d[x] = []
d[x].append(i)
answer = 0
for x in d:
v = len(d[x])
answer+=(v*(v-1)*(v-2)*(v-3))//24
for x in d:
for y in d:
if x != y:
pairs1 = {}
pairs2 = {}
for j in d[y]:
for i in d[x]:
if i > j:
break
if i not in pairs1:
pairs1[i] = 0
if j not in pairs2:
pairs2[j] = 0
pairs1[i]+=1
pairs2[j]+=1
for i in pairs1:
for j in pairs2:
if j < i:
answer+=pairs1[i]*pairs2[j]
return answer
t = int(input())
for i in range(t):
n = int(input())
A = [int(x) for x in input().split()]
print(process(A))
``` | output | 1 | 81,019 | 12 | 162,039 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a_1, a_2 ... a_n. Calculate the number of tuples (i, j, k, l) such that:
* 1 ≤ i < j < k < l ≤ n;
* a_i = a_k and a_j = a_l;
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases.
The first line of each test case contains a single integer n (4 ≤ n ≤ 3000) — the size of the array a.
The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the array a.
It's guaranteed that the sum of n in one test doesn't exceed 3000.
Output
For each test case, print the number of described tuples.
Example
Input
2
5
2 2 2 2 2
6
1 3 3 1 2 3
Output
5
2
Note
In the first test case, for any four indices i < j < k < l are valid, so the answer is the number of tuples.
In the second test case, there are 2 valid tuples:
* (1, 2, 4, 6): a_1 = a_4 and a_2 = a_6;
* (1, 3, 4, 6): a_1 = a_4 and a_3 = a_6. | instruction | 0 | 81,020 | 12 | 162,040 |
Tags: brute force, combinatorics, data structures, math, two pointers
Correct Solution:
```
import sys
input = sys.stdin.readline
from collections import *
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
a = list(map(lambda x: x-1, a))
ans = 0
for i in range(n):
cntl = [0]*n
cntr = [0]*n
now = 0
for j in range(i+2, n):
cntr[a[j]] += 1
for j in range(i+1, n-1):
if a[i]==a[j]:
#print(i, j, cntl, cntr, now)
ans += now
if a[j]==a[j+1]:
now -= cntl[a[j]]*cntr[a[j+1]]
cntl[a[j]] += 1
cntr[a[j+1]] -= 1
now += cntl[a[j]]*cntr[a[j+1]]
else:
now += cntr[a[j]]
now -= cntl[a[j+1]]
cntl[a[j]] += 1
cntr[a[j+1]] -= 1
print(ans)
``` | output | 1 | 81,020 | 12 | 162,041 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a_1, a_2 ... a_n. Calculate the number of tuples (i, j, k, l) such that:
* 1 ≤ i < j < k < l ≤ n;
* a_i = a_k and a_j = a_l;
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases.
The first line of each test case contains a single integer n (4 ≤ n ≤ 3000) — the size of the array a.
The second line of each test case contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ n) — the array a.
It's guaranteed that the sum of n in one test doesn't exceed 3000.
Output
For each test case, print the number of described tuples.
Example
Input
2
5
2 2 2 2 2
6
1 3 3 1 2 3
Output
5
2
Note
In the first test case, for any four indices i < j < k < l are valid, so the answer is the number of tuples.
In the second test case, there are 2 valid tuples:
* (1, 2, 4, 6): a_1 = a_4 and a_2 = a_6;
* (1, 3, 4, 6): a_1 = a_4 and a_3 = a_6.
Submitted Solution:
```
import sys, math
import io, os
# data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
# from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
# from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var): sys.stdout.write(' '.join(map(str, var)) + '\n')
def out(var): sys.stdout.write(str(var) + '\n')
from decimal import Decimal
# from fractions import Fraction
# sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1e9) + 7
for t in range(int(data())):
n = int(data())
a = mdata()
d = dd(list)
for i in range(len(a)):
d[a[i]].append(i)
ans = 0
for i in range(n-1):
for j in range(i+1,n):
ind1=br(d[a[j]],i)
ind2=len(d[a[i]])-bl(d[a[i]],j)
if a[i]==a[j]:
ind1-=1
ind2-=1
ans+=ind1*ind2
out(ans)
``` | instruction | 0 | 81,024 | 12 | 162,048 |
Yes | output | 1 | 81,024 | 12 | 162,049 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks n integers a1, a2, ..., an are good.
Now she is interested in good sequences. A sequence x1, x2, ..., xk is called good if it satisfies the following three conditions:
* The sequence is strictly increasing, i.e. xi < xi + 1 for each i (1 ≤ i ≤ k - 1).
* No two adjacent elements are coprime, i.e. gcd(xi, xi + 1) > 1 for each i (1 ≤ i ≤ k - 1) (where gcd(p, q) denotes the greatest common divisor of the integers p and q).
* All elements of the sequence are good integers.
Find the length of the longest good sequence.
Input
The input consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 105) — the number of good integers. The second line contains a single-space separated list of good integers a1, a2, ..., an in strictly increasing order (1 ≤ ai ≤ 105; ai < ai + 1).
Output
Print a single integer — the length of the longest good sequence.
Examples
Input
5
2 3 4 6 9
Output
4
Input
9
1 2 3 5 6 7 8 9 10
Output
4
Note
In the first example, the following sequences are examples of good sequences: [2; 4; 6; 9], [2; 4; 6], [3; 9], [6]. The length of the longest good sequence is 4. | instruction | 0 | 81,086 | 12 | 162,172 |
Tags: dp, number theory
Correct Solution:
```
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
import sys
from io import BytesIO, IOBase
from collections import Counter
def seieve_prime_factorisation(n):
p, i = [1] * (n + 1), 2
while i * i <= n:
if p[i] == 1:
for j in range(i * i, n + 1, i):
p[j] = i
i += 1
return p
def prime_factorisation_by_seive(p, x):
c = Counter()
while p[x] != 1:
c[p[x]] += 1
x = x // p[x]
c[x] += 1
return c
def main():
n=int(input())
a=list(map(int,input().split()))
ma,dp=max(a),[1]*n
p=seieve_prime_factorisation(ma)
b=[0]*(ma+1)
for i in range(n-1,-1,-1):
z=prime_factorisation_by_seive(p,a[i])
ma = 0
for j in z:
ma = max(ma, b[j])
dp[i] += ma
for j in z:
b[j] =dp[i]
print(max(dp))
# (region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | output | 1 | 81,086 | 12 | 162,173 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks n integers a1, a2, ..., an are good.
Now she is interested in good sequences. A sequence x1, x2, ..., xk is called good if it satisfies the following three conditions:
* The sequence is strictly increasing, i.e. xi < xi + 1 for each i (1 ≤ i ≤ k - 1).
* No two adjacent elements are coprime, i.e. gcd(xi, xi + 1) > 1 for each i (1 ≤ i ≤ k - 1) (where gcd(p, q) denotes the greatest common divisor of the integers p and q).
* All elements of the sequence are good integers.
Find the length of the longest good sequence.
Input
The input consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 105) — the number of good integers. The second line contains a single-space separated list of good integers a1, a2, ..., an in strictly increasing order (1 ≤ ai ≤ 105; ai < ai + 1).
Output
Print a single integer — the length of the longest good sequence.
Examples
Input
5
2 3 4 6 9
Output
4
Input
9
1 2 3 5 6 7 8 9 10
Output
4
Note
In the first example, the following sequences are examples of good sequences: [2; 4; 6; 9], [2; 4; 6], [3; 9], [6]. The length of the longest good sequence is 4. | instruction | 0 | 81,088 | 12 | 162,176 |
Tags: dp, number theory
Correct Solution:
```
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
import sys
from io import BytesIO, IOBase
from collections import Counter
def seieve_prime_factorisation(n):
p, i = [1] * (n + 1), 2
while i * i <= n:
if p[i] == 1:
for j in range(i * i, n + 1, i):
p[j] = i
i += 1
return p
def prime_factorisation_by_seive(p, x):
c = Counter()
while p[x] != 1:
c[p[x]] += 1
x = x // p[x]
c[x] += 1
return c
def main():
n=int(input())
a=list(map(int,input().split()))
p=seieve_prime_factorisation(max(a))
dp=[1]*n
b=Counter()
for i in range(n-1,-1,-1):
z=prime_factorisation_by_seive(p,a[i])
ma=0
for j in z:
ma=max(ma,b[j])
dp[i]+=ma
for j in z:
b[j]=max(b[j],dp[i])
print(max(dp))
# (region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | output | 1 | 81,088 | 12 | 162,177 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks n integers a1, a2, ..., an are good.
Now she is interested in good sequences. A sequence x1, x2, ..., xk is called good if it satisfies the following three conditions:
* The sequence is strictly increasing, i.e. xi < xi + 1 for each i (1 ≤ i ≤ k - 1).
* No two adjacent elements are coprime, i.e. gcd(xi, xi + 1) > 1 for each i (1 ≤ i ≤ k - 1) (where gcd(p, q) denotes the greatest common divisor of the integers p and q).
* All elements of the sequence are good integers.
Find the length of the longest good sequence.
Input
The input consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 105) — the number of good integers. The second line contains a single-space separated list of good integers a1, a2, ..., an in strictly increasing order (1 ≤ ai ≤ 105; ai < ai + 1).
Output
Print a single integer — the length of the longest good sequence.
Examples
Input
5
2 3 4 6 9
Output
4
Input
9
1 2 3 5 6 7 8 9 10
Output
4
Note
In the first example, the following sequences are examples of good sequences: [2; 4; 6; 9], [2; 4; 6], [3; 9], [6]. The length of the longest good sequence is 4.
Submitted Solution:
```
primes=[]
for i in range(2,10**5):
x=0
for j in range(2,int(i**0.5)+1):
if i%j==0:
x=1
break
if x==0:
primes.append(i)
set_p=set(primes)
n=int(input())
#a=list(map(int,input().split()))
a=[100000 for i in range(1,n+1)]
a=a[::-1]
ans=0
store={}
c=0
for i in a:
c=0
b=set()
#print(store)
x=i
for i in primes:
if x==1:
break
if x in set_p:
b.add(x)
break
if x%i==0:
b.add(i)
while x%i==0:
x=x//i
for i in b:
if i in store:
c=max(c,store[i]+1)
else:
c=max(c,1)
for i in b:
store[i]=c
if c>ans:
ans=c
print(ans)
``` | instruction | 0 | 81,089 | 12 | 162,178 |
No | output | 1 | 81,089 | 12 | 162,179 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks n integers a1, a2, ..., an are good.
Now she is interested in good sequences. A sequence x1, x2, ..., xk is called good if it satisfies the following three conditions:
* The sequence is strictly increasing, i.e. xi < xi + 1 for each i (1 ≤ i ≤ k - 1).
* No two adjacent elements are coprime, i.e. gcd(xi, xi + 1) > 1 for each i (1 ≤ i ≤ k - 1) (where gcd(p, q) denotes the greatest common divisor of the integers p and q).
* All elements of the sequence are good integers.
Find the length of the longest good sequence.
Input
The input consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 105) — the number of good integers. The second line contains a single-space separated list of good integers a1, a2, ..., an in strictly increasing order (1 ≤ ai ≤ 105; ai < ai + 1).
Output
Print a single integer — the length of the longest good sequence.
Examples
Input
5
2 3 4 6 9
Output
4
Input
9
1 2 3 5 6 7 8 9 10
Output
4
Note
In the first example, the following sequences are examples of good sequences: [2; 4; 6; 9], [2; 4; 6], [3; 9], [6]. The length of the longest good sequence is 4.
Submitted Solution:
```
primes=[]
for i in range(2,10**5):
x=0
for j in range(2,int(i**0.5)+1):
if i%j==0:
x=1
break
if x==0:
primes.append(i)
set_p=set(primes)
n=int(input())
a=list(map(int,input().split()))
#a=[100000 for i in range(1,n+1)]
a=a[::-1]
ans=0
store={}
c=0
for i in a:
c=0
b=set()
#print(store)
x=i
for i in primes:
if x==1:
break
if x in set_p:
b.add(x)
break
if x%i==0:
b.add(i)
while x%i==0:
x=x//i
for i in b:
if i in store:
c=max(c,store[i]+1)
else:
c=max(c,1)
for i in b:
store[i]=c
if c>ans:
ans=c
print(ans)
``` | instruction | 0 | 81,090 | 12 | 162,180 |
No | output | 1 | 81,090 | 12 | 162,181 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks n integers a1, a2, ..., an are good.
Now she is interested in good sequences. A sequence x1, x2, ..., xk is called good if it satisfies the following three conditions:
* The sequence is strictly increasing, i.e. xi < xi + 1 for each i (1 ≤ i ≤ k - 1).
* No two adjacent elements are coprime, i.e. gcd(xi, xi + 1) > 1 for each i (1 ≤ i ≤ k - 1) (where gcd(p, q) denotes the greatest common divisor of the integers p and q).
* All elements of the sequence are good integers.
Find the length of the longest good sequence.
Input
The input consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 105) — the number of good integers. The second line contains a single-space separated list of good integers a1, a2, ..., an in strictly increasing order (1 ≤ ai ≤ 105; ai < ai + 1).
Output
Print a single integer — the length of the longest good sequence.
Examples
Input
5
2 3 4 6 9
Output
4
Input
9
1 2 3 5 6 7 8 9 10
Output
4
Note
In the first example, the following sequences are examples of good sequences: [2; 4; 6; 9], [2; 4; 6], [3; 9], [6]. The length of the longest good sequence is 4.
Submitted Solution:
```
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
import sys
from io import BytesIO, IOBase
from collections import Counter
def seieve_prime_factorisation(n):
p, i = [1] * (n + 1), 2
while i * i <= n:
if p[i] == 1:
for j in range(i * i, n + 1, i):
p[j] = i
i += 1
return p
def prime_factorisation_by_seive(p, x):
c = Counter()
while p[x] != 1:
c[p[x]] += 1
x = x // p[x]
c[x] += 1
return c
def main():
n=int(input())
a=list(map(int,input().split()))
ma,dp=max(a),[0]*n
p=seieve_prime_factorisation(ma)
b=[0]*(ma+1)
for i in range(n-1,-1,-1):
z=prime_factorisation_by_seive(p,a[i])
ma=0
for j in z:
b[j]+=1
ma=max(ma,b[j])
dp[i]=ma
print(max(dp))
# (region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | instruction | 0 | 81,091 | 12 | 162,182 |
No | output | 1 | 81,091 | 12 | 162,183 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a sequence of positive integers of length N, a = (a_1, a_2, ..., a_N). Your objective is to remove some of the elements in a so that a will be a good sequence.
Here, an sequence b is a good sequence when the following condition holds true:
* For each element x in b, the value x occurs exactly x times in b.
For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.
Find the minimum number of elements that needs to be removed so that a will be a good sequence.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the minimum number of elements that needs to be removed so that a will be a good sequence.
Examples
Input
4
3 3 3 3
Output
1
Input
5
2 4 1 4 2
Output
2
Input
6
1 2 2 3 3 3
Output
0
Input
1
1000000000
Output
1
Input
8
2 7 1 8 2 8 1 8
Output
5 | instruction | 0 | 81,538 | 12 | 163,076 |
"Correct Solution:
```
n=int(input())
a=list(map(int,input().split()))
b=sorted(a)#n
c=list(set(b))
c.sort()
kosuu_list=[]
kosuu=1
for i in range(len(b)-1):
#kosuu=0
#print(b[i])
if b[i]==b[i+1]:
kosuu+=1
else:
kosuu_list.append(kosuu)
kosuu=1
kosuu_list.append(b.count(b[-1]))
#print(kosuu_list)
count=0
#print(c)
for i in range(len(c)):
if kosuu_list[i]==c[i]:
count+=0
elif kosuu_list[i]>=c[i]:
count+=kosuu_list[i]-c[i]
else:
count+=kosuu_list[i]
print(count)
``` | output | 1 | 81,538 | 12 | 163,077 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a sequence of positive integers of length N, a = (a_1, a_2, ..., a_N). Your objective is to remove some of the elements in a so that a will be a good sequence.
Here, an sequence b is a good sequence when the following condition holds true:
* For each element x in b, the value x occurs exactly x times in b.
For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.
Find the minimum number of elements that needs to be removed so that a will be a good sequence.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the minimum number of elements that needs to be removed so that a will be a good sequence.
Examples
Input
4
3 3 3 3
Output
1
Input
5
2 4 1 4 2
Output
2
Input
6
1 2 2 3 3 3
Output
0
Input
1
1000000000
Output
1
Input
8
2 7 1 8 2 8 1 8
Output
5 | instruction | 0 | 81,539 | 12 | 163,078 |
"Correct Solution:
```
import collections
n = int(input())
a = collections.Counter(list(map(int, input().split()))).most_common()
cnt = 0
for k, v in a:
if k < v:
cnt += (v - k)
elif k > v:
cnt += v
print(cnt)
``` | output | 1 | 81,539 | 12 | 163,079 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a sequence of positive integers of length N, a = (a_1, a_2, ..., a_N). Your objective is to remove some of the elements in a so that a will be a good sequence.
Here, an sequence b is a good sequence when the following condition holds true:
* For each element x in b, the value x occurs exactly x times in b.
For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.
Find the minimum number of elements that needs to be removed so that a will be a good sequence.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the minimum number of elements that needs to be removed so that a will be a good sequence.
Examples
Input
4
3 3 3 3
Output
1
Input
5
2 4 1 4 2
Output
2
Input
6
1 2 2 3 3 3
Output
0
Input
1
1000000000
Output
1
Input
8
2 7 1 8 2 8 1 8
Output
5 | instruction | 0 | 81,540 | 12 | 163,080 |
"Correct Solution:
```
# ABC082C - Good Sequence (ARC087C)
import sys
input = sys.stdin.readline
from collections import Counter
def main():
n = int(input())
cnt = Counter(list(map(int, input().rstrip().split())))
ans = 0
for i, j in cnt.items():
if i > j:
ans += j
elif i < j:
ans += j - i
print(ans)
if __name__ == "__main__":
main()
``` | output | 1 | 81,540 | 12 | 163,081 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a sequence of positive integers of length N, a = (a_1, a_2, ..., a_N). Your objective is to remove some of the elements in a so that a will be a good sequence.
Here, an sequence b is a good sequence when the following condition holds true:
* For each element x in b, the value x occurs exactly x times in b.
For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.
Find the minimum number of elements that needs to be removed so that a will be a good sequence.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the minimum number of elements that needs to be removed so that a will be a good sequence.
Examples
Input
4
3 3 3 3
Output
1
Input
5
2 4 1 4 2
Output
2
Input
6
1 2 2 3 3 3
Output
0
Input
1
1000000000
Output
1
Input
8
2 7 1 8 2 8 1 8
Output
5 | instruction | 0 | 81,541 | 12 | 163,082 |
"Correct Solution:
```
n = len(input())
mp, res = {}, 0
for el in list(map(int, input().split())): mp[el] = mp.get(el, 0) + 1
for key in mp:
val = mp[key]
if key > val: res += val
elif key < val: res += val - key
print(res)
``` | output | 1 | 81,541 | 12 | 163,083 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a sequence of positive integers of length N, a = (a_1, a_2, ..., a_N). Your objective is to remove some of the elements in a so that a will be a good sequence.
Here, an sequence b is a good sequence when the following condition holds true:
* For each element x in b, the value x occurs exactly x times in b.
For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.
Find the minimum number of elements that needs to be removed so that a will be a good sequence.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the minimum number of elements that needs to be removed so that a will be a good sequence.
Examples
Input
4
3 3 3 3
Output
1
Input
5
2 4 1 4 2
Output
2
Input
6
1 2 2 3 3 3
Output
0
Input
1
1000000000
Output
1
Input
8
2 7 1 8 2 8 1 8
Output
5 | instruction | 0 | 81,542 | 12 | 163,084 |
"Correct Solution:
```
from collections import Counter
N=int(input())
A=list(map(int,input().split()))
Ca=dict(Counter(A))
Dk=Ca.keys()
a=0
for i in Dk:
if i>Ca[i]:
a+=Ca[i]
elif i<Ca[i]:
a+=Ca[i]-i
print(a)
``` | output | 1 | 81,542 | 12 | 163,085 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a sequence of positive integers of length N, a = (a_1, a_2, ..., a_N). Your objective is to remove some of the elements in a so that a will be a good sequence.
Here, an sequence b is a good sequence when the following condition holds true:
* For each element x in b, the value x occurs exactly x times in b.
For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.
Find the minimum number of elements that needs to be removed so that a will be a good sequence.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the minimum number of elements that needs to be removed so that a will be a good sequence.
Examples
Input
4
3 3 3 3
Output
1
Input
5
2 4 1 4 2
Output
2
Input
6
1 2 2 3 3 3
Output
0
Input
1
1000000000
Output
1
Input
8
2 7 1 8 2 8 1 8
Output
5 | instruction | 0 | 81,543 | 12 | 163,086 |
"Correct Solution:
```
N=int(input())
a=[int(i) for i in input().split()]
data={}
for num in a:
if num in data:
data[num]+=1
else:
data[num]=1
ans=0
for key in data.keys():
if data[key]<key:
ans+=data[key]
else:
ans+=data[key]-key
print(ans)
``` | output | 1 | 81,543 | 12 | 163,087 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a sequence of positive integers of length N, a = (a_1, a_2, ..., a_N). Your objective is to remove some of the elements in a so that a will be a good sequence.
Here, an sequence b is a good sequence when the following condition holds true:
* For each element x in b, the value x occurs exactly x times in b.
For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.
Find the minimum number of elements that needs to be removed so that a will be a good sequence.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the minimum number of elements that needs to be removed so that a will be a good sequence.
Examples
Input
4
3 3 3 3
Output
1
Input
5
2 4 1 4 2
Output
2
Input
6
1 2 2 3 3 3
Output
0
Input
1
1000000000
Output
1
Input
8
2 7 1 8 2 8 1 8
Output
5 | instruction | 0 | 81,544 | 12 | 163,088 |
"Correct Solution:
```
from collections import Counter
N = int(input())
As = Counter(list(map(int,input().split())))
ans = 0
for x,y in As.items():
if x<y:
ans+=y-x
elif y<x:
ans+=y
print(ans)
``` | output | 1 | 81,544 | 12 | 163,089 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a sequence of positive integers of length N, a = (a_1, a_2, ..., a_N). Your objective is to remove some of the elements in a so that a will be a good sequence.
Here, an sequence b is a good sequence when the following condition holds true:
* For each element x in b, the value x occurs exactly x times in b.
For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.
Find the minimum number of elements that needs to be removed so that a will be a good sequence.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the minimum number of elements that needs to be removed so that a will be a good sequence.
Examples
Input
4
3 3 3 3
Output
1
Input
5
2 4 1 4 2
Output
2
Input
6
1 2 2 3 3 3
Output
0
Input
1
1000000000
Output
1
Input
8
2 7 1 8 2 8 1 8
Output
5 | instruction | 0 | 81,545 | 12 | 163,090 |
"Correct Solution:
```
N = int(input())
A = [int(i) for i in input().split()]
dic = {}
for a in A:
dic[a] = dic.get(a,0)+1
ans = 0
for k in dic:
if dic[k]>k:
ans += dic[k]-k
elif dic[k]<k:
ans += dic[k]
print(ans)
``` | output | 1 | 81,545 | 12 | 163,091 |
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 of positive integers of length N, a = (a_1, a_2, ..., a_N). Your objective is to remove some of the elements in a so that a will be a good sequence.
Here, an sequence b is a good sequence when the following condition holds true:
* For each element x in b, the value x occurs exactly x times in b.
For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.
Find the minimum number of elements that needs to be removed so that a will be a good sequence.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the minimum number of elements that needs to be removed so that a will be a good sequence.
Examples
Input
4
3 3 3 3
Output
1
Input
5
2 4 1 4 2
Output
2
Input
6
1 2 2 3 3 3
Output
0
Input
1
1000000000
Output
1
Input
8
2 7 1 8 2 8 1 8
Output
5
Submitted Solution:
```
from collections import Counter
n = int(input())
a = list(map(int, input().split()))
c = Counter(a)
ans = 0
for key, value in c.items():
if key > value:
ans += value
else:
ans += value - key
print(ans)
``` | instruction | 0 | 81,546 | 12 | 163,092 |
Yes | output | 1 | 81,546 | 12 | 163,093 |
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 of positive integers of length N, a = (a_1, a_2, ..., a_N). Your objective is to remove some of the elements in a so that a will be a good sequence.
Here, an sequence b is a good sequence when the following condition holds true:
* For each element x in b, the value x occurs exactly x times in b.
For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.
Find the minimum number of elements that needs to be removed so that a will be a good sequence.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the minimum number of elements that needs to be removed so that a will be a good sequence.
Examples
Input
4
3 3 3 3
Output
1
Input
5
2 4 1 4 2
Output
2
Input
6
1 2 2 3 3 3
Output
0
Input
1
1000000000
Output
1
Input
8
2 7 1 8 2 8 1 8
Output
5
Submitted Solution:
```
from collections import Counter
def main():
n = int(input())
a = list(map(int, input().split()))
ans = 0
c = Counter(a)
for i in c:
if c[i] < i:
ans += c[i]
else:
ans += c[i] - i
print(ans)
if __name__ == '__main__':
main()
``` | instruction | 0 | 81,547 | 12 | 163,094 |
Yes | output | 1 | 81,547 | 12 | 163,095 |
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 of positive integers of length N, a = (a_1, a_2, ..., a_N). Your objective is to remove some of the elements in a so that a will be a good sequence.
Here, an sequence b is a good sequence when the following condition holds true:
* For each element x in b, the value x occurs exactly x times in b.
For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.
Find the minimum number of elements that needs to be removed so that a will be a good sequence.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the minimum number of elements that needs to be removed so that a will be a good sequence.
Examples
Input
4
3 3 3 3
Output
1
Input
5
2 4 1 4 2
Output
2
Input
6
1 2 2 3 3 3
Output
0
Input
1
1000000000
Output
1
Input
8
2 7 1 8 2 8 1 8
Output
5
Submitted Solution:
```
import collections
N = int(input())
a = list(map(int, input().split()))
a = collections.Counter(a)
a = a.most_common()
ans = 0
for i in range(len(a)):
if a[i][0] <= a[i][1]:
ans += a[i][1] - a[i][0]
else:
ans += a[i][1]
print(ans)
``` | instruction | 0 | 81,548 | 12 | 163,096 |
Yes | output | 1 | 81,548 | 12 | 163,097 |
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 of positive integers of length N, a = (a_1, a_2, ..., a_N). Your objective is to remove some of the elements in a so that a will be a good sequence.
Here, an sequence b is a good sequence when the following condition holds true:
* For each element x in b, the value x occurs exactly x times in b.
For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.
Find the minimum number of elements that needs to be removed so that a will be a good sequence.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the minimum number of elements that needs to be removed so that a will be a good sequence.
Examples
Input
4
3 3 3 3
Output
1
Input
5
2 4 1 4 2
Output
2
Input
6
1 2 2 3 3 3
Output
0
Input
1
1000000000
Output
1
Input
8
2 7 1 8 2 8 1 8
Output
5
Submitted Solution:
```
n = int(input())
a = input().split()
from collections import Counter
b = Counter(a)
remove = 0
for x in b:
if int(x) > b[x]:
remove += b[x]
else:
remove += b[x]-int(x)
print(remove)
``` | instruction | 0 | 81,549 | 12 | 163,098 |
Yes | output | 1 | 81,549 | 12 | 163,099 |
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 of positive integers of length N, a = (a_1, a_2, ..., a_N). Your objective is to remove some of the elements in a so that a will be a good sequence.
Here, an sequence b is a good sequence when the following condition holds true:
* For each element x in b, the value x occurs exactly x times in b.
For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.
Find the minimum number of elements that needs to be removed so that a will be a good sequence.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the minimum number of elements that needs to be removed so that a will be a good sequence.
Examples
Input
4
3 3 3 3
Output
1
Input
5
2 4 1 4 2
Output
2
Input
6
1 2 2 3 3 3
Output
0
Input
1
1000000000
Output
1
Input
8
2 7 1 8 2 8 1 8
Output
5
Submitted Solution:
```
N = int(input())
a = list(map(int, input().split()))
a.sort()
count = 0
while a:
k = a.pop(0)
k_count = 1
while (len(a) > 0) and (a[0] == k):
a.pop(0)
k_count += 1
if k_count < k:
count += k_count
else:
count += k_count - k
print(count)
``` | instruction | 0 | 81,550 | 12 | 163,100 |
No | output | 1 | 81,550 | 12 | 163,101 |
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 of positive integers of length N, a = (a_1, a_2, ..., a_N). Your objective is to remove some of the elements in a so that a will be a good sequence.
Here, an sequence b is a good sequence when the following condition holds true:
* For each element x in b, the value x occurs exactly x times in b.
For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.
Find the minimum number of elements that needs to be removed so that a will be a good sequence.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the minimum number of elements that needs to be removed so that a will be a good sequence.
Examples
Input
4
3 3 3 3
Output
1
Input
5
2 4 1 4 2
Output
2
Input
6
1 2 2 3 3 3
Output
0
Input
1
1000000000
Output
1
Input
8
2 7 1 8 2 8 1 8
Output
5
Submitted Solution:
```
N = int(input())
a = list(map(int, input().split()))
cnt = 0
S = 0
for i in range(100000):
tmp = a.count(i + 1)
S += tmp
if tmp > i + 1:
cnt += tmp - i - 1
elif tmp < i + 1:
cnt += tmp
cnt += N - S
print(cnt)
``` | instruction | 0 | 81,551 | 12 | 163,102 |
No | output | 1 | 81,551 | 12 | 163,103 |
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 of positive integers of length N, a = (a_1, a_2, ..., a_N). Your objective is to remove some of the elements in a so that a will be a good sequence.
Here, an sequence b is a good sequence when the following condition holds true:
* For each element x in b, the value x occurs exactly x times in b.
For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.
Find the minimum number of elements that needs to be removed so that a will be a good sequence.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the minimum number of elements that needs to be removed so that a will be a good sequence.
Examples
Input
4
3 3 3 3
Output
1
Input
5
2 4 1 4 2
Output
2
Input
6
1 2 2 3 3 3
Output
0
Input
1
1000000000
Output
1
Input
8
2 7 1 8 2 8 1 8
Output
5
Submitted Solution:
```
import collections
N = int(input())
A = list(map(int, input().split()))
c = collections.Counter(A)
cs = sorted(c.items(), key=lambda x:x[0])
cnt = 0
for i in range(len(cs)):
if(cs[i][0] != cs[i][1]):
if(cs[i][0] < cs[i][1]):
cnt += cs[i][1]-cs[i][0]
else:
cnt += cs[i][1]
if(N==1):
print(0)
else:
print(cnt)
``` | instruction | 0 | 81,552 | 12 | 163,104 |
No | output | 1 | 81,552 | 12 | 163,105 |
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 of positive integers of length N, a = (a_1, a_2, ..., a_N). Your objective is to remove some of the elements in a so that a will be a good sequence.
Here, an sequence b is a good sequence when the following condition holds true:
* For each element x in b, the value x occurs exactly x times in b.
For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.
Find the minimum number of elements that needs to be removed so that a will be a good sequence.
Constraints
* 1 \leq N \leq 10^5
* a_i is an integer.
* 1 \leq a_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
Output
Print the minimum number of elements that needs to be removed so that a will be a good sequence.
Examples
Input
4
3 3 3 3
Output
1
Input
5
2 4 1 4 2
Output
2
Input
6
1 2 2 3 3 3
Output
0
Input
1
1000000000
Output
1
Input
8
2 7 1 8 2 8 1 8
Output
5
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
s = list(set(a))
ans = 0
for i in s:
if i > a.count(i):
ans += a.count(i)
else:
ans += a.count(i) - i
print(ans)
``` | instruction | 0 | 81,553 | 12 | 163,106 |
No | output | 1 | 81,553 | 12 | 163,107 |
Provide a correct Python 3 solution for this coding contest problem.
A binary heap which satisfies max-heap property is called max-heap. In a max-heap, for every node $i$ other than the root, $A[i] \leq A[parent(i)]$, that is, the value of a node is at most the value of its parent. The largest element in a max-heap is stored at the root, and the subtree rooted at a node contains values no larger than that contained at the node itself.
Here is an example of a max-heap.
<image>
Write a program which reads an array and constructs a max-heap from the array based on the following pseudo code.
$maxHeapify(A, i)$ move the value of $A[i]$ down to leaves to make a sub-tree of node $i$ a max-heap. Here, $H$ is the size of the heap.
1 maxHeapify(A, i)
2 l = left(i)
3 r = right(i)
4 // select the node which has the maximum value
5 if l ≤ H and A[l] > A[i]
6 largest = l
7 else
8 largest = i
9 if r ≤ H and A[r] > A[largest]
10 largest = r
11
12 if largest ≠ i // value of children is larger than that of i
13 swap A[i] and A[largest]
14 maxHeapify(A, largest) // call recursively
The following procedure buildMaxHeap(A) makes $A$ a max-heap by performing maxHeapify in a bottom-up manner.
1 buildMaxHeap(A)
2 for i = H/2 downto 1
3 maxHeapify(A, i)
Input
In the first line, an integer $H$ is given. In the second line, $H$ integers which represent elements in the binary heap are given in order of node id (from $1$ to $H$).
Output
Print values of nodes in the max-heap in order of their id (from $1$ to $H$). Print a single space character before each value.
Example
Input
10
4 1 3 2 16 9 10 14 8 7
Output
16 14 10 8 7 9 3 2 4 1 | instruction | 0 | 81,673 | 12 | 163,346 |
"Correct Solution:
```
from heapq import heapify, heappop, heappush, heappushpop
N = input()
H = [-x for x in map(int, input().split())]
heapify(H)
print('', *[-x for x in H])
``` | output | 1 | 81,673 | 12 | 163,347 |
Provide a correct Python 3 solution for this coding contest problem.
A binary heap which satisfies max-heap property is called max-heap. In a max-heap, for every node $i$ other than the root, $A[i] \leq A[parent(i)]$, that is, the value of a node is at most the value of its parent. The largest element in a max-heap is stored at the root, and the subtree rooted at a node contains values no larger than that contained at the node itself.
Here is an example of a max-heap.
<image>
Write a program which reads an array and constructs a max-heap from the array based on the following pseudo code.
$maxHeapify(A, i)$ move the value of $A[i]$ down to leaves to make a sub-tree of node $i$ a max-heap. Here, $H$ is the size of the heap.
1 maxHeapify(A, i)
2 l = left(i)
3 r = right(i)
4 // select the node which has the maximum value
5 if l ≤ H and A[l] > A[i]
6 largest = l
7 else
8 largest = i
9 if r ≤ H and A[r] > A[largest]
10 largest = r
11
12 if largest ≠ i // value of children is larger than that of i
13 swap A[i] and A[largest]
14 maxHeapify(A, largest) // call recursively
The following procedure buildMaxHeap(A) makes $A$ a max-heap by performing maxHeapify in a bottom-up manner.
1 buildMaxHeap(A)
2 for i = H/2 downto 1
3 maxHeapify(A, i)
Input
In the first line, an integer $H$ is given. In the second line, $H$ integers which represent elements in the binary heap are given in order of node id (from $1$ to $H$).
Output
Print values of nodes in the max-heap in order of their id (from $1$ to $H$). Print a single space character before each value.
Example
Input
10
4 1 3 2 16 9 10 14 8 7
Output
16 14 10 8 7 9 3 2 4 1 | instruction | 0 | 81,674 | 12 | 163,348 |
"Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
def maxheapify(a, i):
l = i*2 + 1
r = i*2 + 2
if r < n:
if a[l] > a[i]:
largest = l
else:
largest = i
if a[r] > a[largest]:
largest = r
if largest != i:
memo = a[i]
a[i] = a[largest]
a[largest] = memo
maxheapify(a, largest)
elif l < n:
if a[l] > a[i]:
largest = l
else:
largest = i
if largest != i:
memo = a[i]
a[i] = a[largest]
a[largest] = memo
maxheapify(a, largest)
for i in reversed(range(n)):
maxheapify(a, i)
print("", *a)
``` | output | 1 | 81,674 | 12 | 163,349 |
Provide a correct Python 3 solution for this coding contest problem.
A binary heap which satisfies max-heap property is called max-heap. In a max-heap, for every node $i$ other than the root, $A[i] \leq A[parent(i)]$, that is, the value of a node is at most the value of its parent. The largest element in a max-heap is stored at the root, and the subtree rooted at a node contains values no larger than that contained at the node itself.
Here is an example of a max-heap.
<image>
Write a program which reads an array and constructs a max-heap from the array based on the following pseudo code.
$maxHeapify(A, i)$ move the value of $A[i]$ down to leaves to make a sub-tree of node $i$ a max-heap. Here, $H$ is the size of the heap.
1 maxHeapify(A, i)
2 l = left(i)
3 r = right(i)
4 // select the node which has the maximum value
5 if l ≤ H and A[l] > A[i]
6 largest = l
7 else
8 largest = i
9 if r ≤ H and A[r] > A[largest]
10 largest = r
11
12 if largest ≠ i // value of children is larger than that of i
13 swap A[i] and A[largest]
14 maxHeapify(A, largest) // call recursively
The following procedure buildMaxHeap(A) makes $A$ a max-heap by performing maxHeapify in a bottom-up manner.
1 buildMaxHeap(A)
2 for i = H/2 downto 1
3 maxHeapify(A, i)
Input
In the first line, an integer $H$ is given. In the second line, $H$ integers which represent elements in the binary heap are given in order of node id (from $1$ to $H$).
Output
Print values of nodes in the max-heap in order of their id (from $1$ to $H$). Print a single space character before each value.
Example
Input
10
4 1 3 2 16 9 10 14 8 7
Output
16 14 10 8 7 9 3 2 4 1 | instruction | 0 | 81,675 | 12 | 163,350 |
"Correct Solution:
```
from typing import List
def max_heapify(heap: List[int], idx: int) -> None:
left_idx = (2 * (idx + 1)) - 1
right_idx = (2 * (idx + 1))
if len(heap) - 1 >= left_idx and heap[left_idx] > heap[idx]:
largest_idx = left_idx
else:
largest_idx = idx
if len(heap) - 1 >= right_idx and heap[right_idx] > heap[largest_idx]:
largest_idx = right_idx
if largest_idx != idx:
heap[largest_idx], heap[idx] = heap[idx], heap[largest_idx]
max_heapify(heap, largest_idx)
def build_max_heap(heap: List[int]) -> None:
for idx in range(len(heap) // 2 - 1, -1, -1):
max_heapify(heap, idx)
if __name__ == "__main__":
node_num = int(input())
heap = list(map(lambda x: int(x), input().split()))
build_max_heap(heap)
print(" " + " ".join([str(elem) for elem in heap]))
``` | output | 1 | 81,675 | 12 | 163,351 |
Provide a correct Python 3 solution for this coding contest problem.
A binary heap which satisfies max-heap property is called max-heap. In a max-heap, for every node $i$ other than the root, $A[i] \leq A[parent(i)]$, that is, the value of a node is at most the value of its parent. The largest element in a max-heap is stored at the root, and the subtree rooted at a node contains values no larger than that contained at the node itself.
Here is an example of a max-heap.
<image>
Write a program which reads an array and constructs a max-heap from the array based on the following pseudo code.
$maxHeapify(A, i)$ move the value of $A[i]$ down to leaves to make a sub-tree of node $i$ a max-heap. Here, $H$ is the size of the heap.
1 maxHeapify(A, i)
2 l = left(i)
3 r = right(i)
4 // select the node which has the maximum value
5 if l ≤ H and A[l] > A[i]
6 largest = l
7 else
8 largest = i
9 if r ≤ H and A[r] > A[largest]
10 largest = r
11
12 if largest ≠ i // value of children is larger than that of i
13 swap A[i] and A[largest]
14 maxHeapify(A, largest) // call recursively
The following procedure buildMaxHeap(A) makes $A$ a max-heap by performing maxHeapify in a bottom-up manner.
1 buildMaxHeap(A)
2 for i = H/2 downto 1
3 maxHeapify(A, i)
Input
In the first line, an integer $H$ is given. In the second line, $H$ integers which represent elements in the binary heap are given in order of node id (from $1$ to $H$).
Output
Print values of nodes in the max-heap in order of their id (from $1$ to $H$). Print a single space character before each value.
Example
Input
10
4 1 3 2 16 9 10 14 8 7
Output
16 14 10 8 7 9 3 2 4 1 | instruction | 0 | 81,676 | 12 | 163,352 |
"Correct Solution:
```
import pprint as pp
class Main():
def exchange(self, n1, n2):
tmp = self.A[n1]
self.A[n1] = self.A[n2]
self.A[n2] = tmp
def left(self, i):
return i * 2
def right(self, i):
return i * 2 + 1
def maxHeapify(self, i):
l = self.left(i)
r = self.right(i)
if l <= self.H and self.A[l] > self.A[i]:
largest = l
else :
largest = i
if r <= self.H and self.A[r] > self.A[largest]:
largest = r
if largest != i:
self.exchange(i, largest)
self.maxHeapify(largest) # 再帰的に呼び出し
def buildMaxHeap(self):
for i in reversed( range(1, self.H//2 + 1) ):
self.maxHeapify(i)
def main(self):
self.H = int( input() )
self.A = [0]
inputData = [int(x) for x in input().split()]
self.A.extend(inputData)
self.buildMaxHeap()
for i in range(1, self.H+1):
print(" " + str(self.A[i]), end = "" )
print()
if __name__ == '__main__':
M = Main()
M.main()
``` | output | 1 | 81,676 | 12 | 163,353 |
Provide a correct Python 3 solution for this coding contest problem.
A binary heap which satisfies max-heap property is called max-heap. In a max-heap, for every node $i$ other than the root, $A[i] \leq A[parent(i)]$, that is, the value of a node is at most the value of its parent. The largest element in a max-heap is stored at the root, and the subtree rooted at a node contains values no larger than that contained at the node itself.
Here is an example of a max-heap.
<image>
Write a program which reads an array and constructs a max-heap from the array based on the following pseudo code.
$maxHeapify(A, i)$ move the value of $A[i]$ down to leaves to make a sub-tree of node $i$ a max-heap. Here, $H$ is the size of the heap.
1 maxHeapify(A, i)
2 l = left(i)
3 r = right(i)
4 // select the node which has the maximum value
5 if l ≤ H and A[l] > A[i]
6 largest = l
7 else
8 largest = i
9 if r ≤ H and A[r] > A[largest]
10 largest = r
11
12 if largest ≠ i // value of children is larger than that of i
13 swap A[i] and A[largest]
14 maxHeapify(A, largest) // call recursively
The following procedure buildMaxHeap(A) makes $A$ a max-heap by performing maxHeapify in a bottom-up manner.
1 buildMaxHeap(A)
2 for i = H/2 downto 1
3 maxHeapify(A, i)
Input
In the first line, an integer $H$ is given. In the second line, $H$ integers which represent elements in the binary heap are given in order of node id (from $1$ to $H$).
Output
Print values of nodes in the max-heap in order of their id (from $1$ to $H$). Print a single space character before each value.
Example
Input
10
4 1 3 2 16 9 10 14 8 7
Output
16 14 10 8 7 9 3 2 4 1 | instruction | 0 | 81,677 | 12 | 163,354 |
"Correct Solution:
```
def parent(i):
return i // 2
def left(i):
return 2 * i
def right(i):
return 2 * i + 1
def max_heapify(i):
global A
l = left(i)
r = right(i)
if l <= H and A[l] > A[i]:
largest = l
else:
largest = i
if r <= H and A[r] > A[largest]:
largest = r
if largest != i: # iが子供に降るときは、
A[i], A[largest] = A[largest], A[i]
max_heapify(largest) # ここでいうlargestは、元々はiの子ノード。戦いに敗れたA[i]が格納されている。
H = int(input())
A = [None] * (H + 1)
_ = list(map(int, input().split()))
A[1:] = _
for i in range(H//2, 0, -1):
# print(i)
max_heapify(i)
print(' ' + ' '.join(map(str, A[1:])))
``` | output | 1 | 81,677 | 12 | 163,355 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.