본문 바로가기

Beakjoon/else

[백준] 9081번 단어 맞추기 (C++)

문제

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

 

9081번: 단어 맞추기

입력의 첫 줄에는 테스트 케이스의 개수 T (1 ≤ T ≤ 10)가 주어진다. 각 테스트 케이스는 하나의 단어가 한 줄로 주어진다. 단어는 알파벳 A~Z 대문자로만 이루어지며 항상 공백이 없는 연속된 알

www.acmicpc.net

코드

#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

char word[100];

int main(){
  int t;
  cin >> t;
  while(t--){
    string s;
    cin >> s;
    int length = s.length();
    for(int i=0; i<length; i++){
      word[i] = s[i];
    }

    int criIdx = length;
    for(int i=length-1; i>0; i--){
      if(word[i-1] < word[i]){
        criIdx=i;
        break;
      }
    }
    if(criIdx==length){
      cout << s << '\n';
      continue;
    }

    for(int i=length-1; i>=criIdx; i--){
      if(word[criIdx-1] < word[i]){
        swap(word[criIdx-1], word[i]);
        break;
      }
    }

    sort(word+criIdx, word+length);

    for(int i=0; i<length; i++){
      cout << word[i];
    }
    cout << '\n';
  }
  return 0;
}

 

다른 풀이(next_permutation 사용)

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>

using namespace std;

int main(){
  int t;
  cin >> t;
  while(t--){
    string s;
    cin >> s;
    vector<char> v;
    for(int i=0; i<s.length(); i++){
      v.push_back(s[i]);
    }
    if(next_permutation(v.begin(), v.end())){
      for(char c : v){
        cout << c;
      }
    }else{
      cout << s;
    }
    cout << '\n';
  }
  return 0;
}

정리

10972번과 매우 유사한 문제이다. 숫자 대신 문자로 바뀐 문제라고 생각하면 쉽다.

참조

https://kdongree.tistory.com/100