문제 : www.acmicpc.net/problem/1107
백트레킹 브루트포스
[ 알고리즘풀이 ]
우리는 최대 N이 500,000 이므로 고장나지 않은 버튼들로 0 ~999,999 까지만 만들어보면 된다.
고장나지 않은 버튼들로 한 번 숫자를 다 만들고 나서부터는 +, - 버튼 말고 누르는 의미가 없으므로,
0 ~ 999,999 까지 고장나지 않은 버튼들로 만들 수 있는 숫자를 다 만들어 최소 버튼 누르는 횟수를 저장하고 N까지 이동하는데 눌러야되는 +, - 버튼의 횟수를 계산해 최소값을 찾으면 된다.
[ 코드구현 C++ ]
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
#include<iostream>
#include<queue>
#include<string>
#include<cstring>
#include<cmath>
using namespace std;
int N, visited[1000001] = {}, K;
bool isBroken[10] = {};
queue<int> q;
void makeChannel(string s) {
for (int i = 0; i < 10; i++) {
if (!isBroken[i]) {
s += ('0' + i);
if (stoi(s) <= 1000000) {
//cout << "만들어진 채널 : " << s << endl;
visited[stoi(s)] = s.length();
makeChannel(s);
}
s.pop_back();
}
}
}
int main(void) {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
memset(visited, -1, sizeof(visited));
cin >> N >> K;
for (int i = 0, x; i < K; i++) {
cin >> x;
isBroken[x] = 1;
}
// 만들 수 있는 모든 수 들을 만들어본다.
if (!isBroken[0]) visited[0] = 1;
for (int i = 1; i < 10; i++) {
if (!isBroken[i]) {
string t = "";
t.push_back('0' + i);
visited[i] = 1;
makeChannel(t);
}
}
visited[100] = 0;
int ans = 999999999;
for (int i = 0; i <= 1000000; i++) {
if (visited[i] != -1) {
ans = min(ans, abs(N - i) + visited[i]);
}
}
cout << ans << '\n';
return 0;
}
|
cs |
[ github ]
github.com/travelbeeee/ProblemSolving/blob/master/BOJ/BOJ1107.cpp
travelbeeee/ProblemSolving
백준 문제풀이. Contribute to travelbeeee/ProblemSolving development by creating an account on GitHub.
github.com
'Problem Solving > BOJ' 카테고리의 다른 글
[BOJ] 9202 : Boggle (0) | 2020.09.17 |
---|---|
[BOJ] 14226 : 이모티콘 (0) | 2020.09.15 |
[BOJ] 17404 : RGB거리 2 (0) | 2020.09.03 |
[BOJ] 9576 : 책 나눠주기 (0) | 2020.09.02 |
[BOJ] 1202 : LOPOV (0) | 2020.08.28 |