├── .vscode └── ipch │ ├── 361cd7221d5cce86 │ └── mmap_address.bin │ ├── 5570a250226adfcd │ ├── ChineseReminderTheorem.ipch │ └── mmap_address.bin │ └── d7d0edf6dbab8e1f │ ├── ChineseReminderTheorem.ipch │ └── mmap_address.bin ├── Cheet Sheets ├── Trig_Cheat_Sheet.pdf ├── cheatsheet2014.pdf └── computer_science_cheatsheet.pdf ├── Collected Library ├── Stanford University ACM Team Notebook.pdf └── Stavropol SU .pdf ├── Data Structure ├── BIT.cpp ├── HeavyLightDecomposition.cpp ├── Histrogram.cpp ├── LCA.cpp ├── RMQ.cpp └── trie.cpp ├── Geometry ├── CircleSegmentTetrahedron.cpp ├── Closest Pair.cpp ├── ConvexHullForthRight.cpp ├── ConvexHullGraham.cpp ├── Convexhull.cpp ├── Geometry Routine.cpp ├── LineSegmentIntersection.cpp ├── PointInPolygon.cpp ├── RotatePoint.cpp └── TanOfLine.cpp ├── Graph ├── Stoer Wagner all pair Min Cut.cpp ├── ArticulationPoint.cpp ├── BellmanFord.cpp ├── BiConnectedComponent.cpp ├── BreadthFirstSearch.cpp ├── Bridge.cpp ├── DisjointSet.cpp ├── EularCircuit.cpp ├── Hungerian Algorithm.cpp ├── Max Weighted Bi-partite Matching.cpp ├── MaxFlow_Dinic.cpp ├── MaximumBipertiteMatching.cpp ├── MincostMaxFlow.cpp ├── MinimumExpression.cpp ├── MyDinitz.cpp ├── MyDinitzWithEdgeList.cpp ├── Stable marrige problem.cpp ├── StronglyConnectedComponent.cpp └── TarjansOfflineLCA.cpp ├── IO └── FastRead.cpp ├── LICENSE ├── Matrix & Numeric ├── BigInt.cpp ├── Bigfloat │ ├── 1~ │ ├── Example.h │ ├── Example.h~ │ ├── base.h │ ├── base.h~ │ ├── bigfloat.cpp │ ├── bigfloat.h │ └── bigfloat.h~ ├── FFT.cpp ├── Gaussian Elimination.cpp └── MatrixExpo.cpp ├── Number theory & Math ├── ChineseReminderTheorem.cpp ├── ExtendedEuclidMOdInverse.cpp ├── Hn.cpp ├── LinearDiphontine.cpp ├── Number Theory Part 1.pdf ├── NumberTheory Part 2.pdf ├── PollardRho.cpp ├── SegmentedSieve.cpp ├── ShankBabyStepGiantStep.cpp ├── Sieve.cpp ├── josepheous.cpp └── ncr.cpp ├── README.md ├── Searching └── TernarySearch.cpp └── String ├── AhoChorasik.cpp ├── KMP.cpp ├── hashing.cpp ├── manacher.cpp ├── suffix-array.pdf └── suffixArray.cpp /.vscode/ipch/361cd7221d5cce86/mmap_address.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbmaruf/Algorithms-Code-Library/d95d79f0ee9ab3653a96ff8dfca44b703641e365/.vscode/ipch/361cd7221d5cce86/mmap_address.bin -------------------------------------------------------------------------------- /.vscode/ipch/5570a250226adfcd/ChineseReminderTheorem.ipch: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbmaruf/Algorithms-Code-Library/d95d79f0ee9ab3653a96ff8dfca44b703641e365/.vscode/ipch/5570a250226adfcd/ChineseReminderTheorem.ipch -------------------------------------------------------------------------------- /.vscode/ipch/5570a250226adfcd/mmap_address.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbmaruf/Algorithms-Code-Library/d95d79f0ee9ab3653a96ff8dfca44b703641e365/.vscode/ipch/5570a250226adfcd/mmap_address.bin -------------------------------------------------------------------------------- /.vscode/ipch/d7d0edf6dbab8e1f/ChineseReminderTheorem.ipch: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbmaruf/Algorithms-Code-Library/d95d79f0ee9ab3653a96ff8dfca44b703641e365/.vscode/ipch/d7d0edf6dbab8e1f/ChineseReminderTheorem.ipch -------------------------------------------------------------------------------- /.vscode/ipch/d7d0edf6dbab8e1f/mmap_address.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbmaruf/Algorithms-Code-Library/d95d79f0ee9ab3653a96ff8dfca44b703641e365/.vscode/ipch/d7d0edf6dbab8e1f/mmap_address.bin -------------------------------------------------------------------------------- /Cheet Sheets/Trig_Cheat_Sheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbmaruf/Algorithms-Code-Library/d95d79f0ee9ab3653a96ff8dfca44b703641e365/Cheet Sheets/Trig_Cheat_Sheet.pdf -------------------------------------------------------------------------------- /Cheet Sheets/cheatsheet2014.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbmaruf/Algorithms-Code-Library/d95d79f0ee9ab3653a96ff8dfca44b703641e365/Cheet Sheets/cheatsheet2014.pdf -------------------------------------------------------------------------------- /Cheet Sheets/computer_science_cheatsheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbmaruf/Algorithms-Code-Library/d95d79f0ee9ab3653a96ff8dfca44b703641e365/Cheet Sheets/computer_science_cheatsheet.pdf -------------------------------------------------------------------------------- /Collected Library/Stanford University ACM Team Notebook.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbmaruf/Algorithms-Code-Library/d95d79f0ee9ab3653a96ff8dfca44b703641e365/Collected Library/Stanford University ACM Team Notebook.pdf -------------------------------------------------------------------------------- /Collected Library/Stavropol SU .pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbmaruf/Algorithms-Code-Library/d95d79f0ee9ab3653a96ff8dfca44b703641e365/Collected Library/Stavropol SU .pdf -------------------------------------------------------------------------------- /Data Structure/BIT.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | update and query function for 2D bit. 3 | MAX is the maximum possible value. 4 | bit[][] holds the 2D binary indexed tree 5 | */ 6 | 7 | /* 8 | (III) Range Update, Range Query: 9 | 10 | I didn't even know it exists until I read some post in TopCoder forums (the post was made by: AnilKishore). 11 | 12 | 13 | 14 | I will just re-state his explanation as it was quite clear itself. All we want here is to support range updates, and do range queries. As from the previous type, if we try to store range updates, the BIT structure effectively captures updates for single positions, instead of range/cumulative sums. However, we can do some tweaking to work around this problem. 15 | 16 | 17 | 18 | Let's just consider only one update: Add v to [a, b] while the rest elements of the array is 0. 19 | 20 | Now, consider sum(0, x) for all possible x, again three situation can arise: 21 | 22 | 1. 0 ≤ x < a : which results in 0 23 | 24 | 2. a ≤ x ≤ b : we get v * (x - (a-1)) 25 | 26 | 3. b < x < n : we get v * (b - (a-1)) 27 | 28 | This suggests that, if we can find v*x for any index x, then we can get the sum(0, x) by subtracting T from it, where: 29 | 30 | 1. 0 ≤ x < : Sum should be 0, thus, T = 0 31 | 32 | 2. a ≤ x ≤ : Sum should be v*x-v*(a-1), thus, T = v*(a-1) 33 | 34 | 3. b < x < n : Sum should be 0, thus, T = -v*b + v*(a-1) 35 | 36 | As, we can see, knowing T solves our problem, we can use another BIT to store this additive amount from which we can get: 37 | 38 | 0 for x < a, v*(a-1) for x in [a..b], -v*b+v(a-1) for x > b. 39 | 40 | 41 | 42 | Now we have two BITs. 43 | 44 | To add v in range [a, b]: Update(a, v), Update(b+1, -v) in the first BIT and Update(a, v*(a-1)) and Update(b+1, -v*b) on the second BIT. 45 | 46 | To get sum in range [0, x]: you simply do Query_BIT1(x)*x - Query_BIT2(x); 47 | 48 | Now you know how to find range sum for [a, b]. Just find sum(b) - sum(a-1) using the formula stated above. 49 | 50 | 51 | 52 | Pretty impressive this one! SPOJ - HORRIBLE can be solved in this approach. And thanks to Iqram Mahmud for this nice problem. 53 | 54 | 55 | 56 | (IV) 2D BIT 57 | 58 | How to write Update and Query methods for 2D BIT is well described in the TopCoder tutorial I've mentioned above. The only thing to notice here is how the queries and updates work. 2D BIT is basically a BIT where each element is another BIT. Adding v on (x, y) means it's effect will be found throughout the rectangle [(x, y), (W, H)], and query for (x, y) gives you the result of the rectangle [(0, 0), (x, y)], assuming the total rectangle is [(0, 0), (W, H)]. SO when you query and update on this BIT, you have to be careful about how many times you are subtracting a rectangle and adding it. Simple set union formula works here. So if you want to get the result of a specific rectangle [(x1, y1), (x2, y2)], the following steps are necessary to do so: 59 | 60 | V = Query(x2, y2) 61 | 62 | V -= Query(x2, y1-1) 63 | 64 | V -= Query(x1-1, y2) 65 | 66 | V += Query(x1-1, y1-1) 67 | 68 | 69 | 70 | 71 | */ 72 | 73 | 74 | 75 | 76 | void update(int x, int y, int v) { 77 | int y1; 78 | while(x <= MAX) { 79 | y1 = y; 80 | while(y1 <= MAX) { 81 | bit[x][y1] += v; 82 | y1 += (y1 & -y1); 83 | } 84 | x += (x & -x); 85 | } 86 | } 87 | 88 | int readsum(int x, int y) { 89 | int v = 0, y1; 90 | while(x > 0) { 91 | y1 = y; 92 | while(y1 > 0) { 93 | v += bit[x][y1]; 94 | y1 -= (y1 & -y1); 95 | } 96 | x -= (x & -x); 97 | } 98 | return v; 99 | } 100 | 101 | 102 | long long tree[100000+2] ; 103 | void update( int idx, int val ) { 104 | while( idx<= 1001 ) { 105 | tree[idx] += val ; 106 | idx += ( idx & -idx ); 107 | } 108 | } 109 | long long query( int idx ) { 110 | long long sum = 0 ; 111 | while( idx > 0 ) { 112 | sum += tree[idx] ; 113 | idx -= ( idx & -idx ) ; 114 | } 115 | return sum ; 116 | } 117 | void range_update( int a, int b, int v ) { 118 | update(a,v) ; 119 | update(b+1,-v) ; 120 | } 121 | long long point_query(int x) { 122 | return query(x) ; 123 | } 124 | 125 | 126 | -------------------------------------------------------------------------------- /Data Structure/HeavyLightDecomposition.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Rough code for heavy light decomposition. Input graph must be a tree. 3 | Also includes the LCA method. 4 | What to do with the chain is problem dependent. 5 | */ 6 | 7 | vector< int > G[MAX]; 8 | int cost[MAX], lvl[MAX], parent[MAX]; 9 | int head[MAX], cnext[MAX], chainid[MAX], chainpos[MAX]; 10 | int nchain, temp[MAX]; 11 | 12 | int dfs(int u, int p, int d) { 13 | int i, v, sz = G[u].size(), tmp, mx, id, tot, hd, k; 14 | lvl[u] = d, mx = 0, id = u, tot = 1; 15 | for(i = 0; i < sz; i++) { 16 | v = G[u][i]; 17 | if(v != p) { 18 | parent[v] = u; 19 | tmp = dfs(v, u, d + 1); 20 | tot += tmp; 21 | if(tmp > mx) { 22 | mx = tmp; 23 | id = v; 24 | } 25 | } 26 | } 27 | if(tot == 1) cnext[u] = -1; 28 | else cnext[u] = id; 29 | for(i = 0; i < sz; i++) { 30 | v = G[u][i]; 31 | if(v != p && v != id) { 32 | for(hd = v, k = 0; v != -1; v = cnext[v], k++) { 33 | head[v] = hd; 34 | temp[k] = cost[v]; 35 | chainpos[v] = k; 36 | chainid[v] = nchain; 37 | } 38 | // buff is the current chain of size k 39 | nchain++; 40 | } 41 | } 42 | return tot; 43 | } 44 | 45 | void hld(int v) { 46 | int hd, k; 47 | nchain = 0; lvl[0] = -1; 48 | dfs(v, 0, 0); 49 | for(hd = v, k = 0; v != -1; v = cnext[v], k++) { 50 | head[v] = hd; 51 | temp[k] = cost[v]; 52 | chainpos[v] = k; 53 | chainid[v] = nchain; 54 | } 55 | // buff is the current chain of size k 56 | nchain++; 57 | } 58 | 59 | int lca(int a, int b) { 60 | while(chainid[a] != chainid[b]) { 61 | if(lvl[head[a]] < lvl[head[b]]) b = parent[head[b]]; 62 | else a = parent[head[a]]; 63 | } 64 | return (lvl[a] < lvl[b]) ? a : b; 65 | } 66 | -------------------------------------------------------------------------------- /Data Structure/Histrogram.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Finds largest rectangular area in a histogram in O(n) 3 | */ 4 | 5 | i64 calc(int *ht, int n) { 6 | i64 ret = 0; 7 | int top = 1, st[MAX], i; 8 | ht[0] = st[0] = ht[++n] = 0; 9 | for(i = 1; i <= n; i++) { 10 | while(top > 1 && ht[st[top-1]] >= ht[i]) { 11 | ret = _max(ret, (i64)ht[st[top-1]]*(i64)(i - st[top-2]-1)); 12 | top--; 13 | } 14 | st[top++] = i; 15 | } 16 | return ret; 17 | } 18 | /* 19 | d(n)=(n-1)* ( d(n-1)+d(n-2) ) 20 | বা d(n)=(n-1) ( d(n-1)+d(n-2) ) 21 | বেস কেস: d(1)=0,d(2)=1 22 | 23 | */ 24 | 25 | -------------------------------------------------------------------------------- /Data Structure/LCA.cpp: -------------------------------------------------------------------------------- 1 | //LCA using sparse table 2 | //Complexity: O(NlgN,lgN) 3 | #define EX 100002 4 | int L[EX]; 5 | int P[EX][22]; 6 | int T[EX]; 7 | vectorg[EX]; 8 | void dfs(int from,int u,int dep) 9 | { 10 | T[u]=from; 11 | L[u]=dep; 12 | for(int i=0;i<(int)g[u].size();i++) 13 | { 14 | int v=g[u][i]; 15 | if(v==from) continue; 16 | dfs(u,v,dep+1); 17 | } 18 | } 19 | 20 | int lca_query(int N, int p, int q) 21 | { 22 | int tmp, log, i; 23 | 24 | if (L[p] < L[q]) 25 | tmp = p, p = q, q = tmp; 26 | 27 | log=1; 28 | while(1) { 29 | int next=log+1; 30 | if((1<L[p])break; 31 | log++; 32 | 33 | } 34 | 35 | for (i = log; i >= 0; i--) 36 | if (L[p] - (1 << i) >= L[q]) 37 | p = P[p][i]; 38 | 39 | if (p == q) 40 | return p; 41 | 42 | for (i = log; i >= 0; i--) 43 | if (P[p][i] != -1 && P[p][i] != P[q][i]) 44 | p = P[p][i], q = P[q][i]; 45 | 46 | return T[p]; 47 | } 48 | 49 | void lca_init(int N) 50 | { 51 | memset (P,-1,sizeof(P)); 52 | int i, j; 53 | for (i = 0; i < N; i++) 54 | P[i][0] = T[i]; 55 | 56 | for (j = 1; 1 << j < N; j++) 57 | for (i = 0; i < N; i++) 58 | if (P[i][j - 1] != -1) 59 | P[i][j] = P[P[i][j - 1]][j - 1]; 60 | } 61 | 62 | int main(void) { 63 | g[0].pb(1); 64 | g[0].pb(2); 65 | g[2].pb(3); 66 | g[2].pb(4); 67 | dfs(0, 0, 0); 68 | lca_init(5); 69 | printf( "%d\n", lca_query(5,3,4) ); 70 | return 0; 71 | } 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | //EX extra node 102 | int EX[NODES][LGNODES] , ST[NODES][LGNODES] ; 103 | int L[NODES] ; 104 | void dfs(int u , int bc , int level , int EX ) { 105 | EX[u][0] = EX , ST[u][0]=bc , L[u] = level; 106 | for( int i = (int)G[u].size()-1 ; i >= 0 ; i-- ) { 107 | int v = G[u][i].u ; 108 | if( v == bc ) continue ; 109 | dfs( v , u , level+1 , G[u][i].w ) ; 110 | } 111 | } 112 | void preProcessLCA() { 113 | memset( ST , -1 , sizeof ST ) ; 114 | memset( EX , 0 , sizeof EX ) ; 115 | dfs(1,-1,0,0) ; 116 | for( int j = 1 ; (1<= 0 ; i-- ) { 130 | if( (L[s] - (1<= L[t] ) { 131 | ret = max( ret , EX[s][i] ) ; 132 | s = ST[s][i] ; 133 | } 134 | } 135 | 136 | if( s == t ) return ret ; 137 | for( int i = 19 ; i >= 0 ; i-- ) { 138 | if( ST[s][i] != -1 ) { 139 | if( ST[s][i] != ST[t][i] ) { 140 | ret = max( ret , EX[s][i] ); 141 | s = ST[s][i] ; 142 | ret = max( ret , EX[t][i] ); 143 | t = ST[t][i] ; 144 | } 145 | } 146 | } 147 | ret = max( ret , EX[s][0] ) ; 148 | ret = max( ret , EX[t][0] ) ; 149 | return ret ; 150 | } 151 | -------------------------------------------------------------------------------- /Data Structure/RMQ.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | inline int readInt() { 4 | int ip = getchar_unlocked(), ret = 0, flag = 1; 5 | for(; ip < 48 || ip > 57; ip = getchar_unlocked()) { 6 | if(ip == 45) { 7 | flag = -1; 8 | ip = getchar_unlocked(); 9 | break; 10 | } 11 | } 12 | for(; ip > 47 && ip < 58; ip = getchar_unlocked()) 13 | ret = ret * 10 + ip - 48 ; 14 | return flag * ret; 15 | } 16 | #define MAX 100000+5 17 | #define LGMAX 18 18 | int ST[MAX][LGMAX]; 19 | 20 | void rmq( int n ){ 21 | for( int j = 1 ; 1<>= 1 ; 47 | lg++ ; 48 | } 49 | lg-- ; 50 | cout << min( ST[x][lg] , ST[y-(1<next[seq[i]]) curr->next[seq[i]] = new trie; 16 | curr = curr->next[seq[i]]; 17 | } 18 | if(!curr->next[MAX]) curr->next[MAX] = new trie; 19 | } 20 | 21 | bool found(trie *root, int *seq, int len) { 22 | trie *curr = root; 23 | for(int i = 0; i < len; i++) { 24 | if(!curr->next[seq[i]]) return false; 25 | curr = curr->next[seq[i]]; 26 | } 27 | if(!curr->next[MAX]) return false; 28 | return true; 29 | } 30 | 31 | 32 | 33 | 34 | /* 35 | Trie implementation using array, faster and takes less memory. 36 | Each node can contain arbitrary data as needed for solving the problem. 37 | The ALPHABET, MAX and scale() may need tuning as necessary. 38 | */ 39 | 40 | const int ALPHABET = 26; 41 | const int MAX = 100000; 42 | 43 | // for mapping items form 0 to ALPHABET-1 44 | #define scale(x) (x-'a') 45 | 46 | 47 | struct TrieTree { 48 | int n, root; 49 | int next[MAX][ALPHABET]; 50 | char data[MAX]; // there can be more data fields 51 | 52 | void init() { 53 | root = 0, n = 1; data[root] = 0; 54 | memset(next[root], -1, sizeof(next[root])); 55 | } 56 | 57 | void insert(char *s) { 58 | int curr = root, i, k; 59 | for(i = 0; s[i]; i++) { 60 | k = scale(s[i]); 61 | if(next[curr][k] == -1) { 62 | next[curr][k] = n; 63 | data[n] = s[i]; // optional 64 | memset(next[n], -1, sizeof(next[n])); 65 | n++; 66 | } 67 | curr = next[curr][k]; 68 | } 69 | data[curr] = 0; // sentinel, optional 70 | } 71 | 72 | bool find(char *s) { 73 | int curr = root, i, k; 74 | for(i = 0; s[i]; i++) { 75 | k = scale(s[i]); 76 | if(next[curr][k] == -1) return false; 77 | curr = next[curr][k]; 78 | } 79 | return (data[curr] == 0); 80 | } 81 | 82 | } trieTree; 83 | -------------------------------------------------------------------------------- /Geometry/CircleSegmentTetrahedron.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This code assumes the circle center and radius to be integer. 3 | Change this when necessary. 4 | */ 5 | 6 | inline double commonArea(const Circle &a, const Circle &b) { 7 | int dsq = sqDist(a.c, b.c); 8 | double d = sqrt((double)dsq); 9 | if(sq(a.r + b.r) <= dsq) return 0; 10 | if(a.r >= b.r && sq(a.r-b.r) >= dsq) return pi * b.r * b.r; 11 | if(a.r <= b.r && sq(b.r-a.r) >= dsq) return pi * a.r * a.r; 12 | double angleA = 2.0 * acos((a.r * a.r + dsq - b.r * b.r) / (2.0 * a.r * d)); 13 | double angleB = 2.0 * acos((b.r * b.r + dsq - a.r * a.r) / (2.0 * b.r * d)); 14 | return 0.5 * (a.r * a.r * (angleA - sin(angleA)) + b.r * b.r * (angleB - sin(angleB))); 15 | } 16 | 17 | 18 | /* 19 | Segment intersection in 2D integer space. 20 | P1, p2 makes first segment, p3, p4 makes the second segment 21 | */ 22 | 23 | inline bool intersect(const Point &p1, const Point &p2, const Point &p3, const Point &p4) { 24 | i64 d1, d2, d3, d4; 25 | d1 = direction(p3, p4, p1); 26 | d2 = direction(p3, p4, p2); 27 | d3 = direction(p1, p2, p3); 28 | d4 = direction(p1, p2, p4); 29 | if(((d1 < 0 && d2 > 0) || (d1 > 0 && d2 < 0)) && ((d3 < 0 && d4 > 0) || (d3 > 0 && d4 < 0))) return true; 30 | if(!d3 && onsegment(p1, p2, p3)) return true; 31 | if(!d4 && onsegment(p1, p2, p4)) return true; 32 | if(!d1 && onsegment(p3, p4, p1)) return true; 33 | if(!d2 && onsegment(p3, p4, p2)) return true; 34 | return false; 35 | } 36 | 37 | 38 | /* 39 | Some tetrahedron formulas 40 | */ 41 | 42 | inline double volume(double u, double v, double w, double U, double V, double W) { 43 | double u1,v1,w1; 44 | u1 = v * v + w * w - U * U; 45 | v1 = w * w + u * u - V * V; 46 | w1 = u * u + v * v - W * W; 47 | return sqrt(4.0*u*u*v*v*w*w - u*u*u1*u1 - v*v*v1*v1 - w*w*w1*w1 + u1*v1*w1) / 12.0; 48 | } 49 | 50 | inline double surface(double a, double b, double c) { 51 | return sqrt((a + b + c) * (-a + b + c) * (a - b + c) * (a + b - c)) / 4.0; 52 | } 53 | 54 | inline double insphere(double WX, double WY, double WZ, double XY, double XZ, double YZ) { 55 | double sur, rad; 56 | sur = surface(WX, WY, XY) + surface(WX, XZ, WZ) + surface(WY, YZ, WZ) + surface(XY, XZ, YZ); 57 | rad = volume(WX, WY, WZ, YZ, XZ, XY) * 3.0 / sur; 58 | return rad; 59 | } 60 | 61 | 62 | //1.angle of a regular polygon if is T then total arm n = 360/(180-T) where n is integer. 63 | 64 | -------------------------------------------------------------------------------- /Geometry/Closest Pair.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | //algorithm of clocest pair, not my algorithm collected from WJMZBMR's code 9 | const int N = int(1e5) + 10; 10 | typedef long long int64; 11 | const int64 INF = 1LL << 60; 12 | 13 | struct Point { 14 | int64 x; 15 | int64 y; 16 | } point[N]; 17 | int n; 18 | int tmpt[N]; 19 | 20 | bool cmpxy(const Point& a, const Point& b) { 21 | if (a.x != b.x) 22 | return a.x < b.x; 23 | return a.y < b.y; 24 | } 25 | 26 | bool cmpy(const int& a, const int& b) { 27 | return point[a].y < point[b].y; 28 | } 29 | 30 | int64 dis2(int i, int j) { 31 | return (point[i].x - point[j].x) * (point[i].x - point[j].x) 32 | + (point[i].y - point[j].y) * (point[i].y - point[j].y); 33 | } 34 | 35 | int64 sqr(int64 x) { 36 | return x * x; 37 | } 38 | 39 | int64 Closest_Pair(int left, int right) { 40 | int64 d = INF; 41 | if (left == right) 42 | return d; 43 | if (left + 1 == right) 44 | return dis2(left, right); 45 | int mid = (left + right) >> 1; 46 | int64 d1 = Closest_Pair(left, mid); 47 | int64 d2 = Closest_Pair(mid + 1, right); 48 | d = min(d1, d2); 49 | int i, j, k = 0; 50 | for (i = left; i <= right; i++) { 51 | if (sqr(point[mid].x - point[i].x) <= d) 52 | tmpt[k++] = i; 53 | } 54 | sort(tmpt, tmpt + k, cmpy); 55 | for (i = 0; i < k; i++) { 56 | for (j = i + 1; j < k && sqr(point[tmpt[j]].y - point[tmpt[i]].y) < d; 57 | j++) { 58 | int64 d3 = dis2(tmpt[i], tmpt[j]); 59 | if (d > d3) 60 | d = d3; 61 | } 62 | } 63 | return d; 64 | } 65 | 66 | 67 | int main(){ 68 | int n ; 69 | cin >> n ; 70 | int64 S[n+1] ; 71 | S[0] = 0 ; 72 | for( int i = 1 ; i <= n ; i++ ){ 73 | int64 tmp ; 74 | cin >> tmp ; 75 | S[i] = S[i-1] + tmp ; 76 | point[i].x = i ; 77 | point[i].y = S[i] ; 78 | } 79 | cout << Closest_Pair(1,n) << "\n" ; 80 | return 0 ; 81 | } 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | /* 102 | closestPair(Point *X, Point *Y, int n); 103 | X contains the points sorted by x co-ordinate, 104 | Y contains the points sorted by y co-ordinate, 105 | One additional item in Point structure is needed, the original index. 106 | */ 107 | 108 | typedef long long i64; 109 | typedef struct { int x, y, i; } Point; 110 | 111 | int flag[MAX]; 112 | 113 | inline i64 sq(const i64 &x) { 114 | return x*x; 115 | } 116 | 117 | inline i64 sqdist(const Point &a, const Point &b) { 118 | return sq(a.x-b.x) + sq(a.y-b.y); 119 | } 120 | 121 | inline i64 closestPair(Point *X, Point *Y, int n) { 122 | if(n == 1) return INF; 123 | if(n == 2) return sqdist(X[0], X[1]); 124 | 125 | int i, j, k, n1, n2, ns, m = n >> 1; 126 | Point Xm = X[m-1], *XL, *XR, *YL, *YR, *YS; 127 | i64 lt, rt, dd, tmp; 128 | 129 | XL = new Point[m], YL = new Point[m]; 130 | XR = new Point[m+1], YR = new Point[m+1]; 131 | YS = new Point[n]; 132 | 133 | for(i = 0; i < m; i++) XL[i] = X[i], flag[X[i].i] = 0; 134 | for(; i < n; i++) XR[i - m] = X[i], flag[X[i].i] = 1; 135 | for(i = n2 = n1 = 0; i < n; i++) { 136 | if(!flag[Y[i].i]) YL[n1++] = Y[i]; 137 | else YR[n2++] = Y[i]; 138 | } 139 | 140 | lt = closestPair(XL, YL, n1); 141 | rt = closestPair(XR, YR, n2); 142 | dd = min(lt, rt); 143 | 144 | for(i = ns = 0; i < n; i++) 145 | if(sq(Y[i].x - Xm.x) < dd) 146 | YS[ns++] = Y[i]; 147 | for(j = 0; j < ns; j++) 148 | for(k = j + 1; k < ns && sq(YS[k].y - YS[j].y) < dd; k++) 149 | dd = min(dd, sqdist(YS[j], YS[k])); 150 | 151 | delete[] XL; delete[] XR; 152 | delete[] YL; delete[] YR; 153 | delete[] YS; 154 | 155 | return dd; 156 | } 157 | -------------------------------------------------------------------------------- /Geometry/ConvexHullForthRight.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 1. Assign hull.n 3 | 2. Take input in hull.point 4 | 3. Call convexSort() 5 | 4. Call findHull() 6 | 5. Convex Hull is ready in hull.convex with hull.m points in it. 7 | */ 8 | 9 | pll g; 10 | 11 | vlong triArea ( pll a, pll b, pll c ) { 12 | vlong area = a.ff * b.ss + b.ff * c.ss + c.ff * a.ss; 13 | area -= a.ff * c.ss + b.ff * a.ss + c.ff * b.ss; 14 | return area; 15 | } 16 | 17 | vlong sqDist ( pll a, pll b ) { 18 | return ( SQ(a.ff-b.ff) + SQ(a.ss-b.ss ) ); 19 | } 20 | 21 | bool convexCompare ( const pll &a, const pll &b ) { 22 | vlong area = triArea ( g, a, b ); 23 | if ( area > 0 ) return true; 24 | else if ( area == 0 && sqDist ( g, a ) < sqDist ( g, b ) ) return true; 25 | else return false; 26 | } 27 | 28 | struct ConvexHull { 29 | int n, m; 30 | pll point[PPP], convex[PPP]; 31 | 32 | void convexSort() { 33 | g = point[0]; 34 | FOR(i,0,n-1) { 35 | if ( point[i].ff < g.ff ) g = point[i]; 36 | else if ( point[i].ff == g.ff && point[i].ss < g.ss ) g = point[i]; 37 | } 38 | sort ( point, point + n, convexCompare ); 39 | } 40 | void findHull() { 41 | if ( n == 1 ) { 42 | convex[0] = convex[1] = point[0]; 43 | m = 1; 44 | return; 45 | } 46 | convex[0] = point[n-1]; convex[1] = point[0]; convex[2] = point[1]; 47 | int cur = 3; 48 | for ( int i = 2; i < n; i++ ) { 49 | vlong area = triArea ( convex[cur-2], convex[cur-1], point[i] ); 50 | if ( area > 0 ) { 51 | convex[cur] = point[i]; 52 | cur++; 53 | } 54 | else if ( area == 0 ) { ///Take action depending on what is required 55 | /*Left Vertical Line gets omitted. Manually handle it*/ 56 | /*convex[cur] = point[i]; 57 | cur++;*/ 58 | ///If extra point needs to be removed 59 | convex[cur-1] = point[i]; 60 | } 61 | else { 62 | cur--; 63 | i--; 64 | } 65 | } 66 | m = cur - 1; 67 | } 68 | 69 | }hull; 70 | 71 | -------------------------------------------------------------------------------- /Geometry/ConvexHullGraham.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 1. Assign hull.n 3 | 2. Take input in hull.point 4 | 3. Call convexSort() 5 | 4. Call findHull() 6 | 5. Convex Hull is ready in hull.convex with hull.m points in it. 7 | */ 8 | 9 | pll g; 10 | 11 | vlong triArea ( pll a, pll b, pll c ) { 12 | vlong area = a.ff * b.ss + b.ff * c.ss + c.ff * a.ss; 13 | area -= a.ff * c.ss + b.ff * a.ss + c.ff * b.ss; 14 | return area; 15 | } 16 | 17 | vlong sqDist ( pll a, pll b ) { 18 | return ( SQ(a.ff-b.ff) + SQ(a.ss-b.ss ) ); 19 | } 20 | 21 | bool convexCompare ( const pll &a, const pll &b ) { 22 | vlong area = triArea ( g, a, b ); 23 | if ( area > 0 ) return true; 24 | else if ( area == 0 && sqDist ( g, a ) < sqDist ( g, b ) ) return true; 25 | else return false; 26 | } 27 | 28 | struct ConvexHull { 29 | int n, m; 30 | pll point[PPP], convex[PPP]; 31 | 32 | void convexSort() { 33 | g = point[0]; 34 | FOR(i,0,n-1) { 35 | if ( point[i].ff < g.ff ) g = point[i]; 36 | else if ( point[i].ff == g.ff && point[i].ss < g.ss ) g = point[i]; 37 | } 38 | sort ( point, point + n, convexCompare ); 39 | } 40 | void findHull() { 41 | if ( n == 1 ) { 42 | convex[0] = convex[1] = point[0]; 43 | m = 1; 44 | return; 45 | } 46 | convex[0] = point[n-1]; convex[1] = point[0]; convex[2] = point[1]; 47 | int cur = 3; 48 | for ( int i = 2; i < n; i++ ) { 49 | vlong area = triArea ( convex[cur-2], convex[cur-1], point[i] ); 50 | if ( area > 0 ) { 51 | convex[cur] = point[i]; 52 | cur++; 53 | } 54 | else if ( area == 0 ) { ///Take action depending on what is required 55 | /*Left Vertical Line gets omitted. Manually handle it*/ 56 | /*convex[cur] = point[i]; 57 | cur++;*/ 58 | ///If extra point needs to be removed 59 | convex[cur-1] = point[i]; 60 | } 61 | else { 62 | cur--; 63 | i--; 64 | } 65 | } 66 | m = cur - 1; 67 | } 68 | 69 | }hull; 70 | 71 | -------------------------------------------------------------------------------- /Geometry/Convexhull.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | vector convex_hull(vector P) 4 | { 5 | int n = P.size(), k = 0; 6 | vector H(2*n); 7 | 8 | sort(P.begin(), P.end()); 9 | 10 | for (int i = 0; i < n; ++i) { 11 | while (k >= 2 && cross(H[k-2], H[k-1], P[i]) < 0) k--; 12 | H[k++] = P[i]; 13 | } 14 | 15 | for (int i = n-2, t = k+1; i >= 0; i--) { 16 | while (k >= t && cross(H[k-2], H[k-1], P[i]) < 0) k--; 17 | H[k++] = P[i]; 18 | } 19 | 20 | H.resize(k); 21 | return H; 22 | } 23 | double dist( Point a , Point b ) { 24 | return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)) ; 25 | } 26 | int main() 27 | { 28 | int cases , caseno = 1 ; 29 | scanf("%d",&cases ) ; 30 | 31 | while( cases -- ) { 32 | scanf("%d%lf",&n,&d) ; 33 | Point temp ; 34 | for( int i = 0 ; i < n ; i++ ) { 35 | scanf("%lld%lld",&temp.x,&temp.y ); 36 | arr.push_back(temp) ; 37 | } 38 | 39 | double ANS = 0 ; 40 | if( n == 2 ) { 41 | ANS = 2*dist( arr[0] , arr[1] ) ; 42 | } else { 43 | vector ConvexHull = convex_hull( arr ) ; 44 | ConvexHull.push_back(ConvexHull[0]) ; 45 | for( int i = 0 ; i < ConvexHull.size()-1 ; i++ ){ 46 | ANS += dist( ConvexHull[i] , ConvexHull[i+1] ) ; 47 | } 48 | } 49 | printf("Case %d: %.8f\n",caseno++ , ANS+2.0*pi*d+1e-9 ) ; 50 | arr.clear() ; 51 | } 52 | 53 | return 0 ; 54 | } 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | /* 69 | ConvexHull : Graham's Scan O(n lg n), integer implementation 70 | P[]: holds all the points, C[]: holds points on the hull 71 | np: number of points in P[], nc: number of points in C[] 72 | to handle duplicate, call makeUnique() before calling convexHull() 73 | call convexHull() if you have np >= 3 74 | to remove co-linear points on hull, call compress() after convexHull() 75 | */ 76 | 77 | point P[MAX], C[MAX], P0; 78 | 79 | inline int triArea2(const point &a, const point &b, const point &c) { 80 | return (a.x*(b.y-c.y) + b.x*(c.y-a.y) + c.x*(a.y-b.y)); 81 | } 82 | 83 | inline int sqDist(const point &a, const point &b) { 84 | return ((a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y)); 85 | } 86 | 87 | inline bool comp(const point &a, const point &b) { 88 | int d = triArea2(P0, a, b); 89 | if(d < 0) return false; 90 | if(!d && sqDist(P0, a) > sqDist(P0, b)) return false; 91 | return true; 92 | } 93 | 94 | inline bool normal(const point &a, const point &b) { 95 | return ((a.x==b.x) ? a.y < b.y : a.x < b.x); 96 | } 97 | 98 | inline bool issame(const point &a, const point &b) { 99 | return (a.x == b.x && a.y == b.y); 100 | } 101 | 102 | inline void makeUnique(int &np) { 103 | sort(&P[0], &P[np], normal); 104 | np = unique(&P[0], &P[np], issame) - P; 105 | } 106 | 107 | void convexHull(int &np, int &nc) { 108 | int i, j, pos = 0; 109 | for(i = 1; i < np; i++) 110 | if(P[i].y 1 ) res = 1; 10 | return acos ( res ); 11 | } 12 | struct myVec { 13 | int d; //Dimension 14 | double val[MAXD];//Contains value of each component 15 | myVec() { 16 | d=2; 17 | memset(val,0,sizeof(val)); 18 | } 19 | myVec(double _x,double _y) { 20 | d=2; 21 | val[0]=_x; 22 | val[1]=_y; 23 | } 24 | myVec(int _d,double*a) { 25 | d=_d; 26 | for(int i=0; i eps ) return false; 52 | return true; 53 | } 54 | myVec perp2D() { 55 | myVec res = (*this); 56 | swap ( res.val[0], res.val[1] ); 57 | res.val[0] *= -1; 58 | return res; 59 | } 60 | double dot ( myVec v ) { //Finds *this (dot) v 61 | double res = 0; 62 | for ( int i = 0; i < d; i++ ) res += val[i] * v.val[i]; 63 | return res; 64 | } 65 | double length () { //Finds length of current vector 66 | return sqrt ( this->dot( *this ) ); 67 | } 68 | myVec unitVec () { 69 | return (*this).div ( length() ); // v / ||v|| 70 | } 71 | double angleBetween2D ( Vec b ) { 72 | double pol1 = atan2 ( val[1], val[0] ); 73 | double pol2 = atan2 ( b.val[1], b.val[0] ); 74 | if ( pol2 + eps < pol1 ) pol2 += 2 * pi; 75 | double x = pol2 - pol1; 76 | if ( x > pi + eps ) x = (2*pi) - x; 77 | //For direction, use sign of cross2D 78 | return x; 79 | } 80 | //Causes precision error. Use angleBetween2D when 2D. 81 | double angleBetween ( myVec b ) { //Angle between two vectors 82 | double res = dot( b ) / ( length() * b.length() ); 83 | if ( res > 1 ) res = 1; 84 | if ( res < -1 ) res = -1; 85 | return acos (res); 86 | } 87 | double polarAngle2D() { //Angle from x-axis 88 | double res = atan2 ( val[1], val[0] ); 89 | if ( res + eps < 0 ) res += 2 * pi; 90 | return res; 91 | } 92 | double cross2D ( myVec v ) { //Cross the two values. Only for 2D. Z compo 0. 93 | return val[0]*v.val[1] - val[1]*v.val[0]; 94 | } 95 | //Provided, a comes before b. Otherwise, need to swap 96 | bool between ( Vec a, Vec b ) { 97 | if ( val[0] + eps < a.val[0] || val[0] > b.val[0] + eps ) return false; 98 | if ( val[1] + eps < a.val[1] || val[1] > b.val[1] + eps ) return false; 99 | return true; 100 | } 101 | }; 102 | double triangleArea ( Vec a, Vec b, Vec c ) { 103 | double area = a.val[0] * b.val[1] + b.val[0] * c.val[1] + c.val[0] * a.val[1]; 104 | area -= b.val[0] * a.val[1] + c.val[0] * b.val[1] + a.val[0] * c.val[1]; 105 | area /= 2; 106 | return area; 107 | } 108 | double cosineRule3Side ( double a, double b, double c ) { 109 | double res = (SQ(a)+SQ(b)-SQ(c)) / (2*a*b); 110 | if ( res < -1 ) res = -1; if ( res > 1 ) res = 1; 111 | return acos ( res ); 112 | } 113 | struct myLine { 114 | myVec a, b; //a is displacement, b is direction. 115 | //Builds a line from two points 116 | myLine() {} 117 | myLine(myVec x, myVec y) { 118 | a=x;b=y.sub(x); 119 | } 120 | myLine lineFromPoints ( myVec x, myVec y ) { 121 | myLine m; 122 | m.a = x; 123 | m.b = y.sub ( x ); 124 | return m; 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]; 149 | q = atPos(1).val[1]; 150 | r = l.a.val[1]; 151 | s = l.atPos ( 1 ).val[1]; 152 | if ( min ( r, s ) > max ( p, q ) ) return false; 153 | if ( max ( r, s ) < min ( p, q ) ) return false; 154 | return true; 155 | } else { 156 | p = a.val[0]; 157 | q = atPos(1).val[0]; 158 | r = l.a.val[0]; 159 | s = l.atPos ( 1 ).val[0]; 160 | if ( min ( r, s ) > max ( p, q ) ) return false; 161 | if ( max ( r, s ) < min ( p, q ) ) return false; 162 | return true; 163 | } 164 | } 165 | char lineAndLineIntersection2D ( myLine l, double &t, double &s ) { 166 | if ( b.cross2D ( l.b) == 0 ) { 167 | if ( l.a.sub(a).cross2D(l.b) == 0 ) { 168 | if ( overlapParallel ( l ) ) return 'o'; //overlaps 169 | else return 'p'; //parallel 170 | } else return 'd'; //disjoint and parallel 171 | } 172 | myVec w = a.sub ( l.a ); 173 | myVec p = l.b.perp2D(), z = b.perp2D(); 174 | t = -(w.dot(p))/p.dot(b); //for current line 175 | s = w.dot(z)/z.dot(l.b); //for line l 176 | return 'i'; 177 | } 178 | double lineAndLineDistance2D ( myLine l ) { 179 | double t, s; //First check if the intersect 180 | char r = lineAndLineIntersection2D ( l, t, s ); 181 | if ( r == 'i' ) return 0; //Intersects. 0 distance. 182 | //Parallel Lines 183 | return lineToPointDistance ( l.a, t ); 184 | } 185 | double lineAndSegmentDistance2D ( myLine l ) { 186 | double t, s; 187 | char r = lineAndLineIntersection2D ( l, t, s ); 188 | if ( r == 'i' && s + eps > 0 && s < 1 + eps ) { 189 | return 0; //Valid intersection 190 | } 191 | double res = lineToPointDistance ( l.a, t ); 192 | res = min ( res, lineToPointDistance ( l.a.add(l.b), t ) ); 193 | return res; 194 | } 195 | double segmentAndSegmentDistance2D ( myLine l ) { 196 | double t, s; 197 | char r = lineAndLineIntersection2D ( l, t, s ); 198 | if ( r =='i' && t+eps > 0 && t < 1 + eps && s + eps > 0 && s < 1 + eps ) { 199 | return 0; //Valid intersection 200 | } 201 | double res = segmentToPointDistance ( l.a, t ); 202 | res = min ( res, segmentToPointDistance ( l.a.add(l.b), t ) ); 203 | res = min ( res, l.segmentToPointDistance ( a, t ) ); 204 | res = min ( res, l.segmentToPointDistance ( a.add ( b ), t ) ); 205 | return res; 206 | } 207 | myLine reflect ( myVec p, myVec norm ) { 208 | myVec ap = p.sub ( a ); //Starting to Point of Reflection 209 | norm = norm.unitVec(); 210 | double d = fabs ( ap.dot ( norm ) ); 211 | myVec m = p.add ( norm.mul ( d ) ); 212 | myVec h = m.sub ( a ).mul ( 2 ); 213 | m = a.add ( h ); 214 | myLine ray = ray.lineFromPoints ( p, m ); 215 | return ray; 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 | myVec m = l.atPos ( t3 ); 233 | myVec am = m.sub ( a ); 234 | //Need to handle when line passes through center 235 | double x = am.polarAngle2D(); 236 | double temp = d / r; 237 | if ( temp > 1 ) temp = 1; 238 | if ( temp < -1 ) temp = -1; 239 | double theta = pi / 2 - asin ( temp ); //Using sin law find internal angle. 240 | t1 = x + theta; 241 | t2 = x - theta; 242 | return 'i'; 243 | } 244 | char sphereAndLineIntersect ( myLine l, double &t1, double &t2 ) { 245 | double tp = 0; 246 | double d = l.lineToPointDistance ( a, tp ); 247 | if ( d > r + eps ) return 'd'; 248 | if ( fabs ( d - r ) < eps ) { 249 | t1 = tp; 250 | return 't'; 251 | } 252 | double chord = sqrt ( r * r - d * d ); 253 | t1 = tp - chord / l.b.length(); 254 | t2 = tp + chord / l.b.length(); 255 | return 'i'; 256 | } 257 | char circleAndCircleIntersection2D ( myCir c2, double &t1, double &t2 ) { 258 | myVec d = c2.a.sub ( a ); 259 | if ( d.length() > r + c2.r + eps ) return 'd'; //Case 1 260 | if ( d.length() + c2.r + eps < r ) return 'd'; //Case 2 261 | if ( a == c2.a && fabs ( r - c2.r ) <= eps ) { 262 | if ( r == 0 ) { 263 | t1 = 0; 264 | return 't'; //Case 7 265 | } 266 | return 's'; //Case 6 267 | } 268 | if ( fabs ( d.length() - r - c2.r ) <= eps || 269 | fabs ( d.length() + c2.r - r ) <= eps ) { 270 | t1 = d.polarAngle2D(); 271 | return 't'; //Case 3 and 4 272 | } 273 | double theta = cosineRule3Side ( r, d.length(), c2.r ); 274 | double m = d.polarAngle2D (); 275 | t1 = m - theta; 276 | t2 = m + theta; 277 | return 'i'; //Case 5 278 | } 279 | int circleToCircleTangentLine (myCir c2,myLine &l1,myLine &l2,myLine &l3,myLine &l4) { 280 | //First circle must be smaller or equal to second circle 281 | if (r>c2.r + eps ) return c2.circleToCircleTangentLine ( *this, l1, l2, l3, l4 ); 282 | myVec oo = c2.a.sub ( a ); 283 | double d = oo.length(); 284 | if ( fabs ( d ) < eps && fabs ( r - c2.r ) < eps ) //Infinite tangents 285 | return -1; 286 | if ( d + r + eps < c2.r ) //No tangents 287 | return 0; 288 | double base = oo.polarAngle2D(); 289 | if ( fabs ( d + r - c2.r ) < eps ) { //Contains Circle 290 | l1 = l1.lineFromPoints ( atPos ( base + pi ), atPos ( base + pi ) ); 291 | return 1; 292 | } 293 | double ang = pi - acos ( (c2.r - r ) / d ); 294 | l1 = l1.lineFromPoints ( atPos ( base + ang ), c2.atPos ( base + ang ) ); 295 | l2 = l2.lineFromPoints ( atPos ( base - ang ), c2.atPos ( base - ang ) ); 296 | if ( d + eps < r + c2.r ) return 2; //Circle intersects 297 | if ( fabs ( d - r - c2.r ) < eps ) { //Circle tangent 298 | l3 = l3.lineFromPoints ( atPos ( base ), atPos ( base ) ); 299 | return 3; 300 | } 301 | //Disjoint Circle 302 | ang = acos ( ( c2.r + r ) / d ); 303 | l3 = l3.lineFromPoints ( atPos ( base + ang ), c2.atPos ( base + ang + pi ) ); 304 | l4 = l4.lineFromPoints ( atPos ( base - ang ), c2.atPos ( base - ang + pi ) ); 305 | return 4; 306 | } 307 | }; 308 | bool collinear ( myVec a, myVec b, myVec c ) { 309 | myVec ab = b.sub(a), ac = c.sub(a); 310 | double d = fabs ( ab.dot(ac) ); 311 | if ( fabs ( d - ab.length() * ac.length() ) <= eps ) return true; 312 | return false; 313 | } 314 | bool collinear ( myVec a, myVec b, myVec c ) { 315 | myVec ab = b.sub(a), ac = c.sub(a); 316 | double d = fabs ( ab.dot(ac) ); 317 | if ( fabs ( d - ab.length() * ac.length() ) <= eps ) return true; 318 | return false; 319 | } 320 | 321 | //Find if C is between A and B or B and A 322 | bool pointBetween ( pii a, pii b, pii c ) { 323 | 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; 324 | else return false; 325 | } 326 | 327 | //Determine if (a,b) and (c,d) line intersects. All points are integer 328 | bool integerPointLineIntersect ( pii a, pii b, pii c, pii d ) { 329 | 330 | int s1 = triArea( a, b, c ); 331 | int s2 = triArea( a, b, d ); 332 | int s3 = triArea( c, d, a ); 333 | int s4 = triArea( c, d, b ); 334 | 335 | if ( s1 * s2 > 0 || s3 * s4 > 0 ) return false; 336 | if ( s1 && s2 && s3 && s4 ) return true; 337 | return ( between( a, b, c ) || between( a, b, d ) || between( c, d, a ) || between( c, d, b ) ); 338 | } 339 | -------------------------------------------------------------------------------- /Geometry/LineSegmentIntersection.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #define rep(i,n) for( int i = 0 ; i < n ; i++ ) 4 | #define x first 5 | #define y second 6 | #define eps 1e-9 7 | using namespace std ; 8 | 9 | 10 | #define MAXD 2 11 | #define FOR(i,b,c) for(int i = b ; i < c ; i++ ) 12 | #define eps 1e-9 13 | #define pi acos(-1.0) 14 | double mx = numeric_limits::max()-1 ; 15 | struct Vec { 16 | 17 | int d; //Dimension 18 | double val[MAXD];//Contains value of each component 19 | Vec() { 20 | d=2; 21 | } 22 | Vec( double a , double b ,double c ) { 23 | val[0] = a ; 24 | val[1] = b ; 25 | val[2] = c ; 26 | d = 3 ; 27 | } 28 | Vec( double a , double b ) { 29 | val[0] = a ; 30 | val[1] = b ; 31 | d = 2 ; 32 | } 33 | Vec add ( Vec b ) { 34 | Vec res; 35 | FOR(i,0,d) res.val[i] = val[i] + b.val[i]; 36 | return res; 37 | } 38 | Vec sub ( Vec b ) { 39 | Vec res; 40 | FOR(i,0,d) res.val[i] = val[i] - b.val[i]; 41 | return res; 42 | } 43 | Vec mul ( double t ) { 44 | Vec res; 45 | FOR(i,0,d)res.val[i] = val[i] * t; 46 | return res; 47 | } 48 | Vec div ( double t ) { 49 | Vec res; 50 | FOR(i,0,d) res.val[i] = val[i] / t; 51 | return res; 52 | } 53 | bool operator == ( Vec b ) { 54 | FOR(i,0,d) if ( fabs ( val[i] - b.val[i] ) > eps ) return false; 55 | return true; 56 | } 57 | Vec perp2D() { 58 | Vec res = (*this); 59 | swap ( res.val[0], res.val[1] ); 60 | res.val[0] *= -1; 61 | return res; 62 | } 63 | double dot ( Vec v ) { //Finds *this (dot) v 64 | double res = 0; 65 | d = 2 ; 66 | for ( int i = 0; i < d; i++ ) res += val[i] * v.val[i]; 67 | return res; 68 | } 69 | double length () { //Finds length of current Vec 70 | return sqrt ( this->dot( *this ) ); 71 | } 72 | Vec unitVec () { 73 | return (*this).div ( length() ); // v / ||v|| 74 | } 75 | double angleBetween ( Vec b ) { //Angle between two Vecs 76 | double res = dot( b ) / ( length() * b.length() ); 77 | if ( res > 1 ) res = 1; 78 | if ( res < -1 ) res = -1; 79 | return acos (res); 80 | } 81 | double polarAngle2D() { //Angle from x-axis 82 | double res = atan2 ( val[1], val[0] ); 83 | if ( res + eps < 0 ) res += 2 * pi; 84 | return res; 85 | } 86 | double dist( Vec a ) { 87 | if( a.d != d )cout << "Wrong dimension to calculate in sqdist function\n" ; 88 | double ret = 0 ; 89 | for( int i = 0 ; i < d ; i++ ) { 90 | ret += ( val[i] - a.val[i] )*( val[i] - a.val[i] ) ; 91 | } 92 | return sqrt(ret) ; 93 | } 94 | double sqdist( Vec a ) { 95 | if( a.d != d )cout << "Wrong dimension to calculate in sqdist function\n" ; 96 | double ret = 0 ; 97 | for( int i = 0 ; i < d ; i++ ) { 98 | ret += ( val[i] - a.val[i] )*( val[i] - a.val[i] ) ; 99 | } 100 | return (ret) ; 101 | } 102 | double cross2D ( Vec v ) { //Cross the two values. Only for 2D. Z compo 0. 103 | return val[0]*v.val[1] - val[1]*v.val[0]; 104 | } 105 | double isLeft( Vec st , Vec en ) { 106 | return ( (en.val[0] - st.val[0])*(val[1] - st.val[1]) 107 | - (val[0] - st.val[0])*(en.val[1] - st.val[1]) ) ; ; 108 | } 109 | }; 110 | 111 | struct Line { 112 | Vec a, b; //a is displacement, b is direction. 113 | //Builds a Line from two points 114 | Line() {} 115 | Line( Vec x, Vec y ) { 116 | a = x; 117 | b = y.sub ( x ); 118 | } 119 | Line( Vec x, Vec y , bool p ) { 120 | a = x; 121 | b = y; 122 | //assign a direction vector 123 | } 124 | Line LineFromPoints ( Vec x, Vec y ) { 125 | Line m; 126 | m.a = x; 127 | m.b = y.sub ( x ); 128 | return m; 129 | } 130 | //Finds point on Line, given t. 131 | double length() { 132 | return b.length(); 133 | } 134 | Vec atPos ( double t ) { 135 | return a.add ( b.mul ( t ) ); // a + tb; 136 | } 137 | double calT( Vec pt ) { 138 | double d1 = a.dist( pt ) ; 139 | double d2 = sqrt(b.val[0]*b.val[0]+b.val[1]*b.val[1]) ; 140 | Vec q = Vec(a.val[0]+b.val[0],a.val[1]+b.val[1]) ; 141 | 142 | double s1 = q.isLeft( Vec(0,0) , a ); 143 | double s2 = pt.isLeft(Vec(0,0) , a ) ; 144 | double mul = 1 ; 145 | if( s1 >= 0 && s2 < 0 )mul = -1 ; 146 | if( s1 < 0 && s2 >= 0 )mul = -1 ; 147 | 148 | return mul*d1/d2 ; 149 | } 150 | double LineToPointDistance ( Vec p, double t ) { 151 | p = p.sub ( a ); //Take it to origin 152 | t = b.dot ( p ) / ( b.length() * b.length() ); //point of intersection 153 | Vec x = b.mul ( t ); //tb 154 | return ( p.sub(x).length() ); //xp length() 155 | } 156 | double segmentToPointDistance ( Vec p, double &t ) { 157 | p = p.sub ( a ); //Take it to origin 158 | t = b.dot ( p ) / ( b.length() * b.length() ); 159 | if ( t + eps < 0 || t > 1 + eps ) { //Not on segment 160 | return min ( p.length(), p.sub(b).length() ); 161 | } 162 | Vec x = b.mul ( t ); //tb 163 | return ( p.sub(x).length() ); //xp length() 164 | } 165 | bool overlapParallel ( Line l ) { 166 | double p, q, r, s; 167 | if ( b.val[0] == 0 ) { 168 | p = a.val[1]; 169 | q = atPos(1).val[1]; 170 | r = l.a.val[1]; 171 | s = l.atPos ( 1 ).val[1]; 172 | if ( min ( r, s ) > max ( p, q ) ) return false; 173 | if ( max ( r, s ) < min ( p, q ) ) return false; 174 | return true; 175 | } else { 176 | p = a.val[0]; 177 | q = atPos(1).val[0]; 178 | r = l.a.val[0]; 179 | s = l.atPos ( 1 ).val[0]; 180 | if ( min ( r, s ) > max ( p, q ) ) return false; 181 | if ( max ( r, s ) < min ( p, q ) ) return false; 182 | return true; 183 | } 184 | } 185 | char LineAndLineIntersection2D ( Line l, double &t, double &s ) { 186 | if ( b.cross2D ( l.b) == 0 ) { 187 | if ( l.a.sub(a).cross2D(l.b) == 0 ) { 188 | if ( overlapParallel ( l ) ) return 'o'; //overlaps 189 | else return 'p'; //parallel 190 | } else return 'd'; //disjoint and parallel 191 | } 192 | Vec w = a.sub ( l.a ); 193 | Vec p = l.b.perp2D(), z = b.perp2D(); 194 | t = -(w.dot(p))/p.dot(b); //for current Line 195 | s = w.dot(z)/z.dot(l.b); //for Line l 196 | return 'i'; 197 | } 198 | double LineAndLineDistance2D ( Line l ) { 199 | double t, s; //First check if the intersect 200 | char r = LineAndLineIntersection2D ( l, t, s ); 201 | if ( r == 'i' ) return 0; //Intersects. 0 distance. 202 | //Parallel Lines 203 | return LineToPointDistance ( l.a, t ); 204 | } 205 | double LineAndSegmentDistance2D ( Line l ) { 206 | double t, s; 207 | char r = LineAndLineIntersection2D ( l, t, s ); 208 | if ( r == 'i' && s + eps > 0 && s < 1 + eps ) { 209 | return 0; //Valid intersection 210 | } 211 | double res = LineToPointDistance ( l.a, t ); 212 | res = min ( res, LineToPointDistance ( l.a.add(l.b), t ) ); 213 | return res; 214 | } 215 | double segmentAndSegmentDistance2D ( Line l ) { 216 | double t, s; 217 | char r = LineAndLineIntersection2D ( l, t, s ); 218 | if ( r =='i' && t+eps > 0 && t < 1 + eps && s + eps > 0 && s < 1 + eps ) { 219 | return 0; //Valid intersection 220 | } 221 | double res = segmentToPointDistance ( l.a, t ); 222 | res = min ( res, segmentToPointDistance ( l.a.add(l.b), t ) ); 223 | res = min ( res, l.segmentToPointDistance ( a, t ) ); 224 | res = min ( res, l.segmentToPointDistance ( a.add ( b ), t ) ); 225 | return res; 226 | } 227 | Line reflect ( Vec p, Vec norm ) { 228 | Vec ap = p.sub ( a ); //Starting to Point of Reflection 229 | norm = norm.unitVec(); 230 | 231 | double d = fabs ( ap.dot ( norm ) ); 232 | 233 | Vec m = p.add ( norm.mul ( d ) ); 234 | Vec h = m.sub ( a ).mul ( 2 ); 235 | m = a.add ( h ); 236 | 237 | Line ray = ray.LineFromPoints ( p, m ); 238 | return ray; 239 | } 240 | }; 241 | 242 | vector< Vec > V ; 243 | 244 | pair getcenter( Vec V1 , Vec V2 , double R ) { 245 | if( (V1.dist(V2)/2.0) > (R+eps)) return {Vec(mx,mx),Vec(mx,mx)} ; 246 | Vec dr = V2.sub(V1) ; 247 | dr = dr.unitVec() ; 248 | swap( dr.val[0] , dr.val[1] ) ; 249 | dr.val[0] = -dr.val[0] ; 250 | Vec pt = V1.add(V2).div(2) ; 251 | double t = sqrt(R*R-V1.sqdist(V2)/4) ; 252 | Vec ret1 = pt.add(dr.mul(t)) ; 253 | Vec ret2 = pt.sub(dr.mul(t)) ; 254 | return {ret1,ret2} ; 255 | 256 | } 257 | -------------------------------------------------------------------------------- /Geometry/PointInPolygon.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | C[] array of points of convex polygon in ccw order, 3 | nc number of points in C, p target points. 4 | returns true if p is inside C (including edge) or false otherwise. 5 | complexity O(lg n) 6 | */ 7 | 8 | inline bool inConvexPoly(point *C, int nc, const point &p) { 9 | int st = 1, en = nc - 1, mid; 10 | while(en - st > 1) { 11 | mid = (st + en)>>1; 12 | if(triArea2(C[0], C[mid], p) < 0) en = mid; 13 | else st = mid; 14 | } 15 | if(triArea2(C[0], C[st], p) < 0) return false; 16 | if(triArea2(C[st], C[en], p) < 0) return false; 17 | if(triArea2(C[en], C[0], p) < 0) return false; 18 | return true; 19 | } 20 | 21 | 22 | 23 | 24 | int crossproduct(pair a , pair b , pairp ){ 25 | return ((a.x-p.x)*(b.y-p.y)-(a.y-p.y)*(b.x-p.x)) ; 26 | } 27 | 28 | bool isInsidePolygon( pair P[] , pair sample , int n ){ 29 | 30 | int cnt = 0 ; 31 | bool f = 0 ; 32 | for( int i = 0 , j = n-1 ; i < n ; j = i++ ){ 33 | 34 | int Xmin = min( P[i].x,P[j].x ) ; 35 | int Xmax = max( P[i].x,P[j].x ) ; 36 | 37 | int Ymin = min( P[i].y,P[j].y ) ; 38 | int Ymax = ma 39 | x( P[i].y,P[j].y ) ; 40 | 41 | if( Xmin <= sample.x && sample.x <= Xmax && Ymin <= sample.y && sample.y <= Ymax){ 42 | if( crossproduct( P[i] , P[j] , sample ) == 0 )return true ; 43 | } 44 | if( crossproduct( P[i] , P[j] , sample ) < 0 ){ 45 | swap( P[i],P[j] ) ; 46 | f = 1 ; 47 | } 48 | 49 | if( P[i].y >= sample.y && P[j].y < sample.y )cnt++ ; 50 | if( f == 1 ){ 51 | f = 0 ; 52 | swap( P[i],P[j] ) ; 53 | } 54 | } 55 | return ( cnt & 1 ) ; 56 | 57 | } 58 | 59 | 60 | /* 61 | P[] holds the points, must be either in cw or ccw 62 | function returns double of the area. 63 | */ 64 | 65 | inline int dArea(int np) { 66 | int area = 0; 67 | for(int i = 0; i < np; i++) { 68 | area += p[i].x*p[i+1].y - p[i].y*p[i+1].x; 69 | } 70 | return abs(area); 71 | } 72 | -------------------------------------------------------------------------------- /Geometry/RotatePoint.cpp: -------------------------------------------------------------------------------- 1 | pair Rotate_Point( pair P ,pair Ref ,double dist, double cosA ,double sinA ){ 2 | 3 | //if only theta comes then sinA= sin(theta) , conA = cos( theta ) ; 4 | double a = sqrt( (P.first-Ref.first)*(P.first-Ref.first) + (P.second-Ref.second)*(P.second-Ref.second) ) ; 5 | 6 | double x1 = (dist*(Ref.first-P.first))/a ; 7 | double y1 = (dist*(Ref.second-P.second))/a ; 8 | 9 | pair ret ; 10 | ret.first = x1*cosA-y1*sinA+P.first ; 11 | ret.second = x1*sinA+y1*cosA+P.second ; 12 | 13 | return ret ; 14 | 15 | } 16 | -------------------------------------------------------------------------------- /Geometry/TanOfLine.cpp: -------------------------------------------------------------------------------- 1 | pair TanOfLine( pair a , pair b ) 2 | { 3 | 4 | const int INF = 1<<30 ; 5 | pair M ; 6 | 7 | if( a.y == b.y ) { 8 | M.x = INF ; 9 | M.y = INF ; 10 | } else { 11 | M.x = a.x-b.x ; 12 | M.y = a.y-b.y ; 13 | int tmp = __gcd( (M.x),(M.y) ) ; 14 | M.x = M.x/tmp ; 15 | M.y = M.y/tmp ; 16 | } 17 | return M ; 18 | } 19 | -------------------------------------------------------------------------------- /Graph/ Stoer Wagner all pair Min Cut.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Algorithm : Stoer Wagner all pair Min Cut 3 | * Complextity : O( n^3 ) 4 | * Note : All vertex is 1 based indexing 5 | */ 6 | #include 7 | #include 8 | using namespace std; 9 | #define MAX_V 1007 10 | #define INF 777777777 11 | long nV,nE; 12 | long Cap[MAX_V+7][MAX_V+7]; 13 | long Dist[MAX_V+7],Done[MAX_V+7]; 14 | long Best,Ind; 15 | 16 | long AllPairMinCut( void ) { 17 | long i,j,u,v,Ans = INF,N = nV; 18 | while( N > 1 ) { 19 | memset( Dist,0,sizeof(Dist)); 20 | memset( Done,0,sizeof(Done)); 21 | for( i=1; i<=N; i++) { 22 | Best = Ind = -1; 23 | for( j=1; j<=N; j++ ) { 24 | if(!Done[j] && Dist[j] > Best) { 25 | Best = Dist[j]; 26 | Ind = j; 27 | } 28 | } 29 | if( i+1==N ) u = Ind; 30 | if( i==N ) { 31 | v = Ind; 32 | Ans = min( Ans,Best ); 33 | } 34 | Done[Ind] = 1; 35 | for( j=1; j<=N; j++) { 36 | Dist[j] += Cap[Ind][j]; 37 | } 38 | } 39 | if( u > v) swap( u,v); 40 | for( i=1; i<=N; i++ ) { 41 | Cap[u][i] += Cap[v][i]; 42 | Cap[i][u] += Cap[i][v]; 43 | } 44 | for( i=1; i<=N; i++) { 45 | Cap[v][i] = Cap[N][i]; 46 | Cap[i][v] = Cap[i][N]; 47 | } 48 | N--; 49 | } 50 | return Ans; 51 | } 52 | 53 | int main( void) { 54 | memset(Cap,0,sizeof(Cap)); 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /Graph/ArticulationPoint.cpp: -------------------------------------------------------------------------------- 1 | // A C++ program to find articulation points in a given undirected graph 2 | #include 3 | #include 4 | #define NIL -1 5 | using namespace std; 6 | 7 | // A class that represents an undirected graph 8 | class Graph 9 | { 10 | int V; // No. of vertices 11 | list *adj; // A dynamic array of adjacency lists 12 | void APUtil(int v, bool visited[], int disc[], int low[], 13 | int parent[], bool ap[]); 14 | public: 15 | Graph(int V); // Constructor 16 | void addEdge(int v, int w); // function to add an edge to graph 17 | void AP(); // prints articulation points 18 | }; 19 | 20 | Graph::Graph(int V) 21 | { 22 | this->V = V; 23 | adj = new list[V]; 24 | } 25 | 26 | void Graph::addEdge(int v, int w) 27 | { 28 | adj[v].push_back(w); 29 | adj[w].push_back(v); // Note: the graph is undirected 30 | } 31 | 32 | // A recursive function that find articulation points using DFS traversal 33 | // u --> The vertex to be visited next 34 | // visited[] --> keeps tract of visited vertices 35 | // disc[] --> Stores discovery times of visited vertices 36 | // parent[] --> Stores parent vertices in DFS tree 37 | // ap[] --> Store articulation points 38 | void Graph::APUtil(int u, bool visited[], int disc[], 39 | int low[], int parent[], bool ap[]) 40 | { 41 | // A static variable is used for simplicity, we can avoid use of static 42 | // variable by passing a pointer. 43 | static int time = 0; 44 | 45 | // Count of children in DFS Tree 46 | int children = 0; 47 | 48 | // Mark the current node as visited 49 | visited[u] = true; 50 | 51 | // Initialize discovery time and low value 52 | disc[u] = low[u] = ++time; 53 | 54 | // Go through all vertices aadjacent to this 55 | list::iterator i; 56 | for (i = adj[u].begin(); i != adj[u].end(); ++i) 57 | { 58 | int v = *i; // v is current adjacent of u 59 | 60 | // If v is not visited yet, then make it a child of u 61 | // in DFS tree and recur for it 62 | if (!visited[v]) 63 | { 64 | children++; 65 | parent[v] = u; 66 | APUtil(v, visited, disc, low, parent, ap); 67 | 68 | // Check if the subtree rooted with v has a connection to 69 | // one of the ancestors of u 70 | low[u] = min(low[u], low[v]); 71 | 72 | // u is an articulation point in following cases 73 | 74 | // (1) u is root of DFS tree and has two or more chilren. 75 | if (parent[u] == NIL && children > 1) 76 | ap[u] = true; 77 | 78 | // (2) If u is not root and low value of one of its child is more 79 | // than discovery value of u. 80 | if (parent[u] != NIL && low[v] >= disc[u]) 81 | ap[u] = true; 82 | } 83 | 84 | // Update low value of u for parent function calls. 85 | else if (v != parent[u]) 86 | low[u] = min(low[u], disc[v]); 87 | } 88 | } 89 | 90 | // The function to do DFS traversal. It uses recursive function APUtil() 91 | void Graph::AP() 92 | { 93 | // Mark all the vertices as not visited 94 | bool *visited = new bool[V]; 95 | int *disc = new int[V]; 96 | int *low = new int[V]; 97 | int *parent = new int[V]; 98 | bool *ap = new bool[V]; // To store articulation points 99 | 100 | // Initialize parent and visited, and ap(articulation point) arrays 101 | for (int i = 0; i < V; i++) 102 | { 103 | parent[i] = NIL; 104 | visited[i] = false; 105 | ap[i] = false; 106 | } 107 | 108 | // Call the recursive helper function to find articulation points 109 | // in DFS tree rooted with vertex 'i' 110 | for (int i = 0; i < V; i++) 111 | if (visited[i] == false) 112 | APUtil(i, visited, disc, low, parent, ap); 113 | 114 | // Now ap[] contains articulation points, print them 115 | for (int i = 0; i < V; i++) 116 | if (ap[i] == true) 117 | cout << i << " "; 118 | } 119 | 120 | // Driver program to test above function 121 | int main() 122 | { 123 | // Create graphs given in above diagrams 124 | cout << "\nArticulation points in first graph \n"; 125 | Graph g1(5); 126 | g1.addEdge(1, 0); 127 | g1.addEdge(0, 2); 128 | g1.addEdge(2, 1); 129 | g1.addEdge(0, 3); 130 | g1.addEdge(3, 4); 131 | g1.AP(); 132 | 133 | cout << "\nArticulation points in second graph \n"; 134 | Graph g2(4); 135 | g2.addEdge(0, 1); 136 | g2.addEdge(1, 2); 137 | g2.addEdge(2, 3); 138 | g2.AP(); 139 | 140 | cout << "\nArticulation points in third graph \n"; 141 | Graph g3(7); 142 | g3.addEdge(0, 1); 143 | g3.addEdge(1, 2); 144 | g3.addEdge(2, 0); 145 | g3.addEdge(1, 3); 146 | g3.addEdge(1, 4); 147 | g3.addEdge(1, 6); 148 | g3.addEdge(3, 5); 149 | g3.addEdge(4, 5); 150 | g3.AP(); 151 | 152 | return 0; 153 | } 154 | -------------------------------------------------------------------------------- /Graph/BellmanFord.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std ; 3 | 4 | int N , R , P ; 5 | int U[9900+1] , V[9900+1] , C[9900+1] , D[101] ; 6 | 7 | int main() { 8 | 9 | int cases , caseno = 1 ; 10 | //scanf("%d",&cases ) ; 11 | cases = readInt() ; 12 | 13 | while( cases -- ) { 14 | 15 | //scanf("%d%d%d",&N,&R,&P) ; 16 | N = readInt() ; 17 | R = readInt() ; 18 | P = readInt() ; 19 | for( int i = 0 ;i < R ; i++ ){ 20 | int e ; 21 | //scanf("%d%d%d%d" , &U[i],&V[i],&C[i],&e) ; 22 | U[i] = readInt() ; 23 | V[i] = readInt() ; 24 | C[i] = readInt() ; 25 | e = readInt() ; 26 | C[i] = P*e-C[i] ; 27 | } 28 | memset( D , (1<<30) , sizeof D ) ; 29 | D[0] = 0 ; 30 | bool isCycle = 0 ; 31 | for( int i = 0 ; i < N ; i++ ){ 32 | bool brk = 0 ; 33 | for( int j = 0 ; j < R ; j++ ){ 34 | int u = U[j] ; 35 | int v = V[j] ; 36 | if( D[u] + C[j] < D[v] ){ 37 | brk = 1 ; 38 | if( i == (N-1) )isCycle =1 ; 39 | else D[v] = D[u] + C[j] ; 40 | } 41 | } 42 | if( !brk ) break ; 43 | } 44 | 45 | if( isCycle )cout << "Case " << caseno++ << ": YES\n" ; 46 | else cout << "Case " << caseno++ << ": NO\n" ; 47 | } 48 | 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /Graph/BiConnectedComponent.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #define NIL -1 5 | using namespace std; 6 | int count = 0; 7 | class Edge 8 | { 9 | public: 10 | int u; 11 | int v; 12 | Edge(int u, int v); 13 | }; 14 | Edge::Edge(int u, int v) 15 | { 16 | this->u = u; 17 | this->v = v; 18 | } 19 | 20 | // A class that represents an directed graph 21 | class Graph 22 | { 23 | int V; // No. of vertices 24 | int E; // No. of edges 25 | list *adj; // A dynamic array of adjacency lists 26 | 27 | // A Recursive DFS based function used by BCC() 28 | void BCCUtil(int u, int disc[], int low[], 29 | list *st, int parent[]); 30 | public: 31 | Graph(int V); // Constructor 32 | void addEdge(int v, int w); // function to add an edge to graph 33 | void BCC(); // prints strongly connected components 34 | }; 35 | 36 | Graph::Graph(int V) 37 | { 38 | this->V = V; 39 | this->E = 0; 40 | adj = new list[V]; 41 | } 42 | 43 | void Graph::addEdge(int v, int w) 44 | { 45 | adj[v].push_back(w); 46 | E++; 47 | } 48 | 49 | // A recursive function that finds and prints strongly connected 50 | // components using DFS traversal 51 | // u --> The vertex to be visited next 52 | // disc[] --> Stores discovery times of visited vertices 53 | // low[] -- >> earliest visited vertex (the vertex with minimum 54 | // discovery time) that can be reached from subtree 55 | // rooted with current vertex 56 | // *st -- >> To store visited edges 57 | void Graph::BCCUtil(int u, int disc[], int low[], list *st, 58 | int parent[]) 59 | { 60 | // A static variable is used for simplicity, we can avoid use 61 | // of static variable by passing a pointer. 62 | static int time = 0; 63 | 64 | // Initialize discovery time and low value 65 | disc[u] = low[u] = ++time; 66 | int children = 0; 67 | 68 | // Go through all vertices adjacent to this 69 | list::iterator i; 70 | for (i = adj[u].begin(); i != adj[u].end(); ++i) 71 | { 72 | int v = *i; // v is current adjacent of 'u' 73 | 74 | // If v is not visited yet, then recur for it 75 | if (disc[v] == -1) 76 | { 77 | children++; 78 | parent[v] = u; 79 | //store the edge in stack 80 | st->push_back(Edge(u,v)); 81 | BCCUtil(v, disc, low, st, parent); 82 | 83 | // Check if the subtree rooted with 'v' has a 84 | // connection to one of the ancestors of 'u' 85 | // Case 1 -- per Strongly Connected Components Article 86 | low[u] = min(low[u], low[v]); 87 | 88 | //If u is an articulation point, 89 | //pop all edges from stack till u -- v 90 | if( (disc[u] == 1 && children > 1) || 91 | (disc[u] > 1 && low[v] >= disc[u]) ) 92 | { 93 | while(st->back().u != u || st->back().v != v) 94 | { 95 | cout << st->back().u << "--" << st->back().v << " "; 96 | st->pop_back(); 97 | } 98 | cout << st->back().u << "--" << st->back().v; 99 | st->pop_back(); 100 | cout << endl; 101 | count++; 102 | } 103 | } 104 | 105 | // Update low value of 'u' only of 'v' is still in stack 106 | // (i.e. it's a back edge, not cross edge). 107 | // Case 2 -- per Strongly Connected Components Article 108 | else if(v != parent[u] && disc[v] < low[u]) 109 | { 110 | low[u] = min(low[u], disc[v]); 111 | st->push_back(Edge(u,v)); 112 | } 113 | } 114 | } 115 | 116 | // The function to do DFS traversal. It uses BCCUtil() 117 | void Graph::BCC() 118 | { 119 | int *disc = new int[V]; 120 | int *low = new int[V]; 121 | int *parent = new int[V]; 122 | list *st = new list[E]; 123 | 124 | // Initialize disc and low, and parent arrays 125 | for (int i = 0; i < V; i++) 126 | { 127 | disc[i] = NIL; 128 | low[i] = NIL; 129 | parent[i] = NIL; 130 | } 131 | 132 | for (int i = 0; i < V; i++) 133 | { 134 | if (disc[i] == NIL) 135 | BCCUtil(i, disc, low, st, parent); 136 | 137 | int j = 0; 138 | //If stack is not empty, pop all edges from stack 139 | while(st->size() > 0) 140 | { 141 | j = 1; 142 | cout << st->back().u << "--" << st->back().v << " "; 143 | st->pop_back(); 144 | } 145 | if(j == 1) 146 | { 147 | cout << endl; 148 | count++; 149 | } 150 | } 151 | } 152 | 153 | // Driver program to test above function 154 | int main() 155 | { 156 | Graph g(12); 157 | g.addEdge(0,1);g.addEdge(1,0); 158 | g.addEdge(1,2);g.addEdge(2,1); 159 | g.addEdge(1,3);g.addEdge(3,1); 160 | g.addEdge(2,3);g.addEdge(3,2); 161 | g.addEdge(2,4);g.addEdge(4,2); 162 | g.addEdge(3,4);g.addEdge(4,3); 163 | g.addEdge(1,5);g.addEdge(5,1); 164 | g.addEdge(0,6);g.addEdge(6,0); 165 | g.addEdge(5,6);g.addEdge(6,5); 166 | g.addEdge(5,7);g.addEdge(7,5); 167 | g.addEdge(5,8);g.addEdge(8,5); 168 | g.addEdge(7,8);g.addEdge(8,7); 169 | g.addEdge(8,9);g.addEdge(9,8); 170 | g.addEdge(10,11);g.addEdge(11,10); 171 | g.BCC(); 172 | cout << "Above are " << count << " biconnected components in graph"; 173 | return 0; 174 | } 175 | -------------------------------------------------------------------------------- /Graph/BreadthFirstSearch.cpp: -------------------------------------------------------------------------------- 1 | // Program to print BFS traversal from a given 2 | // source vertex. BFS(int s) traverses vertices 3 | // reachable from s. 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | // This class represents a directed graph using 10 | // adjacency list representation 11 | class Graph 12 | { 13 | int V; // No. of vertices 14 | 15 | // Pointer to an array containing adjacency 16 | // lists 17 | list *adj; 18 | public: 19 | Graph(int V); // Constructor 20 | 21 | // function to add an edge to graph 22 | void addEdge(int v, int w); 23 | 24 | // prints BFS traversal from a given source s 25 | void BFS(int s); 26 | }; 27 | 28 | Graph::Graph(int V) 29 | { 30 | this->V = V; 31 | adj = new list[V]; 32 | } 33 | 34 | void Graph::addEdge(int v, int w) 35 | { 36 | adj[v].push_back(w); // Add w to v’s list. 37 | } 38 | 39 | void Graph::BFS(int s) 40 | { 41 | // Mark all the vertices as not visited 42 | bool *visited = new bool[V]; 43 | for(int i = 0; i < V; i++) 44 | visited[i] = false; 45 | 46 | // Create a queue for BFS 47 | list queue; 48 | 49 | // Mark the current node as visited and enqueue it 50 | visited[s] = true; 51 | queue.push_back(s); 52 | 53 | // 'i' will be used to get all adjacent 54 | // vertices of a vertex 55 | list::iterator i; 56 | 57 | while(!queue.empty()) 58 | { 59 | // Dequeue a vertex from queue and print it 60 | s = queue.front(); 61 | cout << s << " "; 62 | queue.pop_front(); 63 | 64 | // Get all adjacent vertices of the dequeued 65 | // vertex s. If a adjacent has not been visited, 66 | // then mark it visited and enqueue it 67 | for (i = adj[s].begin(); i != adj[s].end(); ++i) 68 | { 69 | if (!visited[*i]) 70 | { 71 | visited[*i] = true; 72 | queue.push_back(*i); 73 | } 74 | } 75 | } 76 | } 77 | 78 | // Driver program to test methods of graph class 79 | int main() 80 | { 81 | // Create a graph given in the above diagram 82 | Graph g(4); 83 | g.addEdge(0, 1); 84 | g.addEdge(0, 2); 85 | g.addEdge(1, 2); 86 | g.addEdge(2, 0); 87 | g.addEdge(2, 3); 88 | g.addEdge(3, 3); 89 | 90 | cout << "Following is Breadth First Traversal " 91 | << "(starting from vertex 2) \n"; 92 | g.BFS(2); 93 | 94 | return 0; 95 | } -------------------------------------------------------------------------------- /Graph/Bridge.cpp: -------------------------------------------------------------------------------- 1 | // A C++ program to find bridges in a given undirected graph 2 | #include 3 | #include 4 | #define NIL -1 5 | using namespace std; 6 | 7 | // A class that represents an undirected graph 8 | class Graph 9 | { 10 | int V; // No. of vertices 11 | list *adj; // A dynamic array of adjacency lists 12 | void bridgeUtil(int v, bool visited[], int disc[], int low[], int parent[]); 13 | public: 14 | Graph(int V); // Constructor 15 | void addEdge(int v, int w); // function to add an edge to graph 16 | void bridge(); // prints all bridges 17 | }; 18 | 19 | Graph::Graph(int V) 20 | { 21 | this->V = V; 22 | adj = new list[V]; 23 | } 24 | 25 | void Graph::addEdge(int v, int w) 26 | { 27 | adj[v].push_back(w); 28 | adj[w].push_back(v); // Note: the graph is undirected 29 | } 30 | 31 | // A recursive function that finds and prints bridges using DFS traversal 32 | // u --> The vertex to be visited next 33 | // visited[] --> keeps tract of visited vertices 34 | // disc[] --> Stores discovery times of visited vertices 35 | // parent[] --> Stores parent vertices in DFS tree 36 | void Graph::bridgeUtil(int u, bool visited[], int disc[], 37 | int low[], int parent[]) 38 | { 39 | // A static variable is used for simplicity, we can avoid use of static 40 | // variable by passing a pointer. 41 | static int time = 0; 42 | 43 | // Mark the current node as visited 44 | visited[u] = true; 45 | 46 | // Initialize discovery time and low value 47 | disc[u] = low[u] = ++time; 48 | 49 | // Go through all vertices aadjacent to this 50 | list::iterator i; 51 | for (i = adj[u].begin(); i != adj[u].end(); ++i) 52 | { 53 | int v = *i; // v is current adjacent of u 54 | 55 | // If v is not visited yet, then recur for it 56 | if (!visited[v]) 57 | { 58 | parent[v] = u; 59 | bridgeUtil(v, visited, disc, low, parent); 60 | 61 | // Check if the subtree rooted with v has a connection to 62 | // one of the ancestors of u 63 | low[u] = min(low[u], low[v]); 64 | 65 | // If the lowest vertex reachable from subtree under v is 66 | // below u in DFS tree, then u-v is a bridge 67 | if (low[v] > disc[u]) 68 | cout << u <<" " << v << endl; 69 | } 70 | 71 | // Update low value of u for parent function calls. 72 | else if (v != parent[u]) 73 | low[u] = min(low[u], disc[v]); 74 | } 75 | } 76 | 77 | // DFS based function to find all bridges. It uses recursive function bridgeUtil() 78 | void Graph::bridge() 79 | { 80 | // Mark all the vertices as not visited 81 | bool *visited = new bool[V]; 82 | int *disc = new int[V]; 83 | int *low = new int[V]; 84 | int *parent = new int[V]; 85 | 86 | // Initialize parent and visited arrays 87 | for (int i = 0; i < V; i++) 88 | { 89 | parent[i] = NIL; 90 | visited[i] = false; 91 | } 92 | 93 | // Call the recursive helper function to find Bridges 94 | // in DFS tree rooted with vertex 'i' 95 | for (int i = 0; i < V; i++) 96 | if (visited[i] == false) 97 | bridgeUtil(i, visited, disc, low, parent); 98 | } 99 | 100 | // Driver program to test above function 101 | int main() 102 | { 103 | 104 | // Create graphs given in above diagrams 105 | cout << "\nBridges in first graph \n"; 106 | Graph g1(5); 107 | g1.addEdge(1, 0); 108 | g1.addEdge(0, 2); 109 | g1.addEdge(2, 1); 110 | g1.addEdge(0, 3); 111 | g1.addEdge(3, 4); 112 | g1.bridge(); 113 | 114 | cout << "\nBridges in second graph \n"; 115 | Graph g2(4); 116 | g2.addEdge(0, 1); 117 | g2.addEdge(1, 2); 118 | g2.addEdge(2, 3); 119 | g2.bridge(); 120 | 121 | cout << "\nBridges in third graph \n"; 122 | Graph g3(7); 123 | g3.addEdge(0, 1); 124 | g3.addEdge(1, 2); 125 | g3.addEdge(2, 0); 126 | g3.addEdge(1, 3); 127 | g3.addEdge(1, 4); 128 | g3.addEdge(1, 6); 129 | g3.addEdge(3, 5); 130 | g3.addEdge(4, 5); 131 | g3.bridge(); 132 | 133 | return 0; 134 | } 135 | -------------------------------------------------------------------------------- /Graph/DisjointSet.cpp: -------------------------------------------------------------------------------- 1 | struct DisjointSet { 2 | int *root, *rank, n; 3 | DisjointSet(int sz) { 4 | root = new int[sz+1]; 5 | rank = new int[sz+1]; 6 | n = sz; 7 | } 8 | ~DisjointSet() { 9 | delete[] root; 10 | delete[] rank; 11 | } 12 | void init() { 13 | for(int i = 1; i <= n; i++) { 14 | root[i] = i; 15 | rank[i] = 0; 16 | } 17 | } 18 | int find(int u) { 19 | if(u != root[u]) root[u] = find(root[u]); 20 | return root[u]; 21 | } 22 | void merge(int u, int v) { 23 | int pu = find(u); 24 | int pv = find(v); 25 | if(rank[pu] > rank[pv]) root[pv] = pu; 26 | else root[pu] = pv; 27 | if(rank[pu]==rank[pv]) rank[pv]++; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Graph/EularCircuit.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | //every edge once 3 | using namespace std; 4 | 5 | int f[100]={0}, ans[100]={0}; 6 | bool g[100][100]={0}, v[100]={0}; 7 | int n=0, m=0, c=0; 8 | 9 | void dfs(int k) 10 | { 11 | for (int i=1;i<=n;i++) 12 | if (g[k][i]) 13 | { 14 | g[k][i]=false; 15 | g[i][k]=false; 16 | dfs(i); 17 | } 18 | m++; 19 | ans[m]=k; 20 | } 21 | 22 | int main(void) 23 | { 24 | cin >> n >> m; 25 | 26 | for (int i=1;i<=m;i++) 27 | { 28 | int x=0, y=0; 29 | g[x][y]=true; 30 | g[y][x]=true; 31 | f[x]++; 32 | f[y]++; 33 | } 34 | 35 | m=0; 36 | int k1=0; 37 | for (int i=1;i<=n;i++) 38 | { 39 | if (f[i]%2==1) k1++; 40 | if (k1>2) 41 | { 42 | cout << "error" << endl; 43 | return 0; 44 | } 45 | if (f[i]%2 && c==0) c=i; 46 | } 47 | 48 | if (c==0) c=1; 49 | dfs(x); 50 | 51 | for (int i=m;i>=1;i--) cout << ans[i] << endl; 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /Graph/Hungerian Algorithm.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Algorithm : Hungarian algorithm 3 | * Max Weighted Bi-partite Matching 4 | * Complexity : O( N^3 ) 5 | * Note : 0 base indexing 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | #define MAX 107 // Max number of vertices in one part 15 | #define INF 100000000 // Just infinity 16 | 17 | long cost[MAX][MAX]; // cost matrix 18 | long N,max_match; // N workers and N jobs 19 | long lx[MAX], ly[MAX]; // Labels of X and Y parts 20 | long xy[MAX]; // xy[x] - vertex that is matched with x, 21 | long yx[MAX]; // yx[y] - vertex that is matched with y 22 | bool S[MAX], T[MAX]; // Sets S and T in algorithm 23 | long slack[MAX]; 24 | long slackx[MAX]; // slackx[y] such a vertex, that 25 | // l(slackx[y]) + l(y) - w(slackx[y],y) = slack[y] 26 | long Prev[MAX]; // Array for memorizing alternating paths 27 | 28 | void Init_Labels() { 29 | memset(lx, 0, sizeof(lx)); 30 | memset(ly, 0, sizeof(ly)); 31 | long x,y; 32 | for( x=0; x 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | #define MAX 107 // Max number of vertices in one part 15 | #define INF 100000000 // Just infinity 16 | 17 | long cost[MAX][MAX]; // cost matrix 18 | long N,max_match; // N workers and N jobs 19 | long lx[MAX], ly[MAX]; // Labels of X and Y parts 20 | long xy[MAX]; // xy[x] - vertex that is matched with x, 21 | long yx[MAX]; // yx[y] - vertex that is matched with y 22 | bool S[MAX], T[MAX]; // Sets S and T in algorithm 23 | long slack[MAX]; 24 | long slackx[MAX]; // slackx[y] such a vertex, that 25 | // l(slackx[y]) + l(y) - w(slackx[y],y) = slack[y] 26 | long Prev[MAX]; // Array for memorizing alternating paths 27 | 28 | void Init_Labels() { 29 | memset(lx, 0, sizeof(lx)); 30 | memset(ly, 0, sizeof(ly)); 31 | long x,y; 32 | for( x=0; x=0; i=next[i]) { 31 | v = to[i]; 32 | if(flow[i] < cap[i] && dist[v]==-1) { 33 | dist[v] = dist[u]+1; 34 | Q[en++] = v; 35 | } 36 | } 37 | } 38 | return dist[snk]!=-1; 39 | } 40 | 41 | int dfs(int u, int fl) { 42 | if(u==snk) return fl; 43 | for(int &e=pro[u], v, df; e>=0; e=next[e]) { 44 | v = to[e]; 45 | if(flow[e] < cap[e] && dist[v]==dist[u]+1) { 46 | df = dfs(v, min(cap[e]-flow[e], fl)); 47 | if(df>0) { 48 | flow[e] += df; 49 | flow[e^1] -= df; 50 | return df; 51 | } 52 | } 53 | } 54 | return 0; 55 | } 56 | 57 | i64 dinitz() { 58 | i64 ret = 0; 59 | int df; 60 | while(bfs()) { 61 | for(int i=1; i<=nNode; i++) pro[i] = fin[i]; 62 | while(true) { 63 | df = dfs(src, INF); 64 | if(df) ret += (i64)df; 65 | else break; 66 | } 67 | } 68 | return ret; 69 | } 70 | -------------------------------------------------------------------------------- /Graph/MaximumBipertiteMatching.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | G[] is the left-side graph, must be bipartite 3 | match(n): n is the number of nodes in left-side set 4 | and returns the maximum possible matching. 5 | Left[] anf Right[] ar assigned with corresponding matches 6 | */ 7 | 8 | vector < int > G[MAX]; 9 | bool visited[MAX]; 10 | int Left[MAX], Right[MAX]; 11 | 12 | bool dfs(int u) { 13 | if(visited[u]) return false; 14 | visited[u] = true; 15 | int len = G[u].size(), i, v; 16 | for(i=0; i Q; 68 | for(i=1; i<=n; i++) { 69 | if(match[i]==NIL) { 70 | dist[i] = 0; 71 | Q.push(i); 72 | } 73 | else dist[i] = INF; 74 | } 75 | dist[NIL] = INF; 76 | while(!Q.empty()) { 77 | u = Q.front(); Q.pop(); 78 | if(u!=NIL) { 79 | len = G[u].size(); 80 | for(i=0; i= 0; i = next[i]) { 34 | v = to[i]; 35 | if(cap[i] && dist[v] > dist[u] + cost[i]) { 36 | dist[v] = dist[u] + cost[i]; 37 | pre[v] = i; 38 | flag = true; 39 | } 40 | } 41 | } 42 | } 43 | return (dist[snk] < INF); 44 | } 45 | 46 | int mcmf(int &fcost) { 47 | int netflow, i, bot, u; 48 | netflow = fcost = 0; 49 | while(bellman()) { 50 | bot = INF; 51 | for(u = pre[snk]; u >= 0; u = pre[from[u]]) bot = min(bot, cap[u]); 52 | for(u = pre[snk]; u >= 0; u = pre[from[u]]) { 53 | cap[u] -= bot; 54 | cap[u^1] += bot; 55 | fcost += bot * cost[u]; 56 | } 57 | netflow += bot; 58 | } 59 | return netflow; 60 | } 61 | -------------------------------------------------------------------------------- /Graph/MinimumExpression.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Finds alphabetically first representation of a cyclic string in O(length) 3 | */ 4 | 5 | inline int minimumExpression(char *s) { 6 | int i, j, k, n, len, p, q; 7 | len = n = strlen(s), n <<= 1, i = 0, j = 1, k = 0; 8 | while(i + k < n && j + k < n) { 9 | p = i+k >= len ? s[i+k-len] : s[i+k]; 10 | q = j+k >= len ? s[j+k-len] : s[j+k]; 11 | if(p == q) k++; 12 | else if(p > q) { i = i+k+1; if(i <= j) i = j+1; k = 0; } 13 | else if(p < q) { j = j+k+1; if(j <= i) j = i+1; k = 0; } 14 | } 15 | return i < j ? i : j; 16 | } 17 | -------------------------------------------------------------------------------- /Graph/MyDinitz.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct edge{ 4 | int v,ri; 5 | long long c; 6 | edge(){} 7 | edge(int _v,long long _c,int _ri){v=_v,c=_c,ri=_ri;} 8 | edge(int _v,long long _c){v=_v,c=_c;} 9 | }; 10 | vectorg[5003]; 11 | int source,sink,level[5003]; 12 | void addEdge(int u,int v,long long c){ 13 | //cout<<"addedge "<q; 22 | q.push(source); 23 | while(!q.empty()){ 24 | int src=q.front(); 25 | q.pop(); 26 | for(int i=0;i<(int)g[src].size();i++){ 27 | if(level[g[src][i].v]==-1 && g[src][i].c>0){ 28 | level[g[src][i].v]=level[src]+1; 29 | q.push(g[src][i].v); 30 | } 31 | } 32 | } 33 | return level[sink]!=-1; 34 | } 35 | long long dfs(int src,long long minCap){ 36 | if(src==sink)return minCap; 37 | long long x=0,y=0; 38 | for(int i=0;i<(int)g[src].size();i++){ 39 | if(g[src][i].c<=0 || level[g[src][i].v]!=level[src]+1)continue; 40 | y=dfs(g[src][i].v,min(g[src][i].c,minCap-x)); 41 | x+=y; 42 | g[src][i].c-=y; 43 | g[g[src][i].v][g[src][i].ri].c+=y; 44 | if(x==minCap)break; 45 | } 46 | if(x==0)level[src]=0; 47 | return x; 48 | } 49 | int main(){ 50 | ios_base::sync_with_stdio(0); 51 | cin.tie(nullptr); 52 | int n,m,u,v,c; 53 | cin>>n>>m; 54 | source=1,sink=n; 55 | for(int i=0;i>u>>v>>c; 57 | addEdge(u,v,c); 58 | addEdge(v,u,c); 59 | } 60 | long long flow=0; 61 | while(bfs()){ 62 | flow+=dfs(source,1LL<<50); 63 | } 64 | cout< 2 | using namespace std; 3 | #define _min(x,y) (((x)<(y))?(x):(y)) 4 | struct edge{ 5 | int u,v,_next,w; 6 | long long c; 7 | edge(){} 8 | edge(int _u,int _v,int __next,long long _c,int _w){u=_u,v=_v,_next=__next,c=_c,w=_w;} 9 | }edgeList[120005]; 10 | int ee,start[5003],nn; 11 | void addEdge(int u,int v,long long cuv,long long cvu,int w){ 12 | edgeList[ee]=edge(u,v,start[u],cuv,w);start[u]=ee;ee++; 13 | edgeList[ee]=edge(v,u,start[v],cvu,-w);start[v]=ee;ee++; 14 | return; 15 | } 16 | int source,sink,level[5003]; 17 | void init(int s,int t,int n){ 18 | source=s,sink=t,ee=0,nn=n; 19 | memset(start,-1,sizeof(start)); 20 | } 21 | bool bfs(){ 22 | memset(level,-1,sizeof(level)); 23 | level[source]=0; 24 | int q[nn+nn],ii=0,jj=0; 25 | q[jj]=source; 26 | jj++; 27 | while(ii0){ 32 | level[edgeList[i].v]=level[src]+1; 33 | q[jj]=edgeList[i].v; 34 | jj++; 35 | } 36 | } 37 | } 38 | return level[sink]!=-1; 39 | } 40 | long long dfs(int src,long long _minCap){ 41 | if(src==sink)return _minCap; 42 | long long x=0,y=0; 43 | for(int i=start[src];i!=-1;i=edgeList[i]._next){ 44 | if(edgeList[i].c<=0 || level[edgeList[i].v]!=level[src]+1)continue; 45 | y=dfs(edgeList[i].v,_min(edgeList[i].c,_minCap-x)); 46 | x+=y; 47 | edgeList[i].c-=y; 48 | edgeList[i^1].c+=y; 49 | if(x==_minCap)break; 50 | } 51 | if(x==0)level[src]=0; 52 | return x; 53 | } 54 | int main(){ 55 | ios_base::sync_with_stdio(0); 56 | cin.tie(nullptr); 57 | int n,m,u,v,c; 58 | cin>>n>>m; 59 | init(1,n,n); 60 | for(int i=0;i>u>>v>>c; 62 | addEdge(u,v,c,c,0); 63 | //addEdge(v,u,c); 64 | } 65 | long long flow=0; 66 | while(bfs()){ 67 | flow+=dfs(source,1LL<<50); 68 | } 69 | cout< 2 | using namespace std ; 3 | #define rep(i,n) for( int i = 0 ;i < n ; i++ ) 4 | int Temp[101] ; 5 | int n , p; 6 | inline int readInt() 7 | { 8 | int ip = getchar_unlocked(), ret = 0, flag = 1; 9 | 10 | for(; ip < 48 || ip > 57; ip = getchar_unlocked()) 11 | { 12 | if(ip == 45) 13 | { 14 | flag = -1; 15 | ip = getchar_unlocked(); 16 | break; 17 | } 18 | } 19 | 20 | for(; ip > 47 && ip < 58; ip = getchar_unlocked()) 21 | ret = ret * 10 + ip - 48 ; 22 | return flag * ret; 23 | } 24 | 25 | int main() { 26 | 27 | int cases , caseno = 1; 28 | scanf("%d",&cases ) ; 29 | 30 | while( cases -- ) { 31 | 32 | //scanf("%d",&n) ; 33 | n = readInt() ; 34 | vector > Can ; 35 | int Com[n][n] ; 36 | for( int i = 1 ; i <= n ; i++ ) { 37 | dequed ; 38 | for( int j = 1; j <= n ; j++ ) { 39 | //scanf("%d",&p) ; 40 | p = readInt() ; 41 | d.push_back(p-n-1) ; 42 | } 43 | Can.push_back(d) ; 44 | } 45 | for( int i = 0 ; i < n ; i++ ) { 46 | for( int j = 0; j < n ; j++ ) { 47 | //scanf("%d",&p) ; 48 | p = readInt() ; 49 | Com[i][p-1] = j ; 50 | } 51 | } 52 | int cnt = 0 ; 53 | 54 | do { 55 | memset( Temp , -1 , sizeof Temp ) ; 56 | cnt = 0 ; 57 | for( int i = 0 ; i < n ; i++ ) { 58 | int q = Can[i][0] ; 59 | if( Temp[q] == -1 )Temp[q] = i,cnt++ ; 60 | else { 61 | int p = Temp[q] ; 62 | if( Com[q][i] < Com[q][p] ) { 63 | Temp[q] = i ; 64 | Can[p].pop_front() ; 65 | } else { 66 | Temp[q] = p ; 67 | Can[i].pop_front() ; 68 | } 69 | } 70 | } 71 | } while( cnt != n ) ; 72 | cout << "Case " << caseno++ << ":" ; 73 | for(int i = 0 ; i < n ; i++ ) { 74 | cout << " (" << Temp[i]+1 << " " << i+n+1 << ")" ; 75 | } 76 | cout << "\n"; 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /Graph/StronglyConnectedComponent.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | SCC (Tarjan) in O(|v| + |e|) 3 | Input: 4 | G[] is a input directed graph with n nodes in range [1,n] 5 | Output: 6 | Component[i] holds the component id to which node i belongs 7 | components: total number of components in the graph 8 | */ 9 | 10 | int Stack[MAX], top; 11 | int Index[MAX], Lowlink[MAX], Onstack[MAX]; 12 | int Component[MAX]; 13 | int idx, components; 14 | vector< int > G[MAX]; 15 | 16 | void tarjan(int u) { 17 | int v, i; 18 | Index[u] = Lowlink[u] = idx++; 19 | Stack[top++] = u; 20 | Onstack[u] = 1; 21 | for(i = 0; i < SZ(G[u]); i++) { 22 | v = G[u][i]; 23 | if(Index[v]==-1) { 24 | tarjan(v); 25 | Lowlink[u] = min(Lowlink[u], Lowlink[v]); 26 | } 27 | else if(Onstack[v]) Lowlink[u] = min(Lowlink[u], Index[v]); 28 | } 29 | if(Lowlink[u] == Index[u]) { 30 | components++; 31 | do { 32 | v = Stack[--top]; 33 | Onstack[v] = 0; 34 | Component[v] = components; 35 | } while(u != v); 36 | } 37 | } 38 | 39 | void findSCC(int n) { 40 | components = top = idx = 0; 41 | SET(Index); CLR(Onstack); MEM(Lowlink, 0x3f); 42 | for(int i = 1; i <= n; i++) if(Index[i]==-1) tarjan(i); 43 | } 44 | 45 | 46 | 47 | #include 48 | using namespace std ; 49 | 50 | int n , m ; 51 | vectorG[20001] ; 52 | vectorGR[20001] ; 53 | int visited[20001] ; 54 | int I[20001] , O[20001] , C[20001] ; 55 | int scc = 0 ; 56 | stack RPost ; 57 | 58 | 59 | void dfs( int node ) { 60 | visited[node] = 1 ; 61 | for( int i = 0 ; i < G[node].size() ; i++ ) { 62 | if(visited[G[node][i]] == 0 ) { 63 | dfs( G[node][i] ) ; 64 | } 65 | } 66 | RPost.push( node ) ; 67 | } 68 | 69 | void dfs2( int node ) { 70 | visited[node] = 1 ; 71 | for( int i = 0 ; i < GR[node].size() ; i++ ) { 72 | if( !visited[GR[node][i]] ) { 73 | dfs2( GR[node][i] ) ; 74 | } 75 | } 76 | C[node] = scc ; 77 | } 78 | 79 | int main() { 80 | 81 | int cases , caseno = 1 ; 82 | scanf("%d",&cases ) ; 83 | 84 | while( cases -- ) { 85 | 86 | scanf("%d%d",&n,&m ) ; 87 | for( int i = 0 ; i < m ; i++ ) { 88 | int u , v ; 89 | scanf("%d%d",&u,&v) ; 90 | G[u].push_back( v ) ; 91 | GR[v].push_back( u ) ; 92 | } 93 | 94 | for( int i = 1 ; i <= n ; i++ ) { 95 | if( !visited[i] ) { 96 | dfs( i ) ; 97 | } 98 | } 99 | 100 | scc = 0 ; 101 | for( int i = 1 ; i <= n ; i++ )visited[i] = 0 ; 102 | 103 | // for( int i = 0 ; i < RPost.size() ; i++ )cout << RPost[i] << " " ; 104 | // cout << "\n" ; 105 | // cout << *(RPost.end()-1)< 57; ip = getchar_unlocked()) 7 | { 8 | if(ip == 45) 9 | { 10 | flag = -1; 11 | ip = getchar_unlocked(); 12 | break; 13 | } 14 | } 15 | 16 | for(; ip > 47 && ip < 58; ip = getchar_unlocked()) 17 | ret = ret * 10 + ip - 48 ; 18 | return flag * ret; 19 | } 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | struct Input { 29 | #define maxBufSize (1 << 23) 30 | #define maxStrSize (1 << 23) 31 | int bufSize, bufEnd, bufPos; 32 | char buffer[maxBufSize]; 33 | void grabBuffer() { 34 | bufSize = (maxBufSize); 35 | bufPos = 0; 36 | bufEnd = fread(buffer, sizeof (char), bufSize, stdin); 37 | buffer[bufEnd] = '\0'; 38 | } 39 | bool bufEof() { 40 | return bufPos == bufEnd; 41 | } 42 | int getChar() { 43 | return buffer[bufPos++]; 44 | } 45 | void skipWS() { 46 | while ((buffer[bufPos] == '\n' || 47 | buffer[bufPos] == ' ' || buffer[bufPos] == '\t')) 48 | bufPos++; 49 | } 50 | int rUint() { 51 | int n = 0, x; 52 | skipWS(); 53 | for (int x = getChar(); x <= '9' && x >= '0'; x = getChar()) 54 | n = (n << 3) + (n << 1) + (x - '0'); 55 | return n; 56 | } 57 | int Int() { 58 | int sign = 0, n = 0, x; 59 | skipWS(); 60 | if (buffer[bufPos] == '-') 61 | sign = 1, getChar(); 62 | for (x = getChar(); x <= '9' && x >= '0'; x = getChar()) 63 | n = (n << 3) + (n << 1) + (x - '0'); 64 | return sign == 0? n: -n; 65 | } 66 | inline bool isWhiteSpace(char x) { 67 | return x == ' ' || x == '\n' || x == '\t'; 68 | } 69 | string rStr() { 70 | char result[maxStrSize]; 71 | skipWS(); 72 | int idx = 0, x; 73 | for (x = getChar(); !isWhiteSpace(x); x = getChar()) 74 | result[idx++] = x; 75 | result[idx] = '\0'; 76 | return result; 77 | } 78 | char rChar() { 79 | skipWS(); 80 | return getChar(); 81 | } 82 | }; 83 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 M Saiful Bari 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Matrix & Numeric/BigInt.cpp: -------------------------------------------------------------------------------- 1 | const int base = 1000000000; 2 | const int base_digits = 9; 3 | struct bigint { 4 | vector a; 5 | int sign; 6 | 7 | bigint() : 8 | sign(1) { 9 | } 10 | 11 | bigint(long long v) { 12 | *this = v; 13 | } 14 | 15 | bigint(const string &s) { 16 | read(s); 17 | } 18 | 19 | void operator=(const bigint &v) { 20 | sign = v.sign; 21 | a = v.a; 22 | } 23 | 24 | void operator=(long long v) { 25 | sign = 1; 26 | if (v < 0) 27 | sign = -1, v = -v; 28 | for (; v > 0; v = v / base) 29 | a.push_back(v % base); 30 | } 31 | 32 | bigint operator+(const bigint &v) const { 33 | if (sign == v.sign) { 34 | bigint res = v; 35 | 36 | for (int i = 0, carry = 0; i < (int) max(a.size(), v.a.size()) || carry; ++i) { 37 | if (i == (int) res.a.size()) 38 | res.a.push_back(0); 39 | res.a[i] += carry + (i < (int) a.size() ? a[i] : 0); 40 | carry = res.a[i] >= base; 41 | if (carry) 42 | res.a[i] -= base; 43 | } 44 | return res; 45 | } 46 | return *this - (-v); 47 | } 48 | 49 | bigint operator-(const bigint &v) const { 50 | if (sign == v.sign) { 51 | if (abs() >= v.abs()) { 52 | bigint res = *this; 53 | for (int i = 0, carry = 0; i < (int) v.a.size() || carry; ++i) { 54 | res.a[i] -= carry + (i < (int) v.a.size() ? v.a[i] : 0); 55 | carry = res.a[i] < 0; 56 | if (carry) 57 | res.a[i] += base; 58 | } 59 | res.trim(); 60 | return res; 61 | } 62 | return -(v - *this); 63 | } 64 | return *this + (-v); 65 | } 66 | 67 | void operator*=(int v) { 68 | if (v < 0) 69 | sign = -sign, v = -v; 70 | for (int i = 0, carry = 0; i < (int) a.size() || carry; ++i) { 71 | if (i == (int) a.size()) 72 | a.push_back(0); 73 | long long cur = a[i] * (long long) v + carry; 74 | carry = (int) (cur / base); 75 | a[i] = (int) (cur % base); 76 | //asm("divl %%ecx" : "=a"(carry), "=d"(a[i]) : "A"(cur), "c"(base)); 77 | } 78 | trim(); 79 | } 80 | 81 | bigint operator*(int v) const { 82 | bigint res = *this; 83 | res *= v; 84 | return res; 85 | } 86 | 87 | friend pair divmod(const bigint &a1, const bigint &b1) { 88 | int norm = base / (b1.a.back() + 1); 89 | bigint a = a1.abs() * norm; 90 | bigint b = b1.abs() * norm; 91 | bigint q, r; 92 | q.a.resize(a.a.size()); 93 | 94 | for (int i = a.a.size() - 1; i >= 0; i--) { 95 | r *= base; 96 | r += a.a[i]; 97 | int s1 = r.a.size() <= b.a.size() ? 0 : r.a[b.a.size()]; 98 | int s2 = r.a.size() <= b.a.size() - 1 ? 0 : r.a[b.a.size() - 1]; 99 | int d = ((long long) base * s1 + s2) / b.a.back(); 100 | r -= b * d; 101 | while (r < 0) 102 | r += b, --d; 103 | q.a[i] = d; 104 | } 105 | 106 | q.sign = a1.sign * b1.sign; 107 | r.sign = a1.sign; 108 | q.trim(); 109 | r.trim(); 110 | return make_pair(q, r / norm); 111 | } 112 | 113 | bigint operator/(const bigint &v) const { 114 | return divmod(*this, v).first; 115 | } 116 | 117 | bigint operator%(const bigint &v) const { 118 | return divmod(*this, v).second; 119 | } 120 | 121 | void operator/=(int v) { 122 | if (v < 0) 123 | sign = -sign, v = -v; 124 | for (int i = (int) a.size() - 1, rem = 0; i >= 0; --i) { 125 | long long cur = a[i] + rem * (long long) base; 126 | a[i] = (int) (cur / v); 127 | rem = (int) (cur % v); 128 | } 129 | trim(); 130 | } 131 | 132 | bigint operator/(int v) const { 133 | bigint res = *this; 134 | res /= v; 135 | return res; 136 | } 137 | 138 | int operator%(int v) const { 139 | if (v < 0) 140 | v = -v; 141 | int m = 0; 142 | for (int i = a.size() - 1; i >= 0; --i) 143 | m = (a[i] + m * (long long) base) % v; 144 | return m * sign; 145 | } 146 | 147 | void operator+=(const bigint &v) { 148 | *this = *this + v; 149 | } 150 | void operator-=(const bigint &v) { 151 | *this = *this - v; 152 | } 153 | void operator*=(const bigint &v) { 154 | *this = *this * v; 155 | } 156 | void operator/=(const bigint &v) { 157 | *this = *this / v; 158 | } 159 | 160 | bool operator<(const bigint &v) const { 161 | if (sign != v.sign) 162 | return sign < v.sign; 163 | if (a.size() != v.a.size()) 164 | return a.size() * sign < v.a.size() * v.sign; 165 | for (int i = a.size() - 1; i >= 0; i--) 166 | if (a[i] != v.a[i]) 167 | return a[i] * sign < v.a[i] * sign; 168 | return false; 169 | } 170 | 171 | bool operator>(const bigint &v) const { 172 | return v < *this; 173 | } 174 | bool operator<=(const bigint &v) const { 175 | return !(v < *this); 176 | } 177 | bool operator>=(const bigint &v) const { 178 | return !(*this < v); 179 | } 180 | bool operator==(const bigint &v) const { 181 | return !(*this < v) && !(v < *this); 182 | } 183 | bool operator!=(const bigint &v) const { 184 | return *this < v || v < *this; 185 | } 186 | 187 | void trim() { 188 | while (!a.empty() && !a.back()) 189 | a.pop_back(); 190 | if (a.empty()) 191 | sign = 1; 192 | } 193 | 194 | bool isZero() const { 195 | return a.empty() || (a.size() == 1 && !a[0]); 196 | } 197 | 198 | bigint operator-() const { 199 | bigint res = *this; 200 | res.sign = -sign; 201 | return res; 202 | } 203 | 204 | bigint abs() const { 205 | bigint res = *this; 206 | res.sign *= res.sign; 207 | return res; 208 | } 209 | 210 | long long longValue() const { 211 | long long res = 0; 212 | for (int i = a.size() - 1; i >= 0; i--) 213 | res = res * base + a[i]; 214 | return res * sign; 215 | } 216 | 217 | friend bigint gcd(const bigint &a, const bigint &b) { 218 | return b.isZero() ? a : gcd(b, a % b); 219 | } 220 | friend bigint lcm(const bigint &a, const bigint &b) { 221 | return a / gcd(a, b) * b; 222 | } 223 | 224 | void read(const string &s) { 225 | sign = 1; 226 | a.clear(); 227 | int pos = 0; 228 | while (pos < (int) s.size() && (s[pos] == '-' || s[pos] == '+')) { 229 | if (s[pos] == '-') 230 | sign = -sign; 231 | ++pos; 232 | } 233 | for (int i = s.size() - 1; i >= pos; i -= base_digits) { 234 | int x = 0; 235 | for (int j = max(pos, i - base_digits + 1); j <= i; j++) 236 | x = x * 10 + s[j] - '0'; 237 | a.push_back(x); 238 | } 239 | trim(); 240 | } 241 | 242 | friend istream& operator>>(istream &stream, bigint &v) { 243 | string s; 244 | stream >> s; 245 | v.read(s); 246 | return stream; 247 | } 248 | 249 | friend ostream& operator<<(ostream &stream, const bigint &v) { 250 | if (v.sign == -1) 251 | stream << '-'; 252 | stream << (v.a.empty() ? 0 : v.a.back()); 253 | for (int i = (int) v.a.size() - 2; i >= 0; --i) 254 | stream << setw(base_digits) << setfill('0') << v.a[i]; 255 | return stream; 256 | } 257 | 258 | static vector convert_base(const vector &a, int old_digits, int new_digits) { 259 | vector p(max(old_digits, new_digits) + 1); 260 | p[0] = 1; 261 | for (int i = 1; i < (int) p.size(); i++) 262 | p[i] = p[i - 1] * 10; 263 | vector res; 264 | long long cur = 0; 265 | int cur_digits = 0; 266 | for (int i = 0; i < (int) a.size(); i++) { 267 | cur += a[i] * p[cur_digits]; 268 | cur_digits += old_digits; 269 | while (cur_digits >= new_digits) { 270 | res.push_back(int(cur % p[new_digits])); 271 | cur /= p[new_digits]; 272 | cur_digits -= new_digits; 273 | } 274 | } 275 | res.push_back((int) cur); 276 | while (!res.empty() && !res.back()) 277 | res.pop_back(); 278 | return res; 279 | } 280 | 281 | typedef vector vll; 282 | 283 | static vll karatsubaMultiply(const vll &a, const vll &b) { 284 | int n = a.size(); 285 | vll res(n + n); 286 | if (n <= 32) { 287 | for (int i = 0; i < n; i++) 288 | for (int j = 0; j < n; j++) 289 | res[i + j] += a[i] * b[j]; 290 | return res; 291 | } 292 | 293 | int k = n >> 1; 294 | vll a1(a.begin(), a.begin() + k); 295 | vll a2(a.begin() + k, a.end()); 296 | vll b1(b.begin(), b.begin() + k); 297 | vll b2(b.begin() + k, b.end()); 298 | 299 | vll a1b1 = karatsubaMultiply(a1, b1); 300 | vll a2b2 = karatsubaMultiply(a2, b2); 301 | 302 | for (int i = 0; i < k; i++) 303 | a2[i] += a1[i]; 304 | for (int i = 0; i < k; i++) 305 | b2[i] += b1[i]; 306 | 307 | vll r = karatsubaMultiply(a2, b2); 308 | for (int i = 0; i < (int) a1b1.size(); i++) 309 | r[i] -= a1b1[i]; 310 | for (int i = 0; i < (int) a2b2.size(); i++) 311 | r[i] -= a2b2[i]; 312 | 313 | for (int i = 0; i < (int) r.size(); i++) 314 | res[i + k] += r[i]; 315 | for (int i = 0; i < (int) a1b1.size(); i++) 316 | res[i] += a1b1[i]; 317 | for (int i = 0; i < (int) a2b2.size(); i++) 318 | res[i + n] += a2b2[i]; 319 | return res; 320 | } 321 | 322 | bigint operator*(const bigint &v) const { 323 | vector a6 = convert_base(this->a, base_digits, 6); 324 | vector b6 = convert_base(v.a, base_digits, 6); 325 | vll a(a6.begin(), a6.end()); 326 | vll b(b6.begin(), b6.end()); 327 | while (a.size() < b.size()) 328 | a.push_back(0); 329 | while (b.size() < a.size()) 330 | b.push_back(0); 331 | while (a.size() & (a.size() - 1)) 332 | a.push_back(0), b.push_back(0); 333 | vll c = karatsubaMultiply(a, b); 334 | bigint res; 335 | res.sign = sign * v.sign; 336 | for (int i = 0, carry = 0; i < (int) c.size(); i++) { 337 | long long cur = c[i] + carry; 338 | res.a.push_back((int) (cur % 1000000)); 339 | carry = (int) (cur / 1000000); 340 | } 341 | res.a = convert_base(res.a, 6, base_digits); 342 | res.trim(); 343 | return res; 344 | } 345 | }; 346 | -------------------------------------------------------------------------------- /Matrix & Numeric/Bigfloat/1~: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbmaruf/Algorithms-Code-Library/d95d79f0ee9ab3653a96ff8dfca44b703641e365/Matrix & Numeric/Bigfloat/1~ -------------------------------------------------------------------------------- /Matrix & Numeric/Bigfloat/Example.h: -------------------------------------------------------------------------------- 1 | #include "bigfloat.h" 2 | 3 | int driver(int argc, char**argv) 4 | { 5 | for (int i=-100; i<=100; ++i) 6 | { 7 | BigFloat aa(i); 8 | aa.Div(100); 9 | BigFloat bb(aa); 10 | bb.Exp().Ln().Sub(aa); 11 | BigFloat cc(aa); 12 | cc.ATan().Tan().Sub(aa); 13 | BigFloat dd(aa); 14 | dd.ASin().Sin().Sub(aa); 15 | BigFloat ee(aa); 16 | ee.ACos().Cos().Sub(aa); 17 | printf("%f %g %g %g %g\n", 18 | aa.ToDouble(), 19 | bb.ToDouble(), 20 | cc.ToDouble(), 21 | dd.ToDouble(), 22 | ee.ToDouble()); 23 | } 24 | 25 | // find what degree formula to generate 26 | ASSERT(argc == 2, "usage: multistep 5, to get 11th degree (5*2+1=11)\n"); 27 | int halfDegree; 28 | sscanf(argv[1], "%d", &halfDegree); 29 | ASSERT(halfDegree > 0, "half degree must be at least 1"); 30 | int degree = 2*halfDegree+1; 31 | 32 | // build polynomials of the appropriate degree, and second derivative 33 | BigFloat *p2 = new BigFloat[3*degree]; // position: poly of degree 34 | BigFloat *p = &p2[degree]; 35 | BigFloat *a2 = new BigFloat[3*degree]; // acceleration: poly of degree-2 36 | BigFloat *a = &a2[degree]; 37 | for (int i=0; i<3*degree; ++i) 38 | { 39 | BigFloat x(1); 40 | BigFloat c(i-degree); 41 | for (int j=0; j 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #ifdef _MSC_VER 13 | # define INLINE __forceinline 14 | typedef unsigned __int64 u8; 15 | typedef unsigned __int32 u4; 16 | typedef unsigned __int16 u2; 17 | typedef unsigned __int8 u1; 18 | typedef __int64 s8; 19 | typedef __int32 s4; 20 | typedef __int16 s2; 21 | typedef __int8 s1; 22 | #else 23 | # include 24 | # define INLINE inline 25 | typedef uint64_t u8; 26 | typedef uint32_t u4; 27 | typedef uint16_t u2; 28 | typedef uint8_t u1; 29 | typedef int64_t s8; 30 | typedef int32_t s4; 31 | typedef int16_t s2; 32 | typedef int8_t s1; 33 | #endif 34 | 35 | class CosmosException : public std::exception 36 | { 37 | public: 38 | CosmosException(const char* m) : _msg(m) {} 39 | CosmosException(const std::string& m) : _msg(m) {} 40 | virtual ~CosmosException() throw() {} 41 | virtual const char* what() const throw() 42 | { 43 | return _msg.c_str(); 44 | } 45 | protected: 46 | std::string _msg; 47 | }; 48 | 49 | #define ASSERT(condition, ...) do { \ 50 | if (!(condition)) Assert(__LINE__, __FILE__, #condition, ##__VA_ARGS__); \ 51 | } while(0) 52 | 53 | #define ASSERTFG(f,g) do { \ 54 | double fr = (f); double gr = (g); double diff = (fr-gr); \ 55 | if (diff > 1.0e-10 || diff < -1.0e-10) \ 56 | Assert(__LINE__, __FILE__, #f "," #g, "%f, %f, %f", fr, gr, diff); \ 57 | } while(0) 58 | 59 | static void Assert( 60 | int line, 61 | const char* filename, 62 | const char* condition) 63 | { 64 | static const int bufSize = 4000; 65 | char y[bufSize]; 66 | sprintf(y, "line=[%d], file=[%s], condition=[%s]", 67 | line, filename, condition); 68 | throw CosmosException(y); 69 | } 70 | 71 | static void Assert( 72 | int line, 73 | const char* filename, 74 | const char* condition, 75 | const char* fmt, 76 | ...) 77 | { 78 | static const int bufSize = 4000; 79 | char x[bufSize]; 80 | char y[bufSize]; 81 | va_list args; 82 | va_start(args, fmt); 83 | vsprintf(x, fmt, args); 84 | va_end(args); 85 | sprintf(y, "line=[%d], file=[%s], condition=[%s], %s", 86 | line, filename, condition, x); 87 | throw CosmosException(y); 88 | } 89 | 90 | -------------------------------------------------------------------------------- /Matrix & Numeric/Bigfloat/base.h~: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "base.h" 3 | 4 | 5 | // This is not fast, but it has good accuracy. 6 | // I need this because orbital problems have a lot of nth-degree 7 | // polynomial approximations, and the coefficients of those polynomial 8 | // approximations are things like 48471792742212/237758976000. The only 9 | // way to get the definitions of coefficients right is to do Gaussian 10 | // elimination on at least n equations with n unknowns, and a precision 11 | // about twice as great as the coefficients I want to end up with, 12 | // followed by continued fractions on the result to find the proper 13 | // fractional representation. 14 | class BigFloat 15 | { 16 | public: 17 | BigFloat() { Zero(); } 18 | BigFloat(const BigFloat& n) { Copy(n); } 19 | BigFloat(s8 n) { FromInteger(n); } 20 | BigFloat(s8 n, s8 exponent) { FromInteger(n, exponent); } 21 | ~BigFloat() {} 22 | 23 | // translation 24 | BigFloat& FromInteger(s8 num, s8 exponent=0); 25 | s8 ToInteger() const; // it will truncate, but not overflow 26 | static s8 RoundInteger(s8 value); // round an s8 to right precision 27 | double ToDouble() const; 28 | bool IsNegative() const { return _isNegative; } 29 | s8 ToExponent() const { return _exponent; } 30 | u8 ToDigits() const; // return digits filling an integer 31 | void ToFraction(BigFloat& num, BigFloat& denom, int depth=0) const; 32 | void Print() const; 33 | void PrintHex() const; 34 | 35 | // arithmetic 36 | BigFloat& PZero() 37 | { 38 | _exponent = c_zeroExponent; 39 | _length = 0; 40 | _isNegative = false; 41 | return *this; 42 | } 43 | BigFloat& NZero() 44 | { 45 | _exponent = c_zeroExponent; 46 | _length = 0; 47 | _isNegative = true; 48 | return *this; 49 | } 50 | BigFloat& Zero( bool neg = false) { return neg ? NZero() : PZero(); } 51 | BigFloat& PInf() 52 | { 53 | _exponent = c_zeroExponent; 54 | _length = 1; 55 | _isNegative = false; 56 | return *this; 57 | } 58 | BigFloat& NInf() 59 | { 60 | _exponent = c_zeroExponent; 61 | _length = 1; 62 | _isNegative = true; 63 | return *this; 64 | } 65 | BigFloat& Inf( bool negative = false) { return negative ? NInf() : PInf(); } 66 | BigFloat& NaN() 67 | { 68 | _exponent = c_zeroExponent; 69 | _length = 2; 70 | _isNegative = false; 71 | return *this; 72 | } 73 | 74 | BigFloat& Copy(const BigFloat& n); 75 | BigFloat& Negate(); 76 | 77 | // round to c_digits digits 78 | // carry=true: there should be an additional top digit of 1 79 | // previousDigit: what _d[c_digits] would have been, or 0 80 | BigFloat& Round(bool carry, s8 previousDigit); 81 | BigFloat& Round(u8 previousDigit); 82 | 83 | // truncate to the nearest integer, towards zero 84 | BigFloat& Trunc(); 85 | 86 | // -1 if |this|<|n|, 0 if |this|==|n|, 1 if |this|>|n| 87 | int CompareAbsolute(const BigFloat& n) const; 88 | 89 | 90 | // -1 if thisn 91 | int Compare(const BigFloat& n) const; 92 | 93 | bool IsZero() const 94 | { 95 | return 96 | _exponent == c_zeroExponent && 97 | _length == 0; 98 | } 99 | bool IsPZero() const 100 | { 101 | return 102 | _exponent == c_zeroExponent && 103 | _length == 0 && 104 | _isNegative == false; 105 | } 106 | bool IsNZero() const 107 | { 108 | return 109 | _exponent == c_zeroExponent && 110 | _length == 0 && 111 | _isNegative == true; 112 | } 113 | bool IsInf() const 114 | { 115 | return 116 | _exponent == c_zeroExponent && 117 | _length == 1; 118 | } 119 | bool IsPInf() const 120 | { 121 | return 122 | _exponent == c_zeroExponent && 123 | _length == 1 && 124 | _isNegative == false; 125 | } 126 | bool IsNInf() const 127 | { 128 | return 129 | _exponent == c_zeroExponent && 130 | _length == 1 && 131 | _isNegative == true; 132 | } 133 | bool IsNaN() const 134 | { 135 | return 136 | _exponent == c_zeroExponent && 137 | _length == 2; 138 | } 139 | bool IsSpecial() const 140 | { 141 | return _exponent == c_zeroExponent; 142 | } 143 | 144 | BigFloat& Add(const BigFloat& n) { return AddOrSubtract(n, false); } 145 | BigFloat& Sub(const BigFloat& n) { return AddOrSubtract(n, true); } 146 | BigFloat& Mult(const BigFloat& n); // x => x*n 147 | BigFloat& Div(const BigFloat& n); // x => x/n 148 | BigFloat& Invert(); // x => 1/x 149 | BigFloat& Sqrt(); // x => positive square root of x 150 | BigFloat& Cos(); // x => cosine of x (x in radians) 151 | BigFloat& Sin(); // x => sine of x (x in radians) 152 | BigFloat& Sec(); // x => secant of x (x in radians) 153 | BigFloat& Csc(); // x => cosecant of x (x in radians) 154 | BigFloat& Tan(); // x => tangent of x (x in radians) 155 | BigFloat& Exp(); // x => e to the xth power 156 | BigFloat& ASin(); // x => arcsin of x (-1 => -pi/2, 1 => pi/2) 157 | BigFloat& ACos(); // x => arccos of x (-1 => pi, 1 => 0) 158 | BigFloat& ATan(); // x => arctan of x (-inf => -pi/2, inf => pi/2) 159 | BigFloat& Ln(); // replaces x with the natural log of x 160 | BigFloat& Log(const BigFloat& n); // x => natural log of n base x 161 | BigFloat& Power(const BigFloat& n); // replaces x with x to the nth 162 | BigFloat& Rand(); // not impl: uniformly distributed value in [0,1) 163 | BigFloat& RandNorm(); // not impl: pseudorandom normally-distributed value 164 | 165 | // constants 166 | static const BigFloat& Pi(); // length of unit circle, 3.14159... 167 | static const BigFloat& E(); // the natural base for exponents, 2.71828... 168 | static const BigFloat& ConstZero(); 169 | static const BigFloat& ConstOne(); 170 | static const BigFloat& ConstMinusOne(); 171 | 172 | // variations where arguments are signed integers 173 | int Compare(s8 n, s8 exponent=0); 174 | BigFloat& Add(s8 n, s8 exponent=0); 175 | BigFloat& Sub(s8 n, s8 exponent=0); 176 | BigFloat& Mult(s8 n, s8 exponent=0); 177 | BigFloat& Div(s8 n, s8 exponent=0); 178 | BigFloat& Power(s8 n, s8 exponent=0); // not implemented 179 | 180 | // Given an m*(m+1) matrix of BigFloat where the last col means =const, 181 | // solve, and fill m[i][m] with the value for the ith variable. 182 | static void GaussianElimination(BigFloat** m, s8 rows, s8 cols); 183 | 184 | // assure that it works as expected 185 | static void UnitTest(); 186 | 187 | private: 188 | // First, this => this mod 2pi. 189 | // Return the quadrant (int)(this / (pi/4)), value 0..7 190 | // this => (this + pi/4) mod pi/2 (positive), - pi/4. 191 | // That means a negative value for odd quadrants and positive for even. 192 | s8 Quadrant(); 193 | BigFloat& PartialSin(); // sin, but only for -pi/4 to pi/4 194 | BigFloat& PartialCos(); // cos, but only for -pi/4 to pi/4 195 | 196 | // this+n, or this-n if minus==true 197 | BigFloat& AddOrSubtract(const BigFloat& n, bool minus); 198 | 199 | // test whether this is the right representation of this integer 200 | static void TestInteger(const BigFloat& n, s8 x); 201 | 202 | // test addition and subtraction of two integers 203 | static void TestAdd(s8 x, s8 y); 204 | 205 | // test multiplication of two numbers 206 | static void TestMult(s8 x, s8 ex, s8 y, s8 ey); 207 | 208 | // test inverse of one number 209 | static void TestInverse(s8 x, s8 ex); 210 | 211 | // test sqrt of one number 212 | static void TestSqrt(s8 x, s8 ex); 213 | 214 | // representation: c_digits digits, each with range 0..c_range-1 215 | // _d[0] is the most significant digit 216 | #ifdef BIGFLOAT_TEST 217 | static const s8 c_digits = 4; 218 | static const s8 c_log = 2; 219 | static const s8 c_zeroExponent = -(((s8)1) << 4); 220 | #else 221 | static const s8 c_digits = 16; 222 | static const s8 c_log = 32; 223 | 224 | // -1<<63 for a signed value, but 1<<63 is not, so 1<<62 then 225 | static const s8 c_zeroExponent = -(((s8)1) << 62); 226 | #endif 227 | static const s8 c_minExponent = c_zeroExponent + c_digits; 228 | static const s8 c_maxExponent = -c_zeroExponent; 229 | static const u8 c_range = (((u8)1)<|n| 87 | int CompareAbsolute(const BigFloat& n) const; 88 | 89 | 90 | // -1 if thisn 91 | int Compare(const BigFloat& n) const; 92 | 93 | bool IsZero() const 94 | { 95 | return 96 | _exponent == c_zeroExponent && 97 | _length == 0; 98 | } 99 | bool IsPZero() const 100 | { 101 | return 102 | _exponent == c_zeroExponent && 103 | _length == 0 && 104 | _isNegative == false; 105 | } 106 | bool IsNZero() const 107 | { 108 | return 109 | _exponent == c_zeroExponent && 110 | _length == 0 && 111 | _isNegative == true; 112 | } 113 | bool IsInf() const 114 | { 115 | return 116 | _exponent == c_zeroExponent && 117 | _length == 1; 118 | } 119 | bool IsPInf() const 120 | { 121 | return 122 | _exponent == c_zeroExponent && 123 | _length == 1 && 124 | _isNegative == false; 125 | } 126 | bool IsNInf() const 127 | { 128 | return 129 | _exponent == c_zeroExponent && 130 | _length == 1 && 131 | _isNegative == true; 132 | } 133 | bool IsNaN() const 134 | { 135 | return 136 | _exponent == c_zeroExponent && 137 | _length == 2; 138 | } 139 | bool IsSpecial() const 140 | { 141 | return _exponent == c_zeroExponent; 142 | } 143 | 144 | BigFloat& Add(const BigFloat& n) { return AddOrSubtract(n, false); } 145 | BigFloat& Sub(const BigFloat& n) { return AddOrSubtract(n, true); } 146 | BigFloat& Mult(const BigFloat& n); // x => x*n 147 | BigFloat& Div(const BigFloat& n); // x => x/n 148 | BigFloat& Invert(); // x => 1/x 149 | BigFloat& Sqrt(); // x => positive square root of x 150 | BigFloat& Cos(); // x => cosine of x (x in radians) 151 | BigFloat& Sin(); // x => sine of x (x in radians) 152 | BigFloat& Sec(); // x => secant of x (x in radians) 153 | BigFloat& Csc(); // x => cosecant of x (x in radians) 154 | BigFloat& Tan(); // x => tangent of x (x in radians) 155 | BigFloat& Exp(); // x => e to the xth power 156 | BigFloat& ASin(); // x => arcsin of x (-1 => -pi/2, 1 => pi/2) 157 | BigFloat& ACos(); // x => arccos of x (-1 => pi, 1 => 0) 158 | BigFloat& ATan(); // x => arctan of x (-inf => -pi/2, inf => pi/2) 159 | BigFloat& Ln(); // replaces x with the natural log of x 160 | BigFloat& Log(const BigFloat& n); // x => natural log of n base x 161 | BigFloat& Power(const BigFloat& n); // replaces x with x to the nth 162 | BigFloat& Rand(); // not impl: uniformly distributed value in [0,1) 163 | BigFloat& RandNorm(); // not impl: pseudorandom normally-distributed value 164 | 165 | // constants 166 | static const BigFloat& Pi(); // length of unit circle, 3.14159... 167 | static const BigFloat& E(); // the natural base for exponents, 2.71828... 168 | static const BigFloat& ConstZero(); 169 | static const BigFloat& ConstOne(); 170 | static const BigFloat& ConstMinusOne(); 171 | 172 | // variations where arguments are signed integers 173 | int Compare(s8 n, s8 exponent=0); 174 | BigFloat& Add(s8 n, s8 exponent=0); 175 | BigFloat& Sub(s8 n, s8 exponent=0); 176 | BigFloat& Mult(s8 n, s8 exponent=0); 177 | BigFloat& Div(s8 n, s8 exponent=0); 178 | BigFloat& Power(s8 n, s8 exponent=0); // not implemented 179 | 180 | // Given an m*(m+1) matrix of BigFloat where the last col means =const, 181 | // solve, and fill m[i][m] with the value for the ith variable. 182 | static void GaussianElimination(BigFloat** m, s8 rows, s8 cols); 183 | 184 | // assure that it works as expected 185 | static void UnitTest(); 186 | 187 | private: 188 | // First, this => this mod 2pi. 189 | // Return the quadrant (int)(this / (pi/4)), value 0..7 190 | // this => (this + pi/4) mod pi/2 (positive), - pi/4. 191 | // That means a negative value for odd quadrants and positive for even. 192 | s8 Quadrant(); 193 | BigFloat& PartialSin(); // sin, but only for -pi/4 to pi/4 194 | BigFloat& PartialCos(); // cos, but only for -pi/4 to pi/4 195 | 196 | // this+n, or this-n if minus==true 197 | BigFloat& AddOrSubtract(const BigFloat& n, bool minus); 198 | 199 | // test whether this is the right representation of this integer 200 | static void TestInteger(const BigFloat& n, s8 x); 201 | 202 | // test addition and subtraction of two integers 203 | static void TestAdd(s8 x, s8 y); 204 | 205 | // test multiplication of two numbers 206 | static void TestMult(s8 x, s8 ex, s8 y, s8 ey); 207 | 208 | // test inverse of one number 209 | static void TestInverse(s8 x, s8 ex); 210 | 211 | // test sqrt of one number 212 | static void TestSqrt(s8 x, s8 ex); 213 | 214 | // representation: c_digits digits, each with range 0..c_range-1 215 | // _d[0] is the most significant digit 216 | #ifdef BIGFLOAT_TEST 217 | static const s8 c_digits = 4; 218 | static const s8 c_log = 2; 219 | static const s8 c_zeroExponent = -(((s8)1) << 4); 220 | #else 221 | static const s8 c_digits = 16; 222 | static const s8 c_log = 32; 223 | 224 | // -1<<63 for a signed value, but 1<<63 is not, so 1<<62 then 225 | static const s8 c_zeroExponent = -(((s8)1) << 62); 226 | #endif 227 | static const s8 c_minExponent = c_zeroExponent + c_digits; 228 | static const s8 c_maxExponent = -c_zeroExponent; 229 | static const u8 c_range = (((u8)1)< 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | using namespace std; 12 | 13 | typedef vector VL; 14 | typedef complex CN; 15 | const double PI = 2*acos( 0.0 ); 16 | 17 | void FFT( vector &a, bool invert ) { 18 | long i,j,n = a.size(); 19 | for( i=1,j=0; i> 1 ; 21 | for( ; j>=bit; bit>>=1 ) j -= bit ; 22 | j += bit ; 23 | if( i < j ) swap( a[i],a[j] ); 24 | } 25 | long len; 26 | for( len=2; len<=n; len<<=1 ) { 27 | double ang = 2*PI / len * ( invert ? -1:1 ); 28 | CN wlen( cos( ang ) , sin( ang ) ); 29 | for( i=0; i fa( a.begin(),a.end() ), fb( b.begin(),b.end() ); 46 | long i,n = 1 ; 47 | while( n < max( a.size(),b.size()) ) n <<= 1; 48 | n <<= 1; 49 | fa.resize( n ),fb.resize( n ); 50 | FFT( fa,false ) , FFT( fb,false ); 51 | for( i=0; i 2 | using namespace std ; 3 | int a , b , n , m ; 4 | 5 | 6 | template class Matrix { 7 | 8 | public: 9 | long long arr[N][N]; 10 | 11 | Matrix() { 12 | for( int i = 0 ; i < N ; i ++ ) { 13 | for( int j = 0 ; j < N ; j++ ) { 14 | arr[i][j] = 0 ; 15 | } 16 | } 17 | } 18 | 19 | Matrix operator *(const Matrix &in) { 20 | Matrix ret ; 21 | for( int i = 0 ; i < N ; i++ ) { 22 | for( int j = 0 ; j < N ; j++ ) 23 | for( int k = 0 ; k < N ; k++ ) { 24 | ret.arr[i][j] += (arr[i][k] ) * ( in.arr[k][j] ) ; 25 | ret.arr[i][j] %= 10000 ; 26 | } 27 | } 28 | return ret ; 29 | } 30 | 31 | Matrix operator ^( int POW ) { 32 | 33 | Matrix ret ; 34 | for( int i = 0 ; i < N ; i++ ) { 35 | ret.arr[i][i] = 1 ; 36 | } 37 | 38 | Matrix ME = *this ; 39 | 40 | while( POW ) { 41 | 42 | if( POW&1 ) { 43 | ret = ret * ME ; 44 | } 45 | ME = ME * ME ; 46 | POW >>= 1 ; 47 | 48 | } 49 | return ret ; 50 | } 51 | }; 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | #include 64 | using namespace std ; 65 | class matrix { 66 | public: 67 | vector >arr; 68 | matrix() {} 69 | matrix(int N) { 70 | for( int i = 0 ; i < N ; i ++ ) { 71 | vectory; 72 | for( int j = 0 ; j < N ; j++ ) { 73 | y.push_back(0); 74 | } 75 | arr.push_back(y); 76 | } 77 | } 78 | matrix operator *(const matrix &in) { 79 | matrix ret ; 80 | int N=this->arr.size(); 81 | ret=matrix(N); 82 | for( int i = 0 ; i < N ; i++ ) { 83 | for( int j = 0 ; j < N ; j++ ) 84 | for( int k = 0 ; k < N ; k++ ) { 85 | ret.arr[i][j]+=(arr[i][k])*(in.arr[k][j]) ; 86 | ret.arr[i][j]%=10 ; 87 | } 88 | } 89 | return ret ; 90 | } 91 | matrix operator ^( long long int POW) { 92 | matrix ret; 93 | int N=this->arr.size(); 94 | ret=matrix(N); 95 | for( int i = 0 ; i < N ; i++ ) { 96 | ret.arr[i][i] = 1 ; 97 | } 98 | matrix ME = *this ; 99 | while( POW ) { 100 | if( POW&1 ) { 101 | ret = ret * ME ; 102 | } 103 | ME = ME * ME ; 104 | POW >>= 1 ; 105 | } 106 | return ret ; 107 | } 108 | matrix operator +(const matrix &x) { 109 | matrix ret; 110 | int N=this->arr.size(); 111 | ret=matrix(N); 112 | for(int i=0; i 2 | #include 3 | using namespace std ; 4 | 5 | long long Extendex_GCD( long long a , long long b ) { 6 | long long x = 0 , y = 1 , g = b ; 7 | long long m, n, q, r; 8 | for (long long u=1, v=0; a != 0; g=a, a=r) { 9 | q = g / a; 10 | r = g % a; 11 | m = x-u*q; 12 | n = y-v*q; 13 | x=u; 14 | y=v; 15 | u=m; 16 | v=n; 17 | } 18 | return y; 19 | 20 | } 21 | 22 | 23 | long long CRT(pair arr[] , int n ) { 24 | long long int N = 1 ; 25 | for( int i = 0 ; i < n ; i++ ) { 26 | N*=arr[i].first ; 27 | } 28 | long long ans = 0 ; 29 | for( int i = 0 ; i < n ; i++ ) { 30 | long long b = Extendex_GCD( arr[i].first , N/arr[i].first ); 31 | ans+=arr[i].second*b*(N/arr[i].first) ; 32 | ans%=N ; 33 | } 34 | if( ans < 0 )ans += N ; 35 | return ans ; 36 | 37 | } 38 | 39 | int main() { 40 | 41 | // freopen( "in" , "r" , stdin ) ; 42 | int cases , caseno = 1 ; 43 | scanf("%d",&cases ) ; 44 | 45 | while( cases -- ) { 46 | 47 | int n ; 48 | scanf("%d" , &n) ; 49 | pair arr[n] ; 50 | 51 | for( int i = 0 ; i < n ; i++ ) { 52 | scanf("%lld%lld",&arr[i].first , &arr[i].second ) ; 53 | } 54 | 55 | printf("Case %d: %lld\n",caseno++,CRT(arr , n )) ; 56 | 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /Number theory & Math/ExtendedEuclidMOdInverse.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Implementation of extended euclid algorithm. 3 | Modular inverse requires gcd(a, n) = 1. 4 | */ 5 | 6 | class Euclid { 7 | public: 8 | i64 x, y, d; 9 | Euclid() {} 10 | Euclid(i64 _x, i64 _y, i64 _d) : x(_x), y(_y), d(_d) {} 11 | }; 12 | 13 | Euclid egcd(i64 a, i64 b) { 14 | if(!b) return Euclid(1, 0, a); 15 | Euclid r = egcd(b, a % b); 16 | return Euclid(r.y, r.x - a / b * r.y, r.d); 17 | } 18 | 19 | i64 modinv(i64 a, i64 n) { 20 | Euclid t = egcd(a, n); 21 | if(t.d > 1) return 0; 22 | i64 r = t.x % n; 23 | return (r < 0 ? r + n : r); 24 | } 25 | -------------------------------------------------------------------------------- /Number theory & Math/Hn.cpp: -------------------------------------------------------------------------------- 1 | void precalc() { 2 | arr[0] = 0 ; 3 | arr[1] = 1 ; 4 | for( int i = 2 ; i < 1000000 ; i++ ) { 5 | arr[i] = arr[i-1]+ (1/double(i)) ; 6 | } 7 | } 8 | #define gamma 0.57721566490153286060651209008240243104215933593992 9 | double Hn( double N ) { 10 | if( N < 1000000 ) { 11 | return arr[int(N)]; 12 | } else return (log(double(N))+log(double(N+1)))/2 + gamma ; ; 13 | } 14 | 15 | 16 | --------------------------------- 17 | long long H( int n ) { 18 | long long res = 0; 19 | for( int i = 1; i <= n; i++ ) 20 | res = res + n / i; 21 | return res; 22 | } 23 | 24 | 25 | long long a ; 26 | scanf("%lld",&a ) ; 27 | long long ans = 0 ; 28 | long long LIM = sqrt( a ) ; 29 | for( int i = 1 ; i <= LIM ; i++ ) { 30 | ans += a/i ; 31 | } 32 | printf("Case %d: %lld\n",caseno++ , (ans<<1) - LIM*LIM ) ; 33 | -------------------------------------------------------------------------------- /Number theory & Math/LinearDiphontine.cpp: -------------------------------------------------------------------------------- 1 | typedef long long Long; 2 | 3 | void Egcd( Long a, Long b, Long &x, Long &y, Long &g ){ 4 | if( !b ) x = 1,y = 0,g = a; 5 | else{ 6 | Long x1,y1; 7 | Egcd( b,a%b,x1,y1,g ); 8 | x = y1; 9 | y = x1 - a/b*y1; 10 | } 11 | } 12 | 13 | Long MyFloor( Long a, Long b ) { 14 | Long c = a / b; 15 | if( (a%b) and a<0 ) c--; 16 | return c; 17 | } 18 | 19 | Long Solve( Long a, Long b, Long c, Long x1, Long x2, Long y1, Long y2 ){ 20 | Long x,y,g; 21 | 22 | if( a < 0 ) a *= -1, x1 *= -1, x2 *= -1, swap(x1, x2); 23 | if( b < 0 ) b *= -1, y1 *= -1, y2 *= -1, swap(y1, y2); 24 | 25 | if( !a and !b ) return !c ? ( x2-x1+1 )*( y2-y1+1 ) : 0; 26 | if( b==0 ){ 27 | if( c%a ) return 0; 28 | x = c/a; 29 | return ( x>=x1 and x<=x2)*( y2-y1+1 ); 30 | } 31 | if( a==0 ) { 32 | if( c%b ) return 0; 33 | y = c/b; 34 | return ( y>=y1 and y<=y2 )*( x2-x1+1 ); 35 | } 36 | 37 | Egcd( a,b,x,y,g ); 38 | if( c%g ) return 0; 39 | 40 | a /= g; b /= g; c /= g; g = 1; 41 | x = x*c; y = y*c; 42 | 43 | Long n2 = min( MyFloor( x-x1, b ), MyFloor( y2-y, a ) ); 44 | Long n1 = -min( MyFloor( y-y1, a ), MyFloor( x2-x, b ) ); 45 | return ( n2 2 | using namespace std; 3 | #define LL long long 4 | /* 5 | This is not my code . I collect It from net. use it. save it as 6 | a pollard rho in my library. Use as a API for problem solving. 7 | http://www.csie.ntnu.edu.tw/~u91029/Prime.html 8 | */ 9 | 10 | int p[5500], pt = 0; 11 | void sieve() { 12 | int mark[46340] = {}; 13 | int i, j; 14 | for(i = 2; i < 46340; i++) { 15 | if(mark[i] == 0) { 16 | p[pt++] = i; 17 | for(j = i+i; j < 46340; j += i) 18 | mark[j] = 1; 19 | } 20 | } 21 | } 22 | LL modmultiply(LL a,LL b,LL c) { 23 | LL x = 0,y = a%c; 24 | while(b > 0) { 25 | if(b%2 == 1) { 26 | x = (x+y)%c; 27 | } 28 | y = (y*2)%c; 29 | b /= 2; 30 | } 31 | return x%c; 32 | } 33 | LL modpow(LL x, LL y, LL mod) { 34 | LL ret = 1;// ret = x^y%mod; 35 | while(y) { 36 | if(y&1) 37 | //ret = (ret*x)%mod; 38 | ret = modmultiply(ret, x, mod); 39 | //x = (x*x)%mod; 40 | x = modmultiply(x, x, mod); 41 | y >>= 1; 42 | } 43 | return ret; 44 | } 45 | int isprime(LL n) { 46 | if(n == 2 || n == 3) 47 | return 1; 48 | if(n < 2 || (n&1) == 0) 49 | return 0; 50 | int i, a; 51 | for(i = 0; i < 5; i++) { 52 | a = rand()%(n-4)+2; 53 | if(modpow(a, n-1, n) != 1) 54 | return 0; 55 | } 56 | return 1; 57 | } 58 | LL gcd(LL x, LL y) { 59 | if(!x) return y; 60 | if(!y) return x; 61 | if(x < 0) x = -x; 62 | if(y < 0) y = -y; 63 | LL t; 64 | while(x%y) 65 | t = x, x = y, y = t%y; 66 | return y; 67 | } 68 | vector ret; 69 | LL pollard_rho(LL n, LL c) { 70 | long long x = 2, y = 2; 71 | do { 72 | //x = (x*x+c)%n; 73 | x = (modmultiply(x, x, n)+c)%n; 74 | //y = (y*y+c)%n, y = (y*y+c)%n; 75 | y = (modmultiply(y, y, n)+c)%n; 76 | y = (modmultiply(y, y, n)+c)%n; 77 | LL d = gcd(x-y, n); 78 | if(d > 1) return d; 79 | } while(true); 80 | return n; 81 | } 82 | void small_factorize(LL n) { 83 | int i; 84 | for(i = 0; i < pt && p[i]*p[i] <= n; i++) { 85 | if(n%p[i] == 0) { 86 | while(n%p[i] == 0) 87 | ret.push_back(p[i]), n /= p[i]; 88 | } 89 | } 90 | if(n != 1) 91 | ret.push_back(n); 92 | } 93 | void factorize(LL n) { 94 | if(n == 1) return; 95 | if(isprime(n)) { 96 | ret.push_back(n); 97 | return; 98 | } 99 | if(n < 1000000000) { 100 | small_factorize(n); 101 | return; 102 | } 103 | int c; 104 | LL d = n; 105 | for(c = 2; d == n; c++) { 106 | d = pollard_rho(n, c); 107 | } 108 | factorize(d); 109 | factorize(n/d); 110 | } 111 | int main() { 112 | sieve(); 113 | int cases ; 114 | scanf("%d",&cases ) ; 115 | while( cases-- ) { 116 | long long n ; 117 | scanf("%lld", &n); 118 | ret.clear(); 119 | factorize(n); 120 | sort(ret.begin(), ret.end()); 121 | cout << n << " = " ; 122 | /* 123 | for( int i = 0 ; i < ret.size() ; i++ )cout << ret[i] << " " ; 124 | cout << "\n" ; 125 | */ 126 | int cnt = 1 ; 127 | for( int i = 1 ; i < ret.size() ; i++ ){ 128 | if( ret[i] == ret[i-1] )cnt ++ ; 129 | else { 130 | cout << ret[i-1] ; 131 | if( cnt > 1 ){ 132 | cout << "^" << cnt ; 133 | } 134 | cout << " * " ; 135 | cnt = 1 ; 136 | } 137 | } 138 | cout << ret[ret.size()-1] ; 139 | if( cnt > 1 )cout << "^" << cnt ; 140 | cout << "\n" ; 141 | 142 | } 143 | return 0; 144 | } 145 | -------------------------------------------------------------------------------- /Number theory & Math/SegmentedSieve.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Generates primes within interval [a, b] when b - a <= 100000 3 | and 1 <= a <= b <= 2147483647 4 | */ 5 | int base[MAX>>6], segment[RNG>>6], primes[LEN], prlen; 6 | 7 | #define chkC(x,n) (x[n>>6]&(1<<((n>>1)&31))) 8 | #define setC(x,n) (x[n>>6]|=(1<<((n>>1)&31))) 9 | 10 | void sieve() { 11 | int i, j, k; 12 | for(i=3; i M; 11 | map< long long, int > :: iterator it; 12 | m = (int)ceil(sqrt((double)(p))); 13 | M.insert(make_pair(1, 0)); 14 | for(j = 1, aj = 1; j < m; j++) { 15 | aj = (aj * a) % p; 16 | M.insert(make_pair(aj, j)); 17 | } 18 | ami = modexp(modinv(a, p), m, p); 19 | for(c = b, i = 0; i < m; i++) { 20 | it = M.find(c); 21 | if(it != M.end()) return i * m + it->second; 22 | c = (c * ami) % p; 23 | } 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /Number theory & Math/Sieve.cpp: -------------------------------------------------------------------------------- 1 | #define MAX 10000000 2 | unsigned flag[MAX/64]; 3 | vectorprime ; 4 | 5 | #define chkC(n) (flag[n>>6]&(1<<((n>>1)&31))) 6 | #define setC(n) (flag[n>>6]|=(1<<((n>>1)&31))) 7 | int lim; 8 | void sieve() { 9 | unsigned i, j, k; 10 | flag[0]|=0; 11 | int sqrtN = sqrt(MAX) ; 12 | for(i=3; i<= sqrtN ; i+=2) 13 | if(!chkC(i)) 14 | for(j=i*i,k=i<<1; j>1)<<1) + ((n&1)?1:-1); 9 | } 10 | 11 | int f(int n, int k) { 12 | if(n == 1) return 0; 13 | return (f(n-1, k) + k)%n; 14 | } 15 | -------------------------------------------------------------------------------- /Number theory & Math/ncr.cpp: -------------------------------------------------------------------------------- 1 | void precalc() { 2 | for(int i = 1 ; i <= 1000 ; i++) { 3 | nCr[i][0]=1; 4 | nCr[i][1]=i; 5 | for(int j = 2 ; j <= i ; j++ ) { 6 | nCr[i][j] = ( nCr[i-1][j-1] + nCr[i-1][j] ) % MOD; 7 | } 8 | } 9 | } 10 | long long Pow(long long n , long long k) { 11 | long long ret = 1; 12 | while( k ) { 13 | if( k&1 ) { 14 | ret *= n; 15 | ret %= MOD; 16 | } 17 | n *= n; 18 | n %= MOD; 19 | k >>= 1; 20 | } 21 | return ret; 22 | } 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Algorithms-Code-Library 2 | C++ Implementation of variety of Algorithms and some mush have cheetsheets for CS Students. 3 | 4 | ## Cheet Sheets 5 | - [Trigonometry Cheat sheet](https://github.com/sbmaruf/Algorithms-Code-Library/blob/master/Cheet%20Sheets/Trig_Cheat_Sheet.pdf) 6 | - [Computer Science Cheat sheet](https://github.com/sbmaruf/Algorithms-Code-Library/blob/master/Cheet%20Sheets/computer_science_cheatsheet.pdf) : Mainly series, algorithm discrete math and calculus based cheat sheet. 7 | - [ICPC Cheatsheet](https://github.com/sbmaruf/Algorithms-Code-Library/blob/master/Cheet%20Sheets/cheatsheet2014.pdf) : Outdated, may be helpful for beginners. 8 | 9 | ## Data Structure 10 | 11 | In no particular order, 12 | 13 | - Binary Indexed tree (BIT) 14 | - Heavy Light Decomposition (HLD) 15 | - Histrogram 16 | - LCA 17 | - RMQ 18 | - trie 19 | ## Geometry 20 | 21 | In no particular order, 22 | 23 | - CircleSegmentTetrahedron 24 | - Closest Pair 25 | - ConvexHull 26 | - ConvexHull GrahamScan 27 | - ConvexHull MonotoneChain 28 | - Parametric Geometry routine 29 | - Line segment intersection 30 | - Ray casting algorithm (PointInPolygon) 31 | - Rotate point 32 | - Tangent of line 33 | 34 | ## Graph 35 | 36 | In no particular order, 37 | 38 | - Stoer Wagner all pair Min Cut 39 | - Articulation Point 40 | - Bellman Ford 41 | - BiConnected Component 42 | - Bridge 43 | - Disjoint Set 44 | - Eular Circuit 45 | - Hungerian Algorithm 46 | - Max Weighted Bi-partite Matching 47 | - MaxFlow Dinic 48 | - Maximum Bipertite Matching 49 | - Mincost Max Flow 50 | - Minimum Expression 51 | - Dinitz 52 | - Dinitz With EdgeList 53 | - Stable marrige problem 54 | - Strongly Connected Component 55 | - Tarjans Off line LCA 56 | - manacher 57 | 58 | 59 | ## Matrix & Numeric 60 | 61 | In no particular order, 62 | 63 | - Big float (C++ library) 64 | - BigInt 65 | - FFT 66 | - Faussian Elimination 67 | - matrix Exponentiation 68 | 69 | 70 | 71 | ## Number theory and Math 72 | 73 | In no particular order, 74 | 75 | - ExtendedEuclidMOdInverse 76 | - Hn 77 | - LinearDiphontine 78 | - Number Theory Part 1.pdf - Good colelction of Number theoric discussion. 79 | - NumberTheory Part 2.pdf - Good colelction of Number theoric discussion. 80 | - PollardRho 81 | - SegmentedSieve 82 | - ShankBabyStepGiantStep 83 | - Sieve 84 | - josepheous 85 | - ncr 86 | 87 | ## Searching 88 | 89 | - Ternary Search 90 | 91 | 92 | ## String 93 | - Aho Chorasik 94 | - KMP 95 | - Hashing 96 | - suffix-array.pdf - Good discussion of suffix-array 97 | - Suffix array code. 98 | 99 | 100 | ## IO 101 | - Fast read C++ 102 | 103 | ## Collected Library 104 | 105 | - [Stanford University ACM Team Notebook](https://github.com/sbmaruf/Algorithms-Code-Library/blob/master/Collected%20Library/Stanford%20University%20ACM%20Team%20Notebook.pdf) : Outdated, maybe helpful for mid-level/above mid-level problem solver. 106 | - Combinatorial optimization1. 107 | 1. Sparse max-flow (C++) 108 | 2. Min-cost max-flow (C++) 109 | 3. Push-relabel max-flow (C++) 110 | 4. Min-cost matching (C++) 111 | 5. Max bipartite matching (C++) 112 | 6. Global min cut (C++) 113 | 7. Graph cut inference (C++) 114 | - Geometry 115 | 1. Convex hull (C++) 116 | 2. Miscellaneous geometry (C++) 117 | 3. Java geometry (Java) 118 | 4. 3D geometry (Java) 119 | 5. Slow Delaunay triangulation (C++) 120 | - Numerical algorithms 121 | 1. Number theoretic algorithms (modular, Chinese remainder, linear Diophantine) (C++) 122 | 2. Systems of linear equations, matrix inverse, determinant (C++) 123 | 3. Reduced row echelon form, matrix rank (C++) 124 | 4. Fast Fourier transform (C++) 125 | 5. Simplex algorithm (C++) 126 | - Graph algorithms 127 | 1. Fast Dijkstra's algorithm (C++) 128 | 2. Strongly connected components (C) 129 | 3. Eulerian Path (C++) 130 | - Data structures 131 | 1. Suffix arrays (C++) 132 | 2. Binary Indexed Tree 133 | 3. Union-Find Set (C/C++) 134 | 4. KD-tree (C++) 135 | 5. Lazy Segment Tree (Java) 136 | 6. Lowest Common Ancestor (C++) 137 | - Miscellaneous 138 | 1. Longest increasing subsequence (C++) 139 | 2. Dates (C++) 140 | 3. Regular expressions (Java) 141 | 4. Prime numbers (C++) 142 | 5. C++ input/output 143 | 6. Knuth-Morris-Pratt (C++) 144 | - [Stavropol SU](https://github.com/sbmaruf/Algorithms-Code-Library/blob/master/Collected%20Library/Stavropol%20SU%20.pdf) : Extremely outdated, but worth to look at. 145 | - vimrc 146 | - Java template 147 | - Combinatorics 148 | - Number Theory 149 | - String Algorithms 150 | - Min-cost max-flow 151 | - Graph Theory 152 | - Games 153 | - Geometry 154 | - Math 155 | - Data Structures 156 | - Miscellanious 13FFT 157 | 158 | 159 | Special Thanks: My trainer Tarif Ezaz and my friend Mohammad Abdullah Matin Khan Zarzis to whom I learned to think. 160 | 161 | I also want to mention some of the other special names for their tremendous support. Nafis Ahmed, Mohammad Samiul Islam, Zobayer Hasan, Forhad Ahmed and Leonardo Boshell 162 | 163 | NOTE : I don't claim all of the soutions to be mine. While I was solving the problems, I took help from different peoples and see other people's code for many problems. In Fact most of the coder here is collected. But I never submit any code without my complete understanding. I suugest those who will be following the repo to do so. Pasting code to online judges won't take you any further except frustration. 164 | -------------------------------------------------------------------------------- /Searching/TernarySearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std ; 3 | #define x first 4 | #define y second 5 | pair p[4] ; 6 | 7 | double dist( pair a ,pair b ){ 8 | return ( (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) ) ; 9 | } 10 | double Dist( pair a ,pair b ){ 11 | return sqrt( (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) ) ; 12 | } 13 | double ternary_search(){ 14 | pair P[4] ; 15 | for( int i = 0 ; i < 40 ; i++ ){ 16 | 17 | P[0].x = (2*p[0].x+p[1].x)/3.0 ; 18 | P[0].y = (2*p[0].y+p[1].y)/3.0 ; 19 | 20 | P[1].x = (p[0].x+2*p[1].x)/3.0 ; 21 | P[1].y = (p[0].y+2*p[1].y)/3.0 ; 22 | 23 | P[2].x = (2*p[2].x+p[3].x)/3.0 ; 24 | P[2].y = (2*p[2].y+p[3].y)/3.0 ; 25 | 26 | P[3].x = (p[2].x+2*p[3].x)/3.0 ; 27 | P[3].y = (p[2].y+2*p[3].y)/3.0 ; 28 | 29 | //cout << P[0].x << " " << P[0].y <<" " << P[1].x << " " << P[1].y <<" " << P[2].x << " " << P[2].y <<" " << P[3].x << " " << P[3].y << endl; 30 | 31 | if( dist( P[0] , P[2] ) > dist( P[1] , P[3] ) ){ 32 | p[0] = P[0] ; 33 | p[2] = P[2] ; 34 | }else { 35 | p[1] = P[1] ; 36 | p[3] = P[3] ; 37 | } 38 | 39 | } 40 | return min(Dist(p[0],p[2]),Dist(p[1],p[3])) ; 41 | } 42 | 43 | int main(){ 44 | 45 | int cases , caseno=1 ; 46 | scanf("%d",&cases ) ; 47 | while( cases-- ){ 48 | scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&p[0].x,&p[0].y,&p[1].x,&p[1].y,&p[2].x,&p[2].y,&p[3].x,&p[3].y) ; 49 | printf("Case %d: %.8f\n",caseno++,ternary_search()); 50 | } 51 | 52 | return 0 ; 53 | } 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | #include 62 | 63 | #define x first 64 | #define y second.first 65 | #define z second.second 66 | 67 | using namespace std ; 68 | 69 | typedef pair > _3Dpoint ; 70 | 71 | 72 | double dist( _3Dpoint a , _3Dpoint b ) 73 | { 74 | return sqrt( (a.x-b.x)* (a.x-b.x) + (a.y-b.y)* (a.y-b.y) + (a.z-b.z)* (a.z-b.z) ) ; 75 | } 76 | 77 | double TS(_3Dpoint point[]) 78 | { 79 | 80 | _3Dpoint lthird , rthird ; 81 | int tmp = 100 ; 82 | 83 | while( tmp -- ) { 84 | 85 | lthird.x = (2*point[0].x+point[1].x)/3.0 ; 86 | lthird.y = (2*point[0].y+point[1].y)/3.0 ; 87 | lthird.z = (2*point[0].z+point[1].z)/3.0 ; 88 | rthird.x = (point[0].x+2*point[1].x)/3.0 ; 89 | rthird.y = (point[0].y+2*point[1].y)/3.0 ; 90 | rthird.z = (point[0].z+2*point[1].z)/3.0 ; 91 | 92 | if( dist( lthird,point[2] ) > dist( rthird , point[2] ) ) 93 | point[0] = lthird ; 94 | else 95 | point[1] = rthird ; 96 | 97 | } 98 | 99 | double ret = dist( point[0] , point[2] ) ; 100 | return ret ; 101 | } 102 | 103 | int main() 104 | { 105 | 106 | int T ; 107 | scanf("%d",&T) ; 108 | 109 | for( int i = 0; i < T ; i++ ) { 110 | _3Dpoint point[3] ; 111 | scanf("%lf%lf%lf%lf%lf%lf%lf%lf%lf",&point[0].x,&point[0].y,&point[0].z,&point[1].x,&point[1].y,&point[1].z,&point[2].x,&point[2].y,&point[2].z) ; 112 | double ans = TS(point) ; 113 | printf("Case %d: %.10f\n", i+1 , ans ); 114 | } 115 | 116 | return 0 ; 117 | } 118 | 119 | -------------------------------------------------------------------------------- /String/AhoChorasik.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std ; 3 | char T[1000000+1] ; 4 | char keyword[500] ; 5 | char tmp[1000000+1] ; 6 | int n ; 7 | int freq[1000000+1] ; 8 | int ans[1000000] ; 9 | struct Trie { 10 | int level,_next[26] ; 11 | vectorpatIdx ; 12 | int parent ; 13 | Trie() { 14 | level = 0 ; 15 | memset( _next , 0 , sizeof _next ) ; 16 | patIdx.clear() ; 17 | parent = 0 ; 18 | } 19 | }; 20 | 21 | const int MAXC = 500*500+5 ; 22 | 23 | Trie Tree[MAXC] ; 24 | int treeIdx ; 25 | 26 | void InsertTrie(char keyword[],int idx) { 27 | int root = 0 ; 28 | for( int i = 0 ; keyword[i] ; i++ ) { 29 | char ch = keyword[i]-'a' ; 30 | if( Tree[root]._next[ch] == 0 ) { 31 | Tree[root]._next[ch] = treeIdx++ ; 32 | } 33 | Tree[Tree[root]._next[ch]].level = Tree[root].level+1 ; 34 | root = Tree[root]._next[ch] ; 35 | } 36 | Tree[root].patIdx.push_back(idx); 37 | } 38 | 39 | void print(){ 40 | for( int i = 0 ;i < 9 ; i++ )cout << Tree[i].parent << " " ; 41 | cout << endl ; 42 | } 43 | 44 | int FindParent( int src,int ch ) { 45 | int par = Tree[src].parent ; 46 | while( par > 0 && Tree[par]._next[ch] == 0 ) { 47 | par = Tree[par].parent ; 48 | } 49 | return par ; 50 | } 51 | 52 | void bfsOnTrie() { 53 | 54 | queueQ ; 55 | for( int i =0 ; i < 26 ; i++ ) { 56 | if( Tree[0]._next[i] != 0 ) { 57 | Q.push( Tree[0]._next[i] ) ; 58 | } 59 | } 60 | while( !Q.empty() ) { 61 | int src = Q.front() ; 62 | Q.pop(); 63 | for( int i = 0 ; i < 26 ; i++ ) { 64 | if( Tree[src]._next[i] != 0 ) { 65 | int dest = Tree[src]._next[i] ; 66 | int par = FindParent(src,i) ; 67 | Tree[dest].parent = Tree[par]._next[i] ; 68 | //print(); 69 | Q.push(dest) ; 70 | } 71 | } 72 | } 73 | } 74 | 75 | bool comp( pair a , pair b ){ 76 | return a.first > b.first ; 77 | } 78 | 79 | void query() { 80 | int root = 0 ; 81 | memset( freq , 0 , sizeof freq ) ; 82 | for( int i = 0 ; T[i] ; i++ ) { 83 | int ch = T[i] - 'a' , par; 84 | if( Tree[root]._next[ch] == 0 ) { 85 | int par = FindParent(root,ch) ; 86 | root = Tree[par]._next[ch] ; 87 | } else { 88 | root = Tree[root]._next[ch] ; 89 | } 90 | freq[root]++ ; 91 | } 92 | vector > tmp ; 93 | for( int i = 0 ; i < treeIdx ; i++ ){ 94 | tmp.push_back( make_pair(Tree[i].level,i) ) ; 95 | } 96 | sort( tmp.begin() , tmp.end() , comp ); 97 | for( int i = 0 ; i < treeIdx ; i++ ){ 98 | freq[ Tree[tmp[i].second].parent ]+=freq[tmp[i].second] ; 99 | } 100 | for( int i = 1 ; i < treeIdx ; i++ ){ 101 | for( int j = 0 ; j < Tree[i].patIdx.size() ; j++ ){ 102 | ans[Tree[i].patIdx[j]] = freq[i] ; 103 | } 104 | } 105 | } 106 | 107 | int main() { 108 | 109 | int cases,caseno=1 ; 110 | scanf("%d",&cases ) ; 111 | while( cases -- ) { 112 | scanf("%d%s",&n,T) ; 113 | treeIdx = 1 ; 114 | for( int i = 0 ; i < n ; i++ ) { 115 | scanf("%s",keyword) ; 116 | InsertTrie(keyword,i) ; 117 | } 118 | bfsOnTrie() ; 119 | query(); 120 | cout << "Case " << caseno++ << ":\n"; 121 | for(int i = 0 ; i < n ; i++ ){ 122 | cout << ans[i] << "\n" ; 123 | } 124 | for( int i = 0 ; i < MAXC ; i++ ) Tree[i] = Trie() ; 125 | } 126 | return 0 ; 127 | } 128 | 129 | 130 | /* 131 | 132 | 1 133 | 4 134 | aishers 135 | he 136 | she 137 | hers 138 | his 139 | */ 140 | -------------------------------------------------------------------------------- /String/KMP.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbmaruf/Algorithms-Code-Library/d95d79f0ee9ab3653a96ff8dfca44b703641e365/String/KMP.cpp -------------------------------------------------------------------------------- /String/hashing.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int cum[1501] ; 4 | const int mod[3]= {132543,56346,3125}; 5 | const int mul[3]= {27,6545,543}; 6 | const int ads[3]= {32,543,76}; 7 | 8 | int main() { 9 | 10 | ios_base::sync_with_stdio(0); 11 | cin.tie() ; 12 | 13 | string s , s1 ; 14 | int k ; 15 | cin >> s >> s1 >> k ; 16 | int l = s.size() , ans = 0 ; 17 | 18 | cum[0] = int(s1[s[0]-'a']=='0') ; 19 | for( int i = 1 ; i < l ; i++ ) { 20 | cum[i]=cum[i-1]+int(s1[s[i]-'a']=='0') ; 21 | } 22 | for( int len = 1 ; len <= l ; len++ ) { 23 | set< vector >st ; 24 | vectorhsh,tmp ; 25 | for( int i = 0 ; i < 3 ; i++ ) { 26 | tmp.push_back(1) ; 27 | hsh.push_back(0) ; 28 | } 29 | for( int j = 0 ; j < len ; j++ ) { 30 | for(int k = 0 ; k < 3 ; k++ ) { 31 | hsh[k] = (hsh[k]*mul[k]+s[j]+ads[k])%mod[k] ; 32 | tmp[k] = tmp[k]*mul[k]%mod[k] ; 33 | } 34 | } 35 | if( cum[len-1] <= k )st.insert(hsh) ; 36 | for( int i = len ; i < l ; i++ ) { 37 | for(int j = 0 ; j < 3 ; j++ ) { 38 | hsh[j]=(hsh[j]*mul[j]+s[i]+ads[j])%mod[j] ; 39 | hsh[j]-=tmp[j]*(s[i-len]+ads[j])%mod[j] ; 40 | if( hsh[j] < 0 ){ 41 | hsh[j] += mod[j] ; 42 | } 43 | } 44 | if( cum[i]-cum[i-len] <= k )st.insert(hsh) ; 45 | } 46 | //cout << len << " " << st.size() < pallen && buff[i-pallen-1] == buff[i]) { 13 | pallen += 2, i++; 14 | continue; 15 | } 16 | lengths[k++] = pallen; 17 | s = k - 2, e = s - pallen, found = 0; 18 | for(j = s; j > e; j--) { 19 | d = j - e - 1; 20 | if(lengths[j] == d) { 21 | pallen = d; 22 | found = 1; 23 | break; 24 | } 25 | lengths[k++] = (d < lengths[j]? d : lengths[j]); 26 | } 27 | if(!found) { pallen = 1; i++; } 28 | } 29 | lengths[k++] = pallen; 30 | return lengths[k-1]; 31 | } 32 | -------------------------------------------------------------------------------- /String/suffix-array.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbmaruf/Algorithms-Code-Library/d95d79f0ee9ab3653a96ff8dfca44b703641e365/String/suffix-array.pdf -------------------------------------------------------------------------------- /String/suffixArray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Generates suffix array in O(n (lg n)^2). Finds LCP in O(lg n) 3 | A[] is the target string with N length. base is the lowest character in A[]. 4 | S[i] holds the index of ith suffix when sorted lexicographically. 5 | Change base as necessary and MAXLOG = log2(MAXLEN). 6 | */ 7 | 8 | int N, stp, P[MAXLOG][MAXLEN], S[MAXLEN]; 9 | char A[MAXLEN], base = 'a'; 10 | struct entry { int nr[2], p; } L[MAXLEN]; 11 | 12 | inline bool cmp(const entry &a, const entry &b) { 13 | return a.nr[0] == b.nr[0] ? (a.nr[1] < b.nr[1] ? 1 : 0) : (a.nr[0] < b.nr[0] ? 1 : 0); 14 | } 15 | 16 | void generateSuffix() { 17 | register int i, cnt; 18 | for(i=0; i>1 < N; stp++, cnt<<=1) { 20 | for(i=0; i 0 && L[i].nr[0] == L[i - 1].nr[0] && L[i].nr[1] == L[i - 1].nr[1]) P[stp][L[i].p] = P[stp][L[i - 1].p]; 28 | else P[stp][L[i].p] = i; 29 | } 30 | } 31 | for(i=0; i= 0 && x < N && y < N; k --) 38 | if(P[k][x] == P[k][y]) 39 | x += 1 << k, y += 1 << k, ret += 1 << k; 40 | return ret; 41 | } 42 | 43 | 44 | 45 | //nlogn 46 | /* 47 | Suffix array implementation using bucket sorting + lcp. 48 | Complexity O(n log n), str[] is the target string, 49 | n is its length and suffix[i] contains i'th sorted suffix position. 50 | */ 51 | 52 | const int MAXN = 1 << 16; 53 | const int MAXL = 16; 54 | 55 | int n, stp, mv, suffix[MAXN], tmp[MAXN]; 56 | int sum[MAXN], cnt[MAXN], rank[MAXL][MAXN]; 57 | char str[MAXN]; 58 | 59 | inline bool equal(const int &u, const int &v){ 60 | if(!stp) return str[u] == str[v]; 61 | if(rank[stp-1][u] != rank[stp-1][v]) return false; 62 | int a = u + mv < n ? rank[stp-1][u+mv] : -1; 63 | int b = v + mv < n ? rank[stp-1][v+mv] : -1; 64 | return a == b; 65 | } 66 | 67 | void update(){ 68 | int i, rnk; 69 | for(i = 0; i < n; i++) sum[i] = 0; 70 | for(i = rnk = 0; i < n; i++) { 71 | suffix[i] = tmp[i]; 72 | if(i && !equal(suffix[i], suffix[i-1])) { 73 | rank[stp][suffix[i]] = ++rnk; 74 | sum[rnk+1] = sum[rnk]; 75 | } 76 | else rank[stp][suffix[i]] = rnk; 77 | sum[rnk+1]++; 78 | } 79 | } 80 | 81 | void Sort() { 82 | int i; 83 | for(i = 0; i < n; i++) cnt[i] = 0; 84 | memset(tmp, -1, sizeof tmp); 85 | for(i = 0; i < mv; i++){ 86 | int idx = rank[stp - 1][n - i - 1]; 87 | int x = sum[idx]; 88 | tmp[x + cnt[idx]] = n - i - 1; 89 | cnt[idx]++; 90 | } 91 | for(i = 0; i < n; i++){ 92 | int idx = suffix[i] - mv; 93 | if(idx < 0)continue; 94 | idx = rank[stp-1][idx]; 95 | int x = sum[idx]; 96 | tmp[x + cnt[idx]] = suffix[i] - mv; 97 | cnt[idx]++; 98 | } 99 | update(); 100 | return; 101 | } 102 | 103 | inline bool cmp(const int &a, const int &b){ 104 | if(str[a]!=str[b]) return str[a]= 0; i--) { 127 | if(rank[i][u] == rank[i][v]) { 128 | ret += 1<