全排列之字典序法

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
 
解决的方法,采用全排列字典序法,如1342下一个
(1)从最右端开始,找到第一个比它的右临位小的数字;3
(2)然后从该数字的右边找到比它大的最小的数字4,交换两数字1432
(3)最后将4位置右端的数字倒序排列1423
 
在知道算法的情况下写了两个小时,大体实现了,输出格式还不对,没有判断有0的情况
就先这样吧
对于冒泡排序  实在是太陌生了
代码如下
// 字典排序.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "stdio.h"
#include "string"
using namespace std;
void find_a(char*ptr,char*pa,int *indexa)
{

    for (int m=3;m>=0;m--)
    {
        if (ptr[m-1]<ptr[m])
        {
            *pa=ptr[m-1];
            *indexa=(m-1);

            break;
        }
    }
}

void find_b(char*ptr,char a,int indexa,char*pb,int*indexb)
{
    *pb='9';
    *indexb=3;
    for (int m=3;m>indexa;m--)
    {
        if (ptr[m]>a&&*pb>ptr[m])
        {
            *pb=ptr[m];
            *indexb=m;
        }
    }

}
void swap(char*a,char*b)
{
    int temp;
    temp=*a;
    *a=*b;
    *b=temp;
}
void paixu(char *p,int len)
{
    for (int m=len-1;m>0;m--)
    {
        char temp;
        for (int n=0;n<m;n++)
        {
            if (p[n]>p[n+1])
            {
                temp=p[n];
                p[n]=p[n+1];
                p[n+1]=temp;
            }
        }
    }
}

void paixu_down(char *p,int len)
{
    for (int m=len-1;m>0;m--)
    {
        char temp;
        for (int n=0;n<m;n++)
        {
            if (p[n]<p[n+1])
            {
                temp=p[n];
                p[n]=p[n+1];
                p[n+1]=temp;
            }
        }
    }
    

}

int _tmain(int argc, _TCHAR* argv[])
{
    FILE*fp;
    fp=fopen("A.txt","r");
    char temp[5]={0};
    char maxmun[5]={0};

    while(!feof(fp))
    {

    
    fscanf(fp,"%c %c %c %c\n",&temp[0],&temp[1],&temp[2],&temp[3]);
    for (int i=0;i<4;i++)
    {
        printf("%c",temp[i]);
        
    }
    printf(" ");

    strcpy(maxmun,temp);

    paixu_down(maxmun,4);

    while (strcmp(maxmun,temp)>0)
    {


        char a,b;
        int indexa,indexb;
        find_a(temp,&a,&indexa);
         if (indexa==0)
         {
             printf("\n");
         }
        find_b(temp,a,indexa,&b,&indexb);
        swap(&temp[indexa],&temp[indexb]);

        paixu(&temp[indexa]+1,3-indexa);
        for (int i=0;i<4;i++)
        {
            printf("%c",temp[i]);
        }
        printf(" ");

    }

    printf("\n\n");
    }

    fclose(fp);
    return 0;
}

 

 
 
 
posted @ 2013-05-09 11:52  songnb_7  阅读(347)  评论(0编辑  收藏  举报