擅长排列的小明

描述

小明十分聪明,而且十分擅长排列计算。比如给小明一个数字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

来源

[hzyqazasdf]原创

上传者

hzyqazasdf

 

一:全排列:

从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)

 

#include<string>

#include<iostream>

using namespace std;

int main()

{

  string s("12345asdf");

  string a = s.substr(0,5);     //获得字符串s中从第0位开始的长度为5的字符串

  cout << a << endl;

}

输出结果为:12345

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值