排列2
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4174 Accepted Submission(s): 1609
链接 HDU 1716
现有四张卡片,用这四张卡片能排列出很多不同的4位数,要求按从小到大的顺序输出这些4位数。
每组输出数据间空一行,最后一组数据后面没有空行。
1 2 3 4 1 1 2 3 0 1 2 3 0 0 0 0
1234 1243 1324 1342 1423 1432 2134 2143 2314 2341 2413 2431 3124 3142 3214 3241 3412 3421 4123 4132 4213 4231 4312 4321 1123 1132 1213 1231 1312 1321 2113 2131 2311 3112 3121 3211 1023 1032 1203 1230 1302 1320 2013 2031 2103 2130 2301 2310 3012 3021 3102 3120 3201 3210
简单的排列问题,用到了STL库中的next_permutation(a.begin(),a.end())函数;
下面介绍一下此函数:
next_permutation函数是通过将数组a[](整型,char都可)的值改变,使得形成当前排列的下一个排列(还有prev_permutation()函数是求当前排列的上一个排列);
其返回值是bool型的。
#include <algorithm>
bool next_permutation( iterator start, iterator end );
The next_permutation() function attempts to transform the given range of elements [start,end) into the next lexicographically greater permutation of elements. If it succeeds, it returns true, otherwise, it returns false.
下面一个简单的整形数组的例子:#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int a[10],i,k;
for(i=0; i<4; i++)
{
a[i]=i+1;
}
k=1;
while(next_permutation(a,a+4))//a[0]到a[3]的排列;
{
cout<<"排列"<<k<<": ";
for(i=0; i<4; i++)
cout<<a[i]<<" ";
if(k%4==0)
cout<<endl;
k++;
}
return 0;
}
另外,函数也可对于char型的数组进行排列;
方法和字符数组类似;
本题对于输出格式限制较多,尾行无空行,每行尾部无空格,输出时要注意:
代码;
#include<iostream>
#include <stdlib.h>
#include<stdio.h>
#include<algorithm>
#include<memory.h>
using namespace std;
int cmp(const void *a,const void *b)
{
return *(int *)a-*(int *)b;
}
int a[5];
int main()
{
int i,j,b;
int k=0;
while(~scanf("%d%d%d%d",&a[0],&a[1],&a[2],&a[3])&&(a[0]||a[1]||a[2]||a[3]))
{
if(k!=0)
cout<<endl;
k++;
qsort(a,4,sizeof(int),cmp);//排序题目要求从小到大输出
b=0;
for(j=0; j<4; j++)
{
if((j!=0&&a[0]==b)||a[0]==0)
{
//cout<<b<<endl;
int temp;
temp=a[j+1];
a[j+1]=a[0];
a[0]=temp;
continue;
}
/* for(i=0; i<4; i++)
{
printf("%d",a[i]);
}
printf(" ");*/
while(1)
{
for(i=0; i<4; i++)
{
printf("%d",a[i]);
}
if(next_permutation(a+1,a+4))
{printf(" ");}
else
break;
}
b=a[0];
if(a[j+1]!=a[j])
{
int temp;
temp=a[j+1];
a[j+1]=a[0];
a[0]=temp;
}
sort(a+1,a+4);//再次排序,保证从小到大的顺序
cout<<endl;
}
memset(a,0,sizeof(a));
}
return 0;
}