{"id":21477726,"url":"https://github.com/debarghya4469/algorithm-lib","last_synced_at":"2026-03-19T20:33:52.479Z","repository":{"id":41473825,"uuid":"395934944","full_name":"DEBARGHYA4469/algorithm-lib","owner":"DEBARGHYA4469","description":"Notes for algorithmic techniques used in competitive programming: .dev","archived":false,"fork":false,"pushed_at":"2024-12-17T15:39:51.000Z","size":1103,"stargazers_count":2,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-01-23T17:55:18.806Z","etag":null,"topics":["codechef","codeforces-problems","competitive-coding"],"latest_commit_sha":null,"homepage":"https://debarghya4469.github.io/algorithm-lib/","language":"HTML","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/DEBARGHYA4469.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-08-14T07:55:22.000Z","updated_at":"2024-12-17T15:39:55.000Z","dependencies_parsed_at":"2023-09-26T04:52:15.390Z","dependency_job_id":"33c95134-6857-4426-9fc3-7cfc9a20df51","html_url":"https://github.com/DEBARGHYA4469/algorithm-lib","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DEBARGHYA4469%2Falgorithm-lib","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DEBARGHYA4469%2Falgorithm-lib/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DEBARGHYA4469%2Falgorithm-lib/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DEBARGHYA4469%2Falgorithm-lib/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/DEBARGHYA4469","download_url":"https://codeload.github.com/DEBARGHYA4469/algorithm-lib/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243997170,"owners_count":20380981,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["codechef","codeforces-problems","competitive-coding"],"created_at":"2024-11-23T11:14:53.859Z","updated_at":"2026-01-03T08:05:01.400Z","avatar_url":"https://github.com/DEBARGHYA4469.png","language":"HTML","funding_links":[],"categories":[],"sub_categories":[],"readme":"# CP Hack Tools\r\n\r\n\u003cdetails markdown=\"1\"\u003e \r\n\u003csummary\u003e My Programming Template\r\n\u003c/summary\u003e\r\n\r\n```cpp\r\n#include \u003cext/pb_ds/assoc_container.hpp\u003e\r\n#include \u003cbits/stdc++.h\u003e\r\n\r\n#define eb emplace_back\r\n#define fi first \r\n#define se second \r\n#define mp make_pair\r\n#define mt make_tuple\r\n#define tm ((tl+tr)\u003e\u003e1)\r\n#define INF (1\u003c\u003c62)\r\n#define endl \"\\n\"\r\n#define mem(v,w) memset(v,w,sizeof(v))\r\n#define sz(v) v.size()\r\n#define all(v) v.begin(),v.end()\r\n#define rall(v) v.rbegin(),v.rend()\r\n#define ub upper_bound\r\n#define lb lower_bound\r\n#define vi vector\u003cint\u003e\r\n#define si stack\u003cint\u003e\r\n#define vvi vector\u003cvector\u003cint\u003e\u003e\r\n#define setbits(v) __builtin_popcount(v)\r\n#define setbitsll(v) __builtin_popcountll(v)\r\n#define nth_element(s,n) *(s.find_by_order(n-1)) \r\n#define count_smaller(s,n) s.order_of_key(n)  \r\n#define raffle_draw(l,r) uniform_int_distribution\u003cint\u003e(l,r)(prng)\r\n#define log(...) cerr \u003c\u003c __LINE__ \u003c\u003c \": \"; logger(#__VA_ARGS__,__VA_ARGS__)\r\n\r\nusing namespace std;\r\nusing namespace __gnu_pbds;\r\n\r\ntypedef long long ll;\r\ntypedef unsigned long long ull;\r\ntypedef pair\u003cint,int\u003e pii;\r\ntypedef pair\u003cll,ll\u003e pll;\r\ntypedef tree\u003cint, null_type, less\u003cint\u003e, rb_tree_tag, tree_order_statistics_node_update\u003e ordered_set; //pbds\r\n\r\ntemplate \u003cclass T,class U\u003e bool chmin(T \u0026x, U y){ if(x\u003ey){ x=y; return true; } return false; }\r\ntemplate \u003cclass T,class U\u003e bool chmax(T \u0026x, U y){ if(x\u003cy){ x=y; return true; } return false; }\r\n\r\nmt19937 prng(chrono::steady_clock::now().time_since_epoch().count()); // mersenne twister\r\nconst long double pi = acos(-1.0);\r\nconst int mod = 1e9+7;\r\n\r\n/* logging utitlies */\r\ntemplate\u003ctypename ...Args\u003e\r\nvoid logger(string vars, Args\u0026\u0026... values){\r\n\tcerr \u003c\u003c \"[\";\r\n\tcerr \u003c\u003c vars \u003c\u003c \"] = \";\r\n\tstring delimeter = \"\";\r\n\tcerr \u003c\u003c \"[\";\r\n\t\t(..., (cerr \u003c\u003c  delimeter \u003c\u003c values, delimeter=\",\"));\r\n\tcerr \u003c\u003c \"]\\n\";\r\n}\r\n\r\n/* i/o stream utilities */\r\nostream\u0026 operator \u003c\u003c(ostream\u0026 out, pair\u003cint,int\u003e const\u0026 v){\r\n    out \u003c\u003c v.fi \u003c\u003c \",\" \u003c\u003c v.se; \r\n    return out; \r\n}\r\n\r\ntemplate\u003ctypename T\u003e\r\nostream\u0026 operator \u003c\u003c(ostream\u0026 out, const vector\u003cT\u003e\u0026 v){\r\n    for (const T\u0026 x: v) out \u003c\u003c x \u003c\u003c \" \"; \r\n    return out; \r\n}\r\n\r\ntemplate\u003ctypename T, typename S\u003e\r\nostream\u0026 operator \u003c\u003c(ostream\u0026 out, const map\u003cT,S\u003e\u0026 v){\r\n    for (auto\u0026 x: v) out \u003c\u003c x.fi \u003c\u003c \"--\u003e\" \u003c\u003c x.se; \r\n    return out; \r\n}\r\n\r\ntemplate\u003ctypename T\u003e\r\nostream\u0026 operator \u003c\u003c(ostream\u0026 out, const set\u003cT\u003e\u0026 v){\r\n    for (auto\u0026 x: v) cout \u003c\u003c x \u003c\u003c \" \";\r\n    return out;\r\n}\r\n\r\ntemplate\u003ctypename T\u003e\r\nostream\u0026 operator \u003c\u003c(ostream\u0026 out, const multiset\u003cT\u003e\u0026 v){\r\n    for (auto\u0026 x: v) cout \u003c\u003c x \u003c\u003c \" \";\r\n    return out;\r\n}\r\n\r\n/* adhoc utilities */  \r\ninline ll ceil_divide(ll a,ll b){   return (a+b-1)/b; }\t\r\n\r\ntemplate \u003cclass T\u003e\r\nvoid remove_duplicates(vector\u003cT\u003e \u0026v){ sort(all(v)); v.erase(unique(all(v)),v.end());}\r\n\r\nstring to_binary(ll v){\r\n    if(!v) return \"0\";\r\n    string s=\"\";\r\n    while (v\u003e0){\r\n        s += static_cast\u003cchar\u003e(v%2 + '0');\r\n        v/=2;\r\n    }\r\n    reverse(all(s));\r\n    return s; \r\n    \r\n}\r\n\r\nint main(){\r\n\t\r\n\tstd::ios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n\r\n\t#ifdef _INPUT\r\n\tfreopen(\"input.txt\", \"r\", stdin);\r\n\t#endif \r\n\r\n\treturn 0;\r\n}\r\n```\r\n\r\n\u003c/details\u003e\r\n\r\n\r\n\r\n\u003cdetails markdown=\"1\"\u003e\r\n\u003csummary\u003eStress Test PY Template\r\n\u003c/summary\u003e\r\n\r\n```py\r\nimport filecmp\r\nimport os\r\nimport random\r\nimport sys\r\nimport subprocess\r\n\r\nmy_solution = sys.argv[1]\r\ntest_solution = sys.argv[2]\r\n\r\nmy_solution_exe = my_solution.split(\".cpp\")[0]\r\ntest_solution_exe = test_solution.split(\".cpp\")[0]\r\n\r\ninput_file = \"in.txt\"\r\nmy_solution_out = \"out1.txt\"\r\ntest_solution_out = \"out2.txt\"\r\n\r\ndef generate_input_file():\r\n    '''\r\n    Write code here to generate the input file\r\n    Tips:\r\n        1. Use random.randint(l,r) : to generate random number between l...r\r\n        2. Perm = list(range(1,n)) random.shuffle(Perm) : to generate a randome permutation\r\n    '''\r\n    with open (input_file, \"w\") as f:\r\n        N = 10\r\n        M = 3\r\n        f.write(f\"{N} {M}\\n\")\r\n        for i in range(M):\r\n            K = random.randint(1,N) \r\n            C = random.randint(1,100)\r\n            f.write (f\"{K} {C}\")\r\n            f.write (\"\\n\")\r\n            \r\n            lst = list(range(1,N+1))\r\n            random.shuffle(lst)\r\n            lst = lst [0:K]\r\n            for j in lst:\r\n                f.write (f\"{j} \")\r\n\r\n            f.write(\"\\n\")\r\n    \r\ndef test_case(i):\r\n    u  = generate_input_file()\r\n    os.system(f\"./{my_solution_exe} \u003c {input_file} \u003e {my_solution_out}\")\r\n    os.system(f\"./{test_solution_exe} \u003c {input_file} \u003e {test_solution_out}\")\r\n\r\n    with open(my_solution_out, \"r\") as f:\r\n        a = f.readline()\r\n        a.rstrip()\r\n\r\n    with open(test_solution_out, \"r\") as f:\r\n        b = f.readline()\r\n        b.rstrip()\r\n\r\n    if a == b:\r\n        print(f\"Test {i} passed.\")\r\n    else:\r\n        print(\"ERROR, match out1.txt and out2.txt.\")\r\n        sys.exit(0)\r\n\r\ndef run_commands(cmd):\r\n    print(cmd)\r\n    try:\r\n        cmd = cmd.split(\" \")\r\n        subprocess.run(cmd, check=True)\r\n    except subprocess.CalledProcessError as e:\r\n        print (\"Error:\", e)\r\n\r\ndef compile_command(cpp_file):\r\n    compilation_flags = \"-std=c++17\"\r\n    exe_name = cpp_file.split(\".cpp\")[0]\r\n    return f\"g++ {compilation_flags} -o {exe_name} {cpp_file}\"\r\n\r\nif __name__ == '__main__':\r\n\r\n    run_commands(compile_command(my_solution))\r\n    run_commands(compile_command(test_solution))\r\n\r\n    for i in range(1,100):\r\n        test_case(i)\r\n```\r\n\u003c/details\u003e\r\n\r\n---\r\n\r\n\u003cdetails markdown=\"1\"\u003e\r\n\u003csummary\u003eCombinatorics Template\r\n\u003c/summary\u003e\r\n\r\n\r\n```cpp\r\ninline int mul(int x,int y){    ll z = 1ll; z=z*x*y;   z%=mod; return (int)z; }\r\ninline int add(int x,int y){    ll z = 0ll; z=z+x+y;   z%=mod; return (int)z; }\r\ninline int sub(int x,int y){    ll z=0ll;   z=x+mod-y; z%=mod; return (int)z; }\r\n\r\ninline int binpow(int x,int y){\r\n\r\n    ll z = 1ll;\r\n    while(y){\r\n        if(y\u00261) z=mul(z,x);\r\n        x = mul(x,x);\r\n        y\u003e\u003e=1;\r\n    }\r\n    return (int)z;\r\n}\r\n\r\ninline int inv(int x){ return binpow(x,mod-2); }\r\n\r\nconst int N = 400004;\r\nint fac[N], rfac[N];\r\nvoid fasetup(){\r\n\tfac[0] = rfac[0] = 1;\r\n\tfor(int i=1;i\u003cN;i++) fac[i] = mul(fac[i-1],i);\r\n\trfac[N-1] = inv(fac[N-1]);\r\n\tfor(int i=N-2;i\u003e0;i--) rfac[i] = mul(rfac[i+1], i+1);\r\n} \r\n\r\nint choose(int n,int r){\r\n\tassert(n\u003e=r);\r\n\treturn mul(fac[n], mul(rfac[r],rfac[n-r])); \r\n}\r\n```\r\n\u003c/details\u003e\r\n\r\n\u003cdetails markdown=\"1\"\u003e\r\n\u003csummary\u003e Fenwick Tree Template\r\n\u003c/summary\u003e\r\n\r\n\r\n```cpp\r\nvoid update (int i, int val) {\r\n    for (; i \u003c N ; i+= i\u0026-i) Fen[i] = max (Fen[i], val); \r\n}\r\nint query (int r) {\r\n    int Ans = 0; \r\n    for (; r \u003e 0 ; r -= r\u0026-r) Ans = max (Ans, Fen[r]);\r\n    return Ans; \r\n}   \r\n\r\nvoid cleanTree (int i) {\r\n    for (; i\u003cN; i += i\u0026-i) Fen[i] = 0; \r\n}\r\n```\r\n\u003c/details\u003e\r\n\r\n\u003cdetails markdown=\"1\"\u003e  \r\n\u003csummary\u003e Number Theory Template \r\n\u003c/summary\u003e\r\n\r\n```cpp\r\nvector\u003cint\u003e p; \r\nint sieve [MAXN]; \r\nauto sievef = [\u0026] (int MAXN) -\u003e void {\r\n    sieve[1] = 1;\r\n    for (int i = 2; i \u003c MAXN; i++){\r\n        if (sieve[i]) continue;\r\n        p.emplace_back (i); \r\n        for (int j = i; j \u003c MAXN; j += i){\r\n            if (!sieve[j]) sieve [j] = i; \r\n        }\r\n    }\r\n};\r\n\r\nauto factor = [\u0026](int n) -\u003e vector\u003cpii\u003e {\r\n    vector\u003cpii\u003e res;\r\n    for (int \u0026x : p){\r\n        if (x * x \u003e n) break;\r\n        else if (n % x) continue;\r\n        res.emplace_back (x, 0); \r\n        while (n % x == 0) {\r\n            res.back().se++; \r\n            n /= x; \r\n        } \r\n    }\r\n    if (n \u003e 1) res.emplace_back (n, 1); \r\n    return res; \r\n};\r\n\r\nvi divisors (int n) {\r\n    vi d = {1};\r\n    while (n \u003e 1){\r\n        int m = 0;\r\n        int q = sieve[n];\r\n        while (n % q == 0) { m++; n /= q; }\r\n        int dsize = d.size();\r\n        int pw = q; \r\n        for (int i = 0;i \u003c m; i++) {\r\n            for (int j = 0; j \u003c dsize; j++) d.emplace_back (d[j] * pw);\r\n            pw *= q;\r\n        } \r\n    }\r\n    return d; \r\n} \r\n\r\n```\r\n\r\n\u003c/details\u003e\r\n\t\r\n\t\r\n\r\n\u003cdetails markdown=\"1\"\u003e\r\n\u003csummary\u003eDisjoint Set Template\r\n\u003c/summary\u003e\r\n\t\r\n```cpp\r\n/* Usage: DSU S(n); S.unite (1, 2); S.totalSize(2); */\r\n\r\nstruct DSU {\r\n\tvector \u003cint\u003e par, size_;\r\n\tint biggest; \r\n\tDSU (int n) : par (n+1), size_(n+1, 1), biggest(1) { \r\n\t\tfor (int i=0;i\u003c=n;i++) par[i] = i;\r\n\t}\r\n\tint root (int u) {\r\n\t\tif (par[u] == u) return u; \r\n\t\treturn par[u] = root (par[u]);\r\n\t}\r\n\tvoid unite (int u, int v){\r\n\t\tint ru = root(u), rv = root(v); \r\n\t\tif (ru == rv) return; \r\n\t\tif (rand() \u0026 1) swap (u, v); \r\n\t\tsize_[rv] += size_[ru];\r\n\t\tpar[ru] = rv;\r\n\t\tchmax (biggest, size_[rv]); \t\r\n\t}\r\n\r\n\tint totalSize (int u) {\r\n\t\treturn size_[root(u)]; \r\n\t} \r\n};\r\n```\r\n\r\n\u003c/details\u003e\r\n\r\n\u003cdetails markdown=\"1\"\u003e\r\n\u003csummary\u003e Segment Tree Template\r\n\u003c/summary\u003e\r\n\r\n```cpp\r\n/* 1-based segment tree template */\r\n// $set : infinite, ST_MAX, Node constructor, combine code\r\n\r\n\r\nconst int ST_MAX = \u003c\u003e;\r\nint _array[ST_MAX];\r\nconst int infinite = \u003c\u003e;\r\n\r\nstruct Node{\r\n    // 0. add node variables and constructors \r\n    // int node_variables;\r\n\tint val;\t\r\n\tNode () {\r\n\t\tval = infinite; \r\n\t} \r\n\tNode (int val) : val (val) {} \r\n};\r\n\r\nint _n; // $ set _n \r\nclass SegmentTree {\r\n    public:\r\n\t\t\r\n        Node *_t;\r\n    public:\r\n        \r\n        SegmentTree (int n) {\r\n            _n = n;\r\n            _t = new Node[_n*6]; \r\n        }\r\n\r\n        Node combine (Node lc, Node rc){\r\n            Node res;\r\n            /* 1. add your combine code along with empty node  */\r\n\t\t\tif (lc.val == infinite) return rc; \r\n\t\t\telse if (rc.val == infinite) return lc; \r\n\t\t\tint va = max (lc.val, rc.val);  \r\n            return Node (va);\r\n        }\r\n\r\n        Node query (const int\u0026 l, const int\u0026 r, int v=1, int tl=1, int tr=_n){\r\n            if (r\u003ctl||l\u003etr) return Node (); \r\n            if (tl\u003e=l \u0026\u0026 tr\u003c=r) return _t[v]; \r\n            return combine (query(l, r, v\u003c\u003c1, tl, tm), \r\n                query(l, r, v\u003c\u003c1|1, tm+1, tr));\r\n        }\r\n\r\n        void build (int v=1, int tl=1, int tr=_n){\r\n            if (tl==tr) _t[v] = Node(_array[tl]); \r\n            else {\r\n                build (v\u003c\u003c1, tl, tm);\r\n                build (v\u003c\u003c1|1, tm+1, tr); \r\n                _t[v] = combine (_t[v\u003c\u003c1], _t[v\u003c\u003c1|1]); \r\n            }\r\n        }\r\n\r\n        // point update \r\n        void update (const int\u0026 pos, const int\u0026 val, int v=1, int tl=1, int tr=_n){\r\n            if (tl==tr) _t[v] = Node(val);  \r\n            else {\r\n                if (pos \u003c= tm) update (pos, val, v\u003c\u003c1, tl, tm);\r\n                else update (pos, val, v\u003c\u003c1|1, tm+1, tr); \r\n                _t[v] = combine (_t[v\u003c\u003c1], _t[v\u003c\u003c1|1]);  \r\n            }\r\n        }\r\n};\r\n/* Segment Tree tested*/\r\n```\r\n\u003c/details\u003e\r\n\r\n\u003cdetails markdown=\"1\"\u003e\r\n\u003csummary\u003e Lazy Propagation Template\r\n\u003c/summary\u003e\r\n\r\n```cpp\r\nstruct Node{\r\n\tunsigned long long Colors;\r\n\tNode () { Colors = 0; }\t\r\n\tNode (unsigned long long tColor) {\r\n\t\tColors = tColor;\r\n\t} \r\n};\r\n \r\nint _n; // $ set _n \r\nclass SegmentTree {\r\n    public:\r\n        Node *_t;\r\n    public:\r\n        \r\n        SegmentTree (int n) {\r\n            _n = n;\r\n            _t = new Node[_n * 6]; \r\n        }\r\n \r\n        Node combine (Node lc, Node rc){\r\n            Node res; \r\n            res.Colors = lc.Colors | rc.Colors;\r\n            return res;\r\n        }\r\n           \r\n        void pushdown(int v){\r\n\t\tlazy[v \u003c\u003c 1] = lazy[v]; \r\n\t\tlazy[v \u003c\u003c 1 | 1] = lazy[v];\r\n\t\t_t[v].Colors = lazy[v];\r\n\t\t_t[v \u003c\u003c 1].Colors = lazy[v];\r\n\t\t_t[v \u003c\u003c 1 | 1].Colors = lazy[v];\r\n\t\tlazy[v] = 0;\r\n\t}\r\n \r\n        Node query (const int\u0026 l, const int\u0026 r, int v = 1, int tl = 1, int tr = _n){\r\n            if (r \u003c tl || l \u003e tr) return Node (); \r\n            if (tl \u003e= l \u0026\u0026 tr \u003c= r) {\r\n            \treturn _t[v];\r\n            } \r\n            if(lazy[v])\r\n            \tpushdown(v);\r\n            \r\n            Node res = combine (query(l, r, v \u003c\u003c 1, tl, tm), \r\n                query(l, r, v \u003c\u003c 1 | 1, tm + 1, tr));\r\n \r\n            return res;\r\n        }\r\n \r\n\tvoid update(int l, int r, int C, int v = 1, int tl = 1, int tr = _n){\t\r\n \r\n\t\tif(l \u003e tr || r \u003c tl) return;\r\n\t\telse if(l \u003c= tl \u0026\u0026 tr \u003c= r) {\r\n\t\t\tlazy[v] = 1LL \u003c\u003c C; \r\n\t\t\t_t[v].Colors = 1LL \u003c\u003c C;\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tif (lazy[v]) \r\n\t\t\tpushdown(v);\r\n\t\t\t\r\n\t\tupdate(l, r, C, v \u003c\u003c 1, tl, tm);\r\n\t\tupdate(l, r, C, v \u003c\u003c 1|1, tm + 1, tr);\r\n\t\t_t[v] = combine (_t[v \u003c\u003c 1], _t[v \u003c\u003c 1 | 1]);\r\n\t}\r\n \r\n        void build (int v=1, int tl=1, int tr=_n){\r\n            if (tl==tr) {\r\n            \t_t[v] = Node(1LL \u003c\u003c Color[to[tl]]); \r\n            }\r\n            else {\r\n                build (v\u003c\u003c1, tl, tm);\r\n                build (v\u003c\u003c1|1, tm+1, tr); \r\n                _t[v] = combine (_t[v\u003c\u003c1], _t[v\u003c\u003c1|1]); \r\n            }\r\n        }\r\n};\r\n```\r\n\u003c/details\u003e\r\n\r\n\u003cdetails markdown=\"1\"\u003e\r\n\u003csummary\u003e Hashing Template \r\n\u003c/summary\u003e\r\n\r\n```cpp\r\nstruct HashInt {\r\n\tstatic const int mx=1e9+7, my=1e9+9;\r\n\tlong long x, y;\r\n\tHashInt () = default;\r\n\tHashInt (long long x_) : x(x_), y(x_) {}\r\n\tHashInt (long long x_, long long y_) : x(x_), y(y_) {}\r\n\tHashInt operator + (const HashInt\u0026 other) const{\r\n\t\tHashInt tmp; \r\n\t\ttmp.x = (x + other.x) % mx;\r\n\t\ttmp.y = (y + other.y) % my;\r\n\t\treturn tmp;\r\n\t}\r\n\tHashInt operator - (const HashInt\u0026 other) const{\r\n\t\tHashInt tmp; \r\n\t\ttmp.x = (mx + x - other.x) % mx;\r\n\t\ttmp.y = (my + y - other.y) % my; \t\t\r\n\t\treturn tmp;\r\n\t}\r\n\tHashInt operator * (const HashInt\u0026 other) const{\r\n\t\tHashInt tmp; \r\n\t\ttmp.x = (x * other.x) % mx;\r\n\t\ttmp.y = (y * other.y) % my; \t\t\r\n\t\treturn tmp;\r\n\t}\r\n\tbool operator == (const HashInt\u0026 other) const{\r\n\t\treturn x == other.x \u0026\u0026 y == other.y;\r\n\t}\r\n\toperator pair\u003clong long ,long long\u003e () const {\r\n\t\treturn make_pair (x, y);\r\n\t}\r\n}; \r\n\r\nnamespace RollHash{\r\n\tconst int P=239017, N_ = 9e5+4;\r\n\tHashInt p[N_], H[N_];\r\n\t\u003calways call init before initializing test cases\u003e \r\n\tvoid init() { \r\n\t\tp[0] = 1;\r\n\t\tfor (int i=1;i\u003cN_;i++){\r\n\t\t\tp[i] = p[i-1] * P; \r\n\t\t}\r\n\t}\r\n\tvoid gen_hashes (const string\u0026 str){\r\n\t\tint n = str.size();\r\n\t\tH[0] = str[0];\r\n\t\tfor (int i=1;i\u003cn;i++){\r\n\t\t\tH[i] = H[i-1] * P + str[i];\r\n\t\t}\r\n\t}\r\n\t\t\r\n\tHashInt hasher (int l, int r) { return l ? H[r] - H[l-1] * p[r-l+1] : H[r]; }\r\n};\r\n\r\nusing namespace RollHash;\r\n```\r\n\u003c/details\u003e\r\n\r\n\r\n\r\n\u003cdetails markdown=\"1\"\u003e\r\n\u003csummary\u003e Sliding Window Template \r\n\u003c/summary\u003e\r\n\r\n```cpp\r\nfor(int l=0,r=-1;l\u003cn;l++){ // left boundary of the sliding window\r\n\tr = max(r, l-1);\r\n\twhile(r+1 \u003c n){\r\n\t\t/* modify the window*/\r\n\t\tif extendible? \r\n\t\t\tr++;\r\n\t\telse \r\n\t\t\t/* rollback window  */ \r\n\t\tbreak;\r\n\r\n\t\tif(chmax(max_length, r-l+1)){\r\n\t\t\t// record answer from window\r\n\t\t}\r\n\t}\r\n\t// modify window to delete left boundary to proceed to the next, l++ happens\r\n}\r\n```\r\n\r\n\u003c/details\u003e\r\n\r\n\u003cdetails markdown=\"1\"\u003e\r\n\u003csummary\u003e MO Query Template \r\n\u003c/summary\u003e\r\n\r\n```cpp\r\nint B; \r\n\r\nstruct Query{\r\n\r\n\tint l, r, idx; \r\n\tpair\u003cint, int\u003e toPair () const {\r\n\t\tint b = l/B; \r\n\t\treturn {b, (b\u00261)?-r:r};\r\n\t}\r\n\tbool operator \u003c (const Query\u0026 other) {\r\n\t\treturn toPair () \u003c other.toPair();\r\n\t}\r\n};\r\n\r\nlong long curr = 0; \r\nvoid add (int); \r\nvoid remove (int);\r\n\r\nvoid solve_offline (vector\u003cQuery\u003e q) {\r\n\tsort (all(q));\r\n\tint currL = 1, currR = 1;\r\n\tadd (arr[1]); \t\r\n\tfor (int Q: q){\r\n\t\tint L,R,idx; \r\n\t\twhile (L \u003c currL) add (arr[--currL]);\t\r\n\t\twhile (R \u003e currR) add (arr[++currR]);\r\n\t\twhile (L \u003e currL) remove (arr[currL++]); \r\n\t\twhile (R \u003c currR) remove (arr[currR--]);\r\n\t\tanswer[idx] = curr;\r\n\t}\r\n} \r\n```\r\n\r\n\u003c/details\u003e\r\n\r\n\r\n\u003cdetails markdown=\"1\"\u003e\r\n\u003csummary\u003e Ordered Set Template \r\n\u003c/summary\u003e\r\n\t\r\n```cpp\r\n\tstruct RBTree { \r\n\ttypedef tree\u003cpii, \r\n\t\t\tnull_type, \r\n\t\t\tless\u003cpii\u003e,\r\n\t\t\trb_tree_tag, \r\n\t\t\ttree_order_statistics_node_update\u003e ord;\r\n\tord s;\r\n\tint _t;\r\n\t\r\n\tRBTree() {  \r\n\t\t_t = 0;\r\n\t}\r\n\tvoid emplace (int x) { s.insert ({x, ++_t});  }\r\n\tvoid erase (int x) { s.erase (s.lower_bound({x, 0})); }\r\n\tint less_than (int x) { return s.order_of_key({x, 0}); }\r\n\tint less_eq (int x) { return s.order_of_key({x+1, 0}); }\r\n\tint find_nth (int n) { \r\n\t\tif (s.find_by_order(n) == s.end()) return -1;\r\n\t\treturn s.find_by_order(n)-\u003efirst;\r\n\t}\r\n};\t\r\n```\r\n\u003c/details\u003e\r\n\r\n\u003cdetails markdown=\"1\"\u003e\r\n\u003csummary\u003e Double Precision Arithmetic\r\n\u003c/summary\u003e\r\n\r\n```cpp\r\nconst double EPS = 1e-9;\r\nbool chequal (double a, double b) {\r\n    return abs (a - b) \u003c EPS; \r\n}\r\n\r\ndouble L2norm (pair\u003cdouble, double\u003e a, pair\u003cdouble, double\u003e b){ \r\n    return sqrt (pow(a.fi - b.fi, 2) + pow(a.se - b.se, 2)); \r\n}\r\n\r\ncout \u003c\u003c setprecision (12) \u003c\u003c fixed; \r\n```\r\n\r\n\u003c/details\u003e\r\n\r\n\u003cdetails markdown=\"1\"\u003e\r\n\u003csummary\u003e Reading Lines of String Template\r\n\u003c/summary\u003e\r\n\r\n```cpp\r\nstring s;\r\ngetline(cin, s);\r\n```\r\n\r\n\u003c/details\u003e\r\n\r\n\r\n### Useful Notes\r\n\r\n---\r\n\r\n\u003cdetails markdown=\"1\"\u003e\r\n\u003csummary\u003eTrees and Graphs (29)\r\n\u003c/summary\u003e\r\n\r\n---\r\n\r\n[1. Cyclicity in undirected graph](graph/graph.md#a)\r\n\r\n[2. Cyclicity in directed graph, coloring technique](graph/graph.md#b)\r\n\r\n[3. All simple cycles in a undirected graph, w/o composite cycles](graph/graph.md#c)\r\n\r\n[4. All tricks using union-find algorithm](graph/graph.md#d)\r\n\r\n[5. Small to Large Trick, Merger Sets, a DSU trick](graph/dsu.md)\r\n\r\n[6. Tarjan's algorithm to find articulation points, bridges](graph/graph.md#e)\r\n\r\n[7. Finding transitive closure of a graph using Floyd Warshall](graph/graph.md#g)\r\n\r\n[8. BFS on complement graph aka Pie for a Pie trick](graph/graph.md#h)\r\n\r\n[9. All topological ordering](graph/graph.md#i)\r\n\r\n[10. Kahn's algorithm for topological ordering](graph/graph.md#j)\r\n\r\n[11. Maximal/Minimal Topological ordering](graph/graph.md#k)\r\n\r\n[12. Floyd Warshall for finding shortest paths](graph/graph.md#l)\r\n\r\n[13. Minimum Spanning Tree, Prim vs Kruskal](graph/graph.md#m)\r\n\r\n[14. Dijkstra's shortest path algoritm for non-negative edges](graph/graph.md#o)\r\n\r\n[15. Kth shortest path and ghostness in dikjstra's algorithm](graph/graph.md#o1)\r\n\r\n[16. Use Bellman Ford for negative edge weights](graph/graph.md#p)\r\n\r\n[17. Detect negative cycle using Bellman Ford](graph/graph.md#q)\r\n\r\n[18. Shortest Cycle in undirected graph using BFS](graph/graph.md#q1)\r\n\r\n[19. 0/1 BFS Trick](graph/graph.md#r)\r\n\r\n[20. Strongly connected component aka SCC](graph/graph.md#s)\r\n\r\n[21. Kosaraju's algorithm for condensed SCC](graph/graph.md#t)\r\n\r\n[22. Finding centeroid a tree, subtree, cut tree](graph/centeroid.md)\r\n\r\n[23. Euler Tour, relation between vertices, propagating tree](graph/euler-tour.md)\r\n\r\n[24. Everything about Trie](graph/trie.md)\r\n\r\n[25. Trie and binary MEX](graph/trie.md)\r\n\r\n[26. Bit prefix Trie and XOR operations](graph/trie.md)\r\n\r\n[27. Games on Trie](graph/trie.md)\r\n\r\n[28. Lazy Propagation in DSU](graph/dsu.md)\r\n\r\n[29. Functional Graphs](graph/functional-graph.md)\r\n\r\n\u003c/details\u003e\r\n\r\n\u003cdetails markdown=\"1\"\u003e\r\n\u003csummary\u003eMathematical Techniques (30)\r\n\u003c/summary\u003e\r\n\r\n---\r\n\t\r\n[1. Custom Ceil Function](math/math.md#a)\r\n\r\n[2. Lazy Caterer](math/math.md#b) \r\n\r\n[3. Chinese Remainder Theorem](math/math.md#c) \r\n\r\n[4. Derangement](math/math.md#d) \r\n\r\n[5. Chicken Mcnugget Theorem](math/math.md#e) \r\n\r\n[6. Erdos Szekeres Theorem](math/math.md#f) \r\n\r\n[7. Cyclicity](math/math.md#g)\r\n\r\n[8. Parity of Permutation](math/math.md#h) \r\n\r\n[9. Rank in Arbitrarty Bases](math/math.md#i) \r\n\r\n[10. Floyd Cycle](math/math.md#j) \r\n\r\n[11. Manhattern Trick](math/math.md#k) \r\n\r\n[12. Complexity of Euclid's dvision Lemma](math/math.md#o)\r\n\r\n[13. Subsequence to Subarray Transformation Trick](math/math.md#l)\r\n\r\n[14. Some properties of sum of absolute differences aka SAD](math/sad.md)\r\n\r\n[15. How to solve diophantine equations](math/diophantine.md#a)\r\n\r\n[16. Gaussian Elimination in GF(2), Max XOR Subsequence](math/gaussian-elimination.md)\r\n\r\n[17. Euclid extended division algorithm for LCM/GCD](math/gcd-lcm.md)\r\n\r\n[18. Catalan Number, Dyck Path](math/combinatorics.md#a)\r\n\r\n[19. Inclusion Exclusion Principle](math/combinatorics.md#b)\r\n\r\n[20. Prime Factorization, Sieve, Divisors of Large numbers](math/prime-factorization.md)\r\n\r\n[21. Minimum Excludent aka MEX](math/mex.md)\r\n\r\n[22. No. of Co-prime pairs](math/cses.md)\r\n\r\n[23. Meet in the Middle aka MiTM](math/cses.md)\r\n\r\n[24. Generating Functions](math/generating_functions.md)\r\n\r\n[25. Difference Array, Sort, Repeat](math/math.md#p)\r\n\r\n[26. Expected Value Problems](math/expected_value.md)\r\n\r\n[27. Hockey Stick Identity](math/math.md#o)\r\n\r\n[28. Catalan Number and problems with producer, consumer](math/math.md#o)\r\n\r\n[29. Stirling Number of Second Kind](math/math.md#s)\r\n\r\n[30. Stars and Bars Method](math/math.md#s)\r\n\r\n\r\n\u003c/details\u003e\r\n\r\n\u003cdetails markdown=\"1\"\u003e\r\n\u003csummary\u003e\r\nGreedy Techniques (21)\r\n\u003c/summary\u003e\r\n\r\n---\r\n\r\n[1. Minimum Increment Decrement to make array equal](greedy/adhoc_greedy.md)\r\n\t\r\n[2. Largest Area in a Histogram using NGE](greedy/adhoc_greedy.md)\r\n\r\n[3. Intermediate Value Property Trick](greedy/adhoc_greedy.md)\r\n\r\n[4. Job Sequencing Problems](greedy/adhoc_greedy.md)\r\n\r\n[5. A Nice Binary Search Trick](greedy/adhoc_greedy.md)\r\n\r\n[6. Find frequency of element in a given range using upperbound, lowerbound](greedy/adhoc_greedy.md)\r\n\r\n[7. All techniques using exchange arguments, powerful proving technique](greedy/exchange-arg.md)\r\n\r\n[8. Invariance and Extremal Ideas](greedy/invariance.md)\r\n\r\n[9. Generic sliding window algorithm](greedy/sliding-window.md)\r\n\r\n[10. Comparing a subarray with a sliding window technique](greedy/sliding-window.md)\r\n\r\n[11. Find closest pair, minimum euclidean distance](greedy/sweepline.md)\r\n\r\n[12. Klee's algorithm for union of intersecting segments](greedy/sweepline.md)\r\n\r\n[13. Intervals and Schedules](greedy/interval.md)\r\n\r\n[14. UpperBound and LowerBound on Tuples](greedy/adhoc_greedy.md)\r\n\r\n[15. Change of slope trick](greedy/adhoc_greedy.md)\r\n\r\n[16. Linear Transformation trick](greedy/adhoc_greedy.md)\r\n\r\n[17. Median Trick](greedy/adhoc_greedy.md)\r\n\r\n[18. Knapsack with weights from a permutation](greedy/adhoc_greedy.md)\r\n\r\n[19. Non-Degenerate Triangles](greedy/adhoc_greedy.md)\r\n\r\n[20. Average Trick](greedy/adhoc_greedy.md)\r\n\r\n[21. Josephus Problem](greedy/adhoc_greedy.md)\r\n\r\n\r\n\u003c/details\u003e\r\n\r\n\r\n\u003cdetails markdown=\"1\"\u003e\r\n\u003csummary\u003eDynamic Programming (19)\r\n\u003c/summary\u003e\r\n\r\n---\r\n\r\n[1. Max Subarray Sum, Kadane's algorithm](dp/adhoc-dp.md)\r\n\r\n[2. Max Subarray Product](dp/adhoc-dp.md)\r\n\r\n[3. All variants of buy-sell share problems](dp/adhoc-dp.md)\r\n\r\n[4. Bitmasking: Assigment Problem](dp/bitmask.md)\r\n\r\n[5. Bitmasking: Held Karp for TSP like problem](dp/bitmask.md)\r\n\r\n[6. Masking over Primes](dp/bitmask.md)\r\n\r\n[7. Enumerating submasks](dp/bitmask.md)\r\n\r\n[8. Profile DP, DP on broken pipes](dp/bitmask.md)\r\n\r\n[9. All tricks in digit DP problems, including LCM trick, pair of numbers](dp/digit-dp.md)\r\n\r\n[10. Divisibility problems using DP](dp/divisibility.md)\r\n\r\n[11. Everything about IN-OUT dp on tree aka Rerooting technique, Tree Distances, Tree Matching](dp/dp-on-trees.md)\r\n\r\n[12. Inclusion and Exclusion DP](dp/dp-on-trees.md)\r\n\r\n[13. Solving any structural dp problems using kadane's approach](dp/dp_tricks.md)\r\n\r\n[14. Subsequence \u0026 Substring comparison of two strings type problems](dp/subsequence_dp.md)\r\n\r\n[15. Everything about Sieve of Eratosthenes, Prime Factorization, Harmonic Lemma](dp/sieve.md)\r\n\r\n[16. Next Element Array technique used in various AND, OR, bitwise problems](dp/next-array.md)\r\n\r\n[17. Matrix Exponentiation Trick](dp/matrixexpo.md)\r\n\r\n[18. DP on Rings](dp/dp_on_ring.md)\r\n\r\n[19. Catalan Number, Dyck Path, Relection Technique](dp/catalan.md)\r\n\r\n\u003c/details\u003e\r\n\r\n\r\n\u003cdetails markdown=\"1\"\u003e\r\n\u003csummary\u003eGame Theory (6)\r\n\u003c/summary\u003e\r\n\t\r\n---\r\n\r\n[1. Games on arbitrary graphs](games/games.md)\r\n\r\n[2. NIM games](games/games.md)\r\n\r\n[3. Sprague Grundy Theorem](games/games.md)\r\n\r\n[4. Converting games to NIM forms using MEX](games/games.md)\r\n\r\n[5. Strategize the game backward, Parity Tricks](games/games.md)\r\n\r\n[6. Tag games on Trees, Graphs](games/games_on_graphs.md)\r\n\r\n\u003c/details\u003e\r\n\r\n\r\n\u003cdetails markdown=\"1\"\u003e\r\n\u003csummary\u003eRange Queries (15)\r\n\u003c/summary\u003e\r\n\r\n---\r\n\t\r\n[1. Binary Lifting, LCA of trees](range-queries/query.md)\r\n\r\n[2. Fenwick Tree, 1D, 2D, difference array trick](range-queries/query.md)\r\n\r\n[3. Sparse Table](range-queries/query.md)\r\n\r\n[4. Segment Tree 1D, 2D, Lazy Propagation](range-queries/query.md)\r\n\r\n[5. Merge Sort Tree](range-queries/query.md)\r\n\r\n[6. Sqrt Decomposition](range-queries/query.md)\r\n\r\n[7. Counting Inversions using Fenwick Tree](range-queries/query.md)\r\n\r\n[8. Order Statistics using Fenwick Tree](range-queries/query.md)\r\n\r\n[9. Classical Fenwick Tree application in DP, Coordinate Compression](range-queries/query.md)\r\n\r\n[10. Segment Tree, Bit manipulation and Lazy propagation](range-queries/query.md)\r\n\r\n[11. Get the nearest element from a given element in a range](range-queries/query.md)\r\n\r\n[12. Ordered Statistics using PBDS](range-queries/ordered_sets.md)\r\n\r\n[13. Interesting RMQ problems from SPOJ](range-queries/spoj-rmq-sprint.md)\r\n\r\n[14. Some non-trivial ideas in RMQ/RSQ](range-queries/non-trivial-examples.md)\r\n\r\n[15. MO's algorithm for RSQs and RMQs](range-queries/mo_query_trick.md)\r\n\r\n\u003c/details\u003e\r\n\r\n\r\n\u003cdetails markdown=\"1\"\u003e\r\n\u003csummary\u003eString Algorithms (9)\r\n\u003c/summary\u003e\r\n\r\n---\r\n\t\r\n[1. Minimum Palindromic Cuts](string/adhoc-strings.md)\r\n\r\n[2. Scatter Palindromes](string/adhoc-strings.md)\r\n\r\n[3. Distinct Subsequences](string/adhoc-strings.md)\r\n\r\n[4. Don't be a Subsequences](string/adhoc-strings.md)\r\n\r\n[5. KMP function, Z algorithm, periodicity of strings](string/kmp.md)\r\n\r\n[6. Polynomial Hashing aka Rolling Hash](string/polyhash.md)\r\n\r\n[7. Rabin Karp, Lexicographically minimal shift, double hashing](string/polyhash.md)\r\n\r\n[8. Fun with Palindromes](string/palindrome.md#fun-with-palindromes)\r\n\r\n[9. Majority Characters in a String](string/adhoc-strings.md)\r\n\r\n\u003c/details\u003e\r\n\r\n\r\n\u003cdetails markdown=\"1\"\u003e\r\n\u003csummary\u003eMiscellaneous Stuff (13)\r\n\u003c/summary\u003e\r\n\r\n---\r\n\r\n[1. K-Majority Voting algorithm aka Boyer-Moore](others/voting.md) \r\n\r\n[2. Some useful bit hacks, bitsets](others/bit-hacks.md)\r\n\r\n[3. Bitset Magic and DP optimizations](others/bitsets.md)\r\n\r\n[4. Minimum, Maximum XOR values of pair of numbers](others/classical_ideas.md)\r\n\r\n[5. Coordinate Compression](others/coordinate-compression.md)\r\n\r\n[6. Ternary Search for unimodal data](others/ternery-search.md)\r\n\r\n[7. Some non-trivial tricks used in DP and Graphs](gym/weekly-algorithm-sheet)\r\n\r\n[8. Some variants of Knapsack problem](others/knapsack.md)\r\n\r\n[9. All about permutations, transpositions and inversion count](others/permutation.md)\r\n\r\n[10. CF blog: Collection of little techniques](https://codeforces.com/blog/entry/100910)\r\n\r\n[11. Contribution Technique](others/contribution_technique.md)\r\n\r\n[12. Some less common causes of TLE](others/common-errors.md)\r\n\r\n[13. XOR Hashing](others/xor-hashing.md)\r\n \r\n\u003c/details\u003e\r\n\r\n[Just Practice Mode]\r\n\r\n---\t\r\n\r\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdebarghya4469%2Falgorithm-lib","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdebarghya4469%2Falgorithm-lib","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdebarghya4469%2Falgorithm-lib/lists"}