Find the arrangement of queue at given time in C++


In this problem, we are given a string consisting of characters 'M' and 'F' only and a time t. Our task is to find the arrangement of the queue at a given time.

The string defines people standing in a common queue to enter the bus. All males in the queue are so chivalrous that if they see a female behind them at any point of time they exchange places with them. There is t unit time left to enter the bus and each exchange takes one unit time. We need to find the positions when the bus comes by rearranging the queue.

Let's take an example to understand the problem,

Input : queue = "MFMMFF" , t = 3
Output : FFMFMM

Explanation

In T = 0 -> 1, 'M' at position 1 changes position with 'W' at 2 and 'M' at position 4 changes position with 'W' at 5. Queue becomes - "FMMFMF".
In T = 0 -> 1, 'M' at position 3 changes position with 'W' at 4 and 'M' at position 5 changes position with 'W' at 6. Queue becomes - "FMFMFM".
In T = 0 -> 1, 'M' at position 2 changes position with 'W' at 3 and 'M' at position 4 changes position with 'W' at 5. Queue becomes - "FFMFMM".

Solution Approach

A simple approach to solve the problem is by traversing the string representing the queue T times. Find the occurrence of "MF" pairs and swap the positions of M and F. And at last return the final string.

Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
string rearrageQueue(int n, int t, string queue) {
   for (int i = 0; i < t; i++)
      for (int j = 0; j < n - 1; j++)
         if (queue[j] == 'M' && queue[j + 1] == 'F') {
            queue[j] = 'F';
            queue[j + 1] = 'M';
            j++;
         }
   return queue;
}
int main() {
   int n = 6, t = 3;
   string queue = "MFMMFF";
   cout<<"The queue after time is over : "<<rearrageQueue(n, t, queue);
   return 0;
}

Output

The queue after time is over : FFMFMM

Updated on: 27-Jan-2022

140 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements