好东西顺便转过来了~~哈哈~~
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相反,由原排列得到字典序中上一次最近排列
补充下:next_permutation 处理的已经在最后的排列像3 2 1 那么下一个就是会1 2 3 好用啊,prev_permutation也是如此。
STL 需要学习学习。。。。
http://support.microsoft.com/kb/157869/zh-tw
http://blog.bc-cn.net/user20/130988/archives/2007/6553.shtml中有详细的解析
排列
Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 7404 Accepted: 3385 Description
题目描述:
大家知道,给出正整数n,则1到n这n个数可以构成n!种排列,把这些排列按照从小到大的顺序(字典顺序)列出,如n=3时,列出1 2 3,1 3 2,2 1 3,2 3 1,3 1 2,3 2 1六个排列。
任务描述:
给出某个排列,求出这个排列的下k个排列,如果遇到最后一个排列,则下1排列为第1个排列,即排列1 2 3…n。
比如:n = 3,k=2 给出排列2 3 1,则它的下1个排列为3 1 2,下2个排列为3 2 1,因此答案为3 2 1。
Input
第一行是一个正整数m,表示测试数据的个数,下面是m组测试数据,每组测试数据第一行是2个正整数n( 1 <= n < 1024 )和k(1<=k<=64),第二行有n个正整数,是1,2 … n的一个排列。Output
对于每组输入数据,输出一行,n个数,中间用空格隔开,表示输入排列的下k个排列。Sample Input
3 3 1 2 3 1 3 1 3 2 1 10 2 1 2 3 4 5 6 7 8 9 10Sample Output
3 1 2 1 2 3 1 2 3 4 5 6 7 9 8 10然后这个题目还困难吗????
//学习next_permutation函数 1833的代码
#include<iostream>
#include<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]);
}
}