├── .gitignore ├── LICENSE ├── MyTemplate.cpp ├── README.md └── Source ├── BackTracking ├── Combinition_Generation.cpp ├── Permutation_generation.cpp └── m-colouring.cpp ├── Big Interger └── factorial.cpp ├── Binary Exponentiation ├── BigMod.cpp ├── BigMod_Wihtout rec.cpp └── matrix_exponent.cpp ├── Combinatorics ├── Catalan_number.cpp └── Inclusion Exclustion.cpp ├── Computetional Geometry ├── Covex Hull (Graham Scan) .cpp └── Jarvis Algorithm.cpp ├── Data Structure ├── BITRangeUpdateRangeQuery.cpp ├── Disjoint Set Undo.cpp ├── Sparse Table RMQ.cpp ├── Trie Pointer.cpp ├── binary indexed tree.cpp ├── disjoint set.cpp ├── iterativeSegmentTree.cpp ├── maximum_subsegment_sum.cpp ├── merge sort tree.cpp ├── segmet tree.cpp ├── squre root decmp.cpp └── trie.cpp ├── Dynamic Programming └── digitDp.cpp ├── Flow and matching ├── Biparite Matching.cpp ├── Flow Edmonds Carp.cpp └── flow dinic.cpp ├── Graph ├── 2-Sat.cpp ├── Articulation Bridge.cpp ├── Articulation point.cpp ├── DFS.cpp ├── Stable Marriage.cpp ├── Warshal.cpp ├── bfs in 2d.cpp ├── bfs.cpp ├── dfs basic .cpp ├── dijkstra.cpp ├── minimum spannig tree (Kruskal).cpp └── prims algo.cpp ├── Miscellaneous └── Stern Brocot tree.cpp ├── Number Theory ├── Basics.md ├── Chinese remainder theorem.cpp ├── SIeve O_n.cpp ├── Sum of divisor.cpp ├── bitwise_sieve.cpp ├── eulers totient sieve.cpp ├── gaussian_elemination.cpp ├── isPrime.cpp ├── miller rabin preimality test.cpp ├── moduler inverse.cpp ├── number of divisor in qube root.cpp ├── number of divisor.cpp ├── number of primes.txt ├── prime factorization log(n).cpp ├── primeFactorization.cpp ├── segmented_sieve.cpp ├── sieve.cpp └── totient.cpp ├── STL └── STL.md ├── Sorting ├── Bubble Sort.cpp ├── Insertion Sort.cpp ├── Merge Sort.cpp ├── Quick Sort.cpp └── Selection Sort.cpp ├── String ├── KMP.cpp ├── Rabin Carp String Matching.cpp └── Suffix Array.cpp └── Trees ├── DSU on tree.cpp └── HLD Anudeep blog Style.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Nadim Mahmud 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /MyTemplate.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define P(X) cout<<"db "< 10 | 11 | #define bchk(n,i) (bool)(n&(1< 102 | using namespace std; 103 | //0 Indexed 104 | #define MX 10000 105 | int spt[MX][22]; 106 | int n,ar[MX]={ 7, 2, 3, 0, 5, 10, 3, 12, 18 }; 107 | void buildST() 108 | { 109 | for (int i = 0; i < n; i++) spt[i][0] = ar[i]; 110 | 111 | for (int j = 1; (1 << j) <= n; j++) { 112 | for (int i = 0; (i + (1 << j) - 1) < n; i++) { 113 | spt[i][j] = min(spt[i + (1 << (j - 1))][j - 1] , spt[i][j - 1]); 114 | } 115 | } 116 | } 117 | 118 | int query(int l, int r) 119 | { 120 | if(l>r) return INT_MAX; 121 | int j = (int)log2(r - l + 1); 122 | ///j = 31 - __builtin_clz(r - l+1); 123 | return min (spt[l][j], spt[r - (1 << j) + 1][j]); 124 | } 125 | 126 | // Driver program 127 | int main() 128 | { 129 | 130 | n = 9; 131 | buildST(); 132 | cout << query(4, 7) << endl; 133 | cout << query(7, 8) << endl; 134 | return 0; 135 | } 136 | 137 | 138 | /// *** BIT O(Log(n)) space O(n) 139 | 140 | /** 1 based index 141 | * which functions has inverse function that can be solve bye BIT 142 | * it works like consucative sums but in log(n) 143 | */ 144 | 145 | int n=SIZE; //of space; 146 | void update(int idx,int val)//adding value val to idx index 147 | { 148 | while(idx<=n){ 149 | bitree[idx]+=val; 150 | idx+=idx&(-idx); // Last set of digit 151 | } 152 | } 153 | int query(int idx){// returns sum of [1,idx] index 154 | int sum=0; 155 | while(idx>0){ 156 | sum+=bitree[idx]; 157 | idx-=idx&(-idx); 158 | } 159 | return sum; 160 | } 161 | 162 | /** 163 | Description : BIT range update range query 164 | Time Complexity : all log(n) 165 | */ 166 | 167 | /// Remember to use 1 based indexing 168 | //const int MX = 100005; 169 | 170 | ll query(ll *bit, int indx) 171 | { 172 | ll sum = 0; 173 | while (indx) { 174 | sum += bit[indx]; 175 | indx -= (indx & -indx); 176 | } 177 | return sum; 178 | } 179 | 180 | void update(ll *bit, int indx, ll x) 181 | { 182 | while (indx < MX) { 183 | bit[indx] += x; 184 | indx += (indx & -indx); 185 | } 186 | } 187 | ll B1[MX],B2[MX];//set 0 188 | 189 | void Rupdate(int l, int r, ll v){ 190 | update(B1, l, v); 191 | update(B1, r+1, -v); 192 | update(B2, l, -((l-1)*v)); 193 | update(B2, r+1, r*v); 194 | } 195 | ll Rquery1(int p){ 196 | ll b1,b2; 197 | b1 = query(B1, p); 198 | b2 = query(B2, p); 199 | return b1 * p + b2; 200 | } 201 | ll Requery(int l,int r){ 202 | return Rquery1(r)-Rquery1(l-1); 203 | } 204 | 205 | /// *** Segment Tree [log(total array size)*Query] 206 | 207 | /** [ulow,uhigh] Query Range 208 | * [low,high] total range of root 209 | * [qlow,qhigh] Query Range 210 | * Currrent position = pos 211 | * 0 based Index And Root is also 0 212 | */ 213 | 214 | int ara[MX],seg[4*MX],lazy[4*MX]; 215 | 216 | void creat(int low,int high,int pos) 217 | { 218 | if(low==high){ 219 | seg[pos] = ara[low]; // reached leaf and update 220 | return ; 221 | } 222 | int mid = (high+low)/2; 223 | creat(low,mid,pos*2+1); 224 | creat(mid+1,high,pos*2+2); 225 | seg[pos] += seg[pos*2+1] + seg[pos*2+2]; 226 | } 227 | 228 | void update(int low,int high,int ulow,int uhigh,int val,int pos) 229 | { 230 | if(low>high) return ; 231 | if(lazy[pos]!=0){ /// is not propagated yet 232 | seg[pos] += (high-low+1)*lazy[pos]; 233 | if(low!=high){ ///if not leaf node 234 | lazy[pos*2+1] += lazy[pos]; 235 | lazy[pos*2+2] += lazy[pos]; 236 | } 237 | lazy[pos] = 0; 238 | } 239 | 240 | if(ulow>high||uhigh=high){ /// Total Overlap 242 | seg[pos] += (high-low+1)*val; 243 | if(low!=high){ 244 | lazy[pos*2+1] += val; 245 | lazy[pos*2+2] += val; 246 | } 247 | return; 248 | } 249 | /// Partial overlap 250 | int mid = (high+low)/2; 251 | 252 | update(low,mid,ulow,uhigh,val,pos*2+1); 253 | update(mid+1,high,ulow,uhigh,val,pos*2+2); 254 | seg[pos] = seg[pos*2+1] + seg[pos*2+2]; /// Updating the intermediate node 255 | } 256 | 257 | int query(int low,int high,int qlow,int qhigh,int pos) 258 | { 259 | if(low>high) return 0; 260 | if(lazy[pos]!=0){ 261 | seg[pos] += (high-low+1)*lazy[pos]; 262 | if(low!=high){ 263 | lazy[pos*2+1] += lazy[pos]; 264 | lazy[pos*2+2] += lazy[pos]; 265 | } 266 | lazy[pos] = 0; 267 | } 268 | 269 | if(qlow>high||qhigh=high) 272 | return seg[pos]; 273 | 274 | int mid = (high+low)/2; 275 | 276 | return query(low,mid,qlow,qhigh,pos*2+1) + query(mid+1,high,qlow,qhigh,pos*2+2); 277 | } 278 | 279 | 280 | /** 281 | Description : Efficient and easy segment trees , Range [l, r) 282 | Time Complexity : O(logn) 283 | from: https://codeforces.com/blog/entry/18051 284 | */ 285 | 286 | const int N = 1e5; // limit for array size 287 | int n; // array size 288 | int tr[2 * N]; 289 | void build() { // build the tree 290 | for (int i = n - 1; i > 0; --i) tr[i] = tr[i<<1] + tr[i<<1|1]; 291 | } 292 | 293 | void modify(int p, int value) { // set value at position p 294 | for (tr[p += n] = value; p > 1; p >>= 1) tr[p>>1] = tr[p] + tr[p^1]; 295 | } 296 | 297 | int query(int l, int r) { // sum on interval [l, r) 298 | int res = 0; 299 | for (l += n, r += n; l < r; l >>= 1, r >>= 1) { 300 | if (l&1) res += tr[l++]; 301 | if (r&1) res += tr[--r]; 302 | } 303 | return res; 304 | } 305 | 306 | int main() { 307 | //scanf("%d", &n); 308 | int ar[]={1,3,4,5,4,5,6,4,6,4,5,6,6,5}; 309 | n=5; 310 | for (int i = 0; i < n; ++i) { 311 | tr[n+i]=ar[i]; 312 | } 313 | build(); 314 | printf("%d\n", query(0, 4));//that means [0,3] 315 | printf("%d\n", query(2, 3)); 316 | modify(0, 5); 317 | printf("%d\n", query(0, 4)); 318 | return 0; 319 | } 320 | 321 | 322 | /** 323 | * Name : Maximum subsegment sum 324 | * Description: Segment Tree with custom merge function. . 325 | * Usage: construct O(N), query O(lg(N)), update O(lg(N)) 326 | * Source: https://github.com/dragonslayerx 327 | */ 328 | 329 | #include 330 | #include 331 | using namespace std; 332 | 333 | #define MAX 50100 334 | #define INF -1000000000 335 | 336 | struct node { 337 | int sum; 338 | int maxs, prefix, suffix; 339 | node(){ 340 | sum = prefix = suffix = 0; 341 | maxs = INF; 342 | } 343 | 344 | node(int sum, int maxs, int prefix, int suffix) { 345 | setNode(sum, maxs, prefix, suffix); 346 | } 347 | 348 | void setNode(int sum, int maxs, int prefix, int suffix){ 349 | this->sum =sum; 350 | this->maxs=maxs; 351 | this->prefix=prefix; 352 | this->suffix=suffix; 353 | } 354 | }; 355 | 356 | int a[MAX]; 357 | node st[4*MAX]; 358 | 359 | node merge(node left, node right){ 360 | node t; 361 | t.prefix = max(left.prefix, left.sum+right.prefix); 362 | t.suffix = max(right.suffix, right.sum+left.suffix); 363 | t.sum = left.sum+right.sum; 364 | t.maxs = left.maxs; 365 | t.maxs = max(t.maxs, right.maxs); 366 | t.maxs = max(t.maxs, left.suffix+right.prefix); 367 | return t; 368 | } 369 | 370 | node construct(int n, int ll, int rl){ 371 | if (ll == rl) { 372 | st[n].setNode(a[ll], a[ll], a[ll], a[ll]); 373 | } else { 374 | node left = construct(2*n+1, ll, (ll+rl)/2); 375 | node right = construct(2*n+2, (ll+rl)/2+1, rl); 376 | st[n] = merge(left, right); 377 | } 378 | return st[n]; 379 | } 380 | 381 | node query(int n, int ll, int rl, int x, int y){ 382 | int mid = (ll+rl)/2; 383 | if (x==ll && y==rl) return st[n]; 384 | else if (y <= mid) return query(2*n+1, ll, mid, x, y); 385 | else if (x > mid) return query(2*n+2, mid+1, rl, x, y); 386 | else { 387 | node left = query(2*n+1, ll, (ll+rl)/2, x, mid); 388 | node right = query(2*n+2, (ll+rl)/2+1, rl, mid+1, y); 389 | return merge(left, right); 390 | } 391 | } 392 | 393 | node update(int n, int ll, int rl, int p, int val){ 394 | if (p < ll || p > rl) return st[n]; 395 | if (p == ll && p == rl) { 396 | st[n].setNode(val, val, val, val); 397 | return st[n]; 398 | } else { 399 | int mid = (ll+rl)/2; 400 | node left = update(2*n+1, ll, (ll+rl)/2, p, val); 401 | node right = update(2*n+2, (ll+rl)/2+1, rl, p, val); 402 | st[n] = merge(left, right); 403 | } 404 | return st[n]; 405 | } 406 | 407 | int main() 408 | { 409 | int n; 410 | scanf("%d", &n); 411 | for (int i = 0; i < n; i++) scanf("%d", a+i); 412 | construct(0, 0, n-1); 413 | int q; 414 | scanf("%d", &q); 415 | while (q--) { 416 | int x, y; 417 | scanf("%d%d", &x, &y); 418 | x--, y--; 419 | printf("%d\n", query(0, 0, n-1, x, y).maxs); 420 | } 421 | } 422 | © 2019 GitHub, Inc. 423 | 424 | /**' 425 | Name : Disjoint set union find 426 | Description : Always check parent for size or anything 427 | Complexity : O(n) ~ O(log n) ~ O(1) 428 | */ 429 | 430 | #define MX 10000 431 | int rp[MX],sz[MX]; 432 | 433 | int parent(int n){ 434 | if(rp[n]==n)return n; 435 | return rp[n]=parent(rp[n]); 436 | } 437 | 438 | void setUp(int a,int b){ 439 | a = parent(a); 440 | b = parent(b); 441 | if(a==b) return; 442 | if(sz[a]next[id] == NULL) 537 | curr->next[id] = new node(); 538 | curr = curr->next[id]; 539 | } 540 | curr->endmark = true; 541 | } 542 | bool search(char* str, int len) 543 | { 544 | node* curr = root; 545 | for (int i = 0; i < len; i++) { 546 | int id = str[i] - 'a'; 547 | if (curr->next[id] == NULL) 548 | return false; 549 | curr = curr->next[id]; 550 | } 551 | return curr->endmark; 552 | } 553 | void del(node* cur) 554 | { 555 | for (int i = 0; i < 26; i++) 556 | if (cur->next[i]) 557 | del(cur->next[i]); 558 | 559 | delete (cur); 560 | } 561 | int main() 562 | { 563 | puts("ENTER NUMBER OF WORDS"); 564 | root = new node(); 565 | int num_word; 566 | cin >> num_word; 567 | for (int i = 1; i <= num_word; i++) { 568 | char str[50]; 569 | scanf("%s", str); 570 | insert(str, strlen(str)); 571 | } 572 | puts("ENTER NUMBER OF QUERY";); 573 | int query; 574 | cin >> query; 575 | for (int i = 1; i <= query; i++) { 576 | char str[50]; 577 | scanf("%s", str); 578 | if (search(str, strlen(str))) 579 | puts("FOUND"); 580 | else 581 | puts("NOT FOUND"); 582 | } 583 | del(root); 584 | return 0; 585 | } 586 | 587 | 588 | 589 | /// *** Trie[(number of words)*(maximum lenght)] 590 | 591 | 592 | /** 593 | Name : Trie with array 594 | This trie is for All Uppercase & Lowercase letters 595 | */ 596 | 597 | int mp(char ch){ 598 | if(ch<95) return (int) (ch - 'A'); 599 | return (int) (ch - 'a' + 26); 600 | } 601 | 602 | struct node{ 603 | bool end; 604 | int next[55]; 605 | int cnt; /// here cnt is counting how many element ends at this point 606 | void set(){ 607 | cnt = 0; 608 | end = false; 609 | for(int i=0;i<=53;i++){ 610 | next[i] = 0; 611 | } 612 | } 613 | }ara[MX]; 614 | 615 | int ptr; 616 | 617 | void insert(char *st){ 618 | int i,in,x=0,y; 619 | for(i=0;st[i];i++){ 620 | if(st[i]==' ') continue; 621 | in = mp(st[i]); 622 | /// If the chain is not exists 623 | /// allocating memory by ptr++ that means new array element 624 | if(!ara[x].next[in]){ 625 | ///putting next arrays position at recent array's linked part 626 | ara[x].next[in] = ptr++; 627 | ara[ptr-1].set(); 628 | } 629 | x = ara[x].next[in]; 630 | } 631 | ///marking last element as last 632 | ara[x].end=1; 633 | ara[x].cnt++; 634 | } 635 | 636 | 637 | int search(char *st){ 638 | int i,in,x=0,cn=0; 639 | for(i=0;st[i];i++){ 640 | if(st[i]==' ')continue; 641 | cn++; 642 | in = mp(st[i]); 643 | ///if query element not exists then returning false 644 | if(!ara[x].next[in]) return 0; 645 | x = ara[x].next[in]; 646 | } 647 | if(!cn) return 1; 648 | /// returning how many elements like "st" 649 | return ara[x].cnt; 650 | } 651 | 652 | 653 | /// *** Merge Sort Tree [nlog(n) + query*log(n)*log(n)] 654 | 655 | 656 | int ara[MX]; 657 | vectorseg[MX*4]; 658 | /// 1 based index 659 | 660 | int bns(int n,int val){ 661 | /// lower bound 1 2 2 2 3 4 662 | /// then returns 2 663 | int mid,i,j,low=0,high = seg[n].size()-1; 664 | while((high-low)>4){ 665 | mid = (low+high)/2; 666 | if(seg[n][mid]<=val) low = mid; 667 | else high = mid - 1; 668 | } 669 | for(low;low<=high&&lowval) break; 671 | } 672 | return seg[n].size()-low; /// numbers greater than value 673 | } 674 | 675 | void mergee(int x,int y,int z){ /// merging 2 vector x and y to Z in sorted order 676 | int i,j,k,md,sz; 677 | sz = seg[x].size() + seg[y].size(); 678 | for(i=0,j=0,k=0;k=seg[x].size()) seg[z].push_back(seg[y][j++]); 680 | else if(j>=seg[y].size()) seg[z].push_back(seg[x][i++]); 681 | else if(seg[x][i]qhigh) return 0; 705 | if(qlow>high||qhigh=high){ 707 | return bns(pos,val); 708 | } 709 | int mid = (low + high)/2; 710 | return query(low,mid,qlow,qhigh,pos*2,val) + query(mid+1,high,qlow,qhigh,pos*2+1,val); 711 | } 712 | 713 | /// *** For Rnage orders statistics (find k'th number in sorted segment) 714 | 715 | vectorinput; 716 | vectorseg[MX*4]; 717 | 718 | void creat(int low,int high,int pos){ /// creating merge sort tree 719 | if(low==high){ 720 | seg[pos].push_back(input[low-1].second); /// in is 0 based 721 | return ; 722 | } 723 | int mid = (low+high)/2; 724 | creat(low,mid,pos*2); 725 | creat(mid+1,high,pos*2+1); 726 | mergee(pos*2,pos*2+1,pos); 727 | } 728 | 729 | /** calculating total number in left range lower than the given index 730 | * if numbers are greater than equals to the searging value than look into left 731 | * searhing on right sub array and substracting left sub arrys given up values 732 | */ 733 | 734 | int query(int low,int high,int qlow,int qhigh,int pos,int val) 735 | { 736 | if(low==high) return seg[pos][0]; 737 | int mid = (low+high)>>1,left=pos<<1; 738 | 739 | int total = upper_bound(seg[left].begin(),seg[left].end(),qhigh) - 740 | lower_bound(seg[left].begin(),seg[left].end(),qlow); 741 | 742 | if(total>=val){ 743 | return query(low,mid,qlow,qhigh,pos*2,val); 744 | } 745 | else{ 746 | return query(mid+1,high,qlow,qhigh,pos*2+1,val-total); 747 | } 748 | } 749 | 750 | sort(input.begin(),input.end()); 751 | 752 | 753 | 754 | /** 755 | GRAPH! GRAPH! GRAPH! GRAPH! GRAPH! GRAPH! 756 | GRAPH! GRAPH! GRAPH! GRAPH! GRAPH! GRAPH! 757 | GRAPH! GRAPH! GRAPH! GRAPH! GRAPH! GRAPH! 758 | GRAPH! GRAPH! GRAPH! GRAPH! GRAPH! GRAPH! 759 | */ 760 | 761 | /// *** BFS [ total(node + edge) ] 762 | /// level by level travarse 763 | 764 | vector ed[MX]; 765 | int lev[MX],ms,par[MX]; 766 | bool vs[MX]; 767 | int bfs(int s){ 768 | int i,j,d,f,v; 769 | queue q; 770 | q.push(s); 771 | lev[s]=0; 772 | vs[s]=1; 773 | while(!q.empty()){ 774 | f=q.front(); 775 | q.pop(); 776 | for(i=0;i q; 800 | pii pr; 801 | vs[fx][fy]=1; 802 | lev[fx][fy]=0; 803 | q.push(pii(fx,fy)); 804 | while(!q.empty()){ 805 | pr=q.front(); 806 | fx=pr.first; 807 | fy=pr.second; 808 | q.pop(); 809 | for(i=0;i<4;i++){ 810 | x=fx+dx[i]; 811 | y=fy+dy[i]; 812 | if(x<0||x>=n||y<0||y>=m)continue; /// for zero based index 813 | if(!vs[x][y]&&st[x][y]!='#'){ /// # is blocked 814 | q.push(pii(x,y)); 815 | vs[x][y]=1; 816 | lev[x][y]=lev[fx][fy]+1; 817 | if(st[x][y]=='d'){ /// d is destinition 818 | md=max(md,lev[x][y]); 819 | } 820 | 821 | } 822 | } 823 | 824 | } 825 | return md;/// max distance of d 826 | 827 | } 828 | 829 | /** 830 | Description : dfs with coloring and visiting time 831 | Complexity : O(V+E) 832 | */ 833 | 834 | vector> adj; // graph represented as an adjacency list 835 | int n; // number of vertices 836 | 837 | vector color; 838 | 839 | vector time_in, time_out; 840 | int dfs_timer = 0; 841 | 842 | void dfs(int v) { 843 | time_in[v] = dfs_timer++; 844 | color[v] = 1; 845 | for (int u : adj[v]) 846 | if (color[u] == 0) 847 | dfs(u); 848 | color[v] = 2; 849 | time_out[v] = dfs_timer++; 850 | } 851 | 852 | 853 | /// *** Dijkstra O(edge * log (node)) 854 | 855 | struct node{ 856 | int id,cost; 857 | node(){} 858 | node(int nid,int ncost) 859 | { 860 | id=nid; 861 | cost=ncost; 862 | } 863 | bool operator < (const node&x)const{ 864 | return cost>x.cost; 865 | } 866 | }; 867 | 868 | vector ed[MX],ec[MX]; 869 | int ds[MX]; 870 | void dxt(int s){ 871 | priority_queue q; 872 | q.push(node(s,0)); 873 | ds[s]=0; 874 | node fn; 875 | int i,u,v; 876 | while(!q.empty()){ 877 | fn=q.top(); 878 | q.pop(); 879 | u=fn.id; 880 | if(fn.cost!=ds[u])continue; 881 | for(i=0;ids[u]+ec[u][i]){ 884 | ds[v]=ds[u]+ec[u][i]; 885 | q.push(node(v,ds[v])); 886 | } 887 | } 888 | } 889 | } 890 | 891 | /** 892 | Name : Warshal Algorithm 893 | 894 | he key idea to notice here is that, we go through all 895 | the nodes and for each node we try to make every path 896 | better by going through that. Hence, Floyd Warshall can add vertex online. 897 | n^2 loop can add this. 898 | 899 | Time Complexity : O(n^3) 900 | 901 | */ 902 | 903 | 904 | int mtx[102][102],n;//intialize with inf; 905 | int next[102][102];//for finding path only 906 | void wrsl() 907 | { 908 | int i,j,k; 909 | for(i=1;i<=n;i++){//for finding path only 910 | for(j=1;j<=n;j++){ 911 | next[i][j]=j; 912 | } 913 | } 914 | 915 | for(k=1;k<=n;k++){ 916 | for(i=1;i<=n;i++){ 917 | for(j=1;j<=n;j++){ 918 | if(mtx[i][j]>mtx[i][k]+mtx[k][j]){ 919 | mtx[i][j]>mtx[i][k]+mtx[k][j]; 920 | next[i][j]=next[i][k];//for finding path only 921 | } 922 | } 923 | } 924 | } 925 | } 926 | //finding path using warshal, i to j 927 | vector path; 928 | void findpath(int i,int j) 929 | { 930 | path.clear(); 931 | path.push_back(i); 932 | while(i!=j){ 933 | i=next[i][j]; 934 | path.push_back(i); 935 | } 936 | } 937 | 938 | 939 | 940 | /// **** Articulation points **** 941 | /// O(E+V) 942 | /// intiate root with starting position of tree 943 | /// by checking marked points we will get articulation points 944 | 945 | 946 | #define MX 10005 947 | vectored[MX]; 948 | int vs[MX],dt[MX],points[MX],low[MX],pr[MX],discovery_time,root; 949 | 950 | void articulation_point(int n){ 951 | int i,v,cn=0; 952 | vs[n] = 1; 953 | dt[n] = low[n] = ++discovery_time; 954 | for(i=0;i1&&n==root) points[n]=1; 974 | } 975 | 976 | void free(){ 977 | for(int i=0;ied[MX], artqb[MX]; 992 | int vs[MX],dt[MX],low[MX],pr[MX],discovery_time,root; 993 | 994 | void articulation_bridge(int n){ 995 | int i,v; 996 | vs[n] = 1; 997 | dt[n] = low[n] = ++discovery_time; 998 | for(i=0;ix.w; 1035 | } 1036 | }ab; 1037 | 1038 | int ara[105],n; 1039 | vectorvc; 1040 | /// vc.push_back(ab) make edge and push 1041 | 1042 | int find(int n){ 1043 | if(ara[n] == n) return n; 1044 | return ara[n] = find(ara[n]); 1045 | } 1046 | 1047 | int mst() 1048 | { 1049 | int sum=0,i,u,v,cn=0,mn=INT_MAX; 1050 | for(i=0;i<=102;i++) ara[i] = i; 1051 | sort(vc.begin(),vc.end()); 1052 | for(i=0;i 1071 | using namespace std; 1072 | #define LL long long 1073 | #define EPS 0.00000001 1074 | #define PI 2*acos(0.0) 1075 | #define MOD 1000000007 1076 | #define ck(XX) cout<=0 && X=0 && Y B.cost;} 1095 | 1096 | 1097 | int node, edge; //Total number of node and edge 1098 | int sow; //Sum Of Weight of MST 1099 | bool taken[100]; 1100 | vector adj[100]; //For storing given graph data 1101 | vector tree[100]; //For creating new minimum spanning tree 1102 | 1103 | 1104 | void PMST(int source) 1105 | { 1106 | sow = 0; 1107 | MS(taken,0); 1108 | 1109 | priority_queue Q; 1110 | taken[source] = 1; 1111 | for(int i=0; i 1191 | #include 1192 | using namespace std; 1193 | 1194 | #define root 0 1195 | #define N 10100 1196 | #define LN 14 1197 | 1198 | vector adj[N], costs[N], indexx[N]; 1199 | int baseArray[N], ptr; 1200 | int chainNo, chainInd[N], chainHead[N], posInBase[N]; 1201 | int depth[N], pa[LN][N], otherEnd[N], subsize[N]; 1202 | int st[N*6], qt[N*6]; 1203 | 1204 | /* 1205 | * make_tree: 1206 | * Used to construct the segment tree. It uses the baseArray for construction 1207 | */ 1208 | void make_tree(int cur, int s, int e) { 1209 | if(s == e-1) { 1210 | st[cur] = baseArray[s]; 1211 | return; 1212 | } 1213 | int c1 = (cur<<1), c2 = c1 | 1, m = (s+e)>>1; 1214 | make_tree(c1, s, m); 1215 | make_tree(c2, m, e); 1216 | st[cur] = st[c1] > st[c2] ? st[c1] : st[c2]; 1217 | } 1218 | 1219 | /* 1220 | * update_tree: 1221 | * Point update. Update a single element of the segment tree. 1222 | */ 1223 | void update_tree(int cur, int s, int e, int x, int val) { 1224 | if(s > x || e <= x) return; 1225 | if(s == x && s == e-1) { 1226 | st[cur] = val; 1227 | return; 1228 | } 1229 | int c1 = (cur<<1), c2 = c1 | 1, m = (s+e)>>1; 1230 | update_tree(c1, s, m, x, val); 1231 | update_tree(c2, m, e, x, val); 1232 | st[cur] = st[c1] > st[c2] ? st[c1] : st[c2]; 1233 | } 1234 | 1235 | /* 1236 | * query_tree: 1237 | * Given S and E, it will return the maximum value in the range [S,E) 1238 | */ 1239 | void query_tree(int cur, int s, int e, int S, int E) { 1240 | if(s >= E || e <= S) { 1241 | qt[cur] = -1; 1242 | return; 1243 | } 1244 | if(s >= S && e <= E) { 1245 | qt[cur] = st[cur]; 1246 | return; 1247 | } 1248 | int c1 = (cur<<1), c2 = c1 | 1, m = (s+e)>>1; 1249 | query_tree(c1, s, m, S, E); 1250 | query_tree(c2, m, e, S, E); 1251 | qt[cur] = qt[c1] > qt[c2] ? qt[c1] : qt[c2]; 1252 | } 1253 | 1254 | /* 1255 | * query_up: 1256 | * It takes two nodes u and v, condition is that v is an ancestor of u 1257 | * We query the chain in which u is present till chain head, then move to next chain up 1258 | * We do that way till u and v are in the same chain, we query for that part of chain and break 1259 | */ 1260 | 1261 | int query_up(int u, int v) { 1262 | if(u == v) return 0; // Trivial 1263 | int uchain, vchain = chainInd[v], ans = -1; 1264 | // uchain and vchain are chain numbers of u and v 1265 | while(1) { 1266 | uchain = chainInd[u]; 1267 | if(uchain == vchain) { 1268 | // Both u and v are in the same chain, so we need to query from u to v, update answer and break. 1269 | // We break because we came from u up till v, we are done 1270 | if(u==v) break; 1271 | query_tree(1, 0, ptr, posInBase[v]+1, posInBase[u]+1); 1272 | // Above is call to segment tree query function 1273 | if(qt[1] > ans) ans = qt[1]; // Update answer 1274 | break; 1275 | } 1276 | query_tree(1, 0, ptr, posInBase[chainHead[uchain]], posInBase[u]+1); 1277 | // Above is call to segment tree query function. We do from chainHead of u till u. That is the whole chain from 1278 | // start till head. We then update the answer 1279 | if(qt[1] > ans) ans = qt[1]; 1280 | u = chainHead[uchain]; // move u to u's chainHead 1281 | u = pa[0][u]; //Then move to its parent, that means we changed chains 1282 | } 1283 | return ans; 1284 | } 1285 | 1286 | /* 1287 | * LCA: 1288 | * Takes two nodes u, v and returns Lowest Common Ancestor of u, v 1289 | */ 1290 | int LCA(int u, int v) { 1291 | if(depth[u] < depth[v]) swap(u,v); 1292 | int diff = depth[u] - depth[v]; 1293 | for(int i=0; i>i)&1 ) u = pa[i][u]; 1294 | if(u == v) return u; 1295 | for(int i=LN-1; i>=0; i--) if(pa[i][u] != pa[i][v]) { 1296 | u = pa[i][u]; 1297 | v = pa[i][v]; 1298 | } 1299 | return pa[0][u]; 1300 | } 1301 | 1302 | void query(int u, int v) { 1303 | /* 1304 | * 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 1305 | */ 1306 | int lca = LCA(u, v); 1307 | int ans = query_up(u, lca); // One part of path 1308 | int temp = query_up(v, lca); // another part of path 1309 | if(temp > ans) ans = temp; // take the maximum of both paths 1310 | printf("%d\n", ans); 1311 | } 1312 | 1313 | /* 1314 | * change: 1315 | * We just need to find its position in segment tree and update it 1316 | */ 1317 | void change(int i, int val) { 1318 | int u = otherEnd[i]; 1319 | update_tree(1, 0, ptr, posInBase[u], val); 1320 | } 1321 | 1322 | /* 1323 | * Actual HL-Decomposition part 1324 | * Initially all entries of chainHead[] are set to -1. 1325 | * So when ever a new chain is started, chain head is correctly assigned. 1326 | * As we add a new node to chain, we will note its position in the baseArray. 1327 | * In the first for loop we find the child node which has maximum sub-tree size. 1328 | * The following if condition is failed for leaf nodes. 1329 | * When the if condition passes, we expand the chain to special child. 1330 | * In the second for loop we recursively call the function on all normal nodes. 1331 | * chainNo++ ensures that we are creating a new chain for each normal child. 1332 | */ 1333 | void HLD(int curNode, int cost, int prev) { 1334 | if(chainHead[chainNo] == -1) { 1335 | chainHead[chainNo] = curNode; // Assign chain head 1336 | } 1337 | chainInd[curNode] = chainNo; 1338 | posInBase[curNode] = ptr; // Position of this node in baseArray which we will use in Segtree 1339 | baseArray[ptr++] = cost; 1340 | 1341 | int sc = -1, ncost; 1342 | // Loop to find special child 1343 | for(int i=0; i 1461 | #define ll long long 1462 | #define P(X) cout<<"db "< 1468 | #define chk(n,i) (bool)(n&(1<g[MX]; 1486 | 1487 | int sz[MX]; 1488 | void getsz(int v, int p){ 1489 | sz[v] = 1; // every vertex has itself in its subtree 1490 | for(auto u : g[v]) 1491 | if(u != p){ 1492 | getsz(u, v); 1493 | sz[v] += sz[u]; // add size of child u to its parent(v) 1494 | } 1495 | } 1496 | 1497 | ll cnt[MX],col[MX],ans[MX],res[MX],mxn; 1498 | bool big[MX]; 1499 | 1500 | void add(int v, int p, int x){ 1501 | //ans[cnt[col[v]]] -= col[v]; 1502 | cnt[col[v]] += x; 1503 | //ans[cnt[col[v]]] += col[v]; 1504 | //mxn = max(cnt[col[v]],mxn); 1505 | for(auto u: g[v]) 1506 | if(u != p && !big[u]) 1507 | add(u, v, x); 1508 | } 1509 | 1510 | 1511 | void dfs(int v, int p, bool keep){ 1512 | int mx = -1, bigChild = -1; 1513 | for(auto u : g[v]) 1514 | if(u != p && sz[u] > mx) 1515 | mx = sz[u], bigChild = u; 1516 | //run a dfs on small childs and clear them from cnt 1517 | for(auto u : g[v]) 1518 | if(u != p && u != bigChild) 1519 | dfs(u, v, 0); // 1520 | // actual processing of vertex v starts from here 1521 | //mxn = 0; 1522 | if(bigChild != -1) 1523 | dfs(bigChild, v, 1), big[bigChild] = 1; // bigChild marked as big and not cleared from cnt 1524 | // calculating ans 1525 | add(v, p, 1); 1526 | //res[v] = ans[mxn]; 1527 | /** here access the result for each node. if needed then access on add() function 1528 | now cnt[c] is the number of vertices in subtree of vertex v that has color c. 1529 | You can answer the queries easily. 1530 | */ 1531 | if(bigChild != -1) 1532 | big[bigChild] = 0; 1533 | if(keep == 0) 1534 | add(v, p, -1); 1535 | } 1536 | 1537 | 1538 | 1539 | int main() 1540 | { 1541 | ll i,j,a,b,ts,cn=0,cas=0,n,m,x,y,sum=0,mn=INT_MAX,u,v; 1542 | //freopen("test.txt","r",stdin); 1543 | cin>>n; 1544 | for(int i = 1; i <= n; i++) { 1545 | cin >> col[i]; 1546 | } 1547 | for(i=1;i>u>>v; 1549 | g[u].push_back(v); 1550 | g[v].push_back(u); 1551 | } 1552 | getsz(1,0); 1553 | dfs(1,0,1); 1554 | for(int i = 1; i <= n; i++) { 1555 | cout << res[i] << ' '; 1556 | } 1557 | return 0; 1558 | } 1559 | 1560 | /** 1561 | Name : 2SAT problem 1562 | */ 1563 | 1564 | #include 1565 | using namespace std; 1566 | typedef long long ll; 1567 | typedef long double ld; 1568 | typedef unsigned long long ull; 1569 | typedef pair pii; 1570 | typedef vector vi; 1571 | typedef vector vll; 1572 | #define ntm(i, n) for(int i = 0; i<(n); ++i) 1573 | #define rep(i, a, b) for(int i = a; i<(b); ++i) 1574 | #define all(x) (x).begin(),(x).end() 1575 | #define trav(x, v) for(auto &x : (v)) 1576 | #define sz(x) (int)(x).size() 1577 | #define mp(a, b) make_pair(a, b) 1578 | #define X first 1579 | #define Y second 1580 | #define pb(x) push_back(x) 1581 | #define PS(x) cout << " " << (x) 1582 | #define P1(x) cout << (x) << endl 1583 | #define P2(x,y) cout << (x) << " " << (y) << endl 1584 | #define P3(x,y,z) cout << (x) << " " << (y) << " " << (z) << endl 1585 | #define SQR(x) ((x)*(x)) 1586 | #define CUBE(x) ((x)*(x)*(x)) 1587 | #define PF(x, y) fixed << setprecision(y) << x 1588 | 1589 | using namespace std; 1590 | 1591 | struct TwoSat { 1592 | int N; 1593 | vector gr; 1594 | vi values; // 0 = false , 1 = true 1595 | TwoSat(int n = 0) : N(n), gr(2*n) {} 1596 | int add_var() { 1597 | gr.emplace_back(); 1598 | gr.emplace_back(); 1599 | return N++; 1600 | } 1601 | void either(int f, int j) { 1602 | f = max(2*f, -1-2*f); 1603 | j = max(2*j, -1-2*j); 1604 | //P3("either: ", f, j); 1605 | gr[f^1].push_back(j); 1606 | gr[j^1].push_back(f); 1607 | } 1608 | void set_value(int x) { either(x, x); } 1609 | void at_most_one(const vi& li) { 1610 | if (sz(li) <= 1) return; 1611 | int cur = ~li[0]; 1612 | rep(i,2,sz(li)) { 1613 | int next = add_var(); 1614 | either(cur, ~li[i]); 1615 | either(cur, next); 1616 | either(~li[i], next); 1617 | cur = ~next; 1618 | } 1619 | either(cur, ~li[1]); 1620 | } 1621 | vi val, comp, z; int time = 0; 1622 | int dfs(int i) { 1623 | int low = val[i] = ++time, x; z.push_back(i); 1624 | trav(e, gr[i]) if (!comp[e]) 1625 | low = min(low, val[e] ?: dfs(e)); 1626 | ++time; 1627 | if (low == val[i]) do { 1628 | x = z.back(); z.pop_back(); 1629 | comp[x] = time; 1630 | if (values[x>>1] == -1) 1631 | values[x>>1] = !(x&1); 1632 | } while (x != i); 1633 | return val[i] = low; 1634 | } 1635 | bool solve() { 1636 | values.assign(N, -1); 1637 | val.assign(2*N, 0); comp = val; 1638 | rep(i,0,2*N) if (!comp[i]) dfs(i); 1639 | rep(i,0,N) if (comp[2*i] == comp[2*i+1]) return 0; 1640 | return 1; 1641 | } 1642 | }; 1643 | 1644 | //// O(n*n) 1645 | 1646 | int womens_priority[MX][MX],married[MX],couple[MX]; 1647 | queuemens_priority[MX]; 1648 | 1649 | void free(){ 1650 | for(int i=0;i>ts; 1662 | while(++cas<=ts){ 1663 | scanf("%d",&n); 1664 | free(); 1665 | //womens 1666 | for(i=1;i<=n;i++){ 1667 | for(j=1;j<=n;j++){ 1668 | scanf("%d",&x); 1669 | womens_priority[i][x] = n-j; 1670 | } 1671 | } 1672 | //mens 1673 | for(i=1;i<=n;i++){ 1674 | for(j=1;j<=n;j++){ 1675 | scanf("%d",&x); 1676 | mens_priority[n+i].push(x); 1677 | } 1678 | } 1679 | cn=0; 1680 | while(cn!=n){ 1681 | for(i=n+1;i<=2*n;i++){ 1682 | if(!married[i]){ 1683 | x = mens_priority[i].front(); 1684 | mens_priority[i].pop(); 1685 | married[i] = 1; 1686 | if(couple[x]==0) { 1687 | couple[x] = i,cn++; 1688 | } 1689 | else{ 1690 | if(womens_priority[x][couple[x]]=ln){ 1730 | if(sum%n==0&&mult%n==0) return 1; 1731 | else return 0; 1732 | } 1733 | if(dp[pos][lst][sum][mult]!=-1) 1734 | return dp[pos][lst][sum][mult]; 1735 | int x=0,y; 1736 | for(int i=0; i<=9; i++){ 1737 | if(lst){ 1738 | y = st[pos]-'0'; 1739 | if(i>y) break; 1740 | x += bct(pos+1,i==y,(sum+i)%n,(mult*10+i)%n); 1741 | } 1742 | else{ 1743 | x += bct(pos+1,0,(sum+i)%n,(mult*10+i)%n); 1744 | } 1745 | } 1746 | return dp[pos][lst][sum][mult] = x; 1747 | } 1748 | 1749 | /** 1750 | FLOW + MATCHING! FLOW + MATCHING! FLOW + MATCHING! FLOW + MATCHING! 1751 | FLOW + MATCHING! FLOW + MATCHING! FLOW + MATCHING! FLOW + MATCHING! 1752 | FLOW + MATCHING! FLOW + MATCHING! FLOW + MATCHING! FLOW + MATCHING! 1753 | FLOW + MATCHING! FLOW + MATCHING! FLOW + MATCHING! FLOW + MATCHING! 1754 | */ 1755 | 1756 | /** 1757 | Name : Bipartite Matching 1758 | Description : Find maximum matching. we can find bipartite graph from left or right array 1759 | lt = left, rt =right, ed = adjesency matrix 1760 | left and right graph can contains nodes with same same or number 1761 | Time Complexity : O(EV) 1762 | Some Properties : 1763 | * in a graph if we push both side then number of pair is ceil(Bipartite/2) 1764 | * A graph is bipartite, if it doesn't contain any odd cycle. 1765 | 0. V = A u B 1766 | 1. Konigs minimax: In a bipartite graph v = t and a = p 1767 | 2. Hall's theorem: G has a matching from A to B, iif, for all X (subset of A), |adj(X)| >= |X| 1768 | 3. The Marriage Theorem: A perfect match exist iff, it has a matching from A to B and |A| = |B| 1769 | 4. Dilworth Theorem: For a finite partially ordered poset S, 1770 | the largest antichain is equal to the minimum chain partition and vice versa. 1771 | Consider a bipartite graph built this way, A = S, B = S and and edge from x(A) to y(B) exists if x <= y. 1772 | Let, c be the minimum chain partition. Then, v + c = n. 1773 | */ 1774 | 1775 | 1776 | #define MX 55 1777 | vectored[MX]; 1778 | int lt[MX],rt[MX]; 1779 | bool vs[MX]; 1780 | 1781 | bool bpm(int u){ 1782 | int i,v; 1783 | for(i=0;i> capacity; 1824 | vector> adj; 1825 | 1826 | int bfs(int s, int t, vector& parent) { 1827 | fill(parent.begin(), parent.end(), -1); 1828 | parent[s] = -2; 1829 | queue> q; 1830 | q.push({s, INF}); 1831 | 1832 | while (!q.empty()) { 1833 | int cur = q.front().first; 1834 | int flow = q.front().second; 1835 | q.pop(); 1836 | 1837 | for (int next : adj[cur]) { 1838 | if (parent[next] == -1 && capacity[cur][next]) { 1839 | parent[next] = cur; 1840 | int new_flow = min(flow, capacity[cur][next]); 1841 | if (next == t) 1842 | return new_flow; 1843 | q.push({next, new_flow}); 1844 | } 1845 | } 1846 | } 1847 | 1848 | return 0; 1849 | } 1850 | 1851 | int maxflow(int s, int t) { 1852 | int flow = 0; 1853 | vector parent(n); 1854 | int new_flow; 1855 | 1856 | while (new_flow = bfs(s, t, parent)) { 1857 | flow += new_flow; 1858 | int cur = t; 1859 | while (cur != s) { 1860 | int prev = parent[cur]; 1861 | capacity[prev][cur] -= new_flow; 1862 | capacity[cur][prev] += new_flow; 1863 | cur = prev; 1864 | } 1865 | } 1866 | 1867 | return flow; 1868 | } 1869 | 1870 | /** 1871 | Name : Flow Dinic 1872 | Time Complexity : O(V^2*E) 1873 | Use : if u to v have mutiple path dont add path multiple time. 1874 | just add the path cost to capacity matrix 1875 | * reverse edge must be push. if unidirectional graph then push reverse edge 1876 | seting the reverse edge capacity zero 1877 | */ 1878 | 1879 | 1880 | typedef pair pii; 1881 | vectoradj[MAX]; 1882 | int cap[MAX][MAX]; 1883 | 1884 | int q[100000]; 1885 | bool fl[MAX][MAX]; // u theke v te path ase kina 1886 | 1887 | /** 1888 | n = number of nodes 1889 | s = starting node 1890 | t = destination node 1891 | returns maximum flow 1892 | */ 1893 | 1894 | int dinic( int n,int s,int t ) { 1895 | int prev[MAX], u, v, i, z, flow = 0, qh, qt, inc; 1896 | while(1) { 1897 | memset( prev, -1, sizeof( prev ) ); 1898 | qh = qt = 0; 1899 | prev[s] = -2; 1900 | q[qt++] = s; 1901 | while( qt != qh && prev[t] == -1 ) { 1902 | u = q[qh++]; 1903 | for(i = 0; i < adj[u].size(); i++) { 1904 | v = adj[u][i]; 1905 | if( prev[v] == -1 && cap[u][v] ) { 1906 | prev[v] = u; 1907 | q[qt++] = v; 1908 | } 1909 | } 1910 | } 1911 | if(prev[t] == -1) break; 1912 | for(z = 1; z <= n; z++) if( prev[z] !=- 1 && cap[z][t] ) { 1913 | inc = cap[z][t]; 1914 | for( v = z, u = prev[v]; u >= 0; v = u, u=prev[v]) inc = min( inc, cap[u][v] ); 1915 | if( !inc ) continue; 1916 | cap[z][t] -= inc; 1917 | cap[t][z] += inc; 1918 | for(v=z, u = prev[v]; u >= 0; v = u, u = prev[v]) { 1919 | cap[u][v] -= inc; 1920 | cap[v][u] += inc; 1921 | } 1922 | flow += inc; 1923 | } 1924 | } 1925 | return flow; 1926 | } 1927 | 1928 | 1929 | scanf("%d %d %d %d",&n,&s,&t,&c); 1930 | CLR(cap); 1931 | CLR(adj); 1932 | CLR(fl); 1933 | for(i=1;i<=c;i++){ 1934 | scanf("%d %d %d",&u,&v,&x); 1935 | if(!fl[u][v]){ 1936 | adj[u].push_back(v); 1937 | adj[v].push_back(u); 1938 | fl[u][v] = fl[v][u]; 1939 | } 1940 | cap[u][v] += x; 1941 | cap[v][u] += x; 1942 | } 1943 | printf("Case %d: %d\n",cas,dinic(n,s,t)); 1944 | 1945 | 1946 | /** 1947 | STRING! STRING! STRING! STRING! STRING! STRING! STRING! 1948 | STRING! STRING! STRING! STRING! STRING! STRING! STRING! 1949 | STRING! STRING! STRING! STRING! STRING! STRING! STRING! 1950 | STRING! STRING! STRING! STRING! STRING! STRING! STRING! 1951 | */ 1952 | 1953 | /// **** Knuth–Morris–Pratt(KMP) [n+k] 1954 | 1955 | #define MX 1000005 1956 | ///Largest possible suffix-prefix upto this index 1957 | int lps[MX]; 1958 | 1959 | /// prefix size is (j+1) as key i 0 based index 1960 | 1961 | void lps_calc(char key[]){ 1962 | int i = 1,j = 0; 1963 | while(key[i]){ 1964 | //cout<<"ff\n"; 1965 | if(key[i]==key[j]){ 1966 | lps[i] = ++j; 1967 | i++; 1968 | } 1969 | else{ 1970 | if(j) j = lps[j-1]; 1971 | else lps[i++] = 0; 1972 | } 1973 | } 1974 | } 1975 | /** 1976 | * @return -1 if no match found else return staring position of match 1977 | */ 1978 | int match(char txt[],char key[],int key_ln){ 1979 | int i=0,j=0,cn=0; 1980 | while(txt[i]){ 1981 | if(txt[i]==key[j]){ 1982 | i++; 1983 | j++; 1984 | if(j==key_ln){ 1985 | return i - key_ln; //satring pos 1986 | ///How many match 1987 | //cn++; 1988 | //j=lps[j-1]; 1989 | } 1990 | } 1991 | else{ 1992 | if(j) j = lps[j-1]; 1993 | else i++; 1994 | /// j = 0 and pos are not equal then skipping this position 1995 | } 1996 | } 1997 | return cn; 1998 | } 1999 | 2000 | char txt[MX],key[MX]; 2001 | 2002 | 2003 | 2004 | /// **** Rabin-Karp 2005 | 2006 | #define MD 1000000009 2007 | using namespace std; 2008 | 2009 | ll pm=31,powr[MX],hs[MX]; 2010 | 2011 | void powCalc(){ 2012 | powr[0] = 1; 2013 | for(int i=1;i ans; 2019 | 2020 | void rabin_karp(char txt[],char ptt[]){ 2021 | int P = strlen(ptt),T=strlen(txt),i,crr; 2022 | 2023 | memset(hs,0,sizeof hs); 2024 | 2025 | for(i=0; i 1 anana 2054 | 3 ana alphabetically 0 banana 2055 | 4 na 4 na 2056 | 5 a 2 nana 2057 | So the suffix array for "banana" is {5, 3, 1, 0, 4, 2} 2058 | 2059 | Uses : 2060 | 2061 | * number of uniqe substring of a string : n(n+1)/2 − ∑ lcp[i] (summation of all lcp is duplicate string as lcp means longest match with the prev string) 2062 | * longest common substring by sliding window (add special character and joint all strings then calculate lcp and by sliding window we can determine the longest substring) 2063 | * longest repeated substring : maximum value of lcp is longest repeated substring, number of the maximum number is the longest repeated substring is the longest repeated substring 2064 | * Finding a substring in a string : by binary search on the lcp array 2065 | */ 2066 | 2067 | #define MX 10005 2068 | 2069 | int sfa[10009],pos[10009],tmp[10009],lcp[10009],gap=1,ln; 2070 | char ss[10009]; 2071 | bool scmp(int a,int b) 2072 | { 2073 | if(pos[a]!=pos[b])return pos[a]b; 2077 | 2078 | } 2079 | void buildsa() 2080 | { 2081 | int i,j; 2082 | ln=strlen(ss); 2083 | for(i=0;i<=ln;i++){ 2084 | sfa[i]=i; 2085 | pos[i]=ss[i]; 2086 | } 2087 | for(gap=1;;gap*=2){ 2088 | sort(sfa,sfa+ln,scmp); 2089 | for(i=0;ir){ 2152 | for(i=1;i<=r;i++){ 2153 | if(i==r) printf("%d\n",sln[i]); 2154 | else printf("%d ",sln[i]); 2155 | } 2156 | return; 2157 | } 2158 | 2159 | for(i=last+1;i<=n;i++){ 2160 | sln[pos] = ara[i]; 2161 | combinition(pos+1,i); 2162 | } 2163 | } 2164 | 2165 | /** 2166 | * Name : m-Coloring problem 2167 | * this variation is to print maximum node with a spacific colour here 2 2168 | */ 2169 | 2170 | ///ncol is number of colours 2171 | vectored[MX]; 2172 | int col[MX]; 2173 | int n,m,tmp[MX],in,ncol=2; 2174 | 2175 | bool safe(int pos,int cl){ 2176 | int x; 2177 | for(int i=0;in){ 2187 | if(cnt>in){ 2188 | in = 0; 2189 | for(int i=1;i<=n;i++){ 2190 | if(col[i]==1) tmp[++in] = i; 2191 | } 2192 | } 2193 | return; 2194 | } 2195 | int i,cn=0; 2196 | 2197 | ///trying all colour in a spacific node 2198 | 2199 | for(i=1;i<=ncol;i++){ 2200 | 2201 | if(i==1) cn = 1; 2202 | else cn = 0; 2203 | 2204 | if(safe(pos,i)){ 2205 | col[pos] = i; 2206 | backtrack(pos+1,cnt+cn); 2207 | col[pos] = 0; 2208 | } 2209 | } 2210 | } 2211 | 2212 | void free(){ 2213 | in = 0; 2214 | for(int i=0;i<105;i++){ 2215 | col[i] = tmp[i] = 0; 2216 | ed[i].clear(); 2217 | } 2218 | } 2219 | 2220 | ///calling with : backtrack(0,0); 2221 | 2222 | /// ***Bigint Factorial **** 2223 | 2224 | //package main; 2225 | 2226 | import java.math.BigInteger; 2227 | import java.util.Scanner; 2228 | 2229 | public class Main { 2230 | 2231 | public static Scanner sc; 2232 | 2233 | public static void main(String [] arg) { 2234 | 2235 | BigInteger [] fact = new BigInteger[200]; 2236 | 2237 | fact[0] = BigInteger.ONE; 2238 | 2239 | for(int i=1;i<=150;i++) { 2240 | fact[i] = fact[i-1].multiply(new BigInteger(i + "")); 2241 | } 2242 | 2243 | sc = new Scanner(System.in); 2244 | int ts = sc.nextInt(); 2245 | int n,cas=0; 2246 | 2247 | while(++cas<=ts) { 2248 | n = sc.nextInt(); 2249 | System.out.println(fact[n]); 2250 | } 2251 | } 2252 | } 2253 | 2254 | /** 2255 | COMPUTATIONAL GEOMETRY! COMPUTATIONAL GEOMETRY! COMPUTATIONAL GEOMETRY! 2256 | COMPUTATIONAL GEOMETRY! COMPUTATIONAL GEOMETRY! COMPUTATIONAL GEOMETRY! 2257 | COMPUTATIONAL GEOMETRY! COMPUTATIONAL GEOMETRY! COMPUTATIONAL GEOMETRY! 2258 | COMPUTATIONAL GEOMETRY! COMPUTATIONAL GEOMETRY! COMPUTATIONAL GEOMETRY! 2259 | */ 2260 | 2261 | 2262 | /// *** Convex Hull[Grahams Scan] [nlog(n)] 2263 | 2264 | #define ll long long 2265 | struct point{ 2266 | ll x,y; 2267 | }convex_points[MX],points[MX];; 2268 | 2269 | /// global scope decraltion of min-left point of collcetion 2270 | point pivot; 2271 | 2272 | ///Distance calculation mathod 2273 | ll dist(point p1,point p2){ 2274 | return ((p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y)); 2275 | } 2276 | 2277 | /** 2278 | * https://www.geeksforgeeks.org/orientation-3-ordered-points/ 2279 | * calculating orientation based on slope (yi-yj)/(xi-xj) 2280 | * by compering slope of p-q and q-r; 2281 | * if p-q0) return 1; 2290 | return 2; 2291 | } 2292 | 2293 | /** 2294 | * sorting by polor angle in counterclockwise order around point0. 2295 | * If polor angle of two points is same, then put the nearest point first. 2296 | */ 2297 | bool cmp(point p1,point p2){ 2298 | ll o = orientation(pivot,p1,p2); 2299 | if(o==0){ 2300 | return dist(pivot,p1) < dist(pivot,p2); 2301 | } 2302 | return (o==2); 2303 | } 2304 | 2305 | /// returning previous value of top element 2306 | inline point nextToTop(stack&st){ 2307 | point p,res; 2308 | p = st.top(); 2309 | st.pop(); 2310 | res = st.top(); 2311 | st.push(p); 2312 | return res; 2313 | } 2314 | 2315 | int total; 2316 | 2317 | /** 2318 | * This function will calculate convexHull points 2319 | * All arrays are in 0 based indexing 2320 | * @param n total numbers of points 2321 | */ 2322 | bool convexHull(int n){ 2323 | ll i,pos=0,in=0,miny = points[0].y,minx = points[0].x; 2324 | stackst; 2325 | 2326 | /// Finding bottom-left most point 2327 | for(i=0;ipoints[i].x)||miny>points[i].y){ 2329 | minx = points[i].x; 2330 | miny = points[i].y; 2331 | pos = i; 2332 | } 2333 | } 2334 | 2335 | ///sorting element according to the criteria 2336 | swap(points[0],points[pos]); 2337 | pivot = points[0]; 2338 | sort(points+1,points+n,cmp); 2339 | 2340 | ///Now removing same angle point 2341 | for(i=1;i0) return 1; 2406 | return 2; 2407 | } 2408 | 2409 | /** 2410 | * sorting by polor angle in counterclockwise order around point0. 2411 | * If polor angle of two points is same, then put the nearest point first. 2412 | */ 2413 | bool cmp(point p1,point p2){ 2414 | ll o = orientation(pivot,p1,p2); 2415 | if(o==0){ 2416 | return dist(pivot,p1) < dist(pivot,p2); 2417 | } 2418 | return (o==2); 2419 | } 2420 | 2421 | /// returning previous value of top element 2422 | inline point nextToTop(stack&st){ 2423 | point p,res; 2424 | p = st.top(); 2425 | st.pop(); 2426 | res = st.top(); 2427 | st.push(p); 2428 | return res; 2429 | } 2430 | 2431 | int total; 2432 | 2433 | /** 2434 | * This function will calculate convexHull points 2435 | * All arrays are in 0 based indexing 2436 | * @param n total numbers of points 2437 | */ 2438 | double convexHull(int n) 2439 | { 2440 | vector hull; 2441 | int l = 0; 2442 | for (int i = 1; i < n; i++) 2443 | if (points[i].x < points[l].x) 2444 | l = i; 2445 | int p = l, q; 2446 | do 2447 | { 2448 | hull.push_back(points[p]); 2449 | q = (p+1)%n; 2450 | for (int i = 0; i < n; i++) 2451 | { 2452 | if (orientation(points[p], points[i], points[q]) == 2) 2453 | q = i; 2454 | } 2455 | 2456 | p = q; 2457 | 2458 | } while (p != l); 2459 | double ans = distd(hull[0],hull[hull.size()-1]); 2460 | for (int i = 0; i 0){ 2505 | if (r&1) x = (x*n)%MD; 2506 | n = (n*n)%MD; 2507 | r >>= 1; 2508 | } 2509 | return x % MD; 2510 | } 2511 | 2512 | 2513 | /// *** Matrix Exponentiation [2^3*log(n)] 2514 | /// by calling exponent this will calculate (ara^p)%md; 2515 | /// here n is the dimention of the matrix ara 2516 | 2517 | #define ll long long 2518 | #define DIM 5 2519 | 2520 | ll tmp[DIM][DIM],result[DIM][DIM]; 2521 | 2522 | void cpy(ll ar1[][DIM],ll ar2[][DIM],ll n){ 2523 | for(int i=1;i<=n;i++) 2524 | for(int j=1;j<=n;j++) 2525 | ar1[i][j] = ar2[i][j]; 2526 | } 2527 | 2528 | void mult(ll ar1[][DIM], ll ar2[][DIM], ll n, ll mod){ 2529 | int i,j,k; 2530 | memset(tmp,0,sizeof tmp); 2531 | for(i=1;i<=n;i++){ 2532 | for(j=1;j<=n;j++){ 2533 | for(k=1;k<=n;k++){ 2534 | tmp[i][j] = (tmp[i][j] + ar1[i][k]*ar2[k][j])%mod; 2535 | } 2536 | } 2537 | } 2538 | cpy(ar1,tmp,n); 2539 | } 2540 | 2541 | void exponent(ll ara[][DIM], ll p,ll n, ll mod){ 2542 | int i,j; 2543 | //initializing identity 2544 | for(i=1;i<=n;i++) 2545 | for(j=1;j<=n;j++) 2546 | if(i==j) result[i][j] = 1; 2547 | else result[i][j] = 0; 2548 | 2549 | while(p){ 2550 | if(p&1){ 2551 | mult(result,ara,n,mod); 2552 | } 2553 | mult(ara,ara,n,mod); 2554 | p >>= 1; 2555 | } 2556 | cpy(ara,result,n); 2557 | } 2558 | 2559 | /** 2560 | COMBINATORICS! COMBINATORICS! COMBINATORICS! 2561 | COMBINATORICS! COMBINATORICS! COMBINATORICS! 2562 | COMBINATORICS! COMBINATORICS! COMBINATORICS! 2563 | COMBINATORICS! COMBINATORICS! COMBINATORICS! 2564 | */ 2565 | 2566 | /// *** ncr [n*r] [but it is dp] 2567 | 2568 | ll cr[902][902]; 2569 | ll ncr(int n,int r){ 2570 | if(n==r)return 1; 2571 | if(r==1)return n; 2572 | if(cr[n][r])return cr[n][r]; 2573 | return cr[n][r] = ncr(n-1,r)+ncr(n-1,r-1); 2574 | } 2575 | 2576 | /** 2577 | Name : Inclusion-Exclusion 2578 | Description : compute the union of sets 2579 | Time Complexity : O(2^n) 2580 | Space : O(n) 2581 | Source : collected form hacker earth 2582 | */ 2583 | 2584 | int n; // the number of sets in the set A 2585 | int result = 0; //final result, the cardinality of sum of all subsets of A 2586 | for(int b = 0; b < (1 << n); ++b){ 2587 | vector indices; 2588 | for(int k = 0; k < n; ++k){ 2589 | if(b & (1 << k)){ 2590 | // we could work with this values 2591 | indices.push_back(k); 2592 | } 2593 | } 2594 | int cardinality = intersectionCardinality(indices); // intersections 2595 | if(indices.size() % 2 == 1) result += cardinality; 2596 | else result -= cardinality; 2597 | } 2598 | cout << result << endl; //printing the final result 2599 | 2600 | 2601 | /** 2602 | Name : Catalan Number 2603 | n’th catalan number : Cn = (1/(n+1))(2n n) = (2n n) - (2n n+1) 2604 | =(2n)!/((2n-n)!*n!*(n+1)) 2605 | =(2n)!/((n)!*(n+1)!) 2606 | 2607 | C(0) = C(1) = 1 2608 | C(4) = C0*C3 + C1*C2 + C2*C1 + C3*C0 2609 | C(n) =C(0)*(n-1) +C(1)*C(n-2) +.......... +C(i)*C(n-i-1)+........+C(n-1)*C(0) 2610 | 2611 | * the number of ways a polygon with n+2 sides can be cut into triangles 2612 | * the number of ways to use n rectangles to tile a stairstep shape (1, 2, ..., n−1, n). 2613 | * Cn counts the number of expressions containing n pairs of parentheses which are correctly matched 2614 | * Cn is the number of different ways (n + 1) factors can be completely parenthesized catalan(3) = 5 , ex : ((ab)c)d, (a(bc))d , (ab)(cd) , a((bc)d) , a(b(cd)) 2615 | * Count the number of possible Binary Search Trees with n keys 2616 | * Total number of full binary tree : catalan(n) * factorial(n) 2617 | * the number of paths of length 2n through an n-by-n grid that do not rise above the main diagonal 2618 | * Cn is the number of ways to form a “mountain ranges” with n upstrokes and n down-strokes that all stay above the original line.The mountain range interpretation is that the mountains will never go below the horizontal. 2619 | * Cn is the number of ways that the vertices of a convex 2n-gon can be paired so that the line segments joining paired vertices do not intersect. This is precisely the condition that guarantees that the paired edges can be identified (sewn together) to form a closed surface of genus zero (a topological 2-sphere). 2620 | 2621 | */ 2622 | 2623 | ///Time Complexity =~ onetime n for factorial 2624 | /// and in each query [log(n)] 2625 | 2626 | #define ll long long 2627 | #define MX 1000005 2628 | #define MD 100000007 2629 | 2630 | ll powr(ll n, ll p){ 2631 | if(p==0) return 1; 2632 | if(p==1) return n; 2633 | if(p&1LL) return (powr(n,p-1)*n)%MD; 2634 | else{ 2635 | ll x = powr(n,p/2)%MD; 2636 | return (x*x)%MD; 2637 | } 2638 | } 2639 | 2640 | ll inverse(ll n){ 2641 | return (powr(n,MD-2))%MD; 2642 | } 2643 | 2644 | ll ft[MX]; 2645 | 2646 | void fact(){ 2647 | ll i; 2648 | ft[0] = 1; 2649 | for(i=1;i 2673 | /** 2674 | 1 10 4 2675 | 2 100 25 2676 | 3 1,000 168 2677 | 4 10,000 1,229 2678 | 5 100,000 9,592 2679 | 6 1,000,000 78,498 2680 | 7 10,000,000 664,579 2681 | 8 100,000,000 5,761,455 2682 | 9 1,000,000,000 50,847,534 2683 | 10 10,000,000,000 455,052,511 2684 | 11 100,000,000,000 4,118,054,813 2685 | 12 1,000,000,000,000 37,607,912,018 2686 | 13 10,000,000,000,000 346,065,536,839 2687 | 14 100,000,000,000,000 3,204,941,750,802 2688 | 15 1,000,000,000,000,000 29,844,570,422,669 2689 | 16 10,000,000,000,000,000 279,238,341,033,925 2690 | 17 100,000,000,000,000,000 2,623,557,157,654,233 2691 | 18 1,000,000,000,000,000,000 24,739,954,287,740,860 2692 | 19 10,000,000,000,000,000,000 234,057,667,276,344,607 2693 | 20 100,000,000,000,000,000,000 2,220,819,602,560,918,840 2694 | 21 1,000,000,000,000,000,000,000 21,127,269,486,018,731,928 2695 | 22 10,000,000,000,000,000,000,000 201,467,286,689,315,906,290 2696 | 23 100,000,000,000,000,000,000,000 1,925,320,391,606,803,968,923 2697 | 24 1,000,000,000,000,000,000,000,000 18,435,599,767,349,200,867,866 2698 | 25 10,000,000,000,000,000,000,000,000 176,846,309,399,143,769,411,680 2699 | */ 2700 | 2701 | /// *** Normal Sieve [ n*sqrt(n) ] 2702 | /// [ mark can be check for is prime ] 2703 | 2704 | #define SZ 100009 2705 | int pr[78600],in=0; 2706 | bool mr[SZ+3]; 2707 | 2708 | void sieve(){ 2709 | int i,j,sq,p; 2710 | sq=sqrt(SZ)+2; 2711 | mr[1]=1; 2712 | for(i=2; i pr; 2735 | 2736 | void sieve(){ 2737 | int i,j; 2738 | for (i=2; i<=N; ++i) { 2739 | if (lp[i] == 0) { 2740 | lp[i] = i; 2741 | pr.push_back (i); 2742 | } 2743 | for (j=0; j<(int)pr.size() && pr[j]<=lp[i] && i*pr[j]<=N; ++j) 2744 | lp[i*pr[j]] = pr[j]; 2745 | } 2746 | } 2747 | 2748 | 2749 | /// *** BitwiseSieve [~ n log(n) may be ] 2750 | /// [It can be use for finding huge number of primes] 2751 | 2752 | #define check(X) (mkr[X>>6]&(1<<((X&63)>>1))) 2753 | #define mark(X) mkr[X>>6]|=(1<<((X&63)>>1)) 2754 | int mkr[10000900/64],SZ=10000020,pr[700000],in=0; 2755 | 2756 | void bitwsiv() 2757 | { 2758 | int i,j,rt=sqrt(SZ)+1; 2759 | for(i=3; i<=rt; i+=2){ 2760 | if(!check(i)){ 2761 | for(j=i*i; j<=SZ; j+=i+i){ 2762 | mark(j); 2763 | } 2764 | } 2765 | } 2766 | pr[++in]=2; 2767 | for(i=3; i<=SZ; i+=2){ 2768 | if(!check(i))pr[++in]=i; 2769 | } 2770 | } 2771 | 2772 | /// *** Segmented Sieve [ sqrt(up) + prime sieve ] 2773 | 2774 | /** [l = lower limit, u = upper limit] 2775 | * [first generate all prime upto sqrt(upper limit)] 2776 | * [Checking prime 2777 | * n = number into that segment] 2778 | * if(!mark[n-l]) then it is prime 2779 | */ 2780 | bool mark[u-l]; 2781 | void segsiv(ll l, ll u) 2782 | { 2783 | ll i,j,lt; 2784 | if(l==1) mark[0] = 1; 2785 | for(i=1; i<=in&&pr[i]*pr[i]<=u; i++){ 2786 | lt = l/pr[i]; 2787 | lt *= pr[i]; 2788 | if(lt 0){ 2838 | if (b&1) x = (x + y) % mod; 2839 | y = (y<<1) % mod; 2840 | b >>= 1; 2841 | } 2842 | return x % mod; 2843 | } 2844 | 2845 | //Bigmod 2846 | ll modulo(ll n, ll r, ll mod){ 2847 | ll x = 1; 2848 | while (r > 0){ 2849 | if (r&1) x = mulmod(x,n,mod); 2850 | n = mulmod(n,n,mod); 2851 | r >>= 1; 2852 | } 2853 | return x % mod; 2854 | } 2855 | /// higher value of "it" ensure higher percision [recomendation 7] 2856 | 2857 | bool MillerRabin(ll p,int it) 2858 | { 2859 | if (p < 2) return 0; 2860 | if (p != 2 && p % 2==0) return 0; 2861 | 2862 | ll i,a,tmp,mod,s=p-1; 2863 | 2864 | while(s%2==0){ 2865 | s>>=1; 2866 | } 2867 | for(i=0;i1) // then n is a prime 2913 | } 2914 | 2915 | /** 2916 | Description : prime factorization 2917 | Complexity : O(log n) 2918 | Limitation : memory complexity O(n) so it works up to 10^7 2919 | */ 2920 | 2921 | const int N = 10000000; 2922 | int lp[N+1]; 2923 | vector pr; 2924 | 2925 | void sieve(){ 2926 | int i,j; 2927 | for (i=2; i<=N; ++i) { 2928 | if (lp[i] == 0) { 2929 | lp[i] = i; 2930 | pr.push_back (i); 2931 | } 2932 | for (j=0; j<(int)pr.size() && pr[j]<=lp[i] && i*pr[j]<=N; ++j) 2933 | lp[i*pr[j]] = pr[j]; 2934 | } 2935 | } 2936 | 2937 | vector prime_fact(int n){ 2938 | vector pf; 2939 | while (n != 1){ 2940 | pf.push_back(lp[n]); 2941 | n = n / lp[n]; 2942 | } 2943 | return pf; 2944 | } 2945 | 2946 | /** 2947 | * Name : NOD 2948 | * Description : Therefore if the prime factorization of n is p1^e1⋅pi2^e2⋯pk^ek, 2949 | * where pi are distinct prime numbers, then the number of divisors is: d(n)=(e1+1)⋅(e2+1)⋯(ek+1) 2950 | * Complexity : O(sqrt(n)) , Squre root porjnto jotogula prime ase 2951 | * Use : store prime up to squreroot(n) by efficient sieve, in = number of prime 2952 | */ 2953 | 2954 | 2955 | 2956 | ll NOD(ll n){ 2957 | ll ans=1,x,count; 2958 | for(int i=0; (ll)prime[i] * (ll)prime[i]<=n && i<=in ;i++){ 2959 | int( n%prime[i] == 0){ 2960 | x=prime[i]; 2961 | count =1; 2962 | while(n%x==0) { 2963 | n/=x; 2964 | count++; 2965 | } 2966 | ans*= count; 2967 | } 2968 | } 2969 | if(n>1) ans*=2; 2970 | return ans; 2971 | } 2972 | 2973 | /** 2974 | * Name : SOD 2975 | * Description : Find sum of divisor of a given number 2976 | * σ(n)=(p1^(e1+1)-1)/(p1−1) * (p2^(e2+1)−1)/(p2−1)***(pk^(ek+1)−1)(pk−1) 2977 | * Complexity : O(sqrt(n)) , Squre root porjnto jotogula prime ase 2978 | * Use : store prime up to squreroot(n) by efficient sieve, in = number of prime 2979 | */ 2980 | 2981 | 2982 | ll SOD(ll n){ 2983 | ll i,cnt,sum=1,tmp,B; 2984 | for(i=1;i<=in&&pr[i]*pr[i]<=n;i++){ 2985 | cnt=0; 2986 | while(n%pr[i]==0){ 2987 | cnt++; 2988 | n /= pr[i]; 2989 | } 2990 | tmp = pr[i]; 2991 | if(cnt){ 2992 | sum *= ((bgM(tmp,cnt+1)-1+MD)%MD)*(modi(tmp-1))%MD; 2993 | } 2994 | sum = sum%MD; 2995 | } 2996 | tmp = n; 2997 | if(n>1){ 2998 | sum *= ((bgM(tmp,2)-1+MD)%MD)*(modi(tmp-1))%MD; 2999 | sum = sum%MD; 3000 | } 3001 | return sum; 3002 | } 3003 | 3004 | 3005 | /// ***Number of divisors [Quberoot(n)] 3006 | 3007 | /** There can be only two prime after qube root 3008 | * so we factorize upto quberoot by the trial divison then 3009 | * handle ramainig <=2 prime 3010 | */ 3011 | 3012 | ll NOD(ll n){ 3013 | ll i,j,r,nod=1,cn; 3014 | for(i=1;i<=in&&(pr[i]*pr[i]*pr[i])<=n;i++){ 3015 | cn = 1; 3016 | while(n%pr[i]==0){ 3017 | n /= pr[i]; 3018 | cn++; 3019 | } 3020 | nod *= cn; 3021 | } 3022 | 3023 | r = sqrtl(n); 3024 | while((r+1)*(r+1)<=n) r++; 3025 | 3026 | if(MillerRabin(n,8)) nod *= 2; 3027 | else if(r*r==n&&MillerRabin(r,8)) nod *= 3; 3028 | else if(n!=1) nod *= 4; 3029 | 3030 | return nod; 3031 | } 3032 | 3033 | /** 3034 | * Name : Totient Function 3035 | * Description : Find number of co-prime of a number less than that number 3036 | * Complexity : O(sqrt(n)) 3037 | * source : https://cp-algorithms.com/algebra/phi-function.html 3038 | */ 3039 | 3040 | int phi(int n) { 3041 | int result = n; 3042 | for (int i = 2; i * i <= n; i++) { 3043 | if(n % i == 0) { 3044 | while(n % i == 0) 3045 | n /= i; 3046 | result -= result / i; 3047 | } 3048 | } 3049 | if(n > 1) 3050 | result -= result / n; 3051 | return result; 3052 | } 3053 | 3054 | 3055 | /// *** Modular Inverse [ log(n) ] 3056 | 3057 | /** [ large division = (upper%M)*modi(low)) ] 3058 | * [ after modular division value should be moded ] 3059 | * [ mainly it returns an iverse and multiplicable value ] 3060 | * [ for loop == first loop throw all number(multiply) with simple mod -] 3061 | * [- then modular inverse ] 3062 | */ 3063 | 3064 | #define M 1000000007 3065 | #define pii pair 3066 | pii extnuc(ll a,ll b) 3067 | { 3068 | if(b==0)return pii(1,0); 3069 | pii d=extnuc(b,a%b); 3070 | return pii(d.second,d.first-d.second*(a/b)); 3071 | } 3072 | 3073 | ll modi(ll n) /// n must be moded value 3074 | { 3075 | pii d=extnuc(n,M); 3076 | return ((d.first%M)+M)%M; 3077 | } 3078 | 3079 | ///Now factorial & inverse factorial with MOD 3080 | void fact() 3081 | { 3082 | ll i; 3083 | fr[0]=fi[0]=1; 3084 | for(i=1;i<2000007;i++){ 3085 | fr[i]=(fr[i-1]*i)%M; 3086 | fi[i]=(fi[i-1]*modi(i))%M; 3087 | //P(fr[i]) 3088 | } 3089 | } 3090 | 3091 | /// Gaussian Elemination [n^3] 3092 | 3093 | void gauss(){ 3094 | for(i=0;iabs(ara[l][i])){ 3098 | l = j; 3099 | } 3100 | } 3101 | if(i!=l){ 3102 | for(j=0;j<=n;j++){ 3103 | swap(ara[i][j], ara[l][j]); 3104 | } 3105 | } 3106 | for(j=0;jr){ 12 | for(i=1;i<=r;i++){ 13 | if(i==r) printf("%d\n",sln[i]); 14 | else printf("%d ",sln[i]); 15 | } 16 | return; 17 | } 18 | 19 | for(i=last+1;i<=n;i++){ 20 | sln[pos] = ara[i]; 21 | combinition(pos+1,i); 22 | } 23 | } 24 | 25 | -------------------------------------------------------------------------------- /Source/BackTracking/Permutation_generation.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Name : all permutation generation 3 | * This code will print all nPr 4 | * While ara contains n elements 5 | * a is starring postion of array 6 | */ 7 | 8 | int ara[200],mr[200],k; 9 | 10 | void permutation(int a,int n){ 11 | int i; 12 | if(a==n+1){ 13 | for(i=1;i<=n;i++) printf("%c",ara[i]); 14 | printf("\n"); 15 | return ; 16 | } 17 | for(i=1;i<=n;i++) if(!mr[i]){ 18 | mr[i] = 1; 19 | ara[a] = i; 20 | permutation(a+1,n); 21 | mr[i] = 0; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Source/BackTracking/m-colouring.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Name : m-Coloring problem 3 | * this variation is to print maximum node with a spacific colour here 2 4 | */ 5 | 6 | ///ncol is number of colours 7 | vectored[MX]; 8 | int col[MX]; 9 | int n,m,tmp[MX],in,ncol=2; 10 | 11 | bool safe(int pos,int cl){ 12 | int x; 13 | for(int i=0;in){ 23 | if(cnt>in){ 24 | in = 0; 25 | for(int i=1;i<=n;i++){ 26 | if(col[i]==1) tmp[++in] = i; 27 | } 28 | } 29 | return; 30 | } 31 | int i,cn=0; 32 | 33 | ///trying all colour in a spacific node 34 | 35 | for(i=1;i<=ncol;i++){ 36 | 37 | if(i==1) cn = 1; 38 | else cn = 0; 39 | 40 | if(safe(pos,i)){ 41 | col[pos] = i; 42 | backtrack(pos+1,cnt+cn); 43 | col[pos] = 0; 44 | } 45 | } 46 | } 47 | 48 | void free(){ 49 | in = 0; 50 | for(int i=0;i<105;i++){ 51 | col[i] = tmp[i] = 0; 52 | ed[i].clear(); 53 | } 54 | } 55 | 56 | ///calling with : backtrack(0,0); 57 | -------------------------------------------------------------------------------- /Source/Big Interger/factorial.cpp: -------------------------------------------------------------------------------- 1 | 2 | /// ***Bigint Factorial **** 3 | 4 | //package main; 5 | 6 | import java.math.BigInteger; 7 | import java.util.Scanner; 8 | 9 | public class Main { 10 | 11 | public static Scanner sc; 12 | 13 | public static void main(String [] arg) { 14 | 15 | BigInteger [] fact = new BigInteger[200]; 16 | 17 | fact[0] = BigInteger.ONE; 18 | 19 | for(int i=1;i<=150;i++) { 20 | fact[i] = fact[i-1].multiply(new BigInteger(i + "")); 21 | } 22 | 23 | sc = new Scanner(System.in); 24 | int ts = sc.nextInt(); 25 | int n,cas=0; 26 | 27 | while(++cas<=ts) { 28 | n = sc.nextInt(); 29 | System.out.println(fact[n]); 30 | } 31 | } 32 | } 33 | 34 | 35 | -------------------------------------------------------------------------------- /Source/Binary Exponentiation/BigMod.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | Name : Bigmod 3 | Description : calculate (n^r)%MD 4 | Complexity : O(log r) 5 | */ 6 | 7 | #define MD 1000007 8 | 9 | ll bigmod(ll n, ll r){ 10 | if(r==0) return 1; 11 | if(r==1) return n%MD; 12 | if(r%2==1) return (bigmod(n,r-1)*n)%MD; 13 | else{ 14 | ll x = bigmod(n,r/2); 15 | return (x*x)%MD; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Source/Binary Exponentiation/BigMod_Wihtout rec.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | Name : bigmod without recursion 3 | Description : calculate (n^r)%MD 4 | Complexity : O(log r) 5 | */ 6 | 7 | 8 | #define MD 1000007 9 | 10 | ll bigmod(ll n, ll r){ 11 | ll x = 1; 12 | while (r > 0){ 13 | if (r&1) x = (x*n)%MD; 14 | n = (n*n)%MD; 15 | r >>= 1; 16 | } 17 | return x % MD; 18 | } 19 | -------------------------------------------------------------------------------- /Source/Binary Exponentiation/matrix_exponent.cpp: -------------------------------------------------------------------------------- 1 | /// *** Matrix Exponentiation [2^3*log(n)] 2 | /// by calling exponent this will calculate (ara^p)%md; 3 | /// here n is the dimention of the matrix ara 4 | 5 | #define ll long long 6 | #define DIM 5 7 | 8 | ll tmp[DIM][DIM],result[DIM][DIM]; 9 | 10 | void cpy(ll ar1[][DIM],ll ar2[][DIM],ll n){ 11 | for(int i=1;i<=n;i++) 12 | for(int j=1;j<=n;j++) 13 | ar1[i][j] = ar2[i][j]; 14 | } 15 | 16 | void mult(ll ar1[][DIM], ll ar2[][DIM], ll n, ll mod){ 17 | int i,j,k; 18 | memset(tmp,0,sizeof tmp); 19 | for(i=1;i<=n;i++){ 20 | for(j=1;j<=n;j++){ 21 | for(k=1;k<=n;k++){ 22 | tmp[i][j] = (tmp[i][j] + ar1[i][k]*ar2[k][j])%mod; 23 | } 24 | } 25 | } 26 | cpy(ar1,tmp,n); 27 | } 28 | 29 | void exponent(ll ara[][DIM], ll p,ll n, ll mod){ 30 | int i,j; 31 | //initializing identity 32 | for(i=1;i<=n;i++) 33 | for(j=1;j<=n;j++) 34 | if(i==j) result[i][j] = 1; 35 | else result[i][j] = 0; 36 | 37 | while(p){ 38 | if(p&1){ 39 | mult(result,ara,n,mod); 40 | } 41 | mult(ara,ara,n,mod); 42 | p >>= 1; 43 | } 44 | cpy(ara,result,n); 45 | } 46 | 47 | -------------------------------------------------------------------------------- /Source/Combinatorics/Catalan_number.cpp: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | Name : Catalan Number 4 | n’th catalan number : Cn = (1/(n+1))(2n n) = (2n n) - (2n n+1) 5 | =(2n)!/((2n-n)!*n!*(n+1)) 6 | =(2n)!/((n)!*(n+1)!) 7 | 8 | C(0) = C(1) = 1 9 | C(4) = C0*C3 + C1*C2 + C2*C1 + C3*C0 10 | C(n) =C(0)*(n-1) +C(1)*C(n-2) +.......... +C(i)*C(n-i-1)+........+C(n-1)*C(0) 11 | 12 | * the number of ways a polygon with n+2 sides can be cut into triangles 13 | * the number of ways to use n rectangles to tile a stairstep shape (1, 2, ..., n−1, n). 14 | * Cn counts the number of expressions containing n pairs of parentheses which are correctly matched 15 | * Cn is the number of different ways (n + 1) factors can be completely parenthesized catalan(3) = 5 , ex : ((ab)c)d, (a(bc))d , (ab)(cd) , a((bc)d) , a(b(cd)) 16 | * Count the number of possible Binary Search Trees with n keys 17 | * Total number of full binary tree : catalan(n) * factorial(n) 18 | * the number of paths of length 2n through an n-by-n grid that do not rise above the main diagonal 19 | * Cn is the number of ways to form a “mountain ranges” with n upstrokes and n down-strokes that all stay above the original line.The mountain range interpretation is that the mountains will never go below the horizontal. 20 | * Cn is the number of ways that the vertices of a convex 2n-gon can be paired so that the line segments joining paired vertices do not intersect. This is precisely the condition that guarantees that the paired edges can be identified (sewn together) to form a closed surface of genus zero (a topological 2-sphere). 21 | 22 | */ 23 | 24 | ///Time Complexity =~ onetime n for factorial 25 | /// and in each query [log(n)] 26 | 27 | #define ll long long 28 | #define MX 1000005 29 | #define MD 100000007 30 | 31 | ll powr(ll n, ll p){ 32 | if(p==0) return 1; 33 | if(p==1) return n; 34 | if(p&1LL) return (powr(n,p-1)*n)%MD; 35 | else{ 36 | ll x = powr(n,p/2)%MD; 37 | return (x*x)%MD; 38 | } 39 | } 40 | 41 | ll inverse(ll n){ 42 | return (powr(n,MD-2))%MD; 43 | } 44 | 45 | ll ft[MX]; 46 | 47 | void fact(){ 48 | ll i; 49 | ft[0] = 1; 50 | for(i=1;i indices; 13 | for(int k = 0; k < n; ++k){ 14 | if(b & (1 << k)){ 15 | // we could work with this values 16 | indices.push_back(k); 17 | } 18 | } 19 | int cardinality = intersectionCardinality(indices); // intersections 20 | if(indices.size() % 2 == 1) result += cardinality; 21 | else result -= cardinality; 22 | } 23 | cout << result << endl; //printing the final result 24 | -------------------------------------------------------------------------------- /Source/Computetional Geometry/Covex Hull (Graham Scan) .cpp: -------------------------------------------------------------------------------- 1 | 2 | /// *** Convex Hull[Grahams Scan] [nlog(n)] 3 | 4 | #define ll long long 5 | struct point{ 6 | ll x,y; 7 | }convex_points[MX],points[MX];; 8 | 9 | /// global scope decraltion of min-left point of collcetion 10 | point pivot; 11 | 12 | ///Distance calculation mathod 13 | ll dist(point p1,point p2){ 14 | return ((p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y)); 15 | } 16 | 17 | /** 18 | * https://www.geeksforgeeks.org/orientation-3-ordered-points/ 19 | * calculating orientation based on slope (yi-yj)/(xi-xj) 20 | * by compering slope of p-q and q-r; 21 | * if p-q0) return 1; 30 | return 2; 31 | } 32 | 33 | /** 34 | * sorting by polor angle in counterclockwise order around point0. 35 | * If polor angle of two points is same, then put the nearest point first. 36 | */ 37 | bool cmp(point p1,point p2){ 38 | ll o = orientation(pivot,p1,p2); 39 | if(o==0){ 40 | return dist(pivot,p1) < dist(pivot,p2); 41 | } 42 | return (o==2); 43 | } 44 | 45 | /// returning previous value of top element 46 | inline point nextToTop(stack&st){ 47 | point p,res; 48 | p = st.top(); 49 | st.pop(); 50 | res = st.top(); 51 | st.push(p); 52 | return res; 53 | } 54 | 55 | int total; 56 | 57 | /** 58 | * This function will calculate convexHull points 59 | * All arrays are in 0 based indexing 60 | * @param n total numbers of points 61 | */ 62 | bool convexHull(int n){ 63 | ll i,pos=0,in=0,miny = points[0].y,minx = points[0].x; 64 | stackst; 65 | 66 | /// Finding bottom-left most point 67 | for(i=0;ipoints[i].x)||miny>points[i].y){ 69 | minx = points[i].x; 70 | miny = points[i].y; 71 | pos = i; 72 | } 73 | } 74 | 75 | ///sorting element according to the criteria 76 | swap(points[0],points[pos]); 77 | pivot = points[0]; 78 | sort(points+1,points+n,cmp); 79 | 80 | ///Now removing same angle point 81 | for(i=1;i0) return 1; 36 | return 2; 37 | } 38 | 39 | /** 40 | * sorting by polor angle in counterclockwise order around point0. 41 | * If polor angle of two points is same, then put the nearest point first. 42 | */ 43 | bool cmp(point p1,point p2){ 44 | ll o = orientation(pivot,p1,p2); 45 | if(o==0){ 46 | return dist(pivot,p1) < dist(pivot,p2); 47 | } 48 | return (o==2); 49 | } 50 | 51 | /// returning previous value of top element 52 | inline point nextToTop(stack&st){ 53 | point p,res; 54 | p = st.top(); 55 | st.pop(); 56 | res = st.top(); 57 | st.push(p); 58 | return res; 59 | } 60 | 61 | int total; 62 | 63 | /** 64 | * This function will calculate convexHull points 65 | * All arrays are in 0 based indexing 66 | * @param n total numbers of points 67 | */ 68 | double convexHull(int n) 69 | { 70 | vector hull; 71 | int l = 0; 72 | for (int i = 1; i < n; i++) 73 | if (points[i].x < points[l].x) 74 | l = i; 75 | int p = l, q; 76 | do 77 | { 78 | hull.push_back(points[p]); 79 | q = (p+1)%n; 80 | for (int i = 0; i < n; i++) 81 | { 82 | if (orientation(points[p], points[i], points[q]) == 2) 83 | q = i; 84 | } 85 | 86 | p = q; 87 | 88 | } while (p != l); 89 | double ans = distd(hull[0],hull[hull.size()-1]); 90 | for (int i = 0; i 7 | using namespace std; 8 | //0 Indexed 9 | #define MX 10000 10 | int spt[MX][22]; 11 | int n,ar[MX]={ 7, 2, 3, 0, 5, 10, 3, 12, 18 }; 12 | void buildST() 13 | { 14 | for (int i = 0; i < n; i++) spt[i][0] = ar[i]; 15 | 16 | for (int j = 1; (1 << j) <= n; j++) { 17 | for (int i = 0; (i + (1 << j) - 1) < n; i++) { 18 | spt[i][j] = min(spt[i + (1 << (j - 1))][j - 1] , spt[i][j - 1]); 19 | } 20 | } 21 | } 22 | 23 | int query(int l, int r) 24 | { 25 | if(l>r) return INT_MAX; 26 | int j = (int)log2(r - l + 1); 27 | ///j = 31 - __builtin_clz(r - l+1); 28 | return min (spt[l][j], spt[r - (1 << j) + 1][j]); 29 | } 30 | 31 | // Driver program 32 | int main() 33 | { 34 | 35 | n = 9; 36 | buildST(); 37 | cout << query(4, 7) << endl; 38 | cout << query(7, 8) << endl; 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Source/Data Structure/Trie Pointer.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | Name : Trie with Dynamic memory 3 | Time complexity : o((number of words)*(maximum lenght)) 4 | */ 5 | 6 | 7 | /// Trie form shafaetsplanet 8 | struct node { 9 | bool endmark; 10 | node* next[26 + 1]; 11 | node() 12 | { 13 | endmark = false; 14 | for (int i = 0; i < 26; i++) 15 | next[i] = NULL; 16 | } 17 | } * root; 18 | void insert(char* str, int len) 19 | { 20 | node* curr = root; 21 | for (int i = 0; i < len; i++) { 22 | int id = str[i] - 'a'; 23 | if (curr->next[id] == NULL) 24 | curr->next[id] = new node(); 25 | curr = curr->next[id]; 26 | } 27 | curr->endmark = true; 28 | } 29 | bool search(char* str, int len) 30 | { 31 | node* curr = root; 32 | for (int i = 0; i < len; i++) { 33 | int id = str[i] - 'a'; 34 | if (curr->next[id] == NULL) 35 | return false; 36 | curr = curr->next[id]; 37 | } 38 | return curr->endmark; 39 | } 40 | void del(node* cur) 41 | { 42 | for (int i = 0; i < 26; i++) 43 | if (cur->next[i]) 44 | del(cur->next[i]); 45 | 46 | delete (cur); 47 | } 48 | int main() 49 | { 50 | puts("ENTER NUMBER OF WORDS"); 51 | root = new node(); 52 | int num_word; 53 | cin >> num_word; 54 | for (int i = 1; i <= num_word; i++) { 55 | char str[50]; 56 | scanf("%s", str); 57 | insert(str, strlen(str)); 58 | } 59 | puts("ENTER NUMBER OF QUERY";); 60 | int query; 61 | cin >> query; 62 | for (int i = 1; i <= query; i++) { 63 | char str[50]; 64 | scanf("%s", str); 65 | if (search(str, strlen(str))) 66 | puts("FOUND"); 67 | else 68 | puts("NOT FOUND"); 69 | } 70 | del(root); 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /Source/Data Structure/binary indexed tree.cpp: -------------------------------------------------------------------------------- 1 | 2 | /// *** BIT O(Log(n)) space O(n) 3 | 4 | /** 1 based index 5 | * which functions has inverse function that can be solve bye BIT 6 | * it works like consucative sums but in log(n) 7 | */ 8 | 9 | int n=SIZE; //of space; 10 | void update(int idx,int val)//adding value val to idx index 11 | { 12 | while(idx<=n){ 13 | bitree[idx]+=val; 14 | idx+=idx&(-idx); // Last set of digit 15 | } 16 | } 17 | int query(int idx){// returns sum of [1,idx] index 18 | int sum=0; 19 | while(idx>0){ 20 | sum+=bitree[idx]; 21 | idx-=idx&(-idx); 22 | } 23 | return sum; 24 | } 25 | -------------------------------------------------------------------------------- /Source/Data Structure/disjoint set.cpp: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | Name : Disjoint set union find 4 | Description : Always check parent for size or anything 5 | Complexity : O(n) ~ O(log n) ~ O(1) 6 | */ 7 | 8 | #define MX 10000 9 | int rp[MX],sz[MX]; 10 | 11 | int parent(int n){ 12 | if(rp[n]==n)return n; 13 | return rp[n]=parent(rp[n]); 14 | } 15 | 16 | void setUp(int a,int b){ 17 | a = parent(a); 18 | b = parent(b); 19 | if(a==b) return; 20 | if(sz[a] 0; --i) tr[i] = tr[i<<1] + tr[i<<1|1]; 12 | } 13 | 14 | void modify(int p, int value) { // set value at position p 15 | for (tr[p += n] = value; p > 1; p >>= 1) tr[p>>1] = tr[p] + tr[p^1]; 16 | } 17 | 18 | int query(int l, int r) { // sum on interval [l, r) 19 | int res = 0; 20 | for (l += n, r += n; l < r; l >>= 1, r >>= 1) { 21 | if (l&1) res += tr[l++]; 22 | if (r&1) res += tr[--r]; 23 | } 24 | return res; 25 | } 26 | 27 | int main() { 28 | //scanf("%d", &n); 29 | int ar[]={1,3,4,5,4,5,6,4,6,4,5,6,6,5}; 30 | n=5; 31 | for (int i = 0; i < n; ++i) { 32 | tr[n+i]=ar[i]; 33 | } 34 | build(); 35 | printf("%d\n", query(0, 4));//that means [0,3] 36 | printf("%d\n", query(2, 3)); 37 | modify(0, 5); 38 | printf("%d\n", query(0, 4)); 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Source/Data Structure/maximum_subsegment_sum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Name : Maximum subsegment sum 3 | * Description: Segment Tree with custom merge function. . 4 | * Usage: construct O(N), query O(lg(N)), update O(lg(N)) 5 | * Source: https://github.com/dragonslayerx 6 | */ 7 | 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | #define MAX 50100 13 | #define INF -1000000000 14 | 15 | struct node { 16 | int sum; 17 | int maxs, prefix, suffix; 18 | node(){ 19 | sum = prefix = suffix = 0; 20 | maxs = INF; 21 | } 22 | 23 | node(int sum, int maxs, int prefix, int suffix) { 24 | setNode(sum, maxs, prefix, suffix); 25 | } 26 | 27 | void setNode(int sum, int maxs, int prefix, int suffix){ 28 | this->sum =sum; 29 | this->maxs=maxs; 30 | this->prefix=prefix; 31 | this->suffix=suffix; 32 | } 33 | }; 34 | 35 | int a[MAX]; 36 | node st[4*MAX]; 37 | 38 | node merge(node left, node right){ 39 | node t; 40 | t.prefix = max(left.prefix, left.sum+right.prefix); 41 | t.suffix = max(right.suffix, right.sum+left.suffix); 42 | t.sum = left.sum+right.sum; 43 | t.maxs = left.maxs; 44 | t.maxs = max(t.maxs, right.maxs); 45 | t.maxs = max(t.maxs, left.suffix+right.prefix); 46 | return t; 47 | } 48 | 49 | node construct(int n, int ll, int rl){ 50 | if (ll == rl) { 51 | st[n].setNode(a[ll], a[ll], a[ll], a[ll]); 52 | } else { 53 | node left = construct(2*n+1, ll, (ll+rl)/2); 54 | node right = construct(2*n+2, (ll+rl)/2+1, rl); 55 | st[n] = merge(left, right); 56 | } 57 | return st[n]; 58 | } 59 | 60 | node query(int n, int ll, int rl, int x, int y){ 61 | int mid = (ll+rl)/2; 62 | if (x==ll && y==rl) return st[n]; 63 | else if (y <= mid) return query(2*n+1, ll, mid, x, y); 64 | else if (x > mid) return query(2*n+2, mid+1, rl, x, y); 65 | else { 66 | node left = query(2*n+1, ll, (ll+rl)/2, x, mid); 67 | node right = query(2*n+2, (ll+rl)/2+1, rl, mid+1, y); 68 | return merge(left, right); 69 | } 70 | } 71 | 72 | node update(int n, int ll, int rl, int p, int val){ 73 | if (p < ll || p > rl) return st[n]; 74 | if (p == ll && p == rl) { 75 | st[n].setNode(val, val, val, val); 76 | return st[n]; 77 | } else { 78 | int mid = (ll+rl)/2; 79 | node left = update(2*n+1, ll, (ll+rl)/2, p, val); 80 | node right = update(2*n+2, (ll+rl)/2+1, rl, p, val); 81 | st[n] = merge(left, right); 82 | } 83 | return st[n]; 84 | } 85 | 86 | int main() 87 | { 88 | int n; 89 | scanf("%d", &n); 90 | for (int i = 0; i < n; i++) scanf("%d", a+i); 91 | construct(0, 0, n-1); 92 | int q; 93 | scanf("%d", &q); 94 | while (q--) { 95 | int x, y; 96 | scanf("%d%d", &x, &y); 97 | x--, y--; 98 | printf("%d\n", query(0, 0, n-1, x, y).maxs); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /Source/Data Structure/merge sort tree.cpp: -------------------------------------------------------------------------------- 1 | /// *** Merge Sort Tree [nlog(n) + query*log(n)*log(n)] 2 | 3 | 4 | int ara[MX]; 5 | vectorseg[MX*4]; 6 | /// 1 based index 7 | 8 | int bns(int n,int val){ 9 | /// lower bound 1 2 2 2 3 4 10 | /// then returns 2 11 | int mid,i,j,low=0,high = seg[n].size()-1; 12 | while((high-low)>4){ 13 | mid = (low+high)/2; 14 | if(seg[n][mid]<=val) low = mid; 15 | else high = mid - 1; 16 | } 17 | for(low;low<=high&&lowval) break; 19 | } 20 | return seg[n].size()-low; /// numbers greater than value 21 | } 22 | 23 | void mergee(int x,int y,int z){ /// merging 2 vector x and y to Z in sorted order 24 | int i,j,k,md,sz; 25 | sz = seg[x].size() + seg[y].size(); 26 | for(i=0,j=0,k=0;k=seg[x].size()) seg[z].push_back(seg[y][j++]); 28 | else if(j>=seg[y].size()) seg[z].push_back(seg[x][i++]); 29 | else if(seg[x][i]qhigh) return 0; 53 | if(qlow>high||qhigh=high){ 55 | return bns(pos,val); 56 | } 57 | int mid = (low + high)/2; 58 | return query(low,mid,qlow,qhigh,pos*2,val) + query(mid+1,high,qlow,qhigh,pos*2+1,val); 59 | } 60 | 61 | /// *** For Rnage orders statistics (find k'th number in sorted segment) 62 | 63 | vectorinput; 64 | vectorseg[MX*4]; 65 | 66 | void creat(int low,int high,int pos){ /// creating merge sort tree 67 | if(low==high){ 68 | seg[pos].push_back(input[low-1].second); /// in is 0 based 69 | return ; 70 | } 71 | int mid = (low+high)/2; 72 | creat(low,mid,pos*2); 73 | creat(mid+1,high,pos*2+1); 74 | mergee(pos*2,pos*2+1,pos); 75 | } 76 | 77 | /** calculating total number in left range lower than the given index 78 | * if numbers are greater than equals to the searging value than look into left 79 | * searhing on right sub array and substracting left sub arrys given up values 80 | */ 81 | 82 | int query(int low,int high,int qlow,int qhigh,int pos,int val) 83 | { 84 | if(low==high) return seg[pos][0]; 85 | int mid = (low+high)>>1,left=pos<<1; 86 | 87 | int total = upper_bound(seg[left].begin(),seg[left].end(),qhigh) - 88 | lower_bound(seg[left].begin(),seg[left].end(),qlow); 89 | 90 | if(total>=val){ 91 | return query(low,mid,qlow,qhigh,pos*2,val); 92 | } 93 | else{ 94 | return query(mid+1,high,qlow,qhigh,pos*2+1,val-total); 95 | } 96 | } 97 | 98 | sort(input.begin(),input.end()); 99 | 100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /Source/Data Structure/segmet tree.cpp: -------------------------------------------------------------------------------- 1 | /// *** Segment Tree [log(total array size)*Query] 2 | 3 | /** [ulow,uhigh] Query Range 4 | * [low,high] total range of root 5 | * [qlow,qhigh] Query Range 6 | * Currrent position = pos 7 | * 0 based Index And Root is also 0 8 | */ 9 | 10 | int ara[MX],seg[4*MX],lazy[4*MX]; 11 | 12 | void creat(int low,int high,int pos) 13 | { 14 | if(low==high){ 15 | seg[pos] = ara[low]; // reached leaf and update 16 | return ; 17 | } 18 | int mid = (high+low)/2; 19 | creat(low,mid,pos*2+1); 20 | creat(mid+1,high,pos*2+2); 21 | seg[pos] += seg[pos*2+1] + seg[pos*2+2]; 22 | } 23 | 24 | void update(int low,int high,int ulow,int uhigh,int val,int pos) 25 | { 26 | if(low>high) return ; 27 | if(lazy[pos]!=0){ /// is not propagated yet 28 | seg[pos] += (high-low+1)*lazy[pos]; 29 | if(low!=high){ ///if not leaf node 30 | lazy[pos*2+1] += lazy[pos]; 31 | lazy[pos*2+2] += lazy[pos]; 32 | } 33 | lazy[pos] = 0; 34 | } 35 | 36 | if(ulow>high||uhigh=high){ /// Total Overlap 38 | seg[pos] += (high-low+1)*val; 39 | if(low!=high){ 40 | lazy[pos*2+1] += val; 41 | lazy[pos*2+2] += val; 42 | } 43 | return; 44 | } 45 | /// Partial overlap 46 | int mid = (high+low)/2; 47 | 48 | update(low,mid,ulow,uhigh,val,pos*2+1); 49 | update(mid+1,high,ulow,uhigh,val,pos*2+2); 50 | seg[pos] = seg[pos*2+1] + seg[pos*2+2]; /// Updating the intermediate node 51 | } 52 | 53 | int query(int low,int high,int qlow,int qhigh,int pos) 54 | { 55 | if(low>high) return 0; 56 | if(lazy[pos]!=0){ 57 | seg[pos] += (high-low+1)*lazy[pos]; 58 | if(low!=high){ 59 | lazy[pos*2+1] += lazy[pos]; 60 | lazy[pos*2+2] += lazy[pos]; 61 | } 62 | lazy[pos] = 0; 63 | } 64 | 65 | if(qlow>high||qhigh=high) 68 | return seg[pos]; 69 | 70 | int mid = (high+low)/2; 71 | 72 | return query(low,mid,qlow,qhigh,pos*2+1) + query(mid+1,high,qlow,qhigh,pos*2+2); 73 | } 74 | 75 | -------------------------------------------------------------------------------- /Source/Data Structure/squre root decmp.cpp: -------------------------------------------------------------------------------- 1 | 2 | /// *** Squre Root Decomposition [Sqrt(n)*Query] 3 | 4 | /** 1 based indexing 5 | * if index are 1 2 3 4 5 6 7 and block size is 3 then 6 | * 1 2 is first block and 3 4 5 is in second block 7 | * this will reduce coding complexity 8 | */ 9 | 10 | int ara[MX],block[sqqrt(MX)],rt,in=0; 11 | 12 | void update(){ 13 | /// point update is simple 14 | /// segment update is like query 15 | } 16 | 17 | void creat(int n){ 18 | in=0; 19 | int mn = INT_MAX,i; 20 | for(i=1;i=ln){ 16 | if(sum%n==0&&mult%n==0) return 1; 17 | else return 0; 18 | } 19 | if(dp[pos][lst][sum][mult]!=-1) 20 | return dp[pos][lst][sum][mult]; 21 | int x=0,y; 22 | for(int i=0; i<=9; i++){ 23 | if(lst){ 24 | y = st[pos]-'0'; 25 | if(i>y) break; 26 | x += bct(pos+1,i==y,(sum+i)%n,(mult*10+i)%n); 27 | } 28 | else{ 29 | x += bct(pos+1,0,(sum+i)%n,(mult*10+i)%n); 30 | } 31 | } 32 | return dp[pos][lst][sum][mult] = x; 33 | } 34 | -------------------------------------------------------------------------------- /Source/Flow and matching/Biparite Matching.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | Name : Bipartite Matching 3 | Description : Find maximum matching. we can find bipartite graph from left or right array 4 | lt = left, rt =right, ed = adjesency matrix 5 | left and right graph can contains nodes with same same or number 6 | Time Complexity : O(EV) 7 | Some Properties : 8 | * in a graph if we push both side then number of pair is ceil(Bipartite/2) 9 | * A graph is bipartite, if it doesn't contain any odd cycle. 10 | 0. V = A u B 11 | 1. Konigs minimax: In a bipartite graph v = t and a = p 12 | 2. Hall's theorem: G has a matching from A to B, iif, for all X (subset of A), |adj(X)| >= |X| 13 | 3. The Marriage Theorem: A perfect match exist iff, it has a matching from A to B and |A| = |B| 14 | 4. Dilworth Theorem: For a finite partially ordered poset S, 15 | the largest antichain is equal to the minimum chain partition and vice versa. 16 | Consider a bipartite graph built this way, A = S, B = S and and edge from x(A) to y(B) exists if x <= y. 17 | Let, c be the minimum chain partition. Then, v + c = n. 18 | */ 19 | 20 | 21 | #define MX 55 22 | vectored[MX]; 23 | int lt[MX],rt[MX]; 24 | bool vs[MX]; 25 | 26 | bool bpm(int u){ 27 | int i,v; 28 | for(i=0;i> capacity; 14 | vector> adj; 15 | 16 | int bfs(int s, int t, vector& parent) { 17 | fill(parent.begin(), parent.end(), -1); 18 | parent[s] = -2; 19 | queue> q; 20 | q.push({s, INF}); 21 | 22 | while (!q.empty()) { 23 | int cur = q.front().first; 24 | int flow = q.front().second; 25 | q.pop(); 26 | 27 | for (int next : adj[cur]) { 28 | if (parent[next] == -1 && capacity[cur][next]) { 29 | parent[next] = cur; 30 | int new_flow = min(flow, capacity[cur][next]); 31 | if (next == t) 32 | return new_flow; 33 | q.push({next, new_flow}); 34 | } 35 | } 36 | } 37 | 38 | return 0; 39 | } 40 | 41 | int maxflow(int s, int t) { 42 | int flow = 0; 43 | vector parent(n); 44 | int new_flow; 45 | 46 | while (new_flow = bfs(s, t, parent)) { 47 | flow += new_flow; 48 | int cur = t; 49 | while (cur != s) { 50 | int prev = parent[cur]; 51 | capacity[prev][cur] -= new_flow; 52 | capacity[cur][prev] += new_flow; 53 | cur = prev; 54 | } 55 | } 56 | 57 | return flow; 58 | } 59 | -------------------------------------------------------------------------------- /Source/Flow and matching/flow dinic.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | Name : Flow Dinic 3 | Time Complexity : O(V^2*E) 4 | Use : if u to v have mutiple path dont add path multiple time. 5 | just add the path cost to capacity matrix 6 | * reverse edge must be push. if unidirectional graph then push reverse edge 7 | seting the reverse edge capacity zero 8 | */ 9 | 10 | 11 | typedef pair pii; 12 | vectoradj[MAX]; 13 | int cap[MAX][MAX]; 14 | 15 | int q[100000]; 16 | bool fl[MAX][MAX]; // u theke v te path ase kina 17 | 18 | /** 19 | n = number of nodes 20 | s = starting node 21 | t = destination node 22 | returns maximum flow 23 | */ 24 | 25 | int dinic( int n,int s,int t ) { 26 | int prev[MAX], u, v, i, z, flow = 0, qh, qt, inc; 27 | while(1) { 28 | memset( prev, -1, sizeof( prev ) ); 29 | qh = qt = 0; 30 | prev[s] = -2; 31 | q[qt++] = s; 32 | while( qt != qh && prev[t] == -1 ) { 33 | u = q[qh++]; 34 | for(i = 0; i < adj[u].size(); i++) { 35 | v = adj[u][i]; 36 | if( prev[v] == -1 && cap[u][v] ) { 37 | prev[v] = u; 38 | q[qt++] = v; 39 | } 40 | } 41 | } 42 | if(prev[t] == -1) break; 43 | for(z = 1; z <= n; z++) if( prev[z] !=- 1 && cap[z][t] ) { 44 | inc = cap[z][t]; 45 | for( v = z, u = prev[v]; u >= 0; v = u, u=prev[v]) inc = min( inc, cap[u][v] ); 46 | if( !inc ) continue; 47 | cap[z][t] -= inc; 48 | cap[t][z] += inc; 49 | for(v=z, u = prev[v]; u >= 0; v = u, u = prev[v]) { 50 | cap[u][v] -= inc; 51 | cap[v][u] += inc; 52 | } 53 | flow += inc; 54 | } 55 | } 56 | return flow; 57 | } 58 | 59 | 60 | scanf("%d %d %d %d",&n,&s,&t,&c); 61 | CLR(cap); 62 | CLR(adj); 63 | CLR(fl); 64 | for(i=1;i<=c;i++){ 65 | scanf("%d %d %d",&u,&v,&x); 66 | if(!fl[u][v]){ 67 | adj[u].push_back(v); 68 | adj[v].push_back(u); 69 | fl[u][v] = fl[v][u]; 70 | } 71 | cap[u][v] += x; 72 | cap[v][u] += x; 73 | } 74 | printf("Case %d: %d\n",cas,dinic(n,s,t)); 75 | -------------------------------------------------------------------------------- /Source/Graph/2-Sat.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | Name : 2SAT problem 3 | */ 4 | 5 | #include 6 | using namespace std; 7 | typedef long long ll; 8 | typedef long double ld; 9 | typedef unsigned long long ull; 10 | typedef pair pii; 11 | typedef vector vi; 12 | typedef vector vll; 13 | #define ntm(i, n) for(int i = 0; i<(n); ++i) 14 | #define rep(i, a, b) for(int i = a; i<(b); ++i) 15 | #define all(x) (x).begin(),(x).end() 16 | #define trav(x, v) for(auto &x : (v)) 17 | #define sz(x) (int)(x).size() 18 | #define mp(a, b) make_pair(a, b) 19 | #define X first 20 | #define Y second 21 | #define pb(x) push_back(x) 22 | #define PS(x) cout << " " << (x) 23 | #define P1(x) cout << (x) << endl 24 | #define P2(x,y) cout << (x) << " " << (y) << endl 25 | #define P3(x,y,z) cout << (x) << " " << (y) << " " << (z) << endl 26 | #define SQR(x) ((x)*(x)) 27 | #define CUBE(x) ((x)*(x)*(x)) 28 | #define PF(x, y) fixed << setprecision(y) << x 29 | 30 | using namespace std; 31 | 32 | struct TwoSat { 33 | int N; 34 | vector gr; 35 | vi values; // 0 = false , 1 = true 36 | TwoSat(int n = 0) : N(n), gr(2*n) {} 37 | int add_var() { 38 | gr.emplace_back(); 39 | gr.emplace_back(); 40 | return N++; 41 | } 42 | void either(int f, int j) { 43 | f = max(2*f, -1-2*f); 44 | j = max(2*j, -1-2*j); 45 | //P3("either: ", f, j); 46 | gr[f^1].push_back(j); 47 | gr[j^1].push_back(f); 48 | } 49 | void set_value(int x) { either(x, x); } 50 | void at_most_one(const vi& li) { 51 | if (sz(li) <= 1) return; 52 | int cur = ~li[0]; 53 | rep(i,2,sz(li)) { 54 | int next = add_var(); 55 | either(cur, ~li[i]); 56 | either(cur, next); 57 | either(~li[i], next); 58 | cur = ~next; 59 | } 60 | either(cur, ~li[1]); 61 | } 62 | vi val, comp, z; int time = 0; 63 | int dfs(int i) { 64 | int low = val[i] = ++time, x; z.push_back(i); 65 | trav(e, gr[i]) if (!comp[e]) 66 | low = min(low, val[e] ?: dfs(e)); 67 | ++time; 68 | if (low == val[i]) do { 69 | x = z.back(); z.pop_back(); 70 | comp[x] = time; 71 | if (values[x>>1] == -1) 72 | values[x>>1] = !(x&1); 73 | } while (x != i); 74 | return val[i] = low; 75 | } 76 | bool solve() { 77 | values.assign(N, -1); 78 | val.assign(2*N, 0); comp = val; 79 | rep(i,0,2*N) if (!comp[i]) dfs(i); 80 | rep(i,0,N) if (comp[2*i] == comp[2*i+1]) return 0; 81 | return 1; 82 | } 83 | }; 84 | -------------------------------------------------------------------------------- /Source/Graph/Articulation Bridge.cpp: -------------------------------------------------------------------------------- 1 | 2 | /// ****Articulation Bridge **** 3 | /// O(E+V) 4 | /// bridges are stored on artqb vector 5 | 6 | #define MX 10005 7 | vectored[MX], artqb[MX]; 8 | int vs[MX],dt[MX],low[MX],pr[MX],discovery_time,root; 9 | 10 | void articulation_bridge(int n){ 11 | int i,v; 12 | vs[n] = 1; 13 | dt[n] = low[n] = ++discovery_time; 14 | for(i=0;ied[MX]; 10 | int vs[MX],dt[MX],points[MX],low[MX],pr[MX],discovery_time,root; 11 | 12 | void articulation_point(int n){ 13 | int i,v,cn=0; 14 | vs[n] = 1; 15 | dt[n] = low[n] = ++discovery_time; 16 | for(i=0;i1&&n==root) points[n]=1; 36 | } 37 | 38 | void free(){ 39 | for(int i=0;i> adj; // graph represented as an adjacency list 7 | int n; // number of vertices 8 | 9 | vector color; 10 | 11 | vector time_in, time_out; 12 | int dfs_timer = 0; 13 | 14 | void dfs(int v) { 15 | time_in[v] = dfs_timer++; 16 | color[v] = 1; 17 | for (int u : adj[v]) 18 | if (color[u] == 0) 19 | dfs(u); 20 | color[v] = 2; 21 | time_out[v] = dfs_timer++; 22 | } 23 | -------------------------------------------------------------------------------- /Source/Graph/Stable Marriage.cpp: -------------------------------------------------------------------------------- 1 | //// O(n*n) 2 | 3 | int womens_priority[MX][MX],married[MX],couple[MX]; 4 | queuemens_priority[MX]; 5 | 6 | void free(){ 7 | for(int i=0;i>ts; 19 | while(++cas<=ts){ 20 | scanf("%d",&n); 21 | free(); 22 | //womens 23 | for(i=1;i<=n;i++){ 24 | for(j=1;j<=n;j++){ 25 | scanf("%d",&x); 26 | womens_priority[i][x] = n-j; 27 | } 28 | } 29 | //mens 30 | for(i=1;i<=n;i++){ 31 | for(j=1;j<=n;j++){ 32 | scanf("%d",&x); 33 | mens_priority[n+i].push(x); 34 | } 35 | } 36 | cn=0; 37 | while(cn!=n){ 38 | for(i=n+1;i<=2*n;i++){ 39 | if(!married[i]){ 40 | x = mens_priority[i].front(); 41 | mens_priority[i].pop(); 42 | married[i] = 1; 43 | if(couple[x]==0) { 44 | couple[x] = i,cn++; 45 | } 46 | else{ 47 | if(womens_priority[x][couple[x]]mtx[i][k]+mtx[k][j]){ 29 | mtx[i][j]>mtx[i][k]+mtx[k][j]; 30 | next[i][j]=next[i][k];//for finding path only 31 | } 32 | } 33 | } 34 | } 35 | } 36 | //finding path using warshal, i to j 37 | vector path; 38 | void findpath(int i,int j) 39 | { 40 | path.clear(); 41 | path.push_back(i); 42 | while(i!=j){ 43 | i=next[i][j]; 44 | path.push_back(i); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Source/Graph/bfs in 2d.cpp: -------------------------------------------------------------------------------- 1 | /// *** BFS in 2D Grid [edge + node] 2 | 3 | int lev[MX][MX],m,n; 4 | bool vs[MX][MX]; 5 | char st[MX][MX]; 6 | int dx[]={1,-1,0, 0, 1,1,}; 7 | int dy[]={0, 0,1,-1,-1, }; 8 | 9 | int bfs(int fx,int fy) /// starting position 10 | { 11 | int i,v,x,y,md=0; 12 | queue q; 13 | pii pr; 14 | vs[fx][fy]=1; 15 | lev[fx][fy]=0; 16 | q.push(pii(fx,fy)); 17 | while(!q.empty()){ 18 | pr=q.front(); 19 | fx=pr.first; 20 | fy=pr.second; 21 | q.pop(); 22 | for(i=0;i<4;i++){ 23 | x=fx+dx[i]; 24 | y=fy+dy[i]; 25 | if(x<0||x>=n||y<0||y>=m)continue; /// for zero based index 26 | if(!vs[x][y]&&st[x][y]!='#'){ /// # is blocked 27 | q.push(pii(x,y)); 28 | vs[x][y]=1; 29 | lev[x][y]=lev[fx][fy]+1; 30 | if(st[x][y]=='d'){ /// d is destinition 31 | md=max(md,lev[x][y]); 32 | } 33 | 34 | } 35 | } 36 | 37 | } 38 | return md;/// max distance of d 39 | 40 | } 41 | 42 | -------------------------------------------------------------------------------- /Source/Graph/bfs.cpp: -------------------------------------------------------------------------------- 1 | /// *** BFS [ total(node + edge) ] 2 | /// level by level travarse 3 | 4 | vector ed[MX]; 5 | int lev[MX],ms,par[MX]; 6 | bool vs[MX]; 7 | int bfs(int s){ 8 | int i,j,d,f,v; 9 | queue q; 10 | q.push(s); 11 | lev[s]=0; 12 | vs[s]=1; 13 | while(!q.empty()){ 14 | f=q.front(); 15 | q.pop(); 16 | for(i=0;ied[MX]; 4 | bool vs[MX]; 5 | int lev[MX]; 6 | 7 | void dfs(int n) 8 | { 9 | if(vs[n]) return; 10 | vs[n] = 1; 11 | int i,v; 12 | for(i=0;ix.cost; 13 | } 14 | }; 15 | 16 | vector ed[MX],ec[MX]; 17 | int ds[MX]; 18 | void dxt(int s){ 19 | priority_queue q; 20 | q.push(node(s,0)); 21 | ds[s]=0; 22 | node fn; 23 | int i,u,v; 24 | while(!q.empty()){ 25 | fn=q.top(); 26 | q.pop(); 27 | u=fn.id; 28 | if(fn.cost!=ds[u])continue; 29 | for(i=0;ids[u]+ec[u][i]){ 32 | ds[v]=ds[u]+ec[u][i]; 33 | q.push(node(v,ds[v])); 34 | } 35 | } 36 | } 37 | } 38 | 39 | -------------------------------------------------------------------------------- /Source/Graph/minimum spannig tree (Kruskal).cpp: -------------------------------------------------------------------------------- 1 | /// *** Minimum Spanning Tree :: Kruskal [mlogm+m] 2 | 3 | struct edge{ 4 | int u,v,w; 5 | bool operator < (const edge& x)const { 6 | return w>x.w; 7 | } 8 | }ab; 9 | 10 | int ara[105],n; 11 | vectorvc; 12 | /// vc.push_back(ab) make edge and push 13 | 14 | int find(int n){ 15 | if(ara[n] == n) return n; 16 | return ara[n] = find(ara[n]); 17 | } 18 | 19 | int mst() 20 | { 21 | int sum=0,i,u,v,cn=0,mn=INT_MAX; 22 | for(i=0;i<=102;i++) ara[i] = i; 23 | sort(vc.begin(),vc.end()); 24 | for(i=0;i 6 | using namespace std; 7 | #define LL long long 8 | #define EPS 0.00000001 9 | #define PI 2*acos(0.0) 10 | #define MOD 1000000007 11 | #define ck(XX) cout<=0 && X=0 && Y B.cost;} 30 | 31 | 32 | int node, edge; //Total number of node and edge 33 | int sow; //Sum Of Weight of MST 34 | bool taken[100]; 35 | vector adj[100]; //For storing given graph data 36 | vector tree[100]; //For creating new minimum spanning tree 37 | 38 | 39 | void PMST(int source) 40 | { 41 | sow = 0; 42 | MS(taken,0); 43 | 44 | priority_queue Q; 45 | taken[source] = 1; 46 | for(int i=0; i pr; 10 | 11 | void sieve(){ 12 | int i,j; 13 | for (i=2; i<=N; ++i) { 14 | if (lp[i] == 0) { 15 | lp[i] = i; 16 | pr.push_back (i); 17 | } 18 | for (j=0; j<(int)pr.size() && pr[j]<=lp[i] && i*pr[j]<=N; ++j) 19 | lp[i*pr[j]] = pr[j]; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Source/Number Theory/Sum of divisor.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Name : SOD 3 | * Description : Find sum of divisor of a given number 4 | * σ(n)=(p1^(e1+1)-1)/(p1−1) * (p2^(e2+1)−1)/(p2−1)***(pk^(ek+1)−1)(pk−1) 5 | * Complexity : O(sqrt(n)) , Squre root porjnto jotogula prime ase 6 | * Use : store prime up to squreroot(n) by efficient sieve, in = number of prime 7 | */ 8 | 9 | 10 | ll SOD(ll n){ 11 | ll i,cnt,sum=1,tmp,B; 12 | for(i=1;i<=in&&pr[i]*pr[i]<=n;i++){ 13 | cnt=0; 14 | while(n%pr[i]==0){ 15 | cnt++; 16 | n /= pr[i]; 17 | } 18 | tmp = pr[i]; 19 | if(cnt){ 20 | sum *= ((bgM(tmp,cnt+1)-1+MD)%MD)*(modi(tmp-1))%MD; 21 | } 22 | sum = sum%MD; 23 | } 24 | tmp = n; 25 | if(n>1){ 26 | sum *= ((bgM(tmp,2)-1+MD)%MD)*(modi(tmp-1))%MD; 27 | sum = sum%MD; 28 | } 29 | return sum; 30 | } 31 | -------------------------------------------------------------------------------- /Source/Number Theory/bitwise_sieve.cpp: -------------------------------------------------------------------------------- 1 | 2 | /// *** BitwiseSieve [~ n log(n) may be ] 3 | /// [It can be use for finding huge number of primes]~10^8 4 | 5 | #define check(X) (mkr[X>>6]&(1<<((X&63)>>1))) 6 | #define mark(X) mkr[X>>6]|=(1<<((X&63)>>1)) 7 | int mkr[10000900/64],SZ=10000020,pr[700000],in=0; 8 | 9 | void bitwsiv() 10 | { 11 | int i,j,rt=sqrt(SZ)+1; 12 | for(i=3; i<=rt; i+=2){ 13 | if(!check(i)){ 14 | for(j=i*i; j<=SZ; j+=i+i){ 15 | mark(j); 16 | } 17 | } 18 | } 19 | pr[++in]=2; 20 | for(i=3; i<=SZ; i+=2){ 21 | if(!check(i))pr[++in]=i; 22 | } 23 | } 24 | 25 | -------------------------------------------------------------------------------- /Source/Number Theory/eulers totient sieve.cpp: -------------------------------------------------------------------------------- 1 | /// ***Eulers totients Sieve [n*n] 2 | /// Number of Co-prime upto a number 3 | 4 | bool mr[MX]; 5 | int pi[MX]; 6 | 7 | void phi(){ 8 | int i,j; 9 | pi[1] = 1; 10 | for(i=2;iabs(ara[l][i])){ 11 | l = j; 12 | } 13 | } 14 | if(i!=l){ 15 | for(j=0;j<=n;j++){ 16 | swap(ara[i][j], ara[l][j]); 17 | } 18 | } 19 | for(j=0;j 0){ 11 | if (b&1) x = (x + y) % mod; 12 | y = (y<<1) % mod; 13 | b >>= 1; 14 | } 15 | return x % mod; 16 | } 17 | 18 | //Bigmod 19 | ll modulo(ll n, ll r, ll mod){ 20 | ll x = 1; 21 | while (r > 0){ 22 | if (r&1) x = mulmod(x,n,mod); 23 | n = mulmod(n,n,mod); 24 | r >>= 1; 25 | } 26 | return x % mod; 27 | } 28 | /// higher value of "it" ensure higher percision [recomendation 7] 29 | 30 | bool MillerRabin(ll p,int it) 31 | { 32 | if (p < 2) return 0; 33 | if (p != 2 && p % 2==0) return 0; 34 | 35 | ll i,a,tmp,mod,s=p-1; 36 | 37 | while(s%2==0){ 38 | s>>=1; 39 | } 40 | for(i=0;i 13 | pii extnuc(ll a,ll b) 14 | { 15 | if(b==0)return pii(1,0); 16 | pii d=extnuc(b,a%b); 17 | return pii(d.second,d.first-d.second*(a/b)); 18 | } 19 | 20 | ll modi(ll n) /// n must be moded value 21 | { 22 | pii d=extnuc(n,M); 23 | return ((d.first%M)+M)%M; 24 | } 25 | 26 | ///Now factorial & inverse factorial with MOD 27 | void fact() 28 | { 29 | ll i; 30 | fr[0]=fi[0]=1; 31 | for(i=1;i<2000007;i++){ 32 | fr[i]=(fr[i-1]*i)%M; 33 | fi[i]=(fi[i-1]*modi(i))%M; 34 | //P(fr[i]) 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /Source/Number Theory/number of divisor in qube root.cpp: -------------------------------------------------------------------------------- 1 | 2 | /// ***Number of divisors [Quberoot(n)] 3 | 4 | /** There can be only two prime after qube root 5 | * so we factorize upto quberoot by the trial divison then 6 | * handle ramainig <=2 prime 7 | * Miller Rabin needed 8 | */ 9 | 10 | ll NOD(ll n){ 11 | ll i,j,r,nod=1,cn; 12 | for(i=1;i<=in&&(pr[i]*pr[i]*pr[i])<=n;i++){ 13 | cn = 1; 14 | while(n%pr[i]==0){ 15 | n /= pr[i]; 16 | cn++; 17 | } 18 | nod *= cn; 19 | } 20 | 21 | r = sqrtl(n); 22 | while((r+1)*(r+1)<=n) r++; 23 | 24 | if(MillerRabin(n,8)) nod *= 2; 25 | else if(r*r==n&&MillerRabin(r,8)) nod *= 3; 26 | else if(n!=1) nod *= 4; 27 | 28 | return nod; 29 | } 30 | 31 | -------------------------------------------------------------------------------- /Source/Number Theory/number of divisor.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Name : NOD 3 | * Description : Therefore if the prime factorization of n is p1^e1⋅pi2^e2⋯pk^ek, 4 | * where pi are distinct prime numbers, then the number of divisors is: d(n)=(e1+1)⋅(e2+1)⋯(ek+1) 5 | * Complexity : O(sqrt(n)) , Squre root porjnto jotogula prime ase 6 | * Use : store prime up to squreroot(n) by efficient sieve, in = number of prime 7 | */ 8 | 9 | 10 | 11 | ll NOD(ll n){ 12 | ll ans=1,x,count; 13 | for(int i=0; (ll)prime[i] * (ll)prime[i]<=n && i<=in ;i++){ 14 | int( n%prime[i] == 0){ 15 | x=prime[i]; 16 | count =1; 17 | while(n%x==0) { 18 | n/=x; 19 | count++; 20 | } 21 | ans*= count; 22 | } 23 | } 24 | if(n>1) ans*=2; 25 | return ans; 26 | } 27 | 28 | -------------------------------------------------------------------------------- /Source/Number Theory/number of primes.txt: -------------------------------------------------------------------------------- 1 | 2 | /// Number of primes ---> 3 | 4 | 1 10 4 5 | 2 100 25 6 | 3 1,000 168 7 | 4 10,000 1,229 8 | 5 100,000 9,592 9 | 6 1,000,000 78,498 10 | 7 10,000,000 664,579 11 | 8 100,000,000 5,761,455 12 | 9 1,000,000,000 50,847,534 13 | 10 10,000,000,000 455,052,511 14 | 11 100,000,000,000 4,118,054,813 15 | 12 1,000,000,000,000 37,607,912,018 16 | 13 10,000,000,000,000 346,065,536,839 17 | 14 100,000,000,000,000 3,204,941,750,802 18 | 15 1,000,000,000,000,000 29,844,570,422,669 19 | 16 10,000,000,000,000,000 279,238,341,033,925 20 | 17 100,000,000,000,000,000 2,623,557,157,654,233 21 | 18 1,000,000,000,000,000,000 24,739,954,287,740,860 22 | 19 10,000,000,000,000,000,000 234,057,667,276,344,607 23 | 20 100,000,000,000,000,000,000 2,220,819,602,560,918,840 24 | 21 1,000,000,000,000,000,000,000 21,127,269,486,018,731,928 25 | 22 10,000,000,000,000,000,000,000 201,467,286,689,315,906,290 26 | 23 100,000,000,000,000,000,000,000 1,925,320,391,606,803,968,923 27 | 24 1,000,000,000,000,000,000,000,000 18,435,599,767,349,200,867,866 28 | 25 10,000,000,000,000,000,000,000,000 176,846,309,399,143,769,411,680 29 | -------------------------------------------------------------------------------- /Source/Number Theory/prime factorization log(n).cpp: -------------------------------------------------------------------------------- 1 | /** 2 | Description : prime factorization 3 | Complexity : O(log n) 4 | Limitation : memory complexity O(n) so it works up to 10^7 5 | */ 6 | 7 | const int N = 10000000; 8 | int lp[N+1]; 9 | vector pr; 10 | 11 | void sieve(){ 12 | int i,j; 13 | for (i=2; i<=N; ++i) { 14 | if (lp[i] == 0) { 15 | lp[i] = i; 16 | pr.push_back (i); 17 | } 18 | for (j=0; j<(int)pr.size() && pr[j]<=lp[i] && i*pr[j]<=N; ++j) 19 | lp[i*pr[j]] = pr[j]; 20 | } 21 | } 22 | 23 | vector prime_fact(int n){ 24 | vector pf; 25 | while (n != 1){ 26 | pf.push_back(lp[n]); 27 | n = n / lp[n]; 28 | } 29 | return pf; 30 | } 31 | -------------------------------------------------------------------------------- /Source/Number Theory/primeFactorization.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Description : normal prime factorization 3 | * Complexity : O(sqrt(n)) 4 | * Use : store prime up to squreroot(n) by efficient sieve, in = number of prime 5 | */ 6 | 7 | 8 | void primeFactorization(ll n){ 9 | ll i,cn=0; 10 | for(i=1; i <= in && (ll)pr[i]*(ll)pr[i] <= n; i++){ 11 | cn = 0; 12 | while(n%pr[i] == 0){ 13 | n /= pr[i]; 14 | cn++; 15 | } 16 | // cn is the prime power 17 | } 18 | if(n>1) // then n is a prime 19 | } 20 | -------------------------------------------------------------------------------- /Source/Number Theory/segmented_sieve.cpp: -------------------------------------------------------------------------------- 1 | 2 | /// *** Segmented Sieve O( sqrt(up) + prime sieve ) 3 | 4 | /** [l = lower limit, u = upper limit] 5 | * [first generate all prime upto sqrt(upper limit)] 6 | * [Checking prime 7 | * n = number into that segment] 8 | * if(!mark[n-l]) then it is prime 9 | */ 10 | bool mark[u-l]; 11 | void segsiv(ll l, ll u) 12 | { 13 | ll i,j,lt; 14 | if(l==1) mark[0] = 1; 15 | for(i=1; i<=in&&pr[i]*pr[i]<=u; i++){ 16 | lt = l/pr[i]; 17 | lt *= pr[i]; 18 | if(lt 1) 18 | result -= result / n; 19 | return result; 20 | } 21 | -------------------------------------------------------------------------------- /Source/STL/STL.md: -------------------------------------------------------------------------------- 1 | ## STL : 2 | * **Multiset** 3 | * `multiset > set1;` empty multiset container greater for descending order 4 | * `set1.insert(40);` insert elements in random order 5 | * `set1.erase(set1.begin(), set1.find(40));` remove all elements up to element with value 40 in set1 6 | * `int num = set1.erase(50);` remove all elements with value 50 in set2 || num = number of element 50 removed 7 | * `set1.clear();` clear all elements 8 | * `set1.find(20);` Returns iterator to 20 if found else returns end() 9 | * `set1.count(const g) ` Returns the number of matches to element ‘g’ in the multiset. 10 | * `set1.rbegin()` Returns a reverse iterator pointing to the last element in the multiset container. 11 | * `multiset > :: iterator itr;` iterator is normal like others iterators 12 | * `multiset set2(set1.begin(), set1.end());` assigning the elements from set1 to set2 13 | * `multiset::swap()` This function is used to exchange the contents of two multisets but the sets must be of same type, although sizes may differ. 14 | * lower bound and upper bound for multiset set1 15 | * `*set1.lower_bound() << endl;` 16 | * `*set1.upper_bound() << endl;` 17 | -------------------------------------------------------------------------------- /Source/Sorting/Bubble Sort.cpp: -------------------------------------------------------------------------------- 1 | /// *** Bubble sort [n*n] 2 | 3 | void bubbleSort(ll ara[],ll n){ 4 | ll i,j; 5 | for(i = 1; i <= n; i++){ 6 | for(j = 1; j < n-i; j++){ 7 | if(ara[j+1] < ara[j]){ 8 | swap(ara[j+1],ara[j]); 9 | } 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /Source/Sorting/Insertion Sort.cpp: -------------------------------------------------------------------------------- 1 | 2 | /// *** Insertion Sort [n*n] 3 | 4 | void insertionSort(ll ara[],ll n){ 5 | ll i,j,tmp; 6 | for(i = 1; i<=n; i++){ 7 | tmp = ara[i]; 8 | j = i-1; 9 | while(j >= 1 && ara[j] > tmp){ 10 | ara[j+1] = ara[j]; 11 | j--; 12 | } 13 | ara[j+1] = tmp; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Source/Sorting/Merge Sort.cpp: -------------------------------------------------------------------------------- 1 | /// *** merge sort [nlog(n)] 2 | 3 | #define MX 1000000 4 | 5 | ll tmp[MX]; 6 | 7 | void mergeSort(ll ara[],ll l,ll r){ 8 | if(l==r) return; 9 | ll i,j,k,md; 10 | md = (l+r)/2; 11 | mergeSort(ara,l,md); 12 | mergeSort(ara,md+1,r); 13 | for(i=l,j=md+1,k=l;k<=r;k++){ 14 | if(i>md) tmp[k] = ara[j++]; 15 | else if(j>r) tmp[k] = ara[i++]; 16 | else if(ara[i]=hi) return; 17 | ll pivot = partition(ara,lw,hi); 18 | Quicksort(ara,lw,pivot-1); 19 | Quicksort(ara,pivot+1,hi); 20 | } -------------------------------------------------------------------------------- /Source/Sorting/Selection Sort.cpp: -------------------------------------------------------------------------------- 1 | 2 | /// *** Selection sort [n*n] 3 | 4 | void selectionSort(ll ara[],ll n){ 5 | for(int i = 1; i<=n; i++){ 6 | for(int j = i+1; j<=n; j++){ 7 | if(ara[i]>ara[j]){ 8 | swap(ara[i],ara[j]); 9 | } 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /Source/String/KMP.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Nadim-Mahmud/Competitive-Programming/3f88ef395a334e2c8ca450f912f8ebbe1c3dd584/Source/String/KMP.cpp -------------------------------------------------------------------------------- /Source/String/Rabin Carp String Matching.cpp: -------------------------------------------------------------------------------- 1 | 2 | /// **** Rabin-Karp 3 | 4 | #define MD 1000000009 5 | using namespace std; 6 | 7 | ll pm=31,powr[MX],hs[MX]; 8 | 9 | void powCalc(){ 10 | powr[0] = 1; 11 | for(int i=1;i ans; 17 | 18 | void rabin_karp(char txt[],char ptt[]){ 19 | int P = strlen(ptt),T=strlen(txt),i,crr; 20 | 21 | memset(hs,0,sizeof hs); 22 | 23 | for(i=0; i 1 anana 12 | 3 ana alphabetically 0 banana 13 | 4 na 4 na 14 | 5 a 2 nana 15 | So the suffix array for "banana" is {5, 3, 1, 0, 4, 2} 16 | 17 | Uses : 18 | 19 | * number of uniqe substring of a string : n(n+1)/2 − ∑ lcp[i] (summation of all lcp is duplicate string as lcp means longest match with the prev string) 20 | * longest common substring by sliding window (add special character and joint all strings then calculate lcp and by sliding window we can determine the longest substring) 21 | * longest repeated substring : maximum value of lcp is longest repeated substring, number of the maximum number is the longest repeated substring is the longest repeated substring 22 | * Finding a substring in a string : by binary search on the lcp array 23 | */ 24 | 25 | #define MX 10005 26 | 27 | int sfa[10009],pos[10009],tmp[10009],lcp[10009],gap=1,ln; 28 | char ss[10009]; 29 | bool scmp(int a,int b) 30 | { 31 | if(pos[a]!=pos[b])return pos[a]b; 35 | 36 | } 37 | void buildsa() 38 | { 39 | int i,j; 40 | ln=strlen(ss); 41 | for(i=0;i<=ln;i++){ 42 | sfa[i]=i; 43 | pos[i]=ss[i]; 44 | } 45 | for(gap=1;;gap*=2){ 46 | sort(sfa,sfa+ln,scmp); 47 | for(i=0;i 2 | #define ll long long 3 | #define P(X) cout<<"db "< 9 | #define chk(n,i) (bool)(n&(1<g[MX]; 27 | 28 | int sz[MX]; 29 | void getsz(int v, int p){ 30 | sz[v] = 1; // every vertex has itself in its subtree 31 | for(auto u : g[v]) 32 | if(u != p){ 33 | getsz(u, v); 34 | sz[v] += sz[u]; // add size of child u to its parent(v) 35 | } 36 | } 37 | 38 | ll cnt[MX],col[MX],ans[MX],res[MX],mxn; 39 | bool big[MX]; 40 | 41 | void add(int v, int p, int x){ 42 | //ans[cnt[col[v]]] -= col[v]; 43 | cnt[col[v]] += x; 44 | //ans[cnt[col[v]]] += col[v]; 45 | //mxn = max(cnt[col[v]],mxn); 46 | for(auto u: g[v]) 47 | if(u != p && !big[u]) 48 | add(u, v, x); 49 | } 50 | 51 | 52 | void dfs(int v, int p, bool keep){ 53 | int mx = -1, bigChild = -1; 54 | for(auto u : g[v]) 55 | if(u != p && sz[u] > mx) 56 | mx = sz[u], bigChild = u; 57 | //run a dfs on small childs and clear them from cnt 58 | for(auto u : g[v]) 59 | if(u != p && u != bigChild) 60 | dfs(u, v, 0); // 61 | // actual processing of vertex v starts from here 62 | //mxn = 0; 63 | if(bigChild != -1) 64 | dfs(bigChild, v, 1), big[bigChild] = 1; // bigChild marked as big and not cleared from cnt 65 | // calculating ans 66 | add(v, p, 1); 67 | //res[v] = ans[mxn]; 68 | /** here access the result for each node. if needed then access on add() function 69 | now cnt[c] is the number of vertices in subtree of vertex v that has color c. 70 | You can answer the queries easily. 71 | */ 72 | if(bigChild != -1) 73 | big[bigChild] = 0; 74 | if(keep == 0) 75 | add(v, p, -1); 76 | } 77 | 78 | 79 | 80 | int main() 81 | { 82 | ll i,j,a,b,ts,cn=0,cas=0,n,m,x,y,sum=0,mn=INT_MAX,u,v; 83 | //freopen("test.txt","r",stdin); 84 | cin>>n; 85 | for(int i = 1; i <= n; i++) { 86 | cin >> col[i]; 87 | } 88 | for(i=1;i>u>>v; 90 | g[u].push_back(v); 91 | g[v].push_back(u); 92 | } 93 | getsz(1,0); 94 | dfs(1,0,1); 95 | for(int i = 1; i <= n; i++) { 96 | cout << res[i] << ' '; 97 | } 98 | return 0; 99 | } 100 | -------------------------------------------------------------------------------- /Source/Trees/HLD Anudeep blog Style.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | Descripton : 3 | Source :https://blog.anudeep2011.com/heavy-light-decomposition/ 4 | */ 5 | 6 | 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | #define root 0 12 | #define N 10100 13 | #define LN 14 14 | 15 | vector adj[N], costs[N], indexx[N]; 16 | int baseArray[N], ptr; 17 | int chainNo, chainInd[N], chainHead[N], posInBase[N]; 18 | int depth[N], pa[LN][N], otherEnd[N], subsize[N]; 19 | int st[N*6], qt[N*6]; 20 | 21 | /* 22 | * make_tree: 23 | * Used to construct the segment tree. It uses the baseArray for construction 24 | */ 25 | void make_tree(int cur, int s, int e) { 26 | if(s == e-1) { 27 | st[cur] = baseArray[s]; 28 | return; 29 | } 30 | int c1 = (cur<<1), c2 = c1 | 1, m = (s+e)>>1; 31 | make_tree(c1, s, m); 32 | make_tree(c2, 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 | update_tree(c1, s, m, x, val); 48 | update_tree(c2, m, e, x, val); 49 | st[cur] = st[c1] > st[c2] ? st[c1] : st[c2]; 50 | } 51 | 52 | /* 53 | * query_tree: 54 | * Given S and E, it will return the maximum value in the range [S,E) 55 | */ 56 | void query_tree(int cur, int s, int e, int S, int E) { 57 | if(s >= E || e <= S) { 58 | qt[cur] = -1; 59 | return; 60 | } 61 | if(s >= S && e <= E) { 62 | qt[cur] = st[cur]; 63 | return; 64 | } 65 | int c1 = (cur<<1), c2 = c1 | 1, m = (s+e)>>1; 66 | query_tree(c1, s, m, S, E); 67 | query_tree(c2, m, e, S, E); 68 | qt[cur] = qt[c1] > qt[c2] ? qt[c1] : qt[c2]; 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 | 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 | 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; // Assign chain head 153 | } 154 | chainInd[curNode] = chainNo; 155 | posInBase[curNode] = ptr; // Position of this node in baseArray which we will use in Segtree 156 | baseArray[ptr++] = cost; 157 | 158 | int sc = -1, ncost; 159 | // Loop to find special child 160 | for(int i=0; i