DAA Model Lab - 230412 - 112849
DAA Model Lab - 230412 - 112849
DAA Model Lab - 230412 - 112849
Program:
#include <stdio.h>
int mid = n / 2;
int left[mid];
int right[n - mid];
mergeSort(left, mid);
mergeSort(right, n - mid);
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements separated by space: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int person = 2;
int i = 1;
while (i < n) {
printf("Person %d is given with element: %d\n", person, arr[i]);
i *= 2;
person++;
}
return 0;
}
2 You are given an array of N integers and your task is to sort the array using the
following operations.
In one operation you can select a sub-array of the array and sort it. The cost of
performing such an operation will be the square of the length of the sub-array
you are sorting.
Your task is to find the minimum cost of sorting the whole array.
Input Format:
The first line contains a single integer T representing the number of test cases.
Then each test case follows.
The first line of each test case contains one integers N denoting the number of
elements in the array.
The next line of each test case contains N integers of the array.
Output Format:
For each test case, print the minimum cost required to sort the whole array.
Constraints:
1 <= T <= 5
3 <= N <= 105
1 <= arr[i] <= 109
Program:
#include <stdio.h>
#include <math.h>
int cost = 0;
for (int i = n - 1; i >= 0; i--) {
int subarray_length = n - i; // Length of sub-array to be sorted
cost += subarray_length * subarray_length; // Add cost of sorting the
sub-array
}
return cost;
}
int main() {
int t;
printf("Enter the number of test cases: ");
scanf("%d", &t);
while (t--) {
int n;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements separated by space: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
return 0;
}
SET - 2
Program:
#include <stdio.h>
mergeSort(left, mid);
mergeSort(right, n - mid);
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements separated by space: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
mergeSort(arr, n);
return 0;
}
2 There are N cities and Demon is in city 1. Now, there are M pair of roads
between
some cities and each of the roads have cost to travel by it. The cost to travel
from
city c1 to ck is 1*w1 + 2*w2 + 3*w3+......+(k-1)*wk-1 where wi is the cost to
travel from city pi to city pi+1. Demon is lazy and so he wants you to find the
minimum cost to travel from city 1 to every other city from 1 to N. If there
exists
no path to travel from city 1 to city i, print -1.
Note: There can be self-loop roads or multiple edge roads. All the roads are
bidirectional.
Input Format:
The first line contains two space-separated integers n and m - the number of
nodes
and edges respectively. The next m lines contain three space-separated integers
x,
y, and w - representing an edge between x and y with cost w
Output Format:
Output n lines. In the ith line, output the minimum distance from city 1 to the
ith
city. If there exists no such path, output -1.
Constraints:
1<=n<=3000
0<=m<=10000
1<=x,y<=n
1<=w<=1e9
Program:
#include <stdio.h>
#include <stdbool.h>
#include <limits.h>
// Find the node with minimum distance that is not visited yet
for (int j = 1; j <= n; j++) {
if (!visited[j] && (u == -1 || dist[j] < dist[u])) {
u = j;
}
}
int main() {
printf("Enter the number of nodes and edges: ");
scanf("%d %d", &n, &m);
SET - 3
1 You are given n objects, a knapsack of capacity c, array v, and array w. The ith
object has value v[i] and weight w[i].
Determine the maximum total value that you can get by selecting objects in
such
a manner that their sum of weights is not greater than the capacity c.
Hint: Use Dynamic programming.
Input format:
First line: Two integers n and c denoting the number of objects and capacity of
the knapsack ( 1 <= n<= 10^3 and 1 <= C <= 2*10^6 ) .
Second line: n integers (0 <= Vi <= 50)
Third line: n integers ( 10 <=Wi <= 2*10^6)
Output format:
Print a single integer denoting the maximum value that you can get by
selecting
the objects.
Program:
#include <stdio.h>
int main() {
printf("Enter the number of objects and capacity of knapsack: ");
scanf("%d %d", &n, &c);
return 0;
}
2 Given a chess board having NxN cells, you need to place N queens on the
board
in such a way that no queen attacks any other queen.
Input Format:
The only line of input consists of a single integer denoting N.
Output Format:
If it is possible to place all the N queens in such a way that no queen attacks
another
queen, then print N lines having N integers. The integer in ith line and jth
column
will denote the cell (i,j) of the board and should be 1 if a queen is placed at (i,j)
otherwise 0. If there are more than way of placing queens print any of them. If
it
is not possible to place all N queens in the desired way, then print "Not
possible"
(without quotes).
Constraints:
1 <= N <= 10
Program:
#include <stdio.h>
if (solveNQueens(col + 1)) {
return 1; // Move to the next column
}
int main() {
printf("Enter the value of N: ");
scanf("%d", &N);
if (solveNQueens(0)) {
printf("Queens placement:\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%d ", board[i][j]);
}
printf("\n");
}
} else {
printf("Not possible\n");
}
return 0;
}
SET - 4
1 Write a program to implement Quick Sort.
Program:
#include <stdio.h>
// Iterate through the array and swap elements smaller than pivot
// to the left side of the pivot
for (int j = low + 1; j <= high; j++) {
if (arr[j] < pivot) {
swap(&arr[i], &arr[j]);
i++;
}
}
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
return 0;
}
2 The travelling salesman has a map containing m*n squares. He starts from
the top left corner and visits every cell exactly once and returns to his initial
position (top left). The time taken for the salesman to move from a square to
its
neighbor might not be the same. Two squares are considered adjacent if they
share
a common edge and the time taken to reach square b from square a and
vice-versa
are the same. Can you figure out the shortest time in which the salesman can
visit
every cell and get back to his initial position?
Hint: Use Branch and Bound
Program:
#include <stdio.h>
#include <limits.h>
// Base case: if all cells are visited, return the time taken to go back to the
top left corner
if (dp[0][VISITED_ALL] != -1) {
return dp[0][VISITED_ALL];
}
// If not all cells are visited, initialize minimum time taken to maximum
integer value
int min_time = INT_MAX;
int main() {
int m, n;
int grid[10][10];
// Print the minimum time taken to visit every cell and return to the top left
corner
printf("Minimum time taken: %d\n", min_time);
return 0;
}
SET - 5
1 Given a Directed and Acyclic Graph having N vertices and M edges, print
topological sorting of the vertices.
Program:
#include <stdio.h>
#include <stdbool.h>
// Push the current vertex to stack after visiting all its adjacent vertices
stack[N] = vertex;
}
int main() {
int N, M;
int adjMatrix[MAX_SIZE][MAX_SIZE];
2 The task is very simple you ar given an array of n numbers. You need to print
all
the unique subsets of the array having sum K in sorted order.
Note that each of the subset you print should be in sorted order also also a
smaller
subset should be printed first i.e all subsets should also be printed in sorted
order.
A subset A is smaller than subset B if there exists A[i] < B[i] for the smallest
possible i.
Please not that you only need to print unique subsets i/e dont print them twice
if
they accur more than once.
INPUT FORMAT:
First line contains 2 integers N and K
Second line contains N space sperated integers
OUTPUT FORMAT:
Output unique subsets having sum K in sorted order
CONSTRAINTS:
1 <= N <= 15
1 <= K <= 10000
1 <= A[i] <= 100
Program:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
int main() {
int N, K;
int arr[15]; // Maximum array size as per constraint
int subset[15]; // Maximum subset size as per constraint
// Input the number of elements in the array and the required sum
printf("Enter the number of elements in the array: ");
scanf("%d", &N);
printf("Enter the required sum K: ");
scanf("%d", &K);
return 0;
}
SET - 6
int main() {
int N, M, K;
int graph[101][101]; // Maximum N as per constraint
int u, v, w;
// Input the number of cities, number of roads, and maximum toll charge
printf("Enter the number of cities, number of roads, and maximum toll
charge (N M K): ");
scanf("%d %d %d", &N, &M, &K);
return 0;
}
if (v == t) {
return true; // Augmenting path found
}
if (dfs(v, t)) {
return true;
}
}
}
maxFlow += bottleneck;
return maxFlow;
}
int main() {
int source, sink;
int u, v, capacity;
int main() {
int N;
printf("Enter the number of elements in the array: ");
scanf("%d", &N);
int arr[N];
printf("Enter the elements of the array: ");
for (int i = 0; i < N; i++) {
scanf("%d", &arr[i]);
}
return 0;
}
2 Given an undirected graph and a starting node, determine the lengths of the
shortest paths from the starting node to all other nodes in the graph. If a node
is
unreachable, its distance is -1. Nodes will be numbered consecutively from to ,
and edges will have varying distances or lengths using dijkstra’s algorithm.
Program:
#include <stdio.h>
#include <stdbool.h>
#include <limits.h>
// Function to find the minimum distance vertex from the set of unvisited
vertices
int minDistance(int dist[], bool visited[], int V) {
int min = INF;
int min_index;
return min_index;
}
// Function to print the shortest path distances from the source node
void printShortestDistances(int dist[], int V, int src) {
printf("Shortest path distances from node %d:\n", src);
for (int i = 0; i < V; i++) {
if (dist[i] == INF) {
printf("Node %d is unreachable\n", i);
} else {
printf("Node %d: %d\n", i, dist[i]);
}
}
}
int main() {
int V; // Number of nodes in the graph
printf("Enter the number of nodes in the graph: ");
scanf("%d", &V);
return 0;
}
SET - 8
// Function to find the vertex with minimum key value from the set of vertices
not yet included in MST
int minKey(int key[], bool mstSet[], int V) {
int min = INF;
int min_index;
return min_index;
}
int main() {
int V; // Number of nodes in the graph
printf("Enter the number of nodes in the graph: ");
scanf("%d", &V);
return 0;
}
// Initialize the first row of dp[][] to true, as sum 0 is always possible with
an empty subset
for (int i = 0; i <= n; i++) {
dp[i][0] = true;
}
// Initialize the first column of dp[][] to false, as sum greater than 0 is not
possible with an empty set
for (int i = 1; i <= sum; i++) {
dp[0][i] = false;
}
while (T--) {
int N, K; // Size of set and target sum for each test case
printf("Enter the size of set and target sum: ");
scanf("%d %d", &N, &K);
return 0;
}
SET - 9
1 You are given an array $A$ of size $N$. Sort the array using Quick Sort and
print
the sorted array.
Input Format:
The first line of the input contains a single integer T denoting the number
of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N.
The second line contains N space-separated integers 1, 2… A1, A2,…,
AN.
Output Format : for each test case print a single line containing N
spaceseparated
integers - the sorted array.
Constraints:
Program
#include <stdio.h>
// Swap the pivot element with the element at index i+1, to place pivot at its
correct position
swap(&arr[i + 1], &arr[high]);
// Recursively sort the two subarrays before and after pivot element
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
int main() {
int T; // Number of test cases
printf("Enter the number of test cases: ");
scanf("%d", &T);
while (T--) {
int N; // Size of array
printf("Enter the size of array: ");
scanf("%d", &N);
return 0;
}
// Function to perform Floyd Warshall algorithm to find all pairs shortest path
void floydWarshall(int graph[][4], int V) {
int dist[V][V]; // 2D array to store the shortest distances
int main() {
int graph[4][4] = {{0, 5, INF, 10},
{INF, 0, 3, INF},
{INF, INF, 0, 1},
{INF, INF, INF, 0}};
// Call the Floyd Warshall function to find all pairs shortest path
floydWarshall(graph, V);
return 0;
}
SET - 10
1 Given an array arr[], its starting position l and its ending position r. Sort the
array
using merge sort algorithm.
Input Format
First line: the size of the array
Second line: the array to be sorted (numbers separated by spaces)
Output Format
Output between two brackets and each number separated by a coma.
Program:
#include <stdio.h>
int arr[n];
printf("Enter the array elements separated by spaces: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
return 0;
}
return minFee;
}
int main() {
int t;
printf("Enter the number of test cases: ");
scanf("%d", &t);
while (t--) {
int n, k;
printf("Enter the number of cities and number of toll booths: ");
scanf("%d %d", &n, &k);
int tolls[MAXK][2];
printf("Enter the toll booth ranges (x_i, y_i): \n");
for (int i = 0; i < k; i++) {
scanf("%d %d", &tolls[i][0], &tolls[i][1]);
}
return 0;
}
SET - 11
return dp[n][W];
}
int main() {
int n;
printf("Enter the number of items: ");
scanf("%d", &n);
int W;
printf("Enter the knapsack weight limit: ");
scanf("%d", &W);
return 0;
}
2 Given a directed flow network where each edge has a capacity of flow it could
allow, find the maximum flow over the network from source(S) to sink(T).
Network will follow these rules:
Only one source(S) and only one sink(T).
Other than source and sink, nodes are represented with alphabets [A-O].
There are no self loops.
There will be no initial dead ends other than T.
For any pair of nodes, direction of edges between them will be in single
direction.
Input Format:
First line has an integer E- number of edges.
Next E lines have three values Vi,Vj,...,Cx which implies there is a node from
Vi
to Vj with capacity Cx.
Output Format:
Print a single integer which is the maximum flow from source to sink.
Constraints:
1 <= E <= 50
1 <= Cx <= 50
Network includes S, T, a maximum of 15 other nodes.
Program:
#include <stdio.h>
#include <stdbool.h>
#include <limits.h>
return maxFlow;
}
int main() {
int e; // Number of edges
printf("Enter the number of edges: ");
scanf("%d", &e);
return 0;
}
SET - 12
int main() {
int T; // Number of test cases
scanf("%d", &T);
while (T--) {
int n; // Size of input array
scanf("%d", &n);
int A[n]; // Input array
return 0;
}
2 You are given an undirected connected weighted graph having ‘N’ nodes
numbered from 1 to 'N'. A matrix ‘E’ of size M x 2 is given which represents
the ‘M’ edges such that there is an edge directed from node E[i][0] to node
E[i][1]. You are supposed to return the minimum spanning tree where you
need to return weight for each edge in the MST using Prim’s algorithm.
Program:
#include <stdio.h>
#include <stdbool.h>
#include <limits.h>
int main() {
int n, m; // Number of nodes and edges
printf("Enter the number of nodes and edges: ");
scanf("%d %d", &n, &m);
return 0;
}
SET - 13
1 You are given an array A[] of N numbers. Implement Quick Sort Algorithm.
Input:
First line will contain N which denotes the number of numbers.
Second line will contain an Array [] A[].
Output: Print the sorted numbers in ascending order
Program:
#include <stdio.h>
// Iterate through the array and move elements smaller than pivot to the left
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
// Recursively sort the two subarrays on the left and right of pivot
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
int main() {
int n; // Number of elements in the array
printf("Enter the number of elements: ");
scanf("%d", &n);
return 0;
}
2 Given a Directed and Acyclic Graph having N vertices and M edges, print
topological sorting of the vertices.
Input Format:
First line consists of two space separated integers denoting N and M.
Each of the following M lines consists of two space separated
integers X and Y denoting there is an from X directed towards Y.
Output Format:
Print N space separated integers denoting the topological sort, if there are
multiple ordering print the lexicographically smallest one.
Program:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, m; // Number of vertices and edges
printf("Enter the number of vertices and edges: ");
scanf("%d %d", &n, &m);
return 0;
}
SET - 14
// Compare elements from left and right arrays and merge them in sorted
order
while (i < leftSize && j < rightSize) {
if (left[i] <= right[j]) {
arr[k++] = left[i++];
} else {
arr[k++] = right[j++];
}
}
int mid = n / 2;
int left[mid];
int right[n - mid];
int main() {
int n; // Number of integers
printf("Enter the number of integers: ");
scanf("%d", &n);
return 0;
}
// Initialize the first column with true, as sum 0 can always be achieved
for (int i = 0; i <= n; i++) {
dp[i][0] = 1;
}
// Initialize the first row, except the first element, with false
for (int i = 1; i <= sum; i++) {
dp[0][i] = 0;
}
// Return the result for the last element in the set and the given sum
return dp[n][sum];
}
int main() {
int t; // Number of test cases
printf("Enter the number of test cases: ");
scanf("%d", &t);
while (t--) {
int n, k; // Size of set and target sum for current test case
printf("Enter the size of set and target sum: ");
scanf("%d %d", &n, &k);
return 0;
}