描述
小明十分聪明,而且十分擅长排列计算。比如给小明一个数字5,他能立刻给出1-5按字典序的全排列,如果你想为难他,在这5个数字中选出几个数字让他继续全排列,那么你就错了,他同样的很擅长。现在需要你写一个程序来验证擅长排列的小明到底对不对。
输入
第一行输入整数N(1<N<10)表示多少组测试数据,
每组测试数据第一行两个整数 n m (1<n<9,0<m<=n)
输出
在1-n中选取m个字符进行全排列,按字典序全部输出,每种排列占一行,每组数据间不需分界。如样例
样例输入
2
3 1
4 2
样例输出
1
2
3
12
13
14
21
23
24
31
32
34
41
42
43
来源
上传者
一:全排列:
从n个不同元素中任取m(m≤n)个元素,按照一定的顺序排列起来,叫做从n个不同元素中取出m个元素的一个排列。当m=n时所有的排列情况叫全排列。
公式:全排列数f(n)=n!(定义0!=1),如1,2,3三个元素的全排列为:
1,2,3
1,3,2
2,1,3
2,3,1
3,1,2
3,2,1
共3*2*1=6种。
二:方法:
以下介绍全排列算法四种:
(A)字典序法
(B)递增进位制数法
(C)递减进位制数法
(D)邻位对换法
三: string 类型的 next_permutation(next函数默认从小到大的顺序,pre函数默认从大到小的顺序)
int main()
{
string line;
while(cin>>line&&line!="#")
{
if(next_permutation(line.begin(),line.end())) //从当前输入位置开始
cout<<line<<endl;
else cout<<"Nosuccesor\n";
}
}
int main()
{
string line;
while(cin>>line&&line!="#")
{
sort(line.begin(),line.end());//全排列
cout<<line<<endl;
while(next_permutation(line.begin(),line.end()))
cout<<line<<endl;
}
}
next_permutation 自定义比较函数
#include<iostream> //poj 1256 Anagram
#include<string>
#include<algorithm>
using namespace std;
int cmp(char a,char b) //'A'<'a'<'B'<'b'<...<'Z'<'z'.
{
if(tolower(a)!=tolower(b))
return tolower(a)<tolower(b);
else
return a<b;
}
int main()
{
char ch[20];
int n;
cin>>n;
while(n--)
{
scanf("%s",ch);
sort(ch,ch+strlen(ch),cmp);
do
{
printf("%s\n",ch);
}while(next_permutation(ch,ch+strlen(ch),cmp));
}
return 0;
}
代码:
#include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;
int N,n,m;
int main()
{
scanf("%d",&N);
while(N--)
{
scanf("%d %d",&n,&m);
string s1,s2;
for(int i=1;i<=n;i++)
s1+='0'+i;//添加数字字符
s2=s1.substr(0,m);
cout<<s2<<endl;
while(next_permutation(s1.begin() ,s1.end() )){//排序排的是整个s1数组,但是输出的不是整个s1数组,而是s2数组。
if(s2!=s1.substr(0,m) ){//substr函数,从s1数组中抽取下标为0到下标为m的字符串,赋给s2数组.
s2=s1.substr(0,m) ;
cout<<s2<<endl;
}
}
}
return 0;
}
substr函数:
用途:一种构造string的方法
形式:s.substr(pos, n)
|
输出结果为:12345