message stringlengths 2 433k | message_type stringclasses 2
values | message_id int64 0 1 | conversation_id int64 113 108k | cluster float64 12 12 | __index_level_0__ int64 226 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Ashish has an array a of size n.
A subsequence of a is defined as a sequence that can be obtained from a by deleting some elements (possibly none), without changing the order of the remaining elements.
Consider a subsequence s of a. He defines the cost of s as the minimum between:
* The maximum among all elements at odd indices of s.
* The maximum among all elements at even indices of s.
Note that the index of an element is its index in s, rather than its index in a. The positions are numbered from 1. So, the cost of s is equal to min(max(s_1, s_3, s_5, …), max(s_2, s_4, s_6, …)).
For example, the cost of \{7, 5, 6\} is min( max(7, 6), max(5) ) = min(7, 5) = 5.
Help him find the minimum cost of a subsequence of size k.
Input
The first line contains two integers n and k (2 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the size of the array a and the size of the subsequence.
The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the elements of the array a.
Output
Output a single integer — the minimum cost of a subsequence of size k.
Examples
Input
4 2
1 2 3 4
Output
1
Input
4 3
1 2 3 4
Output
2
Input
5 3
5 3 4 2 6
Output
2
Input
6 4
5 3 50 2 4 5
Output
3
Note
In the first test, consider the subsequence s = \{1, 3\}. Here the cost is equal to min(max(1), max(3)) = 1.
In the second test, consider the subsequence s = \{1, 2, 4\}. Here the cost is equal to min(max(1, 4), max(2)) = 2.
In the fourth test, consider the subsequence s = \{3, 50, 2, 4\}. Here the cost is equal to min(max(3, 2), max(50, 4)) = 3. | instruction | 0 | 46,432 | 12 | 92,864 |
Tags: binary search, dp, dsu, greedy, implementation
Correct Solution:
```
def fun(mid):
global ar,k
cur1=0
cur2=0
for i in ar:
if(i<=mid or cur1%2==0):
cur1+=1
if(i<=mid or cur2%2!=0):
cur2+=1
f1=bool(cur1>=k)
f2=bool(cur2>=k)
return (f1 or f2)
n,k=map(int,input().split())
ar=list(map(int,input().split()))
l=0
r=max(ar)
while(l<r):
mid=(l+r)//2
if(fun(mid)):
r=mid
else:
l=mid+1
print(l)
``` | output | 1 | 46,432 | 12 | 92,865 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ashish has an array a of size n.
A subsequence of a is defined as a sequence that can be obtained from a by deleting some elements (possibly none), without changing the order of the remaining elements.
Consider a subsequence s of a. He defines the cost of s as the minimum between:
* The maximum among all elements at odd indices of s.
* The maximum among all elements at even indices of s.
Note that the index of an element is its index in s, rather than its index in a. The positions are numbered from 1. So, the cost of s is equal to min(max(s_1, s_3, s_5, …), max(s_2, s_4, s_6, …)).
For example, the cost of \{7, 5, 6\} is min( max(7, 6), max(5) ) = min(7, 5) = 5.
Help him find the minimum cost of a subsequence of size k.
Input
The first line contains two integers n and k (2 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the size of the array a and the size of the subsequence.
The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the elements of the array a.
Output
Output a single integer — the minimum cost of a subsequence of size k.
Examples
Input
4 2
1 2 3 4
Output
1
Input
4 3
1 2 3 4
Output
2
Input
5 3
5 3 4 2 6
Output
2
Input
6 4
5 3 50 2 4 5
Output
3
Note
In the first test, consider the subsequence s = \{1, 3\}. Here the cost is equal to min(max(1), max(3)) = 1.
In the second test, consider the subsequence s = \{1, 2, 4\}. Here the cost is equal to min(max(1, 4), max(2)) = 2.
In the fourth test, consider the subsequence s = \{3, 50, 2, 4\}. Here the cost is equal to min(max(3, 2), max(50, 4)) = 3. | instruction | 0 | 46,433 | 12 | 92,866 |
Tags: binary search, dp, dsu, greedy, implementation
Correct Solution:
```
# https://codeforces.com/contest/1370/problem/D
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
# do magic here
n, k = map(int, input().split())
arr = [int(x) for x in input().split()]
low = min(arr)
high = max(arr)
def check(mid):
# for odd
subseq1, subseq2 = [], []
for item in arr:
if (len(subseq1)+1) & 1:
if item <= mid:
subseq1.append(item)
else:
subseq1.append(item)
for item in arr:
if (len(subseq2)+1) & 1:
subseq2.append(item)
else:
if item <= mid:
subseq2.append(item)
return (len(subseq1) >= k or len(subseq2)>=k)
while low < high:
mid = (low+high)//2
if check(mid):
high = mid
else:
low = mid+1
print(low)
``` | output | 1 | 46,433 | 12 | 92,867 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ashish has an array a of size n.
A subsequence of a is defined as a sequence that can be obtained from a by deleting some elements (possibly none), without changing the order of the remaining elements.
Consider a subsequence s of a. He defines the cost of s as the minimum between:
* The maximum among all elements at odd indices of s.
* The maximum among all elements at even indices of s.
Note that the index of an element is its index in s, rather than its index in a. The positions are numbered from 1. So, the cost of s is equal to min(max(s_1, s_3, s_5, …), max(s_2, s_4, s_6, …)).
For example, the cost of \{7, 5, 6\} is min( max(7, 6), max(5) ) = min(7, 5) = 5.
Help him find the minimum cost of a subsequence of size k.
Input
The first line contains two integers n and k (2 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the size of the array a and the size of the subsequence.
The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the elements of the array a.
Output
Output a single integer — the minimum cost of a subsequence of size k.
Examples
Input
4 2
1 2 3 4
Output
1
Input
4 3
1 2 3 4
Output
2
Input
5 3
5 3 4 2 6
Output
2
Input
6 4
5 3 50 2 4 5
Output
3
Note
In the first test, consider the subsequence s = \{1, 3\}. Here the cost is equal to min(max(1), max(3)) = 1.
In the second test, consider the subsequence s = \{1, 2, 4\}. Here the cost is equal to min(max(1, 4), max(2)) = 2.
In the fourth test, consider the subsequence s = \{3, 50, 2, 4\}. Here the cost is equal to min(max(3, 2), max(50, 4)) = 3. | instruction | 0 | 46,434 | 12 | 92,868 |
Tags: binary search, dp, dsu, greedy, implementation
Correct Solution:
```
import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7
def bisearch_min(mn, mx, func):
ok = mx
ng = mn
while ng+1 < ok:
mid = (ok+ng) // 2
if func(mid):
ok = mid
else:
ng = mid
return ok
def check(m):
cnt1 = 0
cnt2 = 0
i = 0
while i < N:
if A[i] <= m:
cnt1 += 1
i += 1
if i < N:
cnt2 += 1
i += 1
else:
i += 1
cnt3 = 0
cnt4 = 1
i = 1
while i < N:
if A[i] <= m:
cnt3 += 1
i += 1
if i < N:
cnt4 += 1
i += 1
else:
i += 1
return (cnt1 >= ceil(K, 2) and cnt1+cnt2 >= K) or (cnt3 >= K // 2 and cnt3+cnt4 >= K)
N, K = MAP()
A = LIST()
res = bisearch_min(0, 10**9+1, check)
print(res)
``` | output | 1 | 46,434 | 12 | 92,869 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ashish has an array a of size n.
A subsequence of a is defined as a sequence that can be obtained from a by deleting some elements (possibly none), without changing the order of the remaining elements.
Consider a subsequence s of a. He defines the cost of s as the minimum between:
* The maximum among all elements at odd indices of s.
* The maximum among all elements at even indices of s.
Note that the index of an element is its index in s, rather than its index in a. The positions are numbered from 1. So, the cost of s is equal to min(max(s_1, s_3, s_5, …), max(s_2, s_4, s_6, …)).
For example, the cost of \{7, 5, 6\} is min( max(7, 6), max(5) ) = min(7, 5) = 5.
Help him find the minimum cost of a subsequence of size k.
Input
The first line contains two integers n and k (2 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the size of the array a and the size of the subsequence.
The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the elements of the array a.
Output
Output a single integer — the minimum cost of a subsequence of size k.
Examples
Input
4 2
1 2 3 4
Output
1
Input
4 3
1 2 3 4
Output
2
Input
5 3
5 3 4 2 6
Output
2
Input
6 4
5 3 50 2 4 5
Output
3
Note
In the first test, consider the subsequence s = \{1, 3\}. Here the cost is equal to min(max(1), max(3)) = 1.
In the second test, consider the subsequence s = \{1, 2, 4\}. Here the cost is equal to min(max(1, 4), max(2)) = 2.
In the fourth test, consider the subsequence s = \{3, 50, 2, 4\}. Here the cost is equal to min(max(3, 2), max(50, 4)) = 3. | instruction | 0 | 46,435 | 12 | 92,870 |
Tags: binary search, dp, dsu, greedy, implementation
Correct Solution:
```
def check(x, fl):
global n, a, k
cur = []
for i in range(n):
if (len(cur) + 1) % 2 == fl and a[i] <= x:
cur += [a[i]]
elif (len(cur) + 1) % 2 != fl:
cur += [a[i]]
return (len(cur) >= k)
def Bin():
l = 1
r = int(1e9)
while l < r:
mid = (l + r) // 2
if check(mid, 0) or check(mid, 1):
r = mid
else:
l = mid + 1
return l
n, k = map(int, input().split())
a = list(map(int, input().split()))
print(Bin())
``` | output | 1 | 46,435 | 12 | 92,871 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ashish has an array a of size n.
A subsequence of a is defined as a sequence that can be obtained from a by deleting some elements (possibly none), without changing the order of the remaining elements.
Consider a subsequence s of a. He defines the cost of s as the minimum between:
* The maximum among all elements at odd indices of s.
* The maximum among all elements at even indices of s.
Note that the index of an element is its index in s, rather than its index in a. The positions are numbered from 1. So, the cost of s is equal to min(max(s_1, s_3, s_5, …), max(s_2, s_4, s_6, …)).
For example, the cost of \{7, 5, 6\} is min( max(7, 6), max(5) ) = min(7, 5) = 5.
Help him find the minimum cost of a subsequence of size k.
Input
The first line contains two integers n and k (2 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the size of the array a and the size of the subsequence.
The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the elements of the array a.
Output
Output a single integer — the minimum cost of a subsequence of size k.
Examples
Input
4 2
1 2 3 4
Output
1
Input
4 3
1 2 3 4
Output
2
Input
5 3
5 3 4 2 6
Output
2
Input
6 4
5 3 50 2 4 5
Output
3
Note
In the first test, consider the subsequence s = \{1, 3\}. Here the cost is equal to min(max(1), max(3)) = 1.
In the second test, consider the subsequence s = \{1, 2, 4\}. Here the cost is equal to min(max(1, 4), max(2)) = 2.
In the fourth test, consider the subsequence s = \{3, 50, 2, 4\}. Here the cost is equal to min(max(3, 2), max(50, 4)) = 3. | instruction | 0 | 46,436 | 12 | 92,872 |
Tags: binary search, dp, dsu, greedy, implementation
Correct Solution:
```
import sys
from collections import defaultdict as dd
from collections import Counter as cc
from queue import Queue
import math
import itertools
try:
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
except:
pass
input = lambda: sys.stdin.buffer.readline().rstrip()
n,k=map(int,input().split())
a=list(map(int,input().split()))
def z(s,m):
c=0
for i in range(n):
if s or a[i]<=m:
s^=1
c+=1
return c>=k
q=1
w=max(a)
while q<w:
m=(q+w)//2
if z(0,m) or z(1,m):
w=m
else:
q=m+1
print(q)
``` | output | 1 | 46,436 | 12 | 92,873 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ashish has an array a of size n.
A subsequence of a is defined as a sequence that can be obtained from a by deleting some elements (possibly none), without changing the order of the remaining elements.
Consider a subsequence s of a. He defines the cost of s as the minimum between:
* The maximum among all elements at odd indices of s.
* The maximum among all elements at even indices of s.
Note that the index of an element is its index in s, rather than its index in a. The positions are numbered from 1. So, the cost of s is equal to min(max(s_1, s_3, s_5, …), max(s_2, s_4, s_6, …)).
For example, the cost of \{7, 5, 6\} is min( max(7, 6), max(5) ) = min(7, 5) = 5.
Help him find the minimum cost of a subsequence of size k.
Input
The first line contains two integers n and k (2 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the size of the array a and the size of the subsequence.
The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the elements of the array a.
Output
Output a single integer — the minimum cost of a subsequence of size k.
Examples
Input
4 2
1 2 3 4
Output
1
Input
4 3
1 2 3 4
Output
2
Input
5 3
5 3 4 2 6
Output
2
Input
6 4
5 3 50 2 4 5
Output
3
Note
In the first test, consider the subsequence s = \{1, 3\}. Here the cost is equal to min(max(1), max(3)) = 1.
In the second test, consider the subsequence s = \{1, 2, 4\}. Here the cost is equal to min(max(1, 4), max(2)) = 2.
In the fourth test, consider the subsequence s = \{3, 50, 2, 4\}. Here the cost is equal to min(max(3, 2), max(50, 4)) = 3. | instruction | 0 | 46,437 | 12 | 92,874 |
Tags: binary search, dp, dsu, greedy, implementation
Correct Solution:
```
import sys
n,k = 0,0
ans = 1000000000
a = []
def ok(mid):
for i in [0,1] :
l = 0
for val in a :
if l % 2 != i or val <= mid :
l += 1
if l >= k :
return True
return False
def solve():
# code goes here!!
global n,k
global a
global ans
n,k = map(int,input().split())
a = list(map(int,input().split()))
lo = 1
hi = max(a[0:])
while lo <= hi :
mid = int((lo + hi) / 2)
if ok(mid) :
ans = mid
hi = mid - 1
else :
lo = mid + 1
print(ans)
def main():
# comment when submit.
#sys.stdin = open("test.inp","r")
solve()
if __name__ == '__main__':
main()
``` | output | 1 | 46,437 | 12 | 92,875 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ashish has an array a of size n.
A subsequence of a is defined as a sequence that can be obtained from a by deleting some elements (possibly none), without changing the order of the remaining elements.
Consider a subsequence s of a. He defines the cost of s as the minimum between:
* The maximum among all elements at odd indices of s.
* The maximum among all elements at even indices of s.
Note that the index of an element is its index in s, rather than its index in a. The positions are numbered from 1. So, the cost of s is equal to min(max(s_1, s_3, s_5, …), max(s_2, s_4, s_6, …)).
For example, the cost of \{7, 5, 6\} is min( max(7, 6), max(5) ) = min(7, 5) = 5.
Help him find the minimum cost of a subsequence of size k.
Input
The first line contains two integers n and k (2 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the size of the array a and the size of the subsequence.
The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the elements of the array a.
Output
Output a single integer — the minimum cost of a subsequence of size k.
Examples
Input
4 2
1 2 3 4
Output
1
Input
4 3
1 2 3 4
Output
2
Input
5 3
5 3 4 2 6
Output
2
Input
6 4
5 3 50 2 4 5
Output
3
Note
In the first test, consider the subsequence s = \{1, 3\}. Here the cost is equal to min(max(1), max(3)) = 1.
In the second test, consider the subsequence s = \{1, 2, 4\}. Here the cost is equal to min(max(1, 4), max(2)) = 2.
In the fourth test, consider the subsequence s = \{3, 50, 2, 4\}. Here the cost is equal to min(max(3, 2), max(50, 4)) = 3. | instruction | 0 | 46,438 | 12 | 92,876 |
Tags: binary search, dp, dsu, greedy, implementation
Correct Solution:
```
n,k=map(int,input().split())
a=list(map(int,input().split()))
def f(x):
global n,k,a
#x以下にできるか(こっちは奇数番目)
check=0
now=1
for i in range(n):
if now:
if a[i]<=x:
now=1-now
check+=1
else:
now=1-now
check+=1
if check>=k:
#print(check)
return True
#偶数番目
check=0
now=0
for i in range(n):
if now:
if a[i]<=x:
now=1-now
check+=1
else:
now=1-now
check+=1
if check>=k:
#print(check)
return True
else:
#print(check)
return False
l,r=0,10**9+1
#最小値を求める
while l+1<r:
m=l+(r-l)//2
#print(f(m))
if f(m):
r=m
else:
l=m
print(r)
``` | output | 1 | 46,438 | 12 | 92,877 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Ashish has an array a of size n.
A subsequence of a is defined as a sequence that can be obtained from a by deleting some elements (possibly none), without changing the order of the remaining elements.
Consider a subsequence s of a. He defines the cost of s as the minimum between:
* The maximum among all elements at odd indices of s.
* The maximum among all elements at even indices of s.
Note that the index of an element is its index in s, rather than its index in a. The positions are numbered from 1. So, the cost of s is equal to min(max(s_1, s_3, s_5, …), max(s_2, s_4, s_6, …)).
For example, the cost of \{7, 5, 6\} is min( max(7, 6), max(5) ) = min(7, 5) = 5.
Help him find the minimum cost of a subsequence of size k.
Input
The first line contains two integers n and k (2 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the size of the array a and the size of the subsequence.
The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the elements of the array a.
Output
Output a single integer — the minimum cost of a subsequence of size k.
Examples
Input
4 2
1 2 3 4
Output
1
Input
4 3
1 2 3 4
Output
2
Input
5 3
5 3 4 2 6
Output
2
Input
6 4
5 3 50 2 4 5
Output
3
Note
In the first test, consider the subsequence s = \{1, 3\}. Here the cost is equal to min(max(1), max(3)) = 1.
In the second test, consider the subsequence s = \{1, 2, 4\}. Here the cost is equal to min(max(1, 4), max(2)) = 2.
In the fourth test, consider the subsequence s = \{3, 50, 2, 4\}. Here the cost is equal to min(max(3, 2), max(50, 4)) = 3. | instruction | 0 | 46,439 | 12 | 92,878 |
Tags: binary search, dp, dsu, greedy, implementation
Correct Solution:
```
l = lambda:map(int,input().split())
n,k = l()
a = list(l())
def check(x,cur):
ans = 0
for i in range(n):
if cur == 0:
ans+=1
cur = 1
elif a[i] <= x:
ans+=1
cur = 0
return ans >= k
lo = 1
hi = int(1e9)
while lo < hi:
mid = (lo + hi) // 2
if check(mid, 0) or check(mid, 1):
hi = mid
else:
lo = mid + 1
print(lo)
``` | output | 1 | 46,439 | 12 | 92,879 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ashish has an array a of size n.
A subsequence of a is defined as a sequence that can be obtained from a by deleting some elements (possibly none), without changing the order of the remaining elements.
Consider a subsequence s of a. He defines the cost of s as the minimum between:
* The maximum among all elements at odd indices of s.
* The maximum among all elements at even indices of s.
Note that the index of an element is its index in s, rather than its index in a. The positions are numbered from 1. So, the cost of s is equal to min(max(s_1, s_3, s_5, …), max(s_2, s_4, s_6, …)).
For example, the cost of \{7, 5, 6\} is min( max(7, 6), max(5) ) = min(7, 5) = 5.
Help him find the minimum cost of a subsequence of size k.
Input
The first line contains two integers n and k (2 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the size of the array a and the size of the subsequence.
The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the elements of the array a.
Output
Output a single integer — the minimum cost of a subsequence of size k.
Examples
Input
4 2
1 2 3 4
Output
1
Input
4 3
1 2 3 4
Output
2
Input
5 3
5 3 4 2 6
Output
2
Input
6 4
5 3 50 2 4 5
Output
3
Note
In the first test, consider the subsequence s = \{1, 3\}. Here the cost is equal to min(max(1), max(3)) = 1.
In the second test, consider the subsequence s = \{1, 2, 4\}. Here the cost is equal to min(max(1, 4), max(2)) = 2.
In the fourth test, consider the subsequence s = \{3, 50, 2, 4\}. Here the cost is equal to min(max(3, 2), max(50, 4)) = 3.
Submitted Solution:
```
n,k = map(int,input().split());arr = list(map(int,input().split()))
def done(x,s):
c=0
for i in range(len(arr)):
if s or (arr[i] <=x):c+=1;s=s^1
return c >=k
lb=1
rb=max(arr)
ans=rb
while ( lb<rb):
mid= (lb+rb) // 2
if done(mid,0) or done(mid,1):
rb=mid
ans=min(ans,mid)
else:
lb=mid+1
print(ans)
``` | instruction | 0 | 46,440 | 12 | 92,880 |
Yes | output | 1 | 46,440 | 12 | 92,881 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ashish has an array a of size n.
A subsequence of a is defined as a sequence that can be obtained from a by deleting some elements (possibly none), without changing the order of the remaining elements.
Consider a subsequence s of a. He defines the cost of s as the minimum between:
* The maximum among all elements at odd indices of s.
* The maximum among all elements at even indices of s.
Note that the index of an element is its index in s, rather than its index in a. The positions are numbered from 1. So, the cost of s is equal to min(max(s_1, s_3, s_5, …), max(s_2, s_4, s_6, …)).
For example, the cost of \{7, 5, 6\} is min( max(7, 6), max(5) ) = min(7, 5) = 5.
Help him find the minimum cost of a subsequence of size k.
Input
The first line contains two integers n and k (2 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the size of the array a and the size of the subsequence.
The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the elements of the array a.
Output
Output a single integer — the minimum cost of a subsequence of size k.
Examples
Input
4 2
1 2 3 4
Output
1
Input
4 3
1 2 3 4
Output
2
Input
5 3
5 3 4 2 6
Output
2
Input
6 4
5 3 50 2 4 5
Output
3
Note
In the first test, consider the subsequence s = \{1, 3\}. Here the cost is equal to min(max(1), max(3)) = 1.
In the second test, consider the subsequence s = \{1, 2, 4\}. Here the cost is equal to min(max(1, 4), max(2)) = 2.
In the fourth test, consider the subsequence s = \{3, 50, 2, 4\}. Here the cost is equal to min(max(3, 2), max(50, 4)) = 3.
Submitted Solution:
```
import sys
input = sys.stdin.readline
inputr = lambda: input().rstrip('\n')
INF = 10 ** 18
n, k = map(int, input().split())
A = list(map(int, input().split()))
if k == 1:
print(min(A))
sys.exit(0)
need = k // 2
def test(V, takeo):
g = 0
o = 0
for v in A:
if takeo:
o += 1
takeo = False
elif v <= V:
g += 1
takeo = True
if o + g == k:
return True
return False
SA = sorted(set(A))
lo = 0
hi = len(SA)
best = INF
while lo < hi:
m = (lo + hi) // 2
V = SA[m]
if test(V, False) or test(V, True):
best = min(best, V)
hi = m
else:
lo = m + 1
print(best)
``` | instruction | 0 | 46,441 | 12 | 92,882 |
Yes | output | 1 | 46,441 | 12 | 92,883 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ashish has an array a of size n.
A subsequence of a is defined as a sequence that can be obtained from a by deleting some elements (possibly none), without changing the order of the remaining elements.
Consider a subsequence s of a. He defines the cost of s as the minimum between:
* The maximum among all elements at odd indices of s.
* The maximum among all elements at even indices of s.
Note that the index of an element is its index in s, rather than its index in a. The positions are numbered from 1. So, the cost of s is equal to min(max(s_1, s_3, s_5, …), max(s_2, s_4, s_6, …)).
For example, the cost of \{7, 5, 6\} is min( max(7, 6), max(5) ) = min(7, 5) = 5.
Help him find the minimum cost of a subsequence of size k.
Input
The first line contains two integers n and k (2 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the size of the array a and the size of the subsequence.
The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the elements of the array a.
Output
Output a single integer — the minimum cost of a subsequence of size k.
Examples
Input
4 2
1 2 3 4
Output
1
Input
4 3
1 2 3 4
Output
2
Input
5 3
5 3 4 2 6
Output
2
Input
6 4
5 3 50 2 4 5
Output
3
Note
In the first test, consider the subsequence s = \{1, 3\}. Here the cost is equal to min(max(1), max(3)) = 1.
In the second test, consider the subsequence s = \{1, 2, 4\}. Here the cost is equal to min(max(1, 4), max(2)) = 2.
In the fourth test, consider the subsequence s = \{3, 50, 2, 4\}. Here the cost is equal to min(max(3, 2), max(50, 4)) = 3.
Submitted Solution:
```
#author: riyan
def ss_length(arr, x, k, oe):
l = 0
for i in range(len(arr)):
if oe:
if arr[i] <= x:
l += 1
oe ^= 1
else:
l += 1
oe ^= 1
return (l >= k)
def bin_search(arr, li, hi, k):
if li >= hi:
return li
mi = (li + hi) // 2
ss_len_check = ss_length(arr, mi, k, 0) or ss_length(arr, mi, k, 1)
if ss_len_check:
return bin_search(arr, li, mi, k)
else:
return bin_search(arr, mi + 1, hi, k)
if __name__ == '__main__':
n, k = map(int, input().strip().split())
arr = list(map(int, input().strip().split()))
ans = bin_search(arr, 1, int(1e9), k)
print(ans)
``` | instruction | 0 | 46,442 | 12 | 92,884 |
Yes | output | 1 | 46,442 | 12 | 92,885 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ashish has an array a of size n.
A subsequence of a is defined as a sequence that can be obtained from a by deleting some elements (possibly none), without changing the order of the remaining elements.
Consider a subsequence s of a. He defines the cost of s as the minimum between:
* The maximum among all elements at odd indices of s.
* The maximum among all elements at even indices of s.
Note that the index of an element is its index in s, rather than its index in a. The positions are numbered from 1. So, the cost of s is equal to min(max(s_1, s_3, s_5, …), max(s_2, s_4, s_6, …)).
For example, the cost of \{7, 5, 6\} is min( max(7, 6), max(5) ) = min(7, 5) = 5.
Help him find the minimum cost of a subsequence of size k.
Input
The first line contains two integers n and k (2 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the size of the array a and the size of the subsequence.
The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the elements of the array a.
Output
Output a single integer — the minimum cost of a subsequence of size k.
Examples
Input
4 2
1 2 3 4
Output
1
Input
4 3
1 2 3 4
Output
2
Input
5 3
5 3 4 2 6
Output
2
Input
6 4
5 3 50 2 4 5
Output
3
Note
In the first test, consider the subsequence s = \{1, 3\}. Here the cost is equal to min(max(1), max(3)) = 1.
In the second test, consider the subsequence s = \{1, 2, 4\}. Here the cost is equal to min(max(1, 4), max(2)) = 2.
In the fourth test, consider the subsequence s = \{3, 50, 2, 4\}. Here the cost is equal to min(max(3, 2), max(50, 4)) = 3.
Submitted Solution:
```
def checker(mid,start):
odd=False
even=False
if start==1:
odd=True
else:
even=True
count,ind,ok=0,start,False
for i in range(n):
if odd==True:
if count%2==0:
if a[i]<=mid:
count+=1
else:
count+=1
if even==True:
if count%2==1:
if a[i]<=mid:
count+=1
else:
count+=1
if count>=k:
return(True)
return(False)
n,k=map(int,input().split())
a=[int(i) for i in input().split()]
lo=0
hi=10**9
while lo<hi-1:
mid=(lo+hi)//2
if checker(mid,1) or checker(mid,0):
hi=mid
else:
lo=mid
print(hi)
``` | instruction | 0 | 46,443 | 12 | 92,886 |
Yes | output | 1 | 46,443 | 12 | 92,887 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ashish has an array a of size n.
A subsequence of a is defined as a sequence that can be obtained from a by deleting some elements (possibly none), without changing the order of the remaining elements.
Consider a subsequence s of a. He defines the cost of s as the minimum between:
* The maximum among all elements at odd indices of s.
* The maximum among all elements at even indices of s.
Note that the index of an element is its index in s, rather than its index in a. The positions are numbered from 1. So, the cost of s is equal to min(max(s_1, s_3, s_5, …), max(s_2, s_4, s_6, …)).
For example, the cost of \{7, 5, 6\} is min( max(7, 6), max(5) ) = min(7, 5) = 5.
Help him find the minimum cost of a subsequence of size k.
Input
The first line contains two integers n and k (2 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the size of the array a and the size of the subsequence.
The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the elements of the array a.
Output
Output a single integer — the minimum cost of a subsequence of size k.
Examples
Input
4 2
1 2 3 4
Output
1
Input
4 3
1 2 3 4
Output
2
Input
5 3
5 3 4 2 6
Output
2
Input
6 4
5 3 50 2 4 5
Output
3
Note
In the first test, consider the subsequence s = \{1, 3\}. Here the cost is equal to min(max(1), max(3)) = 1.
In the second test, consider the subsequence s = \{1, 2, 4\}. Here the cost is equal to min(max(1, 4), max(2)) = 2.
In the fourth test, consider the subsequence s = \{3, 50, 2, 4\}. Here the cost is equal to min(max(3, 2), max(50, 4)) = 3.
Submitted Solution:
```
import sys
def rl(): return sys.stdin.readline().strip()
n,k = map(int,rl().split())
a = [float('inf')]+[int(x) for x in rl().split()]+[float('inf')]
asort = sorted(a)
index = k//2
while True:
subs = []
aedit = a.copy()
for i in range(index-1,-1,-1):
val = asort[i]
if val in aedit:
subs.append(val)
point = aedit.index(val)
aedit[point] = float('inf')
aedit[point-1] = float('inf')
aedit[point+1] = float('inf')
if k % 2 == 1 and ((len(subs) == k//2 and a[1] not in subs and a[-2] not in subs) or len(subs) == k//2 + 1):
print(subs)
print(asort[index-1])
break
elif k % 2 == 0 and len(subs) == k//2 and (a[1] not in subs or a[-2] not in subs):
print(subs)
print(asort[index - 1])
break
else:
index += 1
``` | instruction | 0 | 46,444 | 12 | 92,888 |
No | output | 1 | 46,444 | 12 | 92,889 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ashish has an array a of size n.
A subsequence of a is defined as a sequence that can be obtained from a by deleting some elements (possibly none), without changing the order of the remaining elements.
Consider a subsequence s of a. He defines the cost of s as the minimum between:
* The maximum among all elements at odd indices of s.
* The maximum among all elements at even indices of s.
Note that the index of an element is its index in s, rather than its index in a. The positions are numbered from 1. So, the cost of s is equal to min(max(s_1, s_3, s_5, …), max(s_2, s_4, s_6, …)).
For example, the cost of \{7, 5, 6\} is min( max(7, 6), max(5) ) = min(7, 5) = 5.
Help him find the minimum cost of a subsequence of size k.
Input
The first line contains two integers n and k (2 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the size of the array a and the size of the subsequence.
The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the elements of the array a.
Output
Output a single integer — the minimum cost of a subsequence of size k.
Examples
Input
4 2
1 2 3 4
Output
1
Input
4 3
1 2 3 4
Output
2
Input
5 3
5 3 4 2 6
Output
2
Input
6 4
5 3 50 2 4 5
Output
3
Note
In the first test, consider the subsequence s = \{1, 3\}. Here the cost is equal to min(max(1), max(3)) = 1.
In the second test, consider the subsequence s = \{1, 2, 4\}. Here the cost is equal to min(max(1, 4), max(2)) = 2.
In the fourth test, consider the subsequence s = \{3, 50, 2, 4\}. Here the cost is equal to min(max(3, 2), max(50, 4)) = 3.
Submitted Solution:
```
'''
dekh ans binary search krke nikal
fir dekh agr jo subsequence liye hai unme sare even palces ka max bhi tere nikale
ans se min hai ya sare odd places ka max b tere nikale ans se min hai to ye ans
ho skta hai , thik ar agr ho skta hai to ar chota try kr ar jo sbse chota mila wo
ans return kr (dp try kia tha pr problem ye huyi ki wo 4d ja rha tha)
'''
def check(a,pos):
u=0
if pos==0:
for i in range(n):
if i%2==0:
u+=1
else:
if t[i]<=a:
u+=1
else:
break
else:
for i in range(n):
if i%2!=0:
u+=1
else:
if t[i]<=a:
u+=1
else:
break
if u>=k:
return 1
else:
return 0
def bina(l,r):
while l<r:
m = l+(r-l)//2
if check(m,0)|check(m,1):
r= m
else:
l=m+1
return l
import sys
input = sys.stdin.readline
n,k = map(int,input().split())
t = list(map(int,input().split()))
print(bina(1,1000000000))
``` | instruction | 0 | 46,445 | 12 | 92,890 |
No | output | 1 | 46,445 | 12 | 92,891 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ashish has an array a of size n.
A subsequence of a is defined as a sequence that can be obtained from a by deleting some elements (possibly none), without changing the order of the remaining elements.
Consider a subsequence s of a. He defines the cost of s as the minimum between:
* The maximum among all elements at odd indices of s.
* The maximum among all elements at even indices of s.
Note that the index of an element is its index in s, rather than its index in a. The positions are numbered from 1. So, the cost of s is equal to min(max(s_1, s_3, s_5, …), max(s_2, s_4, s_6, …)).
For example, the cost of \{7, 5, 6\} is min( max(7, 6), max(5) ) = min(7, 5) = 5.
Help him find the minimum cost of a subsequence of size k.
Input
The first line contains two integers n and k (2 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the size of the array a and the size of the subsequence.
The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the elements of the array a.
Output
Output a single integer — the minimum cost of a subsequence of size k.
Examples
Input
4 2
1 2 3 4
Output
1
Input
4 3
1 2 3 4
Output
2
Input
5 3
5 3 4 2 6
Output
2
Input
6 4
5 3 50 2 4 5
Output
3
Note
In the first test, consider the subsequence s = \{1, 3\}. Here the cost is equal to min(max(1), max(3)) = 1.
In the second test, consider the subsequence s = \{1, 2, 4\}. Here the cost is equal to min(max(1, 4), max(2)) = 2.
In the fourth test, consider the subsequence s = \{3, 50, 2, 4\}. Here the cost is equal to min(max(3, 2), max(50, 4)) = 3.
Submitted Solution:
```
def check(m, l):
c = 0
for i in range(n):
if a[i] <= m or i % 2 != l:
c = c + 1
if c == s:
return True
return False
n, s = list(map(int, input().split(' ')))
a = list(map(int, input().split(' ')))
m1, m2 = min(a), max(a)
while m1 < m2:
c = (m1 + m2) // 2
if check(c, 0) or check(c, 1):
r = c
m2 = c
else:
m1 = c + 1
print(r)
``` | instruction | 0 | 46,446 | 12 | 92,892 |
No | output | 1 | 46,446 | 12 | 92,893 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ashish has an array a of size n.
A subsequence of a is defined as a sequence that can be obtained from a by deleting some elements (possibly none), without changing the order of the remaining elements.
Consider a subsequence s of a. He defines the cost of s as the minimum between:
* The maximum among all elements at odd indices of s.
* The maximum among all elements at even indices of s.
Note that the index of an element is its index in s, rather than its index in a. The positions are numbered from 1. So, the cost of s is equal to min(max(s_1, s_3, s_5, …), max(s_2, s_4, s_6, …)).
For example, the cost of \{7, 5, 6\} is min( max(7, 6), max(5) ) = min(7, 5) = 5.
Help him find the minimum cost of a subsequence of size k.
Input
The first line contains two integers n and k (2 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the size of the array a and the size of the subsequence.
The next line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) — the elements of the array a.
Output
Output a single integer — the minimum cost of a subsequence of size k.
Examples
Input
4 2
1 2 3 4
Output
1
Input
4 3
1 2 3 4
Output
2
Input
5 3
5 3 4 2 6
Output
2
Input
6 4
5 3 50 2 4 5
Output
3
Note
In the first test, consider the subsequence s = \{1, 3\}. Here the cost is equal to min(max(1), max(3)) = 1.
In the second test, consider the subsequence s = \{1, 2, 4\}. Here the cost is equal to min(max(1, 4), max(2)) = 2.
In the fourth test, consider the subsequence s = \{3, 50, 2, 4\}. Here the cost is equal to min(max(3, 2), max(50, 4)) = 3.
Submitted Solution:
```
def maxmin(s):
if len(s)==1: return s[0]
return min(max(s[1::2]),max(s[::2]))
_,k = map(int, input().split())
s = list(map(int, input().split()))
temp = 10000000001
if len(s)%k==0:
for i in range(len(s)//k):
temp = min(temp,maxmin(s[i*k:(i+1)*k]))
print(temp)
else:
for i in range(len(s)//k):
temp = min(temp,maxmin(s[i*k:(i+1)*k]))
temp = min(temp,maxmin(s[(i+1)*k:]))
print(temp)
``` | instruction | 0 | 46,447 | 12 | 92,894 |
No | output | 1 | 46,447 | 12 | 92,895 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i ⊕ x (⊕ denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion in the b array is a pair of integers i and j such that 1 ≤ i < j ≤ n and b_i > b_j.
You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x — output the smallest one.
Input
First line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of elements in a.
Second line contains n space-separated integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Output two integers: the minimum possible number of inversions in b, and the minimum possible value of x, which achieves those number of inversions.
Examples
Input
4
0 1 3 2
Output
1 0
Input
9
10 7 9 10 7 5 5 3 5
Output
4 14
Input
3
8 10 3
Output
0 8
Note
In the first sample it is optimal to leave the array as it is by choosing x = 0.
In the second sample the selection of x = 14 results in b: [4, 9, 7, 4, 9, 11, 11, 13, 11]. It has 4 inversions:
* i = 2, j = 3;
* i = 2, j = 4;
* i = 3, j = 4;
* i = 8, j = 9.
In the third sample the selection of x = 8 results in b: [0, 2, 11]. It has no inversions. | instruction | 0 | 46,451 | 12 | 92,902 |
Tags: bitmasks, data structures, divide and conquer, dp, greedy, math, sortings, strings, trees
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
# threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
# sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2 ** 30, func=lambda a, b: min(a, b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (a.get_at(m)[0] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.isEndOfWord = False
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def _charToIndex(self, ch):
return ord(ch) - ord('a')
def insert(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
pCrawl.children[index] = self.getNode()
pCrawl = pCrawl.children[index]
pCrawl.isEndOfWord = True
def search(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
return False
pCrawl = pCrawl.children[index]
return pCrawl != None and pCrawl.isEndOfWord
# -----------------------------------------trie---------------------------------
def merge(arr, temp, left, mid, right):
inv_count = 0
i = left # i is index for left subarray*/
j = mid # i is index for right subarray*/
k = left # i is index for resultant merged subarray*/
while ((i <= mid - 1) and (j <= right)):
if (arr[i] <= arr[j]):
temp[k] = arr[i]
k += 1
i += 1
else:
temp[k] = arr[j]
k += 1
j += 1
inv_count = inv_count + (mid - i)
while (i <= mid - 1):
temp[k] = arr[i]
k += 1
i += 1
while (j <= right):
temp[k] = arr[j]
k += 1
j += 1
# Copy back the merged elements to original array*/
for i in range(left, right + 1, 1):
arr[i] = temp[i]
return inv_count
def _mergeSort(arr, temp, left, right):
inv_count = 0
if (right > left):
mid = int((right + left) / 2)
inv_count = _mergeSort(arr, temp, left, mid)
inv_count += _mergeSort(arr, temp, mid + 1, right)
inv_count += merge(arr, temp, left, mid + 1, right)
return inv_count
def countSwaps(arr, n):
temp = [0 for i in range(n)]
return _mergeSort(arr, temp, 0, n - 1)
#-----------------------------------------adjcent swap required------------------------------
def minSwaps(arr):
n = len(arr)
arrpos = [*enumerate(arr)]
arrpos.sort(key=lambda it: it[1])
vis = {k: False for k in range(n)}
ans = 0
for i in range(n):
if vis[i] or arrpos[i][0] == i:
continue
cycle_size = 0
j = i
while not vis[j]:
vis[j] = True
j = arrpos[j][0]
cycle_size += 1
if cycle_size > 0:
ans += (cycle_size - 1)
return ans
#----------------------swaps required----------------------------
class Node:
def __init__(self, data):
self.data = data
self.count = 0
self.left = None # left node for 0
self.right = None # right node for 1
class BinaryTrie:
def __init__(self):
self.root = Node(0)
def insert(self, pre_xor):
self.temp = self.root
for i in range(31, -1, -1):
val = pre_xor & (1 << i)
if val:
if not self.temp.right:
self.temp.right = Node(0)
self.temp = self.temp.right
self.temp.count += 1
if not val:
if not self.temp.left:
self.temp.left = Node(0)
self.temp = self.temp.left
self.temp.count += 1
self.temp.data = pre_xor
def query(self, xor):
self.temp = self.root
for i in range(31, -1, -1):
val = xor & (1 << i)
if not val:
if self.temp.left and self.temp.left.count > 0:
self.temp = self.temp.left
elif self.temp.right:
self.temp = self.temp.right
else:
if self.temp.right and self.temp.right.count > 0:
self.temp = self.temp.right
elif self.temp.left:
self.temp = self.temp.left
self.temp.count -= 1
return xor ^ self.temp.data
# -------------------------bin trie-------------------------------------------
n=int(input())
l=list(map(int,input().split()))
lis=[l]
x=0
tot=0
for i in range(29,-1,-1):
w=2**i
cur=[]
inv0 = 0
inv1 = 0
for j in lis:
zero=[]
ones=[]
for k in j:
if k&w==0:
inv0+=len(ones)
zero.append(k)
else:
inv1+=len(zero)
ones.append(k)
if zero!=[]:
cur.append(zero)
if ones!=[]:
cur.append(ones)
if inv1>=inv0:
x+=0
tot+=inv0
else:
x+=w
tot+=inv1
lis=cur
print(tot,x)
``` | output | 1 | 46,451 | 12 | 92,903 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i ⊕ x (⊕ denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion in the b array is a pair of integers i and j such that 1 ≤ i < j ≤ n and b_i > b_j.
You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x — output the smallest one.
Input
First line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of elements in a.
Second line contains n space-separated integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Output two integers: the minimum possible number of inversions in b, and the minimum possible value of x, which achieves those number of inversions.
Examples
Input
4
0 1 3 2
Output
1 0
Input
9
10 7 9 10 7 5 5 3 5
Output
4 14
Input
3
8 10 3
Output
0 8
Note
In the first sample it is optimal to leave the array as it is by choosing x = 0.
In the second sample the selection of x = 14 results in b: [4, 9, 7, 4, 9, 11, 11, 13, 11]. It has 4 inversions:
* i = 2, j = 3;
* i = 2, j = 4;
* i = 3, j = 4;
* i = 8, j = 9.
In the third sample the selection of x = 8 results in b: [0, 2, 11]. It has no inversions. | instruction | 0 | 46,452 | 12 | 92,904 |
Tags: bitmasks, data structures, divide and conquer, dp, greedy, math, sortings, strings, trees
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
cur = [a]
s = sum(a)
ans = 0
cnt = 0
i = 1 << 31
while i:
i >>= 1
fcnt = 0
bcnt = 0
nex = []
for arr in cur:
aa, bb = [], []
zcnt = 0
ocnt = 0
for ai in arr:
if ai & i:
ocnt += 1
fcnt += zcnt
aa.append(ai)
else:
zcnt += 1
bcnt += ocnt
bb.append(ai)
if aa:
nex.append(aa)
if bb:
nex.append(bb)
if bcnt > fcnt:
ans |= i
cnt += fcnt
else:
cnt += bcnt
cur = nex
print(cnt, ans)
``` | output | 1 | 46,452 | 12 | 92,905 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i ⊕ x (⊕ denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion in the b array is a pair of integers i and j such that 1 ≤ i < j ≤ n and b_i > b_j.
You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x — output the smallest one.
Input
First line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of elements in a.
Second line contains n space-separated integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Output two integers: the minimum possible number of inversions in b, and the minimum possible value of x, which achieves those number of inversions.
Examples
Input
4
0 1 3 2
Output
1 0
Input
9
10 7 9 10 7 5 5 3 5
Output
4 14
Input
3
8 10 3
Output
0 8
Note
In the first sample it is optimal to leave the array as it is by choosing x = 0.
In the second sample the selection of x = 14 results in b: [4, 9, 7, 4, 9, 11, 11, 13, 11]. It has 4 inversions:
* i = 2, j = 3;
* i = 2, j = 4;
* i = 3, j = 4;
* i = 8, j = 9.
In the third sample the selection of x = 8 results in b: [0, 2, 11]. It has no inversions. | instruction | 0 | 46,453 | 12 | 92,906 |
Tags: bitmasks, data structures, divide and conquer, dp, greedy, math, sortings, strings, trees
Correct Solution:
```
import sys
sys.setrecursionlimit(10**5)
int1 = lambda x: int(x)-1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]
def solve(aa):
x = 0
inv = 0
q = [aa]
for k in range(32, -1, -1):
inv0 = inv1 = 0
nq = []
for aa in q:
aa0, aa1 = [], []
c0 = c1 = 0
for a in aa:
if a >> k & 1:
inv1 += c0
c1 += 1
aa1.append(a)
else:
inv0 += c1
c0 += 1
aa0.append(a)
if aa0: nq.append(aa0)
if aa1: nq.append(aa1)
if inv1 < inv0:
x |= 1 << k
inv += inv1
else:
inv += inv0
q = nq
# print(k,q,inv,x)
print(inv, x)
n = II()
aa = LI()
solve(aa)
``` | output | 1 | 46,453 | 12 | 92,907 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i ⊕ x (⊕ denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion in the b array is a pair of integers i and j such that 1 ≤ i < j ≤ n and b_i > b_j.
You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x — output the smallest one.
Input
First line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of elements in a.
Second line contains n space-separated integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Output two integers: the minimum possible number of inversions in b, and the minimum possible value of x, which achieves those number of inversions.
Examples
Input
4
0 1 3 2
Output
1 0
Input
9
10 7 9 10 7 5 5 3 5
Output
4 14
Input
3
8 10 3
Output
0 8
Note
In the first sample it is optimal to leave the array as it is by choosing x = 0.
In the second sample the selection of x = 14 results in b: [4, 9, 7, 4, 9, 11, 11, 13, 11]. It has 4 inversions:
* i = 2, j = 3;
* i = 2, j = 4;
* i = 3, j = 4;
* i = 8, j = 9.
In the third sample the selection of x = 8 results in b: [0, 2, 11]. It has no inversions. | instruction | 0 | 46,454 | 12 | 92,908 |
Tags: bitmasks, data structures, divide and conquer, dp, greedy, math, sortings, strings, trees
Correct Solution:
```
import io
import os
from collections import Counter, defaultdict, deque
def solve(N, A):
total = 0
ans = 0
groups = [A] # group by high bits equal so far
for pos in reversed(range(32)):
bit = 1 << pos
invs = 0
flippedInvs = 0
nextGroups = []
for group in groups:
binary = []
big = []
small = []
for x in group:
if x & bit:
binary.append(1)
big.append(x)
else:
binary.append(0)
small.append(x)
if big:
nextGroups.append(big)
if small:
nextGroups.append(small)
numZeroes = 0
numOnes = 0
for x in binary[::-1]:
if x == 0:
numZeroes += 1
flippedInvs += numOnes
else:
numOnes += 1
invs += numZeroes
groups = nextGroups
if flippedInvs < invs:
ans |= 1 << pos
total += min(flippedInvs, invs)
return str(total) + " " + str(ans)
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(N,) = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
ans = solve(N, A)
print(ans)
``` | output | 1 | 46,454 | 12 | 92,909 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i ⊕ x (⊕ denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion in the b array is a pair of integers i and j such that 1 ≤ i < j ≤ n and b_i > b_j.
You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x — output the smallest one.
Input
First line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of elements in a.
Second line contains n space-separated integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Output two integers: the minimum possible number of inversions in b, and the minimum possible value of x, which achieves those number of inversions.
Examples
Input
4
0 1 3 2
Output
1 0
Input
9
10 7 9 10 7 5 5 3 5
Output
4 14
Input
3
8 10 3
Output
0 8
Note
In the first sample it is optimal to leave the array as it is by choosing x = 0.
In the second sample the selection of x = 14 results in b: [4, 9, 7, 4, 9, 11, 11, 13, 11]. It has 4 inversions:
* i = 2, j = 3;
* i = 2, j = 4;
* i = 3, j = 4;
* i = 8, j = 9.
In the third sample the selection of x = 8 results in b: [0, 2, 11]. It has no inversions. | instruction | 0 | 46,455 | 12 | 92,910 |
Tags: bitmasks, data structures, divide and conquer, dp, greedy, math, sortings, strings, trees
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
n, ls = int(input()), list(map(int, input().split()))
cur, res, cc = [ls], 0, 0
for i in range(30, -1, -1):
t_rc0, t_rc1, nx = 0, 0, []
for ar in cur:
ar0, ar1 = [], []
rc0, cc0, rc1, cc1 = 0, 0, 0, 0
for u in ar:
b = u & (1<<i)
if b:
rc1, cc1 = rc1+cc0, cc1+1
ar1.append(u)
else:
rc0, cc0 = rc0+cc1, cc0+1
ar0.append(u)
t_rc0, t_rc1 = t_rc0+rc0, t_rc1+rc1
if ar0: nx.append(ar0)
if ar1: nx.append(ar1)
if t_rc0 > t_rc1: res |= (1<<i)
cc += min(t_rc0, t_rc1)
cur = nx
print(cc, res)
``` | output | 1 | 46,455 | 12 | 92,911 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i ⊕ x (⊕ denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion in the b array is a pair of integers i and j such that 1 ≤ i < j ≤ n and b_i > b_j.
You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x — output the smallest one.
Input
First line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of elements in a.
Second line contains n space-separated integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Output two integers: the minimum possible number of inversions in b, and the minimum possible value of x, which achieves those number of inversions.
Examples
Input
4
0 1 3 2
Output
1 0
Input
9
10 7 9 10 7 5 5 3 5
Output
4 14
Input
3
8 10 3
Output
0 8
Note
In the first sample it is optimal to leave the array as it is by choosing x = 0.
In the second sample the selection of x = 14 results in b: [4, 9, 7, 4, 9, 11, 11, 13, 11]. It has 4 inversions:
* i = 2, j = 3;
* i = 2, j = 4;
* i = 3, j = 4;
* i = 8, j = 9.
In the third sample the selection of x = 8 results in b: [0, 2, 11]. It has no inversions. | instruction | 0 | 46,456 | 12 | 92,912 |
Tags: bitmasks, data structures, divide and conquer, dp, greedy, math, sortings, strings, trees
Correct Solution:
```
import sys,collections as cc
input = sys.stdin.buffer.readline
I = lambda : list(map(int,input().split()))
n,=I()
l=I()
an=ban=0
ar=cc.defaultdict(list)
ar[0]=l
xo=1<<30
for i in range(30,-1,-1):
a=b=0
pr=cc.defaultdict(list)
for j in ar:
ff=j
j=ar[j]
aa=bb=0
oo=zz=0
for x in range(len(j)):
if j[x]&xo:
aa+=zz
oo+=1
pr[2*ff+0].append(j[x])
else:
bb+=oo
zz+=1
pr[2*ff+1].append(j[x])
a+=aa
b+=bb
ar=pr
if a<b:
an+=xo
ban+=a
else:
ban+=b
xo//=2
"""
for i in l:
k=format(i,'b')
k='0'*(4-len(k))+k
x=format(i^an,'b')
x='0'*(4-len(x))+x
print(k,x,i^an)
"""
print(ban,an)
``` | output | 1 | 46,456 | 12 | 92,913 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i ⊕ x (⊕ denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion in the b array is a pair of integers i and j such that 1 ≤ i < j ≤ n and b_i > b_j.
You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x — output the smallest one.
Input
First line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of elements in a.
Second line contains n space-separated integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Output two integers: the minimum possible number of inversions in b, and the minimum possible value of x, which achieves those number of inversions.
Examples
Input
4
0 1 3 2
Output
1 0
Input
9
10 7 9 10 7 5 5 3 5
Output
4 14
Input
3
8 10 3
Output
0 8
Note
In the first sample it is optimal to leave the array as it is by choosing x = 0.
In the second sample the selection of x = 14 results in b: [4, 9, 7, 4, 9, 11, 11, 13, 11]. It has 4 inversions:
* i = 2, j = 3;
* i = 2, j = 4;
* i = 3, j = 4;
* i = 8, j = 9.
In the third sample the selection of x = 8 results in b: [0, 2, 11]. It has no inversions. | instruction | 0 | 46,457 | 12 | 92,914 |
Tags: bitmasks, data structures, divide and conquer, dp, greedy, math, sortings, strings, trees
Correct Solution:
```
n = int(input())
a = [int(x) for x in input().split()]
def solve(w, bit_level):
l = []
h = []
openers = 0
inversions = 0
alt_openers = 0
alt_inversions = 0
for x in w:
if x & bit_level:
h.append(x)
openers += 1
alt_inversions += alt_openers
else:
l.append(x)
inversions += openers
alt_openers += 1
return inversions, alt_inversions, l, h
out = 0
tot_inversions = 0
active_groups = [a]
for bit_level in reversed(range(31)):
sum_i, sum_ai = 0, 0
next_batch = []
for group in active_groups:
i, ai, l, h = solve(group, 1 << bit_level)
sum_i += i
sum_ai += ai
if l: next_batch.append(l)
if h: next_batch.append(h)
if sum_ai < sum_i:
out |= 1 << bit_level
tot_inversions += sum_ai
else:
tot_inversions += sum_i
active_groups = next_batch
print(tot_inversions,out)
``` | output | 1 | 46,457 | 12 | 92,915 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i ⊕ x (⊕ denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion in the b array is a pair of integers i and j such that 1 ≤ i < j ≤ n and b_i > b_j.
You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x — output the smallest one.
Input
First line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of elements in a.
Second line contains n space-separated integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Output two integers: the minimum possible number of inversions in b, and the minimum possible value of x, which achieves those number of inversions.
Examples
Input
4
0 1 3 2
Output
1 0
Input
9
10 7 9 10 7 5 5 3 5
Output
4 14
Input
3
8 10 3
Output
0 8
Note
In the first sample it is optimal to leave the array as it is by choosing x = 0.
In the second sample the selection of x = 14 results in b: [4, 9, 7, 4, 9, 11, 11, 13, 11]. It has 4 inversions:
* i = 2, j = 3;
* i = 2, j = 4;
* i = 3, j = 4;
* i = 8, j = 9.
In the third sample the selection of x = 8 results in b: [0, 2, 11]. It has no inversions. | instruction | 0 | 46,458 | 12 | 92,916 |
Tags: bitmasks, data structures, divide and conquer, dp, greedy, math, sortings, strings, trees
Correct Solution:
```
MB = 29
def ibit(n, k):
return (n>>k)&1
def count(m, k):
res0 = 0
on = 0
res1 = 0
zer = 0
prr = None
for ell in m:
el = ibit(ell, k)
ot = ell >> (k+1)
if ot != prr:
prr = ot
on = 0
zer = 0
#print(ell, el, 'ot-prr', ot, prr, 'on-zer',on, zer)
if el == 1:
res1 += zer
on += 1
else:
res0 += on
zer += 1
return [res0, res1]
def diff(m, k):
res0 = []
res1 = []
res = []
prr = None
for el in m:
ot = el >> (k+1)
if ot != prr:
prr = ot
res += res0 + res1
res0 = []
res1 = []
if ibit(el, k):
res1.append(el)
else:
res0.append(el)
res += res0 + res1
return res
n = int(input())
a = list(map(int, input().split()))
'''
f = sorted(a)
nw = f[0]
colnw = 0
NB = n*(n-1)//2
for el in f:
if nw == el:
colnw += 1
else:
NB -= colnw*(colnw-1)//2
nw = el
colnw = 1
'''
ll = a
bt = MB
rs = 0
inv = 0
while bt >= 0:
# print('BT', bt, inv, rs)
#if bt <= 3:
# print(bt, ll, 'b')
ll = diff(ll, bt+1)
# print('bt', bt, 'll', ll)
#if bt <= 3:
# print(bt, ll, 'a')
r0, r1 = count(ll, bt)
# print('b', r0, r1, 'r0-r1')
#if bt <= 3:
# print(bt, r0, r1)
if r0 > r1:
rs += (1 << bt)
inv += r1
else:
inv += r0
# print('t', 'r0-r1', r0, r1, 'inv-rs', inv, rs)
bt -= 1
print(inv, rs)
``` | output | 1 | 46,458 | 12 | 92,917 |
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 consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i ⊕ x (⊕ denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion in the b array is a pair of integers i and j such that 1 ≤ i < j ≤ n and b_i > b_j.
You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x — output the smallest one.
Input
First line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of elements in a.
Second line contains n space-separated integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Output two integers: the minimum possible number of inversions in b, and the minimum possible value of x, which achieves those number of inversions.
Examples
Input
4
0 1 3 2
Output
1 0
Input
9
10 7 9 10 7 5 5 3 5
Output
4 14
Input
3
8 10 3
Output
0 8
Note
In the first sample it is optimal to leave the array as it is by choosing x = 0.
In the second sample the selection of x = 14 results in b: [4, 9, 7, 4, 9, 11, 11, 13, 11]. It has 4 inversions:
* i = 2, j = 3;
* i = 2, j = 4;
* i = 3, j = 4;
* i = 8, j = 9.
In the third sample the selection of x = 8 results in b: [0, 2, 11]. It has no inversions.
Submitted Solution:
```
from bisect import *
from collections import *
from math import *
from heapq import *
from typing import List
from itertools import *
from operator import *
from functools import *
import sys
'''
@lru_cache(None)
def fact(x):
if x<2:
return 1
return fact(x-1)*x
@lru_cache(None)
def per(i,j):
return fact(i)//fact(i-j)
@lru_cache(None)
def com(i,j):
return per(i,j)//fact(j)
def linc(f,t,l,r):
while l<r:
mid=(l+r)//2
if t>f(mid):
l=mid+1
else:
r=mid
return l
def rinc(f,t,l,r):
while l<r:
mid=(l+r+1)//2
if t<f(mid):
r=mid-1
else:
l=mid
return l
def ldec(f,t,l,r):
while l<r:
mid=(l+r)//2
if t<f(mid):
l=mid+1
else:
r=mid
return l
def rdec(f,t,l,r):
while l<r:
mid=(l+r+1)//2
if t>f(mid):
r=mid-1
else:
l=mid
return l
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def power2(n):
while not n&1:
n>>=1
return n==1
'''
'''
for i in range(t):
#n,m=map(int,input().split())
n,m=1,0
graph=defaultdict(set)
for i in range(m):
u,v=map(int,input().split())
graph[u-1].add(v-1)
visited=[0]*n
ans=[]
def delchild(u):
for child in graph[u]:
visited[child]=1
ans.append(child+1)
for i in range(n):
if not visited[i]:
children=graph[i]
if len(children)==1:
u=children.pop()
visited[u]=1
delchild(u)
elif len(children)==2:
u=children.pop()
v=children.pop()
if u in graph[v]:
delchild(v)
visited[v]=1
elif v in graph[u]:
delchild(u)
visited[u]=1
else:
delchild(u)
delchild(v)
visited[u]=visited[v]=1
print(len(ans))
sys.stdout.flush()
print(' '.join(map(str,ans)))
sys.stdout.flush()
import time
s=time.time()
e=time.time()
print(e-s)
'''
n=int(input())
ans=x=0
arr=[list(map(int,input().split()))]
for k in range(29,-1,-1):
a,b=0,0
mask=1<<k
tmp=[]
for ar in arr:
one=zero=0
tmp1=[]
tmp2=[]
for ai in ar:
cur=ai&mask
if cur==0:
b+=one
zero+=1
tmp1.append(ai)
else:
a+=zero
one+=1
tmp2.append(ai)
if len(tmp1)>1:
tmp.append(tmp1)
if len(tmp2)>1:
tmp.append(tmp2)
if b>a:
x|=mask
ans+=a
else:
ans+=b
arr=tmp
print(ans,x)
``` | instruction | 0 | 46,459 | 12 | 92,918 |
Yes | output | 1 | 46,459 | 12 | 92,919 |
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 consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i ⊕ x (⊕ denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion in the b array is a pair of integers i and j such that 1 ≤ i < j ≤ n and b_i > b_j.
You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x — output the smallest one.
Input
First line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of elements in a.
Second line contains n space-separated integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Output two integers: the minimum possible number of inversions in b, and the minimum possible value of x, which achieves those number of inversions.
Examples
Input
4
0 1 3 2
Output
1 0
Input
9
10 7 9 10 7 5 5 3 5
Output
4 14
Input
3
8 10 3
Output
0 8
Note
In the first sample it is optimal to leave the array as it is by choosing x = 0.
In the second sample the selection of x = 14 results in b: [4, 9, 7, 4, 9, 11, 11, 13, 11]. It has 4 inversions:
* i = 2, j = 3;
* i = 2, j = 4;
* i = 3, j = 4;
* i = 8, j = 9.
In the third sample the selection of x = 8 results in b: [0, 2, 11]. It has no inversions.
Submitted Solution:
```
import os
from sys import stdin, stdout
class Input:
def __init__(self):
self.lines = stdin.readlines()
self.idx = 0
def line(self):
try:
return self.lines[self.idx].strip()
finally:
self.idx += 1
def array(self, sep = ' ', cast = int):
return list(map(cast, self.line().split(sep = sep)))
def known_tests(self):
num_of_cases, = self.array()
for case in range(num_of_cases):
yield self
def unknown_tests(self):
while self.idx < len(self.lines):
yield self
def problem_solver():
oo = float('Inf')
mem = None
def backtrack(a, L, R, B = 31):
if B < 0 or L == R:
return
mask = 1 << B
l = L
r = L
inv0 = 0
inv1 = 0
zero = 0
one = 0
la = []
ra = []
while l < R:
while r < R and (a[l] & mask) == (a[r] & mask):
if (a[r] & mask):
la.append(a[r])
one += 1
inv1 += zero
else:
ra.append(a[r])
zero += 1
inv0 += one
r += 1
l = r
backtrack(la, 0, len(la), B - 1)
backtrack(ra, 0, len(ra), B - 1)
mem[B][0] += inv0
mem[B][1] += inv1
'''
'''
def solver(inpt):
nonlocal mem
n, = inpt.array()
a = inpt.array()
mem = [[0, 0] for i in range(32)]
backtrack(a, 0, n)
inv = 0
x = 0
for b in range(32):
if mem[b][0] <= mem[b][1]:
inv += mem[b][0]
else:
inv += mem[b][1]
x |= 1 << b
print(inv, x)
'''Returns solver'''
return solver
try:
solver = problem_solver()
for tc in Input().unknown_tests():
solver(tc)
except Exception as e:
import traceback
traceback.print_exc(file=stdout)
``` | instruction | 0 | 46,460 | 12 | 92,920 |
Yes | output | 1 | 46,460 | 12 | 92,921 |
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 consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i ⊕ x (⊕ denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion in the b array is a pair of integers i and j such that 1 ≤ i < j ≤ n and b_i > b_j.
You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x — output the smallest one.
Input
First line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of elements in a.
Second line contains n space-separated integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Output two integers: the minimum possible number of inversions in b, and the minimum possible value of x, which achieves those number of inversions.
Examples
Input
4
0 1 3 2
Output
1 0
Input
9
10 7 9 10 7 5 5 3 5
Output
4 14
Input
3
8 10 3
Output
0 8
Note
In the first sample it is optimal to leave the array as it is by choosing x = 0.
In the second sample the selection of x = 14 results in b: [4, 9, 7, 4, 9, 11, 11, 13, 11]. It has 4 inversions:
* i = 2, j = 3;
* i = 2, j = 4;
* i = 3, j = 4;
* i = 8, j = 9.
In the third sample the selection of x = 8 results in b: [0, 2, 11]. It has no inversions.
Submitted Solution:
```
n = input()
a = [list(map(int, input().split()))]
ans = 0
x = 0
for w in range(31, -1, -1):
w = 1<<w
b = []
sum_inv_one = 0
sum_inv_zero = 0
for aa in a:
one = 0
zero = 0
inv_one = 0
inv_zero = 0
a1 = []
a0 = []
for i, ai in enumerate(aa):
if ai & w:
one += 1
inv_one += zero
a1.append(ai)
else:
zero += 1
inv_zero += one
a0.append(ai)
sum_inv_one += inv_one
sum_inv_zero += inv_zero
if a1:
b.append(a1)
if a0:
b.append(a0)
# print(w, a0, a1)
if sum_inv_zero > sum_inv_one:
ans += sum_inv_one
x |= w
else:
ans += sum_inv_zero
a = b
print(ans, x)
``` | instruction | 0 | 46,461 | 12 | 92,922 |
Yes | output | 1 | 46,461 | 12 | 92,923 |
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 consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i ⊕ x (⊕ denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion in the b array is a pair of integers i and j such that 1 ≤ i < j ≤ n and b_i > b_j.
You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x — output the smallest one.
Input
First line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of elements in a.
Second line contains n space-separated integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Output two integers: the minimum possible number of inversions in b, and the minimum possible value of x, which achieves those number of inversions.
Examples
Input
4
0 1 3 2
Output
1 0
Input
9
10 7 9 10 7 5 5 3 5
Output
4 14
Input
3
8 10 3
Output
0 8
Note
In the first sample it is optimal to leave the array as it is by choosing x = 0.
In the second sample the selection of x = 14 results in b: [4, 9, 7, 4, 9, 11, 11, 13, 11]. It has 4 inversions:
* i = 2, j = 3;
* i = 2, j = 4;
* i = 3, j = 4;
* i = 8, j = 9.
In the third sample the selection of x = 8 results in b: [0, 2, 11]. It has no inversions.
Submitted Solution:
```
import sys;input=sys.stdin.readline
N, = map(int, input().split())
A = list(map(int, input().split()))
def check(l, i):
al,bl=[],[]
a=b=0
ta=tb=0
for j in l:
if (A[j]>>i) & 1:
al.append(j)
ta += 1
b += tb
else:
bl.append(j)
tb += 1
a += ta
return a,b,al, bl
ll = [list(range(N))]
R = 0
X = 0
for i in range(29, -1, -1):
nll = []
ac=bc=0
# print(i, ll)
for l in ll:
a, b, al, bl = check(l, i)
ac += a
bc += b
if al:
nll.append(al)
if bl:
nll.append(bl)
# print(ac, bc)
if ac > bc:
X += 1<<i
R += bc
else:
R += ac
ll = nll
print(R, X)
``` | instruction | 0 | 46,462 | 12 | 92,924 |
Yes | output | 1 | 46,462 | 12 | 92,925 |
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 consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i ⊕ x (⊕ denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion in the b array is a pair of integers i and j such that 1 ≤ i < j ≤ n and b_i > b_j.
You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x — output the smallest one.
Input
First line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of elements in a.
Second line contains n space-separated integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Output two integers: the minimum possible number of inversions in b, and the minimum possible value of x, which achieves those number of inversions.
Examples
Input
4
0 1 3 2
Output
1 0
Input
9
10 7 9 10 7 5 5 3 5
Output
4 14
Input
3
8 10 3
Output
0 8
Note
In the first sample it is optimal to leave the array as it is by choosing x = 0.
In the second sample the selection of x = 14 results in b: [4, 9, 7, 4, 9, 11, 11, 13, 11]. It has 4 inversions:
* i = 2, j = 3;
* i = 2, j = 4;
* i = 3, j = 4;
* i = 8, j = 9.
In the third sample the selection of x = 8 results in b: [0, 2, 11]. It has no inversions.
Submitted Solution:
```
n = input()
a = [list(map(int, input().split()))]
ans = 0
x = 0
for w in range(31, 0, -1):
w = 1<<w
b = []
sum_inv_one = 0
sum_inv_zero = 0
for aa in a:
one = 0
zero = 0
inv_one = 0
inv_zero = 0
a1 = []
a0 = []
for i, ai in enumerate(aa):
if ai & w:
one += 1
inv_one += zero
a1.append(ai)
else:
zero += 1
inv_zero += one
a0.append(ai)
sum_inv_one += inv_one
sum_inv_zero += inv_zero
if a1:
b.append(a1)
if a0:
b.append(a0)
if sum_inv_zero > sum_inv_one:
ans += sum_inv_one
x |= w
else:
ans += sum_inv_zero
a = b
print(ans, x)
``` | instruction | 0 | 46,463 | 12 | 92,926 |
No | output | 1 | 46,463 | 12 | 92,927 |
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 consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i ⊕ x (⊕ denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion in the b array is a pair of integers i and j such that 1 ≤ i < j ≤ n and b_i > b_j.
You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x — output the smallest one.
Input
First line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of elements in a.
Second line contains n space-separated integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Output two integers: the minimum possible number of inversions in b, and the minimum possible value of x, which achieves those number of inversions.
Examples
Input
4
0 1 3 2
Output
1 0
Input
9
10 7 9 10 7 5 5 3 5
Output
4 14
Input
3
8 10 3
Output
0 8
Note
In the first sample it is optimal to leave the array as it is by choosing x = 0.
In the second sample the selection of x = 14 results in b: [4, 9, 7, 4, 9, 11, 11, 13, 11]. It has 4 inversions:
* i = 2, j = 3;
* i = 2, j = 4;
* i = 3, j = 4;
* i = 8, j = 9.
In the third sample the selection of x = 8 results in b: [0, 2, 11]. It has no inversions.
Submitted Solution:
```
mod = 1000000007
eps = 10**-9
def main():
import sys
input = sys.stdin.readline
N = int(input())
A_list = [list(map(int, input().split()))]
cnt = 0
x = 0
for lv in range(30, -1, -1):
A_list_new = []
for A in A_list:
AA = [a >> lv & 1 for a in A]
zero = 0
one = 0
inv = 0
A_new_0 = []
A_new_1 = []
for i, a in enumerate(AA):
if a == 0:
zero += 1
inv += one
A_new_0.append(A[i])
else:
one += 1
A_new_1.append(A[i])
inv_flipped = zero * one - inv
if inv <= inv_flipped:
cnt += inv
else:
cnt += inv_flipped
x += 1 << lv
if A_new_0:
A_list_new.append(A_new_0)
if A_new_1:
A_list_new.append(A_new_1)
A_list = A_list_new
print(cnt, x)
if __name__ == '__main__':
main()
``` | instruction | 0 | 46,464 | 12 | 92,928 |
No | output | 1 | 46,464 | 12 | 92,929 |
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 consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i ⊕ x (⊕ denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion in the b array is a pair of integers i and j such that 1 ≤ i < j ≤ n and b_i > b_j.
You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x — output the smallest one.
Input
First line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of elements in a.
Second line contains n space-separated integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Output two integers: the minimum possible number of inversions in b, and the minimum possible value of x, which achieves those number of inversions.
Examples
Input
4
0 1 3 2
Output
1 0
Input
9
10 7 9 10 7 5 5 3 5
Output
4 14
Input
3
8 10 3
Output
0 8
Note
In the first sample it is optimal to leave the array as it is by choosing x = 0.
In the second sample the selection of x = 14 results in b: [4, 9, 7, 4, 9, 11, 11, 13, 11]. It has 4 inversions:
* i = 2, j = 3;
* i = 2, j = 4;
* i = 3, j = 4;
* i = 8, j = 9.
In the third sample the selection of x = 8 results in b: [0, 2, 11]. It has no inversions.
Submitted Solution:
```
n = input()
a = list(map(int, input().split()))
ans = 0
x = 0
def dfs(w, a):
'''
w: mask bit of ai
a: array of ai
'''
global n, ans, x
one = 0 # numbers of 1
zero = 0 # numbers of 0
inv_one = 0 # inv pair numbers when x&w == 1
inv_zero = 0 # inv pair numbers when x&w == 0
a1 = []
a0 = []
for i, ai in enumerate(a):
if ai & w:
one += 1
inv_one += zero
a1.append(ai)
else:
zero += 1
inv_zero += one
a0.append(ai)
# if inv_zero > inv_one:
# ans += inv_one
# x |= w
# else:
# ans += inv_zero
if w != 1:
inv_one_1 = inv_zero_1 = inv_one_2 = inv_zero_2 = 0
if a1:
inv_one_1, inv_zero_1 = dfs(w>>1, a1)
if a0:
inv_one_2, inv_zero_2 = dfs(w>>1, a0)
if inv_zero_1+inv_zero_2 > inv_one_1+inv_one_2:
ans += inv_one_1+inv_one_2
x |= w>>1
else:
ans += inv_zero_1+inv_zero_2
return inv_one, inv_zero
inv_one, inv_zero = dfs(1<<31, a)
if inv_zero > inv_one:
ans += inv_one
x |= 1<<31
else:
ans += inv_zero
print(ans, x)
``` | instruction | 0 | 46,465 | 12 | 92,930 |
No | output | 1 | 46,465 | 12 | 92,931 |
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 consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i ⊕ x (⊕ denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion in the b array is a pair of integers i and j such that 1 ≤ i < j ≤ n and b_i > b_j.
You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x — output the smallest one.
Input
First line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of elements in a.
Second line contains n space-separated integers a_1, a_2, ..., a_n (0 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Output two integers: the minimum possible number of inversions in b, and the minimum possible value of x, which achieves those number of inversions.
Examples
Input
4
0 1 3 2
Output
1 0
Input
9
10 7 9 10 7 5 5 3 5
Output
4 14
Input
3
8 10 3
Output
0 8
Note
In the first sample it is optimal to leave the array as it is by choosing x = 0.
In the second sample the selection of x = 14 results in b: [4, 9, 7, 4, 9, 11, 11, 13, 11]. It has 4 inversions:
* i = 2, j = 3;
* i = 2, j = 4;
* i = 3, j = 4;
* i = 8, j = 9.
In the third sample the selection of x = 8 results in b: [0, 2, 11]. It has no inversions.
Submitted Solution:
```
import os
from sys import stdin, stdout
class Input:
def __init__(self):
self.lines = stdin.readlines()
self.idx = 0
def line(self):
try:
return self.lines[self.idx].strip()
finally:
self.idx += 1
def array(self, sep = ' ', cast = int):
return list(map(cast, self.line().split(sep = sep)))
def known_tests(self):
num_of_cases, = self.array()
for case in range(num_of_cases):
yield self
def unknown_tests(self):
while self.idx < len(self.lines):
yield self
def problem_solver():
oo = float('Inf')
mem = None
a = None
def backtrack(L, R, B = 31):
if B < 0:
return
mask = 1 << B
l = L
r = L
inv0 = 0
inv1 = 0
zero = 0
one = 0
while l < R:
while r < R and (a[l] & mask) == (a[r] & mask):
if (a[l] & mask):
inv1 += zero
one += 1
else:
inv0 += one
zero += 1
r += 1
backtrack(l, r, B - 1)
l = r
mem[B][0] += inv0
mem[B][1] += inv1
'''
'''
def solver(inpt):
nonlocal mem
nonlocal a
n, = inpt.array()
a = inpt.array()
mem = [[0, 0] for i in range(32)]
backtrack(0, n)
inv = 0
x = 0
for b in range(32):
if mem[b][0] <= mem[b][1]:
inv += mem[b][0]
else:
inv += mem[b][1]
x |= 1 << b
print(inv, x)
'''Returns solver'''
return solver
try:
solver = problem_solver()
for tc in Input().unknown_tests():
solver(tc)
except Exception as e:
import traceback
traceback.print_exc(file=stdout)
``` | instruction | 0 | 46,466 | 12 | 92,932 |
No | output | 1 | 46,466 | 12 | 92,933 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You've got a positive integer sequence a1, a2, ..., an. All numbers in the sequence are distinct. Let's fix the set of variables b1, b2, ..., bm. Initially each variable bi (1 ≤ i ≤ m) contains the value of zero. Consider the following sequence, consisting of n operations.
The first operation is assigning the value of a1 to some variable bx (1 ≤ x ≤ m). Each of the following n - 1 operations is assigning to some variable by the value that is equal to the sum of values that are stored in the variables bi and bj (1 ≤ i, j, y ≤ m). At that, the value that is assigned on the t-th operation, must equal at. For each operation numbers y, i, j are chosen anew.
Your task is to find the minimum number of variables m, such that those variables can help you perform the described sequence of operations.
Input
The first line contains integer n (1 ≤ n ≤ 23). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ak ≤ 109).
It is guaranteed that all numbers in the sequence are distinct.
Output
In a single line print a single number — the minimum number of variables m, such that those variables can help you perform the described sequence of operations.
If you cannot perform the sequence of operations at any m, print -1.
Examples
Input
5
1 2 3 6 8
Output
2
Input
3
3 6 5
Output
-1
Input
6
2 4 8 6 10 18
Output
3
Note
In the first sample, you can use two variables b1 and b2 to perform the following sequence of operations.
1. b1 := 1;
2. b2 := b1 + b1;
3. b1 := b1 + b2;
4. b1 := b1 + b1;
5. b1 := b1 + b2. | instruction | 0 | 46,564 | 12 | 93,128 |
Tags: bitmasks, dp
Correct Solution:
```
def Solve(x,B):
if((X,x,B) in Mem):
return Mem[(X,x,B)]
if(len(B)>X):
return False
if(x==len(L)):
return True
if(Form(L[x],B)):
A=list(B)
for e in range(len(B)):
r=A[e]
A[e]=L[x]
if(Solve(x+1,tuple(sorted(A)))):
Mem[(X,x,B)]=True
return True
A[e]=r
A+=[L[x]]
if(Solve(x+1,tuple(sorted(A)))):
Mem[(X,x,B)]=True
return True
Mem[(X,x,B)]=False
return False
def Form(x,B):
for i in range(len(B)):
for j in range(i,len(B)):
if(B[i]+B[j]==x):
return True
return False
n=int(input())
L=list(map(int,input().split()))
done=False
Mem={}
for X in range(1,n+1):
if(Solve(1,(L[0],))):
print(X)
done=True
break
if(not done):
print(-1)
``` | output | 1 | 46,564 | 12 | 93,129 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dr. Evil is interested in math and functions, so he gave Mahmoud and Ehab array a of length n and array b of length m. He introduced a function f(j) which is defined for integers j, which satisfy 0 ≤ j ≤ m - n. Suppose, ci = ai - bi + j. Then f(j) = |c1 - c2 + c3 - c4... cn|. More formally, <image>.
Dr. Evil wants Mahmoud and Ehab to calculate the minimum value of this function over all valid j. They found it a bit easy, so Dr. Evil made their task harder. He will give them q update queries. During each update they should add an integer xi to all elements in a in range [li;ri] i.e. they should add xi to ali, ali + 1, ... , ari and then they should calculate the minimum value of f(j) for all valid j.
Please help Mahmoud and Ehab.
Input
The first line contains three integers n, m and q (1 ≤ n ≤ m ≤ 105, 1 ≤ q ≤ 105) — number of elements in a, number of elements in b and number of queries, respectively.
The second line contains n integers a1, a2, ..., an. ( - 109 ≤ ai ≤ 109) — elements of a.
The third line contains m integers b1, b2, ..., bm. ( - 109 ≤ bi ≤ 109) — elements of b.
Then q lines follow describing the queries. Each of them contains three integers li ri xi (1 ≤ li ≤ ri ≤ n, - 109 ≤ x ≤ 109) — range to be updated and added value.
Output
The first line should contain the minimum value of the function f before any update.
Then output q lines, the i-th of them should contain the minimum value of the function f after performing the i-th update .
Example
Input
5 6 3
1 2 3 4 5
1 2 3 4 5 6
1 1 10
1 1 -9
1 5 -1
Output
0
9
0
0
Note
For the first example before any updates it's optimal to choose j = 0, f(0) = |(1 - 1) - (2 - 2) + (3 - 3) - (4 - 4) + (5 - 5)| = |0| = 0.
After the first update a becomes {11, 2, 3, 4, 5} and it's optimal to choose j = 1, f(1) = |(11 - 2) - (2 - 3) + (3 - 4) - (4 - 5) + (5 - 6) = |9| = 9.
After the second update a becomes {2, 2, 3, 4, 5} and it's optimal to choose j = 1, f(1) = |(2 - 2) - (2 - 3) + (3 - 4) - (4 - 5) + (5 - 6)| = |0| = 0.
After the third update a becomes {1, 1, 2, 3, 4} and it's optimal to choose j = 0, f(0) = |(1 - 1) - (1 - 2) + (2 - 3) - (3 - 4) + (4 - 5)| = |0| = 0. | instruction | 0 | 46,770 | 12 | 93,540 |
Tags: binary search, data structures, sortings
Correct Solution:
```
def read(): return list(map(int, input().split(' ')))
n, m, q = read()
aa = read()
bb = read()
reqs = [read() for _ in range(q)]
asum = 0
bsum = 0
for i, (a, b) in enumerate(zip(aa, bb)):
asum += a if i % 2 == 0 else -a
bsum += b if i % 2 == 0 else -b
bpos = [bsum]
for i in range(len(aa), len(bb)):
b = bb[i]
rempos = i - len(aa)
bsum += b if i % 2 == 0 else -b
bsum -= bb[rempos] if rempos % 2 == 0 else -bb[rempos]
bpos += [bsum if rempos % 2 == 1 else -bsum]
bpos = sorted(set(bpos))
def closest(arr, value):
l = 0
r = len(arr)
while l + 1 < r:
m = (l + r) // 2
if arr[m] <= value:
l = m
else:
r = m
res = arr[l]
if l + 1 < len(arr) and abs(arr[l + 1] - value) < abs(arr[l] - value):
res = arr[l + 1]
return res
print(abs(asum - closest(bpos, asum)))
for req in reqs:
l, r, x = req
l -= 1
if (r - l) % 2 != 0:
asum += x if l % 2 == 0 else -x
print(abs(asum - closest(bpos, asum)))
``` | output | 1 | 46,770 | 12 | 93,541 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Dr. Evil is interested in math and functions, so he gave Mahmoud and Ehab array a of length n and array b of length m. He introduced a function f(j) which is defined for integers j, which satisfy 0 ≤ j ≤ m - n. Suppose, ci = ai - bi + j. Then f(j) = |c1 - c2 + c3 - c4... cn|. More formally, <image>.
Dr. Evil wants Mahmoud and Ehab to calculate the minimum value of this function over all valid j. They found it a bit easy, so Dr. Evil made their task harder. He will give them q update queries. During each update they should add an integer xi to all elements in a in range [li;ri] i.e. they should add xi to ali, ali + 1, ... , ari and then they should calculate the minimum value of f(j) for all valid j.
Please help Mahmoud and Ehab.
Input
The first line contains three integers n, m and q (1 ≤ n ≤ m ≤ 105, 1 ≤ q ≤ 105) — number of elements in a, number of elements in b and number of queries, respectively.
The second line contains n integers a1, a2, ..., an. ( - 109 ≤ ai ≤ 109) — elements of a.
The third line contains m integers b1, b2, ..., bm. ( - 109 ≤ bi ≤ 109) — elements of b.
Then q lines follow describing the queries. Each of them contains three integers li ri xi (1 ≤ li ≤ ri ≤ n, - 109 ≤ x ≤ 109) — range to be updated and added value.
Output
The first line should contain the minimum value of the function f before any update.
Then output q lines, the i-th of them should contain the minimum value of the function f after performing the i-th update .
Example
Input
5 6 3
1 2 3 4 5
1 2 3 4 5 6
1 1 10
1 1 -9
1 5 -1
Output
0
9
0
0
Note
For the first example before any updates it's optimal to choose j = 0, f(0) = |(1 - 1) - (2 - 2) + (3 - 3) - (4 - 4) + (5 - 5)| = |0| = 0.
After the first update a becomes {11, 2, 3, 4, 5} and it's optimal to choose j = 1, f(1) = |(11 - 2) - (2 - 3) + (3 - 4) - (4 - 5) + (5 - 6) = |9| = 9.
After the second update a becomes {2, 2, 3, 4, 5} and it's optimal to choose j = 1, f(1) = |(2 - 2) - (2 - 3) + (3 - 4) - (4 - 5) + (5 - 6)| = |0| = 0.
After the third update a becomes {1, 1, 2, 3, 4} and it's optimal to choose j = 0, f(0) = |(1 - 1) - (1 - 2) + (2 - 3) - (3 - 4) + (4 - 5)| = |0| = 0. | instruction | 0 | 46,771 | 12 | 93,542 |
Tags: binary search, data structures, sortings
Correct Solution:
```
from bisect import *
f = lambda: list(map(int, input().split()))
n, m, q = f()
k = m - n + 1
a = f()
s = sum(a[0:n:2]) - sum(a[1:n:2])
b = [0] + f()
for i in range(2, m + 1, 2): b[i] = -b[i]
for i in range(m): b[i + 1] += b[i]
u = [b[j] - b[j + n] for j in range(1, k, 2)]
v = [b[j + n] - b[j] for j in range(0, k, 2)]
d = sorted(u + v)
def g(s):
j = bisect_right(d, s)
print(min(abs(s - d[j % k]), abs(s - d[j - 1])))
g(s)
for i in range(q):
l, r, x = f()
s += x * (r % 2 + l % 2 - 1)
g(s)
``` | output | 1 | 46,771 | 12 | 93,543 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array of n integer numbers a0, a1, ..., an - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.
Input
The first line contains positive integer n (2 ≤ n ≤ 105) — size of the given array. The second line contains n integers a0, a1, ..., an - 1 (1 ≤ ai ≤ 109) — elements of the array. It is guaranteed that in the array a minimum occurs at least two times.
Output
Print the only number — distance between two nearest minimums in the array.
Examples
Input
2
3 3
Output
1
Input
3
5 6 5
Output
2
Input
9
2 1 3 5 4 1 2 3 1
Output
3 | instruction | 0 | 46,792 | 12 | 93,584 |
Tags: implementation
Correct Solution:
```
#python3
#utf-8
n = int(input())
idx___val = [int(x) for x in input().split()]
minim = min(idx___val)
min_idxes = [idx for idx in range(n) if idx___val[idx] == minim]
min_dist = min([(min_idxes[i] - min_idxes[i - 1]) for i in range(1, len(min_idxes))])
print(min_dist)
``` | output | 1 | 46,792 | 12 | 93,585 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array of n integer numbers a0, a1, ..., an - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.
Input
The first line contains positive integer n (2 ≤ n ≤ 105) — size of the given array. The second line contains n integers a0, a1, ..., an - 1 (1 ≤ ai ≤ 109) — elements of the array. It is guaranteed that in the array a minimum occurs at least two times.
Output
Print the only number — distance between two nearest minimums in the array.
Examples
Input
2
3 3
Output
1
Input
3
5 6 5
Output
2
Input
9
2 1 3 5 4 1 2 3 1
Output
3 | instruction | 0 | 46,793 | 12 | 93,586 |
Tags: implementation
Correct Solution:
```
n = int(input())
s = input()
a = []
s = s.split()
mn = 1000000001
count = 0
minres = 100000
for c in s:
if int(c)<mn:
mn = int(c)
minres = 100000
count = 0
if count!=0 and int(c)==mn:
if count<minres:
minres = count
count=0
count += 1
print(minres)
``` | output | 1 | 46,793 | 12 | 93,587 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array of n integer numbers a0, a1, ..., an - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.
Input
The first line contains positive integer n (2 ≤ n ≤ 105) — size of the given array. The second line contains n integers a0, a1, ..., an - 1 (1 ≤ ai ≤ 109) — elements of the array. It is guaranteed that in the array a minimum occurs at least two times.
Output
Print the only number — distance between two nearest minimums in the array.
Examples
Input
2
3 3
Output
1
Input
3
5 6 5
Output
2
Input
9
2 1 3 5 4 1 2 3 1
Output
3 | instruction | 0 | 46,794 | 12 | 93,588 |
Tags: implementation
Correct Solution:
```
n = int(input())
a = list(map(int,input().split()))
cur = 0
ans = 100001
for i in range(1,n):
if a[cur] == a[i]:
ans = min(ans, i-cur)
cur = i
elif a[i] < a[cur]:
cur = i
ans = 100001
print(ans)
``` | output | 1 | 46,794 | 12 | 93,589 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array of n integer numbers a0, a1, ..., an - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.
Input
The first line contains positive integer n (2 ≤ n ≤ 105) — size of the given array. The second line contains n integers a0, a1, ..., an - 1 (1 ≤ ai ≤ 109) — elements of the array. It is guaranteed that in the array a minimum occurs at least two times.
Output
Print the only number — distance between two nearest minimums in the array.
Examples
Input
2
3 3
Output
1
Input
3
5 6 5
Output
2
Input
9
2 1 3 5 4 1 2 3 1
Output
3 | instruction | 0 | 46,795 | 12 | 93,590 |
Tags: implementation
Correct Solution:
```
input()
A = list(map(int, input().split()))
a_min = min(A)
X = [i for i, a in enumerate(A) if a == a_min]
print(min(i - j for i, j in zip(X[1:], X)))
``` | output | 1 | 46,795 | 12 | 93,591 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array of n integer numbers a0, a1, ..., an - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.
Input
The first line contains positive integer n (2 ≤ n ≤ 105) — size of the given array. The second line contains n integers a0, a1, ..., an - 1 (1 ≤ ai ≤ 109) — elements of the array. It is guaranteed that in the array a minimum occurs at least two times.
Output
Print the only number — distance between two nearest minimums in the array.
Examples
Input
2
3 3
Output
1
Input
3
5 6 5
Output
2
Input
9
2 1 3 5 4 1 2 3 1
Output
3 | instruction | 0 | 46,796 | 12 | 93,592 |
Tags: implementation
Correct Solution:
```
import math
n = int(input())
X = input()
x = X.split()
arr = []
m = math.inf
for i in x:
i = int(i)
if i<m:
m = i
for i in range(len(x)):
if int(x[i]) == int(m):
arr.append(i)
temp = arr[1]-arr[0]
for i in range(len(arr)-1):
if (arr[i+1]-arr[i])<temp:
temp = arr[i+1]-arr[i]
print(temp)
``` | output | 1 | 46,796 | 12 | 93,593 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array of n integer numbers a0, a1, ..., an - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.
Input
The first line contains positive integer n (2 ≤ n ≤ 105) — size of the given array. The second line contains n integers a0, a1, ..., an - 1 (1 ≤ ai ≤ 109) — elements of the array. It is guaranteed that in the array a minimum occurs at least two times.
Output
Print the only number — distance between two nearest minimums in the array.
Examples
Input
2
3 3
Output
1
Input
3
5 6 5
Output
2
Input
9
2 1 3 5 4 1 2 3 1
Output
3 | instruction | 0 | 46,797 | 12 | 93,594 |
Tags: implementation
Correct Solution:
```
n=int(input())
a=list(map(int,input().split()))
x=min(a)
ans=10000000
b=[]
for i in range(0,n):
if a[i]==x:
b.append(i)
pos=b[0]
for i in range(1,len(b)):
ans=min(ans,b[i]-pos)
pos=b[i]
print(ans)
``` | output | 1 | 46,797 | 12 | 93,595 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array of n integer numbers a0, a1, ..., an - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.
Input
The first line contains positive integer n (2 ≤ n ≤ 105) — size of the given array. The second line contains n integers a0, a1, ..., an - 1 (1 ≤ ai ≤ 109) — elements of the array. It is guaranteed that in the array a minimum occurs at least two times.
Output
Print the only number — distance between two nearest minimums in the array.
Examples
Input
2
3 3
Output
1
Input
3
5 6 5
Output
2
Input
9
2 1 3 5 4 1 2 3 1
Output
3 | instruction | 0 | 46,798 | 12 | 93,596 |
Tags: implementation
Correct Solution:
```
n=int(input())
a=[int(i) for i in input().split()]
z=min(a)
p=[]
for i in range(n):
if a[i]==z:
p.append(i)
h=[]
for i in range(len(p)-1):
h.append(p[i+1]-p[i])
print(min(h)+1-1)
``` | output | 1 | 46,798 | 12 | 93,597 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array of n integer numbers a0, a1, ..., an - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.
Input
The first line contains positive integer n (2 ≤ n ≤ 105) — size of the given array. The second line contains n integers a0, a1, ..., an - 1 (1 ≤ ai ≤ 109) — elements of the array. It is guaranteed that in the array a minimum occurs at least two times.
Output
Print the only number — distance between two nearest minimums in the array.
Examples
Input
2
3 3
Output
1
Input
3
5 6 5
Output
2
Input
9
2 1 3 5 4 1 2 3 1
Output
3 | instruction | 0 | 46,799 | 12 | 93,598 |
Tags: implementation
Correct Solution:
```
if __name__ == '__main__':
n = int(input())
a = [int(i) for i in input().split()]
mx = min(a)
a = [i for i in range(n) if a[i] == mx]
d = [a[i] - a[i - 1] for i in range(1, len(a))]
print(min(d))
``` | output | 1 | 46,799 | 12 | 93,599 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Fair Nut has found an array a of n integers. We call subarray l … r a sequence of consecutive elements of an array with indexes from l to r, i.e. a_l, a_{l+1}, a_{l+2}, …, a_{r-1}, a_{r}.
No one knows the reason, but he calls a pair of subsegments good if and only if the following conditions are satisfied:
1. These subsegments should not be nested. That is, each of the subsegments should contain an element (as an index) that does not belong to another subsegment.
2. Subsegments intersect and each element that belongs to the intersection belongs each of segments only once.
For example a=[1, 2, 3, 5, 5]. Pairs (1 … 3; 2 … 5) and (1 … 2; 2 … 3)) — are good, but (1 ... 3; 2 … 3) and (3 … 4; 4 … 5) — are not (subsegment 1 … 3 contains subsegment 2 … 3, integer 5 belongs both segments, but occurs twice in subsegment 4 … 5).
Help the Fair Nut to find out the number of pairs of good subsegments! The answer can be rather big so print it modulo 10^9+7.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of array a.
The second line contains n integers a_1, a_2, …, a_n (-10^9 ≤ a_i ≤ 10^9) — the array elements.
Output
Print single integer — the number of pairs of good subsegments modulo 10^9+7.
Examples
Input
3
1 2 3
Output
1
Input
5
1 2 1 2 3
Output
4
Note
In the first example, there is only one pair of good subsegments: (1 … 2, 2 … 3).
In the second example, there are four pairs of good subsegments:
* (1 … 2, 2 … 3)
* (2 … 3, 3 … 4)
* (2 … 3, 3 … 5)
* (3 … 4, 4 … 5)
Submitted Solution:
```
if __name__ == '__main__':
a = int(input(""))
f = []
for i in range(a):
f.append(i)
array = input("")
mylist2 = []
mylist = array.split(" ")
for i in mylist:
mylist2.append(int(i))
sublist = []
for i in range(a+1):
for j in range(i+1 , a+1):
sub = f[i:j]
if len(sub) == 1:
continue
sublist.append(sub)
n = 0
for i in range(len(sublist)):
for j in range(i+1,len(sublist)):
subsn = []
subdn = []
lo = 0
s = sublist[i]
d = sublist[j]
if s == d:
continue
elif(set(s).issubset(set(d))):
continue
elif(set(d).issubset(set(s))):
continue
for x in s:
for y in d:
if x == y:
lo = 2
break
if lo == 2:
break
if lo == 0:
continue
for x in s:
subsn.append(mylist2[x])
for x in d:
subdn.append(mylist2[x])
list2 = subsn + subdn
for k in list2:
u = list2.count(k)
if u != 1 and u != 2:
sq = 1
break
elif u == 1 or u == 2:
sq = 2
continue
if sq == 2:
n += 1
n = n%(1e9 + 7)
print(int(n))
``` | instruction | 0 | 47,043 | 12 | 94,086 |
No | output | 1 | 47,043 | 12 | 94,087 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Fair Nut has found an array a of n integers. We call subarray l … r a sequence of consecutive elements of an array with indexes from l to r, i.e. a_l, a_{l+1}, a_{l+2}, …, a_{r-1}, a_{r}.
No one knows the reason, but he calls a pair of subsegments good if and only if the following conditions are satisfied:
1. These subsegments should not be nested. That is, each of the subsegments should contain an element (as an index) that does not belong to another subsegment.
2. Subsegments intersect and each element that belongs to the intersection belongs each of segments only once.
For example a=[1, 2, 3, 5, 5]. Pairs (1 … 3; 2 … 5) and (1 … 2; 2 … 3)) — are good, but (1 ... 3; 2 … 3) and (3 … 4; 4 … 5) — are not (subsegment 1 … 3 contains subsegment 2 … 3, integer 5 belongs both segments, but occurs twice in subsegment 4 … 5).
Help the Fair Nut to find out the number of pairs of good subsegments! The answer can be rather big so print it modulo 10^9+7.
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5) — the length of array a.
The second line contains n integers a_1, a_2, …, a_n (-10^9 ≤ a_i ≤ 10^9) — the array elements.
Output
Print single integer — the number of pairs of good subsegments modulo 10^9+7.
Examples
Input
3
1 2 3
Output
1
Input
5
1 2 1 2 3
Output
4
Note
In the first example, there is only one pair of good subsegments: (1 … 2, 2 … 3).
In the second example, there are four pairs of good subsegments:
* (1 … 2, 2 … 3)
* (2 … 3, 3 … 4)
* (2 … 3, 3 … 5)
* (3 … 4, 4 … 5)
Submitted Solution:
```
if __name__ == '__main__':
a = int(input(""))
f = []
for i in range(a):
f.append(i)
array = input("")
mylist2 = []
mylist = array.split(" ")
for i in mylist:
mylist2.append(int(i))
sublist = []
for i in range(a+1):
for j in range(i+1 , a+1):
sub = f[i:j]
if len(sub) == 1:
continue
sublist.append(sub)
n = 0
for i in range(len(sublist)):
for j in range(i+1,len(sublist)):
subsn = []
subdn = []
lo = 0
s = sublist[i]
d = sublist[j]
if s == d:
continue
elif(set(s).issubset(set(d))):
continue
elif(set(d).issubset(set(s))):
continue
for x in s:
for y in d:
if x == y:
lo = 2
break
if lo == 2:
break
if lo == 0:
continue
for x in s:
subsn.append(mylist2[x])
for x in d:
subdn.append(mylist2[x])
list2 = subsn + subdn
for k in list2:
u = list2.count(k)
if u != 1 and u%2 == 1:
sq = 1
break
elif u == 1 or u%2 == 0:
sq = 2
continue
if sq == 2:
n += 1
n = n%(1e9 + 7)
print(int(n))
``` | instruction | 0 | 47,044 | 12 | 94,088 |
No | output | 1 | 47,044 | 12 | 94,089 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a matrix a, consisting of n rows and m columns. Each cell contains an integer in it.
You can change the order of rows arbitrarily (including leaving the initial order), but you can't change the order of cells in a row. After you pick some order of rows, you traverse the whole matrix the following way: firstly visit all cells of the first column from the top row to the bottom one, then the same for the second column and so on. During the traversal you write down the sequence of the numbers on the cells in the same order you visited them. Let that sequence be s_1, s_2, ..., s_{nm}.
The traversal is k-acceptable if for all i (1 ≤ i ≤ nm - 1) |s_i - s_{i + 1}| ≥ k.
Find the maximum integer k such that there exists some order of rows of matrix a that it produces a k-acceptable traversal.
Input
The first line contains two integers n and m (1 ≤ n ≤ 16, 1 ≤ m ≤ 10^4, 2 ≤ nm) — the number of rows and the number of columns, respectively.
Each of the next n lines contains m integers (1 ≤ a_{i, j} ≤ 10^9) — the description of the matrix.
Output
Print a single integer k — the maximum number such that there exists some order of rows of matrix a that it produces an k-acceptable traversal.
Examples
Input
4 2
9 9
10 8
5 3
4 3
Output
5
Input
2 4
1 2 3 4
10 3 7 3
Output
0
Input
6 1
3
6
2
5
1
4
Output
3
Note
In the first example you can rearrange rows as following to get the 5-acceptable traversal:
5 3
10 8
4 3
9 9
Then the sequence s will be [5, 10, 4, 9, 3, 8, 3, 9]. Each pair of neighbouring elements have at least k = 5 difference between them.
In the second example the maximum k = 0, any order is 0-acceptable.
In the third example the given order is already 3-acceptable, you can leave it as it is. | instruction | 0 | 47,045 | 12 | 94,090 |
Tags: binary search, bitmasks, brute force, dp, graphs
Correct Solution:
```
import sys
from array import array # noqa: F401
from typing import List, Tuple, TypeVar, Generic, Sequence, Union # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
def solve(i, n, delta, delta2):
inf = 2 * 10**9
dp = [[-1] * n for _ in range(1 << n)]
dp[(1 << i)][i] = inf
stack = [(1 << i, i)]
for t in range(1, n + 1):
next_s = []
for bit, v in stack:
for dest in range(n):
if (1 << dest) & bit:
continue
if dp[bit | (1 << dest)][dest] == -1:
next_s.append((bit | (1 << dest), dest))
dp[bit | (1 << dest)][dest] = max(dp[bit | (1 << dest)][dest], min(dp[bit][v], delta[v][dest]))
stack = next_s
return max(min(delta2[j][i], dp[-1][j]) for j in range(n) if i != j)
def main():
n, m = map(int, input().split())
matrix = [tuple(map(int, input().split())) for _ in range(n)]
if n == 1:
print(min(abs(x - y) for x, y in zip(matrix[0], matrix[0][1:])))
exit()
delta = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(i + 1, n):
delta[i][j] = delta[j][i] = min(abs(x - y) for x, y in zip(matrix[i], matrix[j]))
delta2 = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
delta2[i][j] = min((abs(x - y) for x, y in zip(matrix[i], matrix[j][1:])), default=2 * 10**9)
print(max(solve(i, n, delta, delta2) for i in range(n)))
if __name__ == '__main__':
main()
``` | output | 1 | 47,045 | 12 | 94,091 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a matrix a, consisting of n rows and m columns. Each cell contains an integer in it.
You can change the order of rows arbitrarily (including leaving the initial order), but you can't change the order of cells in a row. After you pick some order of rows, you traverse the whole matrix the following way: firstly visit all cells of the first column from the top row to the bottom one, then the same for the second column and so on. During the traversal you write down the sequence of the numbers on the cells in the same order you visited them. Let that sequence be s_1, s_2, ..., s_{nm}.
The traversal is k-acceptable if for all i (1 ≤ i ≤ nm - 1) |s_i - s_{i + 1}| ≥ k.
Find the maximum integer k such that there exists some order of rows of matrix a that it produces a k-acceptable traversal.
Input
The first line contains two integers n and m (1 ≤ n ≤ 16, 1 ≤ m ≤ 10^4, 2 ≤ nm) — the number of rows and the number of columns, respectively.
Each of the next n lines contains m integers (1 ≤ a_{i, j} ≤ 10^9) — the description of the matrix.
Output
Print a single integer k — the maximum number such that there exists some order of rows of matrix a that it produces an k-acceptable traversal.
Examples
Input
4 2
9 9
10 8
5 3
4 3
Output
5
Input
2 4
1 2 3 4
10 3 7 3
Output
0
Input
6 1
3
6
2
5
1
4
Output
3
Note
In the first example you can rearrange rows as following to get the 5-acceptable traversal:
5 3
10 8
4 3
9 9
Then the sequence s will be [5, 10, 4, 9, 3, 8, 3, 9]. Each pair of neighbouring elements have at least k = 5 difference between them.
In the second example the maximum k = 0, any order is 0-acceptable.
In the third example the given order is already 3-acceptable, you can leave it as it is. | instruction | 0 | 47,046 | 12 | 94,092 |
Tags: binary search, bitmasks, brute force, dp, graphs
Correct Solution:
```
import sys
import copy
input = sys.stdin.readline
n,m=map(int,input().split())
MAT=[list(map(int,input().split())) for i in range(n)]
#n=15
#m=10000
#MAT=[list(range(j*j,j*j*(m+1),j*j)) for j in range(1,n+1)]
if n==1:
ANS=10**10
for i in range(1,m):
if ANS>abs(MAT[0][i]-MAT[0][i-1]):
ANS=abs(MAT[0][i]-MAT[0][i-1])
print(ANS)
sys.exit()
EDGE0=[[10**10]*n for i in range(n)]#iが0行目,jが最終行
EDGE1=[[10**10]*n for i in range(n)]
MAX=0
MIN=0
if m!=1:
for i in range(n):
for j in range(n):
EDGE1[i][j]=EDGE1[j][i]=min([abs(MAT[i][k]-MAT[j][k]) for k in range(m)])
if EDGE1[i][j]>MAX:
MAX=EDGE1[i][j]
EDGE0[i][j]=min([abs(MAT[i][k]-MAT[j][k-1]) for k in range(1,m)])
else:
for i in range(n):
for j in range(n):
EDGE1[i][j]=EDGE1[j][i]=min([abs(MAT[i][k]-MAT[j][k]) for k in range(m)])
if EDGE1[i][j]>MAX:
MAX=EDGE1[i][j]
def Hamilton(start,USED,rest,last,weight):
#print(start,USED,rest,last,weight,last*(1<<n)+USED)
if MEMO[last*(1<<n)+USED]!=2:
return MEMO[last*(1<<n)+USED]
if rest==1:
for i in range(n):
if USED & (1<<i)==0:
final=i
break
if EDGE0[start][final]>=weight and EDGE1[last][final]>=weight:
#print(start,USED,rest,last,weight)
MEMO[last*(1<<n)+USED]=1
return 1
else:
#print(start,USED,weight,"!")
MEMO[last*(1<<n)+USED]=0
return 0
for j in range(n):
if USED & (1<<j)==0 and EDGE1[last][j]>=weight:
NEXT=USED+(1<<j)
if Hamilton(start,NEXT,rest-1,j,weight)==1:
#print(start,USED,rest,last,weight)
MEMO[last*(1<<n)+USED]=1
return 1
else:
#print(start,USED,weight,"?")
MEMO[last*(1<<n)+USED]=0
return 0
while MAX!=MIN:
#print(MAX,MIN)
aveweight=(MAX+MIN+1)//2
for start in range(n):
MEMO=[2]*(n*1<<(n+1))
START=1<<start
if Hamilton(start,START,n-1,start,aveweight)==1:
MIN=aveweight
break
else:
MAX=aveweight-1
print(MAX)
``` | output | 1 | 47,046 | 12 | 94,093 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a matrix a, consisting of n rows and m columns. Each cell contains an integer in it.
You can change the order of rows arbitrarily (including leaving the initial order), but you can't change the order of cells in a row. After you pick some order of rows, you traverse the whole matrix the following way: firstly visit all cells of the first column from the top row to the bottom one, then the same for the second column and so on. During the traversal you write down the sequence of the numbers on the cells in the same order you visited them. Let that sequence be s_1, s_2, ..., s_{nm}.
The traversal is k-acceptable if for all i (1 ≤ i ≤ nm - 1) |s_i - s_{i + 1}| ≥ k.
Find the maximum integer k such that there exists some order of rows of matrix a that it produces a k-acceptable traversal.
Input
The first line contains two integers n and m (1 ≤ n ≤ 16, 1 ≤ m ≤ 10^4, 2 ≤ nm) — the number of rows and the number of columns, respectively.
Each of the next n lines contains m integers (1 ≤ a_{i, j} ≤ 10^9) — the description of the matrix.
Output
Print a single integer k — the maximum number such that there exists some order of rows of matrix a that it produces an k-acceptable traversal.
Examples
Input
4 2
9 9
10 8
5 3
4 3
Output
5
Input
2 4
1 2 3 4
10 3 7 3
Output
0
Input
6 1
3
6
2
5
1
4
Output
3
Note
In the first example you can rearrange rows as following to get the 5-acceptable traversal:
5 3
10 8
4 3
9 9
Then the sequence s will be [5, 10, 4, 9, 3, 8, 3, 9]. Each pair of neighbouring elements have at least k = 5 difference between them.
In the second example the maximum k = 0, any order is 0-acceptable.
In the third example the given order is already 3-acceptable, you can leave it as it is. | instruction | 0 | 47,047 | 12 | 94,094 |
Tags: binary search, bitmasks, brute force, dp, graphs
Correct Solution:
```
import sys
def read():
return int(input())
def reads():
return [int(x) for x in input().split()]
N,M=reads()
table=[reads() for i in range(N)]
A=[[0]*N for i in range(N)]
B=[[0]*N for i in range(N)]
for i in range(N):
for j in range(N):
res=10**9+7
for k in range(M):
res=min(res,abs(table[i][k]-table[j][k]))
A[i][j]=res
A[j][i]=res
res=10**9+7
for k in range(M-1):
res=min(res,abs(table[i][k]-table[j][k+1]))
B[i][j]=res
dp=[[-1]*N for i in range((1<<N) )]
def calc(mask,v):
if dp[mask][v]!=-1:
return dp[mask][v]
res =0
for u in range(N):
if (mask & 1<<u) and u!=v:
res =max(res,min(calc(mask^(1<<v),u),A[u][v]))
dp[mask][v]=res
return dp[mask][v]
ans=0
for i in range(N):
dp = [[-1] * N for _ in range((1 << N))]
for k in range(N):
if k==i:
dp[1<<k][k]=10**9+7
else:
dp[1<<k][k]=0
for j in range(N):
ans=max(ans,min(B[j][i],calc((1<<N)-1,j)))
print(ans)
``` | output | 1 | 47,047 | 12 | 94,095 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a matrix a, consisting of n rows and m columns. Each cell contains an integer in it.
You can change the order of rows arbitrarily (including leaving the initial order), but you can't change the order of cells in a row. After you pick some order of rows, you traverse the whole matrix the following way: firstly visit all cells of the first column from the top row to the bottom one, then the same for the second column and so on. During the traversal you write down the sequence of the numbers on the cells in the same order you visited them. Let that sequence be s_1, s_2, ..., s_{nm}.
The traversal is k-acceptable if for all i (1 ≤ i ≤ nm - 1) |s_i - s_{i + 1}| ≥ k.
Find the maximum integer k such that there exists some order of rows of matrix a that it produces a k-acceptable traversal.
Input
The first line contains two integers n and m (1 ≤ n ≤ 16, 1 ≤ m ≤ 10^4, 2 ≤ nm) — the number of rows and the number of columns, respectively.
Each of the next n lines contains m integers (1 ≤ a_{i, j} ≤ 10^9) — the description of the matrix.
Output
Print a single integer k — the maximum number such that there exists some order of rows of matrix a that it produces an k-acceptable traversal.
Examples
Input
4 2
9 9
10 8
5 3
4 3
Output
5
Input
2 4
1 2 3 4
10 3 7 3
Output
0
Input
6 1
3
6
2
5
1
4
Output
3
Note
In the first example you can rearrange rows as following to get the 5-acceptable traversal:
5 3
10 8
4 3
9 9
Then the sequence s will be [5, 10, 4, 9, 3, 8, 3, 9]. Each pair of neighbouring elements have at least k = 5 difference between them.
In the second example the maximum k = 0, any order is 0-acceptable.
In the third example the given order is already 3-acceptable, you can leave it as it is. | instruction | 0 | 47,048 | 12 | 94,096 |
Tags: binary search, bitmasks, brute force, dp, graphs
Correct Solution:
```
import sys
def read():
return int(input())
def reads():
return [int(x) for x in input().split()]
N,M=reads()
table=[reads() for i in range(N)]
A=[[0]*N for i in range(N)]
B=[[0]*N for i in range(N)]
for i in range(N):
for j in range(N):
res=10**9+7
for k in range(M):
res=min(res,abs(table[i][k]-table[j][k]))
A[i][j]=res
A[j][i]=res
res=10**9+7
for k in range(M-1):
res=min(res,abs(table[i][k]-table[j][k+1]))
B[i][j]=res
#print(table)
#print(A)
#print(B)
#A=[[10**9,2,3],[2,10**9,8],[1,5,10**9]]
#B=[[10**9,2,3],[2,10**9,8],[1,5,10**9]]
dp=[[-1]*N for i in range((1<<N) )]
def calc(mask,v):
if dp[mask][v]!=-1:
return dp[mask][v]
res =0
for u in range(N):
if (mask & 1<<u) and u!=v:
res =max(res,min(calc(mask^(1<<v),u),A[u][v]))
dp[mask][v]=res
return dp[mask][v]
ans=0
for i in range(N):
dp = [[-1] * N for i in range((1 << N))]
for k in range(N):
if k==i:
dp[1<<k][k]=10**9+7
else:
dp[1<<k][k]=0
for j in range(N):
ans=max(ans,min(B[j][i],calc((1<<N)-1,j)))
#print(dp,ans)
print(ans)
``` | output | 1 | 47,048 | 12 | 94,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 matrix a, consisting of n rows and m columns. Each cell contains an integer in it.
You can change the order of rows arbitrarily (including leaving the initial order), but you can't change the order of cells in a row. After you pick some order of rows, you traverse the whole matrix the following way: firstly visit all cells of the first column from the top row to the bottom one, then the same for the second column and so on. During the traversal you write down the sequence of the numbers on the cells in the same order you visited them. Let that sequence be s_1, s_2, ..., s_{nm}.
The traversal is k-acceptable if for all i (1 ≤ i ≤ nm - 1) |s_i - s_{i + 1}| ≥ k.
Find the maximum integer k such that there exists some order of rows of matrix a that it produces a k-acceptable traversal.
Input
The first line contains two integers n and m (1 ≤ n ≤ 16, 1 ≤ m ≤ 10^4, 2 ≤ nm) — the number of rows and the number of columns, respectively.
Each of the next n lines contains m integers (1 ≤ a_{i, j} ≤ 10^9) — the description of the matrix.
Output
Print a single integer k — the maximum number such that there exists some order of rows of matrix a that it produces an k-acceptable traversal.
Examples
Input
4 2
9 9
10 8
5 3
4 3
Output
5
Input
2 4
1 2 3 4
10 3 7 3
Output
0
Input
6 1
3
6
2
5
1
4
Output
3
Note
In the first example you can rearrange rows as following to get the 5-acceptable traversal:
5 3
10 8
4 3
9 9
Then the sequence s will be [5, 10, 4, 9, 3, 8, 3, 9]. Each pair of neighbouring elements have at least k = 5 difference between them.
In the second example the maximum k = 0, any order is 0-acceptable.
In the third example the given order is already 3-acceptable, you can leave it as it is.
Submitted Solution:
```
import sys
import copy
input = sys.stdin.readline
n,m=map(int,input().split())
MAT=[list(map(int,input().split())) for i in range(n)]
EDGE0=[[10**10]*n for i in range(n)]#iが0行目,jが最終行
EDGE1=[[10**10]*n for i in range(n)]
MAX=0
MIN=0
for i in range(n):
for j in range(n):
W=10**10
for k in range(m):
if W>abs(MAT[i][k]-MAT[j][k]):
W=abs(MAT[i][k]-MAT[j][k])
EDGE1[i][j]=W
EDGE1[j][i]=W
if W>MAX:
MAX=W
W=10**10
for k in range(1,m):
if W>abs(MAT[i][k]-MAT[j][k-1]):
W=abs(MAT[i][k]-MAT[j][k-1])
EDGE0[i][j]=W
def Hamilton(start,USED,rest,last,weight):
if rest==1:
last=USED.index(0)
if EDGE0[start][last]>=weight:
return 1
else:
#print(start,USED,weight,"!")
return 0
for j in range(n):
if USED[j]==1 or EDGE1[last][j]<weight:
continue
NEXT=copy.copy(USED)
NEXT[j]=1
if Hamilton(start,NEXT,rest-1,j,weight)==1:
return 1
else:
#print(start,USED,weight,"?")
return 0
while MAX!=MIN:
#print(MAX,MIN)
aveweight=(MAX+MIN+1)//2
for start in range(n):
START=[0]*n
START[start]=1
if Hamilton(start,START,n-1,start,aveweight)==1:
MIN=aveweight
break
else:
MAX=aveweight-1
print(MAX)
``` | instruction | 0 | 47,049 | 12 | 94,098 |
No | output | 1 | 47,049 | 12 | 94,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.