- Related Questions & Answers
- How to get nearby city information from Network provider in android?
- How to get city information from Network provider in android?
- What's the best city in India to watch a movie?
- What is the cheapest method of transporting vehicles from one city to another?
- How to make relocating in a new city easy?
- MySQL query to find a list of city names that do not start with vowels?
- Which is the most polluted city in India now?
- Why does any government start makeover of cities when they have foreign delegates visiting the city?
- Which city is best for a Six Sigma Black Belt holders in India?
- Which city of India is called the city of dreams and why?
- Validate city and state with Java Regular Expressions
- Process Scheduling Fundamentals
- Short-term vs medium-term vs long-term scheduling
- Weighted Job Scheduling
- Operating system time slicing in round robin scheduling

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose there are 2N persons. A company wants to organize one interview. The cost for flying the i-th person to city A is costs[i][0], and the cost for flying the i-th person to city B is costs[i][1]. We have to find the minimum cost to fly every person to a city, such that N people arrive in every city. So if the given list is [[10, 20], [30, 200], [400, 50], [30, 20]] The output will be 110. So we will send the person P1 to city A with cost 10, Second person to city A with cost 30, third and fourth person to city B with cost 50 and 20 respectively.

To solve this, we will follow these steps −

- n := size of the array
- a := n / 2 and b := n / 2
- Sort the array, and let ans := 0
- for i := 0 to n – 1 −
- if b = 0 and array[i, 0] <= array[i, 1] and a > 0, then
- decrease a by 1
- ans := ans + array[i, 0]

- else
- decrease b by 1
- ans := ans + array[i, 1]

- if b = 0 and array[i, 0] <= array[i, 1] and a > 0, then
- return ans

Let us see the following implementation to get better understanding −

class Solution { public: static bool cmp(vector <int> a, vector <int> b){ return abs(a[0] - a[1]) > abs(b[0] - b[1]); } int twoCitySchedCost(vector<vector<int>>& costs) { int n = costs.size(); int a = n/2; int b = n/2; sort(costs.begin(), costs.end(), cmp); int ans = 0; for(int i = 0; i < n; i++){ if(b == 0 || (costs[i][0] <= costs[i][1] && a > 0)){ a--; //cout << a << " " << costs[i][0] << endl; ans += costs[i][0]; } else { //cout << costs[i][1] << endl; b--; ans += costs[i][1]; } } return ans; } };

[[10,20],[30,200],[400,50],[30,20]]

110

Advertisements