字典序问题(自己的代码)

          本代码是算法设计与实验的题目的解答,描述如下:在字母表中,按升序排列如a,b,c。。。z这样子的1,2,3。。。。。26,然后ab(注意不能aa,严格意义上的升序)27.......具体网上可以搜得到,下面贴代码

        

# include <stdio.h>

# include <string.h>

 

void main()

{

         intf(int m,int n);

         intn,i,j,k,a,sum,c;

         charl[10];

 

 

         scanf("%d",&n);

 

         while(n--)

         {

                   memset(l,0,10);

                   sum=0;

                   a=0;

                   scanf("%s",l);

                   c=l[0]-'a'+1;

       k=strlen(l);

                  

                   for(n=1;n<k;n++)

                            for(i=1;i<=26;i++)

                            {

                                     sum+=f(i,n);//k位数之前有多少位数字,如abc也要等到yz完之后,也就是二位数全部完之后才能开始3位数

                            }

                            if(k>1)

                            {

                           

                        for(i='a'+strlen(l)-2;i<l[strlen(l)-2];i++)

                                                       sum+=26-(i-'a'+1);

 

                         sum+=l[strlen(l)-1]-l[strlen(l)-2];

 

                         printf("%d\n",sum);

                            }

                            else

                            {

                                     printf("%d",l[0]-'a'+1);

                            }

                  

                  

         }

}

 

int f(int m,int n)//以第i个字符打头的长度不超过K的升序字符串个数

{

         intj;

         intx;

        

         if(n==1)

                   return1;

         else

         {

                   x=0;

                   for(j=m+1;j<=26;j++)

                            x+=f(j,n-1);

                   returnx;

         }

}

展开阅读全文

没有更多推荐了,返回首页