1일1알

백준 5002번 도어맨 C++ 본문

알고리즘

백준 5002번 도어맨 C++

영춘권의달인 2023. 5. 20. 15:53

https://www.acmicpc.net/problem/5002

 

5002번: 도어맨

첫째 줄에 정인이가 기억할 수 있는 가장 큰 차이 X<100이 주어진다. 둘째 줄에는 줄을 서 있는 순서가 주어진다. W는 여성, M은 남성을 나타내며, 길이는 최대 100이다. 가장 왼쪽에 있는 글자가 줄

www.acmicpc.net

 

문자열을 순회하면서

현재 인덱스의 원소가 M일때 만약 남자-여자 수가 x 미만이면 남자그대로 들여보내고

x 이상이면 다음 사람이 남자라면 더이상 입장 불가, 여자라면 자리를 바꿔서 입장시킨다.

현재 인덱스의 원소가 W일때도 같은 방식으로 하면 된다.

 

#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>

using namespace std;
using int64 = long long;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int x;
    string str;
    cin >> x >> str;
    int m = 0;
    int w = 0;
    for (int i = 0; i < str.length(); i++) {
        if (str[i] == 'M') {
            if (m - w >= x) {
                if (i == str.length() - 1) break;
                if (str[i + 1] == 'M') break;
                swap(str[i], str[i + 1]);
                w++;
            }
            else {
                m++;
            }
        }
        else {
            if (w - m >= x) {
                if (i == str.length() - 1) break;
                if (str[i + 1] == 'W') break;
                swap(str[i], str[i + 1]);
                m++;
            }
            else {
                w++;
            }
        }
    }
    cout << m + w;
}