0% found this document useful (0 votes)
2 views

dsa

The document outlines several programming tasks involving data structures and algorithms, including constructing a linked list, solving the 0/1 knapsack problem, performing breadth-first search on a graph, checking if a graph is bipartite, detecting cycles in a directed graph, and implementing Dijkstra's algorithm for shortest paths. Each task is accompanied by C++ code snippets that demonstrate the implementation of the respective algorithms. The document serves as a guide for understanding and implementing fundamental graph and data structure concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

dsa

The document outlines several programming tasks involving data structures and algorithms, including constructing a linked list, solving the 0/1 knapsack problem, performing breadth-first search on a graph, checking if a graph is bipartite, detecting cycles in a directed graph, and implementing Dijkstra's algorithm for shortest paths. Each task is accompanied by C++ code snippets that demonstrate the implementation of the respective algorithms. The document serves as a guide for understanding and implementing fundamental graph and data structure concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Praveen is writing a program that operates on a linked list.

The program should read a


sequence of integers and construct a singly linked list with these values inserted at the
beginning. After constructing the linked list, the program should display only the even-
valued elements from the list.

Your task is to help Praveen implement this program.

#include <iostream>
using namespace std;
struct Node {
int value;
Node* next;
};
void insertValue (Node** head, int newValue) {
Node* newNode = new Node;
newNode->value = newValue;
newNode->next = *head;
*head = newNode;
}
void display EvenValues (Node* head) {
Node* current = head;
while (current != nullptr) {
if (current->value % 2 == 0) {
cout << current->value << " ";
}
current = current->next;
}
}

int main() {
int N;
cin >> N;
Node* head = nullptr;
for (int i = 0; i < N; i++) {
int value;
cin >> value;
insertValue(&head, value);
}
displayEvenValues (head);
while (head != nullptr) {
Node* temp = head;
head head->next;
delete temp;
}
return 0;
}

Reni, an avid traveller, is preparing for her next adventure. She's limited by the amount
of weight she can carry in her backpack, but she wants to maximize the value of the
items she brings along. Reni knows the value and weight of each item she's
considering, and she needs your help to determine which items to pack.

You're tasked with implementing a solution to the 0/1 knapsack problem to assist Reni
in selecting the most valuable combination of items without exceeding her backpack's
weight limit.

#include <stdio.h>
int max(int a, int b) {
return (a > b) ? a: b;

// Memoization table
int memo [100][100];
// Recursive function with memoization
int knapsackRecursive (int W, int wt [], int val[], int n) {
// Base case: no items or no capacity
if (n == 0 || W == 0) {
return 0;
}
// Check if the value is already computed
if (memo[n][W] != -1) {
return memo [n] [W];
}
/ If the weight of the nth item is more than the capacity W
/ if (wt[n 1] > W) { -
return memo[n] [W] = knapsackRecursive (W, wt, val, n } else {
return memo[n] [W] = max(val[n 1] + knapsackRecursive (Wwt[n 1], wt, val, n 1), knapsackRecursive (W, wt, val, n 1));
}
void printknapSack(int W, int wt[], int val[], int n) {
/ Initialize memoization table to -1 /
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= W; j++) {
memo[i][j] = -1;
}
}
int maxValue knapsackRecursive (W, wt, val, n);
// To find the specified weights, we need to backtrack through the memoization table
int w = W;
printf("Specified weights: ");
for (int i= n; i > 0 && maxValue > 0; i--) {
// Check if the item was included if (maxValue != memo [i 1][w]) {
printf("%d ", wt[i - 1]);
w =wt[i-1];
maxValue val[i - 1];
}

}
}
int main() { int val[100], wt[100]; int W, n;
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &val[i]);
for (int i = 0; i < n; i++) scanf("%d", &wt[i]);
scanf("%d", &W);
printknapSack(W, wt, val, n);
return 0;
}

You are designing a navigation system for a city with multiple interconnected cities.
The cities are represented as vertices, and the connections between cities are
represented as edges in a graph.

Your task is to implement a program that performs a breadth-first search (BFS)


traversal on the graph, starting from a given source city, and outputs the order in which
the cities are visited.
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
void BFS(vector<vector<int>>& graph, int numCities, int source) {
vector<bool> visited (numCities, false); queue<int> q;
visited[source] = true;
q.push(source);
while (!q.empty()) {
int currentCity = q.front();
q.pop();
cout <<<< currentCity <<<<< ";
for (int i = 0; i < numCities; i++) {
if (graph[currentCity] [i] == 1 && !visited[i]) { visited[i] = true; q.push(i);
}
}

}
int main() {
int numCities, numConnections;
cin >> numCities >> numConnections;
vector<vector<int>> graph (numCities, vector<int>(numCities, 0));
for (int i = 0; i < numConnections; i++) {
int a, b;
cin >> a >> b;
graph[a] [b] = 1;
}
int source;
cin >> source;
BFS(graph, numCities, source);
return 0;
}

You are given a network of n computers, represented by vertices numbered from 0 to


n-1. The computers are connected to each other through network cables, forming a
communication network. Your task is to determine whether the given network is
bipartite or not using the Breadth-first search algorithm.
A network is considered bipartite if it can be divided into two independent sets of
computers such that no two computers within the same set are directly connected. In
other words, the computers in each set can communicate with computers in the other
set but not within their own set.
#include <stdio.h>
#define V 100
int isBipartite(int G[][V], int src, int n)
{
int colorArr[V];
for (int i = 0; i < n; ++i)
colorArr[i] = -1;
colorArr[src] = 1;
int queue [V];
int front = -1; // Pointer to the front of the queue
int rear = -1; // Pointer to the rear of the queue
queue [++rear] = src;
while (front != rear)
{
int u = queue [++front];
if (G[u][u] == 1) return 0;
for (int v = 0; v < n; ++v)

{
if (G[u][v] && colorArr[v] == -1)
{
colorArr[v] = 1 colorArr[u];
}
queue [++rear] = v;
else if (G[u] [v] && colorArr[v] == colorArr[u])
return 0;
}
}
return 1;
}
int main()
{
int n;
scanf("%d", &n);
int G[V][V];
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
scanf("%d", &G[i][j]);
}

int src;

scanf("%d", &src);

if (isBipartite(G, src, n))

printf("Yes, the given graph is Bipartite");

else

printf("No, the given graph is not Bipartite");

return 0;

You are tasked with analyzing a directed graph represented as a collection of edges.
Your program should determine whether the directed graph contains any cycles.
#include <iostream>

#include <vector>
#include <unordered set>
using namespace std;
// Structure to represent an edge in the graph
struct Edge {
int to;
Edge(int_to): to(_to) {}
};
// Function to perform depth-first search (DFS) and check for cycles
bool isCyclicUtil (const vector<vector<Edge>>& graph, int v, vector<bool>& visited, vector<bool>& recStack) {
if (Ivisited[v]) {
// Mark the current vertex as visited and add it to the recursion stack
visited[v] = true;
recStack[v] = true;
// Recur for all vertices adjacent to this vertex
for (const Edge&e graph[v]) {
if (visited[e.to] && isCyclicUtil (graph, e.to, visited, recStack)) {
return true;
} else if (recStack[e.to]) {
return true;
}

}
}
// Remove the vertex from the recursion stack
recStack[v] = false;
return false;
}
// Function to check whether the given multistage graph is acyclic
bool isAcyclic (const vector<vector<Edge>>& graph, int n) {
// Initialize arrays to track visited vertices and recursion stack
vector<bool> visited(n, false);
vector<bool> recStack(n, false);
// Perform DFS for each vertex
for (int i = 0; i < n; ++i) {
if (isCyclicUtil (graph, i, visited, recStack)) {
return false; // Cycle detected
}
}

int main() {
int numVertices, numEdges;
//cout << "Enter the number of vertices in the graph: ";
cin >> numVertices;
//cout << "Enter the number of edges in the graph: ";
cin >> numEdges;
// Create an adjacency list representation of the graph
vector<vector<Edge>> graph (numVertices);
// Input edges
//
cout << "Enter the edges in the format 'from_vertex to_vertex':" << endl;
for (int i = 0; i < numEdges; ++i) {
int from, to;
cin >> from >> to;
graph [from].push_back(Edge(to));
}
// Check whether the given multistage graph is acyclic
if (isAcyclic (graph, numVertices)) {
cout << "The multistage graph is acyclic.";
} else {
cout << "The multistage graph contains cycles.";
}

You are provided with a map of cities represented as vertices and roads connecting these cities represented as edges
with associated weights. The task is to find the shortest path from a specified starting city to all other cities using
Dijkstra's algorithm.
#include <stdio.h>
#include <limits.h>
#define MAX_CITIES 100
void dijkstra (int graph [MAX_CITIES] [MAX_CITIES], int n, int source, int distances [MAX_CITIES]) { int visited[MAX_CITIES] = {0};
for (int i=0; i < n; i++) {
distances[i] = INT_MAX;
}
distances [source] = 0;
for (int count = 0; count <n 1; count++) {
int u = -1;
for (int i=0; i < n; i++) {
if (Ivisited[i] && (u-1 || distances [i] < distances[u])) { u = i;
}
}
visited[u] 1;

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


if (Ivisited[v] && graph [u] [v] && distances [u] != INT_MAX && distances [u] + graph[u] [v] < distances [v]) { distances [v] = distances [u] + graph[u][v];
}
}
}
}
int main() {
int n, m; // Number of cities and roads
scanf("%d %d", &n, &m);
int graph [MAX_CITIES] [MAX_CITIES] = {0};
int u, v, w; // Road from u to v with weight w
for (int i = 0; i < m; i++) {
scanf("%d %d %d", &u, &v, &w);
graph[u][v] = w;
}
int source; // Starting city
scanf("%d", &source);
int distances [MAX_CITIES];

dijkstra (graph, n, source, distances);


for (int i=0; i < n; i++) { if (i source) {
continue;
} if (distances[i] INT_MAX) {
printf("City %d: Not reachable\n", i);
} else {
printf("City %d: %d units\n", i, distances[i]);
}
}
return 0;
}

You might also like