Header Ads Widget

Road Repair | hackerrank certification solution

 Problem:-

A number of points along the highway are in need of repair. An equal number of crews are available, stationed at various points along the highway. They must move along the highway to reach an assigned point. Given that one crew must be assigned to each job, what is the minimum total amount of distance traveled by all crews before they can begin work?

For example, given crews at points {1, 3, 5} and required repairs at {3, 5, 7} one possible minimum assignment would be {1-3,3-5,5-7} for a total of 6 units traveled.

Function Description

Complete the function getMinCost in the editor below. The function should return the minimum possible total distance traveled as an integer.

Code:-

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

string ltrim(const string &);
string rtrim(const string &);

// function for finding the minimum cost
long getMinCost(vector<int> crew_id, vector<int> job_id) {

sort(crew_id.begin(),crew_id.end());
sort(job_id.begin(),job_id.end());
long count=0;
int n=crew_id.size();
for(int i=0;i<n;i++)
{
count+=abs(crew_id[i]-job_id[i]);
}
return count;
}

// driver function
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string crew_id_count_temp;
getline(cin, crew_id_count_temp);
int crew_id_count = stoi(ltrim(rtrim(crew_id_count_temp)));
vector<int> crew_id(crew_id_count);
for (int i = 0; i < crew_id_count; i++) {
string crew_id_item_temp;
getline(cin, crew_id_item_temp);

int crew_id_item = stoi(ltrim(rtrim(crew_id_item_temp)));

crew_id[i] = crew_id_item;
}
string job_id_count_temp;
getline(cin, job_id_count_temp);
int job_id_count = stoi(ltrim(rtrim(job_id_count_temp)));
vector<int> job_id(job_id_count);
for (int i = 0; i < job_id_count; i++) {
string job_id_item_temp;
getline(cin, job_id_item_temp);

int job_id_item = stoi(ltrim(rtrim(job_id_item_temp)));

job_id[i] = job_id_item;
}
long result = getMinCost(crew_id, job_id);
fout << result << "\n";
fout.close();
return 0;
}

string ltrim(const string &str) {
string s(str);
s.erase(
s.begin(),
find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
);
return s;
}

string rtrim(const string &str) {
string s(str);

s.erase(
find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
s.end()
);

return s;
}


Recommended Post :-

HCL Coding Questions:-

Capgemini Coding Questions:-

Companies interview:-

Full C course:-    

Key points:-

Cracking the coding interview:-

 Array and string:-

Tree and graph:-

Hackerearth Problems:-

Hackerrank Problems:-

Data structure:-

 MCQs:-