From 83348ee188af6641fd44380c9518e970fecc2485 Mon Sep 17 00:00:00 2001 From: Abhik Das Date: Thu, 22 Jul 2021 13:31:08 +0530 Subject: [PATCH] added more square root decomposition problems --- mo's_algo_for_subarray_sum.cpp | 68 ++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 mo's_algo_for_subarray_sum.cpp diff --git a/mo's_algo_for_subarray_sum.cpp b/mo's_algo_for_subarray_sum.cpp new file mode 100644 index 0000000..5e9f1be --- /dev/null +++ b/mo's_algo_for_subarray_sum.cpp @@ -0,0 +1,68 @@ +#include +using namespace std; +#define int long long +const int N = 1e5+2, MOD = 1e9+7; +int rootN; + +struct Q { + int idx, l, r; +}; + +Q q[N]; + +bool compare(Q q1, Q q2) { + if(q1.l/rootN == q2.l/rootN) + return q1.r > q2.r; + + return q1.l/rootN < q2.l/rootN; +} + +signed main() { + int n; + cin>>n; + + vector a(n); + for(int i=0; i>a[i]; + + rootN = sqrtl(n); + int queries; + cin>>queries; + for(int i=0; i>l>>r; + q[i].l = l; + q[i].r = r; + q[i].idx = i; + } + + sort(q, q+queries, compare); + vector ans(queries); + int curr_l = 0, curr_r = -1, l, r; + int curr_ans = 0; + + for(int i=0; i l) + curr_ans += a[--curr_l]; + + while(curr_l < l) + curr_ans -= a[curr_l++]; + + while(curr_r > r) + curr_ans -= a[curr_r--]; + + ans[q[i].idx] = curr_ans; + } + + for(int i=0; i