Skip to content

Commit 459a669

Browse files
authored
Add Job Sequencing in C++ (#5199)
1 parent 314473d commit 459a669

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <string>
4+
#include <sstream>
5+
#include <algorithm>
6+
7+
using namespace std;
8+
9+
const string usage_msg = "Usage: please provide a list of profits and a list of deadlines\n";
10+
const int MAX_JOBS = 100;
11+
12+
struct Job {
13+
int profit;
14+
int deadline;
15+
};
16+
17+
bool compare(const Job &a, const Job &b) {
18+
return a.profit > b.profit;
19+
}
20+
21+
int jobSequencing(vector<Job> &jobs) {
22+
sort(jobs.begin(), jobs.end(), compare);
23+
24+
int maxDeadline = 0;
25+
for (auto &job : jobs) {
26+
maxDeadline = max(maxDeadline, job.deadline);
27+
}
28+
29+
vector<int> slot(MAX_JOBS, 0);
30+
int totalProfit = 0;
31+
32+
for (auto &job : jobs) {
33+
for (int j = min((int)jobs.size(), job.deadline) - 1; j >= 0; --j) {
34+
if (slot[j] == 0) {
35+
slot[j] = 1;
36+
totalProfit += job.profit;
37+
break;
38+
}
39+
}
40+
}
41+
42+
return totalProfit;
43+
}
44+
45+
vector<int> parseInput(const string &input) {
46+
vector<int> arr;
47+
stringstream ss(input);
48+
string token;
49+
while (getline(ss, token, ',')) {
50+
token.erase(0, token.find_first_not_of(" \t"));
51+
token.erase(token.find_last_not_of(" \t") + 1);
52+
if (!token.empty()) {
53+
try {
54+
arr.push_back(stoi(token));
55+
} catch (...) {
56+
throw invalid_argument("Invalid input");
57+
}
58+
}
59+
}
60+
return arr;
61+
}
62+
63+
int main(int argc, char* argv[]) {
64+
if (argc != 3) {
65+
cout << usage_msg;
66+
return 1;
67+
}
68+
69+
vector<int> profits, deadlines;
70+
try {
71+
profits = parseInput(argv[1]);
72+
deadlines = parseInput(argv[2]);
73+
} catch (...) {
74+
cout << usage_msg;
75+
return 1;
76+
}
77+
78+
if (profits.size() != deadlines.size() || profits.empty()) {
79+
cout << usage_msg;
80+
return 1;
81+
}
82+
83+
vector<Job> jobs;
84+
for (size_t i = 0; i < profits.size(); ++i) {
85+
jobs.push_back({profits[i], deadlines[i]});
86+
}
87+
88+
int result = jobSequencing(jobs);
89+
cout << result << endl;
90+
91+
return 0;
92+
}

0 commit comments

Comments
 (0)