HDU - 1716 排列2(暴力;next_permutation)

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
Sponsor
解题思路:
因为一共才4位数,可以直接暴力出所有可能,再进行排序。

当数位比较多的时候暴力就不行了,可以使用STL全排序函数,因为是从小到大所以使用next_permutation()函数
next_permutation()函数具体介绍见:next_permutation()函数

暴力代码

#include<bits/stdc++.h>
using namespace std;
int a[10],b[1010],c[1000];
int main()
{
    
    
	int i,j,k,m;
	int x=0;
    while(1)
    {
    
    
        scanf("%d %d %d %d",&a[0],&a[1],&a[2],&a[3]);
        if(a[0]+a[1]+a[2]+a[3]==0)
	 		break;
        if(x) 
			printf("\n");
        x=1;
		int t=1;
		//暴力循环
		for(i=0;i<4;i++)
		{
    
    
			if(a[i]!=0)//直接舍去0的情况
			for(j=0;j<4;j++)
			for(k=0;k<4;k++)
			for(m=0;m<4;m++)
			if(i!=j&&i!=k&&i!=m&&j!=k&&j!=m&&k!=m)
			{
    
    
				b[t++]=a[i]*1000+a[j]*100+a[k]*10+a[m];//存入数组b
			}
		}
		sort(b,b+t);//排序
		b[0]=0;j=1;
		for(i=1;i<t;i++)//去重
		{
    
    
			if(b[i]==b[i+1])
			continue;
			c[j++]=b[i];
		}
		c[j]=0;
		for(i=1;i<j;i++)
		{
    
    
			if(c[i]/1000==c[i+1]/1000)
			printf("%d ",c[i]);
			else
			printf("%d\n",c[i]);
		}
	}
 } 

next_permutation代码

#include<stdio.h>
#include<algorithm>
using namespace std;
int main()
{
    
    
    int a[5];
    int x=0;
    while(1)
    {
    
    
        scanf("%d %d %d %d",&a[0],&a[1],&a[2],&a[3]);
        if(a[0]+a[1]+a[2]+a[3]==0)
	 		break;
        if(x) 
			printf("\n");
        x=1;
        sort(a,a+4);
        int k=0,w=0;
	   do{
    
    
            if(a[0]==0)
				continue;
			if(k==0)
				k=1;
            else 
			if(w==a[0]) 
				printf(" ");
            else  
				printf("\n");
			printf("%d%d%d%d",a[0],a[1],a[2],a[3]);
            w=a[0];
        }while(next_permutation(a, a +4));
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_46703995/article/details/112999361
今日推荐