├── README.md
├── Sorting Algorithms
├── Bubble Sort.cpp
├── Selection Sort.cpp
├── Insertion Sort.cpp
├── Radix Sort.cpp
├── Count Sort.cpp
├── Merge Sort.cpp
├── Heap Sort.cpp
└── Quick Sort.cpp
├── Max 1D Range Sum.cpp
├── Graph Algorithms
├── DFS.cpp
├── Floyd-Warshall.cpp
├── BFS.cpp
├── Prim.cpp
├── Kruskal.cpp
├── Bellman-Ford.cpp
├── Kosaraju.cpp
├── Max Independent Set of a Tree.cpp
├── Dijkstra.cpp
├── Edmonds–Karp (Maxflow).cpp
├── LCA.cpp
├── Eulerian Path-Cycle (Directed Graphs).cpp
├── Eulerian Path-Cycle (Undirected Graphs).cpp
└── A Star.cpp
├── NP-complete & SAT
├── NP 3-graph coloring to SAT.cpp
├── Solving NP (Approximation Method).cpp
├── Solving NP (Exact Method).cpp
├── NP Hamiltonian Path to SAT.cpp
└── Solving NP (Special Cases Method).cpp
├── Linear Programming
├── Gaussian Elimination.cpp
└── Simplex Method.cpp
├── Sparse Table (min or max range query).cpp
├── String Algorithms
├── KMP (Knuth-Morris-Pratt).cpp
├── Rabin-Karp's Algorithm.cpp
├── Modified Rabin-Karp's Algorithm.cpp
└── Burrows-Wheeler for Pattern Matching.cpp
├── Max 2D Range Sum.cpp
├── Six Basic Data Structures
├── Stack.cpp
├── Set.cpp
├── Queue.cpp
├── Map.cpp
├── Priority Queue (Heap).cpp
└── Linked List.cpp
├── Trie.cpp
├── Suffix Tree.cpp
├── Bisection method for finding polynomial equation roots.cpp
└── AVL Tree.cpp
/README.md:
--------------------------------------------------------------------------------
1 | # Interesting-Algorithms-and-Data-Structures
2 | My own implementation codes for some interesting algorithm and data structures.
3 | Most of them are inspired from my completion for data structures and algorithms specialization from university of California San Diego via Coursera.
4 | Certificate link: https://www.coursera.org/verify/specialization/M5PVBWPZ6RYC
5 | Specialization link: https://www.coursera.org/specializations/data-structures-algorithms
6 |
--------------------------------------------------------------------------------
/Sorting Algorithms/Bubble Sort.cpp:
--------------------------------------------------------------------------------
1 | /// Ahmed Nasser Mohamed
2 | /// 09/07/2020
3 |
4 | /*
5 | --Problem description : sort a given sequence of N elements.
6 | --Solution : 1- Iterate over two nested loops
7 | 2- swap two elements if they are not in order
8 | --Time complexity : O(N^2)
9 | */
10 |
11 | #include
12 | using namespace std;
13 |
14 | void bubbleSort(vector&arr){
15 | for(int i=0; iarr[j+1])
18 | swap(arr[j],arr[j+1]);
19 | }
20 |
21 | int main(){
22 | int n;
23 | cin>>n;
24 | vectorarr(n);
25 | for(int& x : arr) cin>>x;
26 | bubbleSort(arr);
27 | for(int x : arr) cout<
12 | using namespace std;
13 |
14 | void selectionSort(vector&arr){
15 | for(int i=0; iarr[j])
18 | swap(arr[i],arr[j]);
19 | }
20 |
21 | int main(){
22 | int n;
23 | cin>>n;
24 | vectorarr(n);
25 | for(int& x : arr) cin>>x;
26 | selectionSort(arr);
27 | for(int x : arr) cout<
12 | using namespace std;
13 |
14 | void insertionSort(vector&arr){
15 | for(int i=1; i=0 && arr[j]>cur){
19 | arr[j+1]=arr[j];
20 | j--;
21 | }
22 | arr[j+1]=cur;
23 | }
24 | }
25 |
26 | int main(){
27 | int n;
28 | cin>>n;
29 | vectorarr(n);
30 | for(int& x : arr) cin>>x;
31 | insertionSort(arr);
32 | for(int x : arr) cout<
14 | using namespace std;
15 |
16 | int const N=1e2+5, M=4e4+5, OO = 0x3f3f3f3f;
17 |
18 | int n,a,sum,ans;
19 |
20 | int main()
21 | {
22 | // freopen("input.txt","rt",stdin);
23 | // freopen("output.txt","wt",stdout);
24 | sum=ans=0;
25 | scanf("%d",&n);
26 | for(int i=0; i
11 | using namespace std;
12 |
13 | struct Node{
14 | bool vis=0;
15 | vectorneighbours={};
16 | };
17 |
18 | void DFS(Node* node){
19 | // pre-order (befor DFS call)
20 |
21 | node->vis=1;
22 | for(auto& neighbour : node->neighbours)
23 | if(neighbour->vis==0)
24 | DFS(neighbour);
25 |
26 | // post-order (after DFS calls)
27 | }
28 |
29 |
30 | int main(){
31 | int n,m;
32 | cin>>n>>m;
33 | vectornodes(n);
34 | for(auto& node : nodes) node=new Node;
35 | while(m--){
36 | int u,v;
37 | cin>>u>>v;
38 | u--,v--;
39 | nodes[u]->neighbours.push_back(nodes[v]);
40 | nodes[v]->neighbours.push_back(nodes[u]);
41 | }
42 | DFS(nodes[0]);
43 | return 0;
44 | }
45 |
--------------------------------------------------------------------------------
/Sorting Algorithms/Radix Sort.cpp:
--------------------------------------------------------------------------------
1 | /// Ahmed Nasser Mohamed
2 | /// 12/12/2021
3 |
4 | /*
5 | --Problem description : sort a given sequence of N elements.
6 | --Solution : 1- Iterate over the digits from first digit to last digit
7 | 2- For each digit, sort the numbers using count sort
8 | --Time complexity : O(N*D) where N is the number of element, and D is the maximum digit
9 | */
10 |
11 | #include
12 | using namespace std;
13 |
14 | void countSort(vector&arr, int place){
15 | vector freq[10];
16 | for(auto val : arr){
17 | int digit=(val/place) %10;
18 | freq[digit].push_back(val);
19 | }
20 | int i=0;
21 | for(auto dv : freq)
22 | for(auto val : dv)
23 | arr[i++]=val;
24 | }
25 |
26 | void radixSort(vector& arr){
27 | int mx=*max_element(arr.begin(), arr.end());
28 | for(int place=1; mx/place>0; place*=10)
29 | countSort(arr,place);
30 | }
31 |
32 | int main(){
33 | int n;
34 | cin>>n;
35 | vectorarr(n);
36 | for(int &x : arr) cin>>x;
37 | radixSort(arr);
38 | for(int x : arr) cout<
14 | using namespace std;
15 |
16 | void countSort(vector& arr){
17 | int shift=0;
18 | int mn=*min_element(arr.begin(), arr.end());
19 | if(mn<0) shift=-mn;
20 | for(int &x : arr) x+=shift;
21 |
22 | int mx=*max_element(arr.begin(), arr.end());
23 | vectorfreq(mx+1,0);
24 | for(int x : arr) freq[x]++;
25 |
26 | int i=0;
27 | for(int val=0; val<=mx; val++)
28 | while(freq[val]--)
29 | arr[i++]=val-shift;
30 | }
31 |
32 | int main(){
33 | int n;
34 | cin>>n;
35 | vectorarr(n);
36 | for(int &x : arr) cin>>x;
37 | countSort(arr);
38 | for(int x : arr) cout<
11 | using namespace std;
12 |
13 | const int INF=0x3f3f3f3f;
14 |
15 | struct Edge{
16 | int weight=INF;
17 | };
18 |
19 |
20 | void Floyed(vector>& edgeMatrix){
21 | for(int k=0; k>n>>m;
30 | vector>edgeMatrix(n, vector(n));
31 | for(int i=0; i>u>>v>>c;
35 | u--,v--;
36 | edgeMatrix[u][v].weight=edgeMatrix[v][u].weight=min(edgeMatrix[u][v].weight, c);
37 | }
38 | Floyed(edgeMatrix);
39 |
40 | return 0;
41 | }
42 |
--------------------------------------------------------------------------------
/Sorting Algorithms/Merge Sort.cpp:
--------------------------------------------------------------------------------
1 | /// Ahmed Nasser Mohamed
2 | /// 09/07/2020
3 |
4 | /*
5 | --Problem description : sort a given sequence of N elements.
6 | --Solution : 1- Use divide and conquer technique
7 | 2- divide a sequence into two small sequences
8 | 3- merge the two small sequences in a sorted way
9 | --Time complexity : O(N*log(N))
10 | */
11 |
12 | #include
13 | using namespace std;
14 |
15 | void merge(int l, int md, int r, vector& arr){
16 | vectorL,R;
17 | for(int i=l; i<=md; i++) L.push_back(arr[i]);
18 | for(int i=md+1; i<=r; i++) R.push_back(arr[i]);
19 | L.push_back(INT_MAX);
20 | R.push_back(INT_MAX);
21 | int lp=0, rp=0;
22 | for(int i=l; i<=r; i++){
23 | if(L[lp]<=R[rp]) arr[i]=L[lp++];
24 | else arr[i]=R[rp++];
25 | }
26 | }
27 |
28 | void mergeSort(int l, int r, vector& arr){
29 | if(l>=r) return;
30 | int md=(l+r)/2;
31 | mergeSort(l,md,arr);
32 | mergeSort(md+1,r,arr);
33 | merge(l,md,r,arr);
34 | }
35 |
36 | int main(){
37 | int n;
38 | cin>>n;
39 | vectorarr(n);
40 | for(int &x : arr) cin>>x;
41 | mergeSort(0,n-1,arr);
42 | for(int x : arr) cout<
11 | using namespace std;
12 |
13 | struct Node{
14 | bool vis=0;
15 | vectorneighbours=vector();
16 | };
17 |
18 |
19 | void BFS(Node* src){
20 | queueq;
21 | src->vis=1;
22 | q.push(src);
23 | while(!q.empty()){
24 | Node* node=q.front();
25 | q.pop();
26 | for(auto& neighbour : node->neighbours){
27 | if(neighbour->vis==0){
28 | neighbour->vis=1;
29 | q.push(neighbour);
30 | }
31 | }
32 | }
33 | }
34 |
35 |
36 |
37 | int main(){
38 | int n,m;
39 | cin>>n>>m;
40 | vectornodes(n);
41 | for(auto& node : nodes) node=new Node;
42 | while(m--){
43 | int u,v;
44 | cin>>u>>v;
45 | u--,v--;
46 | nodes[u]->neighbours.push_back(nodes[v]);
47 | nodes[v]->neighbours.push_back(nodes[u]);
48 | }
49 | BFS(nodes[0]);
50 |
51 | return 0;
52 | }
53 |
--------------------------------------------------------------------------------
/Sorting Algorithms/Heap Sort.cpp:
--------------------------------------------------------------------------------
1 | /// Ahmed Nasser Mohamed
2 | /// 29/07/2020
3 |
4 | /*
5 | --Problem description : sort a given sequence of N elements.
6 | --Solution : 1- Convert the given sequence into max heap using sift-down technique
7 | 2- iterating n times
8 | 3- for each iteration, take the root of the heap (max element so far) and remove it from the heap
9 | --Time complexity : O(N*log(N))
10 | */
11 |
12 | #include
13 | using namespace std;
14 |
15 | void siftDown(int i, int heapSz, vector& arr){
16 | int mxi=i;
17 | int l=2*(i+1)-1;
18 | if(larr[mxi]) mxi=l;
19 | int r=2*(i+1);
20 | if(rarr[mxi]) mxi=r;
21 | if(mxi!=i){
22 | swap(arr[i],arr[mxi]);
23 | siftDown(mxi,heapSz,arr);
24 | }
25 | }
26 |
27 | void heapSort(vector& arr){
28 | // Buliding Heap
29 | int heapSz=arr.size();
30 | for(int i=arr.size()/2-1; i>=0; i--)
31 | siftDown(i,heapSz,arr);
32 |
33 | // Sort by poping the max each time
34 | for(int i=0; i>n;
43 | vectorarr(n);
44 | for(int &x : arr) cin>>x;
45 | heapSort(arr);
46 | for(int x : arr) cout< first SAT condition
7 | 2- each edge must have different colored two nodes ---> second SAT condition
8 | --Time complexity : O(n)
9 | */
10 |
11 | #include
12 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
13 | using namespace std;
14 | typedef long long ll;
15 |
16 | int const N=1e5+5, M=300+5, MOD=1e9+7, OO=0x3f3f3f3f;
17 | double const EPS=1e-11;
18 |
19 |
20 | int n,m,c,var,u,v;
21 |
22 | int main()
23 | {
24 | // FIO
25 | // freopen("input.txt","rt",stdin);
26 | // freopen("output.txt","wt",stdout);
27 | scanf("%d %d",&n, &m);
28 | var=3*n;
29 | c=4*n + 3*m;
30 | printf("%d %d\n",c,var);
31 | for(int i=0, j=0; i
12 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
13 | using namespace std;
14 | typedef long long ll;
15 |
16 | int const N=20+5, M=200+5, MOD=1e9+7, OO=0x3f3f3f3f;
17 |
18 | int n;
19 | double arr[N][N],ans[N];
20 |
21 |
22 | int main()
23 | {
24 | FIO
25 | // freopen("input.txt","rt",stdin);
26 | // freopen("output.txt","wt",stdout);
27 | cin>>n;
28 | for(int i=0; i>arr[i][j];
31 | for(int i=0; i=0; i--)
46 | {
47 | ans[i]=arr[i][n];
48 | for(int j=i+1; j
11 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
12 | using namespace std;
13 | typedef long long ll;
14 |
15 | int const N=2e5+5, M=17+5, MOD=1e9+7, OO=0x3f3f3f3f;
16 |
17 | int n,q,a,b;
18 | int arr[N];
19 | int table[N][M];
20 |
21 | int Log(int x)
22 | {
23 | return 32-__builtin_clz(x)-1;
24 | }
25 |
26 | void bulidTable()
27 | {
28 | for(int i=0; i
16 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
17 | using namespace std;
18 | typedef long long ll;
19 |
20 | int const N=1e5+5, M=300+5, MOD=1e9+7, OO=0x3f3f3f3f;
21 | double const EPS=1e-11;
22 |
23 | int n,m,u,v;
24 | unordered_setst;
25 | vector>edge;
26 |
27 |
28 | int main()
29 | {
30 | // FIO
31 | // freopen("input.txt","rt",stdin);
32 | // freopen("output.txt","wt",stdout);
33 | scanf("%d %d",&n, &ma);
34 | for(int i=0; i
12 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
13 | using namespace std;
14 | typedef long long ll;
15 |
16 | int const N=1e5+5, M=1e6+5, MOD=1e9+7, OO=0x3f3f3f3f;
17 |
18 |
19 | int n,m,u,v,w,ans;
20 | bool vis[N];
21 | vector>adj[N];
22 |
23 | void prim()
24 | {
25 | int u,v,c;
26 | priority_queue, vector>, greater>>q;
27 | q.push({0,1});
28 | while(!q.empty())
29 | {
30 | u=q.top().second;
31 | c=q.top().first;
32 | q.pop();
33 | if(vis[u])
34 | continue;
35 | ans+=c;
36 | vis[u]=1;
37 | for(pair p : adj[u])
38 | {
39 | v=p.first;
40 | c=p.second;
41 | if(!vis[v])
42 | q.push({c,v});
43 | }
44 |
45 | }
46 | }
47 |
48 |
49 |
50 |
51 | int main()
52 | {
53 | // FIO
54 | // freopen("input.txt","rt",stdin);
55 | // freopen("output.txt","wt",stdout);
56 | scanf("%d %d",&n, &m);
57 | for(int i=0; i
13 | using namespace std;
14 |
15 | int const N=1e5+5, M=1e5+5, OO = 0x3f3f3f3f, MOD=1e9+7;
16 |
17 | #define cost first
18 | #define from second.first
19 | #define to second.second
20 |
21 |
22 | int n,m,c,u,v;
23 | pair> edges[M];
24 | int par[N];
25 |
26 | int findParent(int u)
27 | {
28 | if(par[u]==u)
29 | return u;
30 | return par[u]=findParent(par[u]);
31 |
32 | }
33 |
34 | void join(int a, int b)
35 | {
36 | a=findParent(a);
37 | b=findParent(b);
38 | if(a!=b)
39 | par[b]=a;
40 | }
41 |
42 |
43 |
44 | int kruskal()
45 | {
46 | int ret=0;
47 | iota(par,par+n+1,0);
48 | sort(edges,edges+m);
49 | for(int i=0; i
13 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
14 | using namespace std;
15 | typedef long long ll;
16 |
17 | int const N=2e5+5, M=200+5, MOD=1e9+7, OO=0x3f3f3f3f;
18 |
19 |
20 | int n,m;
21 | string s,p;
22 | vectorprefix,ans;
23 |
24 | void buildPrefix()
25 | {
26 | prefix=vector(n);
27 | int border=0;
28 | prefix[0]=0;
29 | for(int i=1; i0 && s[i]!=s[border])
32 | border=prefix[border-1];
33 | if(s[i]==s[border])
34 | border++;
35 | else
36 | border=0;
37 | prefix[i]=border;
38 | }
39 | }
40 |
41 |
42 | int main()
43 | {
44 | FIO
45 | // freopen("input.txt","rt",stdin);
46 | // freopen("output.txt","wt",stdout);
47 | cin>>s>>p;
48 | s=p+'$'+s;
49 | n=s.size();
50 | m=p.size();
51 | buildPrefix();
52 | for(int i=m+1; i
11 | using namespace std;
12 |
13 | const int MAX=1e3+1, MAX_DIS=2e6+1;
14 |
15 | struct Node{
16 | int distance=MAX_DIS;
17 | };
18 |
19 | struct Edge{
20 | Node* fromNode=NULL;
21 | Node* toNode=NULL;
22 | int weight=MAX;
23 | Edge(Node* _fromNode, Node* _toNode, int _weight) : fromNode(_fromNode), toNode(_toNode), weight(_weight) {}
24 | };
25 |
26 |
27 | bool Bellman(vector& edges, Node* src, int n){
28 | bool hasNegCycle=0;
29 | src->distance=0;
30 | for(int i=1; i<=n; i++){
31 | bool isUpdated=0;
32 | for(auto& edge : edges){
33 | if(edge.toNode->distance > edge.fromNode->distance + edge.weight){
34 | edge.toNode->distance = edge.fromNode->distance + edge.weight;
35 | isUpdated=1;
36 | }
37 | }
38 | if(isUpdated==0) break;
39 | else if(i==n) hasNegCycle=1;
40 | }
41 | return hasNegCycle;
42 | }
43 |
44 | int main(){
45 | int n,m,src;
46 | cin>>n>>m>>src;
47 | src--;
48 | vectornodes(n);
49 | for(auto& node : nodes) node=new Node;
50 | vectoredges;
51 | while(m--){
52 | int u,v,c;
53 | cin>>u>>v>>c;
54 | u--,v--;
55 | edges.push_back(Edge(nodes[u], nodes[v], c));
56 | }
57 |
58 | bool hasNegCycle=Bellman(edges, nodes[src], n);
59 | if(hasNegCycle) cout<<"There is a negative cycle\n";
60 | else cout<<"There is no negative cycle\n";
61 |
62 | return 0;
63 | }
64 |
--------------------------------------------------------------------------------
/Graph Algorithms/Kosaraju.cpp:
--------------------------------------------------------------------------------
1 | /// Ahmed Nasser Mohamed
2 | /// 10/08/2020
3 |
4 | /*
5 | --Problem description : find the strongly connected components in a directed graph
6 | --Solution : 1- DFS to find the sort the nodes with maximum post-order number
7 | 2- Another DFS to visit the nodes
8 | --Time complexity : O(V+E)
9 | */
10 |
11 | #include
12 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
13 | using namespace std;
14 | typedef long long ll;
15 |
16 | int const N=5e5+5, M=1e5, MOD=1e9+7, OO=0x3f3f3f3f;
17 |
18 | int n,m,u,v;
19 | vectoradj[N],adjT[N];
20 | vector vis;
21 | stackpost;
22 |
23 |
24 | void DFS1(int u)
25 | {
26 | vis[u]=1;
27 | for(int v : adjT[u])
28 | if(!vis[v])
29 | DFS1(v);
30 | post.push(u);
31 | }
32 |
33 | void DFS2(int u)
34 | {
35 | vis[u]=1;
36 | printf("%d ",u);
37 | for(int v : adj[u])
38 | if(!vis[v])
39 | DFS2(v);
40 | }
41 |
42 |
43 | void kosaraju()
44 | {
45 | vis=vector(n+1,0);
46 | for(int i=1; i<=n; i++)
47 | if(!vis[i])
48 | DFS1(i);
49 | vis=vector(n+1,0);
50 | while(!post.empty())
51 | {
52 | int i=post.top();
53 | post.pop();
54 | if(!vis[i])
55 | {
56 | DFS2(i);
57 | puts("");
58 | }
59 | }
60 | }
61 |
62 |
63 | int main()
64 | {
65 | // FIO
66 | // freopen("input.txt","rt",stdin);
67 | // freopen("output.txt","wt",stdout);
68 | scanf("%d %d",&n, &m);
69 | for(int i=0; i
13 | using namespace std;
14 |
15 | int const N=16+5, M=(1<>nxt)&1)
39 | continue;
40 | ret=min(ret,mat[cur][nxt]+solve(nxt,mask|(1<
13 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
14 | using namespace std;
15 | typedef long long ll;
16 |
17 | int const N=1e5+5, M=300+5, MOD=1e9+7, OO=0x3f3f3f3f;
18 | double const EPS=1e-11;
19 |
20 | int n,m,u,v;
21 | int par[N],deg[N];
22 | vectoradj[N];
23 | vectortake;
24 | queueq;
25 | vectorans;
26 |
27 |
28 | void DFS(int u, int pr)
29 | {
30 | par[u]=pr;
31 | for(int v : adj[u])
32 | if(v!=pr)
33 | DFS(v,u);
34 | }
35 |
36 | int main()
37 | {
38 | // FIO
39 | // freopen("input.txt","rt",stdin);
40 | // freopen("output.txt","wt",stdout);
41 | scanf("%d %d",&n, &m);
42 | for(int i=0; i(n,1);
51 | for(int i=0; i
13 | using namespace std;
14 |
15 | int const N=1e2+5, M=4e4+5, OO = 0x3f3f3f3f;
16 |
17 | int n,m,mx=-OO,ans=-OO,sum,u,d,ansl,ansr,ansu,ansd,tu;
18 | int arr[N][N];
19 |
20 | int main()
21 | {
22 | // freopen("input.txt","rt",stdin);
23 | // freopen("output.txt","wt",stdout);
24 | scanf("%d %d",&n, &m);
25 | for(int i=1; i<=n; i++)
26 | for(int j=1; j<=m; j++)
27 | {
28 | scanf("%d",&arr[i][j]);
29 | arr[i][j]+=arr[i][j-1];
30 | }
31 | for(int l=1; l<=m; l++)
32 | {
33 | for(int r=l; r<=m; r++)
34 | {
35 | mx=-OO;
36 | sum=u=d=tu=0;
37 | for(int k=1; k<=n; k++)
38 | {
39 | sum+=arr[k][r]-arr[k][l-1];
40 | if(sum>mx)
41 | {
42 | mx=sum;
43 | u=tu;
44 | d=k;
45 | }
46 | if(sum<0)
47 | {
48 | sum=0;
49 | tu=k+1;
50 | }
51 | }
52 | if(mx>ans)
53 | {
54 | ans=mx;
55 | ansl=l;
56 | ansr=r;
57 | ansu=u;
58 | ansd=d;
59 | }
60 | }
61 | }
62 | printf("Max sum is: %d\nleft: %d right: %d top: %d bottom: %d\n",ans,ansl,ansr,ansu,ansd);
63 |
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/Sorting Algorithms/Quick Sort.cpp:
--------------------------------------------------------------------------------
1 | /// Ahmed Nasser Mohamed
2 | /// 13/07/2020
3 |
4 | /*
5 | --Problem description : sort a given sequence of N elements.
6 | --Solution : 1- recursively, choose an element as a pivot
7 | 2- insert the pivot in its right position
8 | 3- repeat the same two steps for the right and the left partitions for the pivot
9 | --Time complexity : O(N*log(N))
10 | */
11 |
12 | #include
13 | using namespace std;
14 |
15 | /*
16 | int random(int mn, int mx){
17 | static bool first=true;
18 | if(first){
19 | srand(time(NULL));
20 | first=false;
21 | }
22 | return mn+rand()%((mx+1)-mn);
23 | }
24 | */
25 |
26 | pairpartition(int l, int r, vector& arr){
27 | int m1=l-1, m2=l;
28 | for(int i=l+1; i<=r; i++){
29 | if(arr[i]& arr){
40 | if(l>=r) return;
41 |
42 | /*
43 | // Randomized Pivot
44 | int randomI=random(l,r);
45 | swap(arr[randomI],arr[l]);
46 | */
47 |
48 | /*
49 | // Median Pivot
50 | int md=(l+r)/2;
51 | if((arr[r]>=arr[md] && arr[r]<=arr[l]) || (arr[r]>=arr[l] && arr[r]<=arr[md]))
52 | swap(arr[r],arr[l]);
53 | else if((arr[md]>=arr[l] && arr[md]<=arr[r]) || (arr[md]>=arr[r] && arr[md]<=arr[l]))
54 | swap(arr[md],arr[l]);
55 | */
56 |
57 | // First Pivot
58 | pairm1m2=partition(l,r,arr);
59 | quickSort(l,m1m2.first-1,arr);
60 | quickSort(m1m2.second+1,r,arr);
61 | }
62 |
63 |
64 | int main(){
65 | int n;
66 | cin>>n;
67 | vectorarr(n);
68 | for(int &x : arr) cin>>x;
69 | quickSort(0,n-1,arr);
70 | for(int x : arr) cout<
11 | using namespace std;
12 |
13 | const int MAX=1e8+1;
14 |
15 | struct Node;
16 | struct Edge;
17 |
18 | struct Node{
19 | int distance=MAX;
20 | vectorneighbours={};
21 | };
22 |
23 | struct Edge{
24 | int weight=0;
25 | Node* toNode=NULL;
26 | Edge(int _weight, Node* _toNode) : weight(_weight), toNode(_toNode) {}
27 | bool operator >(const Edge & e2) const{
28 | return weight > e2.weight;
29 | }
30 | };
31 |
32 |
33 | void Dijkstra(Node* src){
34 | priority_queue, greater>q;
35 | src->distance=0;
36 | q.push(Edge(src->distance,src));
37 | while(!q.empty()){
38 | Edge tp=q.top();
39 | q.pop();
40 |
41 | int soFarWeight=tp.weight;
42 | Node* node=tp.toNode;
43 | if(soFarWeight != node->distance) continue;
44 |
45 | for(auto& edge : node->neighbours){
46 | int weight=edge.weight;
47 | Node* neighbour=edge.toNode;
48 | if(neighbour->distance > soFarWeight+weight){
49 | neighbour->distance=soFarWeight+weight;
50 | q.push(Edge(neighbour->distance, neighbour));
51 | }
52 | }
53 | }
54 | }
55 |
56 |
57 | int main(){
58 | int n,m,src;
59 | cin>>n>>m>>src;
60 | src--;
61 | vector nodes(n);
62 | for(auto& node : nodes) node=new Node;
63 | while(m--){
64 | int u,v,c;
65 | cin>>u>>v>>c;
66 | u--,v--;
67 | nodes[u]->neighbours.push_back(Edge(c,nodes[v]));
68 | nodes[v]->neighbours.push_back(Edge(c,nodes[u]));
69 | }
70 | Dijkstra(nodes[src]);
71 | for(int i=0; idistance<<'\n';
73 |
74 | return 0;
75 |
76 | }
77 |
--------------------------------------------------------------------------------
/Six Basic Data Structures/Stack.cpp:
--------------------------------------------------------------------------------
1 | /// Ahmed Nasser Mohamed
2 | /// 16/07/2020
3 |
4 | /*
5 | --Description : store elements with LIFO method (Last In First Out)
6 | --Operations wiht Time complexity : Push O(1) - Pop O(1)
7 | */
8 |
9 | #include
10 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
11 | using namespace std;
12 | typedef long long ll;
13 |
14 | int const N=5, M=600+5, MOD=1e9+7, OO=0x3f3f3f3f;
15 |
16 | struct node
17 | {
18 | int data;
19 | node *next;
20 | };
21 |
22 |
23 | class Stack
24 | {
25 | private:
26 | node *head;
27 | public:
28 | Stack()
29 | {
30 | head=NULL;
31 | }
32 | void push(int value)
33 | {
34 | node *newNode= new node;
35 | newNode->data=value;
36 | newNode->next=head;
37 | head=newNode;
38 | }
39 | int top()
40 | {
41 | return head->data;
42 | }
43 | bool isEmpy()
44 | {
45 | return head==NULL;
46 | }
47 | void pop()
48 | {
49 | if(head==NULL)
50 | cout<<"EMPTY STACK!\n";
51 | else
52 | head=head->next;
53 | }
54 | };
55 |
56 |
57 |
58 | class Stack2
59 | {
60 | private:
61 | int arr[N],ls;
62 | public:
63 | Stack2()
64 | {
65 | memset(arr, 0, sizeof arr);
66 | ls=-1;
67 | }
68 | void push(int value)
69 | {
70 | if(ls
15 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
16 | using namespace std;
17 | typedef long long ll;
18 |
19 | int const N=1e2+5, M=200+5, MOD=1e9+7, OO=0x3f3f3f3f;
20 |
21 | int n,m,u,v,c,f;
22 | int adj[N][N];
23 |
24 |
25 | int getFlow(int src, int tar)
26 | {
27 | int u;
28 | vectorvis(n+1,0);
29 | vectorpar(n+1);
30 | queueq;
31 | vis[src]=1;
32 | par[src]=-1;
33 | q.push(src);
34 | while(!q.empty())
35 | {
36 | u=q.front();
37 | q.pop();
38 | if(u==tar)
39 | break;
40 | for(int v=1; v<=n; v++)
41 | {
42 | if(adj[u][v] && !vis[v])
43 | {
44 | vis[v]=1;
45 | par[v]=u;
46 | q.push(v);
47 | }
48 | }
49 | }
50 | if(u!=tar)
51 | return 0;
52 | int mn=OO,v=u;
53 | while(par[v]!=-1)
54 | {
55 | mn=min(mn,adj[par[v]][v]);
56 | v=par[v];
57 | }
58 | while(par[u]!=-1)
59 | {
60 | adj[par[u]][u]-=mn;
61 | adj[u][par[u]]+=mn;
62 | u=par[u];
63 | }
64 | return mn;
65 | }
66 |
67 |
68 |
69 | int main()
70 | {
71 | // FIO
72 | // freopen("input.txt","rt",stdin);
73 | // freopen("output.txt","wt",stdout);
74 | scanf("%d %d",&n, &m);
75 | for(int i=0; i
13 | using namespace std;
14 |
15 |
16 | struct Node{
17 | int id=-1;
18 | int depth=-1;
19 | vector neighbours=vector();
20 | vector ancestors=vector();
21 | Node(int _id) : id(_id) {}
22 | };
23 |
24 |
25 | int Log(int x){
26 | return 31-__builtin_clz(x);
27 | }
28 |
29 | void DFS(Node* node, Node* par){
30 | for(auto& neighbour : node->neighbours){
31 | if(neighbour==par) continue;
32 | neighbour->depth=node->depth+1;
33 | neighbour->ancestors.push_back(node);
34 | for(int j=1; (1<depth; j++)
35 | neighbour->ancestors.push_back(neighbour->ancestors[j-1]->ancestors[j-1]);
36 | DFS(neighbour, node);
37 | }
38 | }
39 |
40 | Node* kAnc(Node* node, int k){
41 | k=min(k, node->depth);
42 | for(int j=0; (1<ancestors[j];
45 | return node;
46 | }
47 |
48 | Node* LCA(Node* u, Node* v){
49 | if(u->depth < v->depth) swap(u,v);
50 | int d=u->depth - v->depth;
51 | u=kAnc(u,d);
52 |
53 | if(u==v) return u;
54 |
55 | int m=Log(u->depth);
56 | for(int j=m; j>=0; j--){
57 | if(u->ancestors[j]!=v->ancestors[j]){
58 | u=u->ancestors[j];
59 | v=v->ancestors[j];
60 | }
61 | }
62 | return u->ancestors[0];
63 | }
64 |
65 | int main(){
66 | int n;
67 | cin>>n;
68 | vectornodes(n);
69 | for(int i=0; i>m;
73 | while(m--){
74 | int child;
75 | cin>>child;
76 | node->neighbours.push_back(nodes[child]);
77 | }
78 | }
79 | int root=0;
80 | nodes[root]->depth=0;
81 | DFS(nodes[root], nodes[root]);
82 | int q;
83 | cin>>q;
84 | while(q--){
85 | int u,v;
86 | cin>>u>>v;
87 | cout<id<<'\n';
88 | }
89 |
90 | return 0;
91 | }
92 |
--------------------------------------------------------------------------------
/Graph Algorithms/Eulerian Path-Cycle (Directed Graphs).cpp:
--------------------------------------------------------------------------------
1 | /// Ahmed Nasser Mohamed
2 | /// 27/08/2020
3 |
4 | /*
5 | --Problem description : find Eulerian path or cycle which goes through each edge exactly once
6 | --Solution : 1- calculate the in and the out degrees for each node
7 | 2- if in and out degrees are equal for all nodes, the Eulerian cycle exists
8 | 3- else if exactly one node has (out - in =1) and exactly another node has (in - out =1), the Eulerian path exists
9 | 4- do DFS until you stuck, push the current node to the front of the answer
10 | --Time complexity : O(E)
11 | */
12 |
13 | #include
14 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
15 | using namespace std;
16 | typedef long long ll;
17 |
18 | int const N=1e5+5, M=300+5, MOD=1e9+7, OO=0x3f3f3f3f;
19 | double const EPS=1e-11;
20 |
21 | bool ans=1;
22 | int n,m,u,v,st=-1,en=-1;
23 | int in[N],out[N];
24 | vectoradj[N],res;
25 |
26 |
27 |
28 | void solve(int u)
29 | {
30 | while(out[u]!=0)
31 | {
32 | int v=adj[u][--out[u]];
33 | solve(v);
34 | }
35 | res.push_back(u);
36 | }
37 |
38 |
39 | int main()
40 | {
41 | // FIO
42 | // freopen("input.txt","rt",stdin);
43 | // freopen("output.txt","wt",stdout);
44 | scanf("%d %d",&n, &m);
45 | for(int i=0; i1)
55 | ans=0;
56 | else if(out[i]-in[i]==1)
57 | {
58 | if(st==-1)st=i;
59 | else
60 | ans=0;
61 | }
62 | else if(in[i]-out[i]==1)
63 | {
64 | if(en==-1)en=i;
65 | else ans=0;
66 | }
67 | }
68 | if(!(ans && ((st==-1 && en==-1)||(st!=-1 && en!=-1))))
69 | {
70 | puts("NO Eulerian Path/Cycle");
71 | return 0;
72 | }
73 | if(st==-1)
74 | for(int i=1; i<=n && st==-1; i++)
75 | if(out[i]>0)
76 | st=i;
77 | solve(st);
78 | if((int)res.size()==m+1)
79 | {
80 | for(int i=m; i>=0; i--)
81 | printf("%d ",res[i]);
82 | puts("");
83 | }
84 | else
85 | puts("NO Eulerian Path/Cycle");
86 |
87 | return 0;
88 | }
89 |
--------------------------------------------------------------------------------
/String Algorithms/Rabin-Karp's Algorithm.cpp:
--------------------------------------------------------------------------------
1 | /// Ahmed Nasser Mohamed
2 | /// 06/08/2020
3 |
4 | /*
5 | --Problem description : find all occurrences of string T in string S.
6 | --Solution : 1- Hash all sub-strings in S of length |T| using polynomial hash function
7 | 2- Hash T with the same hash function
8 | 3- Compare the hash values of all sub-strings in S of length |T| with the hash value of T
9 | 4- If the hash values are not the same, so they are definitely not the same strings
10 | 5- Else, there may be a collusion, so compare the two strings character by character to see if they are the same or not
11 | --Time complexity : O(|S| + q*|T|) where q is the number of times for T occurrence in S
12 | */
13 |
14 | #include
15 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
16 | using namespace std;
17 | typedef long long ll;
18 |
19 | int const N=5e5+5, M=1e5, MOD=1e9+7, OO=0x3f3f3f3f;
20 |
21 |
22 | string s,t;
23 | int n,m;
24 | ll x,p,tHash,Hash[N];
25 | vectorans;
26 |
27 |
28 | ll random(ll mn, ll mx)
29 | {
30 | static bool first=true;
31 | if(first)
32 | {
33 | srand(time(NULL));
34 | first=false;
35 | }
36 | return mn+rand()%((mx+1)-mn);
37 | }
38 |
39 | ll modPower(ll a, ll b, ll m)
40 | {
41 | if(!b)
42 | return 1;
43 | ll t= (modPower(a, b>>1,m))%m;
44 | return ((t*t)%m*((b&1) ? a : 1)%m)%m;
45 | }
46 |
47 |
48 | ll polyHash(string a)
49 | {
50 | int sz=a.size();
51 | ll ret=0;
52 | for(int i=sz-1; i>=0; i--)
53 | ret=(ret*x+a[i])%p;
54 | return ret;
55 | }
56 |
57 |
58 | void buildHash()
59 | {
60 | Hash[n-m]=polyHash(s.substr(n-m));
61 | ll y=modPower(x,m,p);
62 | for(int i=n-m-1; i>=0; i--)
63 | Hash[i]=(((x*Hash[i+1]+s[i]-y*s[i+m])%p)+p)%p;
64 | }
65 |
66 |
67 | int main()
68 | {
69 | FIO
70 | // freopen("input.txt","rt",stdin);
71 | // freopen("output.txt","wt",stdout);
72 | cin>>s>>t;
73 | n=s.size();
74 | m=t.size();
75 | p=1e9+7;
76 | x=random(1,p-1);
77 | tHash=polyHash(t);
78 | buildHash();
79 | for(int i=0; i<=n-m; i++)
80 | {
81 | if(Hash[i]!=tHash)
82 | continue;
83 | if(t==s.substr(i,m))
84 | ans.push_back(i);
85 | }
86 | for(int i : ans)
87 | cout<
14 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
15 | using namespace std;
16 | typedef long long ll;
17 |
18 | int const N=1e5+5, M=300+5, MOD=1e9+7, OO=0x3f3f3f3f;
19 | double const EPS=1e-11;
20 |
21 | bool ans=1;
22 | int n,m,u,v,st=-1,en=-1;
23 | int deg[N];
24 | vector>adj[N];
25 | vectorres;
26 |
27 |
28 | void solve(int u)
29 | {
30 | while(deg[u]!=0)
31 | {
32 | while(adj[u].back().second==-1)
33 | adj[u].pop_back();
34 | pair p=adj[u].back();
35 | adj[u].pop_back();
36 | deg[u]--;
37 | adj[p.first][p.second].second=-1;
38 | deg[p.first]--;
39 | solve(p.first);
40 | }
41 | res.push_back(u);
42 | }
43 |
44 |
45 | int main()
46 | {
47 | // FIO
48 | // freopen("input.txt","rt",stdin);
49 | // freopen("output.txt","wt",stdout);
50 | scanf("%d %d",&n, &m);
51 | for(int i=0; i0)
79 | st=i;
80 | solve(st);
81 | if((int)res.size()==m+1)
82 | {
83 | for(int i=m; i>=0; i--)
84 | printf("%d ",res[i]);
85 | puts("");
86 | }
87 | else
88 | puts("NO Eulerian Path/Cycle");
89 |
90 | return 0;
91 | }
92 |
--------------------------------------------------------------------------------
/Six Basic Data Structures/Set.cpp:
--------------------------------------------------------------------------------
1 | /// Ahmed Nasser Mohamed
2 | /// 5/08/2020
3 |
4 | /*
5 | --Description : store elements in a hash table
6 | --Operations wiht Time complexity : Find O(1) - Remove O(1) - Add O(1)
7 | */
8 |
9 | #include
10 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
11 | using namespace std;
12 | typedef long long ll;
13 |
14 | int const N=10, M=1000, MOD=1e9+7, OO=0x3f3f3f3f;
15 |
16 | int const maxVal=2e5;
17 |
18 |
19 | class Set
20 | {
21 | private:
22 | listarr[M];
23 | int p,a,b;
24 | bool isPrime(ll n)
25 | {
26 | for(ll i=2; i*i<=n; i++)
27 | if(n%i==0)
28 | return 0;
29 | return 1;
30 | }
31 | int random(int mn, int mx)
32 | {
33 | static bool first=true;
34 | if(first)
35 | {
36 | srand(time(NULL));
37 | first=false;
38 | }
39 | return mn+rand()%((mx+1)-mn);
40 | }
41 | int Hash(int x)
42 | {
43 | return ((a*x+b)%p)%M;
44 | }
45 | public:
46 | Set()
47 | {
48 | p=-1;
49 | for(int i=maxVal+1; p==-1; i++)
50 | if(isPrime(i))
51 | p=i;
52 | a=random(1,p-1);
53 | b=random(0,p-1);
54 | }
55 | bool Find(int x)
56 | {
57 | int ind=Hash(x);
58 | for(list::iterator it=arr[ind].begin(); it != arr[ind].end(); ++it)
59 | if(*it==x)
60 | return 1;
61 | return 0;
62 | }
63 | void Remove(int x)
64 | {
65 | int ind=Hash(x);
66 | for(list::iterator it=arr[ind].begin(); it != arr[ind].end(); ++it)
67 | {
68 | if(*it==x)
69 | {
70 | arr[ind].erase(it);
71 | return;
72 | }
73 | }
74 | }
75 | void Add(int x)
76 | {
77 | int ind=Hash(x);
78 | for(list::iterator it=arr[ind].begin(); it != arr[ind].end(); ++it)
79 | if(*it==x)
80 | return;
81 | arr[ind].push_back(x);
82 | }
83 |
84 | };
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 | int main()
93 | {
94 | // FIO
95 | // freopen("input.txt","rt",stdin);
96 | // freopen("output.txt","wt",stdout);
97 |
98 | return 0;
99 | }
100 |
--------------------------------------------------------------------------------
/Graph Algorithms/A Star.cpp:
--------------------------------------------------------------------------------
1 | // Ahmed Nasser Mohamed
2 |
3 | /*
4 | --Problem description : find the shortest paths form a node to a target node
5 | --Solution : 1- use a priority queue to pick the minimum weight each time
6 | 2- use heuristic function like (Euclidean distance) to choose the right direction
7 | 3- relax the reached nodes with minimum
8 | 4- stop when reaching the target node
9 | --Time complexity : O((V+E)*log(V))
10 | */
11 |
12 | #include
13 | using namespace std;
14 |
15 | const int MAX=1e8+1;
16 |
17 | struct Node;
18 | struct Edge;
19 |
20 | struct Node{
21 | int x=0;
22 | int y=0;
23 | int distance=MAX;
24 | vectorneighbours={};
25 | Node(int _x, int _y) : x(_x), y(_y) {}
26 | };
27 |
28 | struct Edge{
29 | double euclidean=0;
30 | int weight=0;
31 | Node* toNode=NULL;
32 | Edge(double _euclidean, int _weight, Node* _toNode) : euclidean(_euclidean), weight(_weight), toNode(_toNode) {}
33 | bool operator >(const Edge & e2) const{
34 | if(euclidean != e2.euclidean) return euclidean > e2.euclidean;
35 | return weight > e2.weight;
36 | }
37 | };
38 |
39 | double Euclidean(Node* a, Node* b){
40 | return hypot(a->x - b->x, a->y - b->y);
41 | }
42 |
43 | int AStar(Node* src, Node* tar){
44 | priority_queue, greater>q;
45 | src->distance=0;
46 | q.push(Edge(Euclidean(src,tar),src->distance,src));
47 | while(!q.empty()){
48 | Edge tp=q.top();
49 | q.pop();
50 |
51 | int soFarWeight=tp.weight;
52 | Node* node=tp.toNode;
53 | if(node==tar) break;
54 | if(soFarWeight != node->distance) continue;
55 |
56 | for(auto& edge : node->neighbours){
57 | int weight=edge.weight;
58 | Node* neighbour=edge.toNode;
59 | if(neighbour->distance > soFarWeight+weight){
60 | neighbour->distance=soFarWeight+weight;
61 | q.push(Edge(Euclidean(neighbour,tar), neighbour->distance, neighbour));
62 | }
63 | }
64 | }
65 | return tar->distance;
66 | }
67 |
68 |
69 | int main(){
70 | int n,m,src,tar;
71 | cin>>n>>m>>src>>tar;
72 | src--,tar--;
73 | vector nodes(n);
74 | for(auto& node : nodes){
75 | int x,y;
76 | cin>>x>>y;
77 | node=new Node(x,y);
78 | }
79 | while(m--){
80 | int u,v,c;
81 | cin>>u>>v>>c;
82 | u--,v--;
83 | double euclidean=Euclidean(nodes[u],nodes[v]);
84 | nodes[u]->neighbours.push_back(Edge(euclidean,c,nodes[v]));
85 | nodes[v]->neighbours.push_back(Edge(euclidean,c,nodes[u]));
86 | }
87 | int ans=AStar(nodes[src],nodes[tar]);
88 | cout<
10 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
11 | using namespace std;
12 | typedef long long ll;
13 |
14 | int const N=5, M=600+5, MOD=1e9+7, OO=0x3f3f3f3f;
15 |
16 | struct node
17 | {
18 | int data;
19 | node *next;
20 | };
21 |
22 | class Queue
23 | {
24 | private:
25 | node *head, *tail;
26 | public:
27 | Queue()
28 | {
29 | head=tail=NULL;
30 | }
31 | void enqueue(int value)
32 | {
33 | node *newNode=new node;
34 | newNode->data=value;
35 | if(head==NULL)
36 | head=tail=newNode;
37 | else
38 | {
39 | tail->next=newNode;
40 | tail=newNode;
41 | }
42 | }
43 | int Front()
44 | {
45 | return head->data;
46 | }
47 | void dequeue()
48 | {
49 | if(head==NULL)
50 | cout<<"EMPTY QUEUE!\n";
51 | else
52 | {
53 | head=head->next;
54 | if(head==NULL)
55 | tail=NULL;
56 | }
57 | }
58 | bool isEmpty()
59 | {
60 | return head==NULL;
61 | }
62 | };
63 |
64 |
65 |
66 |
67 |
68 | class Queue2
69 | {
70 | private:
71 | int arr[N],r,w;
72 | public:
73 | Queue2()
74 | {
75 | memset(arr, 0, sizeof arr);
76 | r=w=0;
77 | }
78 | void enqueue(int value)
79 | {
80 | if((w+1)%N==r)
81 | cout<<"NO SPACE!\n";
82 | else
83 | {
84 | arr[w++]=value;
85 | w%=N;
86 | }
87 | }
88 | int Front()
89 | {
90 | return arr[r];
91 | }
92 | void dequeue()
93 | {
94 | if(r==w)
95 | cout<<"EMPTY QUEUE!\n";
96 | else
97 | {
98 | arr[r++]=0;
99 | r%=N;
100 | }
101 | }
102 | bool isEmpty()
103 | {
104 | return r==w;
105 | }
106 | };
107 |
108 | int main()
109 | {
110 | // FIO
111 | // freopen("input.txt","rt",stdin);
112 | // freopen("output.txt","wt",stdout);
113 |
114 | return 0;
115 | }
116 |
--------------------------------------------------------------------------------
/String Algorithms/Modified Rabin-Karp's Algorithm.cpp:
--------------------------------------------------------------------------------
1 | /// Ahmed Nasser Mohamed
2 | /// 06/08/2020
3 |
4 | /*
5 | --Problem description : find all occurrences of string T in string S.
6 | --Solution : 1- Hash all sub-strings in S of length |T| using two different polynomial hash functions
7 | 2- Hash T with the same two hash functions
8 | 3- Compare the hash values of all sub-strings in S of length |T| with the hash values of T
9 | 4- If the first hash function values are the same and the second hash function values are the same, so the strings are the same.
10 | 5- Else, the strings are not the same
11 | --Time complexity : O(|S|) with probability of wrong answers less than (|T|/p1)*(|T|/p2) which is <= 1e-18 almost zero,
12 | and it is better to use more different hash functions.
13 | */
14 |
15 | #include
16 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
17 | using namespace std;
18 | typedef long long ll;
19 |
20 | int const N=5e5+5, M=1e5, MOD=1e9+7, OO=0x3f3f3f3f;
21 |
22 |
23 | string s,t;
24 | int n,m;
25 | ll x,p1=1e9+7,p2=1e9+9,tHash1,tHash2,Hash1[N],Hash2[N];
26 | vectorans;
27 |
28 |
29 | ll random(ll mn, ll mx)
30 | {
31 | static bool first=true;
32 | if(first)
33 | {
34 | srand(time(NULL));
35 | first=false;
36 | }
37 | return mn+rand()%((mx+1)-mn);
38 | }
39 |
40 | ll modPower(ll a, ll b, ll m)
41 | {
42 | if(!b)
43 | return 1;
44 | ll t= (modPower(a, b>>1,m))%m;
45 | return ((t*t)%m*((b&1) ? a : 1)%m)%m;
46 | }
47 |
48 |
49 | ll polyHash(string a, ll p)
50 | {
51 | int sz=a.size();
52 | ll ret=0;
53 | for(int i=sz-1; i>=0; i--)
54 | ret=(ret*x+a[i])%p;
55 | return ret;
56 | }
57 |
58 |
59 | void buildHash()
60 | {
61 | Hash1[n-m]=polyHash(s.substr(n-m),p1);
62 | Hash2[n-m]=polyHash(s.substr(n-m),p2);
63 | ll y1=modPower(x,m,p1);
64 | ll y2=modPower(x,m,p2);
65 | for(int i=n-m-1; i>=0; i--)
66 | {
67 | Hash1[i]=(((x*Hash1[i+1]+s[i]-y1*s[i+m])%p1)+p1)%p1;
68 | Hash2[i]=(((x*Hash2[i+1]+s[i]-y2*s[i+m])%p2)+p2)%p2;
69 |
70 | }
71 | }
72 |
73 |
74 | int main()
75 | {
76 | FIO
77 | // freopen("input.txt","rt",stdin);
78 | // freopen("output.txt","wt",stdout);
79 | cin>>s>>t;
80 | n=s.size();
81 | m=t.size();
82 | x=random(1,1e9);
83 | tHash1=polyHash(t,p1);
84 | tHash2=polyHash(t,p2);
85 | buildHash();
86 | for(int i=0; i<=n-m; i++)
87 | {
88 | if(Hash1[i]==tHash1 && Hash2[i]==tHash2)
89 | ans.push_back(i);
90 | }
91 | for(int i : ans)
92 | cout< first SAT condition
7 | 2- each position must exist exactly once in the path (No position contains more than one node) ---> second SAT condition
8 | 3- No two different non-adjacent nodes are adjacent in position of the path ---> third SAT condition
9 | --Time complexity : O(n^3)
10 | */
11 |
12 | #include
13 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
14 | using namespace std;
15 | typedef long long ll;
16 |
17 | int const N=1e5+5, M=300+5, MOD=1e9+7, OO=0x3f3f3f3f;
18 | double const EPS=1e-11;
19 |
20 |
21 | int n,m,c,var,u,v;
22 | vector>ans;
23 | set>st;
24 |
25 | int num(int i, int j)
26 | {
27 | return ((i-1)*n)+j;
28 | }
29 | /// i node
30 | /// j position
31 | int main()
32 | {
33 | // FIO
34 | // freopen("input.txt","rt",stdin);
35 | // freopen("output.txt","wt",stdout);
36 | scanf("%d %d",&n, &m);
37 | var=n*n;
38 | for(int i=0; iv1;
48 | for(int j=1; j<=n; j++)
49 | v1.push_back(num(i,j));
50 | ans.push_back(v1);
51 | int sz=v1.size();
52 | for(int a=0; a{-v1[a],-v1[b]});
55 | }
56 | /// Exactly One for each position j (Ex : no two nodes occupy same position)
57 | for(int j=1; j<=n; j++)
58 | {
59 | vectorv1;
60 | for(int i=1; i<=n; i++)
61 | v1.push_back(num(i,j));
62 | ans.push_back(v1);
63 | int sz=v1.size();
64 | for(int a=0; a{-v1[a],-v1[b]});
67 | }
68 | /// No two different non-adjacent nodes are adjacent in position of the path
69 | for(int a=1; a<=n; a++)
70 | for(int b=1; b<=n; b++)
71 | if(a!=b && st.find({a,b})==st.end())
72 | for(int j=1; j{-num(a,j),-num(b,j+1)});
74 | c=ans.size();
75 | printf("%d %d\n",c,var);
76 | for(vector v : ans)
77 | {
78 | for(int x : v)
79 | printf("%d ",x);
80 | puts("0");
81 | }
82 |
83 | return 0;
84 | }
85 |
--------------------------------------------------------------------------------
/Six Basic Data Structures/Map.cpp:
--------------------------------------------------------------------------------
1 | /// Ahmed Nasser Mohamed
2 | /// 5/08/2020
3 |
4 | /*
5 | --Description : store elements with an additional value varibale in a hash table
6 | --Operations wiht Time complexity : hasKey O(1) - Get O(1) - Set O(1)
7 | */
8 |
9 | #include
10 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
11 | using namespace std;
12 | typedef long long ll;
13 |
14 | int const N=10, M=1000, MOD=1e9+7, OO=0x3f3f3f3f;
15 |
16 | int const maxVal=2e5;
17 |
18 |
19 | class Map
20 | {
21 | private:
22 | list>arr[M];
23 | int p,a,b;
24 | bool isPrime(ll n)
25 | {
26 | for(ll i=2; i*i<=n; i++)
27 | if(n%i==0)
28 | return 0;
29 | return 1;
30 | }
31 | int random(int mn, int mx)
32 | {
33 | static bool first=true;
34 | if(first)
35 | {
36 | srand(time(NULL));
37 | first=false;
38 | }
39 | return mn+rand()%((mx+1)-mn);
40 | }
41 | int Hash(int x)
42 | {
43 | return ((a*x+b)%p)%M;
44 | }
45 | public:
46 | Map()
47 | {
48 | p=-1;
49 | for(int i=maxVal+1; p==-1; i++)
50 | if(isPrime(i))
51 | p=i;
52 | a=random(1,p-1);
53 | b=random(0,p-1);
54 | }
55 | bool hasKey(int x)
56 | {
57 | int ind=Hash(x);
58 | for(list>::iterator it=arr[ind].begin(); it != arr[ind].end(); ++it)
59 | if(it->first==x)
60 | return 1;
61 | return 0;
62 | }
63 | int Get(int x)
64 | {
65 | int ind=Hash(x);
66 | for(list>::iterator it=arr[ind].begin(); it != arr[ind].end(); ++it)
67 | if(it->first==x)
68 | return it->second;
69 | return OO;
70 | }
71 | void Set(int x, int v)
72 | {
73 | int ind=Hash(x);
74 | for(list>::iterator it=arr[ind].begin(); it != arr[ind].end(); ++it)
75 | {
76 | if(it->first==x)
77 | {
78 | it->second=v;
79 | return;
80 | }
81 | }
82 | arr[ind].push_back({x,v});
83 | }
84 |
85 | };
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 | int main()
94 | {
95 | // FIO
96 | // freopen("input.txt","rt",stdin);
97 | // freopen("output.txt","wt",stdout);
98 |
99 |
100 | return 0;
101 | }
102 |
--------------------------------------------------------------------------------
/Six Basic Data Structures/Priority Queue (Heap).cpp:
--------------------------------------------------------------------------------
1 | /// Ahmed Nasser Mohamed
2 | /// 29/07/2020
3 |
4 | /*
5 | --Description : store elements in a complete binary tree (max/min heap)
6 | --Operations wiht Time complexity : Push O(log(n)) - Pop O(log(n)) - remove O(log(n)) - change O(log(n))
7 | */
8 |
9 | #include
10 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
11 | using namespace std;
12 | typedef long long ll;
13 |
14 | int const N=5, M=17+5, MOD=1e9+7, OO=0x3f3f3f3f;
15 |
16 | class priorityQueue
17 | {
18 | private:
19 | int arr[N],sz;
20 | int parent(int i)
21 | {
22 | return i/2;
23 | }
24 |
25 | int leftChild(int i)
26 | {
27 | return i*2;
28 | }
29 |
30 | int rightChild(int i)
31 | {
32 | return i*2+1;
33 | }
34 |
35 | void siftUp(int i)
36 | {
37 | while(i>1 && arr[parent(i)]arr[mxi])
49 | mxi=l;
50 | int r=rightChild(i);
51 | if(r<=sz && arr[r]>arr[mxi])
52 | mxi=r;
53 | if(mxi!=i)
54 | {
55 | swap(arr[i],arr[mxi]);
56 | siftDown(mxi);
57 | }
58 | }
59 | public:
60 | priorityQueue()
61 | {
62 | memset(arr, 0, sizeof arr);
63 | sz=0;
64 | }
65 | void push(int p)
66 | {
67 | if(sz==N-1)
68 | cout<<"NO SPACE!\n";
69 | else
70 | {
71 | arr[++sz]=p;
72 | siftUp(sz);
73 | }
74 | }
75 | void pop()
76 | {
77 | if(sz==0)
78 | cout<<"EMPTY PRIORITY QUEUE!\n";
79 | else
80 | {
81 | arr[1]=arr[sz--];
82 | siftDown(1);
83 | }
84 | }
85 | int top()
86 | {
87 | return arr[1];
88 | }
89 | bool isEmpty()
90 | {
91 | return sz==0;
92 | }
93 | int getSize()
94 | {
95 | return sz;
96 | }
97 | void Remove(int i)
98 | {
99 | arr[i]=OO;
100 | siftUp(i);
101 | pop();
102 | }
103 | void change(int i, int p)
104 | {
105 | int oldp=arr[i];
106 | arr[i]=p;
107 | if(p>oldp)
108 | siftUp(i);
109 | else
110 | siftDown(i);
111 | }
112 | };
113 |
114 |
115 |
116 | int main()
117 | {
118 | // FIO
119 | // freopen("input.txt","rt",stdin);
120 | // freopen("output.txt","wt",stdout);
121 |
122 | return 0;
123 | }
124 |
--------------------------------------------------------------------------------
/Trie.cpp:
--------------------------------------------------------------------------------
1 | /// Ahmed Nasser Mohamed
2 | /// 16/08/2020
3 |
4 | /*
5 | --Description : Trie is a tree of charaters used in search and auto complete
6 | --Operations with time complexity: Add O(|S|) - Find O(|S|) - PrintTrie O(sum of all |S|)
7 | */
8 |
9 | #include
10 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
11 | using namespace std;
12 | typedef long long ll;
13 |
14 | int const N=1e5+5, M=200+5, MOD=1e9+7, OO=0x3f3f3f3f;
15 |
16 |
17 | class trie
18 | {
19 | private:
20 | int sz;
21 | vector>>adj;
22 | unordered_setst;
23 | public:
24 | trie()
25 | {
26 | sz=0;
27 | vector>v;
28 | adj.push_back(v);
29 | }
30 | int getSize()
31 | {
32 | return sz;
33 | }
34 | void add(string s)
35 | {
36 | st.insert(s);
37 | int sn=s.size();
38 | int u=0;
39 | for(int i=0; i p : adj[u])
43 | {
44 | if(p.second==s[i])
45 | {
46 | u=p.first;
47 | f=1;
48 | break;
49 | }
50 | }
51 | if(!f)
52 | {
53 | vector>v;
54 | adj.push_back(v);
55 | adj[u].push_back({++sz,s[i]});
56 | u=sz;
57 | }
58 | }
59 | }
60 | pair Find(string s) /// If it finds a match in the given string, returns {1,the first match}
61 | { /// else, returns {0,""};
62 | int sn=s.size();
63 | int u=0;
64 | string ret="";
65 | for(int i=0; i p : adj[u])
71 | {
72 | if(p.second==s[i])
73 | {
74 | u=p.first;
75 | ret+=s[i];
76 | f=1;
77 | break;
78 | }
79 | }
80 | if(!f)
81 | break;
82 | }
83 | if((int)(adj[u].size())==0 || st.find(ret)!=st.end())
84 | return {1,ret};
85 | return {0,""};
86 |
87 | }
88 | void printTrie()
89 | {
90 | for(int i=0; i<=sz; i++)
91 | for(pair p : adj[i])
92 | cout<"<>n;
108 | while(n--)
109 | {
110 | cin>>s;
111 | t.add(s);
112 | }
113 | t.printTrie();
114 |
115 | return 0;
116 | }
117 |
--------------------------------------------------------------------------------
/NP-complete & SAT/Solving NP (Special Cases Method).cpp:
--------------------------------------------------------------------------------
1 | /// Ahmed Nasser Mohamed
2 | /// 31/08/2020
3 |
4 | /*
5 | --Problem description : solve NP problem by special cases method. this problem is 2-SAT and solved by implication graph
6 | --Solution : 1- construct the implication graph
7 | 2- construct the strongly connected components of the implication graph
8 | 3- If there is a SCC containing a variable an its negation, so the problem is unsatisfiable
9 | 4- else, assign ones to SCC in topological order, and zero to its negation SCCs
10 | --Time complexity : O(V+E)
11 | */
12 |
13 | #include
14 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
15 | using namespace std;
16 | typedef long long ll;
17 |
18 | int const N=2e6+5, M=300+5, MOD=1e9+7, OO=0x3f3f3f3f;
19 | double const EPS=1e-11;
20 |
21 | int var,c,u,v,n,sccn;
22 | int par[N];
23 | bool isSat=1;
24 | vectoradj[N],adjT[N];
25 | vector>scc;
26 | vectorvc,ans,sccAns;
27 | vectorvis;
28 | stackpost;
29 |
30 | void DFS1(int u)
31 | {
32 | vis[u]=1;
33 | for(int v : adjT[u])
34 | if(!vis[v])
35 | DFS1(v);
36 | post.push(u);
37 | }
38 |
39 | void DFS2(int u)
40 | {
41 | vis[u]=1;
42 | scc[sccn].push_back(u);
43 | par[u]=sccn;
44 | for(int v : adj[u])
45 | if(!vis[v])
46 | DFS2(v);
47 | }
48 |
49 |
50 | void kosaraju()
51 | {
52 | vis=vector(n+1,0);
53 | for(int i=1; i<=n; i++)
54 | if(!vis[i])
55 | DFS1(i);
56 | vis=vector(n+1,0);
57 | while(!post.empty())
58 | {
59 | int i=post.top();
60 | post.pop();
61 | if(!vis[i])
62 | {
63 | scc.push_back(vc);
64 | DFS2(i);
65 | sccn++;
66 | }
67 | }
68 | }
69 |
70 |
71 | int nag(int x)
72 | {
73 | if(x>var)
74 | return x-var;
75 | return x+var;
76 | }
77 |
78 | int main()
79 | {
80 | // FIO
81 | // freopen("input.txt","rt",stdin);
82 | // freopen("output.txt","wt",stdout);
83 | scanf("%d %d",&var, &c);
84 | n=2*var;
85 | for(int i=0; i(sccn,0);
108 | ans=vector(n+1);
109 | for(int i=0; i
10 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
11 | using namespace std;
12 | typedef long long ll;
13 |
14 | int const N=1e5+5, M=200+5, MOD=1e9+7, OO=0x3f3f3f3f;
15 |
16 |
17 | #define V first
18 | #define I second.first
19 | #define L second.second
20 |
21 |
22 | class suffTree
23 | {
24 | private:
25 | int sz;
26 | string s;
27 | vector>>>adj;
28 | int common(string a, int i, int n, string b, int j, int m)
29 | {
30 | int lo=0, md, hi=min(n,m);
31 | while(hi-lo>0)
32 | {
33 | md=(lo+hi+1)/2;
34 | if(a.substr(i,md)==b.substr(j,md))
35 | lo=md;
36 | else
37 | hi=md-1;
38 | }
39 | return hi;
40 | }
41 | void add(int i, int l)
42 | {
43 | int u=0;
44 | vector>>v;
45 | while(true)
46 | {
47 | bool f=0;
48 | for(pair> &p : adj[u])
49 | {
50 | int c=common(s,i,l,s,p.I,p.L);
51 | if(c)
52 | {
53 | if(p.L-c)
54 | {
55 | adj.push_back(v);
56 | swap(adj[++sz],adj[p.V]);
57 | adj[p.V].push_back({sz,{p.I+c,p.L-c}});
58 | }
59 | i+=c;
60 | l-=c;
61 | p.L=c;
62 | u=p.V;
63 | f=1;
64 | break;
65 | }
66 | }
67 | if(!f)
68 | {
69 | adj.push_back(v);
70 | adj[u].push_back({++sz,{i,l}});
71 | break;
72 | }
73 | }
74 | }
75 | public:
76 | suffTree(string S)
77 | {
78 | sz=0;
79 | s=S+'$';
80 | vector>>v;
81 | adj.push_back(v);
82 | }
83 | int Find(string a)
84 | {
85 | int u,i,l,an,sum=0;
86 | u=i=0;
87 | an=l=a.size();
88 | while(true)
89 | {
90 | bool f=0, fb=0;
91 | for(pair> p : adj[u])
92 | {
93 | int c=common(s,p.I,p.L,a,i,l);
94 | if(c)
95 | {
96 | i+=c;
97 | if(i==an)
98 | return p.I-sum;
99 | if(c!=p.L)
100 | return -1;
101 | sum+=c;
102 | l-=c;
103 | f=1;
104 | u=p.V;
105 | break;
106 | }
107 | }
108 | if(!f)
109 | return -1;
110 | }
111 | }
112 | void buildTree()
113 | {
114 | int n=s.size();
115 | for(int i=0; i> p : adj[i])
122 | cout<"<>a;
134 | suffTree t=suffTree(a);
135 | t.buildTree();
136 | t.printTree();
137 |
138 |
139 |
140 | return 0;
141 | }
142 |
--------------------------------------------------------------------------------
/Six Basic Data Structures/Linked List.cpp:
--------------------------------------------------------------------------------
1 | /// Ahmed Nasser Mohamed
2 | /// 16/07/2020
3 |
4 | /*
5 | --Description : store elements with pointer(s) for linkage
6 | --Operations wiht Time complexity : pushFront O(1) - popFront O(1) - pushBack O(1) -
7 | popBack O(n) single pointer or O(1) double pointer -
8 | addAfter O(1) - addBefore O(n) single pointer or O(1) double pointer -
9 | findNode O(n)
10 | */
11 |
12 | #include
13 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
14 | using namespace std;
15 | typedef long long ll;
16 |
17 | int const N=30+5, M=600+5, MOD=1e9+7, OO=0x3f3f3f3f;
18 |
19 | struct node
20 | {
21 | int data;
22 | node *next;
23 | };
24 |
25 |
26 | class linkedList
27 | {
28 | private:
29 | node *head,*tail;
30 | public:
31 | linkedList()
32 | {
33 | head=tail=NULL;
34 | }
35 | void pushFront(int value)
36 | {
37 | node *newNode=new node;
38 | newNode->data=value;
39 | newNode->next=head;
40 | head=newNode;
41 | if(tail==NULL)
42 | tail=newNode;
43 | }
44 | int getFront()
45 | {
46 | return head->data;
47 | }
48 | void PopFront()
49 | {
50 | if(head==NULL)
51 | cout<<"EMPTY LIST!\n";
52 | else
53 | {
54 | head=head->next;
55 | if(head==NULL)
56 | tail=NULL;
57 | }
58 | }
59 | void pushBack(int value)
60 | {
61 | node *newNode= new node;
62 | newNode->data=value;
63 | newNode->next=NULL;
64 | if(head==NULL)
65 | head=tail=newNode;
66 | else
67 | {
68 | tail->next=newNode;
69 | tail=newNode;
70 | }
71 | }
72 | int getBack()
73 | {
74 | return tail->data;
75 | }
76 | void popBack()
77 | {
78 | if(head==NULL)
79 | cout<<"EMPTY LIST!\n";
80 | else if(head==tail)
81 | head=tail=NULL;
82 | else
83 | {
84 | node *temp=head;
85 | while(temp->next->next!=NULL)
86 | temp=temp->next;
87 | temp->next=NULL;
88 | tail=temp;
89 | }
90 | }
91 | void addAfter(node *Node, int value)
92 | {
93 | node *newNode= new node;
94 | newNode->data=value;
95 | newNode->next=Node->next;
96 | Node->next=newNode;
97 | if(Node==tail)
98 | tail=newNode;
99 | }
100 | void addBefore(node *Node, int value)
101 | {
102 | if(Node==head)
103 | pushFront(value);
104 | else
105 | {
106 | node *temp=head;
107 | while(temp->next!=Node)
108 | temp=temp->next;
109 | addAfter(temp,value);
110 | }
111 | }
112 | node* findNode(int value)
113 | {
114 | node *temp=head;
115 | while(temp!=NULL)
116 | {
117 | if(temp->data==value)
118 | return temp;
119 | temp=temp->next;
120 | }
121 | return NULL;
122 | }
123 | bool isEmpty()
124 | {
125 | return head==NULL;
126 | }
127 | void printList()
128 | {
129 | node *temp=head;
130 | while(temp!=NULL)
131 | {
132 | cout<data<<" ";
133 | temp=temp->next;
134 | }
135 | cout<<"\n";
136 | }
137 |
138 | };
139 |
140 |
141 |
142 | int main()
143 | {
144 | // FIO
145 | // freopen("input.txt","rt",stdin);
146 | // freopen("output.txt","wt",stdout);
147 |
148 |
149 | return 0;
150 | }
151 |
--------------------------------------------------------------------------------
/String Algorithms/Burrows-Wheeler for Pattern Matching.cpp:
--------------------------------------------------------------------------------
1 | /// Ahmed Nasser Mohamed
2 | /// 19/08/2020
3 |
4 | /*
5 | --Problem description : find all occurrences of N strings (P) in string S.
6 | --Solution : 1- construct the suffix array for the string S
7 | 2- construct the BWT(S) from using the suffix array
8 | 3- for each string P, use last first property of Burrows-Wheeler to find the matches
9 | --Time complexity : |T|log(|T|) ---> for construction suffix array and BWT
10 | +
11 | |T| + |P| ---> for search for ALL match for a pattern
12 | */
13 |
14 |
15 | #include
16 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
17 | using namespace std;
18 | typedef long long ll;
19 |
20 | int const N=2e5+5, M=200+5, MOD=1e9+7, OO=0x3f3f3f3f;
21 |
22 | int t,n,m,L;
23 | string s,ss,BWT,a;
24 | vectorsuffArr,classArr;
25 | unordered_mapfo;
26 | unordered_map>cnt;
27 |
28 |
29 | void sortChars()
30 | {
31 | vectorcntSort(27,0);
32 | for(int i=0; icntSort(n,0),newSuff(n,0);
60 | for(int i=0; i=0; i--)
65 | {
66 | int st=(((suffArr[i]-L)%n)+n)%n;
67 | newSuff[--cntSort[classArr[st]]]=st;
68 | }
69 | suffArr=newSuff;
70 | }
71 |
72 | void doubleLClasses()
73 | {
74 | vectornewClass(n,0);
75 | newClass[suffArr[0]]=0;
76 | for(int i=1; i solve()
94 | {
95 | int top=0, bottom=n-1;
96 | for(int i=m-1; i>=0 && top<=bottom; i--)
97 | {
98 | if(fo.find(a[i])!=fo.end())
99 | {
100 | if(cnt[a[i]][bottom+1]-cnt[a[i]][top]>0)
101 | {
102 | top=fo[a[i]]+cnt[a[i]][top];
103 | bottom=fo[a[i]]+cnt[a[i]][bottom+1]-1;
104 | }
105 | else
106 | return {-1,-1};
107 | }
108 | else
109 | return {-1,-1};
110 | }
111 | return {top,bottom};
112 |
113 | }
114 |
115 | int main()
116 | {
117 | FIO
118 | // freopen("input.txt","rt",stdin);
119 | // freopen("output.txt","wt",stdout);
120 | cin>>s>>t;
121 | s+='$';
122 | n=s.size();
123 | vectorv(n+1,0);
124 | suffArr=vector(n,0);
125 | classArr=vector(n,0);
126 | sortChars();
127 | charsClasses();
128 | L=1;
129 | while(L p : fo)
148 | cnt[p.first][i]+=cnt[p.first][i-1];
149 | while(t--)
150 | {
151 | cin>>a;
152 | m=a.size();
153 | pairans=solve();
154 | if(ans.first!=-1)
155 | {
156 | cout<
11 | using namespace std;
12 |
13 | //Constants
14 | int const N=5e5+5, M=26+5, oo=0x3f3f3f3f, MOD=1e8, maxit=100;
15 | double const tol=1e-20,OO=0x3f3f3f3f3f3f3f3f;
16 |
17 | // Global variables
18 | int dom1,dom2,Dom1,Dom2,cnt;
19 | bool notValid;
20 | string eq;
21 | vector > arr;
22 | map mem;
23 | map sol;
24 |
25 | /// Functions prototypes
26 | string trim(string s);
27 | void findCoff(string eq);
28 | void check(string stemp);
29 | double bisection(double a, double b);
30 | double fun(double x);
31 |
32 | int main()
33 | {
34 |
35 | while(true)
36 | {
37 | notValid=0;
38 | arr.clear();
39 | cout<<" F(x) = ax^b + cx^d + ex^f +....+gx+h Where a,b,c,d,e,f,g and h are constants.\n";
40 | cout<<"\nEnter an equation following the format of F(x): ";
41 | getline(cin,eq);
42 | findCoff(trim(eq));
43 | if(notValid)
44 | cout<<"\nThe input is NOT CORRECT, please try again!\n\n";
45 | else
46 | break;
47 | }
48 |
49 | cout<<"\nEnter the integer start of the domain: ";
50 | cin>>dom1;
51 | cout<<"\nEnter the integer end of the domain: ";
52 | cin>>dom2;
53 | cout<<"\n";
54 | Dom1=min(dom1,dom2);
55 | Dom2=max(dom1,dom2);
56 | cout<0)
62 | continue;
63 | double ans=bisection((double)(i),(double)(j));
64 | if(sol[ans]==0)
65 | {
66 | sol[ans]=1;
67 | cout<<"Root "<<++cnt<<" = "< p : arr)
88 | ret+=p.first*pow(x,p.second);
89 | return mem[x]=ret;
90 | }
91 |
92 |
93 |
94 | double bisection(double a, double b)
95 | {
96 | double c;
97 | double fa=fun(a);
98 | if(abs(fa)0)
113 | {
114 | a=c;
115 | fa=fc;
116 | }
117 | if(fb*fc>0)
118 | {
119 | b=c;
120 | fb=fc;
121 | }
122 | }
123 | return c;
124 | }
125 |
126 |
127 | string trim(string s)
128 | {
129 | string str=s;
130 | str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
131 | return str;
132 | }
133 |
134 |
135 | void check(string stemp)
136 | {
137 | double coff=OO;
138 | char a;
139 | int ord=oo;
140 | string ts="NONE",stest="NONE";
141 | stringstream ss1;
142 | ss1<>coff;
144 | if(coff!=OO && coff!=0)
145 | {
146 | ss1>>ts;
147 | if(ts=="x")
148 | arr.push_back({coff,1});
149 | else if(ts.substr(0,2)=="x^" && ts.size()>2)
150 | {
151 | stringstream ss2;
152 | ss2<>a>>a>>ord>>stest;
154 | if(ord!=oo && ord!=0 && stest=="NONE")
155 | arr.push_back({coff,ord});
156 | else
157 | notValid=1;
158 | }
159 | else if (ts=="NONE")
160 | arr.push_back({coff,0});
161 | else
162 | notValid=1;
163 | }
164 | else
165 | notValid=1;
166 |
167 | }
168 |
169 |
170 | void findCoff(string eq)
171 | {
172 | if(eq[0]!='-')
173 | eq='+'+eq;
174 | int sz=eq.size();
175 | string stemp="";
176 | bool taken=0;
177 | for(int i=0; i1 && !(stemp[1]-'0'>=0 && stemp[1]-'0'<=9))
184 | stemp.insert(1,"1");
185 | check(stemp);
186 | taken=0;
187 | i--;
188 | continue;
189 | }
190 | else
191 | {
192 | taken=1;
193 | }
194 | stemp=eq[i];
195 | }
196 | else
197 | stemp+=eq[i];
198 | }
199 | check(stemp);
200 | }
201 |
--------------------------------------------------------------------------------
/AVL Tree.cpp:
--------------------------------------------------------------------------------
1 | /// Ahmed Nasser Mohamed
2 | /// 09/08/2020
3 |
4 | /*
5 | --Description : AVL tree is a balanced binary search tree that can perform all operations in O(log(n))
6 | --Operations : Insert - Search - Delete - Range
7 | --Time complexity : O(log(n))
8 | */
9 |
10 | #include
11 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
12 | using namespace std;
13 | typedef long long ll;
14 |
15 | int const N=1e5+5, MOD=1e9+7, OO=0x3f3f3f3f;
16 |
17 | struct node{
18 | int data,height;
19 | node *parent,*left,*right;
20 | };
21 |
22 |
23 | class AVL
24 | {
25 | private:
26 | node *root;
27 | node* LeftDescendant(node* Node)
28 | {
29 | if(Node->left==NULL)
30 | return Node;
31 | return LeftDescendant(Node->left);
32 | }
33 | node* RightAncestor(node *Node)
34 | {
35 | if(Node->parent==NULL || Node->data < Node->parent->data)
36 | return Node->parent;
37 | return RightAncestor(Node->parent);
38 | }
39 | node* Find(int Data, node *Root) /// If the node is found, the function returns the node itself
40 | { /// else the function returns its future parent
41 | if(Root->data==Data)
42 | return Root;
43 | if(Root->data > Data && Root->left!=NULL)
44 | return Find(Data, Root->left);
45 | if(Root->data < Data && Root->right!=NULL)
46 | return Find(Data, Root->right);
47 | return Root;
48 | }
49 | node* Next(node *Node) /// The function returns the first node greater than given node
50 | { /// The function may return NULL is the given node is the greatest one
51 | if(Node->right!=NULL)
52 | return LeftDescendant(Node->right);
53 | return RightAncestor(Node);
54 | }
55 | int Height(node *Node)
56 | {
57 | if(Node==NULL)
58 | return 0;
59 | if(Node->left==NULL && Node->right==NULL)
60 | return Node->height=1;
61 | return Node->height=1+max(Height(Node->left),Height(Node->right));
62 | }
63 | void RotateRight(node *X)
64 | {
65 | node *P=X->parent;
66 | node *Y=X->left;
67 | node *B=Y->right;
68 | Y->parent=P;
69 | if(P==NULL)
70 | root=Y;
71 | else if(P->left==X)
72 | P->left=Y;
73 | else
74 | P->right=Y;
75 | X->parent=Y;
76 | Y->right=X;
77 | if(B!=NULL)
78 | B->parent=X;
79 | X->left=B;
80 | }
81 | void RotateLeft(node *X)
82 | {
83 | node *P=X->parent;
84 | node *Y=X->right;
85 | node *B=Y->left;
86 | Y->parent=P;
87 | if(P==NULL)
88 | root=Y;
89 | else if(P->left==X)
90 | P->left=Y;
91 | else
92 | P->right=Y;
93 | X->parent=Y;
94 | Y->left=X;
95 | if(B!=NULL)
96 | B->parent=X;
97 | X->right=B;
98 |
99 | }
100 | void Rebalance(node *Node)
101 | {
102 | int ln,rn,lm,rm;
103 | node *P=Node->parent;
104 | ln=(Node->left==NULL)? 0 : Node->left->height;
105 | rn=(Node->right==NULL)? 0 : Node->right->height;
106 | if(ln>rn+1)
107 | {
108 | node *M=Node->left;
109 | lm=(M->left==NULL)? 0 : M->left->height;
110 | rm=(M->right==NULL)? 0 : M->right->height;
111 | if(rm>lm)
112 | RotateLeft(M);
113 | RotateRight(Node);
114 | Height(root);
115 | }
116 | ln=(Node->left==NULL)? 0 : Node->left->height;
117 | rn=(Node->right==NULL)? 0 : Node->right->height;
118 | if(rn>ln+1)
119 | {
120 | node *M=Node->right;
121 | lm=(M->left==NULL)? 0 : M->left->height;
122 | rm=(M->right==NULL)? 0 : M->right->height;
123 | if(lm>rm)
124 | RotateRight(M);
125 | RotateLeft(Node);
126 | Height(root);
127 | }
128 | if(P!=NULL)
129 | Rebalance(P);
130 | }
131 |
132 | public:
133 | AVL()
134 | {
135 | root=NULL;
136 | }
137 | node* GetRoot()
138 | {
139 | if(root==NULL)
140 | cout<<"\nEMPTY AVL TREE!\n";
141 | return root;
142 | }
143 | bool Search(int Data)
144 | {
145 | if(root==NULL)
146 | return 0;
147 | node *Node=Find(Data, root);
148 | if(Node->data==Data)
149 | return 1;
150 | return 0;
151 | }
152 | vector Range(int x, int y)
153 | {
154 | vector ret;
155 | if(root==NULL)
156 | return ret;
157 | node *Node=Find(x,root);
158 | while(Node!=NULL && Node->data <= y)
159 | {
160 | if(Node->data >= x)
161 | ret.push_back(Node->data);
162 | Node=Next(Node);
163 | }
164 | return ret;
165 | }
166 | void Insert(int Data)
167 | {
168 | if(root==NULL)
169 | {
170 | node *newNode=new node;
171 | newNode->data=Data;
172 | newNode->parent=newNode->left=newNode->right=NULL;
173 | newNode->height=1;
174 | root=newNode;
175 | return;
176 | }
177 | node *P=Find(Data, root);
178 | if(P->data==Data)
179 | return;
180 | node *newNode=new node;
181 | newNode->data=Data;
182 | newNode->parent=P;
183 | newNode->left=newNode->right=NULL;
184 | if(P->data > Data)
185 | P->left=newNode;
186 | else
187 | P->right=newNode;
188 | Height(root);
189 | Rebalance(newNode);
190 | }
191 | void Delete(int Data)
192 | {
193 | if(root==NULL)
194 | return;
195 | node *Node=Find(Data, root);
196 | if(Node->data!=Data)
197 | return;
198 | node *P;
199 | if(Node->right==NULL)
200 | {
201 | P=Node->parent;
202 | node *L=Node->left;
203 | if(P==NULL)
204 | root=L;
205 | else if(P->right==Node)
206 | P->right=L;
207 | else
208 | P->left=L;
209 | if(L!=NULL)
210 | L->parent=P;
211 | delete Node;
212 | }
213 | else
214 | {
215 | node *X=Next(Node);
216 | Node->data=X->data;
217 | P=X->parent;
218 | node *R=X->right;
219 | if(P->right==X)
220 | P->right=R;
221 | else
222 | P->left=R;
223 | if(R!=NULL)
224 | R->parent=P;
225 | delete X;
226 | }
227 | Height(root);
228 | if(P!=NULL)
229 | Rebalance(P);
230 | }
231 | void printAVL(node *Root, string indent, bool last)
232 | {
233 | if (Root!=NULL)
234 | {
235 | cout<data<left, indent, 0);
248 | printAVL(Root->right, indent, 1);
249 | }
250 | }
251 |
252 | };
253 |
254 |
255 |
256 | int main()
257 | {
258 | FIO
259 | // freopen("input.txt","rt",stdin);
260 | // freopen("output.txt","wt",stdout);
261 |
262 | return 0;
263 | }
264 |
--------------------------------------------------------------------------------
/Linear Programming/Simplex Method.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
3 | using namespace std;
4 | typedef long long ll;
5 |
6 | int const N=100+5, M=300+5, MOD=1e9+7, OO=0x3f3f3f3f;
7 | long double const tolerance=1e-11;
8 |
9 | int eqN,varN,n,m,art;
10 | int basis[N];
11 | long double arr[N][M],cj[M],z[M],ans[M], opt;
12 | bool isleft[M];
13 |
14 | void printTable()
15 | {
16 | cout<<0<<" | ";
17 | for(int j=0; j0)
60 | {
61 | d=arr[i][0]/arr[i][kj];
62 | if(d+toleranceeqN+varN)
71 | {
72 | ki=i;
73 | tBasis=basis[i];
74 | }
75 | }
76 | }
77 | }
78 | /// Unbounded case if there is no positive numbers in key column
79 | if(ki==-1)
80 | return 0;
81 | /// Updating the basis variables (Entering and Leaving)
82 | if(basis[ki]>varN+eqN)
83 | isleft[basis[ki]]=1;
84 | basis[ki]=kj;
85 | /// Gauss-Jordan for the key element
86 | d=arr[ki][kj];
87 | for(int j=0; j>eqN>>varN;
131 | for(int i=0; i>arr[i][j];
137 | }
138 | for(int i=0; i>arr[i][0];
141 | if(arr[i][0]<0)
142 | {
143 | arr[i][i+varN+1]=-1;
144 | for(int j=0; j<=varN; j++)
145 | arr[i][j]*=-1;
146 | art++;
147 | arr[i][varN+eqN+art]=1;
148 | cj[varN+eqN+art]=-1;
149 | basis[i]=varN+eqN+art;
150 | }
151 | }
152 | n=eqN+2;
153 | m=1+varN+eqN+art;
154 | for(int j=1; j<=varN; j++)
155 | cin>>z[j];
156 | for(int j=0; jvarN+eqN)
172 | isFeasible=0;
173 | if(!isFeasible)
174 | {
175 | cout<<"No solution\n";
176 | return 0;
177 | }
178 | m-=art;
179 | for(int j=1; j
209 | #define FIO ios_base::sync_with_stdio(0);cin.tie(0);
210 | using namespace std;
211 | typedef long long ll;
212 |
213 | int const N=100+5, M=300+5, MOD=1e9+7, OO=0x3f3f3f3f;
214 | long double const tolerance=1e-11;
215 |
216 | int eqN,varN,n,m,art;
217 | int basis[N];
218 | long double arr[N][M],cj[M],z[M],ans[M], opt;
219 | bool isleft[M];
220 |
221 | void printTable()
222 | {
223 | cout<<0<<" | ";
224 | for(int j=0; j0)
267 | {
268 | d=arr[i][0]/arr[i][kj];
269 | if(d+toleranceeqN+varN)
278 | {
279 | ki=i;
280 | tBasis=basis[i];
281 | }
282 | }
283 | }
284 | }
285 | /// Unbounded case if there is no positive numbers in key column
286 | if(ki==-1)
287 | return 0;
288 | /// Updating the basis variables (Entering and Leaving)
289 | if(basis[ki]>varN+eqN)
290 | isleft[basis[ki]]=1;
291 | basis[ki]=kj;
292 | /// Gauss-Jordan for the key element
293 | d=arr[ki][kj];
294 | for(int j=0; j>eqN>>varN;
338 | for(int i=0; i>arr[i][j];
344 | }
345 | for(int i=0; i>arr[i][0];
348 | if(arr[i][0]<0)
349 | {
350 | arr[i][i+varN+1]=-1;
351 | for(int j=0; j<=varN; j++)
352 | arr[i][j]*=-1;
353 | art++;
354 | arr[i][varN+eqN+art]=1;
355 | cj[varN+eqN+art]=-1;
356 | basis[i]=varN+eqN+art;
357 | }
358 | }
359 | n=eqN+2;
360 | m=1+varN+eqN+art;
361 | for(int j=1; j<=varN; j++)
362 | cin>>z[j];
363 | for(int j=0; jvarN+eqN)
379 | isFeasible=0;
380 | if(!isFeasible)
381 | {
382 | cout<<"No solution\n";
383 | return 0;
384 | }
385 | m-=art;
386 | for(int j=1; j