-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWeek10_A_12171675_JeongChanLee.cpp
More file actions
149 lines (122 loc) · 2.69 KB
/
Week10_A_12171675_JeongChanLee.cpp
File metadata and controls
149 lines (122 loc) · 2.69 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#include <iostream>
#include <string>
#include <queue>
#include <algorithm>
#include <string.h>
using namespace std;
int answer;
bool able[10001];
void BFS(int start, string end) {
queue<pair<int, int>> q;
pair<int, int> first = { start, answer };
q.push(first);
while (!q.empty()) {
int cur = q.front().first;
int curAnswer = q.front().second;
able[cur] = false;
q.pop();
for (int i = 0; i < 3; i++) {
if (i == 0) {
int next = cur + 1;
int nextAnswer = curAnswer + 1;
if (next > 9999 || !able[next])
continue;
string check = to_string(next);
if (check.length() != 4) {
if (check.length() == 1)
check = "000" + check;
else if (check.length() == 2)
check = "00" + check;
else
check = "0" + check;
}
if (check == end) {
cout << nextAnswer << '\n';
return;
}
able[next] = false;
q.push({ next, nextAnswer });
}
else if (i == 1) {
int next = cur - 1;
int nextAnswer = curAnswer + 1;
if (next < 0 || !able[next])
continue;
string check = to_string(next);
if (check.length() != 4) {
if (check.length() == 1)
check = "000" + check;
else if (check.length() == 2)
check = "00" + check;
else
check = "0" + check;
}
if (check == end) {
cout << nextAnswer << '\n';
return;
}
able[next] = false;
q.push({ next, nextAnswer });
}
else {
string next = to_string(cur);
int nextAnswer = curAnswer + 1;
if (next.length() != 4) {
if (next.length() == 1)
next = "000" + next;
else if (next.length() == 2)
next = "00" + next;
else
next = "0" + next;
}
string tmp = next;
reverse(next.begin(), next.end());
if (tmp == next)
continue;
if (next == end) {
cout << nextAnswer << '\n';
return;
}
int index;
for (int i = 0; i < 4; i++) {
if (next[i] != '0') {
index = i;
break;
}
}
next = next.substr(index, next.length());
int save = stoi(next);
if (!able[save])
continue;
able[save] = false;
q.push({ save, nextAnswer });
}
}
}
}
void solve() {
memset(able, true, sizeof(bool) * 10001);
int start;
string end;
cin >> start >> end;
if (end.length() != 4) {
if (end.length() == 1)
end = "000" + end;
else if (end.length() == 2)
end = "00" + end;
else
end = "0" + end;
}
answer = 0;
BFS(start, end);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int T;
cin >> T;
while (T--)
solve();
return 0;
}