mirror of
https://github.com/TheAlgorithms/C-Plus-Plus.git
synced 2026-11-29 15:36:06 +08:00
Greedy Algorithms -> greedy_algorithms (#647)
This commit is contained in:
145
greedy_algorithms/Dijkstra.cpp
Normal file
145
greedy_algorithms/Dijkstra.cpp
Normal file
@@ -0,0 +1,145 @@
|
||||
#include <iostream>
|
||||
#include <limits.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
//Wrapper class for storing a graph
|
||||
class Graph
|
||||
{
|
||||
public:
|
||||
int vertexNum;
|
||||
int **edges;
|
||||
|
||||
//Constructs a graph with V vertices and E edges
|
||||
Graph(const int V)
|
||||
{
|
||||
|
||||
// initializes the array edges.
|
||||
this->edges = new int *[V];
|
||||
for (int i = 0; i < V; i++)
|
||||
{
|
||||
edges[i] = new int[V];
|
||||
}
|
||||
|
||||
// fills the array with zeros.
|
||||
for (int i = 0; i < V; i++)
|
||||
{
|
||||
for (int j = 0; j < V; j++)
|
||||
{
|
||||
edges[i][j] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
this->vertexNum = V;
|
||||
}
|
||||
|
||||
//Adds the given edge to the graph
|
||||
void addEdge(int src, int dst, int weight)
|
||||
{
|
||||
this->edges[src][dst] = weight;
|
||||
}
|
||||
};
|
||||
//Utility function to find minimum distance vertex in mdist
|
||||
int minDistance(int mdist[], bool vset[], int V)
|
||||
{
|
||||
int minVal = INT_MAX, minInd = 0;
|
||||
for (int i = 0; i < V; i++)
|
||||
{
|
||||
if (!vset[i] && (mdist[i] < minVal))
|
||||
{
|
||||
minVal = mdist[i];
|
||||
minInd = i;
|
||||
}
|
||||
}
|
||||
|
||||
return minInd;
|
||||
}
|
||||
|
||||
//Utility function to print distances
|
||||
void print(int dist[], int V)
|
||||
{
|
||||
cout << "\nVertex Distance" << endl;
|
||||
for (int i = 0; i < V; i++)
|
||||
{
|
||||
if (dist[i] < INT_MAX)
|
||||
cout << i << "\t" << dist[i] << endl;
|
||||
else
|
||||
cout << i << "\tINF" << endl;
|
||||
}
|
||||
}
|
||||
|
||||
//The main function that finds the shortest path from given source
|
||||
//to all other vertices using Dijkstra's Algorithm.It doesn't work on negative
|
||||
//weights
|
||||
void Dijkstra(Graph graph, int src)
|
||||
{
|
||||
int V = graph.vertexNum;
|
||||
int mdist[V]; //Stores updated distances to vertex
|
||||
bool vset[V]; // vset[i] is true if the vertex i included
|
||||
// in the shortest path tree
|
||||
|
||||
//Initialise mdist and vset. Set distance of source as zero
|
||||
for (int i = 0; i < V; i++)
|
||||
{
|
||||
mdist[i] = INT_MAX;
|
||||
vset[i] = false;
|
||||
}
|
||||
|
||||
mdist[src] = 0;
|
||||
|
||||
//iterate to find shortest path
|
||||
for (int count = 0; count < V - 1; count++)
|
||||
{
|
||||
int u = minDistance(mdist, vset, V);
|
||||
|
||||
vset[u] = true;
|
||||
|
||||
for (int v = 0; v < V; v++)
|
||||
{
|
||||
if (!vset[v] && graph.edges[u][v] && mdist[u] + graph.edges[u][v] < mdist[v])
|
||||
{
|
||||
mdist[v] = mdist[u] + graph.edges[u][v];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
print(mdist, V);
|
||||
}
|
||||
|
||||
//Driver Function
|
||||
int main()
|
||||
{
|
||||
int V, E, gsrc;
|
||||
int src, dst, weight;
|
||||
cout << "Enter number of vertices: ";
|
||||
cin >> V;
|
||||
cout << "Enter number of edges: ";
|
||||
cin >> E;
|
||||
Graph G(V);
|
||||
for (int i = 0; i < E; i++)
|
||||
{
|
||||
cout << "\nEdge " << i + 1 << "\nEnter source: ";
|
||||
cin >> src;
|
||||
cout << "Enter destination: ";
|
||||
cin >> dst;
|
||||
cout << "Enter weight: ";
|
||||
cin >> weight;
|
||||
|
||||
// makes sure source and destionation are in the proper bounds.
|
||||
if (src >= 0 && src < V && dst >= 0 && dst < V)
|
||||
{
|
||||
G.addEdge(src, dst, weight);
|
||||
}
|
||||
else
|
||||
{
|
||||
cout << "source and/or destination out of bounds" << endl;
|
||||
i--;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
cout << "\nEnter source:";
|
||||
cin >> gsrc;
|
||||
Dijkstra(G, gsrc);
|
||||
|
||||
return 0;
|
||||
}
|
||||
92
greedy_algorithms/Knapsack.cpp
Normal file
92
greedy_algorithms/Knapsack.cpp
Normal file
@@ -0,0 +1,92 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
struct Item
|
||||
{
|
||||
int weight;
|
||||
int profit;
|
||||
};
|
||||
|
||||
float profitPerUnit(Item x)
|
||||
{
|
||||
return (float)x.profit / (float)x.weight;
|
||||
}
|
||||
|
||||
int partition(Item arr[], int low, int high)
|
||||
{
|
||||
Item pivot = arr[high]; // pivot
|
||||
int i = (low - 1); // Index of smaller element
|
||||
|
||||
for (int j = low; j < high; j++)
|
||||
{
|
||||
// If current element is smaller than or
|
||||
// equal to pivot
|
||||
if (profitPerUnit(arr[j]) <= profitPerUnit(pivot))
|
||||
{
|
||||
i++; // increment index of smaller element
|
||||
Item temp = arr[i];
|
||||
arr[i] = arr[j];
|
||||
arr[j] = temp;
|
||||
}
|
||||
}
|
||||
Item temp = arr[i + 1];
|
||||
arr[i + 1] = arr[high];
|
||||
arr[high] = temp;
|
||||
return (i + 1);
|
||||
}
|
||||
|
||||
void quickSort(Item arr[], int low, int high)
|
||||
{
|
||||
if (low < high)
|
||||
{
|
||||
|
||||
int p = partition(arr, low, high);
|
||||
|
||||
quickSort(arr, low, p - 1);
|
||||
quickSort(arr, p + 1, high);
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
cout << "\nEnter the capacity of the knapsack : ";
|
||||
float capacity;
|
||||
cin >> capacity;
|
||||
cout << "\n Enter the number of Items : ";
|
||||
int n;
|
||||
cin >> n;
|
||||
Item itemArray[n];
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
cout << "\nEnter the weight and profit of item " << i + 1 << " : ";
|
||||
cin >> itemArray[i].weight;
|
||||
cin >> itemArray[i].profit;
|
||||
}
|
||||
|
||||
quickSort(itemArray, 0, n - 1);
|
||||
|
||||
// show(itemArray, n);
|
||||
|
||||
float maxProfit = 0;
|
||||
int i = n;
|
||||
while (capacity > 0 && --i >= 0)
|
||||
{
|
||||
if (capacity >= itemArray[i].weight)
|
||||
{
|
||||
maxProfit += itemArray[i].profit;
|
||||
capacity -= itemArray[i].weight;
|
||||
cout << "\n\t" << itemArray[i].weight << "\t" << itemArray[i].profit;
|
||||
}
|
||||
else
|
||||
{
|
||||
maxProfit += profitPerUnit(itemArray[i]) * capacity;
|
||||
cout << "\n\t" << capacity << "\t" << profitPerUnit(itemArray[i]) * capacity;
|
||||
capacity = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
cout << "\nMax Profit : " << maxProfit;
|
||||
|
||||
return 0;
|
||||
}
|
||||
37
greedy_algorithms/Kruskals Minimum Spanning Tree.cpp
Normal file
37
greedy_algorithms/Kruskals Minimum Spanning Tree.cpp
Normal file
@@ -0,0 +1,37 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
#define V 6
|
||||
#define INFINITY 99999
|
||||
|
||||
int graph[V][V] = {
|
||||
{0, 4, 1, 4, INFINITY, INFINITY},
|
||||
{4, 0, 3, 8, 3, INFINITY},
|
||||
{1, 3, 0, INFINITY, 1, INFINITY},
|
||||
{4, 8, INFINITY, 0, 5, 7},
|
||||
{INFINITY, 3, 1, 5, 0, INFINITY},
|
||||
{INFINITY, INFINITY, INFINITY, 7, INFINITY, 0}};
|
||||
|
||||
void findMinimumEdge()
|
||||
{
|
||||
for (int i = 0; i < V; i++)
|
||||
{
|
||||
int min = INFINITY;
|
||||
int minIndex = 0;
|
||||
for (int j = 0; j < V; j++)
|
||||
{
|
||||
if (graph[i][j] != 0 && graph[i][j] < min)
|
||||
{
|
||||
min = graph[i][j];
|
||||
minIndex = j;
|
||||
}
|
||||
}
|
||||
cout << i << " - " << minIndex << "\t" << graph[i][minIndex] << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
findMinimumEdge();
|
||||
return 0;
|
||||
}
|
||||
79
greedy_algorithms/Prims Minimum Spanning Tree.cpp
Normal file
79
greedy_algorithms/Prims Minimum Spanning Tree.cpp
Normal file
@@ -0,0 +1,79 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
#define V 4
|
||||
#define INFINITY 99999
|
||||
|
||||
int graph[V][V] = {
|
||||
{0, 5, 1, 2},
|
||||
{5, 0, 3, 3},
|
||||
{1, 3, 0, 4},
|
||||
{2, 3, 4, 0}};
|
||||
|
||||
struct mst
|
||||
{
|
||||
bool visited;
|
||||
int key;
|
||||
int near;
|
||||
};
|
||||
|
||||
mst MST_Array[V];
|
||||
|
||||
void initilize()
|
||||
{
|
||||
for (int i = 0; i < V; i++)
|
||||
{
|
||||
MST_Array[i].visited = false;
|
||||
MST_Array[i].key = INFINITY; // considering INFINITY as inifinity
|
||||
MST_Array[i].near = i;
|
||||
}
|
||||
|
||||
MST_Array[0].key = 0;
|
||||
}
|
||||
|
||||
void updateNear()
|
||||
{
|
||||
for (int v = 0; v < V; v++)
|
||||
{
|
||||
int min = INFINITY;
|
||||
int minIndex = 0;
|
||||
for (int i = 0; i < V; i++)
|
||||
{
|
||||
if (MST_Array[i].key < min && MST_Array[i].visited == false && MST_Array[i].key != INFINITY)
|
||||
{
|
||||
min = MST_Array[i].key;
|
||||
minIndex = i;
|
||||
}
|
||||
}
|
||||
|
||||
MST_Array[minIndex].visited = true;
|
||||
|
||||
for (int i = 0; i < V; i++)
|
||||
{
|
||||
if (graph[minIndex][i] != 0 && graph[minIndex][i] < INFINITY)
|
||||
{
|
||||
if (graph[minIndex][i] < MST_Array[i].key)
|
||||
{
|
||||
MST_Array[i].key = graph[minIndex][i];
|
||||
MST_Array[i].near = minIndex;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void show()
|
||||
{
|
||||
for (int i = 0; i < V; i++)
|
||||
{
|
||||
cout << i << " - " << MST_Array[i].near << "\t" << graph[i][MST_Array[i].near] << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
initilize();
|
||||
updateNear();
|
||||
show();
|
||||
return 0;
|
||||
}
|
||||
109
greedy_algorithms/huffman.cpp
Normal file
109
greedy_algorithms/huffman.cpp
Normal file
@@ -0,0 +1,109 @@
|
||||
// C++ program for Huffman Coding
|
||||
#include <iostream>
|
||||
#include <queue>
|
||||
using namespace std;
|
||||
|
||||
// A Huffman tree node
|
||||
struct MinHeapNode {
|
||||
|
||||
// One of the input characters
|
||||
char data;
|
||||
|
||||
// Frequency of the character
|
||||
unsigned freq;
|
||||
|
||||
// Left and right child
|
||||
MinHeapNode *left, *right;
|
||||
|
||||
MinHeapNode(char data, unsigned freq)
|
||||
|
||||
{
|
||||
|
||||
left = right = NULL;
|
||||
this->data = data;
|
||||
this->freq = freq;
|
||||
}
|
||||
};
|
||||
|
||||
// For comparison of
|
||||
// two heap nodes (needed in min heap)
|
||||
struct compare {
|
||||
|
||||
bool operator()(MinHeapNode* l, MinHeapNode* r)
|
||||
|
||||
{
|
||||
return (l->freq > r->freq);
|
||||
}
|
||||
};
|
||||
|
||||
// Prints huffman codes from
|
||||
// the root of Huffman Tree.
|
||||
void printCodes(struct MinHeapNode* root, string str)
|
||||
{
|
||||
|
||||
if (!root)
|
||||
return;
|
||||
|
||||
if (root->data != '$')
|
||||
cout << root->data << ": " << str << "\n";
|
||||
|
||||
printCodes(root->left, str + "0");
|
||||
printCodes(root->right, str + "1");
|
||||
}
|
||||
|
||||
// The main function that builds a Huffman Tree and
|
||||
// print codes by traversing the built Huffman Tree
|
||||
void HuffmanCodes(char data[], int freq[], int size)
|
||||
{
|
||||
struct MinHeapNode *left, *right, *top;
|
||||
|
||||
// Create a min heap & inserts all characters of data[]
|
||||
priority_queue<MinHeapNode*, vector<MinHeapNode*>, compare> minHeap;
|
||||
|
||||
for (int i = 0; i < size; ++i)
|
||||
minHeap.push(new MinHeapNode(data[i], freq[i]));
|
||||
|
||||
// Iterate while size of heap doesn't become 1
|
||||
while (minHeap.size() != 1) {
|
||||
|
||||
// Extract the two minimum
|
||||
// freq items from min heap
|
||||
left = minHeap.top();
|
||||
minHeap.pop();
|
||||
|
||||
right = minHeap.top();
|
||||
minHeap.pop();
|
||||
|
||||
// Create a new internal node with
|
||||
// frequency equal to the sum of the
|
||||
// two nodes frequencies. Make the
|
||||
// two extracted node as left and right children
|
||||
// of this new node. Add this node
|
||||
// to the min heap '$' is a special value
|
||||
// for internal nodes, not used
|
||||
top = new MinHeapNode('$', left->freq + right->freq);
|
||||
|
||||
top->left = left;
|
||||
top->right = right;
|
||||
|
||||
minHeap.push(top);
|
||||
}
|
||||
|
||||
// Print Huffman codes using
|
||||
// the Huffman tree built above
|
||||
printCodes(minHeap.top(), "");
|
||||
}
|
||||
|
||||
// Driver program to test above functions
|
||||
int main()
|
||||
{
|
||||
|
||||
char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
|
||||
int freq[] = { 5, 9, 12, 13, 16, 45 };
|
||||
|
||||
int size = sizeof(arr) / sizeof(arr[0]);
|
||||
|
||||
HuffmanCodes(arr, freq, size);
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user