再也不用为全排列绞尽脑汁,递归什么的早就out了
next_permutation()这是个好东西
可以输出不重复的全排列
1.用comp()函数构造自己希望的排列方式
如POJ 1256:
bool comp(const char &a,const char &b)
{
int x,y;
if(islower(a)&&islower(b))
{
if(a<b)
return 1;
else
return 0;
}
else if(isupper(a)&&isupper(b))
{
if(a<b)
return 1;
else
return 0;
}
else if(isupper(a)&&islower(b))
{
x=a-'A';
y=b-'a';
if(x<=y)
return 1;
else
return 0;
}
else
{
x=a-'a';
y=b-'A';
if(x<y)
return 1;
else
return 0;
}
}
我们可以这样输出
while(next_permutation(str,str+len,comp))//注意不能输出第一个排列
printf("%s\n",str);
这个comp(),sort()函数也可用,变为:AaBbCc序列
效果:str="aAb"
Aab Aba aAb
abA bAa baA
2.普通用法
NYOJ 19
题意:在1-n中选取m个字符进行全排列
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int main()
{
char str[15],copy[15],cut[15];
int i,n,x,y;
cin>>n;
while(n--)
{
cin>>x>>y;
memset(str,0,sizeof(str));
memset(copy,0,sizeof(copy));
memset(cut,0,sizeof(cut));
for(i=0;i<x;i++)
str[i]=i+1+'0';
strncpy(copy,str,y);//输出第一个排列
cout<<copy<<endl;
while(next_permutation(str,str+x))
{
strncpy(cut,str,y);
if(strcmp(copy,cut)!=0)
{
cout<<cut;
cout<<endl;
}
strncpy(copy,str,y);
}
}
return 0;
}
3.适用于枚举情况,找出最优解
如:hdu 1572
while(cin>>T&&T)
{
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(f,0,sizeof(f));
for(i=0;i<T;i++)
for(j=0;j<T;j++)
cin>>a[i][j];
cin>>N;
k=0;
for(i=0;i<N;i++)
{
cin>>n;
if(!f[n])
{f[n]=1;b[k]=n;++k;}
}
sort(b,b+k);
XY=sum=0;
for(j=0;j<k;j++)
{
sum+=a[XY][b[j]];
XY=b[j];
}
max=sum;
while(next_permutation(b,b+k))//客人较少,最多7人,可枚举
{
XY=sum=0;
for(j=0;j<k;j++)
{
sum+=a[XY][b[j]];
XY=b[j];
}
if(sum<max)
max=sum;
}
cout<<max<<endl;
}