1.s.substr(pos,n)功能:从一个字符串复制一个从指定位置pos开始,并具有指定长度n的子字符串
2.next_permutation(,)和prev_permutation(,)
在STL中,除了next_permutation(,)外,还有一个函数prev_permutation(,),两者都是用来计算排列组合的函数。前者是求出下一个排列组合,而后者是求出上一个排列组合。所谓“下一个”和“上一个”,书中举了一个简单的例子:对序列 {a, b, c},每一个元素都比后面的小,按照字典序列,固定a之后,a比bc都小,c比b大,它的下一个序列即为{a, c, b},而{a, c, b}的上一个序列即为{a, b, c},同理可以推出所有的六个序列为:{a, b, c}、{a, c, b}、{b, a, c}、{b, c, a}、{c, a, b}、{c, b, a},其中{a, b, c}没有上一个元素,{c, b, a}没有下一个元素。
next_permutation(,)函数将按字母表顺序生成给定序列的下一个较大的排列,直到整个序列为降序为止。prev_permutation(,)函数与之相反,是生成给定序列的上一个较小的排列。二者原理相同,仅遍例顺序相反。
该段是求1234的全排列,输出1234 1243 1324 1342 1423 1432 2134 2143 2314 2341 2413 2431 3124 3142 3214 3241 3412 3421 4123 4132 4213 4231 4312 4321 一共24个组合。
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
int a[4]={1,2,3,4};
do{
cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<" "<<a[3]<<endl;
}while(next_permutation(a,a+4));
system("pause");
}
prev_permutation:输出结果的顺序和上面相反,从4321到1234,数量一样。
#include <cstdio>
#include <algorithm>
using namespace std;
int main(void)
{
int n,t,a[15];
scanf("%d", &t);
while(t--)
{
scanf("%d", &n);
for(int i=0; i<n; ++i)
a[i] = n-i;
do
{
for(int i=0; i<n; ++i)
printf("%d", a[i]);
printf("\n");
} while (prev_permutation(a,a+n));
}
}
擅长排列的小明
-
描述
- 小明十分聪明,而且十分擅长排列计算。比如给小明一个数字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
AC代码:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int n,m,t;
cin>>t;
while(t--)
{
string s="123456789",s1;
cin>>n>>m;
s=s.substr(0,n);//从0开始选取长度为n的子串
s1=s.substr(0,m);//选子串的子串,长度为m
cout<<s1<<endl;//要先输出第一组,接下来就开始升序了
while(next_permutation(s.begin(),s.end()))
{
if(s1!=s.substr(0,m)) //不是重复的
{
s1=s.substr(0,m);
cout<<s1<<endl;
}
}
}
return 0;
}