From 1275d5150f3c637d6a1ce20e865a6fade8c8cbfa Mon Sep 17 00:00:00 2001 From: Abhishek Nalla Date: Sat, 16 Dec 2017 21:47:47 +0530 Subject: [PATCH] added greedy algos --- .../Greedy/KruskalMst/Kruskal.cpp | 72 +++++++++++ .../Greedy/KruskalMst/Readme.md | 23 ++++ Competitive Coding/Greedy/PrimMst/Prim.cpp | 121 ++++++++++++++++++ Competitive Coding/Greedy/PrimMst/Readme.md | 34 +++++ .../Greedy/activitySelection/Readme.md | 16 +++ .../activitySelection/activitySelection.cpp | 38 ++++++ .../Greedy/huffmanCoding/Readme.md | 43 +++++++ .../Greedy/huffmanCoding/huffmanCoding.py | 118 +++++++++++++++++ .../Greedy/jobSequencing/Readme.md | 23 ++++ .../Greedy/jobSequencing/jobSequencing.cpp | 51 ++++++++ .../Greedy/travellingSalesman/Readme.md | 38 ++++++ .../travellingSalesman/travellingSalesman.c | 55 ++++++++ 12 files changed, 632 insertions(+) create mode 100644 Competitive Coding/Greedy/KruskalMst/Kruskal.cpp create mode 100644 Competitive Coding/Greedy/KruskalMst/Readme.md create mode 100644 Competitive Coding/Greedy/PrimMst/Prim.cpp create mode 100644 Competitive Coding/Greedy/PrimMst/Readme.md create mode 100644 Competitive Coding/Greedy/activitySelection/Readme.md create mode 100644 Competitive Coding/Greedy/activitySelection/activitySelection.cpp create mode 100644 Competitive Coding/Greedy/huffmanCoding/Readme.md create mode 100644 Competitive Coding/Greedy/huffmanCoding/huffmanCoding.py create mode 100644 Competitive Coding/Greedy/jobSequencing/Readme.md create mode 100644 Competitive Coding/Greedy/jobSequencing/jobSequencing.cpp create mode 100644 Competitive Coding/Greedy/travellingSalesman/Readme.md create mode 100644 Competitive Coding/Greedy/travellingSalesman/travellingSalesman.c diff --git a/Competitive Coding/Greedy/KruskalMst/Kruskal.cpp b/Competitive Coding/Greedy/KruskalMst/Kruskal.cpp new file mode 100644 index 000000000..cacd8de00 --- /dev/null +++ b/Competitive Coding/Greedy/KruskalMst/Kruskal.cpp @@ -0,0 +1,72 @@ +#include +using namespace std; +bool vis[100]; +int arr[100],size[100]; +#define piii pair > +class mycmp{ + public: + bool operator()(piii p1,piii p2) + { + return p1.first>p2.first; + } +}; +int root(int x) +{ + while(arr[x]!=x) + { + arr[x]=arr[arr[x]]; + x=arr[x]; + } + return x; +} +bool find(int x,int y) +{ + int rootx=root(x),rooty=root(y); + return rootx==rooty; +} +void union1(int x,int y) +{ + int rootx=root(x); + int rooty=root(y); + if(size[rootx]>n>>m; + for(i=1;i<=n;i++) + { + arr[i]=i; + size[i]=1; + } + printf("Enter\nsrc dest weight\n"); + priority_queue,mycmp>pq; + for(i=1;i<=m;i++) + { + int u,v,w;cin>>u>>v>>w; + pq.push({w,{u,v}}); + } + int sum=0; + while(!pq.empty()) + { + piii p=pq.top(); + pq.pop(); + int w=p.first,fir=p.second.first,sec=p.second.second; + if(find(fir,sec)==false) + { + sum+=w; + union1(fir,sec); + } + } + printf("weight of MST\n"); + cout< +#include +#include +using namespace std; +// declare a class for graph + +struct Edge{ + int src,dest,weight; +}; + +class Graph{ + int V,E; + vector edge; // an array of all the edges + public: + Graph(int v, int e); + void addEdge(int src, int dest, int weight); + void mst(); +}; + +Graph::Graph(int v, int e){ + V=v; + E=e; +} + +void Graph::addEdge(int src, int dest, int weight){ + Edge *e= new Edge; + e->src= src; + e->dest= dest; + e->weight= weight; + edge.push_back(*e); +} +bool comp(Edge e1, Edge e2){ + return e1.weight subsets[yroot].rank) + subsets[yroot].parent = xroot; + else + { + subsets[yroot].parent = xroot; + subsets[xroot].rank++; + } +} + +void Graph::mst(){ + sort(edge.begin(), edge.end(), comp); + //create disjoint set for all vertices + struct subset *subsets = new subset[V]; + + // Create V subsets with single elements + for(int i=0;i result; + + // Number of edges to be taken is equal to V-1 + for(auto i=edge.begin(); i!=edge.end();i++){ + int src= i->src; + int dest=i->dest; + //if not same root + if(find(subsets, src)!= find(subsets, dest)){ + result.push_back(*i); + Union(subsets, src, dest); + } + } + printf("The edges of the MST are\n"); + for(auto i=result.begin(); i!=result.end(); i++) + cout<src<<"--"<dest<<"="<weight< + +void selection(int s[], int f[], int n) +{ + int i, j; + i = 0; + printf("%d ", i); + + for (j = 1; j < n; j++) + { + if (s[j] >= f[i]) + { + printf ("%d ", j); + i = j; + } + } +} + +int main() +{ + int n; + printf("Enter no of activities\n"); + scanf("%d",&n); + int s[n],f[n],i; + printf("Enter the start times of the activities\n"); + for(i=0;i1): + left = heapArr.pop(0) + right = heapArr.pop(0) + insertionSort(heapArr, MinHeapNode().setNode(left, right, left.freq+right.freq, left.char + right.char)) + + rootheap= heapArr.pop() + + return rootheap + +def printHeap(heap, str): + if heap.left != None: + printHeap(heap.left, str + '0') + + if heap.right !=None: + printHeap(heap.right, str + '1' ) + + if heap.left == None: + print("character code-word") + print(heap.char, str) + dic[heap.char] = str + +def insertionSort(heapArr, heap): + index = len(heapArr) + for i in range(len(heapArr)): + if heap.freq < heapArr[i].freq: + index = i + break + heapArr.insert(index, heap) + +def makeNewString(arr, freq): + + freqcopy = freq[:] + arrcopy = arr[:] + strval = '' + while len(freqcopy) >0: + number = random.randrange(0,len(freqcopy)) + freqcopy[number] = freqcopy[number]-1 + strval = strval + arrcopy[number] + if freqcopy[number] == 0: + freqcopy.pop(number) + arrcopy.pop(number) + + return strval + +def endcoding(str): + strval = '' + for i in range(len(str)): + strval = strval + dic[str[i]] + + return strval + +def huffmandecode(rootheap, strvalencoded): + + index = 0; + orgstr = ''; + + while index < len(strvalencoded): + str = getchar(rootheap, index, strvalencoded) + index = index + len(dic[str]) + orgstr = orgstr + str + return orgstr + +def getchar(rootheap, index, strvalencoded): + if rootheap.left == None: + return rootheap.char + + number = int(strvalencoded[index]) + if number ==0: + return getchar(rootheap.left, index+1, strvalencoded) + + if number ==1: + return getchar(rootheap.right, index+1, strvalencoded) + + +print("Example input:") +print("6\na\n5\nb\n9\nc\n12\nd\n13\ne\n16\nf\n45\n") +text = raw_input("Enter no of characters ") +text = int(text) +arr = [] +freq = [] +for i in range(text): + arr.append((raw_input("Character "))) + freq.append(int(raw_input("Frequency "))) + +# arr[i] = raw_input("character") +# freq[i] = raw_input("frequency") + +#arr = ['a', 'b', 'c', 'd', 'e', 'f'] +#freq = [5, 9, 12, 13, 16, 45] +rootheap = huffmanCoding(arr, freq) + +printHeap(rootheap, '') + +strval = makeNewString(arr, freq) +print("org ", strval) + +strvalencoded = endcoding(strval) +print("encoded ",strvalencoded) + +orgencoded = huffmandecode(rootheap, strvalencoded) +print("decoded ", orgencoded) diff --git a/Competitive Coding/Greedy/jobSequencing/Readme.md b/Competitive Coding/Greedy/jobSequencing/Readme.md new file mode 100644 index 000000000..3ba51bc5b --- /dev/null +++ b/Competitive Coding/Greedy/jobSequencing/Readme.md @@ -0,0 +1,23 @@ +Given an array of jobs where every job has a deadline and associated profit if the job is finished before the deadline. It is also given that every job takes single unit of time, so the minimum possible deadline for any job is 1. How to maximize total profit if only one job can be scheduled at a time. + + +A Simple Solution is to generate all subsets of given set of jobs and check individual subset for feasibility of jobs in that subset. Keep track of maximum profit among all feasible subsets. The time complexity of this solution is exponential. + +This is a standard Greedy Algorithm problem. Following is algorithm. + +1) Sort all jobs in decreasing order of profit. +2) Initialize the result sequence as first job in sorted jobs. +3) Do following for remaining n-1 jobs +.......a) If the current job can fit in the current result sequence + without missing the deadline, add current job to the result. + Else ignore the current job. + +Example: +4 +a 4 20 +b 1 10 +c 1 40 +d 1 30 + +Output: +c a diff --git a/Competitive Coding/Greedy/jobSequencing/jobSequencing.cpp b/Competitive Coding/Greedy/jobSequencing/jobSequencing.cpp new file mode 100644 index 000000000..a12760ba9 --- /dev/null +++ b/Competitive Coding/Greedy/jobSequencing/jobSequencing.cpp @@ -0,0 +1,51 @@ +#include +#include +using namespace std; + +struct job +{ + char title; + int dead; + int profit; +}; + +bool compare(job a,job b) +{ + return (a.profit > b.profit); +} + +int main() +{ + int n; + printf("Example Input:\n"); + printf("4\n"); + printf("a 4 20\n"); + printf("b 1 10\n"); + printf("c 1 40\n"); + printf("d 1 30\n"); + printf("Enter no of activities\n"); + cin>>n; + job j[n]; + printf("Enter\n"); + printf("JobID Deadline Profit\n"); + for(int i=0;i>j[i].title; + cin>>j[i].dead; + cin>>j[i].profit; + } + sort(j,j+n,compare); + printf("Max sequence of jobs is\n"); + + cout< count) //If current job can be accocmodated take it + { + cout< +#include +#include +#define size 10 //maximum 10 cities +#define min(a,b) a>b?b:a +#define sizePOW 1024 // 2^10 +int n,npow,g[size][sizePOW],p[size][sizePOW],adj[size][size]; +int compute(int start,int set) +{ int masked,mask,result=INT_MAX,temp,i; + if(g[start][set]!=-1) + return g[start][set]; + for(i=0;i