在給定時間內用 C++ 查詢佇列的排列
在此問題中,我們給定一個僅包含字元 'M' 和 'F' 的字串和時間 t。我們的任務是找出佇列在給定時間內的排列。
該字串定義了排隊進站的佇列。如果佇列中的所有男性在任何時間點看到女性在他們後面,他們會與女性交換位置。在進站前還有一單位時間,並且每次交換需要一單位時間。我們需要在公共汽車到達時重新排列佇列,並找出位置。
我們以一個例子來說明這個問題,
Input : queue = "MFMMFF" , t = 3 Output : FFMFMM
說明 -
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".
解決方案方法
解決此問題的簡單方法是遍歷表示佇列的字串 T 次。找出 "MF" 對的出現然後交換 M 和 F 的位置。最後返回最終字串。
示例
說明我們解決方案的工作原理的程式
#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;
}輸出
The queue after time is over : FFMFMM
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP