0% found this document useful (0 votes)
17 views27 pages

DAA CAT2

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

DAA CAT2

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

GREEDY TECHNIQUES:

FRACTIONAL KNAPSACK
#include <iostream>

#include <vector>

#include <algorithm> // For sort function

using namespace std;

// Structure for an item that stores weight and value

struct Item {

int value, weight;

// Constructor

Item(int value, int weight) : value(value), weight(weight) {}

};

// Comparison function to sort items by value/weight ratio

bool compare(Item a, Item b) {

double r1 = (double)a.value / a.weight;

double r2 = (double)b.value / b.weight;

return r1 > r2;

// Function to get the maximum value in a fractional knapsack

double fractionalKnapsack(int W, vector<Item>& items) {

// Sort items by value-to-weight ratio in decreasing order

sort(items.begin(), items.end(), compare);

double totalValue = 0.0; // Total value accumulated in the knapsack

int currentWeight = 0; // Current weight in the knapsack

// Loop through each item

for (Item item : items) {

if (currentWeight + item.weight <= W) {

// If the full item can be added, add it

currentWeight += item.weight;
totalValue += item.value;

} else {

// Otherwise, take the fraction of the item that fits

int remainingWeight = W - currentWeight;

totalValue += item.value * ((double)remainingWeight / item.weight);

break; // Knapsack is full, break the loop

return totalValue;

int main() {

int n, W;

// Take the number of items from the user

cout << "Enter the number of items: ";

cin >> n;

// Take the maximum capacity of the knapsack

cout << "Enter the maximum capacity of the knapsack: ";

cin >> W;

vector<Item> items;

// Take value and weight for each item

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

int value, weight;

cout << "Enter value and weight of item " << i + 1 << ": ";

cin >> value >> weight;

items.push_back(Item(value, weight));

// Call the fractional knapsack function

double maxValue = fractionalKnapsack(W, items);


// Output the result

cout << "Maximum value in Knapsack: " << maxValue << endl;

return 0;

HUFFMAN CODING
#include <iostream>

#include <queue>

#include <unordered_map>

#include <vector>

using namespace std;

// A Huffman tree node

struct Node {

char ch;

int freq;

Node* left;

Node* right;

Node(char character, int frequency) : ch(character), freq(frequency), left(nullptr), right(nullptr)


{}

};

// Comparison object to be used to order the heap

struct Compare {

bool operator()(Node* left, Node* right) {

return left->freq > right->freq;

};

// Function to print the Huffman codes from the root of the Huffman tree

void printCodes(Node* root, string str) {

if (!root) {

return;

}
// If this is a leaf node, it contains a character

if (!root->left && !root->right) {

cout << root->ch << ": " << str << "\n";

// Recursive calls to traverse the tree

printCodes(root->left, str + "0");

printCodes(root->right, str + "1");

// Function to build the Huffman Tree and generate the codes

void huffmanCoding(unordered_map<char, int>& freqMap) {

// Priority queue to store the forest of trees

priority_queue<Node*, vector<Node*>, Compare> minHeap;

// Create a leaf node for each character and add it to the priority queue

for (auto& pair : freqMap) {

minHeap.push(new Node(pair.first, pair.second));

// Iterate while the size of the heap is greater than 1

while (minHeap.size() > 1) {

// Extract the two nodes with the lowest frequency

Node* left = minHeap.top();

minHeap.pop();

Node* right = minHeap.top();

minHeap.pop();

// Create a new internal node with a frequency equal to the sum of the two nodes' frequencies

Node* newNode = new Node('$', left->freq + right->freq);

newNode->left = left;

newNode->right = right;

// Add the new node to the priority queue

minHeap.push(newNode);
}

// The root of the Huffman Tree

Node* root = minHeap.top();

// Print the Huffman codes by traversing the tree

printCodes(root, "");

int main() {

int n;

unordered_map<char, int> freqMap;

// Take user input for the number of characters

cout << "Enter the number of characters: ";

cin >> n;

// Take user input for each character and its frequency

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

char ch;

int freq;

cout << "Enter character " << i + 1 << " and its frequency: ";

cin >> ch >> freq;

freqMap[ch] = freq;

// Call the Huffman coding function

huffmanCoding(freqMap);

return 0;

}
DYNAMIC PROGRAMMING:
ASSEMBLY LINE SCHD.
#include <iostream>

#include <vector>

#include <algorithm>

#include <limits>

using namespace std;

int assemblyLineScheduling(int n, vector<int>& a, vector<int>& b, vector<int>& t, int T1, int T2)


{

vector<int> dp1(n); // Time taken to finish all tasks on line 1

vector<int> dp2(n); // Time taken to finish all tasks on line 2

// Base cases

dp1[0] = T1 + a[0]; // Entry time + processing time on line 1

dp2[0] = T2 + b[0]; // Entry time + processing time on line 2

// Fill the dp arrays

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

dp1[i] = min(dp1[i - 1] + a[i], dp2[i - 1] + t[i - 1] + a[i]); // Coming from line 1 or switching
from line 2

dp2[i] = min(dp2[i - 1] + b[i], dp1[i - 1] + t[i - 1] + b[i]); // Coming from line 2 or switching
from line 1

// Return the minimum time to complete all tasks

return min(dp1[n - 1], dp2[n - 1]);

int main() {

int n;

// Take user input for the number of tasks

cout << "Enter the number of tasks: ";

cin >> n;
vector<int> a(n), b(n), t(n - 1);

// Take user input for processing times on line 1

cout << "Enter processing times on line 1 for each task: ";

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

cin >> a[i];

// Take user input for processing times on line 2

cout << "Enter processing times on line 2 for each task: ";

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

cin >> b[i];

// Take user input for switch times between lines

cout << "Enter switch times between lines for each task (except the last task): ";

for (int i = 0; i < n - 1; i++) {

cin >> t[i];

int T1, T2;

// Take user input for entry times

cout << "Enter entry time for line 1: ";

cin >> T1;

cout << "Enter entry time for line 2: ";

cin >> T2;

// Calculate the minimum time to complete all tasks

int minTime = assemblyLineScheduling(n, a, b, t, T1, T2);

// Output the result

cout << "Minimum time to complete all tasks: " << minTime << endl;

return 0;

DYNAMIC PROGRAMMING:
MATRIX CHAIN MULTIPLICATION
#include <iostream>

#include <vector>

#include <climits> // For INT_MAX

using namespace std;

// Function to find the minimum number of scalar multiplications

int matrixChainMultiplication(vector<int>& p, int n) {

// Create a 2D DP table to store the minimum multiplication costs

vector<vector<int>> m(n, vector<int>(n, 0));

// m[i][i] is zero because a single matrix doesn't need any multiplications

for (int len = 2; len < n; len++) { // len is the chain length

for (int i = 1; i < n - len + 1; i++) {

int j = i + len - 1;

m[i][j] = INT_MAX; // Initialize to a large value

// Find the minimum cost by trying all possible splits

for (int k = i; k <= j - 1; k++) {

// q = cost of splitting at k

int q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j];

if (q < m[i][j]) {

m[i][j] = q;

// Return the minimum cost of multiplying matrices from 1 to n-1

return m[1][n - 1];

int main() {

// Dimensions of the matrices


vector<int> p = {10, 20, 30, 40, 30}; // 4 matrices: 10x20, 20x30, 30x40, 40x30

int n = p.size();

// Call the matrix chain multiplication function

int minMultiplications = matrixChainMultiplication(p, n);

// Output the result

cout << "Minimum number of scalar multiplications: " << minMultiplications << endl;

return 0;

LONGEST COMMON SUBSEQUENCE


#include <iostream>

#include <vector>

#include <string>

using namespace std;

// Function to find the length of the longest common subsequence

int LCS(const string &X, const string &Y) {

int m = X.length();

int n = Y.length();

// Create a 2D table to store the length of LCS

vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));

// Build the dp table in a bottom-up manner

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

for (int j = 1; j <= n; j++) {

if (X[i - 1] == Y[j - 1]) {

dp[i][j] = dp[i - 1][j - 1] + 1;

} else {

dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);

}
}

// The last cell of dp contains the length of the LCS

return dp[m][n];

// Function to print the longest common subsequence

string getLCS(const string &X, const string &Y, const vector<vector<int>> &dp) {

int i = X.length();

int j = Y.length();

string lcs = "";

// Trace the LCS from the dp table

while (i > 0 && j > 0) {

if (X[i - 1] == Y[j - 1]) {

lcs = X[i - 1] + lcs; // Add the character to the result

i--;

j--;

} else if (dp[i - 1][j] > dp[i][j - 1]) {

i--;

} else {

j--;

return lcs;

int main() {

string X, Y;

cout << "Enter the first string: ";

cin >> X;

cout << "Enter the second string: ";

cin >> Y;

// Calculate LCS length and construct the DP table

int m = X.length();
int n = Y.length();

vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));

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

for (int j = 1; j <= n; j++) {

if (X[i - 1] == Y[j - 1]) {

dp[i][j] = dp[i - 1][j - 1] + 1;

} else {

dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);

// Get the LCS string

string lcs = getLCS(X, Y, dp);

// Output the length of the LCS and the LCS string

cout << "Length of the longest common subsequence: " << dp[m][n] << endl;

cout << "Longest common subsequence: " << lcs << endl;

return 0;

0/1 KNAPSACK PROBLEM


#include <iostream>

#include <vector>

using namespace std;

// Function to solve the 0/1 Knapsack problem using dynamic programming

int knapsack(int W, const vector<int> &weights, const vector<int> &values, int n) {

// Create a DP table with dimensions (n+1) x (W+1)

vector<vector<int>> dp(n + 1, vector<int>(W + 1, 0));

// Build the dp table in a bottom-up manner

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


for (int w = 1; w <= W; w++) {

// If the current item's weight is less than or equal to the current capacity

if (weights[i - 1] <= w) {

// Maximize the value by either including or excluding the current item

dp[i][w] = max(dp[i - 1][w], dp[i - 1][w - weights[i - 1]] + values[i - 1]);

} else {

// If the current item's weight exceeds the current capacity, skip the item

dp[i][w] = dp[i - 1][w];

// The last cell of dp contains the maximum value

return dp[n][W];

int main() {

int n, W;

// Input number of items and knapsack capacity

cout << "Enter the number of items: ";

cin >> n;

cout << "Enter the capacity of the knapsack: ";

cin >> W;

vector<int> weights(n), values(n);

// Input weights and values of the items

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

cout << "Enter value and weight for item " << i + 1 << ": ";

cin >> values[i] >> weights[i];

// Calculate the maximum value that can be obtained

int maxValue = knapsack(W, weights, values, n);


// Output the result

cout << "Maximum value in the knapsack: " << maxValue << endl;

return 0;

TRAVELLING SALESMAN PROBLEM


#include <iostream>

#include <vector>

#include <climits>

#include <cmath>

using namespace std;

// Define a very large value representing infinity

#define INF 1000000000

// Function to solve the Traveling Salesman Problem using dynamic programming

int tsp(int n, const vector<vector<int>>& dist) {

// DP table: dp[mask][i] -> minimum distance to visit all cities in mask and end at city i

vector<vector<int>> dp(1 << n, vector<int>(n, INF));

// Base case: start at city 0 with only city 0 visited

dp[1][0] = 0;

// Iterate over all possible subsets of cities (bitmask representation)

for (int mask = 1; mask < (1 << n); mask++) {

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

// If city i is not visited in this subset, skip it

if (!(mask & (1 << i))) continue;

// Try moving from city j to city i

for (int j = 0; j < n; j++) {

if (i != j && (mask & (1 << j))) {

dp[mask][i] = min(dp[mask][i], dp[mask ^ (1 << i)][j] + dist[j][i]);

}
}

// Find the minimum cost to return to the starting city (city 0)

int result = INF;

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

result = min(result, dp[(1 << n) - 1][i] + dist[i][0]);

return result;

int main() {

int n;

// Input the number of cities

cout << "Enter the number of cities: ";

cin >> n;

// Input the distance matrix

vector<vector<int>> dist(n, vector<int>(n));

cout << "Enter the distance matrix (nxn):" << endl;

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

for (int j = 0; j < n; j++) {

cin >> dist[i][j];

// Solve the TSP and output the result

int minCost = tsp(n, dist);

cout << "The minimum cost of the tour is: " << minCost << endl;

return 0;

}
BACKTRACKING:
N – QUEENS PROBLEM
#include <iostream>

#include <vector>

using namespace std;

// Function to check if a queen can be placed at board[row][col]

bool isSafe(const vector<vector<int>>& board, int row, int col, int N) {

// Check the row on the left side

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

if (board[row][i]) {

return false;

// Check the upper diagonal on the left side

for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {

if (board[i][j]) {

return false;

// Check the lower diagonal on the left side

for (int i = row, j = col; i < N && j >= 0; i++, j--) {

if (board[i][j]) {

return false;

return true;

// Function to print the board configuration

void printBoard(const vector<vector<int>>& board, int N) {

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


for (int j = 0; j < N; j++) {

cout << (board[i][j] ? "Q " : ". ");

cout << endl;

cout << endl;

// Recursive utility function to solve the N-Queens problem

bool solveNQueensUtil(vector<vector<int>>& board, int col, int N) {

// Base case: If all queens are placed

if (col >= N) {

return true;

// Consider this column and try placing this queen in all rows one by one

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

if (isSafe(board, i, col, N)) {

// Place this queen

board[i][col] = 1;

// Recur to place the rest of the queens

if (solveNQueensUtil(board, col + 1, N)) {

return true;

// If placing the queen leads to a solution, keep it; otherwise, backtrack

board[i][col] = 0; // Backtrack

// If no queen can be placed in this column, return false

return false;

// Function to solve the N-Queens problem


bool solveNQueens(int N) {

// Initialize the chessboard with 0s

vector<vector<int>> board(N, vector<int>(N, 0));

// Call the utility function to solve the problem

if (solveNQueensUtil(board, 0, N)) {

printBoard(board, N); // Print the solution

return true;

} else {

cout << "No solution exists for " << N << " queens." << endl;

return false;

int main() {

int N;

cout << "Enter the number of queens (N): ";

cin >> N;

// Solve the N-Queens problem

solveNQueens(N);

return 0;

SUBEST SUM
#include <iostream>

#include <vector>

using namespace std;


// Function to print a subset

void printSubset(const vector<int>& subset) {

cout << "{ ";

for (int num : subset) {

cout << num << " ";

cout << "}" << endl;

// Backtracking function to find subsets with the target sum

void subsetSumUtil(const vector<int>& set, vector<int>& subset, int index, int currentSum, int
targetSum) {

// Base case: If the current sum matches the target sum, print the subset

if (currentSum == targetSum) {

printSubset(subset);

return;

// If the current sum exceeds the target sum or if we've processed all elements, return

if (index >= set.size() || currentSum > targetSum) {

return;

// Include the current element in the subset and recurse

subset.push_back(set[index]);

subsetSumUtil(set, subset, index + 1, currentSum + set[index], targetSum);

// Exclude the current element from the subset (backtrack) and recurse

subset.pop_back();

subsetSumUtil(set, subset, index + 1, currentSum, targetSum);

// Function to initiate the backtracking algorithm for the subset sum problem

void subsetSum(const vector<int>& set, int targetSum) {

vector<int> subset; // To store the current subset

subsetSumUtil(set, subset, 0, 0, targetSum);


}

int main() {

int n, targetSum;

// Input the size of the set

cout << "Enter the number of elements in the set: ";

cin >> n;

// Input the set elements

vector<int> set(n);

cout << "Enter the elements of the set: ";

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

cin >> set[i];

// Input the target sum

cout << "Enter the target sum: ";

cin >> targetSum;

// Call the subset sum function

cout << "Subsets with sum " << targetSum << " are:" << endl;

subsetSum(set, targetSum);

return 0;

GRAPH COLORING
#include <iostream>

#include <vector>

using namespace std;


// Function to check if it is safe to assign color 'c' to vertex 'v'

bool isSafe(int v, const vector<vector<int>>& graph, const vector<int>& color, int c) {

// Check all adjacent vertices

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

if (graph[v][i] == 1 && color[i] == c) { // If adjacent vertex has the same color

return false;

return true;

// Recursive utility function to solve graph coloring problem

bool graphColoringUtil(const vector<vector<int>>& graph, int m, vector<int>& color, int v) {

// Base case: If all vertices are assigned a color

if (v == graph.size()) {

return true;

// Consider this vertex v and try different colors

for (int c = 1; c <= m; c++) {

// Check if assigning color c to vertex v is safe

if (isSafe(v, graph, color, c)) {

color[v] = c; // Assign color c

// Recur to assign colors to the rest of the vertices

if (graphColoringUtil(graph, m, color, v + 1)) {

return true;

// If assigning color c doesn't lead to a solution, backtrack

color[v] = 0;

// If no color can be assigned to this vertex, return false

return false;
}

// Function to solve the m-coloring problem

bool graphColoring(const vector<vector<int>>& graph, int m) {

vector<int> color(graph.size(), 0); // Initialize all vertices as uncolored

// Call graphColoringUtil() to solve the problem

if (!graphColoringUtil(graph, m, color, 0)) {

cout << "No solution exists with " << m << " colors." << endl;

return false;

// Print the solution

cout << "Solution exists with the following colors assigned:" << endl;

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

cout << "Vertex " << i + 1 << " -> Color " << color[i] << endl;

return true;

int main() {

int V, E, m;

// Input the number of vertices and edges

cout << "Enter the number of vertices: ";

cin >> V;

cout << "Enter the number of edges: ";

cin >> E;

// Create the graph as an adjacency matrix

vector<vector<int>> graph(V, vector<int>(V, 0));

cout << "Enter the edges (u v) where there is an edge between vertex u and vertex v:" << endl;

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

int u, v;

cin >> u >> v;


graph[u - 1][v - 1] = 1; // Mark the edge between u and v

graph[v - 1][u - 1] = 1; // Since the graph is undirected

// Input the number of colors

cout << "Enter the number of colors: ";

cin >> m;

// Solve the graph coloring problem

graphColoring(graph, m);

return 0;

STRING MATCHING :
NAIVE STRING MATCHING ALG.
#include <iostream>

#include <string>

using namespace std;

// Naive string matching algorithm

void naiveStringMatching(const string &text, const string &pattern) {

int n = text.length(); // Length of the text

int m = pattern.length(); // Length of the pattern

// Iterate through the text

for (int i = 0; i <= n - m; i++) {

int j;

// Check for a match

for (j = 0; j < m; j++) {

if (text[i + j] != pattern[j]) {

break; // Mismatch found

// If we found a match

if (j == m) {
cout << "Pattern found at index: " << i << endl;

int main() {

string text, pattern;

cout << "Enter the text: ";

getline(cin, text); // Read full line for text

cout << "Enter the pattern: ";

getline(cin, pattern); // Read full line for pattern

naiveStringMatching(text, pattern);

return 0;

KMP ALGORITHM
#include <iostream>

#include <vector>

#include <string>

using namespace std;

// Function to preprocess the pattern and create the LPS (Longest Prefix Suffix) array

void computeLPSArray(const string &pattern, vector<int> &lps) {

int length = 0; // Length of previous longest prefix suffix

lps[0] = 0; // lps[0] is always 0

int i = 1;

// Loop to fill lps array

while (i < pattern.length()) {

if (pattern[i] == pattern[length]) {

length++;

lps[i] = length;

i++;

} else {
// Mismatch after length matches

if (length != 0) {

length = lps[length - 1]; // Use the previously computed lps

} else {

lps[i] = 0;

i++;

// Function to implement KMP algorithm

void KMPsearch(const string &text, const string &pattern) {

int n = text.length();

int m = pattern.length();

vector<int> lps(m); // Create LPS array

computeLPSArray(pattern, lps); // Preprocess the pattern

int i = 0; // Index for text

int j = 0; // Index for pattern

while (i < n) {

if (pattern[j] == text[i]) {

i++;

j++;

// If j equals m, then a match is found

if (j == m) {

cout << "Pattern found at index: " << (i - j) << endl;

j = lps[j - 1]; // Get the next position from the LPS

// Mismatch after j matches

else if (i < n && pattern[j] != text[i]) {

// Do not match lps[0..lps[j-1]] characters


if (j != 0) {

j = lps[j - 1];

} else {

i++;

int main() {

string text, pattern;

cout << "Enter the text: ";

getline(cin, text); // Read full line for text

cout << "Enter the pattern: ";

getline(cin, pattern); // Read full line for pattern

KMPsearch(text, pattern);

return 0;

RABIN – KARP ALGORITHM


#include <iostream>

#include <string>

using namespace std;

// Function to implement Rabin-Karp Algorithm

void rabinKarp(const string& text, const string& pattern, int d, int q) {

int n = text.size();

int m = pattern.size();

int h = 1; // The value of d^(m-1) to be used in rolling hash

int p = 0; // Hash value for the pattern

int t = 0; // Hash value for the text

int i, j;
// Calculate the value of h = pow(d, m-1) % q

for (i = 0; i < m - 1; i++) {

h = (h * d) % q;

// Calculate the initial hash values for the pattern and first window of the text

for (i = 0; i < m; i++) {

p = (d * p + pattern[i]) % q;

t = (d * t + text[i]) % q;

// Slide the pattern over text one by one

for (i = 0; i <= n - m; i++) {

// If the hash values of current window of text and pattern match, then check characters

if (p == t) {

bool match = true;

for (j = 0; j < m; j++) {

if (text[i + j] != pattern[j]) {

match = false;

break;

// If match is found

if (match) {

cout << "Pattern found at index " << i << endl;

// Calculate the hash value for the next window of text

// Remove leading digit and add trailing digit

if (i < n - m) {

t = (d * (t - text[i] * h) + text[i + m]) % q;

// We might get a negative value of t, converting it to positive

if (t < 0) {

t = (t + q);
}

int main() {

string text, pattern;

int q = 101; // A prime number for modulo operation

int d = 256; // Number of characters in the input alphabet (ASCII)

// Input the text

cout << "Enter the text: ";

getline(cin, text);

// Input the pattern

cout << "Enter the pattern to search: ";

getline(cin, pattern);

// Call the Rabin-Karp algorithm

rabinKarp(text, pattern, d, q);

return 0;

You might also like