-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1039.cpp
More file actions
48 lines (43 loc) · 1.08 KB
/
1039.cpp
File metadata and controls
48 lines (43 loc) · 1.08 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
#include <bits/stdc++.h>
using namespace std;
string bfs(string s, int k) {
queue<string> q;
int m = s.size();
int cnt = 0;
string ret = "-1";
q.push(s);
while (!q.empty() && cnt < k) {
int size = q.size();
set<string> visited;
for (int t = 0; t < size; t++) {
string cur = q.front();
q.pop();
for (int i = 0; i < m - 1; i++) {
for (int j = i + 1; j < m; j++) {
if (i == 0 && cur[j] == '0') continue;
swap(cur[i], cur[j]);
if (!visited.count(cur)) {
if (cnt == k - 1) ret = max(ret, cur);
q.push(cur);
visited.insert(cur);
}
swap(cur[i], cur[j]);
}
}
}
cnt++;
}
if (cnt != k)
return "-1";
else
return ret;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
string s;
int k;
cin >> s >> k;
cout << bfs(s, k) << "\n";
return 0;
}