next_permutation函数
今天做题时,用到了这个函数,亮瞎我的双眼~~~
先贴出来题目!!!!!!
刚看到题目,没多少思路,没想到STL有这么一个函数,先看看AC代码。
#include<stdio.h>
#include <ctype.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
bool 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()
{
int n,l;
char a[15];
scanf("%d",&n);
while(n--)
{
scanf("%s",a);
l = strlen(a);
sort(a, a + l,cmp);
do
{
printf("%s\n",a);
}while(next_permutation(a, a + l, cmp));
}
return 0;
}
next_permutation 的头文件#include<algorithm>
作用: 求全排列,按字典序排列!!!
(1)in
t类型的 的next_permutation
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
int main()
{
int a[3];
a[0] = 1;
a[1] = 2;
a[2] = 3;
do
{
printf("%d %d %d\n",a[0],a[1],a[2]);
}while(next_permutation(a,a + 3));
return 0;
}
(next_permutation(a,a + 2)) 也就是从a[0]到a[1]的排列。
上面代码输出
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
如果把a+3改成a + 2 就是
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
如果把a+3改成a + 2 就是
1 2 3
2 1 3
(2) char 类型的next_permutation
2 1 3
(2) char 类型的next_permutation
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
int main()
{
char a[200];
scanf("%s",a);
sort(a,a + strlen(a));
do
{
printf("%s\n",a);
}while(next_permutation(a,a + strlen(a)));
return 0;
}
意思跟int类型的含义一样,next_permutation()括号里面是指针,也可以定义指针变量来指定排列。
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<iostream>
#include<string>
using namespace std;
int main()
{
string line;
while(cin>>line&&line!="#")
{
if(next_permutation(line.begin(),line.end())) //从当前输入位置开始
cout<<line<<endl;
}
}
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;
}
}
两个函数,一个是从当前排列,一个是全排列,跟平成一样
(4)自定义比较函数的全排列(代码见上面题目AC代码)
自定义比较函数跟构造sort自定义比较函数一模一样,用法也是一样
next_permutation(首地址,尾地址,构造的比较函数)。
上面AC代码用了tolower();函数,这个函数的作用就是把大写变成小写。还有toupper()把小写转换成大写。
大小写转换函数的头文件都是#include <ctype.h>。
(5)类似的next_permutation还有与之完全相反的函数还有prev_permutation
作用是得到上一个排列。
代码可以验证。
输出为:
3 2 1
3 1 2
2 3 1
2 1 3
1 3 2
1 2 3
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
int main()
{
int a[3];
a[0] = 3;
a[1] = 2;
a[2] = 1;
do
{
printf("%d %d %d\n",a[0],a[1],a[2]);
}while(prev_permutation(a,a + 3));
return 0;
}
输出为:
3 2 1
3 1 2
2 3 1
2 1 3
1 3 2
1 2 3