Ignatius and the Princess II
题目描述
Problem Description:
Now our hero finds the door to the BEelzebub feng5166. He opens the door and finds feng5166 is about to kill our pretty Princess. But now the BEelzebub has to beat our hero first. feng5166 says, “I have three question for you, if you can work them out, I will release the Princess, or you will be my dinner, too.” Ignatius says confidently, “OK, at last, I will save the Princess.”
“Now I will show you the first problem.” feng5166 says, “Given a sequence of number 1 to N, we define that 1,2,3…N-1,N is the smallest sequence among all the sequence which can be composed with number 1 to N(each number can be and should be use only once in this problem). So it’s easy to see the second smallest sequence is 1,2,3…N,N-1. Now I will give you two numbers, N and M. You should tell me the Mth smallest sequence which is composed with number 1 to N. It’s easy, isn’t is? Hahahahaha…”
Can you help Ignatius to solve this problem?
Input:
The input contains several test cases. Each test case consists of two numbers, N and M(1<=N<=1000, 1<=M<=10000). You may assume that there is always a sequence satisfied the BEelzebub’s demand. The input is terminated by the end of file.
output:
For each test case, you only have to output the sequence satisfied the BEelzebub’s demand. When output a sequence, you should print a space between two numbers, but do not output any spaces after the last number.
样例输入:
6 4
11 8
样例输出:
1 2 3 5 6 4
1 2 3 4 5 6 7 9 8 11 10
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1027
思路:
该题是多组测试,题目大意是输入m,n,求第n个m的最小全排序列。
例如输入6 4;
把1~6全排列:
1 2 3 4 5 6
1 2 3 4 6 5
1 2 3 5 4 6
1 2 3 5 6 4
…
即输出第四个排列:1 2 3 5 6 4。
这道题可以用C++ STL全排列里的函数next_permutation
使用next_permutation需要引入头文件 #include < algorithm >
next_permutation:求下一个排列方式
使用方法为next_permutation(a,a+a.size())
其中a是数组名,其返回值是bool型,当不存在下一个排列方式时返回false,其余返回true,被排列好的数据会被存入原数组。与其相对的也有prev_permutation函数,是求上一个排列方式。其与next_permutation使用方法类似,返回值都为bool型。
全排列算法思路:
全排列是借助递归实现的,通过不断地把一个数当作坐标,再去寻找下一个数,并把下一个数当作新的坐标(坐标之前的数据不变),以此通过递归去寻找,直到寻找完所有数据,即得到一种全排列方式。
#include <iostream>
using namespace std;
void Permutations(int a[],int begin,int end) //全排列函数
{
if(begin == end) //如果寻找完所有数据则输出
{
for(int i = 0;i<=end;i++)
cout << a[i] << ' ';
cout <<endl;
return;
}
else //反之寻找下一个数据
{
int t;
for(int i = begin;i <= end;i++)
{
t = a[begin];a[begin] = a[i]; a[i] = t; //换值,以让所有的数据都当一次坐标
Permutations(a,begin+1,end); //递归寻找下一个数据
t = a[begin];a[begin] = a[i]; a[i] = t; //把数据归位,进行下一次循环
}
}
}
int main()
{
int n;
while(cin >> n)
{
int a[n];
for(int i = 0;i<n;i++)
a[i]=i+1;
Permutations(a,0,n-1);
}
}
代码:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n,m;
while(cin >> n >> m)
{
int a[n];
for(int i = 0;i<n;i++) //初始化数组
a[i]=i+1;
int d = 0;
do{
d++;
if(d==m) //得到第m个全排列时输出
{
int i;
for(i = 0;i < n-1; i++)
cout << a[i] << ' ';
cout << a[i] << endl;
break; //输出后结束循环
}
}
while(next_permutation(a,a+n)); //全排列函数的调用
}
}