摘自http://old.blog.edu.cn/user4/248323/archives/2007/1935675.shtml
STL就是好啊,next_permutation可以计算一组数据的全排列
// next_permutation #i nclude <iostream> #i nclude <algorithm> using namespace std; int main () { int myints[] = {1,2,3}; cout << "The 3! possible permutations with 3 elements:/n"; sort (myints,myints+3); do { cout << myints[0] << " " << myints[1] << " " << myints[2] << endl; } while ( next_permutation (myints,myints+3) ); return 0; }
这样就可以排除n个数的全排列了
int main(){
int a[] = {3,1,2};
do{
cout << a[0] << " " << a[1] << " " << a[2] << endl;
}
while (next_permutation(a,a+3));
return 0;
}
如果是这样的话,因为原序列没有排序,就从当前序列开始,只输出比它大大序列,若已经到最大序列,返回值为false,序列变成最小的序列,就不再执行了
prev_permutation与next_permutation相反,由原排列得到字典序中上一次最近排列
http://support.microsoft.com/kb/157869/zh-tw
http://blog.bc-cn.net/user20/130988/archives/2007/6553.shtml中有详细的解析
//学习next_permutation函数 1833的代码
#i nclude<iostream>
#i nclude<algorithm>
using namespace std;
int main()
{
int ncase,n,k,i;
int s[1024];
scanf("%d",&ncase);
while(ncase--)
{
scanf("%d%d",&n,&k);
for(i=0;i<n;i++)
scanf("%d",&s[i]);
for(i=0;i<k;i++)
next_permutation(s,s+n);
for(i=0;i<n-1;i++)
printf("%d ",s[i]);
printf("%d/n",s[i]);
}
}