Skip to content

Commit 1275d51

Browse files
committed
added greedy algos
1 parent 8f0483d commit 1275d51

File tree

12 files changed

+632
-0
lines changed

12 files changed

+632
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
bool vis[100];
4+
int arr[100],size[100];
5+
#define piii pair<int,pair<int,int> >
6+
class mycmp{
7+
public:
8+
bool operator()(piii p1,piii p2)
9+
{
10+
return p1.first>p2.first;
11+
}
12+
};
13+
int root(int x)
14+
{
15+
while(arr[x]!=x)
16+
{
17+
arr[x]=arr[arr[x]];
18+
x=arr[x];
19+
}
20+
return x;
21+
}
22+
bool find(int x,int y)
23+
{
24+
int rootx=root(x),rooty=root(y);
25+
return rootx==rooty;
26+
}
27+
void union1(int x,int y)
28+
{
29+
int rootx=root(x);
30+
int rooty=root(y);
31+
if(size[rootx]<size[rooty])
32+
{
33+
arr[rootx]=rooty;
34+
size[rooty]+=size[rootx];
35+
}
36+
else
37+
{
38+
arr[rooty]=rootx;
39+
size[rootx]+=size[rooty];
40+
}
41+
}
42+
int main()
43+
{
44+
printf("Enter no of vertices and no of edges\n");
45+
int n,m,i;cin>>n>>m;
46+
for(i=1;i<=n;i++)
47+
{
48+
arr[i]=i;
49+
size[i]=1;
50+
}
51+
printf("Enter\nsrc dest weight\n");
52+
priority_queue<piii,vector<piii>,mycmp>pq;
53+
for(i=1;i<=m;i++)
54+
{
55+
int u,v,w;cin>>u>>v>>w;
56+
pq.push({w,{u,v}});
57+
}
58+
int sum=0;
59+
while(!pq.empty())
60+
{
61+
piii p=pq.top();
62+
pq.pop();
63+
int w=p.first,fir=p.second.first,sec=p.second.second;
64+
if(find(fir,sec)==false)
65+
{
66+
sum+=w;
67+
union1(fir,sec);
68+
}
69+
}
70+
printf("weight of MST\n");
71+
cout<<sum<<endl;
72+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
Given a connected and undirected graph, a spanning tree of that graph is a subgraph that is a tree and connects all the vertices together. A single graph can have many different spanning trees. A minimum spanning tree (MST) or minimum weight spanning tree for a weighted, connected and undirected graph is a spanning tree with weight less than or equal to the weight of every other spanning tree. The weight of a spanning tree is the sum of weights given to each edge of the spanning tree.
2+
3+
4+
Below are the steps for finding MST using Kruskal’s algorithm
5+
6+
1. Sort all the edges in non-decreasing order of their weight.
7+
2. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If cycle is not formed, include this edge. Else, discard it.
8+
3. Repeat step#2 until there are (V-1) edges in the spanning tree.
9+
10+
The step#2 uses Union-Find algorithm to detect cycle.
11+
12+
The algorithm is a Greedy Algorithm. The Greedy Choice is to pick the smallest weight edge that does not cause a cycle in the MST constructed so far.
13+
14+
15+
Example:
16+
4 5
17+
0 1 10
18+
0 2 6
19+
0 3 5
20+
1 3 15
21+
2 3 4
22+
23+
Output: 19
+121
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
#include<iostream>
2+
#include <vector>
3+
#include <algorithm>
4+
using namespace std;
5+
// declare a class for graph
6+
7+
struct Edge{
8+
int src,dest,weight;
9+
};
10+
11+
class Graph{
12+
int V,E;
13+
vector<Edge> edge; // an array of all the edges
14+
public:
15+
Graph(int v, int e);
16+
void addEdge(int src, int dest, int weight);
17+
void mst();
18+
};
19+
20+
Graph::Graph(int v, int e){
21+
V=v;
22+
E=e;
23+
}
24+
25+
void Graph::addEdge(int src, int dest, int weight){
26+
Edge *e= new Edge;
27+
e->src= src;
28+
e->dest= dest;
29+
e->weight= weight;
30+
edge.push_back(*e);
31+
}
32+
bool comp(Edge e1, Edge e2){
33+
return e1.weight<e2.weight ;
34+
}
35+
36+
struct subset{
37+
int parent;
38+
int rank;
39+
};
40+
// A utility function to find set of an element i
41+
// (uses path compression technique)
42+
int find(struct subset subsets[], int i){
43+
// find root and make root as parent of i (path compression)
44+
if (subsets[i].parent != i)
45+
subsets[i].parent = find(subsets, subsets[i].parent);
46+
return subsets[i].parent;
47+
}
48+
49+
// A function that does union of two sets of x and y
50+
// (uses union by rank)
51+
void Union(struct subset subsets[], int x, int y)
52+
{
53+
int xroot = find(subsets, x);
54+
int yroot = find(subsets, y);
55+
56+
// Attach smaller rank tree under root of high rank tree
57+
// (Union by Rank)
58+
if (subsets[xroot].rank < subsets[yroot].rank)
59+
subsets[xroot].parent = yroot;
60+
else if (subsets[xroot].rank > subsets[yroot].rank)
61+
subsets[yroot].parent = xroot;
62+
else
63+
{
64+
subsets[yroot].parent = xroot;
65+
subsets[xroot].rank++;
66+
}
67+
}
68+
69+
void Graph::mst(){
70+
sort(edge.begin(), edge.end(), comp);
71+
//create disjoint set for all vertices
72+
struct subset *subsets = new subset[V];
73+
74+
// Create V subsets with single elements
75+
for(int i=0;i<V;i++){
76+
subsets[i].parent = i;
77+
subsets[i].rank = 0;
78+
}
79+
vector<Edge> result;
80+
81+
// Number of edges to be taken is equal to V-1
82+
for(auto i=edge.begin(); i!=edge.end();i++){
83+
int src= i->src;
84+
int dest=i->dest;
85+
//if not same root
86+
if(find(subsets, src)!= find(subsets, dest)){
87+
result.push_back(*i);
88+
Union(subsets, src, dest);
89+
}
90+
}
91+
printf("The edges of the MST are\n");
92+
for(auto i=result.begin(); i!=result.end(); i++)
93+
cout<<i->src<<"--"<<i->dest<<"="<<i->weight<<endl;
94+
return;
95+
}
96+
97+
int main(){
98+
int V; // Number of vertices in graph
99+
int E;
100+
printf("Enter no of vertices and edges\n");
101+
scanf("%d%d",&V,&E); // Number of edges in graph
102+
Graph g(V,E);
103+
int i,u,v,x;
104+
printf("Enter\nsrc dest weight\n");
105+
for(i=0;i<E;i++)
106+
{
107+
scanf("%d%d%d",&u,&v,&x);
108+
g.addEdge(u,v,x);
109+
}
110+
// add edge 0-1
111+
/*g.addEdge(0,3,1);
112+
g.addEdge(4,5,2);
113+
g.addEdge(2,4,5);
114+
g.addEdge(3,4,6);
115+
g.addEdge(0,1,3);
116+
g.addEdge(1,2,1);
117+
g.addEdge(2,3,1);
118+
g.addEdge(1,3,3);
119+
g.addEdge(2,5,4);*/
120+
g.mst();
121+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
The idea behind Prim’s algorithm is simple, a spanning tree means all vertices must be connected. So the two disjoint subsets (discussed above) of vertices must be connected to make a Spanning Tree. And they must be connected with the minimum weight edge to make it a Minimum Spanning Tree.
2+
3+
4+
Algorithm
5+
6+
1) Create a set mstSet that keeps track of vertices already included in MST.
7+
2) Assign a key value to all vertices in the input graph. Initialize all key values as INFINITE. Assign key value as 0 for the first vertex so that it is picked first.
8+
3) While mstSet doesn’t include all vertices
9+
….a) Pick a vertex u which is not there in mstSet and has minimum key value.
10+
….b) Include u to mstSet.
11+
….c) Update key value of all adjacent vertices of u. To update the key values, iterate through all adjacent vertices. For every adjacent vertex v, if weight of edge u-v is less than the previous key value of v, update the key value as weight of u-v.
12+
13+
14+
The idea of using key values is to pick the minimum weight edge from cut. The key values are used only for vertices which are not yet included in MST, the key value for these vertices indicate the minimum weight edges connecting them to the set of vertices included in MST.
15+
16+
Example:
17+
6 9
18+
0 3 1
19+
4 5 2
20+
2 4 5
21+
3 4 6
22+
0 1 3
23+
1 2 1
24+
2 3 1
25+
1 3 3
26+
2 5 4
27+
28+
29+
Output :
30+
0--3=1
31+
1--2=1
32+
2--3=1
33+
4--5=2
34+
2--5=4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
You are given n activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time.
2+
3+
The greedy choice is to always pick the next activity whose finish time is least among the remaining activities and the start time is more than or equal to the finish time of previously selected activity. We can sort the activities according to their finishing time so that we always consider the next activity as minimum finishing time activity.
4+
5+
1) Sort the activities according to their finishing time
6+
2) Select the first activity from the sorted array and print it.
7+
3) Do following for remaining activities in the sorted array.
8+
…….a) If the start time of this activity is greater than or equal to the finish time of previously selected activity then select this activity and print it.
9+
10+
Example:
11+
6
12+
1 3 0 5 8 5
13+
2 4 6 7 9 9
14+
15+
Output:
16+
selected activities are 0 1 3 4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#include<stdio.h>
2+
3+
void selection(int s[], int f[], int n)
4+
{
5+
int i, j;
6+
i = 0;
7+
printf("%d ", i);
8+
9+
for (j = 1; j < n; j++)
10+
{
11+
if (s[j] >= f[i])
12+
{
13+
printf ("%d ", j);
14+
i = j;
15+
}
16+
}
17+
}
18+
19+
int main()
20+
{
21+
int n;
22+
printf("Enter no of activities\n");
23+
scanf("%d",&n);
24+
int s[n],f[n],i;
25+
printf("Enter the start times of the activities\n");
26+
for(i=0;i<n;i++)
27+
{
28+
scanf("%d",&s[i]);
29+
}
30+
printf("Enter the finish times of the actvities\n");
31+
for(i=0;i<n;i++)
32+
{
33+
scanf("%d",&f[i]);
34+
}
35+
printf("Following activities are selected\n");
36+
selection(s, f, n);
37+
return 0;
38+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
Huffman coding is a lossless data compression algorithm. The idea is to assign variable-length codes to input characters, lengths of the assigned codes are based on the frequencies of corresponding characters. The most frequent character gets the smallest code and the least frequent character gets the largest code.
2+
The variable-length codes assigned to input characters are Prefix Codes, means the codes (bit sequences) are assigned in such a way that the code assigned to one character is not prefix of code assigned to any other character. This is how Huffman Coding makes sure that there is no ambiguity when decoding the generated bit stream.
3+
4+
There are mainly two major parts in Huffman Coding
5+
1) Build a Huffman Tree from input characters.
6+
2) Traverse the Huffman Tree and assign codes to characters.
7+
8+
9+
Steps to build Huffman Tree:
10+
11+
a) Input is array of unique characters along with their frequency of occurrences and output is Huffman Tree.
12+
13+
1. Create a leaf node for each unique character and build a min heap of all leaf nodes (Min Heap is used as a priority queue. The value of frequency field is used to compare two nodes in min heap. Initially, the least frequent character is at root)
14+
15+
2. Extract two nodes with the minimum frequency from the min heap.
16+
17+
3. Create a new internal node with frequency equal to the sum of the two nodes frequencies. Make the first extracted node as its left child and the other extracted node as its right child. Add this node to the min heap.
18+
19+
4. Repeat steps #2 and #3 until the heap contains only one node. The remaining node is the root node and the tree is complete.
20+
21+
b) Steps to print codes from Huffman Tree:
22+
23+
Traverse the tree formed starting from the root. Maintain an auxiliary array. While moving to the left child, write 0 to the array. While moving to the right child, write 1 to the array. Print the array when a leaf node is encountered.
24+
25+
26+
27+
Example:
28+
6
29+
a 5
30+
b 9
31+
c 12
32+
d 13
33+
e 16
34+
f 45
35+
36+
Output:
37+
character code-word
38+
f 0
39+
c 100
40+
d 101
41+
a 1100
42+
b 1101
43+
e 111

0 commit comments

Comments
 (0)