To solve the Student Rearrangement Problem, we need to ensure that each student in line A has a corresponding student in line B with the same height. The goal is to achieve this by performing swaps between the two lines with minimal cost, where the cost of each swap is equal to the height of the shorter student involved in the swap.
Here's a step-by-step breakdown of the approach:
-
Frequency Count and Feasibility Check:
- Frequency Count: Calculate the frequency of each height in both lines A and B.
- Feasibility Check: For each height, the total number of students (from both lines) must be even. If any height has an odd total count, it's impossible to balance the lines, and we return
-1.
-
Determine Surplus Students:
- For each height, determine how many students need to be moved from line A to line B or vice versa to balance the frequencies.
- Collect all surplus heights from line A in one list and from line B in another.
-
Minimize Swap Cost:
- Sort the surplus lists: one in ascending order and the other in descending order.
- Pair the smallest surplus from line A with the largest surplus from line B. This pairing minimizes the
min(a, b) cost.
- Additionally, consider the global minimum height across both lines. Sometimes, it might be cheaper to perform two swaps involving the minimum height rather than a direct swap. This is taken into account by calculating
min(min(a, b), 2 * global_min) for each pair.
-
Calculate Total Cost:
- Sum up the minimal costs for all necessary swaps.
Below is the C++ implementation of the above approach:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
// Function to rearrange students with minimal cost
long rearrangeStudents(vector<int> arrA, vector<int> arrB) {
int n = arrA.size();
// Find the global minimum height
int minH = INT32_MAX;
for(auto h : arrA) minH = min(minH, h);
for(auto h : arrB) minH = min(minH, h);
// Sort both arrays
sort(arrA.begin(), arrA.end());
sort(arrB.begin(), arrB.end());
// Count frequencies
// Use two pointers since both arrays are sorted
vector<pair<int, int>> counts; // pair of (height, countA, countB)
int i = 0, j = 0;
int sizeA = arrA.size();
int sizeB = arrB.size();
vector<pair<int, int>> freqA;
vector<pair<int, int>> freqB;
// Count frequencies for arrA
vector<int> uniqueA;
vector<int> countListA;
if(n > 0){
int current = arrA[0];
int cnt =1;
for(int p=1;p<n;p++){
if(arrA[p]==current){
cnt++;
}
else{
freqA.emplace_back(make_pair(current, cnt));
current = arrA[p];
cnt=1;
}
}
freqA.emplace_back(make_pair(current, cnt));
}
// Count frequencies for arrB
vector<pair<int, int>> freqBList;
if(n >0){
int current = arrB[0];
int cnt =1;
for(int p=1;p<n;p++){
if(arrB[p]==current){
cnt++;
}
else{
freqBList.emplace_back(make_pair(current, cnt));
current = arrB[p];
cnt=1;
}
}
freqBList.emplace_back(make_pair(current, cnt));
}
// Merge frequencies
vector<int> uniqueHeights;
int pA=0, pB=0;
while(pA < freqA.size() && pB < freqBList.size()){
if(freqA[pA].first == freqBList[pB].first){
uniqueHeights.push_back(freqA[pA].first);
pA++;
pB++;
}
else if(freqA[pA].first < freqBList[pB].first){
uniqueHeights.push_back(freqA[pA].first);
pA++;
}
else{
uniqueHeights.push_back(freqBList[pB].first);
pB++;
}
}
while(pA < freqA.size()){
uniqueHeights.push_back(freqA[pA].first);
pA++;
}
while(pB < freqBList.size()){
uniqueHeights.push_back(freqBList[pB].first);
pB++;
}
// Remove duplicates
sort(uniqueHeights.begin(), uniqueHeights.end());
uniqueHeights.erase(unique(uniqueHeights.begin(), uniqueHeights.end()), uniqueHeights.end());
// Now, for each unique height, get counts in A and B
// Use binary search since freqA and freqBList are sorted
// Alternatively, traverse both freqA and freqBList with two pointers
pA =0; pB=0;
vector<ll> to_move_from_A;
vector<ll> to_move_from_B;
for(auto h : uniqueHeights){
int cntA =0, cntB=0;
if(pA < freqA.size() && freqA[pA].first == h){
cntA = freqA[pA].second;
pA++;
}
if(pB < freqBList.size() && freqBList[pB].first == h){
cntB = freqBList[pB].second;
pB++;
}
ll total = (ll)cntA + (ll)cntB;
if(total %2 !=0){
return -1;
}
ll desired = total /2;
if((ll)cntA > desired){
ll surplus = ((ll)cntA - desired);
for(ll s=0; s < surplus/2; s++) {
to_move_from_A.push_back(h);
}
}
if((ll)cntB > desired){
ll surplus = ((ll)cntB - desired);
for(ll s=0; s < surplus/2; s++) {
to_move_from_B.push_back(h);
}
}
}
// If no swaps needed
if(to_move_from_A.empty()) return 0;
// Sort to_move_from_A ascending and to_move_from_B descending
sort(to_move_from_A.begin(), to_move_from_A.end());
sort(to_move_from_B.begin(), to_move_from_B.end(), greater<ll>());
// Compute total cost
ll total_cost =0;
ll m = to_move_from_A.size();
for(ll k=0; k < m; k++){
ll a = to_move_from_A[k];
ll b = to_move_from_B[k];
total_cost += min( (ll)min(a, b), 2LL * (ll)minH );
}
return total_cost;
}
// Below is some test code to verify the function.
int main(){
// Example Test Case
vector<int> arrA = {4, 2, 2, 2};
vector<int> arrB = {1, 4, 1, 2};
cout << rearrangeStudents(arrA, arrB) << endl; // Expected Output: 1
// Additional Test Cases
// Test Case 2: Impossible case
vector<int> arrA2 = {1, 2};
vector<int> arrB2 = {1, 3};
cout << rearrangeStudents(arrA2, arrB2) << endl; // Expected Output: -1
// Test Case 3: Already balanced
vector<int> arrA3 = {1, 1, 2, 2};
vector<int> arrB3 = {1, 1, 2, 2};
cout << rearrangeStudents(arrA3, arrB3) << endl; // Expected Output: 0
// Test Case 4: Minimal swaps
vector<int> arrA4 = {2, 2};
vector<int> arrB4 = {1, 1};
cout << rearrangeStudents(arrA4, arrB4) << endl; // Expected Output: 1
// Test Case 5: Larger case
vector<int> arrA5 = {1, 3, 2, 4, 5};
vector<int> arrB5 = {2, 3, 1, 5, 4};
cout << rearrangeStudents(arrA5, arrB5) << endl; // Expected Output: 0
return 0;
}
Explanation of the Code
-
Finding the Global Minimum Height (minH):
- Iterate through both
arrA and arrB to find the smallest height. This value is used to determine if it's cheaper to perform a direct swap or to involve the smallest element in a two-step swap.
-
Sorting and Counting Frequencies:
- Sort both
arrA and arrB to simplify frequency counting.
- Use two separate lists (
freqA and freqBList) to store the frequency of each height in arrA and arrB, respectively.
- Merge these frequency lists to process each unique height once.
-
Balancing the Frequencies:
- For each unique height, calculate the total count across both lines.
- If the total count is odd for any height, return
-1 as it's impossible to balance.
- Determine how many students need to be moved from
arrA to arrB or vice versa to achieve equal frequencies.
-
Sorting Surplus Lists:
- Sort the list of students to be moved from
arrA in ascending order.
- Sort the list of students to be moved from
arrB in descending order.
-
Calculating the Minimal Total Cost:
- Pair the smallest surplus from
arrA with the largest surplus from arrB and calculate the cost for each swap using the formula: min(min(a, b), 2 * minH).
- Sum these costs to get the total minimal cost.
-
Handling Edge Cases:
- If no swaps are needed (i.e., the lists are already balanced), the cost is
0.
- The function includes additional test cases to validate different scenarios.
Complexity Analysis
-
Time Complexity:
- Sorting both arrays takes
O(N log N) time.
- Counting frequencies and processing the lists are done in linear time relative to the number of unique heights.
- Thus, the overall time complexity is
O(N log N).
-
Space Complexity:
- Additional space is used for frequency counts and surplus lists, which in the worst case can be
O(N).
This solution efficiently handles large inputs within the given constraints and ensures that the minimal cost is accurately computed or identifies if the task is impossible.