您的位置:首页 > 其它

next_permutation的简单用法及例题

2017-04-07 18:00 405 查看
一:基本用法;

#include<cstdio>
#include<cstring>
#include<algorithm>
#define max_n 1010
using namespace std;

int a[max_n];

int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,a+n);
do
{
for(int i=0;i<n;i++)
{
if(i>0) printf(" ");
printf("%d",a[i]);
}
printf("\n");
}while(next_permutation(a,a+n));
}
return 0;
}


#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#define max_n 1010
using namespace std;

vector<int> v;

bool cmp(int x,int y)
{
return x<y;
}

int main()
{
int n,k;
while(scanf("%d",&n)!=EOF)
{
for(int i=0;i<n;i++)
{
scanf("%d",&k);
v.push_back(k);
}
sort(v.begin(),v.end(),cmp);
do
{
for(int i=0;i<n;i++)
{
if(i>0) printf(" ");
printf("%d",v.at(i));
}
printf("\n");
}while(next_permutation(v.begin(),v.end()));
}
return 0;
}

二:例题分析:

51nod 1384
全排列


给出一个字符串S(可能有重复的字符),按照字典序从小到大,输出S包括的字符组成的所有排列。例如:S = "1312",
输出为:

1123 1132 1213 1231 1312 1321 2113 2131 2311 3112 3121 3211

Input
输入一个字符串S(S的长度 <= 9,且只包括0 - 9的阿拉伯数字)

Output
输出S所包含的字符组成的所有排列

Input示例
1312

Output示例
1123
1132
1213
1231
1312
1321
2113
2131
2311
3112
3121
3211


思路:不用指针便会TLE,惊呆我了!!!

#include<cstdio>
#include<cstring>
#include<algorithm>
#define max_n 1010
using namespace std;

char a[max_n];

int main()
{
scanf("%s",a);
int n=strlen(a);
sort(a,a+n);
char *p1,*p2; //不用指针会TLE
p1=&a[0];
p2=&a
;
do
{
printf("%s\n",a);
}while(next_permutation(p1,p2));
return 0;
}



#include<cstdio>
#include<algorithm>
using namespace std;

int a[110];

int main()
{
int x,y,z;
for(int i=0;i<=9;i++)
a[i]=i;
do
{
if(!a[0] || !a[4])
continue;
x=a[0]*1000+a[1]*100+a[2]*10+a[3];
y=a[4]*1000+a[5]*100+a[6]*10+a[1];
z=a[4]*10000+a[5]*1000+a[2]*100+a[1]*10+a[7];
if(x+y==z)
printf("%d\n",y);
}while(next_permutation(a,a+10));
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: