0% found this document useful (0 votes)
98 views14 pages

DMDA

The document discusses code for finding the minimum spanning tree of a graph using Kruskal's algorithm. It includes data structures to represent a weighted edge and graph. The Graph structure contains the number of vertices and edges, and an edge array. A function is defined to create a graph with a given number of vertices and edges. The code provides the framework to implement Kruskal's algorithm to find the minimum spanning tree.

Uploaded by

Kartik Vish
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)
98 views14 pages

DMDA

The document discusses code for finding the minimum spanning tree of a graph using Kruskal's algorithm. It includes data structures to represent a weighted edge and graph. The Graph structure contains the number of vertices and edges, and an edge array. A function is defined to create a graph with a given number of vertices and edges. The code provides the framework to implement Kruskal's algorithm to find the minimum spanning tree.

Uploaded by

Kartik Vish
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/ 14

1 //1. WAP to perform union, intersection, addition and subtraction on the two sets given by the user.

2 //2. WAP to perform union, intersection, addition and subtraction on the two multisets given by the user.
3
4 //CODE:
5
6 #include<conio.h>
7 #include<iostream.h>
8 #include<stdio.h>
9
10 int max(int a,int b){
11 if(a>b)
12 return a;
13 else
14 return b;
15 }
16
17
18 int main(){
19 clrscr();
20 getch();
21 int na,nb,t,i,j;
22 int a[1000]={0};
23 int b[1000]={0};
24 int u[1000]={0};
25 int in[1000]={0};
26 cout<<"Enter number of elements of set A:\t";
27 cin>>na;
28 cout<<"Enter number of elements of set B:\t";
29 cin>>nb;
30 for(i=0;i<na;i++){
31 cout<<"Enter Element "<<i+1<<" of set A:\t";
32 cin>>t;
33 a[t]++;
34 }
35 for(i=0;i<nb;i++){
36 cout<<"Enter Element "<<i+1<<" of set B:\t";
37 cin>>t;
38 b[t]++;
39 }
40 for(i=0;i<1000;i++){
41 u[i]=u[i]+a[i]+b[i];
42 }
43 for(i=0;i<1000;i++){
44 if(a[i]>0&&b[i]>0)
45 in[i]=in[i]+max(a[i],b[i]);
46 }
47 cout<<"\nUnion of normal set: ";
48 for(i=0;i<1000;i++){
49 if(u[i]>0)
50 cout<<i<<" ";
51 }
52 cout<<"\nIntersection of normal set: ";
53 for(i=0;i<1000;i++){
54 if(in[i]>0)
55 cout<<i<<" ";
56 }
57 cout<<"\nUnion of Multiset: ";
58 for(i=0;i<1000;i++){
59 if(u[i]>0){
60 for(j=0;j<=u[i];j++)
61 cout<<i<<" ";
62 }
63 }
64 cout<<"\nIntersection of Meltiset: ";
65 for(i=0;i<1000;i++){
66 if(in[i]>0){
67 for(j=0;j<=in[i];j++)
68 cout<<i<<" ";
69 }
70 }
71 getch();
72 return 1;
73 }
74
1 //3. WAP to check whether the given relation is equivalence or not.
2 #include<stdio.h>
3 #include<stdlib.h>
4 #define N 100
5 int matrix[N][N];
6 int main(){
7 int relation[N][2],i,n,set[N],elements=0,j,row,col,flag,mat_sq[N][N];
8 printf("\n\n\tEnter the no of relations:");
9 scanf("%d",&n);
10 for(elements,i=0;i<n;i++){
11 printf("\tEnter element of domain of relation %d:",i+1);
12 scanf("%d",&relation[i][0]);
13 for(j=0;j<elements&&set[j]!=relation[i][0];++j);
14 if(j==elements)set[elements++]=relation[i][0];
15 printf("\tEnter element of range of relation %d:",i+1);
16 scanf("%d",&relation[i][1]);
17 for(j=0;j<elements&&set[j]!=relation[i][1];++j);
18 if(j==elements)set[elements++]=relation[i][1];
19 }
20 for(i=0;i<n;++i){
21 for(row=0;row<elements&&set[row]!=relation[i][0];++row);
22 for(col=0;col<elements&&set[col]!=relation[i][1];++col);
23 matrix[row][col]=1;
24 }
25 for(i=0;i<elements&&matrix[i][i];++i);
26 if(i==elements)printf("\n\n\tRelation is reflexive");
27 for(flag=0,i=0;i<elements&&!flag;++i)for(j=0;j<elements-i&&!flag;j++)if(matrix[i][j]!=matrix[j][i])flag=1;
28 if(!flag)printf("\n\tRelation is symmetric");
29 for(row=0;row<elements;++row)for(col=0;col<elements;++col)
30 for(i=0,mat_sq[row][col]=0;i<elements;++i)
31 mat_sq[row][col]+=matrix[row][i]*matrix[i][col];
32 for(flag=0,i=0;i<elements&&!flag;++i)for(j=0;j<elements&&!flag;++j)if(matrix[i][j]!=mat_sq[i][j])flag=1;
33 if(!flag)printf("\n\tRelation is transitive");
34 fflush(stdin);
35 getchar();
36 return 0;
37 }
1 //4. WAP to check whether the given expression is tautology, contradiction or contingency.
2
3 #include<stdio.h>
4 #include<stdlib.h.h>
5 #include<string.h>
6 #include<malloc.h>
7 #define N 100
8 struct node{
9 char info;
10 struct node*next;
11 }*top;
12 int msin(){
13 char ex[N];
14 int len;
15 printf("\n\n\tEnter the expression use only p,q,r,~,&,|,^,(,):");
16 scanf("%s",ex+1);
17 ex[0]='(';
18 len=strlen(ex);
19 ex[len]=')';
20 ex[len+1]='\0';
21 prefix(ex);
22 printf(evaluate(ex)?"\nExpression is tautology":"Expression is contradiction");
23 fflush(stdin);
24 getchar();
25 return 0;
26 }
27 void push(char c){
28 struct node*p;
29 p=(struct node*)malloc(sizeof(struct node));
30 p->info=c;
31 p->next=top;
32 top=p;
33 }
34 char pop(void){
35 struct node*p;
36 p=top;
37 if(top!=NULL){
38 top=top->next;
39 return p->info;
40 }
41 return '\0';
42 }
43 void prefix(char ex[]){
44 int i,j;
45 char temp[N];
46 for(i=0,j=0;ex[i]!='\0';++i){
47 if(ex[i]=='p'||ex[i]=='q'||ex[i]=='r')temp[j++]=ex[i];
48 else if(ex[i]=='~')
49 }}
1 //5. WAP to sort the numbers using merge sort.
2 //CODE
3 #include<iostream.h>
4 #include<conio.h>
5 void mergesort(int[],int,int);
6 void merge(int[],int,int,int);
7 void main(){
8 int a[10],p,q,r,i,n;
9 clrscr();
10 cout<<"Enter the number of elements";
11 cin>>n;
12 p=0;
13 r=n-1;
14 cout<<"Enter the array";
15 for(i=0;i<n;i++){
16 cin>>a[i];
17 }
18 mergesort(a,p,r);
19 cout<<"The sorted array is:";
20 for(i=0;i<n;i++){
21 cout<<"\n"<<a[i];
22 }
23 getch();
24 }
25
26 void mergesort(int a[],int p,int r){
27 if( p < r){
28 int q=(p+r)/2;
29 mergesort(a,p,q);
30 mergesort(a,q+1,r);
31 merge(a,p,q,r);
32 }
33 }
34 void merge(int a[],int p,int q,int r){
35 int c[10];
36 int i=p;
37 int j=q+1;
38 int k=p;
39 while((i<=q)&&(j<=r)){
40 if(a[i]<a[j]){
41 c[k]=a[i];
42 i=i+1;
43 k=k+1;
44 }
45 else{
46 c[k]=a[j];
47 j=j+1;
48 k=k+1;
49 }
50 }
51 while(i<=q){
52 c[k] =a[i];
53 i=i+1;
54 k=k+1;
55 }
56 while(j<=r){
57 c[k]=a[j];
58 j=j+1;
59 k=k+1;
60 }
61 int l=p;
62 while(l<=r){
63 a[l]=c[l];
64 l=l+1;
65 }
66 }
1 //6. WAP to find the minimum spanning tree using Kruskals Algorithm
2
3 // Kruskal's algortihm to find Minimum Spanning Tree of a given connected,
4 // undirected and weighted graph
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8
9 // a structure to represent a weighted edge in graph
10 struct Edge
11 {
12 int src, dest, weight;
13 };
14
15 // a structure to represent a connected, undirected and weighted graph
16 struct Graph
17 {
18 // V-> Number of vertices, E-> Number of edges
19 int V, E;
20
21 // graph is represented as an array of edges. Since the graph is
22 // undirected, the edge from src to dest is also edge from dest
23 // to src. Both are counted as 1 edge here.
24 struct Edge* edge;
25 };
26
27 // Creates a graph with V vertices and E edges
28 struct Graph* createGraph(int V, int E)
29 {
30 struct Graph* graph = (struct Graph*) malloc( sizeof(struct Graph) );
31 graph->V = V;
32 graph->E = E;
33
34 graph->edge = (struct Edge*) malloc( graph->E * sizeof( struct Edge ) );
35
36 return graph;
37 }
38
39 // A structure to represent a subset for union-find
40 struct subset
41 {
42 int parent;
43 int rank;
44 };
45
46 // A utility function to find set of an element i
47 // (uses path compression technique)
48 int find(struct subset subsets[], int i)
49 {
50 // find root and make root as parent of i (path compression)
51 if (subsets[i].parent != i)
52 subsets[i].parent = find(subsets, subsets[i].parent);
53
54 return subsets[i].parent;
55 }
56
57 // A function that does union of two sets of x and y
58 // (uses union by rank)
59 void Union(struct subset subsets[], int x, int y)
60 {
61 int xroot = find(subsets, x);
62 int yroot = find(subsets, y);
63
64 // Attach smaller rank tree under root of high rank tree
65 // (Union by Rank)
66 if (subsets[xroot].rank < subsets[yroot].rank)
67 subsets[xroot].parent = yroot;
68 else if (subsets[xroot].rank > subsets[yroot].rank)
69 subsets[yroot].parent = xroot;
70
71 // If ranks are same, then make one as root and increment
72 // its rank by one
73 else
74 {
75 subsets[yroot].parent = xroot;
76 subsets[xroot].rank++;
77 }
78 }
79
80 // Compare two edges according to their weights.
81 // Used in qsort() for sorting an array of edges
82 int myComp(const void* a, const void* b)
83 {
84 struct Edge* a1 = (struct Edge*)a;
85 struct Edge* b1 = (struct Edge*)b;
86 return a1->weight > b1->weight;
87 }
88
89 // The main function to construct MST using Kruskal's algorithm
90 void KruskalMST(struct Graph* graph)
91 {
92 int V = graph->V;
93 struct Edge result[V]; // Tnis will store the resultant MST
94 int e = 0; // An index variable, used for result[]
95 int i = 0; // An index variable, used for sorted edges
96
97 // Step 1: Sort all the edges in non-decreasing order of their weight
98 // If we are not allowed to change the given graph, we can create a copy of
99 // array of edges
100 qsort(graph->edge, graph->E, sizeof(graph->edge[0]), myComp);
101
102 // Allocate memory for creating V ssubsets
103 struct subset *subsets =
104 (struct subset*) malloc( V * sizeof(struct subset) );
105
106 // Create V subsets with single elements
107 for (int v = 0; v < V; ++v)
108 {
109 subsets[v].parent = v;
110 subsets[v].rank = 0;
111 }
112
113 // Number of edges to be taken is equal to V-1
114 while (e < V - 1)
115 {
116 // Step 2: Pick the smallest edge. And increment the index
117 // for next iteration
118 struct Edge next_edge = graph->edge[i++];
119
120 int x = find(subsets, next_edge.src);
121 int y = find(subsets, next_edge.dest);
122
123 // If including this edge does't cause cycle, include it
124 // in result and increment the index of result for next edge
125 if (x != y)
126 {
127 result[e++] = next_edge;
128 Union(subsets, x, y);
129 }
130 // Else discard the next_edge
131 }
132
133 // print the contents of result[] to display the built MST
134 printf("Following are the edges in the constructed MST\n");
135 for (i = 0; i < e; ++i)
136 printf("%d -- %d == %d\n", result[i].src, result[i].dest,
137 result[i].weight);
138 return;
139 }
140
141 // Driver program to test above functions
142 int main()
143 {
144 /* Let us create following weighted graph
145 10
146 0--------1
147 | \ |
148 6| 5\ |15
149 | \ |
150 2--------3
151 4 */
152 int V = 4; // Number of vertices in graph
153 int E = 5; // Number of edges in graph
154 struct Graph* graph = createGraph(V, E);
155
156
157 // add edge 0-1
158 graph->edge[0].src = 0;
159 graph->edge[0].dest = 1;
160 graph->edge[0].weight = 10;
161
162 // add edge 0-2
163 graph->edge[1].src = 0;
164 graph->edge[1].dest = 2;
165 graph->edge[1].weight = 6;
166
167 // add edge 0-3
168 graph->edge[2].src = 0;
169 graph->edge[2].dest = 3;
170 graph->edge[2].weight = 5;
171
172 // add edge 1-3
173 graph->edge[3].src = 1;
174 graph->edge[3].dest = 3;
175 graph->edge[3].weight = 15;
176
177 // add edge 2-3
178 graph->edge[4].src = 2;
179 graph->edge[4].dest = 3;
180 graph->edge[4].weight = 4;
181
182 KruskalMST(graph);
183
184 return 0;
185 }
1 //7. WAP to find the number using binary search.
2
3 #include<iostream.h>
4 #include<conio.h>
5 void main()
6 {
7 clrscr();
8 int a[100],n,i,beg,end,mid,item;
9
10 cout<<"\n------------ BINARY SEARCH ------------ \n\n";
11 cout<<"Enter No. of Elements= ";
12 cin>>n;
13
14 cout<<"\nEnter Elements in Sorted Order=\n";
15 for(i=1;i<=n;i++)
16 {
17 cin>>a[i];
18 }
19
20 cout<<"\nEnter Item you want to Search= ";
21 cin>>item;
22
23 beg=1;
24 end=n;
25
26 mid=(beg+end)/2; // Find Mid Location of Array
27
28 while(beg<=end && a[mid]!=item) // Compare Item and Value of Mid
29 {
30 if(a[mid]<item)
31 beg=mid+1;
32 else
33 end=mid-1;
34
35 mid=(beg+end)/2;
36 }
37
38 if(a[mid]==item)
39 {
40 cout<<"\nData is Found at Location : "<<mid;
41 }
42 else
43 {
44 cout<<"Data is Not Found";
45 }
46 getch();
47 }
1 //8. WAP to find maximum and minimum number. (divide & Conquer)
2 #include <iostream>
3
4 using namespace std;
5
6 void findMin(int [],int, int,int &amp;, int &amp;);
7
8 int main()
9
10 {
11
12 int n,min,max;
13
14 cout<<"Enter n:";
15
16 cin>>n;
17
18 int a[n];
19
20 for(int i=0;i<n;i++)
21
22 {
23
24 cout<<"Enter a["<<i<<"]:";
25
26 cin>>a[i];
27
28 }
29
30 findMin(a,0,n-1,min,max);
31
32 cout<<"Minimun of the given array is: "<<min<<;endl;
33
34 cout<<"Maximum of the gvien arrays is: "<<max<<endl;
35
36 return 0;
37
38 }
39
40 void findMin(int a[], int left, int right, int &amp;min, int &amp;max)
41
42 {
43
44 if(left==right)
45
46 {
47
48 min=a[left];
49
50 max=a[right];
51
52 }
53
54 else
55
56 {
57
58 int mid=(left+right)/2;
59
60 findMin(a,left,mid,min,max);
61
62 int left_min=min;
63
64 int left_max=max;
65
66 findMin(a,mid+1,right,min,max);
67
68 int right_min=min;
69
70 int right_max=max;
71
72 if(left_min&lt;right_min)
73
74 min=left_min;
75
76 else
77
78 min=right_min;
79
80 if(left_max&gt;right_max)
81
82 max=left_max;
83
84 else
85
86 max=right_max;
87
88 }
89
90 }
1 //9. WAP to implement all pairs shortest path algorithm for a given graph.
2
3 #include <stdio.h>
4 #include <limits.h>
5
6 // Number of vertices in the graph
7 #define V 9
8
9 // A utility function to find the vertex with minimum distance value, from
10 // the set of vertices not yet included in shortest path tree
11 int minDistance(int dist[], bool sptSet[])
12 {
13 // Initialize min value
14 int min = INT_MAX, min_index;
15
16 for (int v = 0; v < V; v++)
17 if (sptSet[v] == false && dist[v] <= min)
18 min = dist[v], min_index = v;
19
20 return min_index;
21 }
22
23 // A utility function to print the constructed distance array
24 int printSolution(int dist[], int n)
25 {
26 printf("Vertex Distance from Source\n");
27 for (int i = 0; i < V; i++)
28 printf("%d \t\t %d\n", i, dist[i]);
29 }
30
31 // Funtion that implements Dijkstra's single source shortest path algorithm
32 // for a graph represented using adjacency matrix representation
33 void dijkstra(int graph[V][V], int src)
34 {
35 int dist[V]; // The output array. dist[i] will hold the shortest
36 // distance from src to i
37
38 bool sptSet[V]; // sptSet[i] will true if vertex i is included in shortest
39 // path tree or shortest distance from src to i is finalized
40
41 // Initialize all distances as INFINITE and stpSet[] as false
42 for (int i = 0; i < V; i++)
43 dist[i] = INT_MAX, sptSet[i] = false;
44
45 // Distance of source vertex from itself is always 0
46 dist[src] = 0;
47
48 // Find shortest path for all vertices
49 for (int count = 0; count < V-1; count++)
50 {
51 // Pick the minimum distance vertex from the set of vertices not
52 // yet processed. u is always equal to src in first iteration.
53 int u = minDistance(dist, sptSet);
54
55 // Mark the picked vertex as processed
56 sptSet[u] = true;
57
58 // Update dist value of the adjacent vertices of the picked vertex.
59 for (int v = 0; v < V; v++)
60
61 // Update dist[v] only if is not in sptSet, there is an edge from
62 // u to v, and total weight of path from src to v through u is
63 // smaller than current value of dist[v]
64 if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX
65 && dist[u]+graph[u][v] < dist[v])
66 dist[v] = dist[u] + graph[u][v];
67 }
68
69 // print the constructed distance array
70 printSolution(dist, V);
71 }
72
73 // driver program to test above function
74 int main()
75 {
76 /* Let us create the example graph discussed above */
77 int graph[V][V] = {{0, 4, 0, 0, 0, 0, 0, 8, 0},
78 {4, 0, 8, 0, 0, 0, 0, 11, 0},
79 {0, 8, 0, 7, 0, 4, 0, 0, 2},
80 {0, 0, 7, 0, 9, 14, 0, 0, 0},
81 {0, 0, 0, 9, 0, 10, 0, 0, 0},
82 {0, 0, 4, 0, 10, 0, 2, 0, 0},
83 {0, 0, 0, 14, 0, 2, 0, 1, 6},
84 {8, 11, 0, 0, 0, 0, 1, 0, 7},
85 {0, 0, 2, 0, 0, 0, 6, 7, 0}
86 };
87
88 dijkstra(graph, 0);
89
90 return 0;
91 }
1 // 10. WAP to implement 0/1 Knapsack algorithm for the given inputs.
2 #include<stdio.h>
3
4 // A utility function that returns maximum of two integers
5 int max(int a, int b) { return (a > b)? a : b; }
6
7 // Returns the maximum value that can be put in a knapsack of capacity W
8 int knapSack(int W, int wt[], int val[], int n)
9 {
10 int i, w;
11 int K[n+1][W+1];
12
13 // Build table K[][] in bottom up manner
14 for (i = 0; i <= n; i++)
15 {
16 for (w = 0; w <= W; w++)
17 {
18 if (i==0 || w==0)
19 K[i][w] = 0;
20 else if (wt[i-1] <= w)
21 K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]);
22 else
23 K[i][w] = K[i-1][w];
24 }
25 }
26
27 return K[n][W];
28 }
29
30 int main()
31 {
32 int val[] = {60, 100, 120};
33 int wt[] = {10, 20, 30};
34 int W = 50;
35 int n = sizeof(val)/sizeof(val[0]);
36 printf("%d", knapSack(W, wt, val, n));
37 return 0;
38 }

You might also like