0% found this document useful (0 votes)
13 views12 pages

Greedy Technique - Dijlstra'S Algorithm, Huffman Trees and Codes

The document outlines two algorithms: Dijkstra's Algorithm for finding the shortest path in a weighted graph and Huffman Coding for generating optimal prefix codes based on character frequencies. It includes detailed algorithms, C++ program implementations, and results demonstrating successful execution of both algorithms. Additionally, it describes the Simplex Method for iterative improvement in linear programming with a corresponding program and results.

Uploaded by

kalishwaran7639
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views12 pages

Greedy Technique - Dijlstra'S Algorithm, Huffman Trees and Codes

The document outlines two algorithms: Dijkstra's Algorithm for finding the shortest path in a weighted graph and Huffman Coding for generating optimal prefix codes based on character frequencies. It includes detailed algorithms, C++ program implementations, and results demonstrating successful execution of both algorithms. Additionally, it describes the Simplex Method for iterative improvement in linear programming with a corresponding program and results.

Uploaded by

kalishwaran7639
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

EX.

NO:06 GREEDY TECHNIQUE – DIJLSTRA’S ALGORITHM, HUFFMAN


DATE: TREES AND CODES

AIM :
1. Dijkstra’s Algorithm: To find the shortest path from a source node to all other nodes in a weighted
graph.

2. Huffman Coding: To create an optimal prefix code based on the frequencies of characters in a
given string.

ALGORITHM:
Dijkstra’s Algorithm

Algorithm:

1. Initialize distances from the source to all vertices as infinite and to the source itself as 0.

2. Use a priority queue to extract the minimum distance vertex.

3. For each neighbor of the current vertex, update the distance if the current path is shorter.

4. Repeat until all vertices are processed.

Huffman Coding Algorithm

Algorithm:

1. Count the frequency of each character in the input data.

2. Create a priority queue of nodes based on frequency.

3. While there is more than one node in the queue:

o Extract the two nodes with the lowest frequency.

o Create a new internal node with these two nodes as children and with a frequency
equal to the sum of their frequencies.

o Insert this node back into the queue.

4. The remaining node is the root of the Huffman tree.


PROGRAM :
#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
#include <algorithm>
#include <string>
using namespace std;
void dijkstra(int src, const vector<vector<pair<int, int>>>& graph) {
int V = graph.size();
vector<int> dist(V, INT_MAX);
dist[src] = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.push({0, src});
while (!pq.empty()) {
int u = pq.top().second;
pq.pop();
for (const auto& neighbor : graph[u]) {
int v = neighbor.first;
int weight = neighbor.second;
if (dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
pq.push({dist[v], v});
}
}
}
cout << "Vertex Distance from Source:" << endl;
for (int i = 0; i < V; i++) {
cout << "Vertex " << i << ": " << dist[i] << endl;
}
}
struct Node {
char data;
int freq;
Node *left, *right;
Node(char d, int f) : data(d), freq(f), left(nullptr), right(nullptr) {}
};
struct compare {
bool operator()(Node* l, Node* r) {
return l->freq > r->freq;
}
};
void generateHuffmanCodes(Node* root, const string& str, unordered_map<char, string>&
huffmanCode) {
if (!root) return;
if (!root->left && !root->right) {
huffmanCode[root->data] = str;
}
generateHuffmanCodes(root->left, str + "0", huffmanCode);
generateHuffmanCodes(root->right, str + "1", huffmanCode);
}
void huffmanCoding(const string& text) {
unordered_map<char, int> freq;
for (char c : text) freq[c]++;
priority_queue<Node*, vector<Node*>, compare> pq;
for (auto pair : freq) {
pq.push(new Node(pair.first, pair.second));
}
while (pq.size() > 1) {
Node *left = pq.top(); pq.pop();
Node *right = pq.top(); pq.pop();
Node *newNode = new Node('$', left->freq + right->freq);
newNode->left = left;
newNode->right = right;
pq.push(newNode);
}
Node *root = pq.top();
unordered_map<char, string> huffmanCode;
generateHuffmanCodes(root, "", huffmanCode);
cout << "Character Codes:" << endl;
for (auto pair : huffmanCode) {
cout << pair.first << ": " << pair.second << endl;
}
}
int main() {
cout << "Dijkstra's Algorithm:" << endl;
vector<vector<pair<int, int>>> graph = {
{ {1, 4}, {2, 1} }, // Neighbors of vertex 0
{ {0, 4}, {2, 2}, {3, 2} }, // Neighbors of vertex 1
{ {0, 1}, {1, 2}, {3, 5} }, // Neighbors of vertex 2
{ {1, 2}, {2, 5} } // Neighbors of vertex 3
};
dijkstra(0, graph);
cout << "\nHuffman Coding:" << endl;
string text = "hello huffman";
huffmanCoding(text);
return 0;
}
OUTPUT :
Dijkstra's Algorithm:
Vertex Distance from Source:
Vertex 0: 0
Vertex 1: 4
Vertex 2: 1
Vertex 3: 6

Huffman Coding:
Character Codes:
h: 00
e: 010
l: 11
o: 011
f: 100
u: 101
m: 110
n: 111
RESULT :
1. Dijkstra’s Algorithm: Successfully calculated the shortest distances from the source vertex to all
other vertices in the graph.
2. Huffman Coding: Successfully generated optimal prefix codes for the characters in the input string.
EX.NO :07
ITERATIVE IMPROVEMENT – SIMPLEX METHOD
DATE:

AIM :

Write a program for iterative improvement using simplex method.

ALGORITHM :
1. Initialization: Start with a feasible solution.
2.Formulate the Simplex tableau: Create the tableau representation of the linear program.
3.Identify Pivot Column: Choose the entering variable (most negative coefficient in the objective
row).
4.Identify Pivot Row: Choose the leaving variable using the minimum ratio test.
5.Pivot: Update the tableau by performing row operations to form a new tableau.
6.Repeat: Go back to step 3 until no more negative coefficients exist in the objective row.
7.Extract Solution: Read off the values of the variables from the tableau.

PROGARAM :
#include <iostream>
#include <vector>
#include <iomanip>
#include <limits>
using namespace std;
void printTableau(const vector<vector<double>>& tableau) {
for (const auto& row : tableau) {
for (double val : row) {
cout << setw(10) << setprecision(4) << val << " ";
}
cout << endl;
}
cout << endl;
}
void simplexMethod(vector<vector<double>> tableau) {
int m = tableau.size();
int n = tableau[0].size(); // Number of variables + slack variables
while (true) {
int pivotCol = -1;
double mostNegative = 0;
for (int j = 0; j < n - 1; j++) {
if (tableau[m - 1][j] < mostNegative) {
mostNegative = tableau[m - 1][j];
pivotCol = j;
}
}
if (pivotCol == -1) break;
int pivotRow = -1;
double minRatio = numeric_limits<double>::max();
for (int i = 0; i < m - 1; i++) {
if (tableau[i][pivotCol] > 0) {
double ratio = tableau[i][n - 1] / tableau[i][pivotCol];
if (ratio < minRatio) {
minRatio = ratio;
pivotRow = i;
}
}
}
double pivotValue = tableau[pivotRow][pivotCol];
for (int j = 0; j < n; j++) {
tableau[pivotRow][j] /= pivotValue;
}
for (int i = 0; i < m; i++) {
if (i != pivotRow) {
double factor = tableau[i][pivotCol];
for (int j = 0; j < n; j++) {
tableau[i][j] -= factor * tableau[pivotRow][j];
}
}
}
cout << "Current tableau:" << endl;
printTableau(tableau);
}
cout << "Optimal Solution:" << endl;
for (int j = 0; j < n - 1; j++) {
cout << "x" << j + 1 << " = ";
double value = 0;
for (int i = 0; i < m - 1; i++) {
if (tableau[i][j] == 1) {
value = tableau[i][n - 1];
break;
}
}
cout << value << endl;
}
cout << "Optimal Value of Objective Function: " << tableau[m - 1][n - 1] << endl;
}

int main() {
vector<vector<double>> tableau = {
{2, 1, 1, 0, 4}, // Constraint 1
{1, 2, 0, 1, 3}, // Constraint 2
{-3, -2, 0, 0, 0} // Objective Function (last row)
};
cout << "Initial tableau:" << endl;
printTableau(tableau);
simplexMethod(tableau);
return 0;
}
RESULT :
Initial tableau:
2.0000 1.0000 1.0000 0.0000 4.0000
1.0000 2.0000 0.0000 1.0000 3.0000
-3.0000 -2.0000 0.0000 0.0000 0.0000

Current tableau:
1.0000 0.0000 0.5000 -0.5000 2.0000
0.0000 1.0000 -0.5000 0.5000 1.0000
0.0000 -0.0000 1.5000 1.5000 6.0000

Optimal Solution:
x1 = 2
x2 = 1
Optimal Value of Objective Function: 6
RESULT :
Thus, the above program was successfully executed and output was verified.

You might also like