0% found this document useful (0 votes)
2 views9 pages

Greedy

The document contains multiple C++ code snippets demonstrating various algorithms and data structures, including sorting, job scheduling, knapsack problem, interval scheduling, and minimum spanning tree algorithms like Prim's and Kruskal's. Each section includes a main function that tests the respective algorithm with sample data. The code is structured with clear comments explaining the functionality of different parts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views9 pages

Greedy

The document contains multiple C++ code snippets demonstrating various algorithms and data structures, including sorting, job scheduling, knapsack problem, interval scheduling, and minimum spanning tree algorithms like Prim's and Kruskal's. Each section includes a main function that tests the respective algorithm with sample data. The code is structured with clear comments explaining the functionality of different parts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 9

//2nd

#include<iostream>
#include<bits/stdc++.h>
using namespace std;

int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
sort(arr,arr+n);
cout<<endl;
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
int ans=1;
for(int i=0;i<n;i++)
{
if(arr[i]>arr[0] && arr[i]<=arr[0]+4)
{
ans=ans+1;
}
}
cout<<"\nANS : "<<ans;
}

//-----------------

//jobb

#include <bits/stdc++.h>
using namespace std;
struct Job{
int id;
int dead;
int profit;
};

class Solution{
public:
bool static comparison(Job a,Job b){
return a.profit>b.profit;
}
pair <int,int> JobScheduling(Job arr[], int n){
sort(arr,arr+n,comparison);

int maxi=arr[0].dead;
for(int i=1;i<n;i++){
maxi = max(maxi,arr[i].dead);
}
int slot[maxi+1];
for(int i=0;i<=maxi;i++){
slot[i]=-1;
}
int countJobs=0,profitJobs=0;
for(int i=0;i<n;i++){
for(int j=arr[i].dead;j>0;j--){
if(slot[j]==-1){
slot[j]=i;
countJobs++;
profitJobs+=arr[i].profit;
break;
}
}
}
return make_pair(countJobs,profitJobs);
}
};
int main(){
int n=4;
Job arr[n] = {{1,4,20},{2,1,10},{3,2,40},{4,2,30}};
Solution ob;
pair <int, int> ans = ob.JobScheduling(arr,n);
cout<<ans.first<<" "<<ans.second;

}
//---------------------------------------------

//penalty

#include <bits/stdc++.h>
using namespace std;
struct Job{
int id;
int dead;
int penalty;
};

class Solution{
public:
bool static comparison(Job a,Job b){
return a.penalty >b.penalty ;
}
pair <int,int> JobScheduling(Job arr[], int n){
sort(arr,arr+n,comparison);

int maxi=arr[0].dead;
for(int i=1;i<n;i++){
maxi = max(maxi,arr[i].dead);
}
int slot[maxi+1];
for(int i=0;i<=maxi;i++){
slot[i]=-1;
}
int penaltySum=0;
for(int i=0;i<n;i++){
penaltySum+=arr[i].penalty;
}
int countJobs=0,profitJobs=0;
for(int i=0;i<n;i++){
for(int j=arr[i].dead;j>0;j--){
if(slot[j]==-1){
slot[j]=i;
countJobs++;
penaltySum-=arr[i].penalty;
break;
}
}
}
return make_pair(countJobs,penaltySum);
}
};
int main(){
int n=7;
Job arr[n] = {{1,14,80},{2,12,70},{3,14,60},{4,13,50},{5,11,40},{6,14,30},
{7,16,20}};
Solution ob;
pair <int, int> ans = ob.JobScheduling(arr,n);
cout<<ans.first<<" "<<ans.second;

//--------------------------

//knapscak

#include <iostream>
#include <algorithm>

using namespace std;

int main() {
int m;
cin >> m;

int values[m];
int weights[m];

cout << "Enter value and weight of each item:" << endl;
for (int i = 0; i < m; i++) {
cin >> values[i];
cin >> weights[i];
}

double valueWeightRatio[m];

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


valueWeightRatio[i] = double(values[i]) / weights[i];
}s

// Sort the items by their value-to-weight ratio in descending order


sort(valueWeightRatio, valueWeightRatio + m, greater<double>());

int capacity = 50; // Change this to your knapsack capacity


int totalValue = 0;

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


int itemIndex = -1;
// Find the item with the highest value-to-weight ratio
for (int j = 0; j < m; j++) {
if (valueWeightRatio[i] == double(values[j]) / weights[j]) {
itemIndex = j;
break;
}
}

if (itemIndex == -1) {
cerr << "Error: Item not found." << endl;
return 1;
}

if (capacity >= weights[itemIndex]) {


totalValue += values[itemIndex];
capacity -= weights[itemIndex];
} else {
totalValue += (double(capacity) / weights[itemIndex]) *
values[itemIndex];
break;
}
}

cout << "Maximum value in the knapsack: " << totalValue << endl;

return 0;
}

//-------------------------------

//entertainment

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int minKiosksToCoverEntertainmentZones(vector<int>& entertainmentZones, int radius)


{
sort(entertainmentZones.begin(), entertainmentZones.end());

int kiosks = 0;
int i = 0;

while (i < entertainmentZones.size()) {


kiosks++;
int location = entertainmentZones[i];

while (i < entertainmentZones.size() && entertainmentZones[i] <= location +


radius) {
i++;
}

// Move i to the first location that needs a new kiosk


while (i < entertainmentZones.size() && entertainmentZones[i] <= location +
radius) {
i++;
}
}

return kiosks;
}

int main() {
vector<int> entertainmentZones = {30, 50, 35, 26, 72, 65, 54, 90, 50, 60, 120,
100, 80};
int radius = 30;

int kiosks = minKiosksToCoverEntertainmentZones(entertainmentZones, radius);

cout << "Minimum number of kiosks required: " << kiosks << endl;

return 0;
}

//-------------------------------------------

//interval

#include <bits/stdc++.h>
using namespace std;

bool comparison(const pair<int,int>&a, const pair<int,int>&b){


return a.second<b.second;
}
vector <pair<int, int>> intervalScheduling(vector<pair<int, int>>& intervals){
sort(intervals.begin(),intervals.end(),comparison);
vector<pair<int, int>> selectedInt;
selectedInt.push_back(intervals[0]);
for(int i=1;i<intervals.size();i++){
if(intervals[i].first >=selectedInt.back().second){
selectedInt.push_back(intervals[i]);
}
}
return selectedInt;

}
int main(){
vector<pair<int ,int>> intervals={ {1,3},{2,4},{3,5},{4,6},{5,7}};
vector <pair<int,int>> selectedIntervals = intervalScheduling(intervals);
for (const pair<int, int>& interval : selectedIntervals) {
cout << "[" << interval.first << ", " << interval.second << "] ";
}
cout << endl;
int m=intervals.size();
int n=selectedIntervals.size();
cout<<m-n;
return 0;

}
//-----------------------------

//prims

#include <bits/stdc++.h>
using namespace std;

// Number of vertices in the graph


#define V 5

// A utility function to find the vertex with


// minimum key value, from the set of vertices
// not yet included in MST
int minKey(int key[], bool mstSet[])
{
// Initialize min value
int min = INT_MAX, min_index;

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


if (mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;

return min_index;
}

// A utility function to print the


// constructed MST stored in parent[]
void printMST(int parent[], int graph[V][V])
{
cout << "Edge \tWeight\n";
for (int i = 1; i < V; i++)
cout << parent[i] << " - " << i << " \t"
<< graph[i][parent[i]] << " \n";
}

// Function to construct and print MST for


// a graph represented using adjacency
// matrix representation
void primMST(int graph[V][V])
{
// Array to store constructed MST
int parent[V];

// Key values used to pick minimum weight edge in cut


int key[V];

// To represent set of vertices included in MST


bool mstSet[V];

// Initialize all keys as INFINITE


for (int i = 0; i < V; i++)
key[i] = INT_MAX, mstSet[i] = false;

// Always include first 1st vertex in MST.


// Make key 0 so that this vertex is picked as first
// vertex.
key[0] = 0;

// First node is always root of MST


parent[0] = -1;

// The MST will have V vertices


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

// Pick the minimum key vertex from the


// set of vertices not yet included in MST
int u = minKey(key, mstSet);

// Add the picked vertex to the MST Set


mstSet[u] = true;

// Update key value and parent index of


// the adjacent vertices of the picked vertex.
// Consider only those vertices which are not
// yet included in MST
for (int v = 0; v < V; v++)

// graph[u][v] is non zero only for adjacent


// vertices of m mstSet[v] is false for vertices
// not yet included in MST Update the key only
// if graph[u][v] is smaller than key[v]
if (graph[u][v] && mstSet[v] == false
&& graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}

// Print the constructed MST


printMST(parent, graph);
}

// Driver's code
int main()
{
int graph[V][V] = { { 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
{ 6, 8, 0, 0, 9 },
{ 0, 5, 7, 9, 0 } };

// Print the solution


primMST(graph);

return 0;
}

// ----------------------------

//kruskal

#include <bits/stdc++.h>
using namespace std;

// DSU data structure


// path compression + rank by union
class DSU {
int* parent;
int* rank;
public:
DSU(int n)
{
parent = new int[n];
rank = new int[n];

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


parent[i] = -1;
rank[i] = 1;
}
}

// Find function
int find(int i)
{
if (parent[i] == -1)
return i;

return parent[i] = find(parent[i]);


}

// Union function
void unite(int x, int y)
{
int s1 = find(x);
int s2 = find(y);

if (s1 != s2) {
if (rank[s1] < rank[s2]) {
parent[s1] = s2;
}
else if (rank[s1] > rank[s2]) {
parent[s2] = s1;
}
else {
parent[s2] = s1;
rank[s1] += 1;
}
}
}
};

class Graph {
vector<vector<int> > edgelist;
int V;

public:
Graph(int V) { this->V = V; }

// Function to add edge in a graph


void addEdge(int x, int y, int w)
{
edgelist.push_back({ w, x, y });
}

void kruskals_mst()
{
// Sort all edges
sort(edgelist.begin(), edgelist.end());
// Initialize the DSU
DSU s(V);
int ans = 0;
cout << "Following are the edges in the "
"constructed MST"
<< endl;
for (auto edge : edgelist) {
int w = edge[0];
int x = edge[1];
int y = edge[2];

// Take this edge in MST if it does


// not forms a cycle
if (s.find(x) != s.find(y)) {
s.unite(x, y);
ans += w;
cout << x << " -- " << y << " == " << w
<< endl;
}
}
cout << "Minimum Cost Spanning Tree: " << ans;
}
};

// Driver code
int main()
{
Graph g(4);
g.addEdge(0, 1, 10);
g.addEdge(1, 3, 15);
g.addEdge(2, 3, 4);
g.addEdge(2, 0, 6);
g.addEdge(0, 3, 5);

// Function call
g.kruskals_mst();

return 0;
}

//

You might also like