File tree Expand file tree Collapse file tree 1 file changed +82
-0
lines changed
CompetitiveProgramming/CodeChef Expand file tree Collapse file tree 1 file changed +82
-0
lines changed Original file line number Diff line number Diff line change
1
+ def binarySearchCountLess (arr , n , key ):
2
+
3
+ left = 0
4
+ right = n
5
+
6
+ mid = 0
7
+ while (left < right ):
8
+
9
+ mid = (right + left )// 2
10
+ if (arr [mid ] == key ):
11
+
12
+ while (mid + 1 < n and arr [mid + 1 ] == key ):
13
+ mid += 1
14
+ break
15
+
16
+ elif (arr [mid ] > key ):
17
+ right = mid
18
+ else :
19
+ left = mid + 1
20
+
21
+ while (mid > - 1 and arr [mid ] > key ):
22
+ mid -= 1
23
+
24
+ return mid + 1
25
+
26
+ def main ():
27
+ t = int (input ())
28
+ for _ in range (t ):
29
+ n , x , p , k = [int (y ) for y in input ().split ()]
30
+ a = [int (y ) for y in input ().split ()]
31
+ a .sort ()
32
+ if n <= 5 :
33
+ count = 0
34
+ if a [p - 1 ] == x :
35
+ print (0 )
36
+ else :
37
+ for i in range (n + 1 ):
38
+ a [k - 1 ] = x
39
+ a .sort ()
40
+ count += 1
41
+ if a [p - 1 ] == x :
42
+ print (count )
43
+ break
44
+ if a [p - 1 ] != x :
45
+ print (- 1 )
46
+ else :
47
+ if a [p - 1 ] == x :
48
+ res = 0
49
+ else :
50
+ if p < k :
51
+ if a [p - 1 ] < x :
52
+ res = - 1
53
+ else :
54
+ ind = binarySearchCountLess (a , n , x )
55
+ res = p - ind
56
+ elif p > k :
57
+ if a [p - 1 ] > x :
58
+ res = - 1
59
+ else :
60
+ ind = binarySearchCountLess (a , n , x )
61
+ if a [ind - 1 ] != x :
62
+ ind += 1
63
+ else :
64
+ while True :
65
+ if a [ind - 2 ] == x :
66
+ ind -= 1
67
+ else :
68
+ break
69
+ res = ind - p
70
+ else :
71
+ if x < a [p - 1 ]:
72
+ ind = binarySearchCountLess (a , n , x )
73
+ res = p - ind
74
+ else :
75
+ ind = binarySearchCountLess (a , n , x )
76
+ if a [ind - 1 ] != x :
77
+ ind += 1
78
+ res = ind - p
79
+ print (res )
80
+ return 0
81
+
82
+ main ()
You can’t perform that action at this time.
0 commit comments