//
NYOJ--STL--擅长排列的小明
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string a="123456789";
int main()
{
int n;
cin >> n;
while(n--)
{
int n,m;
cin >> n >> m;
string output = a.substr(0,m);
cout << output << endl;
string::iterator i=a.begin();
while(next_permutation(i,i+n))
{
if(!(a.substr(0,m) == output ))
{
output = a.substr(0,m);
cout << output << endl;
}
}
}
system("pause");
return 0;
}
函数next_permutation,可以遍历全排列,要包含头文件<algorithm>与之完全相反的函数还有prev_permutation,next函数默认的是从小到大的顺序,pre函数默认的是从大到小的顺序
int main()
{
int a[3];
a[0]=1;a[1]=2;a[2]=3;
do
{
cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;
} while (next_permutation(a,a+3)); //参数3指的是要进行排列的长度
//如果存在a之后的排列,就返回true。如果a是最后一个排列没有后继,返回false,每执行一次,a就变成它的后继
}
输出:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
如果改成 while(next_permutation(a,a+2));
则输出:
1 2 3
2 1 3
只对前两个元素进行字典排序
显然,如果改成 while(next_permutation(a,a+1)); 则只输出:1 2 3
若排列本来就是最大的了没有后继,则next_permutation执行后,会对排列进行字典升序排序,相当于循环
int list[3]={3,2,1};
next_permutation(list,list+3);
cout<<list[0]<<" "<<list[1]<<" "<<list[2]<<endl;
//输出: 1 2 3