forked from thekeymonache/hacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathActivitySelectionProblem.cpp
More file actions
59 lines (49 loc) · 1.43 KB
/
ActivitySelectionProblem.cpp
File metadata and controls
59 lines (49 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// C++ program for activity selection problem
// when input activities may not be sorted.
#include <bits/stdc++.h>
using namespace std;
void SelectActivities(vector<int> s, vector<int> f)
{
// Vector to store results.
vector<pair<int, int> > ans;
// Minimum Priority Queue to sort activities in
// ascending order of finishing time (f[i]).
priority_queue<pair<int, int>, vector<pair<int, int> >,
greater<pair<int, int> > >
p;
for (int i = 0; i < s.size(); i++) {
// Pushing elements in priority queue where the key
// is f[i]
p.push(make_pair(f[i], s[i]));
}
auto it = p.top();
int start = it.second;
int end = it.first;
p.pop();
ans.push_back(make_pair(start, end));
while (!p.empty()) {
auto itr = p.top();
p.pop();
if (itr.second >= end) {
start = itr.second;
end = itr.first;
ans.push_back(make_pair(start, end));
}
}
cout << "Following Activities should be selected. "
<< endl
<< endl;
for (auto itr = ans.begin(); itr != ans.end(); itr++) {
cout << "Activity started at " << (*itr).first
<< " and ends at " << (*itr).second << endl;
}
}
// Driver code
int main()
{
vector<int> s = { 1, 3, 0, 5, 8, 5 };
vector<int> f = { 2, 4, 6, 7, 9, 9 };
// Function call
SelectActivities(s, f);
return 0;
}