#define function
- int factorial(const int& a)
- val = 1
- for i=2 to a: val = val * i
- return val
#main
- while true:
- if cin.eof() is true: break // 파일의 끝에 도달하면 탈출
- cin >> str >> n
- len = str.length()
- limit = factorial(len)
- if n > limit : "No permutation" 출력, continue
- for i=0 to n-1:
- next_permutation(str.begin(). str.end())
- 출력 형식에 맞춰서 결과 출력
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void make_permutation(string& str, string& nstr, vector<bool>& visited, int& idx, int& cnt, bool& flag, int& len) {
// 기저사례 nstr.size()==str.size()
if (nstr.size() == len) {
cnt++;
if (idx == cnt) {
flag = true;
cout << nstr << endl;
}
return;
}
for (int i = 0; i < len; i++) {
if (visited[i] == true) continue;
visited[i] = true;
nstr.push_back(str[i]);
make_permutation(str, nstr, visited, idx, cnt, flag, len);
nstr.pop_back();
visited[i] = false;
}
return;
}
int main()
{
while (true) {
string str;
int idx;
cin >> str >> idx;
if (cin.eof()) break;
int len = str.length();
string nstr;
vector<bool> visited(len, false);
int cnt = 0;
bool flag = false;
cout << str << " " << idx << " = ";
make_permutation(str, nstr, visited, idx, cnt, flag, len);
if (flag == false) cout << "No permutation" << endl;
}
}
Leave a comment