diff --git a/algos/range_queries/PrefixSum/soln/IshanRajSingh/Solution3.py b/algos/range_queries/PrefixSum/soln/IshanRajSingh/Solution3.py new file mode 100644 index 0000000..6405a3b --- /dev/null +++ b/algos/range_queries/PrefixSum/soln/IshanRajSingh/Solution3.py @@ -0,0 +1,36 @@ +# Submission Link: https://codeforces.com/contest/1605/submission/356614528 +# Approach: find all 1s that should be 0 (from left) and all 0s that should be 1 (from right), if any mismatches do one operation +# Runtime: O(n) per test +import sys +input=sys.stdin.readline +t=int(input().strip()) +for _ in range(t): + n=int(input().strip()) + s=list(input().strip()) + zeros=sorted([i for i in range(n) if s[i]=='0']) + ones=sorted([i for i in range(n) if s[i]=='1']) + l, r=0,len(zeros)-1 + i, j=0,len(ones)-1 + left=0 + right=n-1 + badL=[] + badR=[] + # two pointers: from left find 1 before a zero that should be left + lptr=0 + rptr=n-1 + while lptr=0 and s[rptr]=='1': + rptr-=1 + if lptr half ones using prefix sums +# Runtime: O((n+m) log q) +import sys +input=sys.stdin.readline + +def check(mid, n, segs, ord): + arr=[0]*n + for i in range(mid): + arr[ord[i]] = 1 + pref=[0]*(n+1) + for i in range(n): + pref[i+1]=pref[i]+arr[i] + for l,r in segs: + if pref[r+1]-pref[l] > (r-l+1)//2: + return True + return False + +t=int(input().strip()) +for _ in range(t): + n,m=map(int,input().split()) + segs=[tuple(map(lambda x: int(x)-1, input().split())) for _ in range(m)] + q=int(input().strip()) + ord=[int(input().strip())-1 for _ in range(q)] + lo,hi=0,q+1 + while hi-lo>1: + mid=(lo+hi)//2 + if check(mid,n,segs,ord): + hi=mid + else: + lo=mid + ans = hi if hi<=q else -1 + print(ans)