Created By: Abhinav Rawat CSE4A1 Roll No-08
Created By: Abhinav Rawat CSE4A1 Roll No-08
find if a path exists between two given vertices or not. (Hint: use DFS).
Input Format: Input will be the graph in the form of adjacency matrix or adjacency list. Source vertex
number and destination vertex number is also provided as an input.
Output Format: Output will be 'Yes Path Exists' if path exists, otherwise print 'No Such Path Exists'.
ALGORITHM :
1. Build the graph using an adjacency list from the given edges.
2. Create a visited array and mark all nodes as unvisited.
3. Start DFS from the source node.
4. Mark the current node as visited.
5. For each neighbor of the current node, if it is not visited, call DFS recursively on that neighbor.
6. After DFS finishes, check if the destination node is visited.
7. If visited, print "Yes Path Exists".
8. Otherwise, print "No Such Path Exists".
#include <iostream>
#include <vector>
using namespace std;
void dfs(int node, vector<vector<int>>& graph, vector<bool>& visited) {
visited[node] = true;
for (int neighbor : graph[node]) {
if (!visited[neighbor]) {
dfs(neighbor, graph, visited);
}
}
}
int main() {
int nodes, edges;
cout << "Enter number of nodes and edges: ";
cin >> nodes >> edges;
vector<vector<int>> graph(nodes);
OUTPUT:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
bool isBipartite(vector<vector<int>>& graph, int nodes) {
vector<int> color(nodes, -1);
for (int start = 0; start < nodes; ++start) {
if (color[start] == -1) {
queue<int> q;
q.push(start);
color[start] = 0;
while (!q.empty()) {
OUTPUT:
#include <iostream>
#include <vector>
using namespace std;
bool dfs(int node, vector<vector<int>>& graph, vector<bool>& visited, vector<bool>& inRecStack) {
visited[node] = true;
inRecStack[node] = true;
for (int neighbor : graph[node]) {
if (!visited[neighbor]) {
if (dfs(neighbor, graph, visited, inRecStack))
return true;
} else if (inRecStack[neighbor]) {
OUTPUT:
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <climits>
using namespace std;
void dijkstra(int start, vector<vector<pair<int, int>>>& graph, vector<int>& dist, vector<int>& parent)
{
int n = graph.size();
OUTPUT:
#include <iostream>
#include <vector>
#include <climits>
#include <stack>
using namespace std;
struct Edge {
int u, v, w;
};
void bellmanFord(int n, int m, vector<Edge>& edges, int start, vector<int>& dist, vector<int>& prev) {
dist.assign(n, INT_MAX);
prev.assign(n, -1);
dist[start] = 0;
OUTPUT:
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
const int INF = INT_MAX;
int shortestPathWithKEdges(vector<vector<pair<int,int>>>& graph, int u, int dest, int k) {
if (k == 0 && u == dest) return 0;
if (k == 0) return INF;
int ans = INF;
for (auto &edge : graph[u]) {
int next = edge.first;
int weight = edge.second;
int sub = shortestPathWithKEdges(graph, next, dest, k - 1);
if (sub != INF) {
ans = min(ans, weight + sub);
}
ALGORITHM:
1. Create three arrays:
visited[] = false for all nodes
minEdge[] = ∞ (very large) for all nodes, except minEdge[0] = 0
parent[] = -1 for all nodes
2. Repeat n times (where n is the number of nodes):
a. Find the unvisited node u with the smallest minEdge[u]
b. If no such u exists (i.e., disconnected graph), stop
c. Mark u as visited
d. Add minEdge[u] to total cost
e. For every node v:
If v is not visited and cost[u][v] < minEdge[v], then update minEdge[v] = cost[u][v] and set
parent[v] = u
3. After the loop, total cost is the sum of all selected edges
4. parent[] array stores the MST (Minimum Spanning Tree) edges
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
OUTPUT:
6. When finished, MST contains exactly V – 1 edges, and totalCost is the weight of the minimum
spanning tree.
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
int find(int i, vector<int>& parent) {
if(i == parent[i]) return i;
return parent[i] = find(parent[i], parent);
}
void Union(int a, int b, vector<int> &rank, vector<int>& parent){
int x = find(a, parent);
int y = find(b, parent);
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
int main() {
int V, E;
cout << "Enter number of vertices: " << endl;
cin >> V;
cout << "Enter number of edges: " << endl;
cin >> E;
vector<pair<int,pii>> edges;
cout << "Enter edges (src dest weight):" << endl;
for (int i = 0; i < E; i++) {
int u, v, w;
cin >> u >> v >> w;
edges.push_back({w, {u, v}});
}
sort(edges.begin(), edges.end(), greater<>());
int maxBudget = KruskalMax(edges, V);
cout << "\nMaximum Budget (Total Cost): " << maxBudget << endl;
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
const int INF = 1e9;
int main() {
int n;
cout << "Enter number of vertices: ";
cin >> n;
cout << "Enter adjacency matrix (0 for no edge except diagonal):\n";
vector<vector<int>> dist(n, vector<int>(n));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> dist[i][j];
if (i != j && dist[i][j] == 0) {
dist[i][j] = INF; // no edge
}
#include<bits/stdc++.h>
int main(){
int n, w ;
cin >> w;
int i = 0;
maxVal += v[i].second.second;
w -= v[i].second.first;
else {
w = 0;
i++;
return 0;
OUTPUT:
o Add c to totalCost.
o Insert c back into the heap (representing the newly merged file).
6. When only one file remains, you have merged all files with minimum total computation.
7. Output totalCost.
#include<bits/stdc++.h>
int main(){
int n, minComp = 0;
cin >> n;
cin >> x;
files.push(x);
while(files.size() != 1) {
int x = files.top();
files.pop();
int y = files.top();
files.pop();
minComp += (x + y);
files.push(x + y);
return 0;
OUTPUT:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Activity {
int start, finish;
};
bool cmp(Activity a, Activity b) {
return a.finish < b.finish;
}
int main() {
int n;
cout << "Enter number of activities: ";
cin >> n;
vector<Activity> activities(n);
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
struct Task {
};
int main() {
int n;
cin >> n;
vector<Task> tasks(n);
int totalTime = 0;
totalTime += task.time;
maxHeap.push({task.time, task.index});
maxHeap.pop();
vector<int> selected;
selected.push_back(maxHeap.top().second);
maxHeap.pop();
sort(selected.begin(), selected.end());
cout << "Maximum number of tasks completed on time: " << selected.size() << "\n";
for (int idx : selected) cout << idx << " ";
return 0;
OUTPUT:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Function to find majority element using Boyer-Moore Voting Algorithm
OUTPUT:
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
// Function to print the optimal parenthesization
void printOrder(vector<vector<int>>& split, int i, int j) {
if (i == j) {
cout << "M" << i;
return;
OUTPUT:
OUTPUT:
#include <bits/stdc++.h>
using namespace std;
bool isSubsetSum(vector<int>& arr, int sum) {
int n = arr.size();
vector<vector<bool>> dp(n + 1, vector<bool>(sum + 1, false));
for(int i = 0 ; i < n + 1; i++){
dp[i][0] = true;
}
for(int i = 1; i < n + 1; i++){
for(int j = 1; j < sum + 1; j++){
if(j < arr[i - 1]) {
dp[i][j] = dp[i - 1][j];
int main() {
int n, sum = 0;
cout << "Enter the size of the array: " << endl;
cin >> n;
vector<int> arr(n);
cout << "Enter the elements of the array: " << endl;
for(int i = 0; i < n; i++){
cin >> arr[i];
sum += arr[i];
}
if(sum % 2 == 0) {
sum /= 2;
if (isSubsetSum(arr, sum)) cout << "Yes, can be partitioned into two subsets with equal sum." <<
endl;
else cout << "No, cannot be partitioned into equal sum subsets." << endl;
}
else cout << "No, cannot be partitioned into equal sum subsets" << endl;
return 0;
}
5. After filling the table, the value at dp[n][m] gives the length of the Longest Common
Subsequence.
6. Print the value of dp[n][m] as the result.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int longestCommonSubsequence(string s1, string s2) {
int n = s1.size();
int m = s2.size();
vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (s1[i - 1] == s2[j - 1])
dp[i][j] = 1 + dp[i - 1][j - 1];
else
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
9. Print the maximum value and the list of selected items with their weights and values.
#include <iostream>
#include <vector>
int knapsack(int idx, int cap, vector<int>& val, vector<int>& wt, vector<vector<int>>& memo) {
int c = cap;
vector<int> selectedItems;
if (i == 0) {
selectedItems.push_back(0);
selectedItems.push_back(i);
c -= wt[i];
cout << idx << "\t" << wt[idx] << "\t" << val[idx] << endl;
int main() {
int n;
cin >> n;
int capacity;
cout << "\nMaximum value achievable: " << maxVal << endl;
return 0;
6. Call permute with the sorted string and starting index 0 to generate and print all permutations in
lexicographical order.
#include <iostream>
#include <algorithm>
using namespace std;
void permute(string s, int start) {
if (start == (int)s.size()) {
cout << s << "\n";
return;
}
for (int i = start; i < (int)s.size(); i++) {
swap(s[start], s[i]);
permute(s, start + 1);
swap(s[start], s[i]); // backtrack
}
}
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter number of characters: ";
cin >> n;
char arr[n];
cout << "Enter characters:\n";
for (int i = 0; i < n; i++) {
cin >> arr[i];}
int freq[256] = {0};
for (int i = 0; i < n; i++) {
freq[(int)arr[i]]++;
}
cout << "Distinct characters and their frequencies:\n";
for (int i = 0; i < 256; i++) {
if (freq[i] > 0) cout << (char)i << " : " << freq[i] << "\n";
}
return 0;}
ALGORITHM-
1. Read the number of test cases T.
a. For each test case, do the following:
b. Read the size of the array n.
c. Read the n elements of the array.
d. Read the window size k.
e. Use a data structure (like a hash set) to keep track of elements in the current sliding
window of size k.
f. Traverse the array elements one by one:
i. For each element, check if it already exists in the hash set.
1. If yes, print "Duplicate present in window k" and stop checking for this
test case.
2. If no, add the element to the hash set.
ii. If the current window size exceeds k, remove the element that is left behind (i-k)
from the hash set to maintain the window size.
g. If the entire array is processed without finding duplicates within any window of size k,
print "Duplicate not present in window k".
2. Repeat for all test cases.
#include <iostream>
#include <unordered_set>
#include <vector>
unordered_set<int> window;
return true;
window.insert(arr[i]);
if (window.size() > k) {
window.erase(arr[i - k]);
return false;
int main() {
int T;
cin >> T;
int n, k;
cin >> n;
vector<int> arr(n);
if (containsDuplicateInWindow(arr, k)) {
} else {
return 0;
OUTPUT:
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
int main() {
int n;
cout << "Enter size: ";
cin >> n;
int a[n];
cout << "Enter elements:\n";
for (int i=0; i<n; i++) cin >> a[i];
unordered_map<int, vector<pair<int,int>>> mp;
for (int i=0; i<n; i++) {
OUTPUT:
#include <iostream>
#include <vector>
int nthUglyNumber(int n) {
vector<int> ugly(n);
ugly[0] = 1;
int i2 = 0, i3 = 0, i5 = 0;
ugly[i] = nextUgly;
if (nextUgly == next2) {
i2++;
next2 = ugly[i2] * 2;
if (nextUgly == next3) {
i3++;
next3 = ugly[i3] * 3;
if (nextUgly == next5) {
i5++;
next5 = ugly[i5] * 5;
int main() {
int T;
cin >> T;
while (T--) {
cin >> n;
cout << "The " << n << "th ugly number is: " << result << "\n";
return 0;
OUTPUT
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, m;
cout << "Enter vertices and edges: ";
cin >> n >> m;
vector<vector<int>> graph(n);
cout << "Enter edges (from to):\n";
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
graph[a].push_back(b);
}
int res = findMother(n, graph);
if (res == -1) cout << "No mother vertex\n";
else cout << "Mother vertex: " << res << "\n";
return 0;
}