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

Untitled Copy

Uploaded by

Nitin D
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Untitled Copy

Uploaded by

Nitin D
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 29

1)TRAVELLING SALESMAN PROBLEM:

#include <stdio.h>
#include <limits.h>
#define MAX 20
#define INF INT_MAX
int n;
int distance[MAX][MAX];
int cost_table[1 << MAX][MAX];
int travelling_salesman(int mask, int current) {
if (mask == (1 << n) - 1)
return distance[current][0];
if (cost_table[mask][current] != -1)
return cost_table[mask][current];
int min_cost = INF;
for (int city = 0; city < n; city++) {
if (!(mask & (1 << city))) {
int new_cost = distance[current][city] +
travelling_salesman(mask | (1 << city), city);
if (new_cost < min_cost)
min_cost = new_cost;
}
}
return cost_table[mask][current] = min_cost;
}
int main() {
printf("Enter the number of places: ");
scanf("%d", &n);
printf("Enter the distance matrix:\n");
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
scanf("%d", &distance[i][j]);
for (int i = 0; i < (1 << n); i++)
for (int j = 0; j < n; j++)
cost_table[i][j] = -1;
printf("The minimum cost to visit all places and return to the starting
point is: %d\n", travelling_salesman(1, 0));

return 0;
}

*****

2)Sum of subset:
#include <stdio.h>
#include <stdlib.h>

#define MAX 100

struct Node {
int subset[MAX];
int sum;
int level;
};

void subsetSum(int set[], int n, int targetSum, char method) {


struct Node queue[MAX];
int front = 0, rear = 0;
int solutionFound = 0;

struct Node root = {{0}, 0, 0};


queue[rear++] = root;

while (front != rear) {


struct Node currentNode;

if (method == 'F') {
currentNode = queue[front++];
} else {
currentNode = queue[--rear];
}

if (currentNode.sum == targetSum) {
printf("Subset with sum %d: { ", targetSum);
for (int i = 0; i < currentNode.level; i++) {
if (currentNode.subset[i]) {
printf("%d ", set[i]);
}
}
printf("}\n");
solutionFound = 1;
if (method == 'L') break;
}

if (currentNode.level < n) {
struct Node child1 = currentNode;
child1.level++;
queue[rear++] = child1;

if (currentNode.sum + set[currentNode.level] <= targetSum) {


struct Node child2 = currentNode;
child2.subset[child2.level] = 1;
child2.sum += set[currentNode.level];
child2.level++;
queue[rear++] = child2;
}
}
}

if (!solutionFound) {
printf("No subset with sum %d found.\n", targetSum);
}
}
int main() {
int set[MAX];
int n;
int targetSum;

printf("Name: AKULA LOKESH\n");


printf("Reg.no: 22BBS0223\n");

printf("Enter the number of elements in the set: ");


scanf("%d", &n);

printf("Enter the elements of the set:\n");


for (int i = 0; i < n; i++) {
scanf("%d", &set[i]);
}

printf("Enter the target sum: ");


scanf("%d", &targetSum);

printf("Finding all solutions using FIFO (BFS):\n");


subsetSum(set, n, targetSum, 'F');
printf("Finding one solution using LIFO (DFS):\n");
subsetSum(set, n, targetSum, 'L');
return 0;
}

*****

3)Largest common Subsequence


#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
int max(int a, int b) {
return (a > b) ? a : b;
}
void lcs_dp(char *s1, char *s2, int dp[][MAX_LEN]) {
int m = strlen(s1);
int n = strlen(s2);
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 || j == 0) {
dp[i][j] = 0;
} else if (s1[i - 1] == s2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
}
void find_all_lcs(char *s1, char *s2, int m, int n, int dp[][MAX_LEN],
char *lcs, int index) {
if (m == 0 || n == 0) {
lcs[index] = '\0';
printf("%s\n", lcs);
return;
}
if (s1[m - 1] == s2[n - 1]) {
lcs[index] = s1[m - 1];
find_all_lcs(s1, s2, m - 1, n - 1, dp, lcs, index - 1);
} else {
if (dp[m - 1][n] == dp[m][n]) {
find_all_lcs(s1, s2, m - 1, n, dp, lcs, index);
}
if (dp[m][n - 1] == dp[m][n]) {
find_all_lcs(s1, s2, m, n - 1, dp, lcs, index);
}
}
}
int main() {
char s1[MAX_LEN], s2[MAX_LEN];
int dp[MAX_LEN][MAX_LEN];
printf("Name: AKULA LOKESH\n");
printf("Reg.no: 22BBS0223\n");
printf("Enter the first string: ");
scanf("%s", s1);
printf("Enter the second string: ");
scanf("%s", s2);
int m = strlen(s1);
int n = strlen(s2);
lcs_dp(s1, s2, dp);
int lcs_length = dp[m][n];
printf("Length of the longest common subsequence: %d\n",
lcs_length);
printf("All Longest Common Subsequences:\n");
char lcs[MAX_LEN];
find_all_lcs(s1, s2, m, n, dp, lcs, lcs_length - 1);
return 0;
}
*****

4)Kruskal maximum spanning tree:

#include <stdio.h>
#include <stdlib.h>

// Structure to represent an edge


struct Edge {
int src, dest, weight;
};
// Structure to represent a graph
struct Graph {
int V, E;
struct Edge* edges;
};

// Compare function for qsort to sort edges in descending order of


weights
int compare(const void* a, const void* b) {
return ((struct Edge*)b)->weight - ((struct Edge*)a)->weight;
}

// Find function for Union-Find


int find(int parent[], int i) {
if (parent[i] == -1)
return i;
return find(parent, parent[i]);
}

// Union function for Union-Find


void unionSet(int parent[], int x, int y) {
parent[x] = y;
}

// Function to perform Kruskal's Algorithm to find the Maximum


Spanning Tree
void kruskalMaxST(struct Graph* graph) {
int maxWeight = 0;
int* parent = (int*)malloc(graph->V * sizeof(int));

// Initialize all vertices as their own parent


for (int i = 0; i < graph->V; i++)
parent[i] = -1;

// Sort edges in descending order of their weights


qsort(graph->edges, graph->E, sizeof(graph->edges[0]), compare);

printf("Edges in the Maximum Spanning Tree:\n");

// Iterate through the edges


for (int i = 0; i < graph->E; i++) {
int x = find(parent, graph->edges[i].src);
int y = find(parent, graph->edges[i].dest);

// If including this edge does not form a cycle


if (x != y) {
printf("%d -- %d == %d\n", graph->edges[i].src + 1, graph-
>edges[i].dest + 1, graph->edges[i].weight);
unionSet(parent, x, y);
maxWeight += graph->edges[i].weight;
}
}

printf("Maximum weight of the spanning tree is: %d\n", maxWeight);


free(parent);
}

int main() {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->V = 7; // Number of vertices
graph->E = 9; // Number of edges

graph->edges = (struct Edge*)malloc(graph->E * sizeof(struct


Edge));

// Add edges to the graph


graph->edges[0] = (struct Edge){0, 5, 10};
graph->edges[1] = (struct Edge){0, 1, 28};
graph->edges[2] = (struct Edge){5, 4, 25};
graph->edges[3] = (struct Edge){4, 6, 24};
graph->edges[4] = (struct Edge){4, 3, 22};
graph->edges[5] = (struct Edge){6, 3, 18};
graph->edges[6] = (struct Edge){3, 2, 12};
graph->edges[7] = (struct Edge){2, 1, 16};
graph->edges[8] = (struct Edge){1, 6, 14};

// Run Kruskal's algorithm for Maximum Spanning Tree


kruskalMaxST(graph);

// Free allocated memory


free(graph->edges);
free(graph);

return 0;
}

*****

****

5)Knapsack PROBLEM:
#include <stdio.h>
#include <stdlib.h>

typedef struct {
int weight;
int profit;
float ratio; // profit-to-weight ratio
} Item;

int compareByRatio(const void* a, const void* b) {


float r1 = ((Item*)a)->ratio;
float r2 = ((Item*)b)->ratio;
return (r1 > r2) ? -1 : (r1 < r2) ? 1 : 0;
}

int compareByProfit(const void* a, const void* b) {


int p1 = ((Item*)a)->profit;
int p2 = ((Item*)b)->profit;
return (p1 > p2) ? -1 : (p1 < p2) ? 1 : 0;
}

int compareByWeight(const void* a, const void* b) {


int w1 = ((Item*)a)->weight;
int w2 = ((Item*)b)->weight;
return (w1 < w2) ? -1 : (w1 > w2) ? 1 : 0;
}

float fractionalKnapsack(int capacity, Item items[], int n, int (comp)


(const void, const void*)) {
qsort(items, n, sizeof(Item), comp);

int i;
float totalProfit = 0.0;
for (i = 0; i < n; i++) {
if (capacity == 0)
break;
if (items[i].weight <= capacity) {
totalProfit += items[i].profit;
capacity -= items[i].weight;
} else {
totalProfit += items[i].profit * ((float)capacity / items[i].weight);
capacity = 0;
}
}
return totalProfit;
}
int main() {
int n;
printf("Enter the number of items: ");
scanf("%d", &n);
Item items[n];
int capacity;
printf("Enter the weights and profits of each item:\n");
for (int i = 0; i < n; i++) {
printf("Item %d - Weight: ", i + 1);
scanf("%d", &items[i].weight);
printf("Item %d - Profit: ", i + 1);
scanf("%d", &items[i].profit);
items[i].ratio = (float)items[i].profit / items[i].weight;
}
printf("Enter the capacity of the knapsack: ");
scanf("%d", &capacity);
printf("Maximum profit (using profit-to-weight ratio): %.2f\n",
fractionalKnapsack(capacity, items, n, compareByRatio));
printf("Maximum profit (using profit): %.2f\n",
fractionalKnapsack(capacity, items, n, compareByProfit));
printf("Maximum profit (using weight): %.2f\n",
fractionalKnapsack(capacity, items, n, compareByWeight));

return 0;
}

*****

6)Graph coloring:
#include <stdio.h>
#define MAX_V 100

int graph[MAX_V][MAX_V];
int colour[MAX_V];
int n;

int issafe(int c, int v) {


for (int i = 0; i < n; i++) {
if (graph[v][i] == 1 && c == colour[i]) {
return 0;
}
}
return 1;
}

int graphcolouruntil(int m, int v) {


if (v == n) {
return 1;
}
for (int c = 1; c <= m; c++) {
if (issafe(c, v)) {
colour[v] = c;
if (graphcolouruntil(m, v + 1)) {
return 1;
}
colour[v] = 0;
}
}
return 0;
}

int graphcolouring(int m) {
for (int i = 0; i < n; i++) {
colour[i] = 0;
}
if (!graphcolouruntil(m, 0)) {
printf("Solution does not exist\n");
return 0;
}

printf("\nSolution exists\n");
for (int i = 0; i < n; i++) {
printf("Vertex %d ----> Colour %d\n", i + 1, colour[i]);
}
return 1;
}

int main() {
printf("22BBS0256 - Sanjai K\n");

int c;
printf("Enter the number of vertices: ");
scanf("%d", &n);

printf("Enter the adjacency matrix:\n");


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &graph[i][j]);
}
}
printf("Enter the number of colours: ");
scanf("%d", &c);

graphcolouring(c);

return 0;
}

*****

7)Ford fulkerson:

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define MAX_NODES 1000
#define INF 1000000000

int capacity[MAX_NODES][MAX_NODES];
int flow[MAX_NODES][MAX_NODES];
int n;

// Breadth-First Search for finding augmenting paths


bool bfs(int source, int sink, int parent[]) {
bool visited[MAX_NODES] = {false};
int queue[MAX_NODES], front = 0, rear = 0;

queue[rear++] = source;
visited[source] = true;
parent[source] = -1;

while (front < rear) {


int u = queue[front++];
for (int v = 0; v < n; v++) {
if (!visited[v] && capacity[u][v] - flow[u][v] > 0) {
queue[rear++] = v;
parent[v] = u;
visited[v] = true;
}
}
}
return visited[sink];
}

// Ford-Fulkerson algorithm to find max flow


int fordFulkerson(int source, int sink) {
int u, v;
int parent[MAX_NODES];
int max_flow = 0;

// Augment flow while there is a path from source to sink


while (bfs(source, sink, parent)) {
// Find the maximum flow through the path found by BFS
int path_flow = INF;
for (v = sink; v != source; v = parent[v]) {
u = parent[v];
path_flow = path_flow < capacity[u][v] - flow[u][v] ? path_flow :
capacity[u][v] - flow[u][v];
}

// Update residual capacities of the edges and reverse edges


for (v = sink; v != source; v = parent[v]) {
u = parent[v];
flow[u][v] += path_flow;
flow[v][u] -= path_flow;
}

max_flow += path_flow;
}

return max_flow;
}

int main() {
printf("22BBS0256 - Sanjai K\n");

n = 9; // Number of nodes
memset(capacity, 0, sizeof(capacity)); // Initialize capacity matrix to
0

// Define the graph's capacity


capacity[0][1] = 6;
capacity[0][2] = 1;
capacity[0][3] = 10;
capacity[1][2] = 2;
capacity[1][4] = 4;
capacity[1][5] = 1;
capacity[2][5] = 20;
capacity[3][2] = 2;
capacity[3][6] = 5;
capacity[4][5] = 2;
capacity[4][7] = 5;
capacity[5][6] = 6;
capacity[5][7] = 10;
capacity[6][8] = 4;
capacity[7][8] = 12;

// Run the Ford-Fulkerson algorithm


printf("Max Flow By Ford-Fulkerson Algorithm is %d\n",
fordFulkerson(0, 8));
return 0;
}

*****

8)Djikstra algorithm:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>

#define V 7

int minDistance(int dist[], int sptSet[]) {


int min = INT_MAX, min_index;
for (int v = 0; v < V; v++) {
if (sptSet[v] == 0 && dist[v] <= min) {
min = dist[v];
min_index = v;
}
}
return min_index;
}
void printSolution(int dist[], int n) {
printf("Vertex Distance from Source\n");
for (int i = 0; i < V; i++) {
printf("%d \t\t %d\n", i, dist[i]);
}
}

void printPath(int parent[], int j) {


if (parent[j] == -1) return;
printPath(parent, parent[j]);
printf("%d ", j);
}

void dijkstra(int graph[V][V], int src) {


int dist[V];
int sptSet[V];
int parent[V];

for (int i = 0; i < V; i++) {


dist[i] = INT_MAX;
sptSet[i] = 0;
parent[i] = -1;
}
dist[src] = 0;

for (int count = 0; count < V - 1; count++) {


int u = minDistance(dist, sptSet);
sptSet[u] = 1;

printf("Removed vertex: %d\n", u); // Print the removed vertex

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


if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] +
graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
parent[v] = u;
}
}
}

printf("\nShortest Path Tree:\n");


for (int i = 0; i < V; i++) {
if (i != src) {
printf("Path from %d to %d: ", src, i);
printPath(parent, i);
printf("\n");
}
}
printSolution(dist, V);
}

int mapNode(char node) {


if (node == 'S') return 0;
else if (node == 'A') return 1;
else if (node == 'B') return 2;
else if (node == 'C') return 3;
else if (node == 'D') return 4;
else if (node == 'E') return 5;
else if (node == 'F') return 6;
return -1;
}

int main() {
int graph[V][V] = {
{0, 3, 0, 2, 0, 0, 6},
{0, 0, 6, 0, 1, 0, 0},
{0, 0, 0, 0, 0, 1, 0},
{0, 2, 0, 0, 3, 0, 0},
{0, 0, 0, 0, 0, 4, 0},
{0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 2, 0}
};
char startNode = 'S';
int src = mapNode(startNode);

dijkstra(graph, src);

return 0;
}

*****

9)Bellman ford:

#include <stdio.h>
#include <limits.h>

int V; // Number of vertices


int E; // Number of edges

struct Edge {
int src, dest, weight;
};

// Function to implement Bellman-Ford algorithm


void bellmanFord(struct Edge edges[], int src) {
int dist[V];

// Step 1: Initialize distances from src to all other vertices as


INFINITE
for (int i = 0; i < V; i++) {
dist[i] = INT_MAX;
}
dist[src] = 0;

// Step 2: Relax all edges |V| - 1 times


for (int i = 1; i <= V - 1; i++) {
for (int j = 0; j < E; j++) {
int u = edges[j].src;
int v = edges[j].dest;
int weight = edges[j].weight;
if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
}
}
}

// Step 3: Check for negative-weight cycles


for (int j = 0; j < E; j++) {
int u = edges[j].src;
int v = edges[j].dest;
int weight = edges[j].weight;
if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) {
printf("Graph contains negative weight cycle\n");
return;
}
}

// Print the distances


printf("Vertex Distance from Source\n");
for (int i = 0; i < V; i++) {
printf("%d \t\t %d\n", i + 1, dist[i]);
}
}

int main() {
printf("22BBS0256 - Sanjai K\n");

printf("Enter number of vertices: ");


scanf("%d", &V);

printf("Enter number of edges: ");


scanf("%d", &E);

struct Edge edges[E];

printf("Enter the source, destination, and weight for each edge:\n");


for (int i = 0; i < E; i++) {
int s, d, w;
scanf("%d %d %d", &s, &d, &w);
edges[i].src = s - 1;
edges[i].dest = d - 1;
edges[i].weight = w;
}

bellmanFord(edges, 0);

return 0;
}

You might also like