LAB ASSIGNMENT 9
Submitted for
DATA STRUCTURES AND ALGORITHMS (UNC401)
Submitted by:
Mahim Dixit
3EC1
(BE- ELECTRONICS & COMMUNICATION ENGINEERING)
Submitted to:
Dr. Ankit Soni
(Assistant Professor, ECED)
DEPARTMENT OF ELECTRONICS & COMMUNICATION ENGINEERING
THAPAR INSTITUTE OF ENGINEERING & TECHNOLOGY
(A DEEMED TO BE UNIVERSITY)
PATIALA,PUNJAB- INDIA
EVENSEM2425
Experiment 1: Subset Sum Problem Using Brute Force
Objective: To understand and implement the brute-force approach for solving the
subset sum problem, where the goal is to determine whether a subset of integers exists
that adds up to a given target sum.
Tasks:
1. Write a program that takes a list of integers and a target sum as input, and
checks whether any subset of the list sums up to the target using brute-force.
Example:
Input:
Set = {3, 34, 4, 12, 5, 2}
Sum = 9
Expected Output:
True (because subset {4, 5} sums to 9)
Sol:
Code:
#include <iostream>
#include <vector>
using namespace std;
// Brute‑force
vector<vector<int>> findSubsetsWithSum(const vector<int>& arr, int target) {
int n = arr.size();
int totalMasks = 1 << n; // 2^n subsets
vector<vector<int>> solutions;
for (int mask = 0; mask < totalMasks; ++mask) {
int sum = 0;
vector<int> subset;
for (int i = 0; i < n; ++i) {
if (mask & (1 << i)) {
sum += arr[i];
subset.push_back(arr[i]);
if (sum == target) {
solutions.push_back(subset);
return solutions;
int main() {
cout << "<----------Welcome to the Subset Sum Checker--------- >\n";
cout << "Made by Ananth Vaibhav Agrawal\n";
cout << "Roll Number: 102206214\n";
cout << "Subgroup : 3F12/3F1B\n";
cout << "DSA Lab Assignment 09 under guidance of Dr. Ankit Soni \n\n";
// Read input
int n, target;
cout << "Enter number of elements: ";
cin >> n;
vector<int> arr(n);
cout << "Enter " << n << " elements:\n";
for (int i = 0; i < n; ++i) {
cin >> arr[i];
cout << "Enter target sum: ";
cin >> target;
// Echo the entered array
cout << "\nEntered array: {";
for (int i = 0; i < n; ++i) {
cout << arr[i] << (i + 1 < n ? ", " : "");
cout << "}\n\n";
// Find all subsets summing to target
auto solutions = findSubsetsWithSum(arr, target);
// Output results
if (!solutions.empty()) {
cout << "Target Sum True: Subsets found with sum " << target << ":\n";
for (const auto& subset : solutions) {
cout << " {";
for (int i = 0; i < subset.size(); ++i) {
cout << subset[i] << (i + 1 < subset.size() ? ", " : "");
cout << "}\n";
} else {
cout << "False: No subset sums to " << target << "\n";
return 0;
Output:
Experiment 2: Closest Pair of Points Using Brute Force and Divide & Conquer
Objective: To implement both brute-force and divide-and-conquer algorithms to find the
closest pair of points in a 2D plane and compare their performance in terms of efficiency and
correctness.
Tasks:
1. Write a program that receives a list of 2D points and finds the pair of points with the
minimum Euclidean distance using both approaches.
Example
Input:
Points = [(2,3), (12,30), (40,50), (5,1), (12,10), (3,4)]
Expected Output:
Closest pair: [(2,3), (3,4)] with distance ≈ 1.41
Code:
#include <bits/stdc++.h>
using namespace std;
struct Point { double x, y; };
// Euclidean distance
inline double dist(const Point &a, const Point &b) {
double dx = a.x - b.x, dy = a.y - b.y;
return sqrt(dx*dx + dy*dy);
// Brute-force O(n^2)
pair<pair<Point,Point>, double> brute(vector<Point>& pts) {
double best = 1e18; pair<Point,Point> bp;
int n = pts.size();
for(int i=0;i<n;i++) for(int j=i+1;j<n;j++){
double d = dist(pts[i], pts[j]);
if(d < best){ best=d; bp={pts[i],pts[j]}; }
return {bp,best};
// D&C helper: on pts[l..r], presorted by x
pair<pair<Point,Point>, double> dac(vector<Point>& pts, int l, int r) {
int n = r-l+1;
if(n <= 3) {
vector<Point> tmp(pts.begin()+l, pts.begin()+r+1);
return brute(tmp);
int m = (l+r)/2;
double midx = pts[m].x;
auto left = dac(pts, l, m);
auto right = dac(pts, m+1, r);
auto best = left.second < right.second ? left : right;
double d = best.second;
// Build strip and check up to 7 neighbors in y-order
vector<Point> strip;
for(int i=l;i<=r;i++)
if(fabs(pts[i].x - midx) < d) strip.push_back(pts[i]);
sort(strip.begin(), strip.end(),
[](auto &a, auto &b){ return a.y < b.y; });
for(int i=0;i<strip.size();i++){
for(int j=i+1; j<strip.size() &&
strip[j].y - strip[i].y < d; j++){
double d2 = dist(strip[i], strip[j]);
if(d2 < d){ d=d2; best={ {strip[i],strip[j]},d }; }
return best;
// Wrapper for divide & conquer O(n log n)
auto closestDC(vector<Point> pts){
sort(pts.begin(), pts.end(),
[](auto &a, auto &b){ return a.x < b.x; });
return dac(pts, 0, pts.size()-1);
int main(){
// Banner & details
cout<<"<-- Closest Pair Checker -->\n"
"Name: Ananth Vaibhav Agrawal\n"
"Roll No.: 102206214 | Subgroup: 3F12/3F1B\n"
"DSA Lab09 under Dr. Soni\n\n";
int n; cout<<"Enter Number of point pairs: "; cin>>n;
vector<Point> pts(n);
cout<<"Enter points (x y):\n";
for(auto &p: pts) cin>>p.x>>p.y;
cout<<"\nYou entered: ";
for(auto &p: pts) cout<<"("<<p.x<<","<<p.y<<") ";
cout<<"\n\n";
auto bf = brute(pts);
auto dc = closestDC(pts);
cout<<"The Closest Pair is:"<<endl;
cout<<fixed<<setprecision(4)
<<"Brute: ("<<bf.first.first.x<<","<<bf.first.first.y
<<") & ("<<bf.first.second.x<<","<<bf.first.second.y
<<") distance="<<bf.second<<"\n"
<<"D&C : ("<<dc.first.first.x<<","<<dc.first.first.y
<<") & ("<<dc.first.second.x<<","<<dc.first.second.y
<<") distance="<<dc.second<<"\n";
// Correctness
if(fabs(bf.second - dc.second) < 1e-9)
cout<<"[ ] Results match.\n";
else
cout<<"[ ] Mismatch! Check implementation.\n";
// Performance notes
cout << "\nEfficiency Comparison:\n";
cout << "- Brute‑force: O(n^2)\n";
cout << "- Divide‑&‑Conquer: O(n log n)\n";
cout << "As n grows, the divide‑and‑conquer approach will significantly outperform
brute‑force.\n";
return 0;
}
Output:
Experiment 3: Fractional Knapsack Problem Using Greedy Approach
Objective: To implement the greedy algorithm to solve the fractional knapsack problem,
demonstrating how to achieve maximum profit by taking items (or fractions of items) based
on their profit-to-weight ratio.
Tasks:
1. Write a program that calculates the maximum possible profit for a given list of items with
weights and profits and a knapsack of limited capacity. The solution must allow taking
fractions of items.
Example
Input:
Profits = {60, 100, 120}
Weights = {10, 20, 30}
Capacity = 50
Expected Output:
240.0 (Pick all of item 1 and 2, and 2/3 of item 3)
Code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Item structure storing profit, weight, and ratio
struct Item {
double profit, weight, ratio;
Item(double p, double w) : profit(p), weight(w), ratio(p/w) {}
};
// Comparator to sort items by descending ratio
bool cmp(const Item &a, const Item &b) {
return a.ratio > b.ratio;
int main() {
// Banner and user details
cout << "<---------- Fractional Knapsack Solver ---------- >\n";
cout << "Name : Ananth Vaibhav Agrawal\n";
cout << "Roll Number: 102206214\n";
cout << "Subgroup : 3F12/3F1B\n";
cout << "DSA Lab 09 under guidance of Dr. Ankit Soni\n\n";
// Read number of items
int n;
cout << "Enter number of items: ";
cin >> n;
// Read profits and weights
vector<double> profits(n), weights(n);
cout << "Enter profits:\n";
for (int i = 0; i < n; ++i) cin >> profits[i];
cout << "Enter weights:\n";
for (int i = 0; i < n; ++i) cin >> weights[i];
// Read capacity
double capacity;
cout << "Enter knapsack capacity: ";
cin >> capacity;
// Echo input
cout << "\nItems (profit,weight): { ";
for (int i = 0; i < n; ++i) {
cout << "(" << profits[i] << "," << weights[i] << ")"
<< (i+1<n ? ", " : " ");
cout << "}\n";
cout << "Capacity = " << capacity << "\n\n";
// Build list of Items with ratios
vector<Item> items;
for (int i = 0; i < n; ++i)
items.emplace_back(profits[i], weights[i]);
// Sort by profit-to-weight ratio
sort(items.begin(), items.end(), cmp); // O(n log n) :contentReference[oaicite:5]{index=5}
// Greedy selection
double maxProfit = 0.0;
double remaining = capacity;
cout << "Picked fractions:\n";
for (auto &it : items) {
if (remaining == 0) break;
if (it.weight <= remaining) {
// take whole item
maxProfit += it.profit;
remaining -= it.weight;
cout << " 1.00 of item(ratio=" << it.ratio << ")\n";
} else {
// take fractional part
double f = remaining / it.weight;
maxProfit += it.profit * f;
cout << " " << f << " of item(ratio=" << it.ratio << ")\n"; // fraction taken
:contentReference[oaicite:6]{index=6}
remaining = 0;
// Output result
cout << "\nMaximum Profit = " << maxProfit << "\n";
return 0;
}
Output:
---------x----------x---------------x---------------x--------------------x------------x--------------