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.
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) β mathematical expectation of the minimal element among all k-element subsets.
But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 β€ i, j β€ m the condition Ai β₯ Bj holds. Help Leha rearrange the numbers in the array A so that the sum <image> is maximally possible, where A' is already rearranged array.
Input
First line of input data contains single integer m (1 β€ m β€ 2Β·105) β length of arrays A and B.
Next line contains m integers a1, a2, ..., am (1 β€ ai β€ 109) β array A.
Next line contains m integers b1, b2, ..., bm (1 β€ bi β€ 109) β array B.
Output
Output m integers a'1, a'2, ..., a'm β array A' which is permutation of the array A.
Examples
Input
5
7 3 5 3 4
2 1 3 2 3
Output
4 7 3 5 3
Input
7
4 6 5 8 8 2 6
2 1 2 2 1 1 2
Output
2 6 4 5 8 8 6 | instruction | 0 | 77,272 | 12 | 154,544 |
Tags: combinatorics, greedy, math, number theory, sortings
Correct Solution:
```
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
a.sort()
a.reverse()
j=[]
for i in range(n):
j.append([b[i],i])
j.sort()
ans=[0]*n
for i in range(n):
ans[j[i][1]]=str(a[i])
print(' '.join(ans))
``` | output | 1 | 77,272 | 12 | 154,545 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) β mathematical expectation of the minimal element among all k-element subsets.
But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 β€ i, j β€ m the condition Ai β₯ Bj holds. Help Leha rearrange the numbers in the array A so that the sum <image> is maximally possible, where A' is already rearranged array.
Input
First line of input data contains single integer m (1 β€ m β€ 2Β·105) β length of arrays A and B.
Next line contains m integers a1, a2, ..., am (1 β€ ai β€ 109) β array A.
Next line contains m integers b1, b2, ..., bm (1 β€ bi β€ 109) β array B.
Output
Output m integers a'1, a'2, ..., a'm β array A' which is permutation of the array A.
Examples
Input
5
7 3 5 3 4
2 1 3 2 3
Output
4 7 3 5 3
Input
7
4 6 5 8 8 2 6
2 1 2 2 1 1 2
Output
2 6 4 5 8 8 6 | instruction | 0 | 77,273 | 12 | 154,546 |
Tags: combinatorics, greedy, math, number theory, sortings
Correct Solution:
```
import sys
read = lambda : sys.stdin.readline()
n = int(read())
a = list(map(int, read().split()))
b = list(map(int, read().split()))
a.sort()
a = a[::-1]
z = zip(a, list(sorted(b)))
d = dict()
for (one, two) in z:
if two in d:
d[two].append(one)
else:
d[two] = [one]
for i in b:
print(d[i].pop(), end=' ')
print()
``` | output | 1 | 77,273 | 12 | 154,547 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) β mathematical expectation of the minimal element among all k-element subsets.
But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 β€ i, j β€ m the condition Ai β₯ Bj holds. Help Leha rearrange the numbers in the array A so that the sum <image> is maximally possible, where A' is already rearranged array.
Input
First line of input data contains single integer m (1 β€ m β€ 2Β·105) β length of arrays A and B.
Next line contains m integers a1, a2, ..., am (1 β€ ai β€ 109) β array A.
Next line contains m integers b1, b2, ..., bm (1 β€ bi β€ 109) β array B.
Output
Output m integers a'1, a'2, ..., a'm β array A' which is permutation of the array A.
Examples
Input
5
7 3 5 3 4
2 1 3 2 3
Output
4 7 3 5 3
Input
7
4 6 5 8 8 2 6
2 1 2 2 1 1 2
Output
2 6 4 5 8 8 6 | instruction | 0 | 77,274 | 12 | 154,548 |
Tags: combinatorics, greedy, math, number theory, sortings
Correct Solution:
```
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
b1 = []
a1 = []
for i in range(n):
b1.append(b[i])
a1.append(a[i])
b1.sort()
a1.sort()
a1.reverse()
d = dict()
for i in range(n):
if b1[i] in d: d[b1[i]].append(a1[i])
else: d[b1[i]] = [a1[i]]
for i in range(n):
a[i] = d[b[i]][len(d[b[i]]) - 1]
d[b[i]].pop()
print(*a)
``` | output | 1 | 77,274 | 12 | 154,549 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) β mathematical expectation of the minimal element among all k-element subsets.
But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 β€ i, j β€ m the condition Ai β₯ Bj holds. Help Leha rearrange the numbers in the array A so that the sum <image> is maximally possible, where A' is already rearranged array.
Input
First line of input data contains single integer m (1 β€ m β€ 2Β·105) β length of arrays A and B.
Next line contains m integers a1, a2, ..., am (1 β€ ai β€ 109) β array A.
Next line contains m integers b1, b2, ..., bm (1 β€ bi β€ 109) β array B.
Output
Output m integers a'1, a'2, ..., a'm β array A' which is permutation of the array A.
Examples
Input
5
7 3 5 3 4
2 1 3 2 3
Output
4 7 3 5 3
Input
7
4 6 5 8 8 2 6
2 1 2 2 1 1 2
Output
2 6 4 5 8 8 6 | instruction | 0 | 77,275 | 12 | 154,550 |
Tags: combinatorics, greedy, math, number theory, sortings
Correct Solution:
```
n=int(input())
a=[int(x) for x in input().split()]
b=[int(x) for x in input().split()]
for i in range(n):
b[i]=(b[i],i)
a.sort(reverse=True)
#print(b)
b.sort()
#print(b)
ans=[0]*n
#print(ans)
for i in range(n):
ans[b[i][1]]=a[i]
print(*ans)
``` | output | 1 | 77,275 | 12 | 154,551 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) β mathematical expectation of the minimal element among all k-element subsets.
But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 β€ i, j β€ m the condition Ai β₯ Bj holds. Help Leha rearrange the numbers in the array A so that the sum <image> is maximally possible, where A' is already rearranged array.
Input
First line of input data contains single integer m (1 β€ m β€ 2Β·105) β length of arrays A and B.
Next line contains m integers a1, a2, ..., am (1 β€ ai β€ 109) β array A.
Next line contains m integers b1, b2, ..., bm (1 β€ bi β€ 109) β array B.
Output
Output m integers a'1, a'2, ..., a'm β array A' which is permutation of the array A.
Examples
Input
5
7 3 5 3 4
2 1 3 2 3
Output
4 7 3 5 3
Input
7
4 6 5 8 8 2 6
2 1 2 2 1 1 2
Output
2 6 4 5 8 8 6 | instruction | 0 | 77,276 | 12 | 154,552 |
Tags: combinatorics, greedy, math, number theory, sortings
Correct Solution:
```
import math as mt
import sys,string
input=sys.stdin.readline
from collections import defaultdict
L=lambda : list(map(int,input().split()))
Ls=lambda : list(input().split())
M=lambda : map(int,input().split())
I=lambda :int(input())
n=I()
l=L()
m=L()
x=[]
for i in range(n):
x.append((m[i],i))
x.sort(key=lambda x:(x[0]))
l.sort(reverse=True)
d=[0]*n
for i in range(len(x)):
d[x[i][1]]=l[i]
print(*d)
``` | output | 1 | 77,276 | 12 | 154,553 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) β mathematical expectation of the minimal element among all k-element subsets.
But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 β€ i, j β€ m the condition Ai β₯ Bj holds. Help Leha rearrange the numbers in the array A so that the sum <image> is maximally possible, where A' is already rearranged array.
Input
First line of input data contains single integer m (1 β€ m β€ 2Β·105) β length of arrays A and B.
Next line contains m integers a1, a2, ..., am (1 β€ ai β€ 109) β array A.
Next line contains m integers b1, b2, ..., bm (1 β€ bi β€ 109) β array B.
Output
Output m integers a'1, a'2, ..., a'm β array A' which is permutation of the array A.
Examples
Input
5
7 3 5 3 4
2 1 3 2 3
Output
4 7 3 5 3
Input
7
4 6 5 8 8 2 6
2 1 2 2 1 1 2
Output
2 6 4 5 8 8 6
Submitted Solution:
```
n = int(input())
s1 = input().split()
s2 = input().split()
c1 = [(int(s1[i]), i) for i in range(len(s1))]
c2 = [(int(s2[i]), i) for i in range(len(s2))]
c1 = sorted(c1, key=lambda x: x[0], reverse=True)
c2 = sorted(c2, key=lambda x: x[0])
d = [0 for i in range(n)]
for i in range(n):
nom = c2[i][1]
d[nom] = c1[i][0]
s = ""
for c in d:
s += str(c) + " "
print(s)
``` | instruction | 0 | 77,277 | 12 | 154,554 |
Yes | output | 1 | 77,277 | 12 | 154,555 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) β mathematical expectation of the minimal element among all k-element subsets.
But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 β€ i, j β€ m the condition Ai β₯ Bj holds. Help Leha rearrange the numbers in the array A so that the sum <image> is maximally possible, where A' is already rearranged array.
Input
First line of input data contains single integer m (1 β€ m β€ 2Β·105) β length of arrays A and B.
Next line contains m integers a1, a2, ..., am (1 β€ ai β€ 109) β array A.
Next line contains m integers b1, b2, ..., bm (1 β€ bi β€ 109) β array B.
Output
Output m integers a'1, a'2, ..., a'm β array A' which is permutation of the array A.
Examples
Input
5
7 3 5 3 4
2 1 3 2 3
Output
4 7 3 5 3
Input
7
4 6 5 8 8 2 6
2 1 2 2 1 1 2
Output
2 6 4 5 8 8 6
Submitted Solution:
```
import sys, os
n = int(input())
data = list(map(int, input().split()))
data2 = list(map(int, input().split()))
data3 = []
for i in range(n):
data3.append([data2[i], i])
data3 = sorted(data3)
data = sorted(data, reverse=True)
answer = [0] * n
for i in range(n):
answer[data3[i][1]] = data[i]
print(*answer)
``` | instruction | 0 | 77,278 | 12 | 154,556 |
Yes | output | 1 | 77,278 | 12 | 154,557 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) β mathematical expectation of the minimal element among all k-element subsets.
But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 β€ i, j β€ m the condition Ai β₯ Bj holds. Help Leha rearrange the numbers in the array A so that the sum <image> is maximally possible, where A' is already rearranged array.
Input
First line of input data contains single integer m (1 β€ m β€ 2Β·105) β length of arrays A and B.
Next line contains m integers a1, a2, ..., am (1 β€ ai β€ 109) β array A.
Next line contains m integers b1, b2, ..., bm (1 β€ bi β€ 109) β array B.
Output
Output m integers a'1, a'2, ..., a'm β array A' which is permutation of the array A.
Examples
Input
5
7 3 5 3 4
2 1 3 2 3
Output
4 7 3 5 3
Input
7
4 6 5 8 8 2 6
2 1 2 2 1 1 2
Output
2 6 4 5 8 8 6
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=[]
for i in range(n):
c.append([i,b[i]])
c=sorted(c, key=lambda a: a[1])
a=sorted(a,reverse=True)
for i in range(n):
c[i].append(a[i])
c=sorted(c, key=lambda a: a[0])
for i in range(n):
print(c[i][2],end=" ")
``` | instruction | 0 | 77,279 | 12 | 154,558 |
Yes | output | 1 | 77,279 | 12 | 154,559 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) β mathematical expectation of the minimal element among all k-element subsets.
But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 β€ i, j β€ m the condition Ai β₯ Bj holds. Help Leha rearrange the numbers in the array A so that the sum <image> is maximally possible, where A' is already rearranged array.
Input
First line of input data contains single integer m (1 β€ m β€ 2Β·105) β length of arrays A and B.
Next line contains m integers a1, a2, ..., am (1 β€ ai β€ 109) β array A.
Next line contains m integers b1, b2, ..., bm (1 β€ bi β€ 109) β array B.
Output
Output m integers a'1, a'2, ..., a'm β array A' which is permutation of the array A.
Examples
Input
5
7 3 5 3 4
2 1 3 2 3
Output
4 7 3 5 3
Input
7
4 6 5 8 8 2 6
2 1 2 2 1 1 2
Output
2 6 4 5 8 8 6
Submitted Solution:
```
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
a.sort()
b = sorted([(b[i],i) for i in range(n)])
a2 = [0]*n
for s in range(n):
le = n - 1-s
a2[b[s][1]] = str(a[le])
print(' '.join(a2))
``` | instruction | 0 | 77,280 | 12 | 154,560 |
Yes | output | 1 | 77,280 | 12 | 154,561 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) β mathematical expectation of the minimal element among all k-element subsets.
But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 β€ i, j β€ m the condition Ai β₯ Bj holds. Help Leha rearrange the numbers in the array A so that the sum <image> is maximally possible, where A' is already rearranged array.
Input
First line of input data contains single integer m (1 β€ m β€ 2Β·105) β length of arrays A and B.
Next line contains m integers a1, a2, ..., am (1 β€ ai β€ 109) β array A.
Next line contains m integers b1, b2, ..., bm (1 β€ bi β€ 109) β array B.
Output
Output m integers a'1, a'2, ..., a'm β array A' which is permutation of the array A.
Examples
Input
5
7 3 5 3 4
2 1 3 2 3
Output
4 7 3 5 3
Input
7
4 6 5 8 8 2 6
2 1 2 2 1 1 2
Output
2 6 4 5 8 8 6
Submitted Solution:
```
import operator
n = int(input())
a = list(map(int,input().split(' ')))
b = list(map(int,input().split(' ')))
dic = {}
for i in range(len(b)):
dic[i]=b[i]
a = sorted(a,reverse=True)
sorted_dic = sorted(dic.items(),key=operator.itemgetter(1))
answer = [0]*n
for i in range(len(a)):
answer[sorted_dic[i][0]] = a[i]
print(answer)
``` | instruction | 0 | 77,281 | 12 | 154,562 |
No | output | 1 | 77,281 | 12 | 154,563 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) β mathematical expectation of the minimal element among all k-element subsets.
But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 β€ i, j β€ m the condition Ai β₯ Bj holds. Help Leha rearrange the numbers in the array A so that the sum <image> is maximally possible, where A' is already rearranged array.
Input
First line of input data contains single integer m (1 β€ m β€ 2Β·105) β length of arrays A and B.
Next line contains m integers a1, a2, ..., am (1 β€ ai β€ 109) β array A.
Next line contains m integers b1, b2, ..., bm (1 β€ bi β€ 109) β array B.
Output
Output m integers a'1, a'2, ..., a'm β array A' which is permutation of the array A.
Examples
Input
5
7 3 5 3 4
2 1 3 2 3
Output
4 7 3 5 3
Input
7
4 6 5 8 8 2 6
2 1 2 2 1 1 2
Output
2 6 4 5 8 8 6
Submitted Solution:
```
indexes=[[] for i in range(1000)]
m=int(input())
a=list(map(int, input().split()))
b=list(map(int, input().split()))
for i in range(m):
indexes[b[i]].append(i)
newa=[0 for i in range(m)]
a.sort(reverse=True)
b.sort()
# print(a,b)
for i in range(m):
temp=(indexes[b[i]]).pop()
newa[temp]=a[i]
print(newa)
``` | instruction | 0 | 77,282 | 12 | 154,564 |
No | output | 1 | 77,282 | 12 | 154,565 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) β mathematical expectation of the minimal element among all k-element subsets.
But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 β€ i, j β€ m the condition Ai β₯ Bj holds. Help Leha rearrange the numbers in the array A so that the sum <image> is maximally possible, where A' is already rearranged array.
Input
First line of input data contains single integer m (1 β€ m β€ 2Β·105) β length of arrays A and B.
Next line contains m integers a1, a2, ..., am (1 β€ ai β€ 109) β array A.
Next line contains m integers b1, b2, ..., bm (1 β€ bi β€ 109) β array B.
Output
Output m integers a'1, a'2, ..., a'm β array A' which is permutation of the array A.
Examples
Input
5
7 3 5 3 4
2 1 3 2 3
Output
4 7 3 5 3
Input
7
4 6 5 8 8 2 6
2 1 2 2 1 1 2
Output
2 6 4 5 8 8 6
Submitted Solution:
```
m=int(input())
A=list(input())
B=list(input().split())
C=tuple(B)
B.sort()
D=list(C)
A.sort()
A="".join(A)
A=A[::-1]
A=list(A)
ans=[]
for x in D:
y=B.index(x)
print(A[y],end=" ")
A.pop(y)
B.pop(y)
``` | instruction | 0 | 77,283 | 12 | 154,566 |
No | output | 1 | 77,283 | 12 | 154,567 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) β mathematical expectation of the minimal element among all k-element subsets.
But only function does not interest him. He wants to do interesting things with it. Mom brought him two arrays A and B, each consists of m integers. For all i, j such that 1 β€ i, j β€ m the condition Ai β₯ Bj holds. Help Leha rearrange the numbers in the array A so that the sum <image> is maximally possible, where A' is already rearranged array.
Input
First line of input data contains single integer m (1 β€ m β€ 2Β·105) β length of arrays A and B.
Next line contains m integers a1, a2, ..., am (1 β€ ai β€ 109) β array A.
Next line contains m integers b1, b2, ..., bm (1 β€ bi β€ 109) β array B.
Output
Output m integers a'1, a'2, ..., a'm β array A' which is permutation of the array A.
Examples
Input
5
7 3 5 3 4
2 1 3 2 3
Output
4 7 3 5 3
Input
7
4 6 5 8 8 2 6
2 1 2 2 1 1 2
Output
2 6 4 5 8 8 6
Submitted Solution:
```
import random
def cmp1(a,b):
return a[1]-b[1]
def cmp2(a,b):
return a[0]-b[0]
def cmp0(a,b):
return b-a
def qsrt(a,cmp):
size=0
b=[]
c=[]
d=[]
for i in a:
size=size+1
if size<2:
return a
else:
j=a[random.randrange(0,size-1)]
for i in a:
if cmp(i,j)<0:
b.append(i)
else:
if cmp(i,j)==0:
c.append(i)
else:
d.append(i)
return qsrt(b,cmp)+c+qsrt(d,cmp)
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
c=[]
for i in range(n):
c.append([i,b[i]])
c=qsrt(c,cmp1)
a=qsrt(a,cmp0)
for i in range(n):
c[i].append(a[i])
c=qsrt(c,cmp2)
for i in range(n):
print(c[i][2])
``` | instruction | 0 | 77,284 | 12 | 154,568 |
No | output | 1 | 77,284 | 12 | 154,569 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ehab has an array a of n integers. He likes the [bitwise-xor operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) and he likes to bother Mahmoud so he came up with a problem. He gave Mahmoud q queries. In each of them, he gave Mahmoud 2 integers l and x, and asked him to find the number of subsequences of the first l elements of the array such that their bitwise-xor sum is x. Can you help Mahmoud answer the queries?
A subsequence can contain elements that are not neighboring.
Input
The first line contains integers n and q (1 β€ n, q β€ 105), the number of elements in the array and the number of queries.
The next line contains n integers a1, a2, ..., an (0 β€ ai < 220), the elements of the array.
The next q lines, each contains integers l and x (1 β€ l β€ n, 0 β€ x < 220), representing the queries.
Output
For each query, output its answer modulo 109 + 7 in a newline.
Examples
Input
5 5
0 1 2 3 4
4 3
2 0
3 7
5 7
5 8
Output
4
2
0
4
0
Input
3 2
1 1 1
3 1
2 0
Output
4
2
Note
The bitwise-xor sum of the empty set is 0 and the bitwise-xor sum of a set containing one element is that element itself.
Submitted Solution:
```
def inp():
n,q=map(int,input().split())
a=list(map(int,input().split()))
prefix=[]
prefix.append(a[0])
for i in range(1,n):
prefix.append(prefix[i-1]^a[i])
for i in range(q):
dp={}
l,x=map(int,input().split())
ans=f(a,l,x,0,prefix[i],dp)
print(ans)
def f(a,l,x,i,xor,dp):
st=str(i)+" "+str(xor)
if xor==x:
return 1
if i==l:
return 0
if dp.get(st)!=None:
return dp[st]
dp[st]= f(a,l,x,i+1,xor,dp)+f(a,l,x,i+1,xor^a[i],dp)
return dp[st]
inp()
``` | instruction | 0 | 77,333 | 12 | 154,666 |
No | output | 1 | 77,333 | 12 | 154,667 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ehab has an array a of n integers. He likes the [bitwise-xor operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) and he likes to bother Mahmoud so he came up with a problem. He gave Mahmoud q queries. In each of them, he gave Mahmoud 2 integers l and x, and asked him to find the number of subsequences of the first l elements of the array such that their bitwise-xor sum is x. Can you help Mahmoud answer the queries?
A subsequence can contain elements that are not neighboring.
Input
The first line contains integers n and q (1 β€ n, q β€ 105), the number of elements in the array and the number of queries.
The next line contains n integers a1, a2, ..., an (0 β€ ai < 220), the elements of the array.
The next q lines, each contains integers l and x (1 β€ l β€ n, 0 β€ x < 220), representing the queries.
Output
For each query, output its answer modulo 109 + 7 in a newline.
Examples
Input
5 5
0 1 2 3 4
4 3
2 0
3 7
5 7
5 8
Output
4
2
0
4
0
Input
3 2
1 1 1
3 1
2 0
Output
4
2
Note
The bitwise-xor sum of the empty set is 0 and the bitwise-xor sum of a set containing one element is that element itself.
Submitted Solution:
```
def inp():
n,q=map(int,input().split())
a=list(map(int,input().split()))
prefix=[]
prefix.append(a[0])
for i in range(1,n):
prefix.append(prefix[i-1]^a[i])
for i in range(q):
l,x=map(int,input().split())
ans=f(a,l,x,0,prefix[i])
print(ans)
def f(a,l,x,i,xor):
st=str(i)+" "+str(xor)
if xor==x:
return 1
if i==l:
return 0
return f(a,l,x,i+1,xor)+f(a,l,x,i+1,xor^a[i])
inp()
``` | instruction | 0 | 77,334 | 12 | 154,668 |
No | output | 1 | 77,334 | 12 | 154,669 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ehab has an array a of n integers. He likes the [bitwise-xor operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) and he likes to bother Mahmoud so he came up with a problem. He gave Mahmoud q queries. In each of them, he gave Mahmoud 2 integers l and x, and asked him to find the number of subsequences of the first l elements of the array such that their bitwise-xor sum is x. Can you help Mahmoud answer the queries?
A subsequence can contain elements that are not neighboring.
Input
The first line contains integers n and q (1 β€ n, q β€ 105), the number of elements in the array and the number of queries.
The next line contains n integers a1, a2, ..., an (0 β€ ai < 220), the elements of the array.
The next q lines, each contains integers l and x (1 β€ l β€ n, 0 β€ x < 220), representing the queries.
Output
For each query, output its answer modulo 109 + 7 in a newline.
Examples
Input
5 5
0 1 2 3 4
4 3
2 0
3 7
5 7
5 8
Output
4
2
0
4
0
Input
3 2
1 1 1
3 1
2 0
Output
4
2
Note
The bitwise-xor sum of the empty set is 0 and the bitwise-xor sum of a set containing one element is that element itself.
Submitted Solution:
```
import sys
line = sys.stdin.readline().split()
n = int(line[0])
q = int(line[1])
array = [0] + sys.stdin.readline().split()
for i in range (0, n + 1):
array[i] = int(array[i])
B = [0]
L = []
X = [0]
for i in range (1, n + 1):
a = array[i]
for l in L:
a = min(a, a^l)
if a == 0:
X.append(X[-1]+1)
B.append(B[-1])
else:
L.append(a)
B.append(B[-1]+1)
X.append(X[-1])
for i in range (0, q):
line = sys.stdin.readline().split()
q1 = int(line[0])
q2 = int(line[1])
x = q2
for l in L[:B[q1]]:
q2 = min(q2, q2^l)
if q2 != 0:
print(0)
else:
print(2**X[q1])
``` | instruction | 0 | 77,335 | 12 | 154,670 |
No | output | 1 | 77,335 | 12 | 154,671 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Ehab has an array a of n integers. He likes the [bitwise-xor operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) and he likes to bother Mahmoud so he came up with a problem. He gave Mahmoud q queries. In each of them, he gave Mahmoud 2 integers l and x, and asked him to find the number of subsequences of the first l elements of the array such that their bitwise-xor sum is x. Can you help Mahmoud answer the queries?
A subsequence can contain elements that are not neighboring.
Input
The first line contains integers n and q (1 β€ n, q β€ 105), the number of elements in the array and the number of queries.
The next line contains n integers a1, a2, ..., an (0 β€ ai < 220), the elements of the array.
The next q lines, each contains integers l and x (1 β€ l β€ n, 0 β€ x < 220), representing the queries.
Output
For each query, output its answer modulo 109 + 7 in a newline.
Examples
Input
5 5
0 1 2 3 4
4 3
2 0
3 7
5 7
5 8
Output
4
2
0
4
0
Input
3 2
1 1 1
3 1
2 0
Output
4
2
Note
The bitwise-xor sum of the empty set is 0 and the bitwise-xor sum of a set containing one element is that element itself.
Submitted Solution:
```
class Query:
def __init__(self,x,y):
self.x=x
self.y=y
I=lambda:list(map(int,input().split()))
n,q=I()
arr=I()
d=20
query=[[] for i in range(n+1)]
size=0
ql=[0 for i in range(n+1)]
ans=[0 for i in range(n+1)]
bases=[0 for i in range(20)]
def checkXor(mask):
global bases
for i in range(d):
if(mask&(1<<i)==0):
continue
if(bases[i]==0):
return False
mask^=bases[i]
return True
def insertBases(mask):
global size,bases
for i in range(d):
if(mask&(1<<i)==0):
continue
if(bases[i]==0):
bases[i]=mask
size+=1
return
mask^=bases[i]
for i in range(1,q+1):
ind,x=I()
ql[i]=Query(ind,x)
query[ql[i].x].append(i)
for i in range(n):
insertBases(arr[i])
for j in query[i+1]:
if(checkXor(ql[j].y)):
ans[j]=1<<(i+1-size)
for j in range(1,q+1):
print(ans[j])
``` | instruction | 0 | 77,336 | 12 | 154,672 |
No | output | 1 | 77,336 | 12 | 154,673 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has a sequence a consisting of n integers a_1, a_2, ..., a_n. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number 6 (... 00000000110_2) into 3 (... 00000000011_2), 12 (... 000000001100_2), 1026 (... 10000000010_2) and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence.
Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with [bitwise exclusive or](https://en.wikipedia.org/wiki/Exclusive_or) of all elements equal to 0.
For the given sequence a_1, a_2, β¦, a_n Vasya'd like to calculate number of integer pairs (l, r) such that 1 β€ l β€ r β€ n and sequence a_l, a_{l + 1}, ..., a_r is good.
Input
The first line contains a single integer n (1 β€ n β€ 3 β
10^5) β length of the sequence.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^{18}) β the sequence a.
Output
Print one integer β the number of pairs (l, r) such that 1 β€ l β€ r β€ n and the sequence a_l, a_{l + 1}, ..., a_r is good.
Examples
Input
3
6 7 14
Output
2
Input
4
1 2 1 16
Output
4
Note
In the first example pairs (2, 3) and (1, 3) are valid. Pair (2, 3) is valid since a_2 = 7 β 11, a_3 = 14 β 11 and 11 β 11 = 0, where β β bitwise exclusive or. Pair (1, 3) is valid since a_1 = 6 β 3, a_2 = 7 β 13, a_3 = 14 β 14 and 3 β 13 β 14 = 0.
In the second example pairs (1, 2), (2, 3), (3, 4) and (1, 4) are valid. | instruction | 0 | 77,555 | 12 | 155,110 |
Tags: bitmasks, dp
Correct Solution:
```
import sys
input=sys.stdin.readline
n=int(input())
a=list(map(int,input().split()))
b=[0]*n
for i in range(n):
ai=a[i]
for j in range(61):
if (ai>>j)&1:
b[i]+=1
cnt=[[0]*(n+1) for i in range(2)]
cnt[0][n]=1
res=0
suf=0
for i in range(n)[::-1]:
s=0;MAX=0
add=0
for j in range(i,n):
if j-i>=65:
break
s+=b[j]
MAX=max(MAX,b[j])
if MAX>s-MAX and s%2==0:
add-=1
suf+=b[i]
add+=cnt[suf&1][i+1]
res+=add
cnt[0][i]=cnt[0][i+1]
cnt[1][i]=cnt[1][i+1]
if suf&1:
cnt[1][i]+=1
else:
cnt[0][i]+=1
print(res)
``` | output | 1 | 77,555 | 12 | 155,111 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has a sequence a consisting of n integers a_1, a_2, ..., a_n. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number 6 (... 00000000110_2) into 3 (... 00000000011_2), 12 (... 000000001100_2), 1026 (... 10000000010_2) and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence.
Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with [bitwise exclusive or](https://en.wikipedia.org/wiki/Exclusive_or) of all elements equal to 0.
For the given sequence a_1, a_2, β¦, a_n Vasya'd like to calculate number of integer pairs (l, r) such that 1 β€ l β€ r β€ n and sequence a_l, a_{l + 1}, ..., a_r is good.
Input
The first line contains a single integer n (1 β€ n β€ 3 β
10^5) β length of the sequence.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^{18}) β the sequence a.
Output
Print one integer β the number of pairs (l, r) such that 1 β€ l β€ r β€ n and the sequence a_l, a_{l + 1}, ..., a_r is good.
Examples
Input
3
6 7 14
Output
2
Input
4
1 2 1 16
Output
4
Note
In the first example pairs (2, 3) and (1, 3) are valid. Pair (2, 3) is valid since a_2 = 7 β 11, a_3 = 14 β 11 and 11 β 11 = 0, where β β bitwise exclusive or. Pair (1, 3) is valid since a_1 = 6 β 3, a_2 = 7 β 13, a_3 = 14 β 14 and 3 β 13 β 14 = 0.
In the second example pairs (1, 2), (2, 3), (3, 4) and (1, 4) are valid. | instruction | 0 | 77,556 | 12 | 155,112 |
Tags: bitmasks, dp
Correct Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
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")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=998244353
EPS=1e-6
def Ceil(a,b): return a//b+int(a%b>0)
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
def setBit(x):
ans = 0
while( x ):
x = x & (x-1)
ans += 1
return ans
n = Int()
a=[ setBit(i) for i in array()]
# print(a)
have = [1,0]
ans = 0
cur = 0
prev = 0
for i in range(n):
cur += a[i]
ans += have[cur%2]
# print(cur)
have[cur%2] += 1
j = 0
ma = -1
temp = 0
while ( i-j>=0 and j<100):
temp += a[i-j]
ma = max(ma, a[i-j])
ans -= (temp%2==0 and ma * 2 >temp)
j += 1
print(ans)
``` | output | 1 | 77,556 | 12 | 155,113 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has a sequence a consisting of n integers a_1, a_2, ..., a_n. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number 6 (... 00000000110_2) into 3 (... 00000000011_2), 12 (... 000000001100_2), 1026 (... 10000000010_2) and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence.
Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with [bitwise exclusive or](https://en.wikipedia.org/wiki/Exclusive_or) of all elements equal to 0.
For the given sequence a_1, a_2, β¦, a_n Vasya'd like to calculate number of integer pairs (l, r) such that 1 β€ l β€ r β€ n and sequence a_l, a_{l + 1}, ..., a_r is good.
Input
The first line contains a single integer n (1 β€ n β€ 3 β
10^5) β length of the sequence.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^{18}) β the sequence a.
Output
Print one integer β the number of pairs (l, r) such that 1 β€ l β€ r β€ n and the sequence a_l, a_{l + 1}, ..., a_r is good.
Examples
Input
3
6 7 14
Output
2
Input
4
1 2 1 16
Output
4
Note
In the first example pairs (2, 3) and (1, 3) are valid. Pair (2, 3) is valid since a_2 = 7 β 11, a_3 = 14 β 11 and 11 β 11 = 0, where β β bitwise exclusive or. Pair (1, 3) is valid since a_1 = 6 β 3, a_2 = 7 β 13, a_3 = 14 β 14 and 3 β 13 β 14 = 0.
In the second example pairs (1, 2), (2, 3), (3, 4) and (1, 4) are valid. | instruction | 0 | 77,557 | 12 | 155,114 |
Tags: bitmasks, dp
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
# ------------------------------
def main():
n = N()
arr = RLL()
narr = [bin(i).count('1') for i in arr]
res = 0
dp = [[0, 0] for _ in range(n+1)]
dp[0][0] = 1
sm = [0]
for i in narr: sm.append(sm[-1]+i)
for i in range(1, n+1):
t = res
if i>1:
if sm[i]%2:
res+=dp[i-2][1]
else:
res+=dp[i-2][0]
# print(i, res-t, sm[i])
dp[i][sm[i]%2] = dp[i-1][sm[i]%2]+1
dp[i][(sm[i]%2)^1] = dp[i-1][(sm[i]%2)^1]
for l in range(1, n+1):
ma = narr[l-1]
for r in range(l+1, min(n+1, l+63)):
ma = max(ma, narr[r-1])
now = sm[r]-sm[l-1]
if now%2==0 and ma>now-ma:
res-=1
print(res)
if __name__ == "__main__":
main()
``` | output | 1 | 77,557 | 12 | 155,115 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has a sequence a consisting of n integers a_1, a_2, ..., a_n. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number 6 (... 00000000110_2) into 3 (... 00000000011_2), 12 (... 000000001100_2), 1026 (... 10000000010_2) and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence.
Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with [bitwise exclusive or](https://en.wikipedia.org/wiki/Exclusive_or) of all elements equal to 0.
For the given sequence a_1, a_2, β¦, a_n Vasya'd like to calculate number of integer pairs (l, r) such that 1 β€ l β€ r β€ n and sequence a_l, a_{l + 1}, ..., a_r is good.
Input
The first line contains a single integer n (1 β€ n β€ 3 β
10^5) β length of the sequence.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^{18}) β the sequence a.
Output
Print one integer β the number of pairs (l, r) such that 1 β€ l β€ r β€ n and the sequence a_l, a_{l + 1}, ..., a_r is good.
Examples
Input
3
6 7 14
Output
2
Input
4
1 2 1 16
Output
4
Note
In the first example pairs (2, 3) and (1, 3) are valid. Pair (2, 3) is valid since a_2 = 7 β 11, a_3 = 14 β 11 and 11 β 11 = 0, where β β bitwise exclusive or. Pair (1, 3) is valid since a_1 = 6 β 3, a_2 = 7 β 13, a_3 = 14 β 14 and 3 β 13 β 14 = 0.
In the second example pairs (1, 2), (2, 3), (3, 4) and (1, 4) are valid. | instruction | 0 | 77,558 | 12 | 155,116 |
Tags: bitmasks, dp
Correct Solution:
```
from array import array
def popcount(x):
res = 0;
while(x > 0):
res += (x & 1)
x >>= 1
return res
def main():
n = int(input())
a = array('i',[popcount(int(x)) for x in input().split(' ')])
ans,s0,s1 = 0,0,0
for i in range(n):
if(a[i] & 1):
s0,s1 = s1,s0 + 1
else:
s0,s1 = s0 + 1, s1
ans += s0
for i in range(n):
mx,sum = a[i],0
for j in range(i, min(n, i + 70)):
mx = max(mx, a[j]<<1)
sum += a[j]
if( (sum & 1 is 0) and (mx > sum)):
ans-=1
print(ans)
main()
``` | output | 1 | 77,558 | 12 | 155,117 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has a sequence a consisting of n integers a_1, a_2, ..., a_n. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number 6 (... 00000000110_2) into 3 (... 00000000011_2), 12 (... 000000001100_2), 1026 (... 10000000010_2) and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence.
Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with [bitwise exclusive or](https://en.wikipedia.org/wiki/Exclusive_or) of all elements equal to 0.
For the given sequence a_1, a_2, β¦, a_n Vasya'd like to calculate number of integer pairs (l, r) such that 1 β€ l β€ r β€ n and sequence a_l, a_{l + 1}, ..., a_r is good.
Input
The first line contains a single integer n (1 β€ n β€ 3 β
10^5) β length of the sequence.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^{18}) β the sequence a.
Output
Print one integer β the number of pairs (l, r) such that 1 β€ l β€ r β€ n and the sequence a_l, a_{l + 1}, ..., a_r is good.
Examples
Input
3
6 7 14
Output
2
Input
4
1 2 1 16
Output
4
Note
In the first example pairs (2, 3) and (1, 3) are valid. Pair (2, 3) is valid since a_2 = 7 β 11, a_3 = 14 β 11 and 11 β 11 = 0, where β β bitwise exclusive or. Pair (1, 3) is valid since a_1 = 6 β 3, a_2 = 7 β 13, a_3 = 14 β 14 and 3 β 13 β 14 = 0.
In the second example pairs (1, 2), (2, 3), (3, 4) and (1, 4) are valid. | instruction | 0 | 77,559 | 12 | 155,118 |
Tags: bitmasks, dp
Correct Solution:
```
from bisect import bisect_left
n=int(input())
b=list(map(int,input().split()))
pre = [0]
res=[]
for j in range(n):
res.append(bin(b[j]).count('1'))
pre.append(pre[-1]+res[-1])
ans = 0
e = 1
o = 0
for j in range(n):
if pre[j+1] % 2 == 0:
ans += e
e += 1
else:
ans += o
o += 1
s=0
m=0
i=j
while(i>=max(0,j-62)):
s+=res[i]
m=max(m,res[i])
if s%2==0 and s<2*m:
ans+=-1
i+=-1
print(ans)
``` | output | 1 | 77,559 | 12 | 155,119 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has a sequence a consisting of n integers a_1, a_2, ..., a_n. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number 6 (... 00000000110_2) into 3 (... 00000000011_2), 12 (... 000000001100_2), 1026 (... 10000000010_2) and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence.
Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with [bitwise exclusive or](https://en.wikipedia.org/wiki/Exclusive_or) of all elements equal to 0.
For the given sequence a_1, a_2, β¦, a_n Vasya'd like to calculate number of integer pairs (l, r) such that 1 β€ l β€ r β€ n and sequence a_l, a_{l + 1}, ..., a_r is good.
Input
The first line contains a single integer n (1 β€ n β€ 3 β
10^5) β length of the sequence.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^{18}) β the sequence a.
Output
Print one integer β the number of pairs (l, r) such that 1 β€ l β€ r β€ n and the sequence a_l, a_{l + 1}, ..., a_r is good.
Examples
Input
3
6 7 14
Output
2
Input
4
1 2 1 16
Output
4
Note
In the first example pairs (2, 3) and (1, 3) are valid. Pair (2, 3) is valid since a_2 = 7 β 11, a_3 = 14 β 11 and 11 β 11 = 0, where β β bitwise exclusive or. Pair (1, 3) is valid since a_1 = 6 β 3, a_2 = 7 β 13, a_3 = 14 β 14 and 3 β 13 β 14 = 0.
In the second example pairs (1, 2), (2, 3), (3, 4) and (1, 4) are valid. | instruction | 0 | 77,560 | 12 | 155,120 |
Tags: bitmasks, dp
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
# ------------------------------
def main():
n = N()
arr = RLL()
narr = [bin(i).count('1') for i in arr]
res = 0
dp = [[0, 0] for _ in range(n+1)]
dp[0][0] = 1
sm = [0]
for i in narr: sm.append(sm[-1]+i)
for i in range(1, n+1):
t = res
if i>1:
if sm[i]%2:
res+=dp[i-2][1]
else:
res+=dp[i-2][0]
# print(i, res-t, sm[i])
dp[i][sm[i]%2] = dp[i-1][sm[i]%2]+1
dp[i][(sm[i]%2)^1] = dp[i-1][(sm[i]%2)^1]
for l in range(1, n+1):
ma = narr[l-1]
for r in range(l+1, n+1):
ma = max(ma, narr[r-1])
now = sm[r]-sm[l-1]
if now>120: break
if now%2==0 and ma>now-ma:
res-=1
print(res)
if __name__ == "__main__":
main()
``` | output | 1 | 77,560 | 12 | 155,121 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has a sequence a consisting of n integers a_1, a_2, ..., a_n. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number 6 (... 00000000110_2) into 3 (... 00000000011_2), 12 (... 000000001100_2), 1026 (... 10000000010_2) and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence.
Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with [bitwise exclusive or](https://en.wikipedia.org/wiki/Exclusive_or) of all elements equal to 0.
For the given sequence a_1, a_2, β¦, a_n Vasya'd like to calculate number of integer pairs (l, r) such that 1 β€ l β€ r β€ n and sequence a_l, a_{l + 1}, ..., a_r is good.
Input
The first line contains a single integer n (1 β€ n β€ 3 β
10^5) β length of the sequence.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^{18}) β the sequence a.
Output
Print one integer β the number of pairs (l, r) such that 1 β€ l β€ r β€ n and the sequence a_l, a_{l + 1}, ..., a_r is good.
Examples
Input
3
6 7 14
Output
2
Input
4
1 2 1 16
Output
4
Note
In the first example pairs (2, 3) and (1, 3) are valid. Pair (2, 3) is valid since a_2 = 7 β 11, a_3 = 14 β 11 and 11 β 11 = 0, where β β bitwise exclusive or. Pair (1, 3) is valid since a_1 = 6 β 3, a_2 = 7 β 13, a_3 = 14 β 14 and 3 β 13 β 14 = 0.
In the second example pairs (1, 2), (2, 3), (3, 4) and (1, 4) are valid. | instruction | 0 | 77,561 | 12 | 155,122 |
Tags: bitmasks, dp
Correct Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------------------------------------------------------------
#mod = 9223372036854775807
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)
class SegmentTree1:
def __init__(self, data, default=10**6, 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)
MOD=10**9+7
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(10)]
pp=[0]*10
def SieveOfEratosthenes(n=10):
p = 2
c=0
while (p * p <= n):
if (prime[p] == True):
c+=1
for i in range(p, n+1, p):
pp[i]+=1
prime[i] = False
p += 1
#---------------------------------Binary Search------------------------------------------
def binarySearch(arr, n, key):
left = 0
right = n-1
mid = 0
res=arr[n-1]
while (left <= right):
mid = (right + left)//2
if (arr[mid] >= key):
res=arr[mid]
right = mid-1
else:
left = mid + 1
return res
def binarySearch1(arr, n, key):
left = 0
right = n-1
mid = 0
res=arr[0]
while (left <= right):
mid = (right + left)//2
if (arr[mid] > key):
right = mid-1
else:
res=arr[mid]
left = mid + 1
return res
#---------------------------------running code------------------------------------------
n = int(input())
cnt = [[0 for _ in range(n + 1)] for _ in range(2)]
b = [bin(_).count('1') for _ in list(map(int, input().split()))]
res = 0
suf_sum = 0
cnt[0][n] = 1
for i in range(n)[::-1]:
_sum, mx = 0, 0
lst_j = i
add = 0
for j in range(i, min(n, i + 65)):
_sum += b[j]
mx = max(mx, b[j])
if mx > _sum - mx and _sum % 2 == 0:
add -= 1
lst_j = j
suf_sum += b[i]
add += cnt[suf_sum & 1][i + 1]
res += add
cnt[0][i] = cnt[0][i + 1]
cnt[1][i] = cnt[1][i + 1]
if suf_sum & 1:
cnt[1][i] += 1
else:
cnt[0][i] += 1
print(res)
``` | output | 1 | 77,561 | 12 | 155,123 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya has a sequence a consisting of n integers a_1, a_2, ..., a_n. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number 6 (... 00000000110_2) into 3 (... 00000000011_2), 12 (... 000000001100_2), 1026 (... 10000000010_2) and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence.
Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with [bitwise exclusive or](https://en.wikipedia.org/wiki/Exclusive_or) of all elements equal to 0.
For the given sequence a_1, a_2, β¦, a_n Vasya'd like to calculate number of integer pairs (l, r) such that 1 β€ l β€ r β€ n and sequence a_l, a_{l + 1}, ..., a_r is good.
Input
The first line contains a single integer n (1 β€ n β€ 3 β
10^5) β length of the sequence.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^{18}) β the sequence a.
Output
Print one integer β the number of pairs (l, r) such that 1 β€ l β€ r β€ n and the sequence a_l, a_{l + 1}, ..., a_r is good.
Examples
Input
3
6 7 14
Output
2
Input
4
1 2 1 16
Output
4
Note
In the first example pairs (2, 3) and (1, 3) are valid. Pair (2, 3) is valid since a_2 = 7 β 11, a_3 = 14 β 11 and 11 β 11 = 0, where β β bitwise exclusive or. Pair (1, 3) is valid since a_1 = 6 β 3, a_2 = 7 β 13, a_3 = 14 β 14 and 3 β 13 β 14 = 0.
In the second example pairs (1, 2), (2, 3), (3, 4) and (1, 4) are valid. | instruction | 0 | 77,562 | 12 | 155,124 |
Tags: bitmasks, dp
Correct Solution:
```
n = int(input())
cnt = [[0 for _ in range(n + 1)] for _ in range(2)]
b = [bin(_).count('1') for _ in list(map(int, input().split()))]
res = 0
suf_sum = 0
cnt[0][n] = 1
for i in range(n)[::-1]:
_sum, mx = 0, 0
lst_j = i
add = 0
for j in range(i, min(n, i + 65)):
_sum += b[j]
mx = max(mx, b[j])
if mx > _sum - mx and _sum % 2 == 0:
add -= 1
lst_j = j
suf_sum += b[i]
add += cnt[suf_sum & 1][i + 1]
res += add
cnt[0][i] = cnt[0][i + 1]
cnt[1][i] = cnt[1][i + 1]
if suf_sum & 1:
cnt[1][i] += 1
else:
cnt[0][i] += 1
print(res)
``` | output | 1 | 77,562 | 12 | 155,125 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has a sequence a consisting of n integers a_1, a_2, ..., a_n. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number 6 (... 00000000110_2) into 3 (... 00000000011_2), 12 (... 000000001100_2), 1026 (... 10000000010_2) and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence.
Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with [bitwise exclusive or](https://en.wikipedia.org/wiki/Exclusive_or) of all elements equal to 0.
For the given sequence a_1, a_2, β¦, a_n Vasya'd like to calculate number of integer pairs (l, r) such that 1 β€ l β€ r β€ n and sequence a_l, a_{l + 1}, ..., a_r is good.
Input
The first line contains a single integer n (1 β€ n β€ 3 β
10^5) β length of the sequence.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^{18}) β the sequence a.
Output
Print one integer β the number of pairs (l, r) such that 1 β€ l β€ r β€ n and the sequence a_l, a_{l + 1}, ..., a_r is good.
Examples
Input
3
6 7 14
Output
2
Input
4
1 2 1 16
Output
4
Note
In the first example pairs (2, 3) and (1, 3) are valid. Pair (2, 3) is valid since a_2 = 7 β 11, a_3 = 14 β 11 and 11 β 11 = 0, where β β bitwise exclusive or. Pair (1, 3) is valid since a_1 = 6 β 3, a_2 = 7 β 13, a_3 = 14 β 14 and 3 β 13 β 14 = 0.
In the second example pairs (1, 2), (2, 3), (3, 4) and (1, 4) are valid.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
# ------------------------------
def main():
n = N()
arr = RLL()
narr = [bin(i).count('1') for i in arr]
res = 0
dp = [[0, 0] for _ in range(n+1)]
dp[0][0] = 1
sm = [0]
for i in narr: sm.append(sm[-1]+i)
for i in range(1, n+1):
if i>1:
if sm[i]%2:
res+=dp[i-1][1]
else:
res+=dp[i-1][0]
dp[i][narr[i-1]%2] = dp[i-1][narr[i-1]%2]+1
dp[i][(narr[i-1]%2)^1] = dp[i-1][(narr[i-1]%2)^1]
# print(res, i, sm)
for l in range(n-1):
ma = narr[l+1]
for r in range(l+2, min(n, l+63)):
now = sm[r]-sm[l]
if now%2==0 and now-ma<ma:
res-=1
print(res)
if __name__ == "__main__":
main()
``` | instruction | 0 | 77,563 | 12 | 155,126 |
No | output | 1 | 77,563 | 12 | 155,127 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has a sequence a consisting of n integers a_1, a_2, ..., a_n. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number 6 (... 00000000110_2) into 3 (... 00000000011_2), 12 (... 000000001100_2), 1026 (... 10000000010_2) and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence.
Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with [bitwise exclusive or](https://en.wikipedia.org/wiki/Exclusive_or) of all elements equal to 0.
For the given sequence a_1, a_2, β¦, a_n Vasya'd like to calculate number of integer pairs (l, r) such that 1 β€ l β€ r β€ n and sequence a_l, a_{l + 1}, ..., a_r is good.
Input
The first line contains a single integer n (1 β€ n β€ 3 β
10^5) β length of the sequence.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^{18}) β the sequence a.
Output
Print one integer β the number of pairs (l, r) such that 1 β€ l β€ r β€ n and the sequence a_l, a_{l + 1}, ..., a_r is good.
Examples
Input
3
6 7 14
Output
2
Input
4
1 2 1 16
Output
4
Note
In the first example pairs (2, 3) and (1, 3) are valid. Pair (2, 3) is valid since a_2 = 7 β 11, a_3 = 14 β 11 and 11 β 11 = 0, where β β bitwise exclusive or. Pair (1, 3) is valid since a_1 = 6 β 3, a_2 = 7 β 13, a_3 = 14 β 14 and 3 β 13 β 14 = 0.
In the second example pairs (1, 2), (2, 3), (3, 4) and (1, 4) are valid.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
# ------------------------------
def main():
n = N()
arr = RLL()
narr = [bin(i).count('1') for i in arr]
res = 0
dp = [[0, 0] for _ in range(n+1)]
dp[0][0] = 1
sm = [0]
for i in narr: sm.append(sm[-1]+i)
for i in range(1, n+1):
t = res
if i>1:
if sm[i]%2:
res+=dp[i-2][1]
else:
res+=dp[i-2][0]
# print(i, res-t, sm[i])
dp[i][sm[i]%2] = dp[i-1][sm[i]%2]+1
dp[i][(sm[i]%2)^1] = dp[i-1][(sm[i]%2)^1]
for l in range(n-1):
ma = narr[l+1]
for r in range(l+2, min(n+1, l+63)):
now = sm[r]-sm[l]
if now%2==0 and ma>now-ma:
res-=1
print(res)
if __name__ == "__main__":
main()
``` | instruction | 0 | 77,564 | 12 | 155,128 |
No | output | 1 | 77,564 | 12 | 155,129 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has a sequence a consisting of n integers a_1, a_2, ..., a_n. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number 6 (... 00000000110_2) into 3 (... 00000000011_2), 12 (... 000000001100_2), 1026 (... 10000000010_2) and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence.
Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with [bitwise exclusive or](https://en.wikipedia.org/wiki/Exclusive_or) of all elements equal to 0.
For the given sequence a_1, a_2, β¦, a_n Vasya'd like to calculate number of integer pairs (l, r) such that 1 β€ l β€ r β€ n and sequence a_l, a_{l + 1}, ..., a_r is good.
Input
The first line contains a single integer n (1 β€ n β€ 3 β
10^5) β length of the sequence.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^{18}) β the sequence a.
Output
Print one integer β the number of pairs (l, r) such that 1 β€ l β€ r β€ n and the sequence a_l, a_{l + 1}, ..., a_r is good.
Examples
Input
3
6 7 14
Output
2
Input
4
1 2 1 16
Output
4
Note
In the first example pairs (2, 3) and (1, 3) are valid. Pair (2, 3) is valid since a_2 = 7 β 11, a_3 = 14 β 11 and 11 β 11 = 0, where β β bitwise exclusive or. Pair (1, 3) is valid since a_1 = 6 β 3, a_2 = 7 β 13, a_3 = 14 β 14 and 3 β 13 β 14 = 0.
In the second example pairs (1, 2), (2, 3), (3, 4) and (1, 4) are valid.
Submitted Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
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")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=998244353
EPS=1e-6
def Ceil(a,b): return a//b+int(a%b>0)
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
# vsInput()
def setBit(x):
ans = 0
while( x ):
x = x & (x-1)
ans += 1
return ans
n = Int()
a=[ setBit(i) for i in array()]
# print(a)
have = [1,0]
ans = 0
cur = 0
prev = 0
for i in range(n):
cur += a[i]
ans += have[cur%2]
have[cur%2] += 1
j= 1
ma = a[i]
temp = a[i]
while ( i-j>=0 and j<100):
temp += a[i-j]
ma = max(ma, a[i-j])
ans -= (temp%2 and ma * 2 >temp)
j += 1
print(ans)
``` | instruction | 0 | 77,565 | 12 | 155,130 |
No | output | 1 | 77,565 | 12 | 155,131 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya has a sequence a consisting of n integers a_1, a_2, ..., a_n. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number 6 (... 00000000110_2) into 3 (... 00000000011_2), 12 (... 000000001100_2), 1026 (... 10000000010_2) and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence.
Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with [bitwise exclusive or](https://en.wikipedia.org/wiki/Exclusive_or) of all elements equal to 0.
For the given sequence a_1, a_2, β¦, a_n Vasya'd like to calculate number of integer pairs (l, r) such that 1 β€ l β€ r β€ n and sequence a_l, a_{l + 1}, ..., a_r is good.
Input
The first line contains a single integer n (1 β€ n β€ 3 β
10^5) β length of the sequence.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^{18}) β the sequence a.
Output
Print one integer β the number of pairs (l, r) such that 1 β€ l β€ r β€ n and the sequence a_l, a_{l + 1}, ..., a_r is good.
Examples
Input
3
6 7 14
Output
2
Input
4
1 2 1 16
Output
4
Note
In the first example pairs (2, 3) and (1, 3) are valid. Pair (2, 3) is valid since a_2 = 7 β 11, a_3 = 14 β 11 and 11 β 11 = 0, where β β bitwise exclusive or. Pair (1, 3) is valid since a_1 = 6 β 3, a_2 = 7 β 13, a_3 = 14 β 14 and 3 β 13 β 14 = 0.
In the second example pairs (1, 2), (2, 3), (3, 4) and (1, 4) are valid.
Submitted Solution:
```
n=int(input())
b=list(map(int,input().split()))
pre=[0]
for j in range(n):
pre.append(pre[-1]+bin(b[j]).count('1'))
ans=0
e=0
o=0
for j in range(n+1):
if pre[j]%2==0:
ans+=e
e+=1
else:
ans+=o
o+=1
print(ans)
``` | instruction | 0 | 77,566 | 12 | 155,132 |
No | output | 1 | 77,566 | 12 | 155,133 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given the array a consisting of n elements and the integer k β€ n.
You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations:
* Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of a is mn then you choose such index i that a_i = mn and set a_i := a_i + 1);
* take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of a is mx then you choose such index i that a_i = mx and set a_i := a_i - 1).
Your task is to calculate the minimum number of moves required to obtain at least k equal elements in the array.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the number of elements in a and the required number of equal elements.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the i-th element of a.
Output
Print one integer β the minimum number of moves required to obtain at least k equal elements in the array.
Examples
Input
6 5
1 2 2 4 2 3
Output
3
Input
7 5
3 3 2 1 1 1 3
Output
4 | instruction | 0 | 77,689 | 12 | 155,378 |
Tags: greedy
Correct Solution:
```
def count(a, b):
k = 0
while(a > b):
a = a//2
k+=1
if a==b:
return k
else:
return None
n, k = input().split()
n = int(n)
k = int(k)
s = list(input().split(" "))
for i in range(n):
s[i] = int(s[i])
s.sort()
number_of_operations = []
for i in range(1, max(s) + 1):
sum = 0
quantity = 0
for number in s:
try:
sum += count(number, i)
quantity += 1
except TypeError:
continue
if quantity == k:
number_of_operations.append(sum)
break
print(min(number_of_operations))
"""
f = 0
while(f ==0):
trend = collections.Counter(s).most_common()
count = s.count(trend)
if count == k:
f = 1
break
for i in range(s.index(trend, 0, n)):
print(i)
#s[i]/=2
res+=1
"""
``` | output | 1 | 77,689 | 12 | 155,379 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given the array a consisting of n elements and the integer k β€ n.
You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations:
* Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of a is mn then you choose such index i that a_i = mn and set a_i := a_i + 1);
* take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of a is mx then you choose such index i that a_i = mx and set a_i := a_i - 1).
Your task is to calculate the minimum number of moves required to obtain at least k equal elements in the array.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the number of elements in a and the required number of equal elements.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the i-th element of a.
Output
Print one integer β the minimum number of moves required to obtain at least k equal elements in the array.
Examples
Input
6 5
1 2 2 4 2 3
Output
3
Input
7 5
3 3 2 1 1 1 3
Output
4 | instruction | 0 | 77,690 | 12 | 155,380 |
Tags: greedy
Correct Solution:
```
n,k = map(int,input().split())
a = list(map(int,input().split()))
pos = []
for i in range(n):
x = a[i]
while x > 0:
pos.append(x)
x //= 2
ans = 1000000000
for res in pos:
cnt = []
for i in range(n):
x = a[i]
cur = 0
while x > res:
x //= 2
cur += 1
if x == res:cnt.append(cur)
if len(cnt) < k:continue
cnt.sort()
ans = min(ans,sum(cnt[:k]))
print(ans)
``` | output | 1 | 77,690 | 12 | 155,381 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given the array a consisting of n elements and the integer k β€ n.
You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations:
* Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of a is mn then you choose such index i that a_i = mn and set a_i := a_i + 1);
* take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of a is mx then you choose such index i that a_i = mx and set a_i := a_i - 1).
Your task is to calculate the minimum number of moves required to obtain at least k equal elements in the array.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the number of elements in a and the required number of equal elements.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the i-th element of a.
Output
Print one integer β the minimum number of moves required to obtain at least k equal elements in the array.
Examples
Input
6 5
1 2 2 4 2 3
Output
3
Input
7 5
3 3 2 1 1 1 3
Output
4 | instruction | 0 | 77,691 | 12 | 155,382 |
Tags: greedy
Correct Solution:
```
from collections import defaultdict
def arrinp():
return [*map(int, input().split(' '))]
def mulinp():
return map(int, input().split(' '))
def intinp():
return int(input())
def solution():
n, k = mulinp()
arr = []
for i in sorted(arrinp()):
if not arr or arr[-1][0] != i:
arr.append([i, 1])
else:
arr[-1][1] += 1
costSum = []
countSum = []
for i, count in arr:
if costSum:
costSum.append(costSum[-1] + count * i)
countSum.append(countSum[-1] + count)
else:
costSum.append(count * i)
countSum.append(count)
# print(arr)
# print(countSum)
# print(costSum)
if len(arr) > 1 and k > arr[0][1] and k > arr[-1][1]:
res = min(costSum[-1] - costSum[0] - (countSum[-1] - countSum[0]) * arr[0][0] -
countSum[-1] + k, arr[-1][0] * countSum[-2] - costSum[-2] - countSum[-1] + k)
# print(costSum[-1] - costSum[0] - (countSum[-1] - countSum[0]) * arr[0][0] -
# countSum[-1] + k, arr[-1][0] * countSum[-2] - costSum[-2] - countSum[-1] + k)
else:
res = 0
for i in range(1, len(arr) - 1):
cost = 0
fromLeft = arr[i][0] * countSum[i] - costSum[i]
fromRight = costSum[-1] - costSum[i] - \
arr[i][0] * (countSum[-1] - countSum[i])
# print(i, fromLeft, fromRight)
if countSum[i] < k:
cost = fromLeft + fromRight + k - countSum[-1]
elif arr[i][1] < k:
cost = fromLeft + k - countSum[i]
# print(cost)
if countSum[-1] - countSum[i-1] >= k and arr[i][1] < k:
cost = min(cost, fromRight + k - countSum[-1] + countSum[i-1])
if res > cost:
res = cost
print(res)
testcases = 1
#testcases = int(input())
for _ in range(testcases):
solution()
``` | output | 1 | 77,691 | 12 | 155,383 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given the array a consisting of n elements and the integer k β€ n.
You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations:
* Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of a is mn then you choose such index i that a_i = mn and set a_i := a_i + 1);
* take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of a is mx then you choose such index i that a_i = mx and set a_i := a_i - 1).
Your task is to calculate the minimum number of moves required to obtain at least k equal elements in the array.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the number of elements in a and the required number of equal elements.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the i-th element of a.
Output
Print one integer β the minimum number of moves required to obtain at least k equal elements in the array.
Examples
Input
6 5
1 2 2 4 2 3
Output
3
Input
7 5
3 3 2 1 1 1 3
Output
4 | instruction | 0 | 77,692 | 12 | 155,384 |
Tags: greedy
Correct Solution:
```
from collections import defaultdict as dc
x,y=map(int,input().split())
coun=dc(lambda:0)
steps=dc(lambda:0)
s=list(map(int,input().split()))
s.sort()
for n in s:
coun[n]+=1
if coun[n]==y:
print(0)
exit(0)
res=10**9
for n in s:
p=n
stp=0
while p:
p//=2
stp+=1
coun[p]+=1
steps[p]+=stp
if(coun[p]==y):
res=min(res,steps[p])
print(res)
``` | output | 1 | 77,692 | 12 | 155,385 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given the array a consisting of n elements and the integer k β€ n.
You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations:
* Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of a is mn then you choose such index i that a_i = mn and set a_i := a_i + 1);
* take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of a is mx then you choose such index i that a_i = mx and set a_i := a_i - 1).
Your task is to calculate the minimum number of moves required to obtain at least k equal elements in the array.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the number of elements in a and the required number of equal elements.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the i-th element of a.
Output
Print one integer β the minimum number of moves required to obtain at least k equal elements in the array.
Examples
Input
6 5
1 2 2 4 2 3
Output
3
Input
7 5
3 3 2 1 1 1 3
Output
4 | instruction | 0 | 77,693 | 12 | 155,386 |
Tags: greedy
Correct Solution:
```
n, k = input().split()
n, k = int(n), int(k)
arr = [[] for _ in range(int(2e5 + 1))]
for a in input().split():
a = int(a)
i = 0
while a > 0:
arr[a].append(i)
i += 1
a //= 2
arr[a].append(i)
min_n = -1
for i in arr:
if len(i) >= k:
sum_k = sum(sorted(i)[:k])
if min_n > sum_k or min_n == -1:
min_n = sum_k
print(min_n)
``` | output | 1 | 77,693 | 12 | 155,387 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given the array a consisting of n elements and the integer k β€ n.
You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations:
* Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of a is mn then you choose such index i that a_i = mn and set a_i := a_i + 1);
* take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of a is mx then you choose such index i that a_i = mx and set a_i := a_i - 1).
Your task is to calculate the minimum number of moves required to obtain at least k equal elements in the array.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the number of elements in a and the required number of equal elements.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the i-th element of a.
Output
Print one integer β the minimum number of moves required to obtain at least k equal elements in the array.
Examples
Input
6 5
1 2 2 4 2 3
Output
3
Input
7 5
3 3 2 1 1 1 3
Output
4 | instruction | 0 | 77,694 | 12 | 155,388 |
Tags: greedy
Correct Solution:
```
a,b=list(map(int,input().split()))
array=list(map(int,input().split()))
c=b-1
answer=[]
array.sort()
arr=list(range(1,array[-1]+1))
for it in arr:
element=it
current=0
count=0
for y in range(0,a):
copare=array[y]
if copare<element:
pass
elif current==b:
answer.append(count)
break
else:
moves=0
flag=5
while True:
if copare==element:
break
elif copare<element:
flag=6
break
else:
copare=int(copare//2)
moves+=1
if flag==6:
pass
else:
count+=moves
current+=1
if current==b:
answer.append(count)
array=array[0:b]
moves=0
for it in array:
while True:
if it==0:
break
else:
it=int(it//2)
moves+=1
answer.append(moves)
print(min(answer))
``` | output | 1 | 77,694 | 12 | 155,389 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given the array a consisting of n elements and the integer k β€ n.
You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations:
* Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of a is mn then you choose such index i that a_i = mn and set a_i := a_i + 1);
* take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of a is mx then you choose such index i that a_i = mx and set a_i := a_i - 1).
Your task is to calculate the minimum number of moves required to obtain at least k equal elements in the array.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the number of elements in a and the required number of equal elements.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the i-th element of a.
Output
Print one integer β the minimum number of moves required to obtain at least k equal elements in the array.
Examples
Input
6 5
1 2 2 4 2 3
Output
3
Input
7 5
3 3 2 1 1 1 3
Output
4 | instruction | 0 | 77,695 | 12 | 155,390 |
Tags: greedy
Correct Solution:
```
'''input
5 3
1 2 3 3 3
'''
from sys import stdin
from copy import deepcopy
from collections import deque
def solve(aux):
# print(aux)
count = 0
for i in range(1, len(aux)):
while True:
if aux[i] > aux[i - 1]:
aux[i] //= 2
count += 1
elif aux[i] < aux[i - 1]:
aux[i - 1] //= 2
count += i
else:
break
# print(count)
return count
def get_arr(num, arr):
aux = []
for i in range(len(arr)):
count = 0
c = arr[i]
while True:
if c > num:
c//= 2
count += 1
elif c < num:
aux.append(float('inf'))
break
else:
aux.append(count)
break
aux.sort()
# print(num, aux)
return aux
# main starts
n, k = list(map(int, stdin.readline().split()))
arr = list(map(int, stdin.readline().split()))
m = max(arr)
ans = float('inf')
for i in range(0, m + 1):
aux = get_arr(i, arr)
ans = min(ans, sum(aux[: k]))
print(ans)
``` | output | 1 | 77,695 | 12 | 155,391 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given the array a consisting of n elements and the integer k β€ n.
You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations:
* Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of a is mn then you choose such index i that a_i = mn and set a_i := a_i + 1);
* take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of a is mx then you choose such index i that a_i = mx and set a_i := a_i - 1).
Your task is to calculate the minimum number of moves required to obtain at least k equal elements in the array.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the number of elements in a and the required number of equal elements.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the i-th element of a.
Output
Print one integer β the minimum number of moves required to obtain at least k equal elements in the array.
Examples
Input
6 5
1 2 2 4 2 3
Output
3
Input
7 5
3 3 2 1 1 1 3
Output
4 | instruction | 0 | 77,696 | 12 | 155,392 |
Tags: greedy
Correct Solution:
```
from sys import stdin, stdout
def write(_s):
stdout.write(_s)
def write_int(_s):
stdout.write(str(_s))
def write_list(_l):
stdout.write(" ".join(map(str, _l)))
def read():
return stdin.readline().split(" ")
def readint():
return int(stdin.readline())
def read_int_l():
return map(int, stdin.readline().split(" "))
n, k = read_int_l()
a = sorted(read_int_l())
pref_sum = [0] * (n + 1)
for i in range(n):
pref_sum[i + 1] += pref_sum[i] + a[i]
min_moves = float("inf")
n_to_left = 0
while n_to_left < n:
n_to_right = n_to_left
while n_to_right < n and a[n_to_right] == a[n_to_left]:
n_to_right += 1
curr_element = a[n_to_left]
same_element_count = n_to_right - n_to_left
# cost to get all left elements to curr_element - 1
cost_left = n_to_left * (curr_element - 1) - pref_sum[n_to_left]
# cost to get all right elements to curr_element + 1
cost_right = pref_sum[n] - pref_sum[n_to_right] - \
(curr_element + 1) * (n - n_to_right)
# the current element suffices
if same_element_count >= k:
min_moves = 0
# moving the left elements
if same_element_count + n_to_left >= k:
min_moves = min(min_moves, cost_left + (k - same_element_count))
# moving the right elements
if same_element_count + (n - n_to_right) >= k:
min_moves = min(min_moves, cost_right + (k - same_element_count))
min_moves = min(min_moves, cost_left + cost_right +
(k - same_element_count))
n_to_left = n_to_right
write_int(max(min_moves, 0))
``` | output | 1 | 77,696 | 12 | 155,393 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given the array a consisting of n elements and the integer k β€ n.
You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations:
* Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of a is mn then you choose such index i that a_i = mn and set a_i := a_i + 1);
* take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of a is mx then you choose such index i that a_i = mx and set a_i := a_i - 1).
Your task is to calculate the minimum number of moves required to obtain at least k equal elements in the array.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the number of elements in a and the required number of equal elements.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the i-th element of a.
Output
Print one integer β the minimum number of moves required to obtain at least k equal elements in the array.
Examples
Input
6 5
1 2 2 4 2 3
Output
3
Input
7 5
3 3 2 1 1 1 3
Output
4
Submitted Solution:
```
def get(a):
return max([a.count(i) for i in set(a)])
n, k = map(int, input().split())
a = sorted(list(map(int, input().split())))
b = a.copy()
can = set()
can.add(0)
for i in range(n):
while b[i] != 0:
can.add(b[i])
b[i] //= 2
can = list(can)
ans = []
for i in range(len(can)):
b = a.copy()
local_ans = 0
count = 0
for j in range(n):
now_count = 0
while b[j] > can[i]:
b[j] //= 2
now_count += 1
if b[j] == can[i]:
count += now_count
local_ans += 1
if local_ans >= k:
break
if local_ans >= k:
ans.append(count)
# print(ans)
print(min(ans))
``` | instruction | 0 | 77,697 | 12 | 155,394 |
Yes | output | 1 | 77,697 | 12 | 155,395 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given the array a consisting of n elements and the integer k β€ n.
You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations:
* Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of a is mn then you choose such index i that a_i = mn and set a_i := a_i + 1);
* take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of a is mx then you choose such index i that a_i = mx and set a_i := a_i - 1).
Your task is to calculate the minimum number of moves required to obtain at least k equal elements in the array.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the number of elements in a and the required number of equal elements.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the i-th element of a.
Output
Print one integer β the minimum number of moves required to obtain at least k equal elements in the array.
Examples
Input
6 5
1 2 2 4 2 3
Output
3
Input
7 5
3 3 2 1 1 1 3
Output
4
Submitted Solution:
```
import sys
input = sys.stdin.readline
n, k = list(map(int, input().split()))
A = list(map(int, input().split()))
A.sort()
ops = [0] * 200007
for i in range(n):
alph = A[i]
while alph > 0:
ops[alph] += 1
alph //= 2
ops[0] += 1
ans = float('inf')
for i in range(200007):
if ops[i] >= k:
count = 0
numOps = 0
for j in range(n):
if count == k:
break
alph = A[j]
tmpOps = 0
while alph > i:
alph //= 2
tmpOps += 1
if alph == i:
count += 1
numOps += tmpOps
ans = min(ans, numOps)
print(ans)
``` | instruction | 0 | 77,698 | 12 | 155,396 |
Yes | output | 1 | 77,698 | 12 | 155,397 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given the array a consisting of n elements and the integer k β€ n.
You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations:
* Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of a is mn then you choose such index i that a_i = mn and set a_i := a_i + 1);
* take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of a is mx then you choose such index i that a_i = mx and set a_i := a_i - 1).
Your task is to calculate the minimum number of moves required to obtain at least k equal elements in the array.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the number of elements in a and the required number of equal elements.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the i-th element of a.
Output
Print one integer β the minimum number of moves required to obtain at least k equal elements in the array.
Examples
Input
6 5
1 2 2 4 2 3
Output
3
Input
7 5
3 3 2 1 1 1 3
Output
4
Submitted Solution:
```
def int_multiple():
return [int(c) for c in input().split()]
def int_single():
return int(input())
def str_multiple():
return [c for c in input().split()]
def str_single():
return input()
# start
n, k = int_multiple()
l = int_multiple()
l = sorted(l)
costs = []
for i in range(200001):
costs.append([])
for i in range(n):
tmp = l[i]
cnt = 0
while (tmp != 0):
costs[tmp].append(cnt)
tmp = int(tmp/2)
cnt += 1
for val in costs[1]:
costs[0].append(val+1)
min_cost = 9999999999999
for c in costs:
if len(c) >= k:
cost = sum(c[:k])
if (cost < min_cost):
min_cost = cost
#for cc in costs:
# print(cc)
print(min_cost)
``` | instruction | 0 | 77,699 | 12 | 155,398 |
Yes | output | 1 | 77,699 | 12 | 155,399 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given the array a consisting of n elements and the integer k β€ n.
You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations:
* Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of a is mn then you choose such index i that a_i = mn and set a_i := a_i + 1);
* take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of a is mx then you choose such index i that a_i = mx and set a_i := a_i - 1).
Your task is to calculate the minimum number of moves required to obtain at least k equal elements in the array.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the number of elements in a and the required number of equal elements.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the i-th element of a.
Output
Print one integer β the minimum number of moves required to obtain at least k equal elements in the array.
Examples
Input
6 5
1 2 2 4 2 3
Output
3
Input
7 5
3 3 2 1 1 1 3
Output
4
Submitted Solution:
```
n,k=map(int,input().split())
a=list(map(int,input().split()))
ans=[[0,0] for i in range(200001)]
a.sort()
for i in range(n):
ans[a[i]][0]+=1
for i in range(n):
s=a[i]
d=1
while (s>0):
s=s//2
if ans[s][0]<k:
ans[s][0]+=1
ans[s][1]+=d
d+=1
mi=100000000
for i in range(len(ans)):
if ans[i][0]>=k:
if ans[i][1]<mi:
mi=ans[i][1]
print(mi)
``` | instruction | 0 | 77,700 | 12 | 155,400 |
Yes | output | 1 | 77,700 | 12 | 155,401 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given the array a consisting of n elements and the integer k β€ n.
You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations:
* Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of a is mn then you choose such index i that a_i = mn and set a_i := a_i + 1);
* take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of a is mx then you choose such index i that a_i = mx and set a_i := a_i - 1).
Your task is to calculate the minimum number of moves required to obtain at least k equal elements in the array.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the number of elements in a and the required number of equal elements.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the i-th element of a.
Output
Print one integer β the minimum number of moves required to obtain at least k equal elements in the array.
Examples
Input
6 5
1 2 2 4 2 3
Output
3
Input
7 5
3 3 2 1 1 1 3
Output
4
Submitted Solution:
```
def main():
n,k = map(int,input().split())
arr = list(map(int,input().split()))
arr.sort()
nums = [[0 for i in range(2)] for j in range(2*10**5+1)]
for i in arr:
nums[i][0] += 1
min_moves = float('inf')
for i in range(2*10**5,-1,-1):
if nums[i][0] >= k:
min_moves = min(min_moves,nums[i][1])
index = i//2
if nums[index][0] < k:
if nums[index][0]+nums[i][0] <= k:
nums[index][0] += nums[i][0]
nums[index][1] += nums[i][0]
else:
nums[index][0] += k-nums[i][0]
nums[index][1] += k-nums[i][0]
print(min_moves)
main()
``` | instruction | 0 | 77,701 | 12 | 155,402 |
No | output | 1 | 77,701 | 12 | 155,403 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given the array a consisting of n elements and the integer k β€ n.
You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations:
* Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of a is mn then you choose such index i that a_i = mn and set a_i := a_i + 1);
* take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of a is mx then you choose such index i that a_i = mx and set a_i := a_i - 1).
Your task is to calculate the minimum number of moves required to obtain at least k equal elements in the array.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the number of elements in a and the required number of equal elements.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the i-th element of a.
Output
Print one integer β the minimum number of moves required to obtain at least k equal elements in the array.
Examples
Input
6 5
1 2 2 4 2 3
Output
3
Input
7 5
3 3 2 1 1 1 3
Output
4
Submitted Solution:
```
n= list(map(int,input().split()))
n[0]
k = n[1]
a = list(map(int,input().split()))
dicta = {}
dictb = {}
for j in a:
if j in dicta:
dicta[j]+=1
else:
dicta[j]=1
if j not in dictb:
dictb[j]=0
b=0
for j in dicta:
if dicta[j]>=k:
b=1
break
if b==1:
print(0)
else:
minimum = 10**14
for i in range(20):
tmp = []
# print(a)
for l in a:
j = l//2
if j in dicta:
dicta[j]+=1
dictb[j]+=i+1
if dicta[j]==k:
if dictb[j]<minimum:
minimum =dictb[j]
else:
dicta[j]=1
dictb[j]=i+1
tmp.append(j)
a = tmp
for j in dicta:
if dicta[j]==k:
if dictb[j]<minimum:
minimum =dictb[j]
print(minimum)
``` | instruction | 0 | 77,702 | 12 | 155,404 |
No | output | 1 | 77,702 | 12 | 155,405 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given the array a consisting of n elements and the integer k β€ n.
You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations:
* Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of a is mn then you choose such index i that a_i = mn and set a_i := a_i + 1);
* take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of a is mx then you choose such index i that a_i = mx and set a_i := a_i - 1).
Your task is to calculate the minimum number of moves required to obtain at least k equal elements in the array.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the number of elements in a and the required number of equal elements.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the i-th element of a.
Output
Print one integer β the minimum number of moves required to obtain at least k equal elements in the array.
Examples
Input
6 5
1 2 2 4 2 3
Output
3
Input
7 5
3 3 2 1 1 1 3
Output
4
Submitted 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
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------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**51, 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)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: max(a , b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------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(arr, 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 (arr[m] >= 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------------------------------------
n,k=map(int,input().split())
l=list(map(int,input().split()))
l.sort()
cou=defaultdict(int)
su=0
cnt=0
su1=sum(l)
cnt1=n
fi=sum(l)
sumq=fi
for i in range(n):
cou[l[i]]+=1
if cou[l[i]]>=k:
print(0)
sys.exit(0)
for i in range(n):
if i==0:
ans=sumq-(l[0]-1)*n+k
fi=min(fi,ans)
cnt1-=cou[l[0]]
su1-=cou[l[0]]*l[0]
elif i==n-1:
ans=(l[-1]+1)*n-sumq+k
fi=min(fi,ans)
else:
if l[i]!=l[i-1]:
cnt+=cou[l[i-1]]
su+=l[i-1]*cou[l[i-1]]
cnt1-=cou[l[i]]
su1-=l[i]*cou[l[i]]
ans=(l[i]-1)*cnt-su
ans1=su1-(l[i]+1)*cnt1
tot=ans+ans1+(k-cou[l[i]])
if cnt1>=k:
tot=min(tot,ans1+(k-cou[l[i]]))
if cnt>=k:
tot=min(tot,ans+(k-cou[l[i]]))
fi=min(fi,tot)
print(fi)
``` | instruction | 0 | 77,703 | 12 | 155,406 |
No | output | 1 | 77,703 | 12 | 155,407 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given the array a consisting of n elements and the integer k β€ n.
You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations:
* Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of a is mn then you choose such index i that a_i = mn and set a_i := a_i + 1);
* take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of a is mx then you choose such index i that a_i = mx and set a_i := a_i - 1).
Your task is to calculate the minimum number of moves required to obtain at least k equal elements in the array.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 2 β
10^5) β the number of elements in a and the required number of equal elements.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is the i-th element of a.
Output
Print one integer β the minimum number of moves required to obtain at least k equal elements in the array.
Examples
Input
6 5
1 2 2 4 2 3
Output
3
Input
7 5
3 3 2 1 1 1 3
Output
4
Submitted Solution:
```
'''Author- Akshit Monga'''
from sys import stdin,stdout
input=stdin.readline
t=1
for _ in range(t):
n,p=map(int,input().split())
a=[int(x) for x in input().split()]
vals=set()
dict={}
for i in a:
k=0
while i:
if i in dict:
dict[i].append(k)
else:
dict[i]=[k]
vals.add(i)
i//=2
k+=1
print(vals)
print(dict)
ans = float('inf')
for i in dict:
if len(dict[i])>=p:
ans=min(ans,sum(sorted(dict[i])[:p]))
print(ans)
``` | instruction | 0 | 77,704 | 12 | 155,408 |
No | output | 1 | 77,704 | 12 | 155,409 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
Consider a permutation p of length n, we build a graph of size n using it as follows:
* For every 1 β€ i β€ n, find the largest j such that 1 β€ j < i and p_j > p_i, and add an undirected edge between node i and node j
* For every 1 β€ i β€ n, find the smallest j such that i < j β€ n and p_j > p_i, and add an undirected edge between node i and node j
In cases where no such j exists, we make no edges. Also, note that we make edges between the corresponding indices, not the values at those indices.
For clarity, consider as an example n = 4, and p = [3,1,4,2]; here, the edges of the graph are (1,3),(2,1),(2,3),(4,3).
A permutation p is cyclic if the graph built using p has at least one simple cycle.
Given n, find the number of cyclic permutations of length n. Since the number may be very large, output it modulo 10^9+7.
Please refer to the Notes section for the formal definition of a simple cycle
Input
The first and only line contains a single integer n (3 β€ n β€ 10^6).
Output
Output a single integer 0 β€ x < 10^9+7, the number of cyclic permutations of length n modulo 10^9+7.
Examples
Input
4
Output
16
Input
583291
Output
135712853
Note
There are 16 cyclic permutations for n = 4. [4,2,1,3] is one such permutation, having a cycle of length four: 4 β 3 β 2 β 1 β 4.
Nodes v_1, v_2, β¦, v_k form a simple cycle if the following conditions hold:
* k β₯ 3.
* v_i β v_j for any pair of indices i and j. (1 β€ i < j β€ k)
* v_i and v_{i+1} share an edge for all i (1 β€ i < k), and v_1 and v_k share an edge. | instruction | 0 | 77,718 | 12 | 155,436 |
Tags: combinatorics, dp, graphs, math
Correct Solution:
```
from sys import stdin, stdout
import math,sys,heapq
from itertools import permutations, combinations
from collections import defaultdict,deque,OrderedDict
from os import path
import bisect as bi
def yes():print('YES')
def no():print('NO')
if (path.exists('input.txt')):
#------------------Sublime--------------------------------------#
sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
def I():return (int(input()))
def In():return(map(int,input().split()))
else:
#------------------PYPY FAst I/o--------------------------------#
def I():return (int(stdin.readline()))
def In():return(map(int,stdin.readline().split()))
sys.setrecursionlimit(1500)
def dict(a):
d={}
for x in a:
if d.get(x,-1)!=-1:
d[x]+=1
else:
d[x]=1
return d
def find_gt(a, x):
'Find leftmost value greater than x'
i = bi.bisect_right(a, x)
if i != len(a):
return i
else:
return -1
def main():
try:
n=I()
ans=1
for x in range(1,n+1):
ans=((ans%P)*(x%P))%P
temp=2
for x in range(n-2):
temp=((temp%P)*(2%P))%P
print((ans%P-temp%P)%P)
except:
pass
M = 998244353
P = 1000000007
if __name__ == '__main__':
#for _ in range(I()):main()
for _ in range(1):main()
``` | output | 1 | 77,718 | 12 | 155,437 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
Consider a permutation p of length n, we build a graph of size n using it as follows:
* For every 1 β€ i β€ n, find the largest j such that 1 β€ j < i and p_j > p_i, and add an undirected edge between node i and node j
* For every 1 β€ i β€ n, find the smallest j such that i < j β€ n and p_j > p_i, and add an undirected edge between node i and node j
In cases where no such j exists, we make no edges. Also, note that we make edges between the corresponding indices, not the values at those indices.
For clarity, consider as an example n = 4, and p = [3,1,4,2]; here, the edges of the graph are (1,3),(2,1),(2,3),(4,3).
A permutation p is cyclic if the graph built using p has at least one simple cycle.
Given n, find the number of cyclic permutations of length n. Since the number may be very large, output it modulo 10^9+7.
Please refer to the Notes section for the formal definition of a simple cycle
Input
The first and only line contains a single integer n (3 β€ n β€ 10^6).
Output
Output a single integer 0 β€ x < 10^9+7, the number of cyclic permutations of length n modulo 10^9+7.
Examples
Input
4
Output
16
Input
583291
Output
135712853
Note
There are 16 cyclic permutations for n = 4. [4,2,1,3] is one such permutation, having a cycle of length four: 4 β 3 β 2 β 1 β 4.
Nodes v_1, v_2, β¦, v_k form a simple cycle if the following conditions hold:
* k β₯ 3.
* v_i β v_j for any pair of indices i and j. (1 β€ i < j β€ k)
* v_i and v_{i+1} share an edge for all i (1 β€ i < k), and v_1 and v_k share an edge. | instruction | 0 | 77,719 | 12 | 155,438 |
Tags: combinatorics, dp, graphs, math
Correct Solution:
```
n=int(input())
v=10**9 + 7
def modexp(a,b,c):
if b==1:
return a
if b%2==0:
y=modexp(a,b//2,c)
z= (y*y)
if z>=c:
z=z%c
return z
else:
y=modexp(a,b//2,c)
z=y*y
if z>=c:
z=z%c
x=a*z
if x>=c:
x=x%c
return x
g=1
for i in range(1,n+1):
g=g*i
if g>v:
g=g%v
h=modexp(2,n-1,v)
o=g-h
print(o%v)
``` | output | 1 | 77,719 | 12 | 155,439 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
Consider a permutation p of length n, we build a graph of size n using it as follows:
* For every 1 β€ i β€ n, find the largest j such that 1 β€ j < i and p_j > p_i, and add an undirected edge between node i and node j
* For every 1 β€ i β€ n, find the smallest j such that i < j β€ n and p_j > p_i, and add an undirected edge between node i and node j
In cases where no such j exists, we make no edges. Also, note that we make edges between the corresponding indices, not the values at those indices.
For clarity, consider as an example n = 4, and p = [3,1,4,2]; here, the edges of the graph are (1,3),(2,1),(2,3),(4,3).
A permutation p is cyclic if the graph built using p has at least one simple cycle.
Given n, find the number of cyclic permutations of length n. Since the number may be very large, output it modulo 10^9+7.
Please refer to the Notes section for the formal definition of a simple cycle
Input
The first and only line contains a single integer n (3 β€ n β€ 10^6).
Output
Output a single integer 0 β€ x < 10^9+7, the number of cyclic permutations of length n modulo 10^9+7.
Examples
Input
4
Output
16
Input
583291
Output
135712853
Note
There are 16 cyclic permutations for n = 4. [4,2,1,3] is one such permutation, having a cycle of length four: 4 β 3 β 2 β 1 β 4.
Nodes v_1, v_2, β¦, v_k form a simple cycle if the following conditions hold:
* k β₯ 3.
* v_i β v_j for any pair of indices i and j. (1 β€ i < j β€ k)
* v_i and v_{i+1} share an edge for all i (1 β€ i < k), and v_1 and v_k share an edge. | instruction | 0 | 77,720 | 12 | 155,440 |
Tags: combinatorics, dp, graphs, math
Correct Solution:
```
n = int(input())
fact = 1;
two = 1;
for i in range(1, n + 1):
fact *= i
fact %= 1000000007
for i in range(1, n):
two *= 2
two %= 1000000007
print((fact - two) % 1000000007)
``` | output | 1 | 77,720 | 12 | 155,441 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
Consider a permutation p of length n, we build a graph of size n using it as follows:
* For every 1 β€ i β€ n, find the largest j such that 1 β€ j < i and p_j > p_i, and add an undirected edge between node i and node j
* For every 1 β€ i β€ n, find the smallest j such that i < j β€ n and p_j > p_i, and add an undirected edge between node i and node j
In cases where no such j exists, we make no edges. Also, note that we make edges between the corresponding indices, not the values at those indices.
For clarity, consider as an example n = 4, and p = [3,1,4,2]; here, the edges of the graph are (1,3),(2,1),(2,3),(4,3).
A permutation p is cyclic if the graph built using p has at least one simple cycle.
Given n, find the number of cyclic permutations of length n. Since the number may be very large, output it modulo 10^9+7.
Please refer to the Notes section for the formal definition of a simple cycle
Input
The first and only line contains a single integer n (3 β€ n β€ 10^6).
Output
Output a single integer 0 β€ x < 10^9+7, the number of cyclic permutations of length n modulo 10^9+7.
Examples
Input
4
Output
16
Input
583291
Output
135712853
Note
There are 16 cyclic permutations for n = 4. [4,2,1,3] is one such permutation, having a cycle of length four: 4 β 3 β 2 β 1 β 4.
Nodes v_1, v_2, β¦, v_k form a simple cycle if the following conditions hold:
* k β₯ 3.
* v_i β v_j for any pair of indices i and j. (1 β€ i < j β€ k)
* v_i and v_{i+1} share an edge for all i (1 β€ i < k), and v_1 and v_k share an edge. | instruction | 0 | 77,721 | 12 | 155,442 |
Tags: combinatorics, dp, graphs, math
Correct Solution:
```
import math
M = 10 ** 9 + + 7
def fact(x):
ans = 1
for i in range(2, x + 1):
ans = (ans * i) % M
return ans
def modpow(b, p):
res = 1
while p:
if p % 2:
res = (res * b) % M
p >>= 1
b = (b * b) % M
return res
def tc():
n = int(input())
f = fact(n)
ans = (f - modpow(2, n - 1)) % M
print(ans)
#################
tc()
``` | output | 1 | 77,721 | 12 | 155,443 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
Consider a permutation p of length n, we build a graph of size n using it as follows:
* For every 1 β€ i β€ n, find the largest j such that 1 β€ j < i and p_j > p_i, and add an undirected edge between node i and node j
* For every 1 β€ i β€ n, find the smallest j such that i < j β€ n and p_j > p_i, and add an undirected edge between node i and node j
In cases where no such j exists, we make no edges. Also, note that we make edges between the corresponding indices, not the values at those indices.
For clarity, consider as an example n = 4, and p = [3,1,4,2]; here, the edges of the graph are (1,3),(2,1),(2,3),(4,3).
A permutation p is cyclic if the graph built using p has at least one simple cycle.
Given n, find the number of cyclic permutations of length n. Since the number may be very large, output it modulo 10^9+7.
Please refer to the Notes section for the formal definition of a simple cycle
Input
The first and only line contains a single integer n (3 β€ n β€ 10^6).
Output
Output a single integer 0 β€ x < 10^9+7, the number of cyclic permutations of length n modulo 10^9+7.
Examples
Input
4
Output
16
Input
583291
Output
135712853
Note
There are 16 cyclic permutations for n = 4. [4,2,1,3] is one such permutation, having a cycle of length four: 4 β 3 β 2 β 1 β 4.
Nodes v_1, v_2, β¦, v_k form a simple cycle if the following conditions hold:
* k β₯ 3.
* v_i β v_j for any pair of indices i and j. (1 β€ i < j β€ k)
* v_i and v_{i+1} share an edge for all i (1 β€ i < k), and v_1 and v_k share an edge. | instruction | 0 | 77,722 | 12 | 155,444 |
Tags: combinatorics, dp, graphs, math
Correct Solution:
```
mod = 1000000007
n = int(input())
a = 1
for i in range(1, n + 1):
a = (a * i) % mod
b = pow(2, n - 1, mod)
ans = (a - b + mod) % mod
print(ans)
``` | output | 1 | 77,722 | 12 | 155,445 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.