본문 바로가기

Algorithm/DFS

(C++) - 백준(BOJ) 1039번 : 교환

반응형

문제링크 : https://www.acmicpc.net/problem/1039

 

1039번: 교환

첫째 줄에 정수 N과 K가 주어진다. N은 1,000,000보다 작거나 같은 자연수이고, K는 10보다 작거나 같은 자연수이다.

www.acmicpc.net

메모이제이션을 사용한 DFS 백트래킹 브루트포스 문제였습니다.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
using namespace std;
int m,k;
string n;
int ck[1000001];
int cnt = 0;
int d[1000001][11];
 
int dfs(string a,int depth)
{
    if (depth == k) {
        return stoi(a);
    }
 
    int &ret = d[stoi(a)][depth];
    if (ret!=-1)return ret;
 
    for (int i = 0; i < a.size()-1; i++)
    {
        for (int j = i+1; j < a.size(); j++)
        {
            
            swap(a[i], a[j]);
            if (a[0== '0') {
                swap(a[i], a[j]);
                continue;
            }
            ret=max(ret,dfs(a, depth+1));
            swap(a[i], a[j]);
        }
    }
    return ret;
}
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> n >> k;
    memset(d, -1sizeof(d));
    cout << dfs(n,0<< '\n';
}