├── STsum_update.cpp ├── centroiddecomp.cpp ├── dfs.cpp ├── diameter_tree.txt ├── dijsktra.cpp ├── divisors.cpp ├── divisorsUsingPrimeFactors.cpp ├── fenwick_tree.cpp ├── fibologn.cpp ├── hld.cpp ├── kmp.cpp ├── kruskal.cpp ├── lazytree.cpp ├── lca.cpp ├── linkedlist.cpp ├── maxxorsubarray.cpp ├── mo.cpp ├── modInverse.cpp ├── nCr in O(1) ├── nCr.cpp ├── primefactorsseive.cpp ├── rabin_karp.cpp ├── segmenttreeobj.cpp ├── sparsetable.cpp ├── spojss1.cpp ├── stackusinglinklist.c ├── subarrayswithxor-m.cpp ├── toposort.cpp ├── trie.c └── z_function.c++ /STsum_update.cpp: -------------------------------------------------------------------------------- 1 | class SGTree { 2 | vector seg; 3 | public: 4 | SGTree(int n) { 5 | seg.resize(4 * n + 1); 6 | } 7 | 8 | void build(int ind, int low, int high, int arr[]) { 9 | if (low == high) { 10 | seg[ind] = arr[low]; 11 | return; 12 | } 13 | 14 | int mid = (low + high) / 2; 15 | build(2 * ind + 1, low, mid, arr); 16 | build(2 * ind + 2, mid + 1, high, arr); 17 | seg[ind] = min(seg[2 * ind + 1], seg[2 * ind + 2]); 18 | } 19 | 20 | int query(int ind, int low, int high, int l, int r) { 21 | // no overlap 22 | // l r low high or low high l r 23 | if (r < low || high < l) return INT_MAX; 24 | 25 | // complete overlap 26 | // [l low high r] 27 | if (low >= l && high <= r) return seg[ind]; 28 | 29 | int mid = (low + high) >> 1; 30 | int left = query(2 * ind + 1, low, mid, l, r); 31 | int right = query(2 * ind + 2, mid + 1, high, l, r); 32 | return min(left, right); 33 | } 34 | void update(int ind, int low, int high, int i, int val) { 35 | if (low == high) { 36 | seg[ind] = val; 37 | return; 38 | } 39 | 40 | int mid = (low + high) >> 1; 41 | if (i <= mid) update(2 * ind + 1, low, mid, i, val); 42 | else update(2 * ind + 2, mid + 1, high, i, val); 43 | seg[ind] = min(seg[2 * ind + 1], seg[2 * ind + 2]); 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /centroiddecomp.cpp : -------------------------------------------------------------------------------- 1 | typedef pair II; 2 | typedef vector< II > VII; 3 | typedef vector VI; 4 | typedef vector< VI > VVI; 5 | typedef long long int LL; 6 | typedef unsigned long long int ULL; 7 | 8 | const int N = int(1e5)+10; 9 | const int LOGN = 20; 10 | const int INF = int(1e9); 11 | set g[N]; 12 | int par[N],sub[N],level[N],ans[N]; 13 | int DP[LOGN][N]; 14 | int n,m; 15 | 16 | 17 | // par[] array gives the root of the node 18 | // in the centroid tree 19 | 20 | 21 | /*Using centroid Decomposition of a tree */ 22 | 23 | 24 | /*----------- Pre-Processing ------------*/ 25 | void dfs0(int u) 26 | { 27 | for(auto it=g[u].begin();it!=g[u].end();it++) 28 | if(*it!=DP[0][u]) 29 | { 30 | DP[0][*it]=u; 31 | level[*it]=level[u]+1; 32 | dfs0(*it); 33 | } 34 | } 35 | void preprocess() 36 | { 37 | level[0]=0; 38 | DP[0][0]=0; 39 | dfs0(0); 40 | for(int i=1;ilevel[b])swap(a,b); 47 | int d = level[b]-level[a]; 48 | for(int i=0;i=0;i--) 53 | if(DP[i][a]!=DP[i][b]) 54 | a=DP[i][a],b=DP[i][b]; 55 | return DP[0][a]; 56 | } 57 | int dist(int u,int v) 58 | { 59 | return level[u] + level[v] - 2*level[lca(u,v)]; 60 | } 61 | 62 | 63 | 64 | /*-----------------Decomposition Part--------------------------*/ 65 | int nn; 66 | 67 | // Function to run dfs 68 | // and count the nodes under that node 69 | void dfs1(int u,int p) 70 | { 71 | sub[u]=1; 72 | nn++; 73 | for(auto it=g[u].begin();it!=g[u].end();it++) 74 | if(*it!=p) 75 | { 76 | dfs1(*it,u); 77 | sub[u]+=sub[*it]; 78 | } 79 | } 80 | 81 | // Function to decompose the tree 82 | // using dfs such that eevry node can be the 83 | // centroid of the given subtree 84 | int dfs2(int u,int p) 85 | { 86 | for(auto it=g[u].begin();it!=g[u].end();it++) 87 | if(*it!=p && sub[*it]>nn/2) 88 | return dfs2(*it,u); 89 | return u; 90 | } 91 | 92 | // Function to decompose the tree 93 | void decompose(int root,int p) 94 | { 95 | nn=0; 96 | dfs1(root,root); 97 | int centroid = dfs2(root,root); 98 | if(p==-1)p=centroid; 99 | par[centroid]=p; 100 | for(auto it=g[centroid].begin();it!=g[centroid].end();it++) 101 | { 102 | g[*it].erase(centroid); 103 | decompose(*it,centroid); 104 | } 105 | g[centroid].clear(); 106 | } -------------------------------------------------------------------------------- /dfs.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | using namespace std; 5 | bool vis[(int)(1e5+1)]; 6 | // graph waali 7 | void dfs(int u) 8 | { 9 | vis[u] = true; 10 | for(int i:v[u]) 11 | { 12 | if(!vis[i]) 13 | dfs(i); 14 | } 15 | 16 | } 17 | 18 | // tree waali 19 | void dfs(int child,int parent) 20 | { 21 | v[child]=parent; 22 | for(int i:v[child]) 23 | { 24 | if(i!=v[child]) 25 | dfs(i,child); 26 | } 27 | } -------------------------------------------------------------------------------- /diameter_tree.txt: -------------------------------------------------------------------------------- 1 | pair bfs(int root){ 2 | vector distt(n+1, 0); 3 | distt[root] = 1; 4 | queue q; 5 | q.push(root); 6 | while(!q.empty()){ 7 | int curr = q.front(); 8 | for(auto it : g[curr]){ 9 | if(distt[it] != 0){ 10 | continue; 11 | } 12 | q.push(it); 13 | distt[it] = distt[curr] + 1; 14 | } 15 | q.pop(); 16 | } 17 | int mx = INT_MIN, vertex = -1; 18 | for(int i=1 ; i<=n ; i++){ 19 | if(mx < distt[i]){ 20 | mx = distt[i]; 21 | vertex = i; 22 | } 23 | } 24 | return make_pair(mx, vertex); 25 | } 26 | 27 | int diameter(int root){ 28 | pair p1 = bfs(root), p2; 29 | 30 | xx = p1.second; 31 | 32 | 33 | p2 = bfs(p1.second); 34 | 35 | yy = p2.second; 36 | return p2.first; 37 | } -------------------------------------------------------------------------------- /dijsktra.cpp: -------------------------------------------------------------------------------- 1 | // Time complexity : O(ElogV) 2 | #include 3 | using namespace std; 4 | 5 | typedef vector vi; 6 | typedef pair pii; 7 | typedef vector< pii > vii; 8 | #define INF 0x3f3f3f3f 9 | 10 | vii *G; // Graph 11 | vi Dist; // for storing the distance of every other node from source. 12 | /*==========================================*/ 13 | void Dijkstra(int source, int N) { 14 | priority_queue, greater > Q; // min heap 15 | Dist.assign(N,INF); 16 | Dist[source] = 0; 17 | Q.push({0,source}); 18 | while(!Q.empty()){ 19 | int u = Q.top().second; 20 | Q.pop(); 21 | for(auto &c : G[u]){ 22 | int v = c.first; 23 | int w = c.second; 24 | if(Dist[v] > Dist[u]+w){ 25 | Dist[v] = Dist[u]+w; 26 | Q.push({Dist[v],v}); 27 | } 28 | } 29 | } 30 | } 31 | /*===========================================*/ 32 | int main() { 33 | int N, M, u, v, w, source; // N-total no of nodes, M-no. of edges, 34 | cin >> N >> M; // u,v and w are the end vertices and the weight associated with an edge 35 | G = new vii[N+1]; 36 | 37 | for(int i=0;i> u >> v >> w; 39 | G[u].push_back({v,w}); 40 | G[v].push_back({u,w}); 41 | } 42 | cin >> source; 43 | Dijkstra(source,N); 44 | 45 | for(int i=0;iprime; 2 | 3 | void process(){ 4 | int N = sqrt(1e10)+5; 5 | int prm[N+2]; 6 | memset(prm,0,sizeof prm); 7 | for(int i=2;i<=N;i++){ 8 | if(!prm[i]){ 9 | prime.pb(i); 10 | for(int j=i;j<=N;j+=i){ 11 | prm[j]=1; 12 | } 13 | } 14 | } 15 | } 16 | int NOD(int x){ 17 | int temp = x,ret=1; 18 | for(auto i:prime){ 19 | if(i*i>temp || temp==1) 20 | break; 21 | int cnt=0; 22 | while(temp%i==0) temp/=i,cnt++; 23 | ret*=(cnt+1); 24 | } 25 | if(temp>1) 26 | ret*=2; 27 | return ret; 28 | } -------------------------------------------------------------------------------- /divisorsUsingPrimeFactors.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define m 1000000007 4 | #define ll long long 5 | int main() 6 | { 7 | long long n; 8 | cin >> n; 9 | ll a[n]; 10 | ll sum=1ll; 11 | for(ll i=0;i> a[i]; 14 | sum=(sum*(a[i]+1))%m; 15 | } 16 | 17 | ll sum1=1ll; 18 | //cout << sum1<a[j] count and etc etc 7 | 8 | 9 | // Initially fenwick is fen[maxsize] = 0; 10 | 11 | 12 | // Function to update any index 13 | int update(int ind, int val) 14 | { 15 | for(int i = ind;i<=maxsize; i+= i & -i) 16 | fen[i] += val; 17 | } 18 | 19 | // Function to get the prefix sum or suffix sum 20 | int sum(int ind) 21 | { 22 | int ans = 0; 23 | for(int i = ind; i > 0 ; i-= i& -i) 24 | ans +=fen[i]; 25 | 26 | return ans; 27 | } 28 | -------------------------------------------------------------------------------- /fibologn.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | void multiply(long long F[2][2], long long M[2][2],int m); 4 | 5 | void power(long long F[2][2], int n,int m); 6 | 7 | /* function that returns nth Fibonacci number */ 8 | long long fib(int n,int m) 9 | { 10 | long long F[2][2] = {{1,1},{1,0}}; 11 | if (n == 0) 12 | return 0; 13 | power(F, n-1,m); 14 | return F[0][0]; 15 | } 16 | 17 | /* Optimized version of power() in method 4 */ 18 | void power(long long F[2][2], int n,int m) 19 | { 20 | if( n == 0 || n == 1) 21 | return; 22 | long long M[2][2] = {{1,1},{1,0}}; 23 | 24 | power(F, n/2,m); 25 | multiply(F, F,m); 26 | 27 | if (n%2 != 0) 28 | multiply(F, M,m); 29 | } 30 | 31 | void multiply(long long F[2][2], long long M[2][2],int m) 32 | { 33 | long long x = ((F[0][0]*M[0][0]) + F[0][1]*M[1][0])%m; 34 | long long y = ((F[0][0]*M[0][1]) + F[0][1]*M[1][1])%m; 35 | long long z = ((F[1][0]*M[0][0]) + F[1][1]*M[1][0])%m; 36 | long long w = ((F[1][0]*M[0][1]) + F[1][1]*M[1][1])%m; 37 | 38 | F[0][0] = x; 39 | F[0][1] = y; 40 | F[1][0] = z; 41 | F[1][1] = w; 42 | } 43 | 44 | /* Driver program to test above function */ 45 | int main() 46 | { 47 | 48 | // in Case mod dia hua th m lena wrna remove M har jagah se 49 | 50 | cout< 2 | #include 3 | using namespace std; 4 | 5 | #define root 0 6 | #define N 10100 7 | #define LN 14 8 | 9 | vector adj[N], costs[N], indexx[N]; 10 | int baseArray[N], ptr; 11 | int chainNo, chainInd[N], chainHead[N], posInBase[N]; 12 | int depth[N], pa[LN][N], otherEnd[N], subsize[N]; 13 | int st[N*6]; 14 | 15 | /* 16 | * make_tree: 17 | * Used to construct the segment tree. 18 | It uses the baseArray for construction 19 | */ 20 | 21 | // Initiall 1,0,n 22 | void make_tree(int cur, int s, int e) { 23 | 24 | // all nodes 25 | if(s == e-1) { 26 | st[cur] = baseArray[s]; 27 | return; 28 | } 29 | 30 | int c1 = (cur<<1), c2 = c1 | 1, m = (s+e)>>1; 31 | make_tree(2*cur, s, m); 32 | make_tree(2*cur+1, m, e); 33 | st[cur] = st[c1] > st[c2] ? st[c1] : st[c2]; 34 | } 35 | 36 | /* 37 | * update_tree: 38 | * Point update. Update a single element of the segment tree. 39 | */ 40 | void update_tree(int cur, int s, int e, int x, int val) { 41 | if(s > x || e <= x) return; 42 | if(s == x && s == e-1) { 43 | st[cur] = val; 44 | return; 45 | } 46 | int c1 = (cur<<1), c2 = c1 | 1, m = (s+e)>>1; 47 | 48 | //cout << c1 << " " << c2 << " " << cur << endl; 49 | update_tree(c1, s, m, x, val); 50 | update_tree(c2, m, e, x, val); 51 | st[cur] = st[c1] > st[c2] ? st[c1] : st[c2]; 52 | } 53 | 54 | /* 55 | * query_tree: 56 | * Given S and E, it will return the maximum value in the range [S,E) 57 | */ 58 | int query_tree(int cur, int s, int e, int S, int E) { 59 | if(s >= E || e <= S) { 60 | 61 | return -1; 62 | } 63 | if(s >= S && e <= E) { 64 | return st[cur]; 65 | 66 | } 67 | int c1 = (cur<<1), c2 = c1 | 1, m = (s+e)>>1; 68 | return max(query_tree(c1, s, m, S, E),query_tree(c2, m, e, S, E)); 69 | } 70 | 71 | /* 72 | * query_up: 73 | * It takes two nodes u and v, condition is that v is an ancestor of u 74 | * We query the chain in which u is present till chain head, then move to next chain up 75 | * We do that way till u and v are in the same chain, we query for that part of chain and break 76 | */ 77 | 78 | int query_up(int u, int v) { 79 | if(u == v) return 0; // Trivial 80 | int uchain, vchain = chainInd[v], ans = -1; 81 | // uchain and vchain are chain numbers of u and v 82 | while(1) { 83 | uchain = chainInd[u]; 84 | if(uchain == vchain) { 85 | // Both u and v are in the same chain, so we need to query from u to v, update answer and break. 86 | // We break because we came from u up till v, we are done 87 | if(u==v) break; 88 | ans = max(ans,query_tree(1, 0, ptr, posInBase[v]+1, posInBase[u]+1)); 89 | // Above is call to segment tree query function 90 | //if(qt[1] > ans) ans = qt[1]; // Update answer 91 | break; 92 | } 93 | ans = max(ans,query_tree(1, 0, ptr, posInBase[chainHead[uchain]], posInBase[u]+1)); 94 | // Above is call to segment tree query function. We do from chainHead of u till u. That is the whole chain from 95 | // start till head. We then update the answer 96 | //if(qt[1] > ans) ans = qt[1]; 97 | u = chainHead[uchain]; // move u to u's chainHead 98 | u = pa[0][u]; //Then move to its parent, that means we changed chains 99 | } 100 | return ans; 101 | } 102 | 103 | /* 104 | * LCA: 105 | * Takes two nodes u, v and returns Lowest Common Ancestor of u, v 106 | */ 107 | int LCA(int u, int v) { 108 | if(depth[u] < depth[v]) swap(u,v); 109 | int diff = depth[u] - depth[v]; 110 | for(int i=0; i>i)&1 ) u = pa[i][u]; 111 | if(u == v) return u; 112 | for(int i=LN-1; i>=0; i--) if(pa[i][u] != pa[i][v]) { 113 | u = pa[i][u]; 114 | v = pa[i][v]; 115 | } 116 | return pa[0][u]; 117 | } 118 | 119 | void query(int u, int v) { 120 | /* 121 | * We have a query from u to v, we break it into two queries, u to LCA(u,v) and LCA(u,v) to v 122 | */ 123 | int lca = LCA(u, v); 124 | int ans = query_up(u, lca); // One part of path 125 | int temp = query_up(v, lca); // another part of path 126 | if(temp > ans) ans = temp; // take the maximum of both paths 127 | printf("%d\n", ans); 128 | } 129 | 130 | /* 131 | * change: 132 | * We just need to find its position in segment tree and update it 133 | */ 134 | void change(int i, int val) { 135 | int u = otherEnd[i]; 136 | update_tree(1, 0, ptr, posInBase[u], val); 137 | } 138 | 139 | /* 140 | * Actual HL-Decomposition part 141 | * Initially all entries of chainHead[] are set to -1. 142 | * So when ever a new chain is started, chain head is correctly assigned. 143 | * As we add a new node to chain, we will note its position in the baseArray. 144 | * In the first for loop we find the child node which has maximum sub-tree size. 145 | * The following if condition is failed for leaf nodes. 146 | * When the if condition passes, we expand the chain to special child. 147 | * In the second for loop we recursively call the function on all normal nodes. 148 | * chainNo++ ensures that we are creating a new chain for each normal child. 149 | */ 150 | void HLD(int curNode, int cost, int prev) { 151 | if(chainHead[chainNo] == -1) { 152 | chainHead[chainNo] = curNode; 153 | } 154 | chainInd[curNode] = chainNo; 155 | 156 | // Position of this node in 157 | // baseArray which we will use in Segtree 158 | posInBase[curNode] = ptr; 159 | baseArray[ptr++] = cost; 160 | 161 | int sc = -1, ncost; 162 | // Loop to find special child 163 | for(int i=0; i> t; 213 | while(t--) { 214 | ptr = 0; 215 | int n; 216 | cin >> n; 217 | 218 | // Cleaning step, new test case 219 | for(int i=0; i> u >> v >> c; 230 | u--; v--; 231 | adj[u].push_back(v); 232 | costs[u].push_back(c); 233 | indexx[u].push_back(i-1); 234 | adj[v].push_back(u); 235 | costs[v].push_back(c); 236 | indexx[v].push_back(i-1); 237 | } 238 | 239 | chainNo = 0; 240 | dfs(root, -1); // We set up subsize, depth and parent for each node 241 | 242 | HLD(root, -1, -1); // We decomposed the tree and created baseArray 243 | //cout << ptr << endl; 244 | 245 | make_tree(1, 0, n); // We use baseArray and construct the needed segment tree 246 | 247 | // Below Dynamic programming code is for LCA. 248 | for(int i=1; i> s; 256 | if(s[0]=='D') { 257 | break; 258 | } 259 | int a, b; 260 | cin >> a >> b; 261 | if(s[0]=='Q') { 262 | query(a-1, b-1); 263 | } else { 264 | change(a-1, b); 265 | } 266 | } 267 | } 268 | } -------------------------------------------------------------------------------- /kmp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | vector get_prefix(string s) 4 | { 5 | int n = s.size(); 6 | vectorprefix(n,0); 7 | int j = 0; 8 | for(int i = 1;i0) 12 | { 13 | j = prefix[j-1]; 14 | } 15 | 16 | if(s[i]==s[j]) 17 | j++; 18 | 19 | prefix[i] = j; 20 | } 21 | 22 | return prefix; 23 | } 24 | 25 | int main() 26 | { 27 | string s = "abcdxyaaxyabcd"; 28 | vectorprefix = get_prefix(s); 29 | for(auto it:prefix) 30 | cout << it << " "; 31 | } -------------------------------------------------------------------------------- /kruskal.cpp: -------------------------------------------------------------------------------- 1 | vector parent, rank; 2 | 3 | void make_set(int v) { 4 | parent[v] = v; 5 | rank[v] = 0; 6 | } 7 | 8 | int find_set(int v) { 9 | if (v == parent[v]) 10 | return v; 11 | return parent[v] = find_set(parent[v]); 12 | } 13 | 14 | void union_sets(int a, int b) { 15 | a = find_set(a); 16 | b = find_set(b); 17 | if (a != b) { 18 | if (rank[a] < rank[b]) 19 | swap(a, b); 20 | parent[b] = a; 21 | if (rank[a] == rank[b]) 22 | rank[a]++; 23 | } 24 | } 25 | 26 | struct Edge { 27 | int u, v, weight; 28 | bool operator<(Edge const& other) { 29 | return weight < other.weight; 30 | } 31 | }; 32 | 33 | int n; 34 | vector edges; 35 | 36 | int cost = 0; 37 | vector result; 38 | parent.resize(n); 39 | rank.resize(n); 40 | for (int i = 0; i < n; i++) 41 | make_set(i); 42 | 43 | sort(edges.begin(), edges.end()); 44 | 45 | for (Edge e : edges) { 46 | if (find_set(e.u) != find_set(e.v)) { 47 | cost += e.weight; 48 | result.push_back(e); 49 | union_sets(e.u, e.v); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /lazytree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define m 1000000007 4 | void lt1(int lazy[], int a, int b, int i, int j, int node,int value) { 5 | 6 | 7 | 8 | if(lazy[node] != 0) { 9 | 10 | 11 | if(a != b) { 12 | lazy[node*2+1] =(lazy[node*2+1]%m+ lazy[node]%m)%m; 13 | lazy[node*2+2] =(lazy[node*2+2]%m+ lazy[node]%m)%m; 14 | lazy[node] = 0; 15 | } 16 | 17 | 18 | } 19 | 20 | if(a > b || a > j || b < i) 21 | return; 22 | 23 | if(a >= i && b <= j) { 24 | 25 | lazy[node] =(lazy[node]%m + value%m)%m; 26 | return; 27 | } 28 | 29 | lt1(lazy, a, (a+b)/2, i, j, 2*node+1,value); 30 | lt1(lazy, 1+(a+b)/2, b, i, j,2*node+2, value); 31 | } 32 | 33 | 34 | int query_tree(int lazy[], int a, int b, int i, int j,int node) { 35 | 36 | if(a > b || a > j || b < i) return -1; 37 | 38 | if(lazy[node] != 0) { 39 | 40 | 41 | if(a != b) { 42 | lazy[node*2+1] =(lazy[node*2+1]%m+ lazy[node]%m)%m; 43 | lazy[node*2+2] =(lazy[node*2+2]%m+ lazy[node]%m)%m; 44 | lazy[node] = 0; 45 | } 46 | 47 | 48 | } 49 | 50 | if(a >= i && b <= j) 51 | return lazy[node]%m; 52 | 53 | int q1 = query_tree(lazy, a, (a+b)/2, i, j,2*node+1); 54 | int q2 = query_tree(lazy, 1+(a+b)/2, b, i, j,2*node+2); 55 | 56 | int res = max(q1%m, q2%m); 57 | 58 | return res%m; 59 | } 60 | 61 | int main() { 62 | int t; 63 | cin >> t; 64 | while(t--) 65 | { 66 | 67 | int n,q; 68 | cin >> n>> q; 69 | int i=0; 70 | int h=q; 71 | 72 | int height = (int)(ceil(log2(n))); 73 | 74 | int max_size = 2*(int)pow(2, height)+1 ; 75 | 76 | int ans[max_size] = {0}; 77 | 78 | int h2 = (int)(ceil(log2(h))); 79 | 80 | int maxSize = 2*(int)pow(2, h2) +1; 81 | 82 | int lazy[maxSize] = {0}; 83 | int a[h][3]; 84 | while(q--) 85 | { 86 | cin >> a[i][0]>>a[i][1]>>a[i][2]; 87 | i++; 88 | } 89 | 90 | for(int j=h-1;j>=0;j--) 91 | { 92 | if (a[j][0]==2) 93 | { 94 | 95 | lt1(lazy,0,h-1,a[j][1]-1,a[j][2]-1,0,query_tree(lazy,0,h-1,j,j,0)+1); 96 | } 97 | else 98 | { 99 | lt1(ans,0,n-1,a[j][1]-1,a[j][2]-1,0,query_tree(lazy,0,h-1,j,j,0)+1); 100 | } 101 | } 102 | for(int i=0;i g[N]; 10 | 11 | // Function to pre-compute DFS 12 | void dfs(int v, int p = 0) 13 | { 14 | 15 | // First parent 16 | par[v][0] = p; 17 | 18 | // Finds the parent at 2^i 19 | for (int i = 1; i <= 20; i++) 20 | par[v][i] = par[par[v][i - 1]][i - 1]; 21 | 22 | // Call DFS function 23 | for (int i = 0; i < g[v].size(); i++) { 24 | int to = g[v][i]; 25 | 26 | // Already visited 27 | if (to == p) 28 | continue; 29 | 30 | // Find the depth 31 | dep[to] = dep[v] + 1; 32 | 33 | // Call the Dfs Function 34 | dfs(to, v); 35 | } 36 | } 37 | 38 | 39 | 40 | 41 | // Function to find the lca of a and b 42 | int lca(int a, int b) 43 | { 44 | 45 | // If a is higher than b then swap them 46 | // Tree me a niche rahegi and b upar hamesha 47 | if (dep[a] < dep[b]) 48 | swap(a, b); 49 | 50 | // Make both of them at equal height 51 | for (int i = 20; i >= 0; i--) 52 | { 53 | if (dep[a] - (1 << i) >= dep[b]) 54 | a = par[a][i]; 55 | } 56 | 57 | // Now traverse till up 58 | // till we donot get parent same 59 | for (int i = 20; i >= 0; --i) 60 | { 61 | if (par[a][i] != par[b][i]) 62 | { 63 | a = par[a][i], 64 | b = par[b][i]; 65 | } 66 | } 67 | 68 | // Till now not same 69 | if (a != b) 70 | a = par[a][0]; 71 | 72 | return a; 73 | } 74 | 75 | // Function to find the distance between a and b 76 | int solve(int a, int b) 77 | { 78 | if (a == b) 79 | return 0; 80 | 81 | if (dep[a] < dep[b]) 82 | swap(a, b); 83 | 84 | // Find lca 85 | int q = lca(a, b); 86 | int dist = dep[a] + dep[b] - 2 * dep[q]; 87 | return dist; 88 | } 89 | -------------------------------------------------------------------------------- /linkedlist.cpp: -------------------------------------------------------------------------------- 1 | // http://btechsmartclass.com/DS/U2_T3.html 2 | #include 3 | using namespace std; 4 | typedef struct node 5 | { 6 | int num; 7 | struct node *ptr; 8 | }node; 9 | node *head,*first,*temp=0; 10 | void insert(int n) 11 | { 12 | first=0; 13 | for (int i=0;i> head->num; 17 | if(first!=0){temp->ptr=head;temp=head;} 18 | else first=temp=head; 19 | } 20 | temp->ptr=0; 21 | } 22 | void print() 23 | { 24 | temp=first; 25 | while(temp!=0){cout << temp->num <<" ";temp=temp->ptr;} 26 | cout << endl; 27 | } 28 | void delete1(int x) 29 | { 30 | temp=first; 31 | head=first; 32 | if(temp->num==x) { first=temp->ptr; return ;} 33 | while(temp!=0 && temp->num!=x) 34 | { 35 | head=temp; 36 | temp=temp->ptr; 37 | } 38 | head->ptr=temp->ptr; 39 | 40 | free(temp); 41 | } 42 | void add(int b) 43 | { 44 | temp=first; 45 | while(temp->ptr !=0) 46 | temp=temp->ptr; 47 | head=new node; 48 | head->num=b; 49 | temp->ptr=head; 50 | temp=head; 51 | temp->ptr=0; 52 | 53 | } 54 | int main() 55 | { 56 | int n; 57 | cin >> n; 58 | insert(n); 59 | print(); 60 | int m; 61 | cin >> m; 62 | delete1(m); 63 | print(); 64 | add(8); 65 | print(); 66 | return 0; 67 | } -------------------------------------------------------------------------------- /maxxorsubarray.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for a Trie based O(n) solution to find max 2 | // subarray XOR 3 | #include 4 | using namespace std; 5 | 6 | // Assumed int size 7 | #define INT_SIZE 32 8 | 9 | // A Trie Node 10 | struct TrieNode 11 | { 12 | int value; // Only used in leaf nodes 13 | TrieNode *arr[2]; 14 | }; 15 | 16 | // Utility function tp create a Trie node 17 | TrieNode *newNode() 18 | { 19 | TrieNode *temp = new TrieNode; 20 | temp->value = 0; 21 | temp->arr[0] = temp->arr[1] = NULL; 22 | return temp; 23 | } 24 | 25 | // Inserts pre_xor to trie with given root 26 | void insert(TrieNode *root, int pre_xor) 27 | { 28 | TrieNode *temp = root; 29 | 30 | // Start from the msb, insert all bits of 31 | // pre_xor into Trie 32 | for (int i=INT_SIZE-1; i>=0; i--) 33 | { 34 | // Find current bit in given prefix 35 | bool val = pre_xor & (1<arr[val] == NULL) 39 | temp->arr[val] = newNode(); 40 | 41 | temp = temp->arr[val]; 42 | } 43 | 44 | // Store value at leaf node 45 | temp->value = pre_xor; 46 | } 47 | 48 | // Finds the maximum XOR ending with last number in 49 | // prefix XOR 'pre_xor' and returns the XOR of this maximum 50 | // with pre_xor which is maximum XOR ending with last element 51 | // of pre_xor. 52 | int query(TrieNode *root, int pre_xor) 53 | { 54 | TrieNode *temp = root; 55 | for (int i=INT_SIZE-1; i>=0; i--) 56 | { 57 | // Find current bit in given prefix 58 | bool val = pre_xor & (1<arr[1-val]!=NULL) 63 | temp = temp->arr[1-val]; 64 | 65 | // If there is no prefix with opposite 66 | // bit, then look for same bit. 67 | else if (temp->arr[val] != NULL) 68 | temp = temp->arr[val]; 69 | } 70 | return pre_xor^(temp->value); 71 | } 72 | 73 | // Returns maximum XOR value of a subarray in arr[0..n-1] 74 | int maxSubarrayXOR(int arr[], int n) 75 | { 76 | // Create a Trie and insert 0 into it 77 | TrieNode *root = newNode(); 78 | insert(root, 0); 79 | 80 | // Initialize answer and xor of current prefix 81 | int result = INT_MIN, pre_xor =0; 82 | 83 | // Traverse all input array element 84 | for (int i=0; i 2 | using namespace std; 3 | 4 | #define int long long int 5 | 6 | const int MAX_N = 2e5 + 5; 7 | const int MAX_VAL = 1e6 + 5; 8 | 9 | int N, Q, A[MAX_N]; 10 | long long ans[MAX_N]; 11 | struct query { 12 | int l, r, id; 13 | } q[MAX_N]; 14 | 15 | int cnt[MAX_VAL]; 16 | long long cur; 17 | 18 | inline void add(int x) { 19 | // cur += x * (cnt[x]++ << 1 | 1LL); 20 | // cout << cur << " "; 21 | cur -= x*cnt[x]*cnt[x]; 22 | cnt[x]++; 23 | cur += x*cnt[x]*cnt[x]; 24 | } 25 | 26 | inline void rem(int x) { 27 | //cur -= x * (--cnt[x] << 1 | 1LL); 28 | cur -= x*cnt[x]*cnt[x]; 29 | cnt[x]--; 30 | cur += x*cnt[x]*cnt[x]; 31 | } 32 | 33 | void mo() { 34 | int bsize = sqrt(N) + 0.5; 35 | auto comp = [bsize](query &q1, query &q2) { 36 | int b1 = q1.l / bsize, b2 = q2.l / bsize; 37 | return b1 != b2 ? b1 < b2 : b1 & 1 ? q1.r < q2.r : q2.r < q1.r; 38 | }; 39 | sort(q, q + Q, comp); 40 | 41 | int l = 1, r = 0; 42 | cur = 0; 43 | for(int i = 0; i < Q; i++) { 44 | 45 | //cout << q[i].l << " " << q[i].r << "\n"; 46 | while(l < q[i].l) rem(A[l++]); 47 | //cout << cur << endl; 48 | while(l > q[i].l) add(A[--l]); 49 | while(r < q[i].r) add(A[++r]); 50 | while(r > q[i].r) rem(A[r--]); 51 | //cout << endl; 52 | ans[q[i].id] = cur; 53 | } 54 | } 55 | 56 | signed main() { 57 | ios_base::sync_with_stdio(false); cin.tie(NULL); 58 | #ifndef ONLINE_JUDGE 59 | // for getting input from input.txt 60 | freopen("input.txt", "r", stdin); 61 | // for writing output to output.txt 62 | // freopen("output.txt", "w", stdout); 63 | #endif 64 | 65 | cin >> N >> Q; 66 | for(int i =1 ; i <= N; i++) 67 | cin >> A[i]; 68 | 69 | for(int i = 0; i < Q; i++) { 70 | q[i].id = i; 71 | cin >> q[i].l >> q[i].r; 72 | } 73 | 74 | mo(); 75 | 76 | for(int i = 0; i < Q; i++) 77 | cout << ans[i] << "\n"; 78 | 79 | return 0; 80 | } -------------------------------------------------------------------------------- /modInverse.cpp: -------------------------------------------------------------------------------- 1 | int power(int a, int b) 2 | { 3 | if(!b) 4 | return 1; 5 | int ans = power(a, b/2); 6 | ans = (ans*ans)%mod; 7 | if(b%2) 8 | ans = (ans*a)%mod; 9 | return ans; 10 | } 11 | int inv(int x){ 12 | return power(x,mod-2); 13 | } -------------------------------------------------------------------------------- /nCr in O(1): -------------------------------------------------------------------------------- 1 | #include 2 | #define int long long 3 | 4 | const int N = 1000001; 5 | 6 | using namespace std; 7 | 8 | // array to store inverse of 1 to N 9 | int factorialNumInverse[N + 1]; 10 | 11 | // array to precompute inverse of 1! to N! 12 | int naturalNumInverse[N + 1]; 13 | 14 | // array to store factorial of first N numbers 15 | int fact[N + 1]; 16 | 17 | // Function to precompute inverse of numbers 18 | void InverseofNumber(int p) 19 | { 20 | naturalNumInverse[0] = naturalNumInverse[1] = 1; 21 | for (int i = 2; i <= N; i++) 22 | naturalNumInverse[i] = naturalNumInverse[p % i] * (p - p / i) % p; 23 | } 24 | // Function to precompute inverse of factorials 25 | void InverseofFactorial(int p) 26 | { 27 | factorialNumInverse[0] = factorialNumInverse[1] = 1; 28 | 29 | // precompute inverse of natural numbers 30 | for (int i = 2; i <= N; i++) 31 | factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p; 32 | } 33 | 34 | // Function to calculate factorial of 1 to N 35 | void factorial(int p) 36 | { 37 | fact[0] = 1; 38 | 39 | // precompute factorials 40 | for (int i = 1; i <= N; i++) { 41 | fact[i] = (fact[i - 1] * i) % p; 42 | } 43 | } 44 | 45 | // Function to return nCr % p in O(1) time 46 | int Binomial(int N, int R, int p) 47 | { 48 | // n C r = n!*inverse(r!)*inverse((n-r)!) 49 | int ans = ((fact[N] * factorialNumInverse[R]) 50 | % p * factorialNumInverse[N - R]) 51 | % p; 52 | return ans; 53 | } 54 | 55 | 56 | int main() 57 | { 58 | 59 | int p = 1000000007; 60 | InverseofNumber(p); 61 | InverseofFactorial(p); 62 | factorial(p); 63 | 64 | // 1st query 65 | int N = 15; 66 | int R = 4; 67 | cout << Binomial(N, R, p) << endl; 68 | 69 | // 2nd query 70 | N = 20; 71 | R = 3; 72 | cout << Binomial(N, R, p) << endl; 73 | 74 | return 0; 75 | } 76 | -------------------------------------------------------------------------------- /nCr.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define int long long 3 | 4 | const int N = 1000001; 5 | 6 | using namespace std; 7 | 8 | // array to store inverse of 1 to N 9 | int factorialNumInverse[N + 1]; 10 | 11 | // array to precompute inverse of 1! to N! 12 | int naturalNumInverse[N + 1]; 13 | 14 | // array to store factorial of first N numbers 15 | int fact[N + 1]; 16 | 17 | // Function to precompute inverse of numbers 18 | void InverseofNumber(int p) 19 | { 20 | naturalNumInverse[0] = naturalNumInverse[1] = 1; 21 | for (int i = 2; i <= N; i++) 22 | naturalNumInverse[i] = naturalNumInverse[p % i] * (p - p / i) % p; 23 | } 24 | // Function to precompute inverse of factorials 25 | void InverseofFactorial(int p) 26 | { 27 | factorialNumInverse[0] = factorialNumInverse[1] = 1; 28 | 29 | // precompute inverse of natural numbers 30 | for (int i = 2; i <= N; i++) 31 | factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p; 32 | } 33 | 34 | // Function to calculate factorial of 1 to N 35 | void factorial(int p) 36 | { 37 | fact[0] = 1; 38 | 39 | // precompute factorials 40 | for (int i = 1; i <= N; i++) { 41 | fact[i] = (fact[i - 1] * i) % p; 42 | } 43 | } 44 | 45 | // Function to return nCr % p in O(1) time 46 | int Binomial(int N, int R, int p) 47 | { 48 | // n C r = n!*inverse(r!)*inverse((n-r)!) 49 | int ans = ((fact[N] * factorialNumInverse[R]) 50 | % p * factorialNumInverse[N - R]) 51 | % p; 52 | return ans; 53 | } 54 | 55 | 56 | int main() 57 | { 58 | 59 | int p = 1000000007; 60 | InverseofNumber(p); 61 | InverseofFactorial(p); 62 | factorial(p); 63 | 64 | // 1st query 65 | int N = 15; 66 | int R = 4; 67 | cout << Binomial(N, R, p) << endl; 68 | 69 | // 2nd query 70 | N = 20; 71 | R = 3; 72 | cout << Binomial(N, R, p) << endl; 73 | 74 | return 0; 75 | } -------------------------------------------------------------------------------- /primefactorsseive.cpp: -------------------------------------------------------------------------------- 1 | void SOF() 2 | { 3 | SPF[1] = 1; 4 | for (int i=2; i 2 | using namespace std; 3 | #define int long long 4 | int hashh[100]; 5 | int pr = 27; 6 | int M = 1e9+7; 7 | 8 | // Palindrome check for prefix 9 | void Prefix_palincheck_byHashing(string s) 10 | { 11 | int n = s.size(); 12 | 13 | for(int i = 1;iindex_jahan_hai; 61 | 62 | for(int i = 0;i<=n-m;i++) 63 | { 64 | int value = (string_hash[i+m]+md-string_hash[i])%md; 65 | int temp = (hash_value * poww[i])%md; 66 | if(value == temp) 67 | index_jahan_hai.push_back(i); 68 | } 69 | 70 | // Prints all the index where it starts 71 | // from 72 | for(auto it:index_jahan_hai) 73 | cout << it << " "; 74 | 75 | } 76 | 77 | signed main() 78 | { 79 | string s, t; 80 | s = "arajaarajjraj"; 81 | t = "raj"; 82 | rabin_karp(s,t); 83 | return 0; 84 | } -------------------------------------------------------------------------------- /segmenttreeobj.cpp: -------------------------------------------------------------------------------- 1 | int n; 2 | int a[N], b[N]; 3 | 4 | // 5 | struct SegTree 6 | { 7 | int N; 8 | vector st; 9 | 10 | void init(int n) 11 | { 12 | N = n; 13 | st.resize(4 * N + 5); 14 | } 15 | 16 | 17 | 18 | void Build(int node, int L, int R) 19 | { 20 | if (L == R) 21 | { 22 | st[node] = b[L]; 23 | return; 24 | } 25 | int M = (L + R) / 2; 26 | Build(node * 2, L, M); 27 | Build(node * 2 + 1, M + 1, R); 28 | st[node] = max(st[node * 2], st[node * 2 + 1]); 29 | } 30 | 31 | void Update(int node, int L, int R, int pos, int val) 32 | { 33 | if (L == R) 34 | { 35 | st[node] += val; 36 | return; 37 | } 38 | int M = (L + R) / 2; 39 | if (pos <= M) 40 | Update(node * 2, L, M, pos, val); 41 | else 42 | Update(node * 2 + 1, M + 1, R, pos, val); 43 | 44 | st[node] = max(st[node * 2], st[node * 2 + 1]); 45 | } 46 | 47 | int Query(int node, int L, int R, int i, int j) 48 | { 49 | if (j < L || i > R) 50 | return 0; 51 | if (i <= L && R <= j) 52 | return st[node]; 53 | int M = (L + R) / 2; 54 | return max(Query(node * 2, L, M, i, j), Query(node * 2 + 1, M + 1, R, i, j)); 55 | 56 | } 57 | 58 | 59 | 60 | int query(int l, int r) { return Query(1, 1, N, l, r); } 61 | 62 | void update(int pos, int val) { Update(1, 1, N, pos, val); } 63 | 64 | void build() { Build(1, 1, N); } 65 | 66 | }; 67 | SegTree seg; 68 | 69 | void solve() 70 | { 71 | seg.init(4 * n); 72 | seg.build(); 73 | } 74 | -------------------------------------------------------------------------------- /sparsetable.cpp: -------------------------------------------------------------------------------- 1 | int n; 2 | int a[N]; 3 | int sparse[N][30], sparse1[N][30]; 4 | 5 | 6 | // Fills lookup array lookup[][] in bottom up manner. 7 | void buildSparseTableMin() 8 | { 9 | // Initialize M for the intervals with length 1 10 | for (int i = 0; i < n; i++) 11 | sparse[i][0] = a[i]; 12 | 13 | // Compute values from smaller to bigger intervals 14 | for (int j = 1; (1 << j) <= n; j++) { 15 | // Compute minimum value for all intervals with 16 | // size 2^j 17 | for (int i = 0; (i + (1 << j) - 1) < n; i++) 18 | sparse[i][j] = min(sparse[i][j - 1], sparse[i + (1 << (j - 1))][j - 1]); 19 | } 20 | } 21 | 22 | // Returns minimum of arr[L..R] 23 | int querymin(int L, int R) 24 | { 25 | // Find highest power of 2 that is smaller 26 | // than or equal to count of elements in given 27 | // range. For [2, 10], j = 3 28 | int j = (int)log2(R - L + 1); 29 | 30 | // Compute minimum of last 2^j elements with first 31 | // 2^j elements in range. 32 | return min(sparse[L][j], sparse[R - (1 << j) + 1][j]); 33 | } 34 | 35 | 36 | 37 | // Fills lookup array lookup[][] in bottom up manner. 38 | void buildSparseTableGcd() 39 | { 40 | // Initialize M for the intervals with length 1 41 | for (int i = 0; i < n; i++) 42 | sparse1[i][0] = a[i]; 43 | 44 | // Compute values from smaller to bigger intervals 45 | for (int j = 1; (1 << j) <= n; j++) { 46 | // Compute minimum value for all intervals with 47 | // size 2^j 48 | for (int i = 0; (i + (1 << j) - 1) < n; i++) 49 | sparse1[i][j] = gcd(sparse1[i][j - 1], sparse1[i + (1 << (j - 1))][j - 1]); 50 | } 51 | } 52 | 53 | // Returns minimum of arr[L..R] 54 | int querygcd(int L, int R) 55 | { 56 | // Find highest power of 2 that is smaller 57 | // than or equal to count of elements in given 58 | // range. For [2, 10], j = 3 59 | int j = (int)log2(R - L + 1); 60 | 61 | // Compute minimum of last 2^j elements with first 62 | // 2^j elements in range. 63 | return gcd(sparse1[L][j], sparse1[R - (1 << j) + 1][j]); 64 | } -------------------------------------------------------------------------------- /spojss1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | /*Structure that is used to 4 | store value*/ 5 | struct node 6 | { 7 | int sum,prefixsum; 8 | int suffixsum,maxsum; 9 | }; 10 | node tree[4*50010]; 11 | int arr[50010]; 12 | /*This function is used to build the 13 | segment tree*/ 14 | void build(int index,int start,int end) 15 | { 16 | if(start == end) 17 | { 18 | tree[index].sum = arr[start]; 19 | tree[index].prefixsum = arr[start]; 20 | tree[index].suffixsum = arr[start]; 21 | tree[index].maxsum = arr[start]; 22 | } 23 | else 24 | { 25 | int mid = (start+end)/2; 26 | build(2*index+1,start,mid); 27 | build(2*index+2,mid+1,end); 28 | 29 | /*Note how we use the array to access the left 30 | and right subtree*/ 31 | tree[index].sum = 32 | tree[2*index+1].sum + tree[2*index+2].sum; 33 | tree[index].prefixsum = max(tree[2*index+1].prefixsum,tree[2*index+1].sum + tree[2*index+2].prefixsum); 34 | tree[index].suffixsum = max(tree[2*index+2].suffixsum,tree[2*index+2].sum + tree[2*index+1].suffixsum); 35 | tree[index].maxsum = max(tree[index].prefixsum, max(tree[index].suffixsum, max(tree[2*index+1].maxsum, 36 | max(tree[2*index+2].maxsum, 37 | tree[2*index+1].suffixsum 38 | +tree[2*index+2].prefixsum 39 | ) 40 | ) 41 | ) 42 | ); 43 | } 44 | } 45 | /*this function is used to return the result 46 | for each query*/ 47 | node query(int index,int start,int end,int l,int r) 48 | { 49 | node result; 50 | result.sum=result.prefixsum=INT_MIN; 51 | result.suffixsum=result.maxsum=INT_MIN; 52 | 53 | if(r mid) 60 | return query(2*index+2, mid+1, end, l, r); 61 | if (r <= mid) 62 | return query(2*index+1, start, mid, l, r); 63 | 64 | node left = query(2*index+1,start,mid,l,r); 65 | node right = query(2*index+2,mid+1,end,l,r); 66 | 67 | result.sum = left.sum + right.sum; 68 | result.prefixsum = 69 | max(left.prefixsum, left.sum + right.prefixsum); 70 | result.suffixsum = 71 | max(right.suffixsum, right.sum + left.suffixsum); 72 | result.maxsum = 73 | max(result.prefixsum, 74 | max(result.suffixsum, 75 | max(left.maxsum, 76 | max(right.maxsum, 77 | left.suffixsum + right.prefixsum)))); 78 | return result; 79 | } 80 | int main() { 81 | int n,m,a,b; 82 | scanf("%d",&n); 83 | 84 | for(int i=0;i 2 | 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node *next; 8 | }*top = NULL; 9 | 10 | void push(int); 11 | void pop(); 12 | void display(); 13 | 14 | void main() 15 | { 16 | int choice, value; 17 | clrscr(); 18 | printf("\n:: Stack using Linked List ::\n"); 19 | while(1){ 20 | printf("\n****** MENU ******\n"); 21 | printf("1. Push\n2. Pop\n3. Display\n4. Exit\n"); 22 | printf("Enter your choice: "); 23 | scanf("%d",&choice); 24 | switch(choice){ 25 | case 1: printf("Enter the value to be insert: "); 26 | scanf("%d", &value); 27 | push(value); 28 | break; 29 | case 2: pop(); break; 30 | case 3: display(); break; 31 | case 4: exit(0); 32 | default: printf("\nWrong selection!!! Please try again!!!\n"); 33 | } 34 | } 35 | } 36 | void push(int value) 37 | { 38 | struct Node *newNode; 39 | newNode = (struct Node*)malloc(sizeof(struct Node)); 40 | newNode->data = value; 41 | if(top == NULL) 42 | newNode->next = NULL; 43 | else 44 | newNode->next = top; 45 | top = newNode; 46 | printf("\nInsertion is Success!!!\n"); 47 | } 48 | void pop() 49 | { 50 | if(top == NULL) 51 | printf("\nStack is Empty!!!\n"); 52 | else{ 53 | struct Node *temp = top; 54 | printf("\nDeleted element: %d", temp->data); 55 | top = temp->next; 56 | free(temp); 57 | } 58 | } 59 | void display() 60 | { 61 | if(top == NULL) 62 | printf("\nStack is Empty!!!\n"); 63 | else{ 64 | struct Node *temp = top; 65 | while(temp->next != NULL){ 66 | printf("%d--->",temp->data); 67 | temp = temp -> next; 68 | } 69 | printf("%d--->NULL",temp->data); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /subarrayswithxor-m.cpp: -------------------------------------------------------------------------------- 1 | // C++ Program to count all subarrays having 2 | // XOR of elements as given value m with 3 | // O(n) time complexity. 4 | #include 5 | using namespace std; 6 | 7 | // Returns count of subarrays of arr with XOR 8 | // value equals to m 9 | long long subarrayXor(int arr[], int n, int m) 10 | { 11 | long long ans = 0; //Initialize answer to be returned 12 | 13 | // Create a prefix xor-sum array such that 14 | // xorArr[i] has value equal to XOR 15 | // of all elements in arr[0 ..... i] 16 | int *xorArr = new int[n]; 17 | 18 | // Create map that stores number of prefix array 19 | // elements corresponding to a XOR value 20 | unordered_map mp; 21 | 22 | // Initialize first element of prefix array 23 | xorArr[0] = arr[0]; 24 | 25 | // Computing the prefix array. 26 | for (int i = 1; i < n; i++) 27 | xorArr[i] = xorArr[i-1] ^ arr[i]; 28 | 29 | // Calculate the answer 30 | for (int i = 0; i < n; i++) 31 | { 32 | // Find XOR of current prefix with m. 33 | int tmp = m ^ xorArr[i]; 34 | cout << tmp<<" "; 35 | // If above XOR exists in map, then there 36 | // is another previous prefix with same 37 | // XOR, i.e., there is a subarray ending 38 | // at i with XOR equal to m. 39 | ans = ans + ((long long)mp[tmp]); 40 | //cout << (long long)mp[tmp]<<" "< topo; //Stores lexicographically smallest toposort 2 | vector g[N]; 3 | bool toposort() //Returns 1 if there exists a toposort, 0 if there is a cycle 4 | { 5 | priority_queue, greater > pq; 6 | for(int i=1;i<=n;i++) 7 | for(auto &it:g[i]) 8 | indeg[it]++; 9 | for(int i=1;i<=n;i++) 10 | { 11 | if(!indeg[i]) 12 | pq.push(i); 13 | } 14 | while(!pq.empty()) 15 | { 16 | int u=pq.top(); 17 | pq.pop(); 18 | topo.push_back(u); 19 | for(auto &v:g[u]) 20 | { 21 | indeg[v]--; 22 | if(!indeg[v]) 23 | pq.push(v); 24 | } 25 | } 26 | if(topo.size() 4 | #include 5 | #include 6 | #include 7 | 8 | #define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0]) 9 | 10 | // Alphabet size (# of symbols) 11 | #define ALPHABET_SIZE (26) 12 | 13 | // Converts key current character into index 14 | // use only 'a' through 'z' and lower case 15 | #define CHAR_TO_INDEX(c) ((int)c - (int)'a') 16 | 17 | // trie node 18 | typedef struct TrieNode 19 | { 20 | struct TrieNode *children[ALPHABET_SIZE]; 21 | 22 | // isLeaf is true if the node represents 23 | // end of a word 24 | bool isLeaf; 25 | }nd; 26 | 27 | // Returns new trie node (initialized to NULLs) 28 | struct TrieNode *getNode(void) 29 | { 30 | struct TrieNode *pNode = NULL; 31 | 32 | pNode = (struct TrieNode *)malloc(sizeof(struct TrieNode)); 33 | 34 | if (pNode) 35 | { 36 | int i; 37 | 38 | pNode->isLeaf = false; 39 | 40 | for (i = 0; i < ALPHABET_SIZE; i++) 41 | pNode->children[i] = NULL; 42 | } 43 | 44 | return pNode; 45 | } 46 | 47 | // If not present, inserts key into trie 48 | // If the key is prefix of trie node, just marks leaf node 49 | void insert(struct TrieNode *root, const char *key) 50 | { 51 | int level; 52 | int length = strlen(key); 53 | int index; 54 | 55 | struct TrieNode *pCrawl = root; 56 | 57 | for (level = 0; level < length; level++) 58 | { 59 | index = CHAR_TO_INDEX(key[level]); 60 | if (!pCrawl->children[index]) 61 | pCrawl->children[index] = getNode(); 62 | 63 | pCrawl = pCrawl->children[index]; 64 | } 65 | 66 | // mark last node as leaf 67 | pCrawl->isLeaf = true; 68 | } 69 | 70 | // Returns true if key presents in trie, else false 71 | bool search(struct TrieNode *root, const char *key) 72 | { 73 | int level; 74 | int length = strlen(key); 75 | int index; 76 | struct TrieNode *pCrawl = root; 77 | 78 | for (level = 0; level < length; level++) 79 | { 80 | index = CHAR_TO_INDEX(key[level]); 81 | 82 | if (!pCrawl->children[index]) 83 | return false; 84 | 85 | pCrawl = pCrawl->children[index]; 86 | } 87 | 88 | return (pCrawl != NULL && pCrawl->isLeaf); 89 | } 90 | void delete(nd *root,char *key) 91 | { 92 | nd* pcrawl=root; 93 | int level=0; 94 | int l=strlen(key); 95 | int index; 96 | for(level=0;levelchildren[index]; 100 | 101 | } 102 | pcrawl->isLeaf=false; 103 | } 104 | 105 | 106 | // Driver 107 | int main() 108 | { 109 | // Input keys (use only 'a' through 'z' and lower case) 110 | char keys[][8] = {"the", "a", "there", "answer", "any", 111 | "by", "bye", "their"}; 112 | 113 | char output[][32] = {"Not present in trie", "Present in trie"}; 114 | 115 | 116 | struct TrieNode *root = getNode(); 117 | 118 | // Construct trie 119 | int i; 120 | for (i = 0; i < ARRAY_SIZE(keys); i++) 121 | insert(root, keys[i]); 122 | 123 | // Search for different keys 124 | printf("%s --- %s\n", "the", output[search(root, "the")] ); 125 | printf("%s --- %s\n", "these", output[search(root, "these")] ); 126 | delete(root,"the"); 127 | printf("%s --- %s\n", "the", output[search(root, "the")] ); 128 | printf("%s --- %s\n", "thaw", output[search(root, "thaw")] ); 129 | 130 | return 0; 131 | } 132 | -------------------------------------------------------------------------------- /z_function.c++: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Z array stores the max length prefix that 5 | // matches with substring starting at index i 6 | vector z_func(string s) 7 | { 8 | int n = s.size(); 9 | vectorz(n,0); 10 | int l = 0, r = 0; 11 | 12 | // Iterate to create the Z function 13 | for(int i = 1;i < n;i++) 14 | { 15 | 16 | // Copy till previous 17 | // is does not exceeds range 18 | if(i<=r) 19 | z[i] = min(r-i+1,z[i-l]); 20 | 21 | // Re-start comparison 22 | while(i + z[i] < n && s[z[i]] == s[i+z[i]]) 23 | { 24 | z[i]++; 25 | } 26 | 27 | if(i+z[i]-1>r) 28 | { 29 | l = i; 30 | r = i+z[i]-1; 31 | } 32 | } 33 | return z; 34 | } 35 | 36 | int main() 37 | { 38 | string s = "ddcdddc"; 39 | vector z = z_func(s); 40 | for(auto it:z) 41 | cout << it << " "; 42 | } --------------------------------------------------------------------------------