Professional Documents
Culture Documents
Daa 2
Daa 2
Daa 2
ALGORITHM DIGITAL
ASSIGNMENT-2
Name: Mounika N
Reg no: 21BBS0046
Code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int weight;
int profit;
int index;
};
vector<bool> included;
};
return 0.0;
if (j < n) {
return bound;
}
// Function to solve the 0/1 Knapsack problem using branch and bound
int knapsackBranchAndBound(int capacity, vector<int> weights, vector<int>
profits) {
int n = weights.size();
vector<Item> items(n);
root.level = -1;
root.profit = 0;
root.weight = 0;
root.bound = calculateBound(root, n, capacity, items);
root.included.resize(n, false);
int maxProfit = 0;
while (!queue.empty()) {
// Create the left child node (without including the current item)
Node left = curr;
left.level = curr.level + 1;
left.weight += items[left.level].weight;
left.profit += items[left.level].profit;
right.level = curr.level + 1;
right.bound = calculateBound(right, n, capacity, items);
return maxProfit;
int main() {
int capacity;
cout << "Enter the capacity of the bag: ";
cin >> capacity;
return 0;
}
Output:
Time complexity: The time complexity of this algorithm is
exponential, specifically O(2^n), where n is the number of items. The
branch and bound method explores all possible combinations of
including or excluding each item, resulting in an exponential time
complexity.
Code:
#include <iostream>
#include <queue>
#include <unordered_map>
using namespace std;
// Structure for the Huffman tree node
struct Node {
char data;
unsigned freq;
Node *left,
*right;
{
return l->freq > r->freq;
}
};
// Function to print Huffman codes from the root of the Huffman tree
void printHuffmanCodes(Node* root, string str)
{
if (!root)
return;
if (root->data != '$')
cout << root->data << " : " << str << "\n";
while (minHeap.size() != 1) {
left = minHeap.top();
minHeap.pop();
right = minHeap.top();
minHeap.pop();
top->left = left;
top->right = right;
minHeap.push(top);
printHuffmanCodes(minHeap.top(), "");
}
int main()
{
int n;
return 0;
Output:
Time complexity: The time complexity of this implementation is
O(nlogn), where n is the number of characters. The priority queue
(min-heap) operations take logarithmic time complexity, and we
perform n - 1 iterations to build the Huffman tree.
***END***