- toc {:toc}
๋ฌธ์ ํ์ธํ๊ธฐ
1039: ๊ตํ ๋ฌธ์ ํ์ธํ๊ธฐ
ํ์ด
์ฐ์ฐ ์์ฒด๋ i์ j๋ฅผ ๊ณจ๋ผ swapํ๋ ๊ฐ๋จํ ์ฐ์ฐ์ด๋ค. ๋ค์์ ์ฐ์ฐ์ K๋ฒ ์งํํ์ฌ ๋์ฌ ์ ์๋ ์ต๋๊ฐ์ ๊ตฌํ๋ ๋ฌธ์ ์ด๋ค. ์ด๋, ์ง์คํด์ ๋ด์ผํ ์ ์ K๋ฒ์ ์งํํ๋ค๋ ๋ถ๋ถ์ด๋ค.
- ์ฃผ์ด์ง ์ฐ์ฐ์ K๋ฒ ํ์ ๋, ๋ง๋ค ์ ์๋ ๊ฐ์ฅ ํฐ ์
- 1~K๋ฒ ์ฐ์ฐ์ ์งํ ์ค ๋์ฌ ์ ์๋ ๊ฐ์ฅ ํฐ ์
- K๋ฒ์งธ ์ฐ์ฐ์ ํ์ ๋ ๋์ฌ ์ ์๋ ๊ฒฝ์ฐ์ ์์์ ๊ฐ์ฅ ํฐ ์
๋ค์ 1, 2๋ฒ ์ค ์ด๋ค ๊ฒ์ ์๋ฏธํ ๊น? ํด๋น ๋ฌธ์ ๋ 2๋ฒ์ ์๋ฏธํ๋ค. ๋๋ฌธ์ K๋ฒ์ ์ฐ์ฐ์ ๋ฐ๋์ ์งํํด์ผ ํ๋ฏ๋ก level์ ํตํด ํด๋น ๊ณ์ฐ์ด ๋ช ๋ฒ ์ฐ์ฐ๋๋์ง ํ์ธํ๋ค. ๋ชจ๋ ๊ฒฝ์ฐ์ ์๋ฅผ ํ์ธํด์ผ ํ๊ธฐ์ BFS๋ฅผ ์ฌ์ฉํ๊ณ ๋ฐฉ๋ฌธํ์ ๊ฒฝ์ฐ ๋ฐฉ๋ฌธ ์ฌ๋ถ๋ฅผ ์ฒดํฌํ๋ค. ์ดํ K๋ฒ ์ฐ์ฐํ ๊ฒ์ ๋ฐ๋ก max_q์ ์ ์ฅํด๋๊ณ max_q์์ ๊ฐ์ฅ ํฐ ์๋ฅผ ๋ฐํํ๋ค.
#include <bits/stdc++.h>
using namespace std;
int depth[1000001];
int visit[1000001] = {};
string N;
int res = 0, K, level=0;
queue<pair<string, int>> q;
queue<int> max_q;
string Swap(string str, int i, int j){
char temp;
temp = str[i];
str[i] = str[j];
str[j] = temp;
return str;
}
void bfs(){
int stage = 0;
while(q.empty()==0){
string str = q.front().first;
level = q.front().second;
if (stage != level) {
stage = level;
fill(visit, visit+1000001, 0);
}
if (level == K) {
max_q.push(stoi(str));
q.pop();
continue;
}
for(int i=0; i<N.size()-1; i++){
for(int j=i+1; j<N.size(); j++){
string change = str;
if(i==0 && str[j] == '0') continue;
change = Swap(str, i, j);
int val = stoi(change);
// ๋ฐฉ๋ฌธ ์ฌ๋ถ ํ์ธ
if (!visit[val]){
visit[val] = 1;
q.push({change, level+1});
}
}
}
q.pop();
}
}
int main(){
ios::sync_with_stdio(true);
cin.tie(0); cout.tie(0);
cin >> N >> K;
q.push({N, 0});
if (K==0){
cout << N << endl;
exit(0);
}
else if (N.size() == 1 || (N.size() == 2 && stoi(N) % 10 == 0)){
cout << -1 << endl;
exit(0);
}
bfs();
while(!max_q.empty()){
if(res < max_q.front()){
res = max_q.front();
}
max_q.pop();
}
cout << res << endl;
return 0;
}