Problem Description
Ray又对数字的列产生了兴趣:
现有四张卡片,用这四张卡片能排列出很多不同的4位数,要求按从小到大的顺序输出这些4位数。 |
Input
每组数据占一行,代表四张卡片上的数字(0<=数字<=9),如果四张卡片都是0,则输入结束。
|
Output
对每组卡片按从小到大的顺序输出所有能由这四张卡片组成的4位数,千位数字相同的在同一行,同一行中每个四位数间用空格分隔。
每组输出数据间空一行,最后一组数据后面没有空行。 |
Sample Input
1 2 3 4 1 1 2 3 0 1 2 3 0 0 0 0 |
Sample Output
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 |
Source
2007省赛集训队练习赛(2)
|
Recommend
lcy
|
给出你四个数,要求按要求输出四位数,千位数相同的位于一排
解题思路
接收四个数,然后通过全排列生成算法(next_permutation)后面会有介绍,轻易的求出解,再需要注意的就是输出格式问题qaq
源代码
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <vector>
using namespace std;
int main()
{
bool flag=0;
int a[4];
while(cin >> a[0] >> a[1] >> a[2] >> a[3] && (a[1] + a[2] + a[3] + a[0]) != 0)
{
vector<int>v;
if(flag == 1)
printf("\n");
if(flag == 0)
flag = 1;
sort(a,a + 4);
do
{
if(a[0] == 0)
continue;
v.push_back(a[0] * 1000 + a[1] * 100 + a[2] * 10 + a[3]);
}
while(next_permutation(a,a + 4));
cout << v[0];
int k = v[0] / 1000;
for(int i = 1;i < v.size();i ++)
{
if(v[i] / 1000 == k)
{
printf(" %d",v[i]);
}
else
{
printf("\n");
printf("%d",v[i]);
k = v[i] / 1000;
}
}
printf("\n");
}
}
next_permutation
C++/STL实现
01#include <algorithm>
02#include <iostream>
03#include <string>
04using namespace std;
05//主函数,算法详见相关说明
06int main(void) {
07 //循环处理输入的每一个字符串
08 for (string str; cin >> str;) {
09 if (str.empty()) {
10 continue;
11 }
12 //如果字符串只有1个字符,则直接输出结束
13 if (str.length() <= 1) {
14 cout << "No more Permutation" << endl;
15 }
16 //iPivot为右边最大减序子集左边相邻的一个元素
17 string::iterator iPivot = str.end(), iNewHead;
18 //查找右边最大的减序子集
19 for (--iPivot; iPivot != str.begin(); --iPivot) {
20 if (*(iPivot - 1) < *iPivot ) {
21 break;
22 }
23 }
24 //如果整个序列都为减序,则重排结束。
25 if (iPivot == str.begin()) {
26 cout << "No more Permutation" << endl;
27 }
28 //iPivot指向子集左边相邻的一个元素
29 iPivot--;
30 //iNewHead为仅比iPivot大的元素,在右侧减序子集中寻找
31 for (iNewHead = iPivot + 1; iNewHead != str.end(); ++iNewHead) {
32 if (*iNewHead < *iPivot) {
33 break;
34 }
35 }
36 //交换iPivot和iNewHead的值,但不改变它们的指向
37 iter_swap(iPivot, --iNewHead);
38 //反转右侧减序子集,使之成为最小的增序子集
39 reverse(iPivot + 1, str.end());
40 //本轮重排完成,输出结果
41 cout << str << endl;
42 }
43 return 0;
44}
在STL中,除了next_permutation外,还有一个函数prev_permutation,两者都是用来计算排列组合的函数。前者是求出下一个排列组合,而后者是求出上一个排列组合。所谓“下一个”和“上一个”,书中举了一个简单的例子:对序列 {a, b, c},每一个元素都比后面的小,按照字典序列,固定a之后,a比bc都小,c比b大,它的下一个序列即为{a, c, b},而{a, c, b}的上一个序列即为{a, b, c},同理可以推出所有的六个序列为:{a, b, c}、{a, c, b}、{b, a, c}、{b, c, a}、{c, a, b}、{c, b, a},其中{a, b, c}没有上一个元素,{c, b, a}没有下一个元素。