├── README.md └── code_templates ├── 2sat.cpp ├── aho_corasick.cpp ├── articulation_point.cpp ├── big_int.cpp ├── binary_indexed_tree.cpp ├── bridge.cpp ├── calendar.cpp ├── chinese_remainder_theorem.cpp ├── convex_hull.cpp ├── convex_hull_trick.cpp ├── dice.cpp ├── faster_input_and_output.cpp ├── fft.cpp ├── flow_routine.cpp ├── fraction.cpp ├── gaussian_elimination.cpp ├── geometry_routine.cpp ├── heavy_light_decomposition.cpp ├── kmp.cpp ├── kuhn.cpp ├── linear_diophantine_equation.cpp ├── lis.cpp ├── lowest_common_ancestor.cpp ├── manacher_algorithms.cpp ├── matrix_expo.cpp ├── miller_rabin_primality_test.cpp ├── minimum_expression.cpp ├── mobius_function.cpp ├── pascal_triangle.cpp ├── pollard_rho.cpp ├── prufer_code.cpp ├── scc_tarjan.cpp ├── suffix_array.cpp ├── suffix_automata.cpp ├── template.cpp ├── treap.cpp └── treap_builtin.cpp /README.md: -------------------------------------------------------------------------------- 1 | # Code Library 2 | 3 | All the codes that I have written/collected/organized to solve various algorithmic problems 4 | -------------------------------------------------------------------------------- /code_templates/2sat.cpp: -------------------------------------------------------------------------------- 1 | #define SCCNODE adf 2 | struct SCC{ 3 | int num[SCCNODE], low[SCCNODE], col[SCCNODE], cycle[SCCNODE], st[SCCNODE]; 4 | int tail, cnt, cc; 5 | vi adj[SCCNODE]; 6 | 7 | SCC():tail(0),cnt(0),cc(0) {} 8 | void clear ( int n ) { 9 | cc += 3; 10 | FOR(i,0,n) adj[i].clear(); 11 | tail = 0; 12 | } 13 | void tarjan ( int s ) { 14 | num[s] = low[s] = cnt++; 15 | col[s] = cc + 1; 16 | st[tail++] = s; 17 | FOR(i,0,SZ(adj[s])-1) { 18 | int t = adj[s][i]; 19 | if ( col[t] <= cc ) { 20 | tarjan ( t ); 21 | low[s]=min(low[s],low[t]); 22 | } 23 | /*Back edge*/ 24 | else if (col[t]==cc+1) 25 | low[s]=min(low[s],low[t]); 26 | } 27 | if ( low[s] == num[s] ) { 28 | while ( 1 ) { 29 | int temp=st[tail-1]; 30 | tail--; 31 | col[temp] = cc + 2; 32 | cycle[temp] = s; 33 | if ( s == temp ) break; 34 | } 35 | } 36 | } 37 | void shrink( int n ) { 38 | FOR(i,0,n){ 39 | FOR(j,0,SZ(adj[i])-1){ 40 | adj[i][j] = cycle[adj[i][j]]; ///Careful. This will create self-loop 41 | } 42 | } 43 | FOR(i,0,n){ 44 | if ( cycle[i] == i ) continue; 45 | int u = cycle[i]; 46 | FOR(j,0,SZ(adj[i])-1){ 47 | int v = adj[i][j]; 48 | adj[u].pb ( v ); 49 | } 50 | adj[i].clear(); 51 | } 52 | FOR(i,0,n){ ///Not always necessary 53 | sort ( ALL(adj[i]) ); 54 | UNIQUE(adj[i]); 55 | } 56 | } 57 | void findSCC( int n ) { 58 | FOR(i,0,n) { 59 | if ( col[i] <= cc ) { 60 | tarjan ( i ); 61 | } 62 | } 63 | } 64 | }; 65 | 66 | /* 67 | 1. The nodes need to be split. So change convert() accordingly. 68 | 2. Using clauses, populate scc edges. 69 | 3. Call possible, to find if a valid solution is possible or not. 70 | 4. Dont forget to keep space for !A variables 71 | */ 72 | struct SAT2 { 73 | SCC scc; 74 | 75 | SAT2(): bfscc(1) {} 76 | 77 | void clear( int n ) { 78 | scc.clear( int n ); 79 | } 80 | 81 | int convert ( int n ) { ///Change here. Depends on how input is provided 82 | int x = ABS(n); 83 | x--; 84 | x *= 2; 85 | if ( n < 0 ) x ^= 1; 86 | return x; 87 | } 88 | 89 | void mustTrue ( int a ) { ///A is True 90 | scc.adj[a^1].pb ( a ); 91 | } 92 | void orClause ( int a, int b ) { /// A || B clause 93 | //!a->b !b->a 94 | scc.adj[a^1].pb ( b ); 95 | scc.adj[b^1].pb ( a ); 96 | } 97 | /// Out of all possible option, only one is true 98 | void atMostOneClause ( int a[], int n, int flag ) { 99 | if ( flag == 0 ) { /// At most one can be false 100 | FOR(i,0,n){ 101 | a[i] = a[i] ^ 1; 102 | } 103 | } 104 | FOR(i,0,n) { 105 | FOR(j,i+1,n) { 106 | orClause( a[i] ^ 1, a[j] ^ 1 ); /// !a || !b both being true not allowed 107 | } 108 | } 109 | } 110 | 111 | ///Send n, total number of nodes, after expansion 112 | bool possible( int n ) { 113 | scc.findSCC( n ); 114 | 115 | FOR(i,0,n) { 116 | int a = i, b = i^1; 117 | ///Falls on same cycle a and !a. 118 | if ( scc.cycle[a] == scc.cycle[b] ) return false; 119 | } 120 | 121 | ///Valid solution exists 122 | return true; 123 | } 124 | 125 | ///To determine if A can be true. It cannot be true, if a path exists from A to !A. 126 | int vis[SAT2NODE], qqq[SAT2NODE], bfscc; 127 | void bfs( int s ) { 128 | bfscc++; 129 | int qs = 0, qt = 0; 130 | vis[s] = bfscc; 131 | qqq[qt++] = s; 132 | while ( qs < qt ) { 133 | s = qqq[qs++]; 134 | FOR(i,0,SZ(scc.adj[s])-1) { 135 | int t = scc.adj[s][i]; 136 | if ( vis[t] != bfscc ) { 137 | vis[t] = bfscc; 138 | qqq[qt++] = t; 139 | } 140 | } 141 | } 142 | } 143 | 144 | }sat2; 145 | -------------------------------------------------------------------------------- /code_templates/aho_corasick.cpp: -------------------------------------------------------------------------------- 1 | /// Aho Corasick 2 | /// !!! Works with lowercase letters !!! 3 | /// !!! If RTE, bring struct node outside !!! 4 | 5 | class AhoCorasick { 6 | #define SIZE asdf 7 | struct node { 8 | int val; 9 | int child[26]; 10 | void clear() { 11 | memset(child,0,sizeof child); 12 | } 13 | }trie[SIZE]; 14 | 15 | int curNode, root, fail[SIZE], par[SIZE]; 16 | 17 | public: 18 | void clear() { 19 | root = 0; 20 | curNode = 0; 21 | trie[root].clear(); 22 | } 23 | 24 | void addTrie ( string s ) { 25 | int len = s.size(); 26 | 27 | int cur = root; 28 | for ( int i = 0; i < len; i++ ) { 29 | char c = s[i] - 'a'; 30 | if ( trie[cur].child[c] == 0 ) { 31 | curNode++; 32 | trie[curNode].clear(); 33 | trie[curNode].val = c; 34 | trie[cur].child[c] = curNode; 35 | } 36 | cur = trie[cur].child[c]; 37 | } 38 | 39 | ///Mark the node cur as finishing point, if needed 40 | } 41 | 42 | void calcFail() { 43 | queue q; 44 | q.push ( 0 ); 45 | 46 | while ( !q.empty() ) { 47 | int s = q.front(); q.pop(); 48 | 49 | ///Push all child to queue 50 | for ( int i = 0; i < 26; i++ ) { 51 | int t = trie[s].child[i]; 52 | if ( t != 0 ) { 53 | q.push ( t ); 54 | par[t] = s; 55 | } 56 | } 57 | 58 | ///Calculate failure of current node s 59 | if ( s == 0 ) { ///Special case 60 | fail[s] = 0; 61 | par[s] = 0; 62 | continue; 63 | } 64 | 65 | int p = par[s]; 66 | int f = fail[p]; 67 | int v = trie[s].val; 68 | 69 | while ( f != 0 && trie[f].child[v] == 0 ) f = fail[f]; ///Keep on jumping until found 70 | 71 | fail[s] = trie[f].child[v]; 72 | if ( fail[s] == s ) fail[s] = 0; ///Can't be fail of itself 73 | } 74 | } 75 | 76 | int goTo ( int state, int c ) { 77 | if ( trie[state].child[c] != 0 ) { 78 | return trie[state].child[c]; 79 | } 80 | 81 | ///Fall back 82 | int f = fail[state]; 83 | while ( f != 0 && trie[f].child[c] == 0 ) { 84 | f = fail[f]; 85 | } 86 | 87 | return trie[f].child[c]; 88 | } 89 | 90 | }aho; 91 | 92 | -------------------------------------------------------------------------------- /code_templates/articulation_point.cpp: -------------------------------------------------------------------------------- 1 | #define ARTNODE 10010 2 | 3 | class ArticulationPoint { 4 | int disc[ARTNODE]; ///Discovery time of nodes 5 | int low[ARTNODE]; ///Lowest back edge extension 6 | int col[ARTNODE]; ///Color for marking node 7 | 8 | int cnt; ///Timer 9 | int cc; ///Color 10 | int root; ///Root of tree 11 | 12 | void tarjan ( int s, int p ) { 13 | disc[s] = low[s] = cnt++; 14 | col[s] = cc + 1; 15 | 16 | int child = 0; ///Needed for root only 17 | int art = 0; 18 | 19 | for ( int i = 0; i < adj[s].size(); ++i ) { 20 | 21 | int t = adj[s][i]; 22 | if ( t == p ) continue; ///Don't go to parent 23 | 24 | if ( col[t] <= cc ) { ///New node. Discovery. 25 | child++; 26 | 27 | tarjan ( t, s ); 28 | low[s]=min(low[s],low[t]); ///Update back edge extension for S 29 | 30 | if ( low[t] >= disc[s] ) { ///Back edge of T did not go above S 31 | art++; ///S is articulation point for T 32 | } 33 | } 34 | else if ( col[t] == cc + 1 ) { ///Back Edge 35 | low[s]=min(low[s],disc[t]); 36 | } 37 | } 38 | 39 | if ( ( s == root && child > 1 ) || ( s != root && art ) ) { 40 | ///Edit in this block 41 | printf ( "This is a articulation point: %d\n", s ); 42 | } 43 | } 44 | 45 | public: 46 | 47 | vector adj[ARTNODE]; 48 | 49 | void clear ( int n ) { 50 | cc += 2; ///cc is now 0. cc+1 is 1 51 | for (int i = 0; i <= n; i++ ) { 52 | adj[i].clear(); 53 | } 54 | } 55 | 56 | void findArt( int n, int start = 0 ) { 57 | for ( int i = start; i <= n; i++ ) { 58 | if ( col[i] <= cc ) { 59 | root = i; 60 | tarjan ( i, -1 ); 61 | } 62 | } 63 | } 64 | }art; -------------------------------------------------------------------------------- /code_templates/big_int.cpp: -------------------------------------------------------------------------------- 1 | const int base = 1000000000; 2 | const int base_digits = 9; 3 | 4 | struct bigint { 5 | vector a; 6 | int sign; 7 | 8 | bigint() : 9 | sign(1) { 10 | } 11 | 12 | bigint(long long v) { 13 | *this = v; 14 | } 15 | 16 | bigint(const string &s) { 17 | read(s); 18 | } 19 | 20 | void operator=(const bigint &v) { 21 | sign = v.sign; 22 | a = v.a; 23 | } 24 | 25 | void operator=(long long v) { 26 | a.clear(); 27 | sign = 1; 28 | if (v < 0) 29 | sign = -1, v = -v; 30 | for (; v > 0; v = v / base) 31 | a.push_back(v % base); 32 | } 33 | 34 | bigint operator+(const bigint &v) const { 35 | if (sign == v.sign) { 36 | bigint res = v; 37 | 38 | for (int i = 0, carry = 0; i < (int) max(a.size(), v.a.size()) || carry; ++i) { 39 | if (i == (int) res.a.size()) 40 | res.a.push_back(0); 41 | res.a[i] += carry + (i < (int) a.size() ? a[i] : 0); 42 | carry = res.a[i] >= base; 43 | if (carry) 44 | res.a[i] -= base; 45 | } 46 | return res; 47 | } 48 | return *this - (-v); 49 | } 50 | 51 | bigint operator-(const bigint &v) const { 52 | if (sign == v.sign) { 53 | if (abs() >= v.abs()) { 54 | bigint res = *this; 55 | for (int i = 0, carry = 0; i < (int) v.a.size() || carry; ++i) { 56 | res.a[i] -= carry + (i < (int) v.a.size() ? v.a[i] : 0); 57 | carry = res.a[i] < 0; 58 | if (carry) 59 | res.a[i] += base; 60 | } 61 | res.trim(); 62 | return res; 63 | } 64 | return -(v - *this); 65 | } 66 | return *this + (-v); 67 | } 68 | 69 | void operator*=(int v) { 70 | if (v < 0) 71 | sign = -sign, v = -v; 72 | for (int i = 0, carry = 0; i < (int) a.size() || carry; ++i) { 73 | if (i == (int) a.size()) 74 | a.push_back(0); 75 | long long cur = a[i] * (long long) v + carry; 76 | carry = (int) (cur / base); 77 | a[i] = (int) (cur % base); 78 | //asm("divl %%ecx" : "=a"(carry), "=d"(a[i]) : "A"(cur), "c"(base)); 79 | } 80 | trim(); 81 | } 82 | 83 | bigint operator*(int v) const { 84 | bigint res = *this; 85 | res *= v; 86 | return res; 87 | } 88 | 89 | friend pair divmod(const bigint &a1, const bigint &b1) { 90 | int norm = base / (b1.a.back() + 1); 91 | bigint a = a1.abs() * norm; 92 | bigint b = b1.abs() * norm; 93 | bigint q, r; 94 | q.a.resize(a.a.size()); 95 | 96 | for (int i = a.a.size() - 1; i >= 0; i--) { 97 | r *= base; 98 | r += a.a[i]; 99 | int s1 = r.a.size() <= b.a.size() ? 0 : r.a[b.a.size()]; 100 | int s2 = r.a.size() <= b.a.size() - 1 ? 0 : r.a[b.a.size() - 1]; 101 | int d = ((long long) base * s1 + s2) / b.a.back(); 102 | r -= b * d; 103 | while (r < 0) 104 | r += b, --d; 105 | q.a[i] = d; 106 | } 107 | 108 | q.sign = a1.sign * b1.sign; 109 | r.sign = a1.sign; 110 | q.trim(); 111 | r.trim(); 112 | return make_pair(q, r / norm); 113 | } 114 | 115 | bigint operator/(const bigint &v) const { 116 | return divmod(*this, v).first; 117 | } 118 | 119 | bigint operator%(const bigint &v) const { 120 | return divmod(*this, v).second; 121 | } 122 | 123 | void operator/=(int v) { 124 | if (v < 0) 125 | sign = -sign, v = -v; 126 | for (int i = (int) a.size() - 1, rem = 0; i >= 0; --i) { 127 | long long cur = a[i] + rem * (long long) base; 128 | a[i] = (int) (cur / v); 129 | rem = (int) (cur % v); 130 | } 131 | trim(); 132 | } 133 | 134 | bigint operator/(int v) const { 135 | bigint res = *this; 136 | res /= v; 137 | return res; 138 | } 139 | 140 | int operator%(int v) const { 141 | if (v < 0) 142 | v = -v; 143 | int m = 0; 144 | for (int i = a.size() - 1; i >= 0; --i) 145 | m = (a[i] + m * (long long) base) % v; 146 | return m * sign; 147 | } 148 | 149 | void operator+=(const bigint &v) { 150 | *this = *this + v; 151 | } 152 | void operator-=(const bigint &v) { 153 | *this = *this - v; 154 | } 155 | void operator*=(const bigint &v) { 156 | *this = *this * v; 157 | } 158 | void operator/=(const bigint &v) { 159 | *this = *this / v; 160 | } 161 | 162 | bool operator<(const bigint &v) const { 163 | if (sign != v.sign) 164 | return sign < v.sign; 165 | if (a.size() != v.a.size()) 166 | return a.size() * sign < v.a.size() * v.sign; 167 | for (int i = a.size() - 1; i >= 0; i--) 168 | if (a[i] != v.a[i]) 169 | return a[i] * sign < v.a[i] * sign; 170 | return false; 171 | } 172 | 173 | bool operator>(const bigint &v) const { 174 | return v < *this; 175 | } 176 | bool operator<=(const bigint &v) const { 177 | return !(v < *this); 178 | } 179 | bool operator>=(const bigint &v) const { 180 | return !(*this < v); 181 | } 182 | bool operator==(const bigint &v) const { 183 | return !(*this < v) && !(v < *this); 184 | } 185 | bool operator!=(const bigint &v) const { 186 | return *this < v || v < *this; 187 | } 188 | 189 | void trim() { 190 | while (!a.empty() && !a.back()) 191 | a.pop_back(); 192 | if (a.empty()) 193 | sign = 1; 194 | } 195 | 196 | bool isZero() const { 197 | return a.empty() || (a.size() == 1 && !a[0]); 198 | } 199 | 200 | bigint operator-() const { 201 | bigint res = *this; 202 | res.sign = -sign; 203 | return res; 204 | } 205 | 206 | bigint abs() const { 207 | bigint res = *this; 208 | res.sign *= res.sign; 209 | return res; 210 | } 211 | 212 | long long longValue() const { 213 | long long res = 0; 214 | for (int i = a.size() - 1; i >= 0; i--) 215 | res = res * base + a[i]; 216 | return res * sign; 217 | } 218 | 219 | friend bigint gcd(const bigint &a, const bigint &b) { 220 | return b.isZero() ? a : gcd(b, a % b); 221 | } 222 | friend bigint lcm(const bigint &a, const bigint &b) { 223 | return a / gcd(a, b) * b; 224 | } 225 | 226 | void read(const string &s) { 227 | sign = 1; 228 | a.clear(); 229 | int pos = 0; 230 | while (pos < (int) s.size() && (s[pos] == '-' || s[pos] == '+')) { 231 | if (s[pos] == '-') 232 | sign = -sign; 233 | ++pos; 234 | } 235 | for (int i = s.size() - 1; i >= pos; i -= base_digits) { 236 | int x = 0; 237 | for (int j = max(pos, i - base_digits + 1); j <= i; j++) 238 | x = x * 10 + s[j] - '0'; 239 | a.push_back(x); 240 | } 241 | trim(); 242 | } 243 | 244 | friend istream& operator>>(istream &stream, bigint &v) { 245 | string s; 246 | stream >> s; 247 | v.read(s); 248 | return stream; 249 | } 250 | 251 | friend ostream& operator<<(ostream &stream, const bigint &v) { 252 | if (v.sign == -1) 253 | stream << '-'; 254 | stream << (v.a.empty() ? 0 : v.a.back()); 255 | for (int i = (int) v.a.size() - 2; i >= 0; --i) 256 | stream << setw(base_digits) << setfill('0') << v.a[i]; 257 | return stream; 258 | } 259 | 260 | void print() { 261 | if ( sign == -1 ) printf ( "-" ); 262 | 263 | if ( a.empty() ) printf ( "0" ); 264 | else printf ( "%d", a.back() ); 265 | 266 | 267 | for ( int i = (int)a.size() - 2; i >= 0; i-- ) { 268 | printf ( "%09d", a[i] ); //% 0 base_digits d 269 | } 270 | } 271 | 272 | 273 | static vector convert_base(const vector &a, int old_digits, int new_digits) { 274 | vector p(max(old_digits, new_digits) + 1); 275 | p[0] = 1; 276 | for (int i = 1; i < (int) p.size(); i++) 277 | p[i] = p[i - 1] * 10; 278 | vector res; 279 | long long cur = 0; 280 | int cur_digits = 0; 281 | for (int i = 0; i < (int) a.size(); i++) { 282 | cur += a[i] * p[cur_digits]; 283 | cur_digits += old_digits; 284 | while (cur_digits >= new_digits) { 285 | res.push_back(int(cur % p[new_digits])); 286 | cur /= p[new_digits]; 287 | cur_digits -= new_digits; 288 | } 289 | } 290 | res.push_back((int) cur); 291 | while (!res.empty() && !res.back()) 292 | res.pop_back(); 293 | return res; 294 | } 295 | 296 | typedef vector vll; 297 | 298 | static vll karatsubaMultiply(const vll &a, const vll &b) { 299 | int n = a.size(); 300 | vll res(n + n); 301 | if (n <= 32) { 302 | for (int i = 0; i < n; i++) 303 | for (int j = 0; j < n; j++) 304 | res[i + j] += a[i] * b[j]; 305 | return res; 306 | } 307 | 308 | int k = n >> 1; 309 | vll a1(a.begin(), a.begin() + k); 310 | vll a2(a.begin() + k, a.end()); 311 | vll b1(b.begin(), b.begin() + k); 312 | vll b2(b.begin() + k, b.end()); 313 | 314 | vll a1b1 = karatsubaMultiply(a1, b1); 315 | vll a2b2 = karatsubaMultiply(a2, b2); 316 | 317 | for (int i = 0; i < k; i++) 318 | a2[i] += a1[i]; 319 | for (int i = 0; i < k; i++) 320 | b2[i] += b1[i]; 321 | 322 | vll r = karatsubaMultiply(a2, b2); 323 | for (int i = 0; i < (int) a1b1.size(); i++) 324 | r[i] -= a1b1[i]; 325 | for (int i = 0; i < (int) a2b2.size(); i++) 326 | r[i] -= a2b2[i]; 327 | 328 | for (int i = 0; i < (int) r.size(); i++) 329 | res[i + k] += r[i]; 330 | for (int i = 0; i < (int) a1b1.size(); i++) 331 | res[i] += a1b1[i]; 332 | for (int i = 0; i < (int) a2b2.size(); i++) 333 | res[i + n] += a2b2[i]; 334 | return res; 335 | } 336 | 337 | bigint operator*(const bigint &v) const { 338 | vector a6 = convert_base(this->a, base_digits, 6); 339 | vector b6 = convert_base(v.a, base_digits, 6); 340 | vll a(a6.begin(), a6.end()); 341 | vll b(b6.begin(), b6.end()); 342 | while (a.size() < b.size()) 343 | a.push_back(0); 344 | while (b.size() < a.size()) 345 | b.push_back(0); 346 | while (a.size() & (a.size() - 1)) 347 | a.push_back(0), b.push_back(0); 348 | vll c = karatsubaMultiply(a, b); 349 | bigint res; 350 | res.sign = sign * v.sign; 351 | for (int i = 0, carry = 0; i < (int) c.size(); i++) { 352 | long long cur = c[i] + carry; 353 | res.a.push_back((int) (cur % 1000000)); 354 | carry = (int) (cur / 1000000); 355 | } 356 | res.a = convert_base(res.a, 6, base_digits); 357 | res.trim(); 358 | return res; 359 | } 360 | }; -------------------------------------------------------------------------------- /code_templates/binary_indexed_tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Make sure BIT is 1-indexed 3 | 1. Properly change update and read 4 | 2. Call clear() and set row and col 5 | */ 6 | struct BIT { 7 | int arr2D[XXX][XXX], arr[XXX]; 8 | int row, col; 9 | 10 | void clear( int r, int c ){ 11 | row = r; 12 | col = c; 13 | CLR(arr,0); 14 | } 15 | 16 | ///If I need sum[1-x], I will update from [x-n]. Opposite for reverse. 17 | void update ( int x, int val ) { 18 | for ( int i = x; i <= col; i += i & -i ) arr[i] += val; 19 | } 20 | int read ( int x ) { 21 | int res = 0; 22 | for ( int i = x; i > 0; i -= i & -i ) res += arr[i]; 23 | } 24 | 25 | ///If I need sum[1-x], I will update from [x-n]. Opposite for reverse. 26 | void update2D ( int x, int y, int val ) { 27 | for ( int i = x; i > 0; i -= i & -i ) { ///Change Here. Both increment and loop condition 28 | for ( int j = y; j <= col; j += j & -j ) { ///And here 29 | arr[i][j] += val; 30 | } 31 | } 32 | } 33 | 34 | ///Just reverse direction of update 35 | int read2D ( int x, int y ) { 36 | int res = 0; 37 | for ( int i = x; i <= row; i += i & -i ) { ///Change Here. Both increment and loop condition 38 | for ( int j = y; j > 0; j -= j & -j ) { ///And here 39 | res += arr[i][j]; 40 | } 41 | } 42 | return res; 43 | } 44 | }bit; 45 | -------------------------------------------------------------------------------- /code_templates/bridge.cpp: -------------------------------------------------------------------------------- 1 | #define BRIDGENODE 10010 2 | 3 | class BridgeFinding { 4 | int disc[BRIDGENODE]; ///Discovery time of nodes 5 | int low[BRIDGENODE]; ///Lowest back edge extension 6 | int col[BRIDGENODE]; ///Color for marking node 7 | 8 | int cnt; ///Timer 9 | int cc; ///Color 10 | 11 | void tarjan ( int s, int parentEdge ) { 12 | disc[s] = low[s] = cnt++; 13 | col[s] = cc + 1; 14 | 15 | for ( int i = 0; i < adj[s].size(); ++i ) { 16 | 17 | int t = adj[s][i].ff; 18 | int edgeNumber = adj[s][i].ss; 19 | if ( edgeNumber == parentEdge ) continue; ///Don't use the same edge from parent 20 | 21 | if ( col[t] <= cc ) { ///New node. Discovery. 22 | 23 | tarjan ( t, edgeNumber ); 24 | low[s]=min(low[s],low[t]); ///Update back edge extension for S 25 | 26 | if ( low[t] > disc[s] ) { ///Back edge of T did not go above S 27 | ///This edge is Bridge 28 | } 29 | } 30 | else if ( col[t] == cc + 1 ) { ///Back Edge 31 | low[s]=min(low[s],disc[t]); 32 | } 33 | } 34 | } 35 | 36 | public: 37 | 38 | vector< pair > adj[BRIDGENODE]; ///Enter target and edge number as pair 39 | 40 | void clear ( int n ) { 41 | cc += 2; ///cc is now 0. cc+1 is 1 42 | for (int i = 0; i <= n; i++ ) { 43 | adj[i].clear(); 44 | } 45 | } 46 | 47 | void findBridge( int n, int start = 0 ) { 48 | for ( int i = start; i <= n; i++ ) { 49 | if ( col[i] <= cc ) { 50 | tarjan ( i, -1 ); 51 | } 52 | } 53 | } 54 | }bridge; -------------------------------------------------------------------------------- /code_templates/calendar.cpp: -------------------------------------------------------------------------------- 1 | struct CALENDAR { 2 | int month[13]; 3 | int d, m, y, daysInYear; 4 | int day; 5 | 6 | CALENDER () { 7 | month[1] = 31; month[2] = 28; month[3] = 31; 8 | month[4] = 30; month[5] = 31; month[6] = 30; 9 | month[7] = 31; month[8] = 31; month[9] = 30; 10 | month[10] = 31; month[11] = 30; month[12] = 31; 11 | daysInYear = 365; 12 | } 13 | 14 | void assign ( int a, int b, int c, int _day = 0 ) { 15 | d = a; 16 | m = b; 17 | y = c; 18 | day = _day; 19 | updateFeb(); 20 | } 21 | 22 | bool isLeapYear ( int n ) { 23 | if ( n % 400 == 0 || ( n % 4 == 0 && n % 100 != 0 ) ) return true; 24 | else return false; 25 | } 26 | 27 | //Call this whenever year changes 28 | void updateFeb () { 29 | if ( isLeapYear( y ) ) { 30 | month[2] = 29; 31 | daysInYear = 366; 32 | } 33 | else { 34 | month[2] = 28; 35 | daysInYear = 365; 36 | } 37 | } 38 | 39 | bool operator < ( const CALENDER &b ) const { 40 | if ( y < b.y ) return true; 41 | else if ( y == b.y && m < b.m ) return true; 42 | else if ( y == b.y && m == b.m && d < b.d ) return true; 43 | else return false; 44 | } 45 | 46 | //Increase 1 day 47 | void increment () { 48 | d++; 49 | day = ( day + 1 ) % 7; 50 | 51 | if ( d > month[m] ) { 52 | d = 1; 53 | m++; 54 | if ( m > 12 ) { 55 | m = 1; 56 | y++; 57 | updateFeb(); 58 | } 59 | } 60 | } 61 | 62 | //Number of days between 1/1/a to 31/12/b inclusive 63 | int daysBetweenYear ( int a, int b ) { 64 | int p = b - a + 1; 65 | int res = p * 365; 66 | //Add 1 day for each leap year between [a,b]. 67 | 68 | //Leap year between [0,b] - [0,a-1] 69 | int leap = b / 4 - b / 100 + b / 400; 70 | if ( a ) { 71 | a--; 72 | leap -= a / 4 - a / 100 + a / 400; 73 | } 74 | 75 | return res + leap; 76 | } 77 | 78 | //Return number of days between two dates. Go from b to *this. 79 | int diff ( CALENDER b ) { 80 | if ( y == b.y && m == b.m && d == b.d ) return 0; 81 | if ( *this < b ) return b.diff( *this ); 82 | 83 | int res = 0; 84 | //The year is not same yet 85 | if ( b.y < y ) { 86 | //So we can move to next year, one day at a time. 87 | while ( b.d != 1 || b.m != 1 ) { 88 | b.increment(); 89 | res++; 90 | } 91 | res += daysBetweenYear( b.y, y - 1 ); 92 | b.y = y; 93 | b.updateFeb(); 94 | } 95 | 96 | //Same year 97 | while ( b.d != d || b.m != m ) { 98 | b.increment(); 99 | res++; 100 | } 101 | 102 | return res; 103 | } 104 | 105 | //Add n days to current date 106 | CALENDER add ( int n ) { 107 | CALENDER res = *this; 108 | 109 | if ( n < 800 ) { 110 | while ( n ) { 111 | res.increment(); 112 | n--; 113 | } 114 | return res; 115 | } 116 | 117 | while ( res.d != 1 || res.m != 1 ) { 118 | n--; 119 | res.increment(); 120 | } 121 | 122 | while ( n > 366 ) { 123 | int jump = n / 366; 124 | if ( jump ) { 125 | int jd = daysBetweenYear( res.y, res.y + jump - 1 ); 126 | n -= jd; 127 | res.day = ( res.day + jd ) % 7; 128 | res.y = res.y + jump; 129 | res.updateFeb(); 130 | } 131 | } 132 | 133 | while ( n ) { 134 | res.increment(); 135 | n--; 136 | } 137 | 138 | return res; 139 | } 140 | }; -------------------------------------------------------------------------------- /code_templates/chinese_remainder_theorem.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | A CRT solver which works even when moduli are not pairwise coprime 3 | 4 | 1. Add equations using addEquation() method 5 | 2. Call solve() to get {x, N} pair, where x is the unique solution modulo N. 6 | 7 | Assumptions: 8 | 1. LCM of all mods will fit into long long. 9 | */ 10 | class ChineseRemainderTheorem { 11 | typedef long long vlong; 12 | typedef pair pll; 13 | 14 | /** CRT Equations stored as pairs of vector. See addEqation()*/ 15 | vector equations; 16 | 17 | public: 18 | void clear() { 19 | equations.clear(); 20 | } 21 | 22 | /** Add equation of the form x = r (mod m)*/ 23 | void addEquation( vlong r, vlong m ) { 24 | equations.push_back({r, m}); 25 | } 26 | pll solve() { 27 | if (equations.size() == 0) return {-1,-1}; /// No equations to solve 28 | 29 | vlong a1 = equations[0].first; 30 | vlong m1 = equations[0].second; 31 | a1 %= m1; 32 | /** Initially x = a_0 (mod m_0)*/ 33 | 34 | /** Merge the solution with remaining equations */ 35 | for ( int i = 1; i < equations.size(); i++ ) { 36 | vlong a2 = equations[i].first; 37 | vlong m2 = equations[i].second; 38 | 39 | vlong g = __gcd(m1, m2); 40 | if ( a1 % g != a2 % g ) return {-1,-1}; /// Conflict in equations 41 | 42 | /** Merge the two equations*/ 43 | vlong p, q; 44 | ext_gcd(m1/g, m2/g, &p, &q); 45 | 46 | vlong mod = m1 / g * m2; 47 | vlong x = ( (__int128)a1 * (m2/g) % mod *q % mod + (__int128)a2 * (m1/g) % mod * p % mod ) % mod; 48 | 49 | /** Merged equation*/ 50 | a1 = x; 51 | if ( a1 < 0 ) a1 += mod; 52 | m1 = mod; 53 | } 54 | return {a1, m1}; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /code_templates/convex_hull.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 1. Assign hull.n 3 | 2. Take input in hull.point 4 | 3. Call findHull() 5 | 4. Convex Hull is ready in hull.convex with hull.m points in it. 6 | */ 7 | 8 | pll g; 9 | 10 | vlong triArea ( const pll &a, const pll &b, const pll &c ) { 11 | vlong area = a.ff * b.ss + b.ff * c.ss + c.ff * a.ss; 12 | area -= a.ff * c.ss + b.ff * a.ss + c.ff * b.ss; 13 | return area; 14 | } 15 | 16 | vlong sqDist ( const pll &a, const pll &b ) { 17 | return ( SQ(a.ff-b.ff) + SQ(a.ss-b.ss ) ); 18 | } 19 | 20 | bool convexCompare ( const pll &a, const pll &b ) { 21 | vlong area = triArea ( g, a, b ); 22 | if ( area > 0 ) return true; 23 | else if ( area == 0 && sqDist ( g, a ) < sqDist ( g, b ) ) return true; 24 | else return false; 25 | } 26 | 27 | class ConvexHull { 28 | void convexSort() { ///CCW 29 | g = point[0]; 30 | FOR(i,0,n-1) { 31 | if ( point[i].ff < g.ff ) g = point[i]; 32 | else if ( point[i].ff == g.ff && point[i].ss < g.ss ) g = point[i]; 33 | } 34 | sort ( point, point + n, convexCompare ); 35 | } 36 | 37 | public: 38 | 39 | int n, m; ///N is number of points in polygon and M is number of points in convex hull 40 | 41 | #define PPP adsf 42 | pll point[PPP], convex[PPP]; 43 | 44 | void findHull() { 45 | convexSort(); 46 | 47 | if ( n == 1 ) { 48 | convex[0] = convex[1] = point[0]; 49 | m = 1; 50 | return; 51 | } 52 | convex[0] = point[n-1]; convex[1] = point[0]; convex[2] = point[1]; 53 | int cur = 3; 54 | for ( int i = 2; i < n; i++ ) { 55 | vlong area = triArea ( convex[cur-2], convex[cur-1], point[i] ); 56 | if ( area > 0 ) { 57 | convex[cur] = point[i]; 58 | cur++; 59 | } 60 | else if ( area == 0 ) { ///Take action depending on what is required 61 | /*Left Vertical Line gets omitted. Manually handle it*/ 62 | /*convex[cur] = point[i]; 63 | cur++;*/ 64 | ///If extra point needs to be removed 65 | convex[cur-1] = point[i]; 66 | } 67 | else { 68 | cur--; 69 | i--; 70 | } 71 | } 72 | m = cur - 1; 73 | } 74 | 75 | }hull; -------------------------------------------------------------------------------- /code_templates/convex_hull_trick.cpp: -------------------------------------------------------------------------------- 1 | /* Instructions 2 | 1. Sort lines based on decreasing M and in case of tie, increasing B. 3 | 2. Sort query points according to increasing X. 4 | 3. Clear the class, add all lines and then query. 5 | */ 6 | 7 | class ConvexHullTrick { 8 | int pointer; //Keeps track of the best line from previous query 9 | vector M; //Holds the slopes of the lines in the envelope 10 | vector B; //Holds the y-intercepts of the lines in the envelope 11 | 12 | //Returns true if line l3 is always better than line l2 13 | bool bad(int l1,int l2,int l3){ 14 | /* 15 | intersection(l1,l2) has x-coordinate (b1-b2)/(m2-m1) 16 | intersection(l1,l3) has x-coordinate (b1-b3)/(m3-m1) 17 | set the former greater than the latter, and cross-multiply to 18 | eliminate division 19 | */ 20 | return (B[l3]-B[l1])*(M[l1]-M[l2])<(B[l2]-B[l1])*(M[l1]-M[l3]); 21 | } 22 | 23 | public: 24 | 25 | void clear() { 26 | pointer = 0; 27 | M.clear(); 28 | B.clear(); 29 | } 30 | 31 | //Adds a new line (with lowest slope) to the structure 32 | void add(long long m,long long b){ 33 | if ( M.size() > 0 && M.back() == m ) return; ///Same Gradient. Don't add. 34 | 35 | //First, let's add it to the end 36 | M.push_back(m); 37 | B.push_back(b); 38 | //If the penultimate is now made irrelevant between the antepenultimate 39 | //and the ultimate, remove it. Repeat as many times as necessary 40 | while (M.size()>=3&&bad(M.size()-3,M.size()-2,M.size()-1)){ 41 | M.erase(M.end()-2); 42 | B.erase(B.end()-2); 43 | } 44 | } 45 | 46 | //Returns the minimum y-coordinate of any intersection between a given vertical 47 | //line and the lower envelope 48 | long long query(long long x){ 49 | //Any better line must be to the right, since query values are 50 | //non-decreasing 51 | while (pointer b.face[i] ) return false; 38 | } 39 | return false; 40 | } 41 | 42 | //Find the original Scheme of the DICE 43 | DICE diceScheme() { 44 | DICE res = *this; 45 | DICE temp = *this; 46 | 47 | FOR(i,0,3) { 48 | temp = temp.rotateX(); 49 | FOR(j,0,3) { 50 | temp = temp.rotateZ(); 51 | if ( temp < res ) res = temp; 52 | } 53 | } 54 | FOR(i,0,3) { 55 | temp = temp.rotateY(); 56 | FOR(j,0,3) { 57 | temp = temp.rotateZ(); 58 | if ( temp < res ) res = temp; 59 | } 60 | } 61 | return res; 62 | } 63 | 64 | void print() { 65 | FOR(i,0,5) printf ( "%d ", face[i] ); 66 | nl; 67 | } 68 | }; 69 | -------------------------------------------------------------------------------- /code_templates/faster_input_and_output.cpp: -------------------------------------------------------------------------------- 1 | #define gc getchar_unlocked 2 | 3 | void readInt(int &x){ 4 | register char c = gc(); 5 | x = 0; 6 | int neg = 0; 7 | for(;((c<48 || c>57) && c != '-');c = gc()); 8 | if(c=='-') {neg=1;c=gc();} 9 | for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;} 10 | if(neg) x=-x; 11 | } 12 | 13 | void readVlong (vlong &x){ 14 | register char c = gc(); 15 | x = 0; 16 | int neg = 0; 17 | for(;((c<48 || c>57) && c != '-');c = gc()); 18 | if(c=='-') {neg=1;c=gc();} 19 | for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;} 20 | if(neg) x=-x; 21 | } 22 | 23 | void readChar ( char &x ) { 24 | register char c = gc(); 25 | while (c < 33) c = gc(); 26 | x = c; 27 | } 28 | 29 | void readString(char *str){ 30 | register char c = 0; 31 | register int i = 0; 32 | while (c < 33) 33 | c = gc(); 34 | while (c != '\n') { 35 | str[i] = c; 36 | c = gc(); 37 | i = i + 1; 38 | } 39 | str[i] = '\0'; 40 | } 41 | -------------------------------------------------------------------------------- /code_templates/fft.cpp: -------------------------------------------------------------------------------- 1 | typedef complex base; 2 | 3 | void fft (vector & a, bool invert) { 4 | int n = (int) a.size(); 5 | if (n == 1) return; 6 | 7 | vector a0 (n/2), a1 (n/2); 8 | for (int i=0, j=0; i & a, const vector & b, vector & res) { 36 | vector fa (a.begin(), a.end()), fb (b.begin(), b.end()); 37 | size_t n = 1; 38 | while (n < max (a.size(), b.size())) n <<= 1; 39 | n <<= 1; 40 | fa.resize (n), fb.resize (n); 41 | 42 | fft (fa, false), fft (fb, false); 43 | for (size_t i=0; i dq; 87 | dq.pb ( source ); 88 | while ( !dq.empty() ) { 89 | int s = dq.front(); dq.pop_front(); 90 | inq[s] = 0; 91 | for ( i = head[s]; i != -1; i = edge[i].next ) { 92 | int t = edge[i].y; 93 | if ( edge[i].cap ) { 94 | if ( vis[s] + edge[i].cost < vis[t] ) { 95 | vis[t] = vis[s] + edge[i].cost; 96 | par[t] = s; 97 | record[t] = i; 98 | if ( inq[t] == 0 ) { 99 | inq[t] = 1; 100 | if ( dq.empty() == false && vis[dq.front()] > vis[t] ) 101 | dq.push_front( t ); 102 | else dq.pb ( t ); 103 | } 104 | } 105 | } 106 | } 107 | } 108 | 109 | //if ( vis[sink] > 0 ) break; ///Cost Getting minimized, Change Here 110 | if ( vis[sink] == inf ) break; //Flow getting maximized. Either this, or the one above 111 | 112 | fl++; ///Total flow 113 | res += vis[sink]; ///Cost of Flow 114 | for ( i = sink; i != source; i = par[i] ) { //Travel from sink to source 115 | int t = record[i]; //Record which edge was used to travel to t 116 | edge[t].cap--; 117 | edge[t^1].cap++; 118 | } 119 | } 120 | 121 | return res; ///Min cost of max flow 122 | } 123 | 124 | }graph; 125 | 126 | //Kuhn's algo has been moved to kuhn.cpp 127 | -------------------------------------------------------------------------------- /code_templates/fraction.cpp: -------------------------------------------------------------------------------- 1 | class Fraction { 2 | vlong num, denom; 3 | 4 | void simplify() { 5 | vlong g = gcd ( num, denom ); 6 | num /= g; 7 | denom /= g; 8 | if ( denom < 0 ) { 9 | num *= -1; 10 | denom *= -1; 11 | } 12 | } 13 | 14 | public: 15 | 16 | ///First deal with initiation of the class 17 | Fraction () { 18 | num = 0; 19 | denom = 1; 20 | } 21 | Fraction ( vlong a, vlong b ) { 22 | num = a; 23 | denom = b; 24 | simplify(); 25 | } 26 | Fraction ( vlong x ) { 27 | num = x; 28 | denom = 1; 29 | } 30 | Fraction ( pll x ) { 31 | num = x.ff; 32 | denom = x.ss; 33 | simplify(); 34 | } 35 | Fraction ( const Fraction &b ) { 36 | num = b.num; 37 | denom = b.denom; 38 | } 39 | void operator = ( vlong x ) { 40 | num = x; 41 | denom = 1; 42 | } 43 | void operator = ( pll x ) { 44 | num = x.ff; 45 | denom = x.ss; 46 | simplify(); 47 | } 48 | void operator = ( Fraction b ) { 49 | num = b.num; 50 | denom = b.denom; 51 | } 52 | 53 | ///Basic Arithmetic operations 54 | Fraction operator - () { ///Negation 55 | return Fraction( -num, denom ); 56 | } 57 | Fraction operator + ( Fraction b ) { ///Addition 58 | Fraction res; 59 | res.denom = abs( LCM(denom,b.denom) ); 60 | res.num = (res.denom/denom)*num + (res.denom/b.denom)*b.num; 61 | res.simplify(); 62 | return res; 63 | } 64 | Fraction operator - ( Fraction b ) { ///Subtraction 65 | return (*this) + (-b); 66 | } 67 | Fraction operator * ( Fraction b ) { 68 | Fraction res ( b.num / gcd(b.num,denom), b.denom / gcd(b.denom,num) ); 69 | res.num *= num / gcd(num,b.denom); 70 | res.denom *= denom / gcd(denom,b.num); 71 | res.simplify(); 72 | return res; 73 | } 74 | Fraction operator / ( Fraction b ) { ///Division 75 | Fraction rev ( b.denom, b.num ); 76 | if ( rev.denom < 0 ) { 77 | rev.denom *= -1; 78 | rev.num *= -1; 79 | } 80 | return (*this)*rev; 81 | } 82 | 83 | ///Basic Arithmetic Operations overloaded 84 | void operator += ( Fraction b ) { 85 | *this = *this + b; 86 | } 87 | void operator -= ( Fraction b ) { 88 | *this = *this - b; 89 | } 90 | void operator *= ( Fraction b ) { 91 | *this = *this * b; 92 | } 93 | void operator /= ( Fraction b ) { 94 | *this = *this / b; 95 | } 96 | 97 | ///Comparison 98 | bool operator == ( Fraction b ) { 99 | if ( num == b.num && denom == b.denom ) return true; 100 | else return false; 101 | } 102 | bool operator < ( Fraction b ) { 103 | if ( num * b.denom < b.num * denom ) return true; 104 | else return false; 105 | } 106 | bool operator > ( Fraction b ) { 107 | return ( b < *this ); 108 | } 109 | bool operator <= ( Fraction b ) { 110 | if ( *this == b || *this < b ) return true; 111 | else return false; 112 | } 113 | bool operator >= ( Fraction b ) { 114 | return ( b <= *this ); 115 | } 116 | 117 | ///Output 118 | void print() { 119 | printf ( "%lld/%lld %lf\n",num, denom, num/(denom-0.0) ); 120 | } 121 | 122 | Fraction getAbs() { 123 | return Fraction(abs(num),denom); 124 | } 125 | }; -------------------------------------------------------------------------------- /code_templates/gaussian_elimination.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 1. Set row and col of mat 3 | 2. Call rank() to perform gauss-elimination and find rank 4 | 3. Call isValid() to find if solution exists. 5 | 6 | Careful about int a[x][x]. If mod^2 crosses int, take vlong 7 | If mod is 2, it is better to use XOR since it a lot faster. 8 | */ 9 | struct GAUSS { 10 | int row, col; 11 | vlong a[x][x]; 12 | int mod; 13 | bool valid; 14 | GAUSS() { 15 | mod = xyz; 16 | } 17 | void clear () { 18 | memset ( a, 0, sizeof a ); 19 | } 20 | void isValid ( int st ) { 21 | int i; 22 | valid = true; 23 | for ( i = st; i < row; i++ ) { 24 | if ( a[i][col-1] ) { 25 | valid = false; 26 | return; 27 | } 28 | } 29 | } 30 | ///Return Rank of Matrix 31 | ///Free variable = Variable - Rank or Col - Rank - 1 32 | int rank(){ 33 | int i = 0, j = 0, k, r, u; 34 | while(i < row && j < col - 1){ 35 | r = i; 36 | for(k = i; k < row; k++) 37 | if(a[k][j]){ 38 | r = k; ///Find non-zero coefficient 39 | break; 40 | } 41 | if(a[r][j]){ 42 | if(r != i) ///Swap row if required 43 | for(k = 0; k < col; k++) 44 | swap(a[r][k], a[i][k]); 45 | 46 | ///Neutralize if required. Depends on whether double or modular division 47 | vlong v = a[i][j]; 48 | v = modInv ( v, mod ); 49 | for ( u = j; u < col; u++ ) { 50 | a[i][u] = ( a[i][u] * v ) % mod; 51 | } 52 | /* 53 | double v = a[i][j]; 54 | for ( u = j; u < col; u++ ) { 55 | a[i][u] /= v; 56 | } 57 | */ 58 | 59 | for(u = i + 1; u < row; u++) 60 | if(a[u][j]) { ///Eliminate 61 | int v = a[u][j]; 62 | for(k = j; k < col; k++) { 63 | a[u][k] = ( ( a[i][k] * v ) - a[u][k] ) % mod; ///Change here if no mod 64 | if ( a[u][k] < 0 ) a[u][k] += mod; 65 | } 66 | } 67 | i++; 68 | } 69 | j++; 70 | } 71 | return i; 72 | } 73 | 74 | void print() { 75 | FOR(i,0,row-1){ 76 | FOR(j,0, col-1){ 77 | printf ( "%d ", a[i][j] ); 78 | } 79 | nl; 80 | } 81 | } 82 | }mat; 83 | -------------------------------------------------------------------------------- /code_templates/geometry_routine.cpp: -------------------------------------------------------------------------------- 1 | #define MAXD 2 2 | 3 | double cosineRule3Side ( double a, double b, double c ) { 4 | double res = (SQ(a)+SQ(b)-SQ(c)) / (2*a*b); 5 | if ( res < -1 ) res = -1; if ( res > 1 ) res = 1; 6 | return acos ( res ); 7 | } 8 | 9 | struct myVec { 10 | int d; //Dimension 11 | double val[MAXD];//Contains value of each component 12 | 13 | myVec() { 14 | d = x; ///Change Here 15 | } 16 | 17 | myVec add ( myVec b ) { 18 | myVec res; FOR(i,0,d-1) res.val[i] = val[i] + b.val[i];return res; 19 | } 20 | myVec sub ( myVec b ) { 21 | myVec res; FOR(i,0,d-1) res.val[i] = val[i] - b.val[i];return res; 22 | } 23 | myVec mul ( double t ) { 24 | myVec res; FOR(i,0,d-1)res.val[i] = val[i] * t;return res; 25 | } 26 | myVec div ( double t ) { 27 | myVec res; FOR(i,0,d-1) res.val[i] = val[i] / t;return res; 28 | } 29 | bool operator == ( myVec b ) { 30 | FOR(i,0,d-1) if ( fabs ( val[i] - b.val[i] ) > eps ) return false; return true; 31 | } 32 | myVec perp2D() { 33 | myVec res = (*this); 34 | swap ( res.val[0], res.val[1] ); 35 | res.val[0] *= -1; 36 | return res; 37 | } 38 | double dot ( myVec v ) { //Finds *this (dot) v 39 | double res = 0; for ( int i = 0; i < d; i++ ) res += val[i] * v.val[i]; 40 | return res; 41 | } 42 | double length () { //Finds length of current vector 43 | return sqrt ( this->dot( *this ) ); 44 | } 45 | myVec unitVec () { 46 | return (*this).div ( length() ); // v / ||v|| 47 | } 48 | 49 | double angleBetween2D ( myVec b ) { 50 | double pol1 = atan2 ( val[1], val[0] ); 51 | double pol2 = atan2 ( b.val[1], b.val[0] ); 52 | if ( pol2 + eps < pol1 ) pol2 += 2 * pi; 53 | 54 | double x = pol2 - pol1; 55 | if ( x > pi + eps ) x = (2*pi) - x; 56 | 57 | //For direction, use sign of cross2D 58 | return x; 59 | } 60 | 61 | //Causes precision error. Use angleBetween2D when 2D. 62 | double angleBetween ( myVec b ) { //Angle between two vectors 63 | double res = dot( b ) / ( length() * b.length() ); 64 | if ( res > 1 ) res = 1; if ( res < -1 ) res = -1; 65 | return acos (res); 66 | } 67 | double polarAngle2D() { //Angle from x-axis 68 | double res = atan2 ( val[1], val[0] ); 69 | if ( res + eps < 0 ) res += 2 * pi; 70 | return res; 71 | } 72 | double cross2D ( myVec v ) { //Cross the two values. Only for 2D. Z compo 0. 73 | return val[0]*v.val[1] - val[1]*v.val[0]; 74 | } 75 | 76 | //Provided, a comes before b. Otherwise, need to swap 77 | bool between ( myVec a, myVec b ) { 78 | if ( val[0] + eps < a.val[0] || val[0] > b.val[0] + eps ) return false; 79 | if ( val[1] + eps < a.val[1] || val[1] > b.val[1] + eps ) return false; 80 | return true; 81 | } 82 | }; 83 | 84 | double triangleArea ( myVec a, myVec b, myVec c ) { 85 | double area = a.val[0] * b.val[1] + b.val[0] * c.val[1] + c.val[0] * a.val[1]; 86 | area -= b.val[0] * a.val[1] + c.val[0] * b.val[1] + a.val[0] * c.val[1]; 87 | area /= 2; 88 | return area; 89 | } 90 | 91 | struct myLine { 92 | myVec a, b; //a is displacement, b is direction. 93 | //Builds a line from two points 94 | myLine lineFromPoints ( myVec x, myVec y ) { 95 | myLine m;m.a = x; m.b = y.sub ( x ); 96 | return m; 97 | } 98 | //Line of the form Ax + By + C = 0 99 | myLine lineFromABC ( double A, double B, double C ) { 100 | if ( fabs (A) <= eps && fabs(B) <= eps ) { 101 | assert(false); 102 | myLine somethingIsWrong; 103 | return somethingIsWrong; 104 | } 105 | else if ( fabs(B) < eps ) { //Vertical Line 106 | double x = -C / A; 107 | myVec p1; 108 | p1.val[0] = x; p1.val[1] = 0; 109 | myVec p2; 110 | p2.val[0] = x; p2.val[1] = 1; 111 | 112 | return lineFromPoints(p1, p2); 113 | }else { 114 | //When x = 0 115 | double y = -C / B; 116 | myVec p1; 117 | p1.val[0] = 0; p1.val[1] = y; 118 | //when x = 1 119 | y = ( -C - A ) / B; 120 | myVec p2; 121 | p2.val[0] = 1; p2.val[1] = y; 122 | 123 | return lineFromPoints(p1, p2); 124 | } 125 | } 126 | //Finds point on line, given t. 127 | myVec atPos ( double t ) { 128 | return a.add ( b.mul ( t ) ); // a + tb; 129 | } 130 | double lineToPointDistance ( myVec p, double &t ) { 131 | p = p.sub ( a ); //Take it to origin 132 | t = b.dot ( p ) / ( b.length() * b.length() ); //point of intersection 133 | myVec x = b.mul ( t ); //tb 134 | return ( p.sub(x).length() ); //xp length() 135 | } 136 | double segmentToPointDistance ( myVec p, double &t ) { 137 | p = p.sub ( a ); //Take it to origin 138 | t = b.dot ( p ) / ( b.length() * b.length() ); 139 | if ( t + eps < 0 || t > 1 + eps ) { //Not on segment 140 | return min ( p.length(), p.sub(b).length() ); 141 | } 142 | myVec x = b.mul ( t ); //tb 143 | return ( p.sub(x).length() ); //xp length() 144 | } 145 | bool overlapParallel ( myLine l ) { 146 | double p, q, r, s; 147 | if ( b.val[0] == 0 ) { 148 | p = a.val[1]; q = atPos(1).val[1]; r = l.a.val[1]; s = l.atPos ( 1 ).val[1]; 149 | if ( min ( r, s ) > max ( p, q ) ) return false; 150 | if ( max ( r, s ) < min ( p, q ) ) return false; 151 | return true; 152 | } 153 | else { 154 | p = a.val[0]; q = atPos(1).val[0]; r = l.a.val[0]; s = l.atPos ( 1 ).val[0]; 155 | if ( min ( r, s ) > max ( p, q ) ) return false; 156 | if ( max ( r, s ) < min ( p, q ) ) return false; 157 | return true; 158 | } 159 | } 160 | char lineAndLineIntersection2D ( myLine l, double &t, double &s ) { 161 | if ( b.cross2D ( l.b) == 0 ) { 162 | if ( l.a.sub(a).cross2D(l.b) == 0 ) { 163 | if ( overlapParallel ( l ) ) return 'o'; //overlaps 164 | else return 'p'; //parallel 165 | } 166 | else return 'd'; //disjoint and parallel 167 | } 168 | myVec w = a.sub ( l.a ); 169 | myVec p = l.b.perp2D(), z = b.perp2D(); 170 | t = -(w.dot(p))/p.dot(b); //for current line 171 | s = w.dot(z)/z.dot(l.b); //for line l 172 | return 'i'; 173 | } 174 | double lineAndLineDistance2D ( myLine l ) { 175 | double t, s; //First check if the intersect 176 | char r = lineAndLineIntersection2D ( l, t, s ); 177 | if ( r == 'i' ) return 0; //Intersects. 0 distance. 178 | //Parallel Lines 179 | return lineToPointDistance ( l.a, t ); 180 | } 181 | double lineAndSegmentDistance2D ( myLine l ) { 182 | double t, s; 183 | char r = lineAndLineIntersection2D ( l, t, s ); 184 | if ( r == 'i' && s + eps > 0 && s < 1 + eps ) { 185 | return 0; //Valid intersection 186 | } 187 | double res = lineToPointDistance ( l.a, t ); 188 | res = min ( res, lineToPointDistance ( l.a.add(l.b), t ) ); 189 | return res; 190 | } 191 | double segmentAndSegmentDistance2D ( myLine l ) { 192 | double t, s; 193 | char r = lineAndLineIntersection2D ( l, t, s ); 194 | if ( r =='i' && t+eps > 0 && t < 1 + eps && s + eps > 0 && s < 1 + eps ) { 195 | return 0; //Valid intersection 196 | } 197 | double res = segmentToPointDistance ( l.a, t ); 198 | res = min ( res, segmentToPointDistance ( l.a.add(l.b), t ) ); 199 | res = min ( res, l.segmentToPointDistance ( a, t ) ); 200 | res = min ( res, l.segmentToPointDistance ( a.add ( b ), t ) ); 201 | return res; 202 | } 203 | myLine reflect ( myVec p, myVec norm ) { 204 | myVec ap = p.sub ( a ); //Starting to Point of Reflection 205 | norm = norm.unitVec(); 206 | 207 | double d = fabs ( ap.dot ( norm ) ); 208 | 209 | myVec m = p.add ( norm.mul ( d ) ); 210 | myVec h = m.sub ( a ).mul ( 2 ); 211 | m = a.add ( h ); 212 | 213 | myLine ray = ray.lineFromPoints ( p, m ); 214 | return ray; 215 | } 216 | }; 217 | 218 | struct myCir { 219 | myVec a; 220 | double r; 221 | myVec atPos ( double t ) { 222 | myVec res; 223 | res.val[0] = a.val[0] + r * cos ( t ); 224 | res.val[1] = a.val[1] + r * sin ( t ); 225 | return res; 226 | } 227 | char circleAndLineIntersection2D ( myLine l, double &t1, double &t2 ) { 228 | double t3; 229 | double d = l.lineToPointDistance ( a, t3 ); 230 | if ( d > r + eps ) return 'd'; 231 | if ( fabs ( d - r ) <= eps ) return 't'; 232 | ///Pass through Center 233 | if ( fabs ( d ) <= eps ) { 234 | t1 = l.b.polarAngle2D(); 235 | t2 = t1 + pi; 236 | return 'i'; 237 | } 238 | 239 | myVec m = l.atPos ( t3 ); 240 | myVec am = m.sub ( a ); 241 | 242 | 243 | double x = am.polarAngle2D(); 244 | double temp = d / r; if ( temp > 1 ) temp = 1; if ( temp < -1 ) temp = -1; 245 | double theta = pi / 2 - asin ( temp ); //Using sin law find internal angle. 246 | 247 | t1 = x + theta; 248 | t2 = x - theta; 249 | return 'i'; 250 | } 251 | char sphereAndLineIntersect ( myLine l, double &t1, double &t2 ) { 252 | double tp = 0; 253 | double d = l.lineToPointDistance ( a, tp ); 254 | if ( d > r + eps ) return 'd'; 255 | if ( fabs ( d - r ) < eps ) { 256 | t1 = tp; 257 | return 't'; 258 | } 259 | double chord = sqrt ( r * r - d * d ); 260 | t1 = tp - chord / l.b.length(); 261 | t2 = tp + chord / l.b.length(); 262 | return 'i'; 263 | } 264 | char circleAndCircleIntersection2D ( myCir c2, double &t1, double &t2 ) { 265 | myVec d = c2.a.sub ( a ); 266 | if ( d.length() > r + c2.r + eps ) return 'd'; //Case 1 267 | if ( d.length() + c2.r + eps < r ) return 'd'; //Case 2 268 | if ( a == c2.a && fabs ( r - c2.r ) <= eps ) { 269 | if ( r == 0 ) { 270 | t1 = 0; 271 | return 't'; //Case 7 272 | } 273 | return 's'; //Case 6 274 | } 275 | if ( fabs ( d.length() - r - c2.r ) <= eps || 276 | fabs ( d.length() + c2.r - r ) <= eps ) { 277 | t1 = d.polarAngle2D(); 278 | return 't'; //Case 3 and 4 279 | } 280 | double theta = cosineRule3Side ( r, d.length(), c2.r ); 281 | double m = d.polarAngle2D (); 282 | t1 = m - theta; 283 | t2 = m + theta; 284 | return 'i'; //Case 5 285 | } 286 | int circleToCircleTangentLine (myCir c2,myLine &l1,myLine &l2,myLine &l3,myLine &l4){ 287 | //First circle must be smaller or equal to second circle 288 | if (r>c2.r + eps ) return c2.circleToCircleTangentLine ( *this, l1, l2, l3, l4 ); 289 | 290 | myVec oo = c2.a.sub ( a ); 291 | double d = oo.length(); 292 | 293 | if ( fabs ( d ) < eps && fabs ( r - c2.r ) < eps ) //Infinite tangents 294 | return -1; 295 | if ( d + r + eps < c2.r ) //No tangents 296 | return 0; 297 | 298 | double base = oo.polarAngle2D(); 299 | 300 | if ( fabs ( d + r - c2.r ) < eps ) { //Contains Circle 301 | l1 = l1.lineFromPoints ( atPos ( base + pi ), atPos ( base + pi ) ); 302 | return 1; 303 | } 304 | 305 | double ang = pi - acos ( (c2.r - r ) / d ); 306 | l1 = l1.lineFromPoints ( atPos ( base + ang ), c2.atPos ( base + ang ) ); 307 | l2 = l2.lineFromPoints ( atPos ( base - ang ), c2.atPos ( base - ang ) ); 308 | 309 | if ( d + eps < r + c2.r ) return 2; //Circle intersects 310 | 311 | if ( fabs ( d - r - c2.r ) < eps ) { //Circle tangent 312 | l3 = l3.lineFromPoints ( atPos ( base ), atPos ( base ) ); 313 | return 3; 314 | } 315 | 316 | //Disjoint Circle 317 | ang = acos ( ( c2.r + r ) / d ); 318 | l3 = l3.lineFromPoints ( atPos ( base + ang ), c2.atPos ( base + ang + pi ) ); 319 | l4 = l4.lineFromPoints ( atPos ( base - ang ), c2.atPos ( base - ang + pi ) ); 320 | 321 | return 4; 322 | } 323 | 324 | //Used to find intersection area between circle and polygon 325 | double circleToLineArea ( myLine l ) { 326 | if ( l.a == l.atPos(1) ) return 0; 327 | double t; 328 | double d = l.segmentToPointDistance ( a, t ); 329 | 330 | //Segment Outside, no intersection 331 | if ( d + eps > r ) { 332 | double dif = l.a.sub(a).angleBetween(l.atPos(1).sub(a)); 333 | double area = dif/2 * r * r; 334 | if ( triangleArea (a,l.a,l.atPos(1) ) + eps < 0 ) area *= -1; 335 | return area; 336 | } 337 | 338 | //Segment inside full 339 | double d1 = l.a.sub(a).length(); 340 | double d2 = l.atPos(1).sub(a).length(); 341 | if ( d1 < r + eps && d2 < r + eps ) { 342 | double area = triangleArea ( a, l.a, l.atPos(1) ); 343 | return area; 344 | } 345 | 346 | //seg points outside but intersects print 347 | if ( d1 + eps > r && d2 + eps > r ) { 348 | double t1, t2; 349 | circleAndLineIntersection2D ( l, t1, t2 ); 350 | if ( l.a.sub(atPos(t2)).length() + eps < l.a.sub(atPos(t1)).length() ) { 351 | swap ( t1, t2 ); 352 | } 353 | double area = 0; 354 | area += circleToLineArea ( l.lineFromPoints(l.a,atPos(t1)) ); 355 | area += circleToLineArea ( l.lineFromPoints(atPos(t1),atPos(t2)) ); 356 | area += circleToLineArea ( l.lineFromPoints(atPos(t2),l.atPos(1) ) ); 357 | return area; 358 | } 359 | 360 | //Half in, half out 361 | double t1, t2; 362 | circleAndLineIntersection2D ( l, t1, t2 ); 363 | double it; 364 | if ( atPos(t1).between( l.a, l.atPos(1) ) || atPos(t1).between(l.atPos(1), l.a) ) it = t1; 365 | else it = t2; 366 | double area = 0; 367 | area += circleToLineArea ( l.lineFromPoints ( l.a, atPos(it) ) ); 368 | area += circleToLineArea ( l.lineFromPoints ( atPos(it), l.atPos(1) ) ); 369 | return area; 370 | } 371 | 372 | }; 373 | 374 | bool collinear ( myVec a, myVec b, myVec c ) { 375 | myVec ab = b.sub(a), ac = c.sub(a); 376 | double d = fabs ( ab.dot(ac) ); 377 | if ( fabs ( d - ab.length() * ac.length() ) <= eps ) return true; 378 | return false; 379 | } 380 | 381 | //Find if C is between A and B or B and A 382 | bool pointBetween ( pii a, pii b, pii c ) { 383 | if ( MIN(a.ff,b.ff) <= c.ff && c.ff <= MAX(a.ff,b.ff) && MIN(a.ss,b.ss) <= c.ss && c.ss <= MAX(a.ss,b.ss) ) return true; 384 | else return false; 385 | } 386 | 387 | //Determine if (a,b) and (c,d) segment intersects. All points are integer 388 | bool segmentIntersection ( pii a, pii b, pii c, pii d ) { 389 | 390 | vlong s1 = triArea( a, b, c ); 391 | vlong s2 = triArea( a, b, d ); 392 | vlong s3 = triArea( c, d, a ); 393 | vlong s4 = triArea( c, d, b ); 394 | 395 | if ( s1 < 0 ) s1 = -1; else if ( s1 > 0 ) s1 = 1; 396 | if ( s2 < 0 ) s2 = -1; else if ( s2 > 0 ) s2 = 1; 397 | if ( s3 < 0 ) s3 = -1; else if ( s3 > 0 ) s3 = 1; 398 | if ( s4 < 0 ) s4 = -1; else if ( s4 > 0 ) s4 = 1; 399 | 400 | if ( s1 * s2 > 0 || s3 * s4 > 0 ) return false; 401 | 402 | if ( s1 && s2 && s3 && s4 ) return true; 403 | if ( s1 == 0 && pointBetween ( a, b, c ) ) return true; 404 | else if ( s2 == 0 && pointBetween ( a, b, d ) ) return true; 405 | else if ( s3 == 0 && pointBetween ( c, d, a ) ) return true; 406 | else if ( s4 == 0 && pointBetween ( c, d, b ) ) return true; 407 | 408 | return false; 409 | } 410 | 411 | 412 | /* 413 | Shooting Ray 414 | 415 | For any point (x,y), shoot a ray towards ( x + 10^9+7, y + 10^9 + 9 ), any large coprime numbers so that no integer points fall on the ray. 416 | 417 | Next find the intersection of all edges of polygon with the ray. If intersection is odd, then inside. 418 | 419 | But ray shooting cannot handle points on boundary. So manually check if the give point is on boundary of an edge. 420 | 421 | if ( onboundary ) handle it 422 | else if ( intersect is odd ) inside 423 | else outside 424 | */ 425 | 426 | -------------------------------------------------------------------------------- /code_templates/heavy_light_decomposition.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | 1. First clear the hld class: hld.clear(n, root) 3 | 2. Call hld.decompose() to create the chains and other preprocessing 4 | 3. Call hld.getPath(a, b) to get vector> segments of path 5 | 4. Call hld.getLCA(a, b) to get their lca 6 | */ 7 | 8 | class HLD { 9 | private: 10 | const static int NODE = 10010; 11 | 12 | vector adj[NODE]; 13 | int root, node; 14 | 15 | int par[NODE], level[NODE]; 16 | 17 | void dfs (int u, int p) { 18 | par[u] = p; /// Set parent of u 19 | child[u] = 1; 20 | if (p == -1) level[u] = 0; 21 | else level[u] = level[p] + 1; 22 | 23 | for ( int i = 0; i < adj[u].size(); i++ ) { 24 | int v = adj[u][i]; 25 | if ( v == p ) continue; /// Don't go back to parent 26 | dfs(v, u); 27 | child[u] += child[v]; 28 | } 29 | } 30 | 31 | int chainLeader, arrayPos; 32 | int leader[NODE]; 33 | void hld (int u, int newChain) { 34 | if (newChain) { 35 | chainLeader = u; 36 | } 37 | leader[u] = chainLeader; 38 | linearPos[u] = arrayPos++; 39 | linearTree.push_back(u); 40 | 41 | int bigChild = -1, subTreeSize = -1; 42 | for ( int i = 0; i < adj[u].size(); i++ ) { 43 | int v = adj[u][i]; 44 | if ( v == par[u] ) continue; 45 | if ( child[v] > subTreeSize ) { 46 | subTreeSize = child[v]; 47 | bigChild = v; 48 | } 49 | } 50 | 51 | if ( bigChild != -1 ) { 52 | hld(bigChild, 0); 53 | } 54 | 55 | for ( int i = 0; i < adj[u].size(); i++ ) { 56 | int v = adj[u][i]; 57 | if ( v == par[u] ) continue; 58 | if ( v == bigChild ) continue; 59 | hld(v, 1); 60 | } 61 | } 62 | 63 | public: 64 | vector linearTree; 65 | int child[NODE], linearPos[NODE]; 66 | 67 | HLD() {} 68 | 69 | void clear( int _node, int _root) { 70 | node = _node; 71 | root = _root; 72 | arrayPos = 0; 73 | 74 | for ( int i = 0; i <= node; i++ ) { 75 | adj[i].clear(); 76 | } 77 | 78 | linearTree.clear(); 79 | } 80 | 81 | void addUndirectedEdge(int u, int v) { 82 | adj[u].push_back(v); 83 | adj[v].push_back(u); 84 | } 85 | 86 | void decompose() { 87 | dfs(root, -1); 88 | hld(root, 1); 89 | } 90 | 91 | vector> getPath ( int a, int b ) { 92 | vector> pathSegments; 93 | 94 | if ( level[a] < level[b] ) swap(a, b); 95 | 96 | while ( 1 ) { 97 | int lead = leader[a]; 98 | 99 | if (level[lead] > level[b]) { 100 | /// Jump to lead 101 | pathSegments.push_back({linearPos[lead], linearPos[a]}); 102 | a = par[lead]; 103 | } else { 104 | /// On same chain 105 | pathSegments.push_back({linearPos[b], linearPos[a]}); 106 | break; 107 | } 108 | } 109 | 110 | return pathSegments; 111 | } 112 | 113 | int getLCA ( int a, int b ) { 114 | while (leader[a] != leader[b]) { 115 | if (level[leader[a]] < level[leader[b]]) 116 | b = par[leader[b]]; 117 | else 118 | a = par[leader[a]]; 119 | } 120 | if (level[a] < level[b]) { 121 | return a; 122 | } 123 | return b; 124 | } 125 | }hld; 126 | -------------------------------------------------------------------------------- /code_templates/kmp.cpp: -------------------------------------------------------------------------------- 1 | //WARNING: Arrays are 1-based index. 2 | 3 | const int LENGTH = XYZ; 4 | char text[LENGTH], pat[LENGTH]; 5 | int pre[LENGTH]; 6 | 7 | void compute () { 8 | int plen = strlen ( pat + 1 ), k = 0; 9 | pre[1] = 0; 10 | for ( int i = 2; i <= plen; i++ ) { 11 | while ( k && pat[k+1] != pat[i] ) k = pre[k]; 12 | if ( pat[k+1] == pat[i] ) k++; 13 | pre[i] = k; 14 | } 15 | } 16 | int match () { 17 | int tlen = strlen ( text + 1 ), plen = strlen ( pat + 1 ); 18 | int q = 0, res = 0; 19 | for ( int i = 1; i <= tlen; i++ ) { 20 | while ( q && pat[q+1] != text[i] ) q = pre[q]; 21 | 22 | if ( pat[q+1] == text[i] ) q++; 23 | if ( q == plen ) { 24 | res++; 25 | q = pre[q]; 26 | } 27 | } 28 | return res; 29 | } 30 | 31 | /// Application 32 | /// Period of a string. N - pre[N] is the length of period iff period length divides N. 33 | -------------------------------------------------------------------------------- /code_templates/kuhn.cpp: -------------------------------------------------------------------------------- 1 | // Kuhn's Algo for finding Maximum matching 2 | 3 | // README 4 | // 5 | // How to use it: 6 | // 1. Take an instance of KUHN structure. Let it be called kuhn 7 | // 2. Clear the instance: kuhn.clear(n) 8 | // 3. Build the graph by pushing edges to adj[NODE]. If an edge goes from u to v, 9 | // where u is memeber of left side and v is member of right side, then: 10 | // adj[u].push_back(v) 11 | // 3. Get maximum matching by calling: kuhn.match(n) 12 | // 4. Who is matched with whom is stored in left[] and right[] 13 | // 5. If you want to print vertex cover, call kuhn.findVertexCover(n). Then, 14 | // membership of vertex cover is stored in lcover[] and rcover[] 15 | 16 | struct KUHN{ 17 | int left[NODE]; // Contains who is matched with ith vertex on left side 18 | int right[NODE]; // Contains who is matched with ith vertex on right side 19 | int vis[2*NODE]; ///Node double in vis for vertex print 20 | int cc; 21 | vector adj[NODE]; // For each node on left side, push its neighbor here 22 | 23 | KUHN() : cc(1) {} 24 | 25 | void clear( int n ) { 26 | FOR(i,0,n) adj[i].clear(); 27 | } 28 | 29 | bool tryK ( int v ) { 30 | if ( vis[v] == cc ) return false; 31 | vis[v] = cc; 32 | for ( int i = 0; i < SZ(adj[v]); i++ ) { 33 | int t = adj[v][i]; 34 | if ( right[t] == -1 ) { 35 | right[t] = v; left[v] = t; 36 | return true; 37 | } 38 | } 39 | for ( int i = 0; i < SZ(adj[v]); i++ ) { 40 | int t = adj[v][i]; 41 | if ( tryK ( right[t] ) ) { 42 | right[t] = v; left[v] = t; 43 | return true; 44 | } 45 | } 46 | return false; 47 | } 48 | 49 | int match(int n) { 50 | int res = 0; 51 | bool done; 52 | CLR(left,-1); CLR(right,-1); 53 | do { 54 | done = true; cc++; 55 | FOR(i,0,n) { 56 | if(left[i]==-1 && tryK(i)) { 57 | done = false; 58 | } 59 | } 60 | } while(!done); 61 | FOR(i,0,n) res += (left[i]!=-1); 62 | return res; 63 | } 64 | 65 | ///Careful. Loop runs from 0 to n-1 66 | ///Make sure match() has been run 67 | int lcover[NODE]; // If lcover[i] is 1, then ith node of left side is a member of vertex cover 68 | int rcover[NODE]; // If rcover[i] is 1, then ith node of right side is a member of vertex cover 69 | void findVertexCover ( int n ) { 70 | queue q; 71 | cc++; 72 | FOR(i,0,n-1){ 73 | if ( left[i] == -1 ) { 74 | q.push ( i ); 75 | vis[i] = cc; 76 | } 77 | }; 78 | 79 | while ( !q.empty() ) { 80 | int s = q.front(); q.pop(); 81 | FOR(i,0,SZ(adj[s])-1){ 82 | int t = adj[s][i]; 83 | if ( t == left[s] ) continue; 84 | 85 | int xt = t + n; 86 | if ( vis[xt] == cc ) continue; 87 | 88 | vis[xt] = cc; 89 | xt = right[t]; 90 | 91 | if ( xt != -1 && vis[xt] != cc ) { 92 | vis[xt] = cc; 93 | q.push ( xt ); 94 | } 95 | 96 | }; 97 | } 98 | 99 | FOR(i,0,n-1){ 100 | if ( vis[i] != cc ) lcover[i] = 1; 101 | else lcover[i] = 0; 102 | }; 103 | FOR(i,0,n-1){ 104 | if ( vis[i+n] == cc ) rcover[i] = 1; 105 | else rcover[i] = 0; 106 | }; 107 | 108 | } 109 | }kuhn; 110 | -------------------------------------------------------------------------------- /code_templates/linear_diophantine_equation.cpp: -------------------------------------------------------------------------------- 1 | //Returns char according to kind of solution 2 | //Ax + By = C Run+ Rise- 3 | //AX + (-B)y = C Run+ Rise+ 4 | //When changing X, steps are either d/run or (d+run-1)/run depending on crossing or not. 5 | //When changing Y, steps are same as X, but take ABS(Rise) and assign sign to step. 6 | //Always assign sign to steps and ADD values to x and y. 7 | 8 | 9 | struct LinearDiphontine { 10 | vlong a, b, c, x, y, run, rise; 11 | char solution; 12 | 13 | char solve () { 14 | if ( a == 0 && b == 0 ) { 15 | if ( c == 0 ) { 16 | //Infinite solutions. Anything works 17 | return solution = 'i'; 18 | } 19 | else return solution = '0'; //No solution 20 | } 21 | if ( a == 0 || b == 0 ) { 22 | //Vertical or Horizontal Line 23 | if ( !a ) { 24 | if ( c % b != 0 ) return solution = '0'; /// No Solution 25 | run = 1; rise = 0; 26 | return solution = 'h'; /// ( anything, c / b ) 27 | } 28 | else { 29 | if ( c % a != 0 ) return solution = '0'; ///No Solution 30 | run = 0; rise = 1; 31 | return solution = 'v'; /// ( c / a , anything ) 32 | } 33 | } 34 | 35 | vlong g = ext_gcd( a, b, &x, &y ); 36 | if ( c % g != 0 ) { 37 | //No solution 38 | return solution = '0'; 39 | } 40 | 41 | a /= g; b /= g; c /= g; 42 | 43 | ext_gcd ( a, b, &x, &y ); 44 | x *= c; y *= c; 45 | 46 | ///run and rise calculation 47 | run = b; rise = -a; 48 | if ( run < 0 ) { 49 | run *= -1; rise *= -1; 50 | } 51 | 52 | return solution = '1'; 53 | } 54 | 55 | ///Move solution near to vertical line x = p 56 | void moveNearVerticalLine( int p ) { 57 | if ( run == 0 ) return; /// Both are vertical 58 | vlong jump = ( p - x ) / run; 59 | x += jump * run; 60 | y += jump * rise; 61 | 62 | if ( x < p ) { ///Keep solution on right of the line 63 | x += run; 64 | y += rise; 65 | } 66 | } 67 | 68 | void moveNearHorizontalLine( int p ) { 69 | if ( rise == 0 ) return; /// Both are horizontal 70 | vlong jump = ( p - y ) / rise; 71 | x += jump * run; 72 | y += jump * rise; 73 | 74 | if ( y < p ) { ///Keep solution above the line 75 | if ( rise > 0 ) { 76 | x += run; 77 | y += rise; 78 | } 79 | else { 80 | x -= run; 81 | y -= rise; 82 | } 83 | } 84 | } 85 | }; 86 | -------------------------------------------------------------------------------- /code_templates/lis.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Finds only LIS. LDS can be found by simply multiplying the whole input array with -1. 3 | For Longest Non-Decreasing sequence, simply use upper_bound(). 4 | Complexity: NlogK 5 | */ 6 | struct LIS { 7 | int bbb[NSIZE+10]; 8 | 9 | int calculateLIS ( int arr[], int lisVal[], int n ) { 10 | FOR(i,0,n) { 11 | bbb[i] = inf; 12 | } 13 | bbb[0] = -inf; 14 | 15 | int mx = 0; 16 | FOR(i,0,n-1) { 17 | int v = arr[i]; 18 | int pos = lower_bound ( bbb, bbb + mx + 1, v ) - bbb; 19 | lisVal[i] = pos; 20 | bbb[pos] = v; 21 | mx = MAX(mx,pos); 22 | } 23 | 24 | return mx; 25 | } 26 | }lis; 27 | -------------------------------------------------------------------------------- /code_templates/lowest_common_ancestor.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 1. Set N and root using setNM(). Here N is the largest index of node. No need to worry about 0/1 based indexing 3 | 2. Add Edges using addEdge 4 | 3. Call precal() 5 | 4. Ready to query findLCA(u,v) 6 | */ 7 | struct LCA{ 8 | private: 9 | int tab[LCANODE][LCADEPTH], par[LCANODE], lev[LCANODE], vis[LCANODE], q[LCANODE], cc, N, M, root; 10 | vi adj[LCANODE]; 11 | 12 | void bfs ( int s ) { 13 | vis[s] = cc; lev[s] = 0; par[s] = -1; ///Set par[root] = -1 14 | 15 | int qh = 0, qt = 0, t; 16 | q[qt++] = s; 17 | while ( qh < qt ) { 18 | s = q[qh++]; 19 | FOR(i,0,SZ(adj[s])-1){ 20 | t = adj[s][i]; 21 | if ( vis[t] != cc ) { 22 | par[t] = s; 23 | vis[t] = cc; 24 | lev[t] = lev[s] + 1; 25 | q[qt++] = t; 26 | } 27 | } 28 | } 29 | } 30 | 31 | void calculate (){ 32 | int i,j,p; 33 | for (i=0;i<=N;i++){ 34 | tab[i][0]=par[i]; 35 | } 36 | 37 | for(i=1;i<=M;i++){ 38 | for(j=0;j<=N;j++){ 39 | p=tab[j][i-1]; 40 | if(p==-1) tab[j][i]=-1; 41 | else tab[j][i]=tab[p][i-1]; 42 | } 43 | } 44 | } 45 | void clear () { 46 | cc++; 47 | FOR(i,0,N) adj[i].clear(); 48 | } 49 | 50 | public: 51 | LCA() { 52 | cc = 1; 53 | } 54 | 55 | void setVar ( int n, int r ) { 56 | N = n; 57 | M = 0; ///Dynamically Set Depth 58 | int temp = n+1; ///Cause of 0 based index 59 | while ( temp ) { 60 | M++; 61 | temp /= 2; 62 | } 63 | root = r; 64 | clear(); 65 | } 66 | 67 | void addEdge ( int u, int v ) { 68 | adj[u].pb ( v ); 69 | } 70 | void precal () { 71 | bfs ( root ); ///Does not handle forest. Run a loop for that. 72 | calculate(); 73 | } 74 | int findLCA(int s,int t){ 75 | int dif,pos,i; 76 | if(lev[s]!=lev[t] ) { 77 | if(lev[s]>lev[t]) swap( s, t ); 78 | dif=lev[t]-lev[s]; 79 | while(dif){ 80 | pos=RIGHTMOST(dif); 81 | t=tab[t][pos]; 82 | dif-=1<=0;i--){ 87 | if(tab[s][i]!=tab[t][i]){ 88 | s=tab[s][i]; 89 | t=tab[t][i]; 90 | } 91 | } 92 | return tab[s][0]; 93 | } 94 | }; 95 | -------------------------------------------------------------------------------- /code_templates/manacher_algorithms.cpp: -------------------------------------------------------------------------------- 1 | #define MANALEN 200100 2 | /// Warning: Make MANALEN double of string length 3 | 4 | /* 5 | 1. First assign string to manacher, arr[] 6 | 2. Call init 7 | 3. Call Preprocess to convert string 8 | 4. Call calc to calculate array p[] 9 | */ 10 | 11 | struct MANACHER { 12 | char arr[MANALEN+10], brr[MANALEN+10]; 13 | int p[MANALEN+10]; 14 | int an, bn, mxpalin, mxcenter; 15 | 16 | void init() { 17 | //Assign string to arr 18 | an = strlen ( arr ); 19 | } 20 | 21 | //aba -> ^#a#b#a#$ 22 | void preprocess() { 23 | int cur = 0; 24 | brr[cur++] = '^'; 25 | FOR(i,0,an-1) { 26 | brr[cur++] = '#'; 27 | brr[cur++] = arr[i]; 28 | } 29 | brr[cur++] = '#'; 30 | brr[cur++] = '$'; 31 | brr[cur] = 0; 32 | bn = cur; 33 | } 34 | 35 | ///For each possible center, length of palindrome it can create. 36 | ///Careful, this length is without # 37 | void calc() { 38 | int c = 0, r = 0; 39 | FOR(i,1,bn-2) { 40 | int mi = c - (i-c); 41 | 42 | p[i] = (r > i )? MIN ( r - i, p[mi] ): 0; 43 | 44 | while ( brr[i+p[i]+1] == brr[i-p[i]-1] ) { 45 | p[i]++; 46 | } 47 | 48 | if ( i + p[i] > r ) { 49 | r = i + p[i]; 50 | c = i; 51 | } 52 | } 53 | 54 | mxpalin = 0; mxcenter = 0; 55 | ///Notice we don't multiply 2 with p[i], cause more than half of them are # 56 | FOR(i,1,bn-2) { 57 | if ( p[i] > mxpalin ) { 58 | mxpalin = p[i]; 59 | mxcenter = i; 60 | } 61 | } 62 | ///In brr[], for each center, the palindrome extends from i-p[i] to i+p[i] 63 | } 64 | }mana; 65 | -------------------------------------------------------------------------------- /code_templates/matrix_expo.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 1. Assign MATMOD 3 | 2. Declare MAT win row and col. 4 | */ 5 | 6 | vlong MATMOD; 7 | struct MAT{ 8 | vlong a[x][x];///Maximum dimension of the matrix 9 | int row, col; 10 | MAT(){} 11 | MAT(int r, int c){ 12 | row = r; 13 | col = c; 14 | mem(); 15 | } 16 | void assign ( int r, int c ) { 17 | row = r; 18 | col = c; 19 | } 20 | 21 | void identity(){ 22 | mem(); 23 | for ( int i = 0; i < row; i++ ) a[i][i] = 1; 24 | } 25 | void mem(){ 26 | memset ( a, 0, sizeof a ); 27 | } 28 | void print() { ///For debugging purpose 29 | for ( int i = 0; i < row; i++ ){ 30 | for ( int j = 0; j < col; j++ ) printf ( "%llu ", a[i][j] ); 31 | printf ( "\n" ); 32 | } 33 | } 34 | MAT operator * ( MAT b ) { ///Matrix Multiplication N^3 35 | MAT res ( row, b.col ); 36 | 37 | for ( int i = 0; i < row; i++ ){ 38 | for ( int j = 0; j < b.col; j++ ){ 39 | for ( int k = 0; k < col; k++ ) 40 | res.a[i][j] = ( res.a[i][j] + a[i][k] * b.a[k][j] ) % MATMOD; ///Change here if no mod. 41 | } 42 | } 43 | return res; 44 | } 45 | MAT operator ^ ( vlong p ) { ///Matrix Exponentiation 46 | MAT res ( row, col ); res.identity(); 47 | MAT x = *this; 48 | while ( p ){ 49 | if ( p & 1 ){ 50 | res = res * x; 51 | } 52 | x = x * x; 53 | p >>= 1; 54 | } 55 | return res; 56 | } 57 | }; 58 | -------------------------------------------------------------------------------- /code_templates/miller_rabin_primality_test.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | 1. Works for n <= 2^64 3 | 2. Uses at most 7 witnesses. 4 | 3. Complexity: O( k log^3 n ), where k = 7 5 | 6 | Complexity should be reduced by log(n) factor since I used __int128 instead of mul_mod(), 7 | but lets just consider it 8 | 9 | How to use it? 10 | You just call the only public method of the class, isPrime(n) and get boolean result. 11 | */ 12 | 13 | typedef long long vlong; 14 | 15 | class MillerRabin { 16 | private: 17 | 18 | /** https://miller-rabin.appspot.com/ confirms that the following base covers 2^64**/ 19 | vlong prime[7] = { 2, 325, 9375, 28178, 450775, 9780504, 1795265022 }; 20 | int psize = 7; 21 | 22 | vlong bigmod ( __int128 a, __int128 p, vlong mod ) { 23 | __int128 x = a % mod, res = 1; 24 | while ( p ) { 25 | if ( p & 1 ) res = res * x % mod; 26 | x = x * x % mod; 27 | p >>= 1; 28 | } 29 | return res; 30 | } 31 | 32 | ///Witness to compositeness of n 33 | ///n - 1 = 2^s * d, where d is odd 34 | bool witness ( vlong a, vlong d, vlong s, vlong n ) { 35 | __int128 r = bigmod( a, d, n ); 36 | if ( r == 1 || r == n - 1 ) return false; 37 | int i; 38 | for ( i = 0; i < s - 1; i++ ) { 39 | r = r * r % n; 40 | if ( r == 1 ) return true; 41 | if ( r == n - 1 ) return false; 42 | } 43 | return true; 44 | } 45 | 46 | public: 47 | bool isPrime ( vlong n ) { 48 | if ( n <= 1 ) return false; 49 | 50 | vlong p = n - 1, s = 0; 51 | while ( ! ( p & 1 ) ) { 52 | p /= 2; 53 | s++; 54 | } 55 | vlong d = p; 56 | p = n - 1; 57 | 58 | for ( int i = 0; i < psize && prime[i] < n; i++ ) { 59 | if ( witness ( prime[i], d, s, n ) ) return false; 60 | } 61 | return true; 62 | } 63 | } millerRabin; 64 | -------------------------------------------------------------------------------- /code_templates/minimum_expression.cpp: -------------------------------------------------------------------------------- 1 | ///Returns the smallest index which is lexicographically smallest rotation 2 | inline int minimumExpression(char *s) { 3 | int i, j, k, n, len, p, q; 4 | len = n = strlen(s), n <<= 1, i = 0, j = 1, k = 0; 5 | while(i + k < n && j + k < n) { 6 | p = i+k >= len ? s[i+k-len] : s[i+k]; 7 | q = j+k >= len ? s[j+k-len] : s[j+k]; 8 | if(p == q) k++; 9 | else if(p > q) { i = i+k+1; if(i <= j) i = j+1; k = 0; } 10 | else if(p < q) { j = j+k+1; if(j <= i) j = i+1; k = 0; } 11 | } 12 | return i < j ? i : j; 13 | } -------------------------------------------------------------------------------- /code_templates/mobius_function.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Mobius function is a function which has one of the following values: 3 | mu(x) = -1 : square free number with odd prime factors 4 | mu(x) = 1 : square free number with even prime factors 5 | mu(x) = 0 : not a square free number 6 | 7 | In order to generate mu() from 1-N, we need to generate all primes between 1-N 8 | */ 9 | 10 | void sieve( int n ); ///generates prime from 1-N 11 | 12 | int mobius[SIZE+10]; 13 | void mobiusCalc( int n ) { 14 | FOR(i,1,n) mobius[i] = 1; ///Initially all value is 1 15 | 16 | ///Mark all numbers with square factors 0 17 | int sqrtn = sqrt ( n ); 18 | FOR(i,0,SZ(prime)-1) { 19 | if ( prime[i] > sqrtn ) break; 20 | 21 | int x = prime[i] * prime[i]; 22 | for ( int j = x; j <= n; j += x ) mobius[j] = 0; 23 | } 24 | 25 | ///For each prime, all it's multiple gets multiplied by -1 26 | FOR(i,0,SZ(prime)-1) { 27 | for ( int j = prime[i]; j <= n; j += prime[i] ) mobius[j] *= -1; 28 | } 29 | } 30 | 31 | /*Application of Mobius function 32 | It is mainly used with inclusion exclusion, when items are the first K primes. 33 | Complexity is improved from 2^k to NloglogN 34 | */ 35 | -------------------------------------------------------------------------------- /code_templates/pascal_triangle.cpp: -------------------------------------------------------------------------------- 1 | #define BIOSIZE 0 2 | 3 | struct BIONOMIAL { 4 | vlong n, k, val; 5 | 6 | void goDown() { 7 | vlong a = n + 1, b = n - k + 1; vlong g = gcd ( a, b ); a /= g; b /= g; 8 | val /= b; val *= a; 9 | n++; 10 | } 11 | void goRight() { 12 | if ( k + 1 > n ) { 13 | k = n + 1; 14 | val = 0; 15 | return; 16 | } 17 | vlong a = n - k, b = k + 1; vlong g = gcd ( a, b ); a /= g; b /= g; 18 | val /= b; val *= a; 19 | k++; 20 | } 21 | 22 | void assign ( vlong _n, vlong _k, vlong _val ) { 23 | n = _n; k = _k; val = _val; 24 | } 25 | 26 | void clear () { 27 | //CLR(memo,-1); 28 | } 29 | 30 | //Calculate NCK 31 | int memo[BIOSIZE][BIOSIZE]; 32 | vlong nck ( int n, int k ) { 33 | if ( memo[n][k] != -1 ) return memo[n][k]; 34 | if ( k == 0 ) return 1; 35 | if ( n == 0 ) return 0; 36 | 37 | memo[n][k] = nck ( n - 1, k ) + nck ( n - 1, k - 1 ); 38 | return memo[n][k]; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /code_templates/pollard_rho.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | Dependencies: 3 | 1. MillerRabin 4 | 5 | How to Use it? 6 | 1. Call pollardRho.clear(); 7 | 2. Call pollardRho.getPrimeFactorization(n); 8 | 9 | See sample main() function below 10 | */ 11 | 12 | class PollardRho { 13 | private: 14 | 15 | MillerRabin millerRabin; 16 | 17 | int prime[50000], status[50000], primeSize; 18 | void sieve() { 19 | primeSize = 0; 20 | memset( status, 0, sizeof status ); 21 | 22 | status[0] = status[1] = 1; 23 | int n = 46340; 24 | for ( int i = 4; i <= n; i += 2 ) status[i] = 1; 25 | 26 | int sqrtn = sqrt(n); 27 | for ( int i = 3; i <= sqrtn; i += 2 ){ 28 | for ( int j = i*i; j <= n; j += 2 * i ) { 29 | status[j] = 1; 30 | } 31 | } 32 | 33 | prime[primeSize++] = 2; 34 | for ( int i = 3; i <= n; i += 2 ) { 35 | if ( status[i] == 0 ) { 36 | prime[primeSize++] = i; 37 | } 38 | } 39 | } 40 | 41 | void factorizeWithSieve(int n) { 42 | int sqrtn = sqrt(n); 43 | for ( int i = 0; i < primeSize && prime[i] <= sqrtn; i++ ) { 44 | if ( n % prime[i] == 0 ) { 45 | while ( n % prime[i] == 0 ) { 46 | factors.push_back(prime[i]); 47 | n /= prime[i]; 48 | } 49 | sqrtn = sqrt(n); 50 | } 51 | } 52 | if ( n != 1 ) { 53 | factors.push_back(n); 54 | } 55 | } 56 | 57 | vlong pollard_rho( vlong n, vlong c ) { 58 | vlong y = 2, i = 1, k = 2, d; 59 | __int128 x = 2; 60 | while (true) { 61 | x = x * x % n + c; 62 | if (x >= n) x -= n; 63 | d = __gcd((vlong)x - y, n); 64 | if (d > 1) return d; 65 | if (++i == k) { 66 | y = x, k <<= 1; 67 | } 68 | } 69 | return n; 70 | } 71 | 72 | void factorize(vlong n) { 73 | if (n == 1) 74 | return ; 75 | if (n < 1e+9) { 76 | factorizeWithSieve(n); 77 | return ; 78 | } 79 | if (millerRabin.isPrime(n)) { 80 | factors.push_back(n); 81 | return ; 82 | } 83 | vlong d = n; 84 | for (int i = 2; d == n; i++) { 85 | d = pollard_rho(n, i); 86 | } 87 | factorize(d); 88 | factorize(n/d); 89 | } 90 | 91 | public: 92 | 93 | vector factors; 94 | 95 | PollardRho() { 96 | sieve(); 97 | } 98 | 99 | void clear() { 100 | factors.clear(); 101 | } 102 | 103 | vector> getPrimeFactorization(vlong n) { 104 | factorize(n); 105 | sort(factors.begin(), factors.end()); 106 | 107 | vector> res; 108 | for( int i = 0; i < factors.size(); i++ ) { 109 | vlong p = factors[i]; 110 | int cnt = 1; 111 | while ( i + 1 < factors.size() && factors[i+1] == p) { 112 | i++; 113 | cnt++; 114 | } 115 | res.push_back({p,cnt}); 116 | } 117 | 118 | return res; 119 | } 120 | }pollardRho; 121 | 122 | /***************************/ 123 | 124 | int main() { 125 | int n = 1e16+8; 126 | 127 | pollardRho.clear(); /// Don't forget to clear. Important for multi case. 128 | prime> factors = pollardRho.getPrimeFactorization(n); 129 | for ( int i = 0; i < factors.size(); i++ ) { 130 | int p = factors[i].first; 131 | int a = factors[i].second; 132 | 133 | /// p^a is factor of n 134 | /// Do your work here 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /code_templates/prufer_code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Tree to Prufer Code 3 | Works for both 0 and 1 indexed node numbering 4 | Complexity: O(VlogV) 5 | */ 6 | 7 | vector treeToPruferCode (int nodes, vector> &edges) { 8 | unordered_set neighbors[nodes+1]; // For each node, who is it's neighbor? 9 | 10 | for( int i = 0; i < edges.size(); i++ ) { 11 | pair edge = edges[i]; 12 | int u = edges[i].first; int v = edges[i].second; 13 | neighbors[u].insert(v); 14 | neighbors[v].insert(u); 15 | } 16 | 17 | priority_queue leaves; 18 | for ( int i = 0; i <= nodes; i++ ) { 19 | if (neighbors[i].size() == 1 ) { 20 | leaves.push(-i); // Negating since we need min heap 21 | } 22 | } 23 | vector pruferCode; 24 | int need = nodes - 2; 25 | while(need--) { 26 | int leaf = -leaves.top(); leaves.pop(); 27 | int neighborOfLeaf = *(neighbors[leaf].begin()); 28 | pruferCode.push_back(neighborOfLeaf); 29 | // Remove the leaf 30 | neighbors[neighborOfLeaf].erase(leaf); 31 | // The neighbor can become a new leaf 32 | if(neighbors[neighborOfLeaf].size() == 1) { 33 | leaves.push(-neighborOfLeaf); 34 | } 35 | } 36 | return pruferCode; 37 | } 38 | 39 | /* 40 | Prufer Code to Tree 41 | Complexity: O(VlogV) 42 | */ 43 | 44 | vector> pruferCodeToTree(vector &pruferCode) { 45 | // Stores number count of nodes in the prufer code 46 | unordered_map nodeCount; 47 | 48 | // Set of integers absent in prufer code. They are the leaves 49 | set leaves; 50 | 51 | int len = pruferCode.size(); 52 | int node = len + 2; 53 | 54 | // Count frequency of nodes 55 | for ( int i = 0; i < len; i++ ) { 56 | int t = pruferCode[i]; 57 | nodeCount[t]++; 58 | } 59 | 60 | // Find the absent nodes 61 | for ( int i = 1; i <= node; i++ ) { 62 | if ( nodeCount.find ( i ) == nodeCount.end() ) leaves.insert ( i ); 63 | } 64 | 65 | vector> edges; 66 | /*Connect Edges*/ 67 | for ( int i = 0; i < len; i++ ){ 68 | int a = prufer[i]; // First node 69 | 70 | //Find the smallest number which is not present in prufer code now 71 | int b = *leaves.begin(); // the leaf 72 | 73 | edges.push_back({a,b}); // Edge of the tree 74 | 75 | leaves.erase ( b ); // Remove from absent list 76 | nodeCount[a]--; // Remove from prufer code 77 | if ( nodeCount[a] == 0 ) leaves.insert ( a ); // If a becomes absent 78 | } 79 | 80 | // The final edge 81 | edges.push_back({*leaves.begin(), *leaves.rbegin()}); 82 | return edges; 83 | } 84 | -------------------------------------------------------------------------------- /code_templates/scc_tarjan.cpp: -------------------------------------------------------------------------------- 1 | //Cycle contains which scc node belongs too. 2 | 3 | struct SCC{ 4 | int num[NODE], low[NODE], col[NODE], cycle[NODE], st[NODE]; 5 | int tail, cnt, cc; 6 | vi adj[NODE]; 7 | 8 | SCC():tail(0),cnt(0),cc(0) {} 9 | void clear () { 10 | cc += 3; 11 | FOR(i,0,NODE-1) adj[i].clear(); 12 | tail = 0; 13 | } 14 | void tarjan ( int s ) { 15 | num[s] = low[s] = cnt++; 16 | col[s] = cc + 1; 17 | st[tail++] = s; 18 | FOR(i,0,SZ(adj[s])-1) { 19 | int t = adj[s][i]; 20 | if ( col[t] <= cc ) { 21 | tarjan ( t ); 22 | low[s]=MIN(low[s],low[t]); 23 | } 24 | /*Back edge*/ 25 | else if (col[t]==cc+1) 26 | low[s]=MIN(low[s],low[t]); 27 | } 28 | if ( low[s] == num[s] ) { 29 | while ( 1 ) { 30 | int temp=st[tail-1]; 31 | tail--; 32 | col[temp] = cc + 2; 33 | cycle[temp] = s; 34 | if ( s == temp ) break; 35 | } 36 | } 37 | } 38 | void shrink( int n ) { 39 | FOR(i,0,n){ 40 | FOR(j,0,SZ(adj[i])-1){ 41 | adj[i][j] = cycle[adj[i][j]]; ///Careful. This will create self-loop. Just ignore i->i edges when processing. 42 | } 43 | } 44 | FOR(i,0,n){ 45 | if ( cycle[i] == i ) continue; 46 | int u = cycle[i]; 47 | FOR(j,0,SZ(adj[i])-1){ 48 | int v = adj[i][j]; 49 | adj[u].pb ( v ); 50 | } 51 | adj[i].clear(); 52 | } 53 | FOR(i,0,n){ ///Not always necessary 54 | sort ( ALL(adj[i]) ); 55 | UNIQUE(adj[i]); 56 | } 57 | } 58 | 59 | void findSCC( int n ) { 60 | FOR(i,0,n) { 61 | if ( col[i] <= cc ) { 62 | tarjan ( i ); 63 | } 64 | } 65 | } 66 | }; 67 | -------------------------------------------------------------------------------- /code_templates/suffix_array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Suffix array implementation using bucket sorting + lcp. 3 | Complexity O(n log n), str[] is the target string, 4 | nnn is its length and suffix[i] contains i'th sorted suffix position. 5 | */ 6 | 7 | /* 8 | 1. Fill str[] with string or augmented string. 9 | 2. Assign nnn length of str[]. 10 | 3. Call SortSuffix() 11 | 4. Result is at two different arrays: suffix[i] contains index of i'th sorted string 12 | and sufRank[stp][i] contains rank of i'th suffix 13 | */ 14 | 15 | #define MAXN Maximum Length of str[] 16 | #define MAXL Maximum Depth of log(MaxN) 17 | 18 | int nnn, stp, mv, suffix[MAXN], tmp[MAXN]; 19 | int sum[MAXN], cnt[MAXN], sufRank[MAXL][MAXN]; 20 | char str[MAXN]; 21 | 22 | inline bool equal(const int &u, const int &v){ 23 | if(!stp) return str[u] == str[v]; 24 | if(sufRank[stp-1][u] != sufRank[stp-1][v]) return false; 25 | int a = u + mv < nnn ? sufRank[stp-1][u+mv] : -1; 26 | int b = v + mv < nnn ? sufRank[stp-1][v+mv] : -1; 27 | return a == b; 28 | } 29 | 30 | void update(){ 31 | int i, rnk; 32 | for(i = 0; i < nnn; i++) sum[i] = 0; 33 | for(i = rnk = 0; i < nnn; i++) { 34 | suffix[i] = tmp[i]; 35 | if(i && !equal(suffix[i], suffix[i-1])) { 36 | sufRank[stp][suffix[i]] = ++rnk; 37 | sum[rnk+1] = sum[rnk]; 38 | } 39 | else sufRank[stp][suffix[i]] = rnk; 40 | sum[rnk+1]++; 41 | } 42 | } 43 | 44 | void Sort() { 45 | int i; 46 | for(i = 0; i < nnn; i++) cnt[i] = 0; 47 | memset(tmp, -1, sizeof tmp); 48 | for(i = 0; i < mv; i++){ 49 | int idx = sufRank[stp - 1][nnn - i - 1]; 50 | int x = sum[idx]; 51 | tmp[x + cnt[idx]] = nnn - i - 1; 52 | cnt[idx]++; 53 | } 54 | for(i = 0; i < nnn; i++){ 55 | int idx = suffix[i] - mv; 56 | if(idx < 0)continue; 57 | idx = sufRank[stp-1][idx]; 58 | int x = sum[idx]; 59 | tmp[x + cnt[idx]] = suffix[i] - mv; 60 | cnt[idx]++; 61 | } 62 | update(); 63 | return; 64 | } 65 | 66 | inline bool cmp(const int &a, const int &b){ 67 | if(str[a]!=str[b]) return str[a]= 0; i--) { 91 | if(sufRank[i][u] == sufRank[i][v]) { 92 | ret += 1< 0 ) t[needSL].slink = node; 36 | needSL = node; 37 | } 38 | 39 | bool walkdown ( int node ){ 40 | if ( act_len >= t[node].edgeLen() ) { 41 | act_e += t[node].edgeLen(); 42 | act_len -= t[node].edgeLen(); 43 | act_node = node; 44 | return true; 45 | } 46 | return false; 47 | } 48 | 49 | void st_init() { 50 | needSL = 0; last_added = 0; pos = -1; 51 | rem = 0; act_node = 0; act_e = 0; act_len = 0; 52 | root = act_node = newNode ( -1, -1 ); 53 | } 54 | 55 | void st_extend( int c ) { 56 | text[++pos] = c; 57 | needSL = 0; 58 | rem++; 59 | 60 | while ( rem ) { 61 | if ( act_len == 0 ) act_e = pos; 62 | if ( t[act_node].child[actEdge()] == 0 ) { 63 | int leaf = newNode ( pos ); 64 | t[act_node].child[actEdge()] = leaf; 65 | addSL ( act_node ); 66 | } 67 | else { 68 | int nxt = t[act_node].child[actEdge()]; 69 | if ( walkdown ( nxt ) ) continue; 70 | if ( text[t[nxt].start+act_len] == c ) { 71 | act_len++; 72 | addSL ( act_node ); 73 | break; 74 | } 75 | int split = newNode ( t[nxt].start, t[nxt].start + act_len ); 76 | t[act_node].child[actEdge()] = split; 77 | int leaf = newNode ( pos ); 78 | t[split].child[c] = leaf; 79 | t[nxt].start += act_len; 80 | t[split].child[text[t[nxt].start]] = nxt; 81 | 82 | addSL ( split ); 83 | } 84 | rem--; 85 | if ( act_node == root && act_len > 0 ) { 86 | act_len--; 87 | act_e = pos - rem + 1; 88 | } 89 | else { 90 | if ( t[act_node].slink > 0 ) act_node = t[act_node].slink; 91 | else act_node = root; 92 | } 93 | } 94 | } 95 | }; 96 | 97 | 98 | /* 99 | 1. How to insert? 100 | Take input in a string, then convert each charater to int and insert using st_extend( c ). 101 | At the end of the string, extend using st_extend($), where $ is an int > than others. 102 | 103 | 2. How to check for terminal node? 104 | if ( t[s].end == inf ) it is a terminal node. 105 | */ 106 | -------------------------------------------------------------------------------- /code_templates/template.cpp: -------------------------------------------------------------------------------- 1 | /***********Template Starts Here***********/ 2 | //#include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | 22 | #define pb push_back 23 | #define nl puts ("") 24 | #define sp printf ( " " ) 25 | #define phl printf ( "hello\n" ) 26 | #define ff first 27 | #define ss second 28 | #define POPCOUNT __builtin_popcountll 29 | #define RIGHTMOST __builtin_ctzll 30 | #define LEFTMOST(x) (63-__builtin_clzll((x))) 31 | #define MP make_pair 32 | #define FOR(i,x,y) for(vlong i = (x) ; i <= (y) ; ++i) 33 | #define ROF(i,x,y) for(vlong i = (y) ; i >= (x) ; --i) 34 | #define CLR(x,y) memset(x,y,sizeof(x)) 35 | #define UNIQUE(V) (V).erase(unique((V).begin(),(V).end()),(V).end()) 36 | #define MIN(a,b) ((a)<(b)?(a):(b)) 37 | #define MAX(a,b) ((a)>(b)?(a):(b)) 38 | #define NUMDIGIT(x,y) (((vlong)(log10((x))/log10((y))))+1) 39 | #define SQ(x) ((x)*(x)) 40 | #define ABS(x) ((x)<0?-(x):(x)) 41 | #define FABS(x) ((x)+eps<0?-(x):(x)) 42 | #define ALL(x) (x).begin(),(x).end() 43 | #define LCM(x,y) (((x)/gcd((x),(y)))*(y)) 44 | #define SZ(x) ((vlong)(x).size()) 45 | #define NORM(x) if(x>=mod)x-=mod; 46 | #define MOD(x,y) (((x)*(y))%mod) 47 | #define ODD(x) (((x)&1)==0?(0):(1)) 48 | 49 | using namespace std; 50 | 51 | typedef long long vlong; 52 | typedef unsigned long long uvlong; 53 | typedef pair < vlong, vlong > pll; 54 | typedef vector vll; 55 | typedef vector vl; 56 | 57 | const vlong inf = 2147383647; 58 | const double pi = 2 * acos ( 0.0 ); 59 | const double eps = 1e-9; 60 | 61 | #ifdef forthright48 62 | #include 63 | clock_t tStart = clock(); 64 | #define debug(args...) {dbg,args; cerr< debugger& operator , (const T& v){ 75 | cerr<>= 1; 115 | } 116 | return res; 117 | } 118 | 119 | inline vlong bigmod ( vlong a, vlong p, vlong m ) { 120 | vlong res = 1 % m, x = a % m; 121 | while ( p ) { 122 | if ( p & 1 ) res = ( res * x ) % m; 123 | x = ( x * x ) % m; p >>= 1; 124 | } 125 | return res; 126 | } 127 | 128 | /***********Template Ends Here***********/ 129 | 130 | int main () { 131 | #ifdef forthright48 132 | //freopen ( "input.txt", "r", stdin ); 133 | //freopen ( "output.txt", "w", stdout ); 134 | #endif // forthright48 135 | 136 | return 0; 137 | } 138 | -------------------------------------------------------------------------------- /code_templates/treap.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | To insert an item, pitem x = new item ( key, rand() * rand() ) 3 | Many functions need a root to be passed: insert ( treap.root, x ) 4 | */ 5 | 6 | struct item { 7 | int key, prior, cnt; 8 | item * l, * r; 9 | item() {} 10 | item( int key, int prior ): key(key), prior(prior), l(NULL), r(NULL) {} 11 | }; 12 | typedef item * pitem; 13 | 14 | struct Treap { 15 | int size; 16 | pitem root; 17 | 18 | /*Resets the Treap. Not complete yet. Need to erase all elements from treap*/ 19 | void clear() { 20 | size = 0; 21 | root = NULL; //When the first element is inserted, that element becomes the root 22 | } 23 | 24 | int cnt (pitem t) { 25 | return t ? t->cnt : 0; 26 | } 27 | 28 | void upd_cnt (pitem t) { 29 | if (t) { 30 | t->cnt = 1 + cnt(t->l) + cnt (t->r); 31 | } 32 | } 33 | 34 | void split ( pitem t, int key, pitem &l, pitem &r ) { 35 | /** Takes a treap and splits it into two subtree l and r 36 | such that, l contains elements smaller to key 37 | and r contains elements bigger or equal than key 38 | */ 39 | if ( !t ) { // If treap is empty there is nothing to split 40 | l = r = NULL; 41 | } 42 | else if ( key < t->key ) { // If key is smaller than root 43 | // So now, we have a treap whose right subtree is bigger than root 44 | // but its left subtree has SOME values smaller than key 45 | // So hey! Lets SPLIT the left subtree and extract those values which are bigger than key 46 | // and put them to treap->l. That way, our current treap will have all values bigger than 47 | // key 48 | split( t->l, key, l, t->l ); 49 | r = t; 50 | } 51 | else { 52 | // Same as above. We split treap->r. 53 | split( t->r, key, t->r, r ); 54 | l = t; 55 | } 56 | upd_cnt (t); 57 | } 58 | void insert ( pitem &t, pitem it ) { 59 | if ( !t ) { // If the treap is empty, make the item root of the tree 60 | t = it; 61 | size++; 62 | } 63 | else if ( it->prior > t->prior ) { // When item is more important than root 64 | // Since it is more important than root, IT should be the root 65 | split( t, it->key, it->l, it->r ); // Split the treap and put them as child of item 66 | t = it; 67 | size++; 68 | } 69 | else // Item is not more important than root 70 | if ( it->key < t->key ) insert( t->l, it ); // If item is smaller than root, than go to left subtree 71 | else insert ( t->r, it ); // Else go to right subtree 72 | } 73 | upd_cnt (t); 74 | } 75 | 76 | void merge ( pitem &t, pitem l, pitem r ) { 77 | /** Merges two treap where l contains values smaller than r 78 | 79 | After merging the treap, put it inside pitem t 80 | */ 81 | if ( !l || !r ) { 82 | t = l? l:r; 83 | } 84 | else if ( l->prior > r->prior ){ // Left subtree is more important 85 | // 86 | merge ( l->r, l->r, r ); 87 | t = l; 88 | } 89 | else { 90 | merge ( r->l, l, r->l ); 91 | t = r; 92 | } 93 | upd_cnt( t ); 94 | } 95 | 96 | void erase ( pitem &t, int key ) { 97 | if ( t->key == key ) { 98 | pitem e = t; 99 | merge( t, t->l, t->r ); 100 | delete ( e ); 101 | size--; 102 | } 103 | else { // Iterate over the treap until we find the key 104 | erase( key < t->key? t->l:t->r, key ); 105 | } 106 | upd_cnt (t); 107 | } 108 | 109 | //Find key in treap 110 | pitem find ( pitem t, int key ) { 111 | if ( !t ) return t; 112 | if ( t->key == key ) return t; 113 | if ( key < t->key ) return find ( t->l, key ); 114 | else return find ( t->r, key ); 115 | } 116 | 117 | /*Finds number of element <= x in the treap*/ 118 | int KPivot ( pitem t, int key ) { 119 | if ( !t ) return 0; 120 | else if ( t->key <= key ) { 121 | return ( cnt( t ) - cnt( t->r ) ) + KPivot(t->r, key); 122 | } 123 | else { 124 | return KPivot( t->l, key ); 125 | } 126 | } 127 | 128 | /*Finds kth element in sorted order*/ 129 | pitem pos ( pitem t, int p ) { 130 | if ( cnt ( t->l ) == p ) return t; 131 | if ( cnt ( t->l ) < p ) return pos ( t->r, p - cnt(t->l) - 1 ); 132 | else return pos ( t->l, p ); 133 | } 134 | }treap; 135 | -------------------------------------------------------------------------------- /code_templates/treap_builtin.cpp: -------------------------------------------------------------------------------- 1 | #include // Common file 2 | #include // Including tree_order_statistics_node_update 3 | 4 | using namespace __gnu_pbds; 5 | 6 | int main() { 7 | /// Ordered Set 8 | typedef tree< int, null_type, less, rb_tree_tag, 9 | tree_order_statistics_node_update> ordered_set; 10 | 11 | ordered_set X; 12 | X.insert(1); 13 | cout<<*X.find_by_order(1)< parameter. 18 | typedef tree, rb_tree_tag, 19 | tree_order_statistics_node_update> ordered_multiset; 20 | 21 | ordered_multiset x; 22 | 23 | x.insert(0); 24 | x.insert(1); 25 | x.insert(1); 26 | x.insert(2); 27 | 28 | x.erase(x.find_by_order(x.order_of_key(0))); /// erasing is tricky 29 | 30 | cout<<*x.find_by_order(0)< Ordered Set 33 | typedef tree, null_type, less_equal>, rb_tree_tag, 34 | tree_order_statistics_node_update> ordered_pair; 35 | 36 | return 0; 37 | } 38 | --------------------------------------------------------------------------------