排列2
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Problem Description
Ray又对数字的列产生了兴趣:
现有四张卡片,用这四张卡片能排列出很多不同的4位数,要求按从小到大的顺序输出这些4位数。
现有四张卡片,用这四张卡片能排列出很多不同的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
#include <cstdio>
#include <cstring>
#include <utility>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<int,char>pic;
pic ans[25];
char in[10];
int cnt;
void Swap(int a,int b){
char temp;
temp=in[a];
in[a]=in[b];
in[b]=temp;
}
void Perm(int beg,int end){
int i,j,temp;
bool flag;
if(beg==end){
temp=(((in[0]-48)*10+(in[1]-48))*10+(in[2]-48))*10+(in[3]-48);
ans[cnt++]=make_pair(temp,in[0]);
}else{
vector<char> vis;
for(i=beg;i<=end;i++){
flag=0;
for(j=0;j<vis.size();j++){
if(vis[j]==in[i]){
flag=1;
break;
}
}
if(flag)
continue;
vis.push_back(in[i]);
Swap(beg,i);
Perm(beg+1,end);
Swap(beg,i);
}
}
}
int main(){
int a,b,c,d,cas=1,i;
char index;
bool flag;
while(scanf("%d%d%d%d",&a,&b,&c,&d),a||b||c||d){
if(cas!=1)
puts("");
in[0]=a+48,in[1]=b+48,in[2]=c+48,in[3]=d+48,in[4]='\0';
cnt=0;
Perm(0,3);
sort(ans,ans+cnt);
for(i=0;i<cnt&&ans[i].second=='0';i++);
index='0';
flag=0;
for(;i<cnt;i++){
if(ans[i].second!=index){
if(flag)
puts("");
index=ans[i].second;
printf("%d",ans[i].first);
}else
printf(" %d",ans[i].first);
flag=1;
}
puts("");
cas++;
}
return 0;
}
本文介绍了一个具体的编程问题:使用四张数字卡片排列出所有可能的四位数,并按升序输出。涉及递归算法和排序技巧,展示了完整的C++实现代码。
3918

被折叠的 条评论
为什么被折叠?



