0% found this document useful (0 votes)
14 views68 pages

Daa Notes

The document contains C code implementations for various algorithms, including the Knapsack problem, Floyd-Warshall algorithm for shortest paths, and matrix chain multiplication. It also includes solutions for the N-Queens problem and the Traveling Salesman Problem (TSP). Each section of the code is structured with functions for input, processing, and output of results.

Uploaded by

ruthvikamburayrk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views68 pages

Daa Notes

The document contains C code implementations for various algorithms, including the Knapsack problem, Floyd-Warshall algorithm for shortest paths, and matrix chain multiplication. It also includes solutions for the N-Queens problem and the Traveling Salesman Problem (TSP). Each section of the code is structured with functions for input, processing, and output of results.

Uploaded by

ruthvikamburayrk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

1 #include <stdio.h> 1 #include <stdio.

h>
2 #include <stdlib.h> 2
3 3 int max(int a, int b) { return (a > b) ? a : b; }
4 #define INF 99999 4
5 5 int knapSack(int W, int wt[], int val[], int n) {
6 void printSolution(int **dist, int V) { 6 if (n == 0 || W == 0)
7 printf("The following matrix shows the shortest distances between every pair of 7 return 0;
vertices\n"); 8 if (wt[n - 1] > W)
8 for (int i = 0; i < V; i++) { 9 return knapSack(W, wt, val, n - 1);
9 for (int j = 0; j < V; j++) { 10 else
10 if (dist[i][j] == INF) 11 return max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), knapSack(W, wt,
11 printf("%7s", "INF"); val, n - 1));
12 else 12 }
13 printf("%7d", dist[i][j]); 13
14 } 14 int main() {
15 printf("\n"); 15 int n, W;
16 } 16
17 } 17 printf("Enter the number of items: ");
18 18 scanf("%d", &n);
19 void floydWarshall(int **dist, int V) { 19
20 for (int k = 0; k < V; k++) { 20 int val[n], wt[n];
21 for (int i = 0; i < V; i++) { 21
22 for (int j = 0; j < V; j++) { 22 printf("Enter the values of the items:\n");
23 if (dist[i][k] + dist[k][j] < dist[i][j]) 23 for (int i = 0; i < n; i++) {
24 dist[i][j] = dist[i][k] + dist[k][j]; 24 scanf("%d", &val[i]);
25 } 25 }
26 } 26
27 } 27 printf("Enter the weights of the items:\n");
28 printSolution(dist, V); 28 for (int i = 0; i < n; i++) {
29 } 29 scanf("%d", &wt[i]);
30 int main() { 30 }
31 int V; 31
32 printf("Enter the number of vertices: "); 32 printf("Enter the capacity of the knapsack: ");
33 scanf("%d", &V); 33 scanf("%d", &W);
34 int **graph = (int **)malloc(V * sizeof(int *)); 34
35 for (int i = 0; i < V; i++) { 35 printf("Maximum value in Knapsack = %d\n", knapSack(W, wt, val, n));
36 graph[i] = (int *)malloc(V * sizeof(int)); 36 return 0;
37 } 37 }
38 printf("Enter the adjacency matrix (use %d for INF):\n", INF); 38
39 for (int i = 0; i < V; i++) {
40 for (int j = 0; j < V; j++) {
41 scanf("%d", &graph[i][j]);
42 }
43 }
44 floydWarshall(graph, V);
45 for (int i = 0; i < V; i++) {
46 free(graph[i]);
47 }
48 free(graph);
49 return 0;
50 }
51
1 #include <stdio.h> 1 #include <stdio.h>
2 #include <limits.h> 2 #include <stdlib.h>
3 3 #include <stdbool.h>
4 void printParenthesis(int i, int j, int n, int *bracket, char *name) { 4
5 if (i == j) { 5 int **res;
6 printf("%c", (*name)++); 6 int rCount = 0;
7 return; 7
8 } 8 bool isSafe(int **board, int row, int col, int N) {
9 printf("("); 9 int i, j;
10 printParenthesis(i, *((bracket + j * n) + i), n, bracket, name); 10 for (i = 0; i < col; i++)
11 printParenthesis(*((bracket + j * n) + i) + 1, j, n, bracket, name); 11 if (board[row][i])
12 printf(")"); 12 return false;
13 } 13 for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
14 14 if (board[i][j])
15 void matrixChainOrder(int p[], int n) { 15 return false;
16 int m[n][n]; 16 for (i = row, j = col; j >= 0 && i < N; i++, j--)
17 for (int i = 1; i < n; i++) 17 if (board[i][j])
18 m[i][i] = 0; 18 return false;
19 for (int L = 2; L < n; L++) { 19 return true;
20 for (int i = 1; i < n - L + 1; i++) { 20 }
21 int j = i + L - 1; 21
22 m[i][j] = INT_MAX; 22 bool solveNQUtil(int **board, int col, int N) {
23 for (int k = i; k <= j - 1; k++) { 23 if (col == N) {
24 int q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; 24 res[rCount] = (int *)malloc(N * sizeof(int));
25 if (q < m[i][j]) { 25 for (int i = 0; i < N; i++) {
26 m[i][j] = q; 26 for (int j = 0; j < N; j++) {
27 m[j][i] = k; 27 if (board[i][j] == 1)
28 } 28 res[rCount][j] = i + 1;
29 } 29 }
30 } 30 }
31 } 31 rCount++;
32 char name = 'A'; 32 return true;
33 printf("Optimal Parenthesization is: "); 33 }
34 printParenthesis(1, n - 1, n, (int *)m, &name); 34 bool res = false;
35 printf("\nOptimal Cost is : %d\n", m[1][n - 1]); 35 for (int i = 0; i < N; i++) {
36 } 36 if (isSafe(board, i, col, N)) {
37 37 board[i][col] = 1;
38 int main() { 38 res = solveNQUtil(board, col + 1, N) || res;
39 int n; 39 board[i][col] = 0;
40 printf("Enter no. of matrices: "); 40 }
41 scanf("%d", &n); 41 }
42 int arr[n + 1]; 42 return res;
43 printf("Enter the dimensions of matrices in an array: "); 43 }
44 for (int i = 0; i < n + 1; i++) 44
45 scanf("%d", &arr[i]); 45 void nQueen(int n) {
46 matrixChainOrder(arr, n + 1); 46 rCount = 0;
47 return 0; 47 res = (int **)malloc(100 * sizeof(int *));
48 } 48 int **board = (int **)malloc(n * sizeof(int *));
49 49 for (int i = 0; i < n; i++) {
50 board[i] = (int *)malloc(n * sizeof(int));
51 for (int j = 0; j < n; j++)
52 board[i][j] = 0;
53 }
54 if (solveNQUtil(board, 0, n) == false) {
55 printf("Solution does not exist");
56 return;
57 }
58 for (int i = 0; i < rCount; i++) {
59 printf("[");
60 for (int j = 0; j < n; j++)
61 printf("%d ", res[i][j]);
62 printf("]\n");
63 }
64 for (int i = 0; i < n; i++)
65 free(board[i]);
66 free(board);
67 }
68
69 int main() {
70 int n; 1 //tsp_bb
71 printf("Enter the number of queens: "); 2 #include <stdio.h>
72 scanf("%d", &n); 3 #include <stdlib.h>
73 nQueen(n); 4 #include <limits.h>
74 return 0; 5 #include <stdbool.h>
75 } 6 #define INF 99999
76 7 int findMinCost(int i, int graph[][20], int V) {
8 int min = INF;
9 for (int k = 0; k < V; k++)
10 if (graph[i][k] && graph[i][k] < min)
11 min = graph[i][k];
12 return min;
13 }
14 int findSecondMinCost(int i, int graph[][20], int V) {
15 int first = INF, second = INF;
16 for (int j = 0; j < V; j++) {
17 if (i == j)
18 continue;
19 if (graph[i][j] <= first) {
20 second = first;
21 first = graph[i][j];
22 }
23 else if (graph[i][j] <= second && graph[i][j] != first)
24 second = graph[i][j];
25 }
26 return second;
27 }
28 void printSolution(int path[], int V) {
29 printf("Path: ");
30 for (int i = 0; i < V; i++)
31 printf("%d ", path[i]);
32 printf("%d\n", path[0]);
33 }
34 void TSPRec(int graph[][20], int curr_bound, int curr_weight, int level, int curr_path[],
bool visited[], int V, int *final_res, int final_path[]) {
35 if (level == V) {
36 if (graph[curr_path[level-1]][curr_path[0]] != 0) {
37 int curr_res = curr_weight + graph[curr_path[level-1]][curr_path[0]];
38 if (curr_res < *final_res) {
39 for (int i = 0; i < V; i++)
40 final_path[i] = curr_path[i];
41 final_path[V] = curr_path[0];
42 *final_res = curr_res;
43 }
44 }
45 return;
46 }
47 for (int i = 0; i < V; i++) {
48 if (graph[curr_path[level-1]][i] != 0 && visited[i] == false) {
49 int temp = curr_bound;
50 curr_weight += graph[curr_path[level-1]][i];
51
52 if (level == 1)
53 curr_bound -= ((findMinCost(curr_path[level-1], graph, V) + findMinCost(i
, graph, V)) / 2);
54 else
55 curr_bound -= ((findSecondMinCost(curr_path[level-1], graph, V) +
findMinCost(i, graph, V)) / 2);
56
57 if (curr_bound + curr_weight < *final_res) {
58 curr_path[level] = i;
59 visited[i] = true;
60
61 TSPRec(graph, curr_bound, curr_weight, level+1, curr_path, visited, V,
final_res, final_path);
62 }
63 curr_weight -= graph[curr_path[level-1]][i];
64 curr_bound = temp;
65 for (int k = 0; k < V; k++)
66 visited[k] = false; 1 #include <stdio.h>
67 for (int j = 0; j <= level-1; j++) 2 #include <stdbool.h>
68 visited[curr_path[j]] = true; 3
69 } 4 #define mv 10
70 } 5
71 } 6 bool isSafe(int v, int graph[mv][mv], int color[], int c) {
72 void TSP(int graph[][20], int V) { 7 for (int i = 0; i < mv; i++) {
73 int curr_path[V+1]; 8 if (graph[v][i] && c == color[i]) {
74 int final_path[V+1]; 9 return false;
75 bool visited[V]; 10 }
76 int curr_bound = 0; 11 }
77 for (int i = 0; i < V; i++) 12 return true;
78 curr_bound += (findMinCost(i, graph, V) + findSecondMinCost(i, graph, V)); 13 }
79 14
80 curr_bound = (curr_bound & 1) ? curr_bound/2 + 1 : curr_bound/2; 15 void graphColoringUtil(int graph[mv][mv], int numVertices, int m, int color[], int v, int
81 for (int i = 0; i < V; i++) *count) {
82 visited[i] = false; 16 if (v == numVertices) {
83 visited[0] = true; 17 (*count)++;
84 curr_path[0] = 0; 18 for (int i = 0; i < numVertices; i++) {
85 int final_res = INF; 19 printf(" %d ", color[i]);
86 TSPRec(graph, curr_bound, 0, 1, curr_path, visited, V, &final_res, final_path); 20 }
87 printf("Minimum cost : %d\n", final_res); 21 printf("\n");
88 printSolution(final_path, V); 22 return;
89 } 23 }
90 int main() { 24
91 int V; 25 for (int c = 1; c <= m; c++) {
92 printf("Enter the number of vertices: "); 26 if (isSafe(v, graph, color, c)) {
93 scanf("%d", &V); 27 color[v] = c;
94 int graph[20][20]; 28 graphColoringUtil(graph, numVertices, m, color, v + 1, count);
95 printf("Enter the adjacency matrix of the graph (use %d for no edge):\n", INF); 29 color[v] = 0;
96 for (int i = 0; i < V; i++) { 30 }
97 for (int j = 0; j < V; j++) { 31 }
98 scanf("%d", &graph[i][j]); 32 }
99 } 33
100 } 34 void graphColoring(int graph[mv][mv], int numVertices, int m) {
101 TSP(graph, V); 35 int color[mv] = {0};
102 return 0; 36 int count = 0;
103 } 37 printf("The Coloring possibilities are:\n");
104 38 graphColoringUtil(graph, numVertices, m, color, 0, &count);
39 if (count == 0) {
40 printf("No valid colorings found.\n");
41 }
42 }
43
44 int main() {
45 int numVertices, numEdges, m;
46 int graph[mv][mv] = {{0}};
47
48 printf("The maximum possible colors that can be assigned are: ");
49 scanf("%d", &m);
50 printf("Enter no of edges:");
51 scanf("%d",&numEdges);
52 printf("Enter no of Vertices:");
53 scanf("%d",&numVertices);
54 printf("Enter u and v for each edge:\n");
55 for (int i = 0; i < numEdges; i++) {
56 int u, v;
57 printf("For edge-%d: ", i + 1);
58 scanf("%d %d", &u, &v);
59 graph[u-1][v-1] = graph[v-1][u-1] = 1;
60 }
61 graphColoring(graph, numVertices, m);
62 return 0;
63 }
64
1 ALGORITHMS: 68 return
2 MATRIX CHAIN MULTIPLICATION 69
3 Function matrixChainOrder(p, n) 70 r = root[i][j]
4 Initialize 2D array m of size n x n 71
5 for i = 1 to n-1 72 if parent == 0
6 m[i][i] = 0 73 Print "Root of the tree: " and keys[r]
7 74 else if r < parent
8 for L = 2 to n-1 75 Print "Left child of " and keys[parent] and ": " and keys[r]
9 for i = 1 to n-L 76 else
10 j = i + L - 1 77 Print "Right child of " and keys[parent] and ": " and keys[r]
11 m[i][j] = INT_MAX 78
12 for k = i to j-1 79 Call printOptimalBST(root, keys, i, r-1, keys[r])
13 q = m[i][k] + m[k+1][j] + p[i-1] * p[k] * p[j] 80 Call printOptimalBST(root, keys, r+1, j, keys[r])
14 if q < m[i][j] 81
15 m[i][j] = q 82
16 m[j][i] = k 83 0/1 KNAPSACK PROBLEM USING DP
17 84 Function knapsack(values, weights, n, W)
18 85 // values[] is the array of values of the items
19 ALL PAIR SHORTEST PATH 86 // weights[] is the array of weights of the items
20 Function floydWarshall(dist, V) 87 // n is the number of items
21 for k from 0 to V-1 88 // W is the maximum capacity of the knapsack
22 for i from 0 to V-1 89
23 for j from 0 to V-1 90 // Create a 2D array dp where dp[i][w] represents the maximum value
24 if dist[i][k] + dist[k][j] < dist[i][j] 91 // achievable with the first i items and capacity w
25 dist[i][j] = dist[i][k] + dist[k][j] 92 Initialize dp[n+1][W+1] with 0
26 93
27 Call printSolution(dist, V) 94 // Build the dp array
28 95 for i from 1 to n
29 96 for w from 0 to W
30 OPTIMAL BINARY SEARCH TREE 97 if weights[i-1] <= w
31 Function optimalBST(keys, freq, n) 98 // Item i can be included in the optimal subset
32 // keys[] is the array of keys in sorted order 99 dp[i][w] = max(dp[i-1][w], values[i-1] + dp[i-1][w-weights[i-1]])
33 // freq[] is the array of frequencies for each key 100 else
34 // n is the number of keys 101 // Item i cannot be included in the optimal subset
35 102 dp[i][w] = dp[i-1][w]
36 // Create a 2D array cost[][] where cost[i][j] will store the minimum cost of the 103
BST that can be formed from keys[i] to keys[j] 104 // The maximum value that can be put in a knapsack of capacity W
37 Initialize cost[n][n] with 0 105 Return dp[n][W]
38 106
39 // Create a 2D array root[][] to store the root index of the subtree formed by 107 Function main()
keys[i] to keys[j] 108 Define values[] as the array of item values
40 Initialize root[n][n] with 0 109 Define weights[] as the array of item weights
41 110 Define n as the number of items
42 // Initialize the diagonal of cost matrix 111 Define W as the maximum capacity of the knapsack
43 for i from 0 to n-1 112
44 cost[i][i] = freq[i] 113 Call knapsack(values, weights, n, W)
45 root[i][i] = i 114 Print "Maximum value in Knapsack =", result
46 115
47 // L is the chain length 116
48 for L from 2 to n 117 RELIABILITY DESIN USING DP:
49 for i from 0 to n-L+1 118 Function reliabilityDesign(reliabilities, costs, budget, n)
50 j = i + L - 1 119 // reliabilities[] is a 2D array where reliabilities[i][j] is the reliability of the
51 cost[i][j] = infinity j-th component of type i
52 sum_freq = sum of freq[k] for k from i to j 120 // costs[] is a 2D array where costs[i][j] is the cost of the j-th component of type
53 i
54 for r from i to j 121 // budget is the total budget available
55 c = ((r > i) ? cost[i][r-1] : 0) + 122 // n is the number of types of components
56 ((r < j) ? cost[r+1][j] : 0) + 123
57 sum_freq 124 // Create a 2D array dp where dp[i][b] represents the maximum reliability achievable
58 with the first i types of components and budget b
59 if c < cost[i][j] 125 Initialize dp[n+1][budget+1] with 0
60 cost[i][j] = c 126
61 root[i][j] = r 127 // Initialize the dp array
62 128 for i from 0 to n
63 Print "Optimal Cost: " and cost[0][n-1] 129 for b from 0 to budget
64 Call printOptimalBST(root, keys, 0, n-1, 0) 130 dp[i][b] = 1.0 // Since the product of reliabilities starts from 1
65 131
66 Function printOptimalBST(root, keys, i, j, parent) 132 // Build the dp array
67 if i > j 133 for i from 1 to n
134 for b from 0 to budget
135 // Check all components of type i-1
136 for j from 0 to number of components of type i-1
137 cost = costs[i-1][j]
138 reliability = reliabilities[i-1][j]
139 if cost <= b
140 dp[i][b] = max(dp[i][b], dp[i-1][b-cost] * reliability)
141
142 // The maximum reliability that can be achieved within the budget
143 Return dp[n][budget]
144
145 Function main()
146 Define reliabilities as the 2D array of component reliabilities
147 Define costs as the 2D array of component costs
148 Define budget as the total budget
149 Define n as the number of types of components
150
151 max_reliability = reliabilityDesign(reliabilities, costs, budget, n)
152 Print "Maximum system reliability =", max_reliability
153
154
155
156 TSP USING DP:
157 Function tsp(dist, n)
158 // dist is a 2D array where dist[i][j] is the distance between city i and city j
159 // n is the number of cities
160
161 // Create a 2D array dp where dp[mask][i] represents the minimum cost to visit all
the cities in mask ending at city i
162 Initialize dp[2^n][n] with infinity
163 Initialize dp[1][0] = 0 // Starting at city 0 with only city 0 visited
164
165 // Build the dp array
166 for mask from 1 to 2^n - 1
167 for i from 0 to n - 1
168 if mask & (1 << i) // If city i is in the subset represented by mask
169 for j from 0 to n - 1
170 if mask & (1 << j) and i != j // If city j is in the subset and j is
not equal to i
171 dp[mask][i] = min(dp[mask][i], dp[mask ^ (1 << i)][j] +
dist[j][i])
172
173 // Find the minimum cost to visit all cities and return to the starting city
174 Initialize res with infinity
175 for i from 1 to n - 1
176 res = min(res, dp[(2^n) - 1][i] + dist[i][0])
177
178 Return res
179
180 Function main()
181 Define dist as the 2D array of distances between cities
182 Define n as the number of cities
183
184 min_cost = tsp(dist, n)
185 Print "Minimum cost of visiting all cities =", min_cost
186

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy