ac答案:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n, m, p[1005];
while(cin >> n >> m)
{
for(int i = 0; i < n; i++)
p[i] = i + 1;
m--;
while(m--)
{
next_permutation(p, p + n);
}
for(int j = 0; j < n; j++)
j == n - 1 ? printf("%d\n", p[j]) : printf("%d ", p[j]);
}
return 0;
}
其中用到了函数原型next_permutation();
next_permutation得到下一个排列,如对序列 a, b, c,每一个元素都比后面的小,它的下一个序列即为a, c, b;
其实现原理如下:
在当前序列中,从尾端向前寻找两个相邻元素,前一个记为*i,后一个记为*t,并且满足*i < *t。然后再从尾端寻找另一个元素*j,如果满足*i < *j,即将第i个元素与第j个元素对调,并将第t个元素之后(包括t)的所有元素颠倒排序,即求出下一个序列了。
函数原型
template<class BidirectionalIterator>
bool next_permutation(
BidirectionalIterator first,
BidirectionalIterator last
)
{
if(first == last)
return false; //空序列
BidirectionalIterator i = first;
++i;
if(i == last)
return false; //一个元素,没有下一个序列了
i = last;
--i;
for(;;) {
BidirectionalIterator t = i;
--i;
if(*i < *t) {
BidirectionalIterator j = last;
while(!(*i < *--j));
iter_swap(i, j);
reverse(t, last);
return true;
}
if(i == first) {
reverse(first, last); //全逆向,即为最小字典序列,如cba变为abc
return false;
}
}
}