hdu 1716(dfs)

时间:2023-03-08 17:56:52

题目链接 : http://acm.hdu.edu.cn/showproblem.php?pid=1716

排列2

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
一道全排列的搜索题,思路是先把四个数字从小到大排列,然后把所有可能的四位数全找出来,最后输出的时候把不符合题意的舍去就ok了。
 #include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std; int a[],vis[],s[];
int t,c; void dfs(int num)
{
if (num == )
{
if (c>=)
s[t++] = c;
return ;
}
for (int i=; i<; i++)
{
if (!vis[i]) //标记访问
{
vis[i] = ;
c = c * + a[i];
dfs(num + );
vis[i] = ;
c = (c - a[i]) / ;
}
}
} int main ()
{
int flag = ;
while (scanf ("%d%d%d%d",&a[],&a[],&a[],&a[]))
{
sort(a, a+);
if (a[] == )
break;
if (flag)
{
printf ("\n");
}
flag = ;
memset(vis, , sizeof(vis));
t = c = ;
dfs();
sort(s, s+t);
int temp;
printf ("%d",s[]);
temp = s[] / ; //记住千位数
for (int i=; i<t; i++)
{
if (s[i] == s[i-]) //因为排序过了,所以相同的四位数都在一起
continue ;
if (s[i] / != temp) //千位数不同,换行
{
printf ("\n%d",s[i]);
temp = s[i] / ; //同时记录新的千位数
}
else
{
printf (" %d",s[i]);
}
}
printf ("\n");
}
return ;
}

今天意外看到一位大神博客,用了一个next_permutation(a.begin(), a.end())函数,轻轻松松实现全排列。

附上大神博客链接和他的代码 : http://www.cnblogs.com/jackge/archive/2013/05/22/3093089.html

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm> using namespace std; int main(){ //freopen("input.txt","r",stdin); int a[],tag=;
while(scanf("%d%d%d%d",&a[],&a[],&a[],&a[])){
if(a[]== && a[]== && a[]== && a[]==)
break;
if(tag)
printf("\n");
tag=;
int flag=,tmp;
do{
if(a[]==)
continue;
if(flag){
printf("%d%d%d%d",a[],a[],a[],a[]);
flag=;
}else if(tmp==a[])
printf(" %d%d%d%d",a[],a[],a[],a[]);
else
printf("\n%d%d%d%d",a[],a[],a[],a[]);
tmp=a[];
}while(next_permutation(a,a+));
printf("\n");
}
return ;
}