1일1알

백준 2992번 크면서 작은 수 C++ 본문

알고리즘

백준 2992번 크면서 작은 수 C++

영춘권의달인 2022. 12. 4. 11:20

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

 

2992번: 크면서 작은 수

정수 X가 주어졌을 때, X와 구성이 같으면서 X보다 큰 수 중 가장 작은 수를 출력한다. 수의 구성이 같다는 말은, 수를 이루고 있는 각 자리수가 같다는 뜻이다. 예를 들어, 123과 321은 수의 구성이

www.acmicpc.net

 

백트래킹을 이용해서 문제를 해결하였다.

 

#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 target;
int ans = 0;

vector<bool> visited;
vector<int> idxs;

void BT(int cnt) {
    if (cnt >= str.length()) {
        string currStr = "";
        for (auto a : idxs) {
            currStr += str[a];
        }
        int currNum = stoi(currStr);
        if (currNum > target) {
            if (ans == 0) ans = currNum;
            else ans = min(ans, currNum);
        }
        return;
    }
    for (int i = 0; i < str.length(); i++) {
        if (visited[i]) continue;
        visited[i] = true;
        idxs.push_back(i);
        BT(cnt + 1);
        visited[i] = false;
        idxs.pop_back();
    }
}

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

    cin >> str;
    target = stoi(str);
    visited = vector<bool>(str.length(), false);
    BT(0);
    cout << ans;
}