- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Two City Scheduling in C++
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
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; 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; } }; main(){ Solution ob; vector<vector<int>> c = {{10,20},{30,200},{400,50},{30,20}}; cout << ob.twoCitySchedCost(c); }
Input
[[10,20],[30,200],[400,50],[30,20]]
Output
110
Advertisements