To make the problem easier, we can only generate a line of the matrix.
There are 362880 different kinds of line from 123456789 to 987654321.
In this problem,we regard 123456789 as the first line,regard 123456798
as the second line, and so on.
输入
The input consists of multiple test cases. Each test case consists of an integer n(0<n<=362880). Process to the end of file.
输出
For each test case, print the nth line.
样例输入
1
2
3
362880
样例输出
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 9 8
1 2 3 4 5 6 8 7 9
9 8 7 6 5 4 3 2 1
代码:
#include <stdio.h>
#include<algorithm>
using namespace std;
int main()
{
int a[] = {1,2,3,4,5,6,7,8,9},n,i;
while (scanf("%d",&n)!=EOF)
{
do
{
n--;
if (n==0)
{
for(i=0;i<9;i++)
{
printf("%d",a[i]);
if(i!=8)
putchar(' ');
if(i==8)
putchar(10);
}
}
}while (next_permutation(a,a+9));
}
return 0;
}
int类型的permutation函数:
do
{
n--;
if (n==0)
{
for(i=0;i<n-1;i++)//输出
{
printf("%d",a[i]);
if(i!=8)
putchar(' ');
if(i==n-1)
putchar(10);
}
}
<font color="#FF0000"> }while (next_permutation(a,a+n));<span style="font-size:18px;"><strong>//参数n指的是要进行排列的长度
<wbr>
//如果存在a之后的排列,就返回true。如果a是最后一个排列没有后继,返回false,每执行一次,a就变成它的后继
</wbr></strong><span style="color:#000000;">下面讲<span style="font-size:18px;">prev_permutation:</span></span><strong>
</strong></span></font>
#include <stdio.h>
#include<algorithm>
using namespace std;
int main()
{
int a[] = {1,2,3,4,5,6,7,8,9},n,i;
while (scanf("%d",&n)!=EOF)
{
do
{
n--;
if (n==0)
{
for(i=0;i<9;i++)
{
printf("%d",a[i]);
if(i!=8)
putchar(' ');
if(i==8)
putchar(10);
}
}
}while (prev_permutation(a,a+9));
}
return 0;
}
结果就是:
当然这个函数还有很多用法。。(一下是摘抄)
(2) char 类型的next_permutation
int main()
{
cin >> ch;
sort(ch, ch + strlen(ch) );
//该语句对输入的数组进行字典升序排序。如输入9874563102cout<<ch;将输出0123456789,这样就能输出全排列了
cout<< ch<< endl;
}while(next_permutation(first, last));
}
//这样就不必事先知道ch的大小了,是把整个ch字符串全都进行排序
//若采用 while(next_permutation(ch,ch+5));如果只输入1562,就会产生错误,因为ch中第五个元素指向未知
//若要整个字符串进行排序,参数5指的是数组的长度,不含结束符
(3) string 类型的next_permutation
int main()
{
{
cout<<line<<endl;
}
}
int main()
{
{
sort(line.begin(),line.end());//全排列
cout<<line<<endl;
cout<<line<<endl;
}
}
#include<iostream> //poj 1256Anagram
#include<string>
#include<algorithm>
using namespace std;
int cmp(char a,char b)//'A'<'a'<'B'<'b'<...<'Z'<'z'.
{
}
int main()
{
cin>>n;
{
scanf("%s",ch);
sort(ch,ch+strlen(ch),cmp);
{
printf("%s\n",ch);
}while(next_permutation(ch,ch+strlen(ch),cmp));
}
}