Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 24

1)Karatsuba Algorithm:

#include <bits/stdc++.h>
using namespace std;
string findSum(string str1, string str2)
{
if (str1.length() > str2.length())
swap(str1, str2);
string str = "";
int n1 = str1.length();
int n2 = str2.length();
reverse(str1.begin(), str1.end());
reverse(str2.begin(), str2.end());
int carry = 0;
for (int i = 0; i < n1; i++) {
int sum= ((str1[i] - '0') + (str2[i] - '0') + carry);
str.push_back(sum % 10 + '0');
carry = sum / 10;
}
for (int i = n1; i < n2; i++) {
int sum = ((str2[i] - '0') + carry);
str.push_back(sum % 10 + '0');
carry = sum / 10;
}
if (carry)
str.push_back(carry + '0');
reverse(str.begin(), str.end());
return str;
}
string findDiff(string str1, string str2)
{
// Stores the result of difference
string str = "";
// Calculate length of both string
int n1 = str1.length(), n2 = str2.length();
// Reverse both of strings
reverse(str1.begin(), str1.end());
reverse(str2.begin(), str2.end());
int carry = 0;
for (int i = 0; i < n2; i++) {
int sub
= ((str1[i] - '0')
- (str2[i] - '0')
- carry);
if (sub < 0) {
sub = sub + 10;
carry = 1;
}
else
carry = 0;
str.push_back(sub + '0');
}
for (int i = n2; i < n1; i++) {
int sub = ((str1[i] - '0') - carry);
if (sub < 0) {
sub = sub + 10;
carry = 1;
}
else
carry = 0;
str.push_back(sub + '0');
}
reverse(str.begin(), str.end());
return str;
}
string removeLeadingZeros(string str)
{
const regex pattern("^0+(?!$)");
str = regex_replace(str, pattern, "");
return str;
}
string multiply(string A, string B)
{
if (A.length() > B.length())
swap(A, B);
int n1 = A.length(), n2 = B.length();
while (n2 > n1) {
A = "0" + A;
n1++;
}
if (n1 == 1) {
int ans = stoi(A) * stoi(B);
return to_string(ans);
}
if (n1 % 2 == 1) {
n1++;
A = "0" + A;
B = "0" + B;
}
string Al, Ar, Bl, Br;
for (int i = 0; i < n1 / 2; ++i) {
Al += A[i];
Bl += B[i];
Ar += A[n1 / 2 + i];
Br += B[n1 / 2 + i];
}
string p = multiply(Al, Bl);
string q = multiply(Ar, Br);
string r = findDiff(
multiply(findSum(Al, Ar),
findSum(Bl, Br)),
findSum(p, q));
for (int i = 0; i < n1; ++i)
p = p + "0";
for (int i = 0; i < n1 / 2; ++i)
r = r + "0";
string ans = findSum(p, findSum(q, r));
ans = removeLeadingZeros(ans);
return ans;
}
int main()
{
string A = "743333";
string B = "300000";
cout << multiply(A, B);
return 0;
}
2) Sorting with time

CODE:

#include <bits/stdc++.h>
#include <sys/time.h>
using namespace std;
void merge(int arr[], int p, int q, int r)
{
int n1 = q - p + 1; int n2 = r - q;
int L[n1], M[n2];
for (int i = 0; i < n1; i++) L[i] = arr[p + i];
for (int j = 0; j < n2; j++) M[j] = arr[q + 1 + j];
int i, j, k; i = 0;
j = 0;
k = p;
while (i < n1 && j < n2)
{
if (L[i] <= M[j])
{
arr[k] = L[i]; i++;
}
else
{
arr[k] = M[j]; j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i]; i++;
k++;
}
while (j < n2)
{
arr[k] = M[j]; j++;
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
int m = l + (r - l) / 2;
mergeSort(arr, l, m); mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
void func()
{
int n, i;
cout<<"Enter number of elements : "; cin>>n;
int arr[n];
cout<<"Enter the elements : "; for(i = 0; i < n; i++)
{
cin>>arr[i];
}
mergeSort(arr, 0, n-1); cout<<"Minimum = "<<arr[0]<<endl; cout<<"Maximum = "<<arr[n-
1]<<endl;
}
int main()
{
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
ios_base::sync_with_stdio(false);
func();
clock_gettime(CLOCK_MONOTONIC, &end);
double time_taken;
time_taken = (end.tv_sec - start.tv_sec) * 1e9;
time_taken = (time_taken + (end.tv_nsec - start.tv_nsec)) * 1e-9;
cout << "Time taken by program is : " << fixed
<< time_taken << setprecision(9);
cout << " sec" << endl;
return 0;
}

3)Dijkistra algo with time

Code:

// Dijkstra's Algorithm in C++


#include <iostream>

#include <vector>

#define INT_MAX 10000000

using namespace std;

void DijkstrasTest();

class Node;

class Edge;

void Dijkstras();

vector<Node*>* AdjacentRemainingNodes(Node* node);

Node* ExtractSmallest(vector<Node*>& nodes);

int Distance(Node* node1, Node* node2);

bool Contains(vector<Node*>& nodes, Node* node);

void PrintShortestRouteTo(Node* destination);

vector<Node*> nodes;

vector<Edge*> edges;

class Node {

public:

Node(char id)

: id(id), previous(NULL), distanceFromStart(INT_MAX) {

nodes.push_back(this);

public:

char id;

Node* previous;

int distanceFromStart;

};

class Edge {

public:

Edge(Node* node1, Node* node2, int distance)

: node1(node1), node2(node2), distance(distance) {

edges.push_back(this);
}

bool Connects(Node* node1, Node* node2) {

return (

(node1 == this->node1 &&

node2 == this->node2) ||

(node1 == this->node2 &&

node2 == this->node1));

public:

Node* node1;

Node* node2;

int distance;

};

///////////////////

void DijkstrasTest() {

Node* a = new Node('a');

Node* b = new Node('b');

Node* c = new Node('c');

Node* d = new Node('d');

Node* e = new Node('e');

Node* f = new Node('f');

Node* g = new Node('g');

Edge* e1 = new Edge(a, c, 1);

Edge* e2 = new Edge(a, d, 2);

Edge* e3 = new Edge(b, c, 2);

Edge* e4 = new Edge(c, d, 1);

Edge* e5 = new Edge(b, f, 3);

Edge* e6 = new Edge(c, e, 3);

Edge* e7 = new Edge(e, f, 2);

Edge* e8 = new Edge(d, g, 1);

Edge* e9 = new Edge(g, f, 1);


a->distanceFromStart = 0; // set start node

Dijkstras();

PrintShortestRouteTo(f);

///////////////////

void Dijkstras() {

while (nodes.size() > 0) {

Node* smallest = ExtractSmallest(nodes);

vector<Node*>* adjacentNodes =

AdjacentRemainingNodes(smallest);

const int size = adjacentNodes->size();

for (int i = 0; i < size; ++i) {

Node* adjacent = adjacentNodes->at(i);

int distance = Distance(smallest, adjacent) +

smallest->distanceFromStart;

if (distance < adjacent->distanceFromStart) {

adjacent->distanceFromStart = distance;

adjacent->previous = smallest;

delete adjacentNodes;
}

// Find the node with the smallest distance,

// remove it, and return it.

Node* ExtractSmallest(vector<Node*>& nodes) {

int size = nodes.size();

if (size == 0) return NULL;

int smallestPosition = 0;

Node* smallest = nodes.at(0);

for (int i = 1; i < size; ++i) {

Node* current = nodes.at(i);

if (current->distanceFromStart <

smallest->distanceFromStart) {

smallest = current;

smallestPosition = i;

nodes.erase(nodes.begin() + smallestPosition);

return smallest;

// Return all nodes adjacent to 'node' which are still

// in the 'nodes' collection.

vector<Node*>* AdjacentRemainingNodes(Node* node) {

vector<Node*>* adjacentNodes = new vector<Node*>();

const int size = edges.size();

for (int i = 0; i < size; ++i) {

Edge* edge = edges.at(i);

Node* adjacent = NULL;

if (edge->node1 == node) {

adjacent = edge->node2;

} else if (edge->node2 == node) {


adjacent = edge->node1;

if (adjacent && Contains(nodes, adjacent)) {

adjacentNodes->push_back(adjacent);

return adjacentNodes;

// Return distance between two connected nodes

int Distance(Node* node1, Node* node2) {

const int size = edges.size();

for (int i = 0; i < size; ++i) {

Edge* edge = edges.at(i);

if (edge->Connects(node1, node2)) {

return edge->distance;

return -1; // should never happen

// Does the 'nodes' vector contain 'node'

bool Contains(vector<Node*>& nodes, Node* node) {

const int size = nodes.size();

for (int i = 0; i < size; ++i) {

if (node == nodes.at(i)) {

return true;

return false;

}
///////////////////

void PrintShortestRouteTo(Node* destination) {

Node* previous = destination;

cout << "Distance from start: "

<< destination->distanceFromStart << endl;

while (previous) {

cout << previous->id << " ";

previous = previous->previous;

cout << endl;

// these two not needed

vector<Edge*>* AdjacentEdges(vector<Edge*>& Edges, Node* node);

void RemoveEdge(vector<Edge*>& Edges, Edge* edge);

vector<Edge*>* AdjacentEdges(vector<Edge*>& edges, Node* node) {

vector<Edge*>* adjacentEdges = new vector<Edge*>();

const int size = edges.size();

for (int i = 0; i < size; ++i) {

Edge* edge = edges.at(i);

if (edge->node1 == node) {

cout << "adjacent: " << edge->node2->id << endl;

adjacentEdges->push_back(edge);

} else if (edge->node2 == node) {

cout << "adjacent: " << edge->node1->id << endl;

adjacentEdges->push_back(edge);

}
}

return adjacentEdges;

void RemoveEdge(vector<Edge*>& edges, Edge* edge) {

vector<Edge*>::iterator it;

for (it = edges.begin(); it < edges.end(); ++it) {

if (*it == edge) {

edges.erase(it);

return;

int main() {

DijkstrasTest();

struct timespec start, end;

clock_gettime(CLOCK_MONOTONIC, &start);

ios_base::sync_with_stdio(false);

Dijkstras;

clock_gettime(CLOCK_MONOTONIC, &end);

double time_taken;

time_taken = (end.tv_sec - start.tv_sec) * 1e9;

time_taken = (time_taken + (end.tv_nsec - start.tv_nsec)) * 1e-9;

cout << "Time taken by program is : " << fixed

<< time_taken;

cout << " sec" << endl;

return 0;

3b) Dijikstra algorithm:

#include<iostream>
#include<climits>
using namespace std;
// this method returns a minimum distance for the
// vertex which is not included in Tset.
int minimumDist(int dist[], bool Tset[])
{
int min=INT_MAX,index;

for(int i=0;i<6;i++)
{
if(Tset[i]==false && dist[i]<=min)
{
min=dist[i];
index=i;
}
}
return index;
}

void Dijkstra(int graph[6][6],int src) // adjacency matrix used is 6x6


{
int dist[6]; // integer array to calculate minimum distance for each node.
bool Tset[6];// boolean array to mark visted/unvisted for each node.

// set the nodes with infinity distance


// except for the initial node and mark
// them unvisited.
for(int i = 0; i<6; i++)
{
dist[i] = INT_MAX;
Tset[i] = false;
}

dist[src] = 0; // Source vertex distance is set to zero.

for(int i = 0; i<6; i++)


{
int m=minimumDist(dist,Tset); // vertex not yet included.
Tset[m]=true;// m with minimum distance included in Tset.
for(int i = 0; i<6; i++)
{
// Updating the minimum distance for the particular node.
if(!Tset[i] && graph[m][i] && dist[m]!=INT_MAX && dist[m]
+graph[m][i]<dist[i])
dist[i]=dist[m]+graph[m][i];
}
}
cout<<"Vertex\t\tDistance from source"<<endl;
for(int i = 0; i<6; i++)
{ //Printing
char str=65+i; // Ascii values for pritning A,B,C..
cout<<str<<"\t\t\t"<<dist[i]<<endl;
}
}

int main()
{
int graph[6][6]={
{0, 10, 20, 0, 0, 0},
{10, 0, 0, 50, 10, 0},
{20, 0, 0, 20, 33, 0},
{0, 50, 20, 0, 20, 2},
{0, 10, 33, 20, 0, 1},
{0, 0, 0, 2, 1, 0}};
Dijkstra(graph,0);
return 0;
}

)Minimum spanning codt tree:

#include <bits/stdc++.h>
using namespace std;
class DSU {
int* parent;
int* rank;
public:
DSU(int n)
{
parent = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = -1;
rank[i] = 1;
}
}
// Find function
int find(int i)
{
if (parent[i] == -1)
return i;
return parent[i] = find(parent[i]);
}
// union function
void unite(int x, int y)
{
int s1 = find(x);
int s2 = find(y);
if (s1 != s2) {
if (rank[s1] < rank[s2]) {
parent[s1] = s2;
rank[s2] += rank[s1];
}
else {
parent[s2] = s1;
rank[s1] += rank[s2];
}
}
}
};
class Graph {
vector<vector<int> > edgelist;
int V;
public:
Graph(int V) { this->V = V; }
void addEdge(int x, int y, int w)
{
edgelist.push_back({ w, x, y });
}
void kruskals_mst()
{
// 1. Sort all edges
sort(edgelist.begin(), edgelist.end());
// Initialize the DSU
DSU s(V);
int ans = 0;
cout << "Following are the edges in the "
"constructed MST"
<< endl;
for (auto edge : edgelist) {
int w = edge[0];
int x = edge[1];
int y = edge[2];
// take that edge in MST if it does form a cycle
if (s.find(x) != s.find(y)) {
s.unite(x, y);
ans += w;
cout << x << " -- " << y << " == " << w
<< endl;
}
}
cout << "Minimum Cost Spanning Tree: \n " << ans;
}
};
int main()
{
Graph g(4);
g.addEdge(0, 1, 10);
g.addEdge(1, 3, 15);
g.addEdge(2, 3, 4);
g.addEdge(2, 0, 6);
g.addEdge(0, 3, 5);
g.kruskals_mst();
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
ios_base::sync_with_stdio(false);
clock_gettime(CLOCK_MONOTONIC, &end);
double time_taken;
time_taken = (end.tv_sec - start.tv_sec) * 1e9;
time_taken = (time_taken + (end.tv_nsec - start.tv_nsec)) * 1e-9;
cout << "Time taken by program is : " << fixed
<< time_taken << setprecision(9);
cout << " sec" << endl;
return 0;
}
5) Kmp algorithm:

#include<iostream>
#include<string.h>
using namespace std;
void prefixSuffixArray(char* pat, int M, int* pps) {
   int length = 0;
   pps[0] = 0;
   int i = 1;
   while (i < M) {
      if (pat[i] == pat[length]) {
         length++;
         pps[i] = length;
         i++;
      } else {
         if (length != 0)
         length = pps[length - 1];
         else {
            pps[i] = 0;
            i++;
         }
      }
   }
}
void KMPAlgorithm(char* text, char* pattern) {
   int M = strlen(pattern);
   int N = strlen(text);
   int pps[M];
   prefixSuffixArray(pattern, M, pps);
   int i = 0;
   int j = 0;
   while (i < N) {
      if (pattern[j] == text[i]) {
         j++;
         i++;
      }
      if (j == M) {
         printf("Found pattern at index %d\n", i - j);
         j = pps[j - 1];
      }
      else if (i < N && pattern[j] != text[i]) {
         if (j != 0)
         j = pps[j - 1];
         else
         i = i + 1;
      }
   }
}
int main() {
   char text[] = "xyztrwqxyzfg";
   char pattern[] = "xyz";
   printf("The pattern is found in the text at the following
index : \n");
   KMPAlgorithm(text, pattern);
   return 0;
}

5) Matrix multiplication:
 
#include<stdio.h>
#include<limits.h>
 
 
int MatrixChainMultiplication(int p[], int n)
{
    int m[n][n];
    int i, j, k, L, q;
 
    for (i=1; i<n; i++)
        m[i][i] = 0;    //number of multiplications are 0(zero) when there is only one matrix
 
    //Here L is chain length. It varies from length 2 to length n.
    for (L=2; L<n; L++)
    {
        for (i=1; i<n-L+1; i++)
        {
            j = i+L-1;
            m[i][j] = INT_MAX;  //assigning to maximum value
 
            for (k=i; k<=j-1; k++)
            {
                q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];
                if (q < m[i][j])
                {
                    m[i][j] = q;    //if number of multiplications found less that number will be updated.
                }
            }
        }
    }
 
    return m[1][n-1];   //returning the final answer which is M[1][n]
 
}
 
int main()
{
    int n,i;
    printf("Enter number of matrices\n");
    scanf("%d",&n);
 
    n++;
 
    int arr[n];
 
    printf("Enter dimensions \n");
 
    for(i=0;i<n;i++)
    {
        printf("Enter d%d :: ",i);
        scanf("%d",&arr[i]);
    }
 
    int size = sizeof(arr)/sizeof(arr[0]);
 
    printf("Minimum number of multiplications is %d ", MatrixChainMultiplication(arr, size));
 
    return 0;
}
6) Rod cutting problems:

1. #include<iostream>
2. #include<climits>
3.  
4. using namespace std;
5.  
6. int rodCutting(int n, int value[])
7. {
8. int i,j;
9.  
10. //we will calculate the maximum attainable value of rod in a bottom up
fashion by first calculating for smaller value of n and then using these values
to calculate higher values of n
11.  
12. //create an array to store the results
13. int result[n+1];
14.  
15. //result[i]=maximum attainable value of rod of size i
16.  
17. //initialization
18. result[0]=0;
19.  
20. //in every iteration, find the result for rod of size i
21. for(i=1;i<=n;i++)
22. {
23. result[i]=INT_MIN;
24.  
25. //try to cut the rod of length i into various values of j and select the
one which gives the maximum value
26. for(j=0;j<i;j++)
27. {
28. result[i]=max(result[i],value[j]+result[i-(j+1)]);
29. }
30. }
31.  
32.  
33. return result[n];
34. }
35.  
36. int main()
37. {
38. int n;
39. cout<<"Enter the length of the rod"<<endl;
40. cin>>n;
41.  
42. int value[n];
43. //value[i]=value of rod of size i+1
44. //value[0]=value of rod of size 1
45. //value[1]=value of rod of size 2
46.  
47. cout<<"Enter the values of pieces of rod of all size"<<endl;
48.  
49. for(int i=0;i<n;i++)
50. cin>>value[i];
51.  
52. cout<<"Maximum obtainable value by cutting up the rod in many pieces
are"<<endl;
53. cout<<rodCutting(n,value);
54.  
55. cout<<endl;
56. return 0;
57. }
}
while (i < n1)
{
arr[k] = L[i]; i++;
k++;
}
while (j < n2)
{
arr[k] = M[j]; j++;
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
int m = l + (r - l) / 2;
mergeSort(arr, l, m); mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
void func()
{
int n, i;
cout<<"Enter number of elements : "; cin>>n;
int arr[n];
cout<<"Enter the elements : "; for(i = 0; i < n; i++)
{
cin>>arr[i];
}
mergeSort(arr, 0, n-1); cout<<"Minimum = "<<arr[0]<<endl; cout<<"Maximum = "<<arr[n-
1]<<endl;
}
int main()
{
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start); ios_base::sync_with_stdio(false);
func(); clock_gettime(CLOCK_MONOTONIC, &end);

You might also like