1일1알

백준 1464번 뒤집기 3 C++ 본문

알고리즘

백준 1464번 뒤집기 3 C++

영춘권의달인 2023. 2. 19. 12:05

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

 

1464번: 뒤집기 3

세준이는 어떤 문자열 S를 뒤집으려고 한다. 문자열을 뒤집는 방법은 문자열의 길이를 N이라고 하자. i만큼을 뒤집는다는 소리는 그 문자열의 처음부터 정확하게 i개의 문자를 역순으로 뒤집는

www.acmicpc.net

 

앞에서부터 순서대로 탐색하면서 사전순으로 앞선 문자를 뒤로 보내고 마지막에 뒤집으면 된다.

 

뒤로 보내는 방법은 s[0] ~ s[n-1] 까지 뒤집은 뒤 s[0]~s[n]까지 다시 뒤집으면 되는데, 이 결과는 s[n] + s[0] ~ s[n-1]과 같다.

 

s[n-1] < s[n] 이라면 s[n] + s[0] ~ s[n-1]

s[n-1] >= s[n] 이라면 s[0] ~ s[n-1] + s[n]

 

마지막에 뒤집으면 사전순으로 제일 앞선 문자열이 나온다.

 

#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;

string str;

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

    cin >> str;
    string ans = "";
    ans += str[0];
    for (int i = 1; i < str.length(); i++) {
        if (ans[i - 1] < str[i]) {
            ans = str[i] + ans;
        }
        else {
            ans += str[i];
        }
    }
    reverse(ans.begin(), ans.end());
    cout << ans;
}

'알고리즘' 카테고리의 다른 글

백준 10166번 관중석 C++  (0) 2023.02.21
백준 2594번 놀이공원 C++  (0) 2023.02.20
백준 24230번 트리 색칠하기 C++  (0) 2023.02.18
백준 1913번 달팽이 C++  (0) 2023.02.17
백준 13265번 색칠하기 C++  (0) 2023.02.14