Beginner In CP ....
- Scanline Algorithm
- Meet In The Middle
1 Prefix Trick Also Know As Scanline Algorithm:
Yrr Dekh maanle ik question h ki ik Array di hui h or Then Q no. of query di hui h ki L R X mtlb l se r range tk x add krna h or output last mein array print krni h q query k baad output kya hoga to normal krega to compexity n*q jayegi . Best ye h ki ik array bana nayi usko 0 se initialize krio or let naam h uska Prefix[n+1] (n+1 size is important ) to kya krna h hr L R X k liye prefix[l]=prefix[l]+X And prefix[r+1]=prefix[r+1]-X ; or jab sari query ho jaye or hamme array print krni ho ki change krne k baad kya aayi h sabse pehle prefix array ka prefix sum array nikal prefix sum arrray vo contain kr rha hoga jo kisi A[i] mein change hoga bss phir print krde prefixsum[i]+A[i] for i 1 se N tak k liye . Now Time Taken is Q+N . https://www.hackerrank.com/contests/ab-yeh-kar-ke-dikhao/challenges/kj-and-street-lights/problem https://www.codechef.com/COW42020/problems/COW3E/
2 Meet In The Middle
Given a set of n integers where n <= 40. Each of them is at most 10^12, determine the maximum sum subset having sum equal S where S <= 10^18.
The General Solution is To Calculate every Possible solution and check it as then complexity will be 2^40 which is too high
So the Meet In The Middle states that rather than apply approach on whole array and divide in two and then apply that approach .
when n = 32 to 40 then there is a chance this theorem can be applied too.....
//MEET IN THE MIDDLE
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
signed main() {
ll n, s;
cin >> n >> s;
ll A[n];
for (ll i = 0; i < n; i++)
cin >> A[i];
vector<ll> arr1;
vector<ll> arr2;
for (ll i = 0; i < (n + 1) / 2; i++)
arr1.push_back(A[i]);
for (ll i = ((n + 1) / 2 ); i < n; i++)
arr2.push_back(A[i]);
ll n1 = arr1.size();
ll n2 = arr2.size();
//Power Set
vector<ll> vect1;
vector<ll> vect2;
for (ll i = 0; i < (1 << n1); i++) {
ll sum = 0;
for (ll j = 0; j < n1; j++) {
if (i & (1 << j)) {
sum += arr1[j];
}
}
vect1.push_back(sum);
}
map<ll, ll> tmap;
for (ll i = 0; i < (1 << n2); i++) {
ll sum = 0;
for (ll j = 0; j < n2; j++) {
if (i & (1 << j)) {
sum += arr2[j];
}
}
vect2.push_back(sum);
tmap[sum]++;
}
sort(vect2.begin(), vect2.end());
ll cnt = 0;
for (auto it : vect1) {
//cout << it << endl;
cnt += tmap[s - it];
}
cout << cnt;
}