Ignatius and the Princess II
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1027
题目是要:求n个数的第m个全排列
代码:(超时)
#include<iostream>
#include<algorithm>
using namespace std;
const int N=1005;
int main()
{
int n,a[N],m;
while (cin>>n>>m)
{
int num=0;
for (int i=0;i<n;i++)
a[i]=i+1;
do
{
num++;
if (num==m)
{
for (int i=0;i<n;i++)
{
if (i!=n-1)
cout << a[i] << ' ';
else
cout << a[i] << endl;
}
}
}
while(next_permutation(a,a+n)) ;
}
return 0;
}
上面这个代码,提交的答案是超时,因为找到第m个全排列以后忘记break了;
代码:(AC)
#include<iostream>
#include<algorithm>
using namespace std;
const int N=1005;
int main()
{
int n,a[N],m;
while (cin>>n>>m)
{
int num=0;
for (int i=0;i<n;i++)
a[i]=i+1;
do
{
num++;
if (num==m)
{
for (int i=0;i<n;i++)
{
if (i!=n-1)
cout << a[i] << ' ';
else
cout << a[i] << endl;
}
break;
}
}
while(next_permutation(a,a+n)) ;
}
return 0;
}